问:
how to show pdf file in ionic app with out download
Things i did :

used inappbrowser

used google doc

used webview

so i have tried all these methods to show the pdf file in android device using ionic. But no use, i can see the download button in all these methods. Can any one tell me how can i display pdf without download option for user.

my code :

```<code> <div  class="col col-50 clsGrid" ng-click="showFile('http://www.orimi.com/pdf-test.pdf')">
</div>
</code>```

my pdf file :

http://www.orimi.com/pdf-test.pdf

My JS :

```<code>$scope.showModal = function(templateUrl) {
        $ionicModal.fromTemplateUrl(templateUrl, {
            scope: $scope,
            animation: 'slide-in-up'
        }).then(function(modal) {
            $ionicLoading.show({
            duration: 1000
});
            $scope.modal = modal;
            $scope.modal.show();
        });
    }

    // Close the modal
    $scope.closeModal = function() {
        $scope.modal.hide();
        $scope.modal.remove()
    };

    $scope.showFile = function(FileUrl) {
        var file = FileUrl;
        console.log(file);
        //var openurl = cordova.InAppBrowser.open(file, '_blank');
      //  var openurl = cordova.InAppBrowser.open(file,'_blank', 'location=yes');

          // var openurl = cordova.InAppBrowser.open("https://docs.google.com/viewer?url=" + file, '_blank');

    // var openurl = cordova.InAppBrowser.open('https://docs.google.com/viewer?url=http://www.orimi.com/pdf-test.pdf&embedded=true', '_blank');

          //window.open("https://docs.google.com/viewer?url=http://www.orimi.com/pdf-test.pdf&embedded=true",'_blank');

    var openurl = cordova.InAppBrowser.open('https://docs.google.com/viewer?url=http://www.orimi.com/pdf-test.pdf&embedded=true&toolbar=0&navpanes=0&scrollbar=0', '_blank');

      }
</code>```

I tried all ways. But not able to find the solution.If any one know it will be usefull.If any expert in this, i can send my demo project for reference .
Thanks in advance !

答:
You will need to use ng-pdfviewer.

AngularJS PDF viewer directive using pdf.js.

```<code><button ng-click="prevPage()"><</button>
<button ng-click="nextPage()">></button>
<br>
<span>{{currentPage}}/{{totalPages}}</span>
<br>
<pdfviewer src="test.pdf" on-page-load='pageLoaded(page,total)' id="viewer"></pdfviewer>
</code>```

and in your AngularJS code:

```<code>var app = angular.module('testApp', [ 'ngPDFViewer' ]);

app.controller('TestCtrl', [ '$scope', 'PDFViewerService', function($scope, pdf) {
    $scope.viewer = pdf.Instance("viewer");

    $scope.nextPage = function() {
        $scope.viewer.nextPage();
    };

    $scope.prevPage = function() {
        $scope.viewer.prevPage();
    };

    $scope.pageLoaded = function(curPage, totalPages) {
        $scope.currentPage = curPage;
        $scope.totalPages = totalPages;
    };
}]);
</code>```

Body:
Things i did :

used inappbrowser

used google doc

used webview

so i have tried all these methods to show the pdf file in android device using ionic. But no use, i can see the download button in all these methods. Can any one tell me how can i display pdf without download option for user.

my code :

my pdf file :

http://www.orimi.com/pdf-test.pdf

My JS :

$scope.showModal = function(templateUrl) {
        $ionicModal.fromTemplateUrl(templateUrl, {
            scope: $scope,
            animation: 'slide-in-up'
        }).then(function(modal) {
            $ionicLoading.show({
            duration: 1000
});
            $scope.modal = modal;
            $scope.modal.show();
        });
    }

    // Close the modal
    $scope.closeModal = function() {
        $scope.modal.hide();
        $scope.modal.remove()
    };

    $scope.showFile = function(FileUrl) {
        var file = FileUrl;
        console.log(file);
        //var openurl = cordova.InAppBrowser.open(file, '_blank');
      //  var openurl = cordova.InAppBrowser.open(file,'_blank', 'location=yes');

          // var openurl = cordova.InAppBrowser.open("https://docs.google.com/viewer?url=" + file, '_blank');

    // var openurl = cordova.InAppBrowser.open('https://docs.google.com/viewer?url=http://www.orimi.com/pdf-test.pdf&embedded=true', '_blank');

          //window.open("https://docs.google.com/viewer?url=http://www.orimi.com/pdf-test.pdf&embedded=true",'_blank');

    var openurl = cordova.InAppBrowser.open('https://docs.google.com/viewer?url=http://www.orimi.com/pdf-test.pdf&embedded=true&toolbar=0&navpanes=0&scrollbar=0', '_blank');

      }

I tried all ways. But not able to find the solution.If any one know it will be usefull.If any expert in this, i can send my demo project for reference .
Thanks in advance !

Body:
You will need to use ng-pdfviewer.

AngularJS PDF viewer directive using pdf.js.

<button ng-click="prevPage()">&lt;</button>
<button ng-click="nextPage()">&gt;</button>
<br>
<span>{{currentPage}}/{{totalPages}}</span>
<br>
<pdfviewer src="test.pdf" on-page-load='pageLoaded(page,total)' id="viewer"></pdfviewer>

and in your AngularJS code:

var app = angular.module('testApp', [ 'ngPDFViewer' ]);

app.controller('TestCtrl', [ '$scope', 'PDFViewerService', function($scope, pdf) {
    $scope.viewer = pdf.Instance("viewer");

    $scope.nextPage = function() {
        $scope.viewer.nextPage();
    };

    $scope.prevPage = function() {
        $scope.viewer.prevPage();
    };

    $scope.pageLoaded = function(curPage, totalPages) {
        $scope.currentPage = curPage;
        $scope.totalPages = totalPages;
    };
}]);


来源: stackexchange

问:
Change submit button value on Drupal 8 search form block
I would like to show a FontAwesome Icon inside a submit button in Drupal 8.

For this i want to change the value for the search form to use the Unicode representation of the icon ().

I found infos on how to do this in D7 (https://www.drupal.org/node/154137, https://www.drupal.org/node/45295), but how is it best done it D8? But how would one best do this in Drupal 8?

答:
After much more reading i finally found the answer here: https://drupal.stackexchange.com/questions/197439/how-to-replace-the-search-submit-button-with-a-font-awesome-character/212185#212185

With hook_form_search_block_form_alter one can access the search block form directly:

```<code>function ThemeName_form_search_block_form_alter(&$form, &$form_state) {
  $form['actions']['submit']['#value'] = html_entity_decode('');
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
After much more reading i finally found the answer here: https://drupal.stackexchange.com/questions/197439/how-to-replace-the-search-submit-button-with-a-font-awesome-character/212185#212185

With hook_form_search_block_form_alter one can access the search block form directly:

function ThemeName_form_search_block_form_alter(&$form, &$form_state) {
  $form['actions']['submit']['#value'] = html_entity_decode('&#xf002;');
}


问:
Text and image height do not match
Text and image height do not match, after refresh - all is well.
Thank you for your help!

CodePen

$(document).ready(function() {
  $(window).resize(function() {
    processPost();
  });

  function processPost() {
    $('.post').each(function(i, e) {
      $image = $(e).children('.post-image'),
        $data = $(e).children('.post-data');
      $image.css({
        'background-image': isExist($image.attr('image-url')),
        'height': $data.height(),
      });
    });
  }
  processPost();

  function isExist(data) {
    return `url(${ (data !== undefined && data !== '') ? data : '/data/no-photo.jpg' })`;
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.post {
  display: table;
  margin: 4% 2%;
  padding: .6em 1em;
  background-color: #fefefe;
  border-radius: 2px;
}
.post-cell, .post-image, .post-data {
  display: inline-table;
}
.post-cell {
  width: 100%;
}
.post-cell h4, .post-cell p {
  margin: 0;
  padding: .2em 0;
}
.post-cell h4 {
  font-size: 1.5em;
}
.post-cell p {
  color: #d7d7d7;
}
.post-image {
  float: left;
  width: 39%;
  background-size: cover;
  background-position: center;
  border-radius: 2px;
  min-height: 100px;
  max-height: 300px;
}
.post-data {
  padding-left: 2%;
  width: 59%;
}
.post-data p {
  margin: 0;
}
.text-right {
  text-align: right !important;
}</code>```

Heading

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
      in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

meta, tag, metatag, meta-tag

```

Screenshot:
[Image Height: 175px, Post Height: 200px]

答:
Depending on what additional CSS you have, there may be more work than this, but there are a couple other things that can be addressed first:

jQuery's $(element).height() method returns a number. To this, you need to append the string px, so the value being assigned to the image's height is then a valid CSS length unit.

You probably want to wait until the DOMContentLoaded or similar event, which can also be accessed through jQuery's $(window).ready(callback) function. This will ensure that the text in the DOM is rendered before measuring its height (though this might also change later if you're using external webfonts that take longer to load).

$(window).ready(processPost); // NOTE

function processPost() {
  $('.post').each(function(i, e) {
    $image = $(e).children('.post-image'),
      $data = $(e).children('.post-data');
    $image.css({
      'background-image': isExist($image.attr('image-url')),
      'height': $data.height() + 'px', // NOTE
    });
  });
}

function isExist(data) {
  return `url(${ (data !== undefined && data !== '') ? data : '/data/no-photo.jpg' })`;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>

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

<body>
  <div class="post">
    <div class="post-cell">
      <h4>Heading</h4>
    </div>
    <div class="post-image" image-url="http://www.openarium.ru/фото/грузия/тбилиси/дикие-горы-тушети.jpg">
    </div>
    <div class="post-data">
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
        in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
      </p>
    </div>
    <div class="post-cell text-right">
      <p>meta, tag, metatag, meta-tag</p>
    </div>
  </div>
</body>

</html></code>```

Title: Text and image height do not match

Body:
Text and image height do not match, after refresh - all is well.
Thank you for your help!

CodePen

$(document).ready(function() {
  $(window).resize(function() {
    processPost();
  });

  function processPost() {
    $('.post').each(function(i, e) {
      $image = $(e).children('.post-image'),
        $data = $(e).children('.post-data');
      $image.css({
        'background-image': isExist($image.attr('image-url')),
        'height': $data.height(),
      });
    });
  }
  processPost();

  function isExist(data) {
    return `url(${ (data !== undefined && data !== '') ? data : '/data/no-photo.jpg' })`;
  }
});

.post {
  display: table;
  margin: 4% 2%;
  padding: .6em 1em;
  background-color: #fefefe;
  border-radius: 2px;
}
.post-cell, .post-image, .post-data {
  display: inline-table;
}
.post-cell {
  width: 100%;
}
.post-cell h4, .post-cell p {
  margin: 0;
  padding: .2em 0;
}
.post-cell h4 {
  font-size: 1.5em;
}
.post-cell p {
  color: #d7d7d7;
}
.post-image {
  float: left;
  width: 39%;
  background-size: cover;
  background-position: center;
  border-radius: 2px;
  min-height: 100px;
  max-height: 300px;
}
.post-data {
  padding-left: 2%;
  width: 59%;
}
.post-data p {
  margin: 0;
}
.text-right {
  text-align: right !important;
}

Heading

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
      in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

meta, tag, metatag, meta-tag

Screenshot:
[Image Height: 175px, Post Height: 200px]

Body:
Depending on what additional CSS you have, there may be more work than this, but there are a couple other things that can be addressed first:

jQuery's $(element).height() method returns a number. To this, you need to append the string px, so the value being assigned to the image's height is then a valid CSS length unit.

You probably want to wait until the DOMContentLoaded or similar event, which can also be accessed through jQuery's $(window).ready(callback) function. This will ensure that the text in the DOM is rendered before measuring its height (though this might also change later if you're using external webfonts that take longer to load).

$(window).ready(processPost); // NOTE

function processPost() {
  $('.post').each(function(i, e) {
    $image = $(e).children('.post-image'),
      $data = $(e).children('.post-data');
    $image.css({
      'background-image': isExist($image.attr('image-url')),
      'height': $data.height() + 'px', // NOTE
    });
  });
}

function isExist(data) {
  return `url(${ (data !== undefined && data !== '') ? data : '/data/no-photo.jpg' })`;
}

<!doctype html>
<html>

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

<body>
  <div class="post">
    <div class="post-cell">
      <h4>Heading</h4>
    </div>
    <div class="post-image" image-url="http://www.openarium.ru/фото/грузия/тбилиси/дикие-горы-тушети.jpg">
    </div>
    <div class="post-data">
      <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
        in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
      </p>
    </div>
    <div class="post-cell text-right">
      <p>meta, tag, metatag, meta-tag</p>
    </div>
  </div>
</body>

</html>


问:
Excel formula to find the value where a row stays zero and return column header
I'm trying to create a formula that would be able to find the last zero value in a row by searching a row from right to left. In other words the value where a cell in a row is zero and then all the cells after that are also zero. I've been experimenting with offset, index and lookup but nothing seems to work.

For example, in the data below I would want the formula to come up with the answer "18-Nov-17".

Any suggestions would be greatly appreciated!

here is a sample excel sheet

答:
Try this. When it finds the first occurrence of 3 consecutive zeros, it returns the value in the cell above the first zero of the three.  </p>

<p>EDIT: I just realized that you weren't looking for a macro solution, but this could return what you're looking for just the same I suppose.  </p>

```<code>Sub findthedate()
Dim i As Long

For i = 1 To 20
    If Cells("4", i) = "0" Then
        If Cells("4", i + 1) = "0" Then
            If Cells("4", i + 2) = "0" Then
                MsgBox Cells("3", i)
                Exit For
            End If
        End If
    End If
Next i
End Sub
</code>```

Body:
Try this. When it finds the first occurrence of 3 consecutive zeros, it returns the value in the cell above the first zero of the three.

EDIT: I just realized that you weren't looking for a macro solution, but this could return what you're looking for just the same I suppose.

Sub findthedate()
Dim i As Long

For i = 1 To 20
    If Cells("4", i) = "0" Then
        If Cells("4", i + 1) = "0" Then
            If Cells("4", i + 2) = "0" Then
                MsgBox Cells("3", i)
                Exit For
            End If
        End If
    End If
Next i
End Sub


问:
How do I specify URL resolution in python's requests library in a similar fashion to curl's --resolve flag?
I am writing some python client code and, due to some environmental constraints, I want to specify a URL and also control how it is resolved. I can accomplish this with curl by using the --resolve flag. Is there a way to do something similar with Python's requests library?

Ideally this would work in Python 2.7 but I can make a 3.x solution work as well.

答:
After doing a bit of digging, I (unsurprisingly) found that Requests resolves hostnames by asking Python to do it (which is asking your operating system to do it). First I found some sample code to hijack DNS resolution (Tell urllib2 to use custom DNS) and then I figured out a few more details about how Python resolves hostnames in the socket documentation. Then it was just a matter of wiring everything together:

```<code>import socket
import requests

def is_ipv4(s):
    # Feel free to improve this: https://stackoverflow.com/questions/11827961/checking-for-ip-addresses
    return ':' not in s

dns_cache = {}

def add_custom_dns(domain, port, ip):
    key = (domain, port)
    # Strange parameters explained at:
    # https://docs.python.org/2/library/socket.html#socket.getaddrinfo
    # Values were taken from the output of `socket.getaddrinfo(...)`
    if is_ipv4(ip):
        value = (socket.AddressFamily.AF_INET, 0, 0, '', (ip, port))
    else: # ipv6
        value = (socket.AddressFamily.AF_INET6, 0, 0, '', (ip, port, 0, 0))
    dns_cache[key] = [value]

# Inspired by: https://stackoverflow.com/a/15065711/868533
prv_getaddrinfo = socket.getaddrinfo
def new_getaddrinfo(*args):
    # Uncomment to see what calls to `getaddrinfo` look like.
    # print(args)
    try:
        return dns_cache[args[:2]] # hostname and port
    except KeyError:
        return prv_getaddrinfo(*args)

socket.getaddrinfo = new_getaddrinfo

# Redirect example.com to the IP of test.domain.com (completely unrelated).
add_custom_dns('example.com', 80, '66.96.162.92')
res = requests.get('http://example.com')
print(res.text) # Prints out the HTML of test.domain.com.
</code>```

Some caveats I ran into while writing this:

This works poorly for https. The code works fine (just use https:// and 443 instead of http:// and 80). However, SSL certificates are tied to domain names and Requests is going to try validating the name on the certificate to the original domain you tried connecting to.

getaddrinfo returns slightly different info for IPv4 and IPv6 addresses. My implementation for is_ipv4 feels hacky to me and I strongly recommend a better version if you're using this in a real application.

The code has been tested on Python 3 but I see no reason why it wouldn't work as-is on Python 2.

Body:
After doing a bit of digging, I (unsurprisingly) found that Requests resolves hostnames by asking Python to do it (which is asking your operating system to do it). First I found some sample code to hijack DNS resolution (Tell urllib2 to use custom DNS) and then I figured out a few more details about how Python resolves hostnames in the socket documentation. Then it was just a matter of wiring everything together:

import socket
import requests

def is_ipv4(s):
    # Feel free to improve this: https://stackoverflow.com/questions/11827961/checking-for-ip-addresses
    return ':' not in s

dns_cache = {}

def add_custom_dns(domain, port, ip):
    key = (domain, port)
    # Strange parameters explained at:
    # https://docs.python.org/2/library/socket.html#socket.getaddrinfo
    # Values were taken from the output of `socket.getaddrinfo(...)`
    if is_ipv4(ip):
        value = (socket.AddressFamily.AF_INET, 0, 0, '', (ip, port))
    else: # ipv6
        value = (socket.AddressFamily.AF_INET6, 0, 0, '', (ip, port, 0, 0))
    dns_cache[key] = [value]

# Inspired by: https://stackoverflow.com/a/15065711/868533
prv_getaddrinfo = socket.getaddrinfo
def new_getaddrinfo(*args):
    # Uncomment to see what calls to `getaddrinfo` look like.
    # print(args)
    try:
        return dns_cache[args[:2]] # hostname and port
    except KeyError:
        return prv_getaddrinfo(*args)

socket.getaddrinfo = new_getaddrinfo

# Redirect example.com to the IP of test.domain.com (completely unrelated).
add_custom_dns('example.com', 80, '66.96.162.92')
res = requests.get('http://example.com')
print(res.text) # Prints out the HTML of test.domain.com.

Some caveats I ran into while writing this:

This works poorly for https. The code works fine (just use https:// and 443 instead of http:// and 80). However, SSL certificates are tied to domain names and Requests is going to try validating the name on the certificate to the original domain you tried connecting to.

getaddrinfo returns slightly different info for IPv4 and IPv6 addresses. My implementation for is_ipv4 feels hacky to me and I strongly recommend a better version if you're using this in a real application.

The code has been tested on Python 3 but I see no reason why it wouldn't work as-is on Python 2.


问:
How to ease nested looping?
I find myself looping over vectors of vectors a lot:

```<code>std::vector<std::vector<int> > foo;

for(unsigned int i=0; i != foo.size(); ++i) {
 for(unsigned int j=0; j != foo[i].size(); ++j) {
  // use foo[i][j]
 }
}
</code>```

I don't have a good minimal example why the "data" is represented best by a vector of vectors of int but let's don't doubt it here.

What do you suggest to simplify the looping? I could think of a function that implements the explicit looping and takes a pointer to a function for the body.

How to "generate" nested for-loops in case of more levels?

Are there languages that have "built-in" support for "nested looping"?

Thanks in advance,

Somebody

答:
I think nested loops as the one you showed us aren't that bad.
I would recommend to choose better names for the control variables. If there aren't better names maybe outerIndex and innerIndex can be used?!
Also, sometimes moving the (complex) loop body into a function improves readability.

ContentLicense: CC BY-SA 2.5

Title: How to ease nested looping?

Body:
I find myself looping over vectors of vectors a lot:

std::vector<std::vector<int> > foo;

for(unsigned int i=0; i != foo.size(); ++i) {
 for(unsigned int j=0; j != foo[i].size(); ++j) {
  // use foo[i][j]
 }
}

I don't have a good minimal example why the "data" is represented best by a vector of vectors of int but let's don't doubt it here.

What do you suggest to simplify the looping? I could think of a function that implements the explicit looping and takes a pointer to a function for the body.

How to "generate" nested for-loops in case of more levels?

Are there languages that have "built-in" support for "nested looping"?

Thanks in advance,

Somebody


问:
Efficient way to read .yml file with different keys/filenodes
I have a yaml file with following format:

```<code>%YAML:1.0

data1: !!opencv-matrix
rows: 50
cols: 3
dt: d
data: [ 7.1709999084472656e+01, ...

data2: !!opencv-matrix
rows: 50
cols: 3
dt: d
data: [ 7.1709999084472656e+01, ...

dataN: ...
</code>```

I read the file content and save different data in different Mats:

```<code>QString nodeName[m_NameList.count()]= "data";
QString fullName[m_NameList.count()];
Mat inMat[m_NameList.count()];

for(int i= 0; i< m_NameList.count(); ++i)
{
    fullName[i]= nodeName[i].append(QString::number(i+1));

    FileStorage fsIn("file.yml", CV_STORAGE_READ);
    fsIn[fullName[i].toStdString()] >> inMat[i];
}
</code>```

My problem is defining the node name = "data"; if I want to give it to the FileStorage. Is there any other way that the FileStorage recognize the file-nodes automatically?

答:
Ok, I have found the solution myself, to read my node names from yaml file automatically, if another persons are interested. Basically I iterate the node names over QStringList::iterator and write them in FileNode and get them with fileNode.name() function.

```<code>int idx= 0;
FileStorage fs("file.yml", CV_STORAGE_READ);
FileNode fileNode;
Mat inMat[m_NameList.count()];

for(QStringList::iterator it= m_NameList.begin(); it!= m_NameList.end(); ++it)
{
  fileNode= fs[(*it).toStdString()];

  string key= fileNode.name();
  fs[key] >> inMat[idx];
  cout<<"Key Name: " << key << " Mat: " << inMat[idx]<<endl;
}
</code>```

Body:
I have a yaml file with following format:

%YAML:1.0

data1: !!opencv-matrix
rows: 50
cols: 3
dt: d
data: [ 7.1709999084472656e+01, ...

data2: !!opencv-matrix
rows: 50
cols: 3
dt: d
data: [ 7.1709999084472656e+01, ...

dataN: ...

I read the file content and save different data in different Mats:

QString nodeName[m_NameList.count()]= "data";
QString fullName[m_NameList.count()];
Mat inMat[m_NameList.count()];

for(int i= 0; i< m_NameList.count(); ++i)
{
    fullName[i]= nodeName[i].append(QString::number(i+1));

    FileStorage fsIn("file.yml", CV_STORAGE_READ);
    fsIn[fullName[i].toStdString()] >> inMat[i];
}

My problem is defining the node name = "data"; if I want to give it to the FileStorage. Is there any other way that the FileStorage recognize the file-nodes automatically?

Body:
Ok, I have found the solution myself, to read my node names from yaml file automatically, if another persons are interested. Basically I iterate the node names over QStringList::iterator and write them in FileNode and get them with fileNode.name() function.

int idx= 0;
FileStorage fs("file.yml", CV_STORAGE_READ);
FileNode fileNode;
Mat inMat[m_NameList.count()];

for(QStringList::iterator it= m_NameList.begin(); it!= m_NameList.end(); ++it)
{
  fileNode= fs[(*it).toStdString()];

  string key= fileNode.name();
  fs[key] >> inMat[idx];
  cout<<"Key Name: " << key << " Mat: " << inMat[idx]<<endl;
}


问:
I'm trying to upload a varchar image from my mysql database and it's not working. Any suggestions?
I'm using 000webhost for my php server and phpmyadmin for my database. My image row looks like

```<code>image   varchar(100)    utf8_unicode_ci
</code>```

What i'm trying to do is someone inputs a username and it outputs the image associated with that username. Here's my html:

```<code><!DOCTYPE html>
<html>

<body>

<form action="showimage.php" method="GET">
<h2>Show Image</h2>
        Username: <input type="text" name="username" /><br>

        <input type="submit" value="Show Image" />
    </form>

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

and my php:

```<code><!DOCTYPE html>
<html>
<body>

<?php

$host='localhost';
$user='id1783920_123456';
$pass='';
$db='id1783920_mydb';

$con=mysqli_connect($host,$user,$pass,$db);
if($con) {
//echo 'connected successfully to id1783920_mydb database<br><br>';
}

$id = mysqli_real_escape_string($_GET['id']);
$query = mysqli_query("SELECT * FROM 'blob' WHERE 'id'='$id'");
while($row = mysqli_fetch_assoc($query) {

$imagedata = $row[`image`];

}

echo"$imagedata";
mysqli_close($con);

?>

<img src="showimage.php?username=$_GET['username']">

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

Can someone please give me some suggestions? Thanks so much!
I also keep getting this error

Parse error: syntax error, unexpected ';' in /storage/h11/920/1783920/public_html/Complete/showimage.php on line 23

答:
The error:

Parse error: syntax error, unexpected ';' in /storage/h11/920/1783920/public_html/Complete/showimage.php on line 23

is because:

```<code>$imagedata = $row[`image`];
</code>```

should be:

```<code>$imagedata = $row['image'];
</code>```

Backticks are very useful in MySQL queries. But in the PHP code it is normally either single or double-quotes. For a constant text value it makes no real difference, but if you want to have variables inside the string (e.g., $row["image{$counter}"]) then you need to use double-quotes.

Body:
I'm using 000webhost for my php server and phpmyadmin for my database. My image row looks like

image   varchar(100)    utf8_unicode_ci

What i'm trying to do is someone inputs a username and it outputs the image associated with that username. Here's my html:

<!DOCTYPE html>

<form action="showimage.php" method="GET">

Show Image

        Username: <input type="text" name="username" />

        <input type="submit" value="Show Image" />
    </form>

and my php:

<!DOCTYPE html>

<?php

$host='localhost';
$user='id1783920_123456';
$pass='';
$db='id1783920_mydb';

$con=mysqli_connect($host,$user,$pass,$db);
if($con) {
//echo 'connected successfully to id1783920_mydb database

';
}

$id = mysqli_real_escape_string($_GET['id']);
$query = mysqli_query("SELECT * FROM 'blob' WHERE 'id'='$id'");
while($row = mysqli_fetch_assoc($query) {

$imagedata = $row[`image`];

}

echo"$imagedata";
mysqli_close($con);

?>

Can someone please give me some suggestions? Thanks so much!
I also keep getting this error

Parse error: syntax error, unexpected ';' in /storage/h11/920/1783920/public_html/Complete/showimage.php on line 23

Body:
The error:

Parse error: syntax error, unexpected ';' in /storage/h11/920/1783920/public_html/Complete/showimage.php on line 23

is because:

$imagedata = $row[`image`];

should be:

$imagedata = $row['image'];

Backticks are very useful in MySQL queries. But in the PHP code it is normally either single or double-quotes. For a constant text value it makes no real difference, but if you want to have variables inside the string (e.g., $row["image{$counter}"]) then you need to use double-quotes.


问:
Time difference between rows in R dplyr, different units
Here is my example. I am reading the following file: sample_data

```<code>library(dplyr)

txt <- c('"",  "MDN",                  "Cl_Date"',
          '"1",  "A",  "2017-04-15 15:10:42.510"',
          '"2",  "A",  "2017-04-01 14:47:23.210"',
          '"3",  "A",  "2017-04-01 14:49:54.063"',
          '"4",  "B",  "2017-04-30 13:25:00.000"',
          '"5",  "B",  "2017-04-03 17:53:13.217"',
          '"6",  "B",  "2017-04-15 15:17:43.780"')

ts <- read.csv(text = txt, as.is = TRUE)
ts$Cl_Date <- as.POSIXct(ts$Cl_Date)
ts <- ts %>% group_by(MDN) %>% arrange(Cl_Date) %>%
  mutate(time_diff = c(0,diff(Cl_Date)))
ts <-ts[order(ts$MDN, ts$Cl_Date),]
</code>```

As a result I have

```<code>MDN Cl_Date         time_diff
A   4/1/2017 14:47  0
A   4/1/2017 14:49  2.514216665
A   4/15/2017 15:10 20180.80745
B   4/3/2017 17:53  0
B   4/15/2017 15:17 11.89202041
B   4/30/2017 13:25 14.92171551
</code>```

So I group by MDN column and compute difference between Cl_Date column. As you can see sometime different in minutes (group A) and sometime difference in days (group B).

Why is time difference in different units and how to correct it?

P.S. I could not reproduce the same example with manual data.frame creation, so I had to read from file.

UPDATE 1
diff(ts$Cl_Date) seems to be consistent, everything is in minutes. Does something break within dplyr?

UPDATE 2

```<code>ts <- ts %>% group_by(MDN) %>% arrange(Cl_Date) %>%
  mutate(time_diff_2 = Cl_Date-lag(Cl_Date))
</code>```

produces the same result.

答:
```<code>ts <- ts %>% group_by(MDN) %>% arrange(Cl_Date) %>%
  mutate(time_diff_2 = as.numeric(Cl_Date-lag(Cl_Date), units = 'mins'))
</code>```

Convert the time difference to a numeric value. You can use units argument to make the return values consistent.

Body:
Here is my example. I am reading the following file: sample_data

library(dplyr)

txt <- c('"",  "MDN",                  "Cl_Date"',
          '"1",  "A",  "2017-04-15 15:10:42.510"',
          '"2",  "A",  "2017-04-01 14:47:23.210"',
          '"3",  "A",  "2017-04-01 14:49:54.063"',
          '"4",  "B",  "2017-04-30 13:25:00.000"',
          '"5",  "B",  "2017-04-03 17:53:13.217"',
          '"6",  "B",  "2017-04-15 15:17:43.780"')

ts <- read.csv(text = txt, as.is = TRUE)
ts$Cl_Date <- as.POSIXct(ts$Cl_Date)
ts <- ts %>% group_by(MDN) %>% arrange(Cl_Date) %>%
  mutate(time_diff = c(0,diff(Cl_Date)))
ts <-ts[order(ts$MDN, ts$Cl_Date),]

As a result I have

MDN Cl_Date         time_diff
A   4/1/2017 14:47  0
A   4/1/2017 14:49  2.514216665
A   4/15/2017 15:10 20180.80745
B   4/3/2017 17:53  0
B   4/15/2017 15:17 11.89202041
B   4/30/2017 13:25 14.92171551

So I group by MDN column and compute difference between Cl_Date column. As you can see sometime different in minutes (group A) and sometime difference in days (group B).

Why is time difference in different units and how to correct it?

P.S. I could not reproduce the same example with manual data.frame creation, so I had to read from file.

UPDATE 1
diff(ts$Cl_Date) seems to be consistent, everything is in minutes. Does something break within dplyr?

UPDATE 2

ts <- ts %>% group_by(MDN) %>% arrange(Cl_Date) %>%
  mutate(time_diff_2 = Cl_Date-lag(Cl_Date))

produces the same result.

Body:
ts <- ts %>% group_by(MDN) %>% arrange(Cl_Date) %>%
  mutate(time_diff_2 = as.numeric(Cl_Date-lag(Cl_Date), units = 'mins'))

Convert the time difference to a numeric value. You can use units argument to make the return values consistent.


问:
Alternative to QImage when using QT-=gui
QImage has a lot of nice functionality for image file I/O

However, if you need to compile a command-line application to run on a linux server (specifically without X), you need to compile with QT-=gui, which means no QImage, (also no QVector3d, and no QMatrix4x4 among others, which I really don't understand why these basic data types have a GUI dependency). Do I really have to use a separate library for image file handling in GUI and non-GUI apps, or is there something I'm missing?

This is with Qt 5.4.2. The executable fails to start with:

QXcbConnection: Could not connect to display

答:
I came across a solution here:

Qt 5.1 QApplication Without Display - QXcbConnection: Could not connect to display

TL;DR, you CAN run Qt-applications on headless instances (without running X) as long as you add -platform offscreen to the program arguments at run-time

This works even if you link to QtGUI and QtOpenGL for basic datatypes


问:
Referencing images in Ruby on Rails
I have a script in a page (below) that calls a jQuery plugin and passes in the path to a number of images. The images are stored in app/assets/img/bg as opposed to app/assets/images.

```<code><script>
    $(".forms-wrapper").backstretch([
        "assets/img/bg/6.jpg",
        "assets/img/bg/5.jpg",
        "assets/img/bg/7.jpg",
        ], {
            fade: 1000,
            duration: 7000
        });
</script>
</code>```

The JavaScript function is in a file located in app/assets/plugins/backstretch.

I can get the functionality working by changing the path to the images and moving the images:-

```<code><script>
    $(".forms-wrapper").backstretch([
        "../assets/7.jpg",
        "../assets/16.jpg",
        "../assets/19.jpg",
        ], {
            fade: 1000,
            duration: 7000
        });
</script>
</code>```

I would rather not move the images as they are referenced from lots of different places. I have tried changing the path in the script to ./assets/img/bg/7.jpg and this doesn’t work.

I seem to be having all sorts of problems with relative paths in rails because it seems to apply it’s own rules.

As another example there is a script that changes theme colors and images but this script is referencing the img folder too. I would need to reference the images folder here with a relative path (../assets/img) but relative paths don't appear to behave themselves properly.

```<code>var setColor = function (color, data_header) {
    jQuery('#style_color').attr("href", "assets/css/theme-colors/" + color + ".css");
    if(data_header == 'light'){
        jQuery('.logo img').attr("src", "assets/img/themes/logo1-" + color + ".png");
        jQuery('#logo-footer').attr("src", "assets/img/themes/logo2-" + color + ".png");
        jQuery('.navbar-brand img').attr("src", "assets/img/themes/logo1-" + color + ".png");
    } else if(data_header == 'dark'){
        jQuery('.logo img').attr("src", "assets/img/themes/logo1-" + color + ".png");
        jQuery('#logo-footer').attr("src", "assets/img/themes/logo2-" + color + ".png");
    }
}
</code>```

How can I reliably address a subdirectory of assets to reference images? This issue manifests itself in different ways in different parts of the application.

Thanks

答:
You must use the assets helpers in Rails

```<code>$(".forms-wrapper").backstretch([
    "<%= image_path('bg/6.jpg') %>",
    "<%= image_path('bg/7.jpg') %>",
    "<%= image_path('bg/8.jpg') %>",
    ], {
        fade: 1000,
        duration: 7000
    });
</code>```

This assumes the images are in app/assets/images/img/bg folder.

In general you send in the path following app/assets/images, meaning

```<code>image_path('logo.png')  # references app/assets/images/logo.png
</code>```

Edit:

If you need to reference an unorthodox folder you can add this to your config/initializers/assets.rb (and restart)

```<code>Rails.application.config.assets.paths << Rails.root.join('assets', 'img')
</code>```

Title: Referencing images in Ruby on Rails

Body:
I have a script in a page (below) that calls a jQuery plugin and passes in the path to a number of images. The images are stored in app/assets/img/bg as opposed to app/assets/images.

The JavaScript function is in a file located in app/assets/plugins/backstretch.

I can get the functionality working by changing the path to the images and moving the images:-

I would rather not move the images as they are referenced from lots of different places. I have tried changing the path in the script to ./assets/img/bg/7.jpg and this doesn’t work.

I seem to be having all sorts of problems with relative paths in rails because it seems to apply it’s own rules.

As another example there is a script that changes theme colors and images but this script is referencing the img folder too. I would need to reference the images folder here with a relative path (../assets/img) but relative paths don't appear to behave themselves properly.

var setColor = function (color, data_header) {
    jQuery('#style_color').attr("href", "assets/css/theme-colors/" + color + ".css");
    if(data_header == 'light'){
        jQuery('.logo img').attr("src", "assets/img/themes/logo1-" + color + ".png");
        jQuery('#logo-footer').attr("src", "assets/img/themes/logo2-" + color + ".png");
        jQuery('.navbar-brand img').attr("src", "assets/img/themes/logo1-" + color + ".png");
    } else if(data_header == 'dark'){
        jQuery('.logo img').attr("src", "assets/img/themes/logo1-" + color + ".png");
        jQuery('#logo-footer').attr("src", "assets/img/themes/logo2-" + color + ".png");
    }
}

How can I reliably address a subdirectory of assets to reference images? This issue manifests itself in different ways in different parts of the application.

Thanks

Body:
You must use the assets helpers in Rails

$(".forms-wrapper").backstretch([
    "<%= image_path('bg/6.jpg') %>",
    "<%= image_path('bg/7.jpg') %>",
    "<%= image_path('bg/8.jpg') %>",
    ], {
        fade: 1000,
        duration: 7000
    });

This assumes the images are in app/assets/images/img/bg folder.

In general you send in the path following app/assets/images, meaning

image_path('logo.png')  # references app/assets/images/logo.png

Edit:

If you need to reference an unorthodox folder you can add this to your config/initializers/assets.rb (and restart)

Rails.application.config.assets.paths << Rails.root.join('assets', 'img')


问:
WebPack bundle variables
I'm developing a "widget" and I'm using Webpack, and everything is working fine so far.

But, at this point I want to be able to offer themes to my users so they can choose which color or position they want for the widget

is there a way to pass this variables to the bundle before being injected?

something like

```<code><script src="http://myAwesomeSite.com/js/bundle.js?theme=red"></script>
</code>```

答:
You can use HTML Webpack Plugin to pass the variables you want to use in your HTML. In this case, you will have to transform your HTML to a template (for instance, to an EJS template by renaming the extension of the file to .ejs).

Then you can place the desired variable as follows:

```<code><script src="http://myAwesomeSite.com/js/bundle.js?theme=<%= htmlWebpackPlugin.options.theme %>"></script>
</code>```

Finally, your webpack config file list of plugins should include the HtmlWebpack plugin:

```<code>plugins: [
    // ...
    new HtmlWebpackPlugin({
      theme: 'red',
      template: './template_name.ejs',
      filename: './new_html_file_created.html'
    }),
    //...
  ],
</code>```

Title: WebPack bundle variables

Body:
You can use HTML Webpack Plugin to pass the variables you want to use in your HTML. In this case, you will have to transform your HTML to a template (for instance, to an EJS template by renaming the extension of the file to .ejs).

Then you can place the desired variable as follows:

<script src="http://myAwesomeSite.com/js/bundle.js?theme=<%= htmlWebpackPlugin.options.theme %>"></script>

Finally, your webpack config file list of plugins should include the HtmlWebpack plugin:

plugins: [
    // ...
    new HtmlWebpackPlugin({
      theme: 'red',
      template: './template_name.ejs',
      filename: './new_html_file_created.html'
    }),
    //...
  ],


问:
Object is not being created with info from JSONP API
I'm relatively new to jQuery and Javascript, I'm trying to create an object with information received from an API. The object is supposed to hold an object of basic info, for each of the users from the array users. To do so I make an API call for each user and then pass the json to a constructor that is supposed to create its properties. However, when I run the code the object only has a name property. And only for the first user, not all.

Could someone tell me what am I doing wrong?

Here's the code:

$(document).ready(function () {
    var url = "https://wind-bow.gomix.me/twitch-api/streams/";

    var users = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];

    var streamersObj = {};

    for(var i = 0; i < users.length; i++) {
        console.log(users[i]);
        connectToApi(users[i]);
    }

    function StreamerObjCreate (jsonObj, name) {
       streamersObj[name] = name;
       streamersObj[name].onStream = jsonObj.stream;
       streamersObj[name].channel = jsonObj._links.channel;
       streamersObj[name].stream = jsonObj._links.self;
       console.log(streamersObj);
    }
  function connectToApi (target) {
      url = url + target + "?" + "callback=?";
    $.getJSON(url, function (json) {
        StreamerObjCreate(json, target);
    });
  }
    console.log(streamersObj);
});```

I just started to learn, so if you have any feedback related or unrelated it will be much appreciated.

答:
You're creating a string, and then assigning properties to that string. Try:</p>

```<code> function StreamerObjCreate (jsonObj, name) {
   streamersObj[name] = {
     name: jsonObj.name,
     onStream: jsonObj.stream,
     channel: jsonObj._links.channel,
     stream: jsonObj._links.self
   }
   console.log(streamersObj);
}
</code>```

Body:
I'm relatively new to jQuery and Javascript, I'm trying to create an object with information received from an API. The object is supposed to hold an object of basic info, for each of the users from the array users. To do so I make an API call for each user and then pass the json to a constructor that is supposed to create its properties. However, when I run the code the object only has a name property. And only for the first user, not all.

Could someone tell me what am I doing wrong?

Here's the code:

$(document).ready(function () {
    var url = "https://wind-bow.gomix.me/twitch-api/streams/";

    var users = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];

    var streamersObj = {};

    for(var i = 0; i < users.length; i++) {
        console.log(users[i]);
        connectToApi(users[i]);
    }

    function StreamerObjCreate (jsonObj, name) {
       streamersObj[name] = name;
       streamersObj[name].onStream = jsonObj.stream;
       streamersObj[name].channel = jsonObj._links.channel;
       streamersObj[name].stream = jsonObj._links.self;
       console.log(streamersObj);
    }
  function connectToApi (target) {
      url = url + target + "?" + "callback=?";
    $.getJSON(url, function (json) {
        StreamerObjCreate(json, target);
    });
  }
    console.log(streamersObj);
});

I just started to learn, so if you have any feedback related or unrelated it will be much appreciated.

Body:
You're creating a string, and then assigning properties to that string. Try:

 function StreamerObjCreate (jsonObj, name) {
   streamersObj[name] = {
     name: jsonObj.name,
     onStream: jsonObj.stream,
     channel: jsonObj._links.channel,
     stream: jsonObj._links.self
   }
   console.log(streamersObj);
}


问:
How to consider few parameters in method
I have my own implementation of SimpleFileVisitor with a visitFile method.
I wonder how can i perform more precise search, if there are more than only one parameter. Here what i mean

```<code>public class SearchFileVisitor extends SimpleFileVisitor<Path>
{
    private String partOfName;
    private String partOfContent;
    private int minSize;
    private int maxSize;
    private List<Path> foundFiles = new ArrayList<>();

    public void setPartOfName(String partOfName)
    {
        this.partOfName = partOfName;
    }

    public void setPartOfContent(String partOfContent)
    {
        this.partOfContent = partOfContent;
    }

    public void setMinSize(int minSize)
    {
        this.minSize = minSize;
    }

    public void setMaxSize(int maxSize)
    {
        this.maxSize = maxSize;
    }

    public List<Path> getFoundFiles()
    {
        return foundFiles;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException
    {
        if(partOfName != null && file.toString().contains(partOfName))
        {
           foundFiles.add(file);
        }
        else if(partOfContent != null)
            {
                try(Scanner scanner = new Scanner(file))
                {
                    while(scanner.hasNextLine())
                    {
                        String line = scanner.nextLine();
                        if(line.contains(partOfContent))
                        {
                            foundFiles.add(file);
                            break;
                        }
                    }
                }
            }
         else if(file.toFile().length() < maxSize)
         {
             foundFiles.add(file);
         }
         else if(file.toFile().length() > minSize)
         {
             foundFiles.add(file);
         }
        return super.visitFile(file, attrs);
    }
}
</code>```

The main method:

```<code>public static void main(String[] args) throws IOException
    {
        SearchFileVisitor searchFileVisitor = new SearchFileVisitor();

        searchFileVisitor.setPartOfName("John");
        searchFileVisitor.setPartOfContent("be or not to be?");
        searchFileVisitor.setMinSize(500);
        searchFileVisitor.setMaxSize(10000);

        Files.walkFileTree(Paths.get("D:/SecretFolder"), searchFileVisitor);

        List<Path> foundFiles = searchFileVisitor.getFoundFiles();
        for (Path file : foundFiles)
        {
            System.out.println(file);
        }
    }
</code>```

So, if i set only partOfName it should relay only on it. But if beside it i also set partOfContent and say maxSize, it simultaneously should relay on 3 parameters so far. And consequently if there are 4 par it should relay on four and add to the List, if the object satisfies all the criteria. How can i do that?(Without damn boolean flags)

答:
Note this just describes the general idea. On a review I'd probably reconsider class and method names.

I'd introduce a "Predicate" and describe the expected result in a declarative way using decorators.

The interface of the Predicate would look like this:

```<code>public interface Predicate {
    boolean matches (Path file, BasicFileAttributes attrs);
}
</code>```

Each instance only matches a single criteria like the name and delegates to another predicate for additional tests:

```<code>public final class Named implements Predicate{

   private final Predicate mDelegate;
   private final String mPartOfName;

   public Named(String partOfName, Predicate delegate)
   {
       mPartOfName = partOfName;
       mDelegate = delegate;
   }

   @Override
   public boolean matches(Path file, BasicFileAttributes attrs)
   {
       return file.toString().contains(mPartOfName) && mDelegate.matches(file, attrs);
   }
}
</code>```

Or the maximum size:

```<code>public final class MaxSized implements Predicate{

   private final Predicate mDelegate;
   private final int mMaxSize;

   public MaxSized(int maxSize, Predicate delegate)
   {
       mMaxSize = maxSize;
       mDelegate = delegate;
   }

   @Override
   public boolean matches(Path file, BasicFileAttributes attrs)
   {
       return file.toFile().length() < mMaxSize && mDelegate(file, attrs);
   }
}
</code>```

A "match all" predicate looks as simple as this:

```<code>public final class All implements Predicate{
   @Override
   public boolean matches(Path file, BasicFileAttributes attrs)
   {
       return true;
   }
}
</code>```

The SeachFileVisitor would shrink down to this:

```<code>public final class SearchFileVisitor extends SimpleFileVisitor<Path>{
    private final List<Path> foundFiles = new ArrayList<>();
    private final Predicate mPredicate;

    public SearchFileVisitor(Predicate predicate){
        mPredicate = predicate;
    }

    public List<Path> getFoundFiles() {
        return foundFiles;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        if (mPredicate.matches(file, attrs)) {
            foundFiles.add(file);
        }
    }
}
</code>```

and you would set it up like this:

```<code>SearchFileVisitor searchFileVisitor =
    new SearchFileVisitor(
        new MaxSized(10000,
            new Named("John",
                new All())));
</code>```

The predicate can be read as "return All elements that are Named like "John" and have a maximum size of 10000". You can also read it forward like this: "A size constrained and name constrained version of a match-all predicate".

The predicates are immutable, so no side effects in concurrent environments.

All classes are short and simple and easy to test.

New predicates can be added without modifying existing code.

No "damn boolean flags"

Body:
I have my own implementation of SimpleFileVisitor with a visitFile method.
I wonder how can i perform more precise search, if there are more than only one parameter. Here what i mean

public class SearchFileVisitor extends SimpleFileVisitor<Path>
{
    private String partOfName;
    private String partOfContent;
    private int minSize;
    private int maxSize;
    private List<Path> foundFiles = new ArrayList<>();

    public void setPartOfName(String partOfName)
    {
        this.partOfName = partOfName;
    }

    public void setPartOfContent(String partOfContent)
    {
        this.partOfContent = partOfContent;
    }

    public void setMinSize(int minSize)
    {
        this.minSize = minSize;
    }

    public void setMaxSize(int maxSize)
    {
        this.maxSize = maxSize;
    }

    public List<Path> getFoundFiles()
    {
        return foundFiles;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException
    {
        if(partOfName != null && file.toString().contains(partOfName))
        {
           foundFiles.add(file);
        }
        else if(partOfContent != null)
            {
                try(Scanner scanner = new Scanner(file))
                {
                    while(scanner.hasNextLine())
                    {
                        String line = scanner.nextLine();
                        if(line.contains(partOfContent))
                        {
                            foundFiles.add(file);
                            break;
                        }
                    }
                }
            }
         else if(file.toFile().length() < maxSize)
         {
             foundFiles.add(file);
         }
         else if(file.toFile().length() > minSize)
         {
             foundFiles.add(file);
         }
        return super.visitFile(file, attrs);
    }
}

The main method:

public static void main(String[] args) throws IOException
    {
        SearchFileVisitor searchFileVisitor = new SearchFileVisitor();

        searchFileVisitor.setPartOfName("John");
        searchFileVisitor.setPartOfContent("be or not to be?");
        searchFileVisitor.setMinSize(500);
        searchFileVisitor.setMaxSize(10000);

        Files.walkFileTree(Paths.get("D:/SecretFolder"), searchFileVisitor);

        List<Path> foundFiles = searchFileVisitor.getFoundFiles();
        for (Path file : foundFiles)
        {
            System.out.println(file);
        }
    }

So, if i set only partOfName it should relay only on it. But if beside it i also set partOfContent and say maxSize, it simultaneously should relay on 3 parameters so far. And consequently if there are 4 par it should relay on four and add to the List, if the object satisfies all the criteria. How can i do that?(Without damn boolean flags)

Body:
Note this just describes the general idea. On a review I'd probably reconsider class and method names.

I'd introduce a "Predicate" and describe the expected result in a declarative way using decorators.

The interface of the Predicate would look like this:

public interface Predicate {
    boolean matches (Path file, BasicFileAttributes attrs);
}

Each instance only matches a single criteria like the name and delegates to another predicate for additional tests:

public final class Named implements Predicate{

   private final Predicate mDelegate;
   private final String mPartOfName;

   public Named(String partOfName, Predicate delegate)
   {
       mPartOfName = partOfName;
       mDelegate = delegate;
   }

   @Override
   public boolean matches(Path file, BasicFileAttributes attrs)
   {
       return file.toString().contains(mPartOfName) && mDelegate.matches(file, attrs);
   }
}

Or the maximum size:

public final class MaxSized implements Predicate{

   private final Predicate mDelegate;
   private final int mMaxSize;

   public MaxSized(int maxSize, Predicate delegate)
   {
       mMaxSize = maxSize;
       mDelegate = delegate;
   }

   @Override
   public boolean matches(Path file, BasicFileAttributes attrs)
   {
       return file.toFile().length() < mMaxSize && mDelegate(file, attrs);
   }
}

A "match all" predicate looks as simple as this:

public final class All implements Predicate{
   @Override
   public boolean matches(Path file, BasicFileAttributes attrs)
   {
       return true;
   }
}

The SeachFileVisitor would shrink down to this:

public final class SearchFileVisitor extends SimpleFileVisitor<Path>{
    private final List<Path> foundFiles = new ArrayList<>();
    private final Predicate mPredicate;

    public SearchFileVisitor(Predicate predicate){
        mPredicate = predicate;
    }

    public List<Path> getFoundFiles() {
        return foundFiles;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        if (mPredicate.matches(file, attrs)) {
            foundFiles.add(file);
        }
    }
}

and you would set it up like this:

SearchFileVisitor searchFileVisitor =
    new SearchFileVisitor(
        new MaxSized(10000,
            new Named("John",
                new All())));

The predicate can be read as "return All elements that are Named like "John" and have a maximum size of 10000". You can also read it forward like this: "A size constrained and name constrained version of a match-all predicate".

The predicates are immutable, so no side effects in concurrent environments.

All classes are short and simple and easy to test.

New predicates can be added without modifying existing code.

No "damn boolean flags"


问:
Tensorflow build issue with Bazel
I am getting a build error when executing TF.

I have an include file issue. I have installed latest zlib1g-dev, but no luck.

Bazel binaries built from source V0.3.2,
TF command:

bazel build --config=opt //tensorflow/tools/pip_package:build_pip_package

ERROR:

```<code>ERROR: tensorflow/core/BUILD:853:1: undeclared inclusion(s) in rule '//tensorflow/core:lib_internal':
this rule is missing dependency declarations for the following files included by 'tensorflow/core/lib/png/png_io.cc':
~/.cache/bazel/_bazel_madhu/a9aabe45cf3d94341ef4fb777deb58c5/external/zlib_archive/zlib.h'
~/.cache/bazel/_bazel_madhu/a9aabe45cf3d94341ef4fb777deb58c5/external/zlib_archive/zconf.h'."
</code>```

答: Clean your $HOME/.cache/bazel directory.

Title: Tensorflow build issue with Bazel

Body:
I am getting a build error when executing TF.

I have an include file issue. I have installed latest zlib1g-dev, but no luck.

Bazel binaries built from source V0.3.2,
TF command:

bazel build --config=opt //tensorflow/tools/pip_package:build_pip_package

ERROR:

ERROR: tensorflow/core/BUILD:853:1: undeclared inclusion(s) in rule '//tensorflow/core:lib_internal':
this rule is missing dependency declarations for the following files included by 'tensorflow/core/lib/png/png_io.cc':
~/.cache/bazel/_bazel_madhu/a9aabe45cf3d94341ef4fb777deb58c5/external/zlib_archive/zlib.h'
~/.cache/bazel/_bazel_madhu/a9aabe45cf3d94341ef4fb777deb58c5/external/zlib_archive/zconf.h'."


问:
How return list object to show in view
I have controller where I use service. That service do some querys and return List like this:

Controller:

```<code> public ActionResult GetTareas(string tiporesponsable, int responsableID, int? cuadrillaID, int? sucursalID, int regionID, int solicitudID, string chkFinalizadas)
 {
    var consulta = ag.ConsultarAgenda(tiporesponsable, responsableID,
     cuadrillaID, sucursalID, regionID, solicitudID, chkFinalizadas);
    return View();
 }
</code>```

Now I want to get some value of that service (ag.ConsultarAgenda) for example: "SucursalCodigo" and receive into view into div like:

```<code><div id="event_box" class="margin-bottom-10"></div>
</code>```

Can anyone explain me how can I do it? Regards

Can I do sending Json? like:

```<code> return Json(consulta, JsonRequestBehavior.AllowGet);
</code>```

but How can I receive specific object into view?

答:
ASP.NET MVC offers us several options for passing data from controller to view upon request, one of them is ViewBag.
As of your example above you can do the following in the controller part:

```<code> public ActionResult GetTareas(string tiporesponsable, int responsableID, int? cuadrillaID, int? sucursalID, int regionID, int solicitudID, string chkFinalizadas)
    {
  ViewBag.ConsultarAgenda = ag.ConsultarAgenda(tiporesponsable, responsableID,
 cuadrillaID, sucursalID, regionID, solicitudID, chkFinalizadas);
        return View();
    }
</code>```

And in the view :

```<code><div id="event_box" class="margin-bottom-10">@ViewBag.ConsultarAgenda</div>
</code>```

The best practice to consume Json is via AJAX on the frontend(The View):

```<code><script type="text/javascript">
  $.ajax({
  url: '@Url.Action("GetTareas", "ControllerName")',
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(data){
  //consume the returned data here
   $(".margin-bottom-10").html(data);
  },
  error: errorFunc});
</sript>
<div id="event_box" class="margin-bottom-10"></div>
</code>```

Title: How return list object to show in view

Body:
I have controller where I use service. That service do some querys and return List like this:

Controller:

 public ActionResult GetTareas(string tiporesponsable, int responsableID, int? cuadrillaID, int? sucursalID, int regionID, int solicitudID, string chkFinalizadas)
 {
    var consulta = ag.ConsultarAgenda(tiporesponsable, responsableID,
     cuadrillaID, sucursalID, regionID, solicitudID, chkFinalizadas);
    return View();
 }

Now I want to get some value of that service (ag.ConsultarAgenda) for example: "SucursalCodigo" and receive into view into div like:

Can anyone explain me how can I do it? Regards

Can I do sending Json? like:

 return Json(consulta, JsonRequestBehavior.AllowGet);

but How can I receive specific object into view?

Body:
ASP.NET MVC offers us several options for passing data from controller to view upon request, one of them is ViewBag.
As of your example above you can do the following in the controller part:

 public ActionResult GetTareas(string tiporesponsable, int responsableID, int? cuadrillaID, int? sucursalID, int regionID, int solicitudID, string chkFinalizadas)
    {
  ViewBag.ConsultarAgenda = ag.ConsultarAgenda(tiporesponsable, responsableID,
 cuadrillaID, sucursalID, regionID, solicitudID, chkFinalizadas);
        return View();
    }

And in the view :

<div id="event_box" class="margin-bottom-10">@ViewBag.ConsultarAgenda</div>

The best practice to consume Json is via AJAX on the frontend(The View):

<script type="text/javascript">
  $.ajax({
  url: '@Url.Action("GetTareas", "ControllerName")',
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(data){
  //consume the returned data here
   $(".margin-bottom-10").html(data);
  },
  error: errorFunc});
</sript>
<div id="event_box" class="margin-bottom-10"></div>


问:
Reading integers from text file
I am trying to read integers from a text file but I failed.
(It fails to read even the first integer)

```<code>public void readFromFile(String filename) {
    File file = new File(filename);
    try {
        Scanner scanner = new Scanner(file);
        if (scanner.hasNextInt()) {
            int x = scanner.nextInt();
        }
        scanner.close();

    } catch (FileNotFoundException e) {
        System.out.println("File to load game was not found");
    }
}
</code>```

The error I get is: NoSuchElementException.
The file looks like this:

```<code>N,X1,Y1,X2,Y2,X3,Y3
</code>```

While n equals 3 in this example.

I call this method a in the main method like this:

```<code>readFromFile("file.txt");
</code>```

答:
I am not sure whether you would like to display only the integers after separating them from the string. If that is the case, I would suggest you to use BufferedInputStream.

```<code>    try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)))){
        String input = br.readLine();
        int count = 0;
        for(int i = 0; i < input.length()- 1; i++){
            if(isNumeric(input.charAt(i))){

                // replace the Sysout with your own logic
                   System.out.println(input.charAt(i));
                }
            }
        } catch (IOException ex){
            ex.printStackTrace();
        }
</code>```

where isNumeric can be defined as follows:

```<code>private static boolean isNumeric(char val) {
    return (val >= 48 && val <=57);
}
</code>```

Title: Reading integers from text file

Body:
I am trying to read integers from a text file but I failed.
(It fails to read even the first integer)

public void readFromFile(String filename) {
    File file = new File(filename);
    try {
        Scanner scanner = new Scanner(file);
        if (scanner.hasNextInt()) {
            int x = scanner.nextInt();
        }
        scanner.close();

    } catch (FileNotFoundException e) {
        System.out.println("File to load game was not found");
    }
}

The error I get is: NoSuchElementException.
The file looks like this:

N,X1,Y1,X2,Y2,X3,Y3

While n equals 3 in this example.

I call this method a in the main method like this:

readFromFile("file.txt");

Body:
I am not sure whether you would like to display only the integers after separating them from the string. If that is the case, I would suggest you to use BufferedInputStream.

    try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)))){
        String input = br.readLine();
        int count = 0;
        for(int i = 0; i < input.length()- 1; i++){
            if(isNumeric(input.charAt(i))){

                // replace the Sysout with your own logic
                   System.out.println(input.charAt(i));
                }
            }
        } catch (IOException ex){
            ex.printStackTrace();
        }

where isNumeric can be defined as follows:

private static boolean isNumeric(char val) {
    return (val >= 48 && val <=57);
}


问:
Oracle SQL Developer - Error message does not appear
CREATE OR REPLACE FUNCTION func_totalStaffOrders(
   v_staffID IN INTEGER)
  RETURN VARCHAR
AS
  v_totalOrders NUMBER;
  MESSAGE       VARCHAR2(100);

BEGIN
    IF v_staffID IS NOT NULL THEN
        SELECT COUNT(order_id)
        INTO v_totalOrders
        FROM orders
        WHERE staff_ID = v_staffID;

        MESSAGE := 'Staff with the ID ' || v_staffID ||' has took an overall of ' ||
        v_totalOrders || ' order/s.';
        RETURN MESSAGE;

    ELSE
        MESSAGE:='Null values are not allowed.';
        RETURN MESSAGE;
    END IF;
EXCEPTION
WHEN NO_DATA_FOUND THEN
  MESSAGE := 'Invalid staff ID entered.';
  RETURN MESSAGE;
WHEN OTHERS THEN
  MESSAGE := 'Error! ' || SQLERRM;
  RETURN MESSAGE;
END;

This function counts the total number of orders made by a single staff member. It takes in a staff ID and returns the total number of orders. If I enter a staff ID that is not in the system, it does not show the exception message. Can anyone, help me please?

答:
Your query is always going to return a value.  If there are no matches, then the count will be 0, so v_totalorders will be zero.

No exception is generated.  You want explicit if logic on v_totalorders.


问:
What's the purpose of having both db level and code level uniqueness validations in Rails?
I see a table that has both db-level and code-level validations in Rails.

```<code>CREATE UNIQUE INDEX some_index_name ON joined_table_name USING btree (user_id, restriction_id);
</code>```

and code level:

```<code>class SomeJoinTable
validates_uniqueness_of :restriction_id, :scope => :user_id
end
</code>```

What's the benefit of having both?

答:
To quote an excellent article by thoughtbot:

When you persist a user instance, Rails will validate your model by running a SELECT query to see if any user records already exist with the provided email. Assuming the record proves to be valid, Rails will run the INSERT statement to persist the user. This works great in development and may even work in production if you’re running a single instance of a single process web server.

But you’re not running a lone instance of WEBrick, are you? No, to maximize requests per minute, you’re running Unicorn on multiple Heroku dynos, each with multiple web processes. Let’s take a look at what happens if just two of these processes are trying to create a user with the same email address at around the same time:

...you can create the unique index when generating the migration or model with:

rails generate model user email:string:uniq

With the index in place, how does the above scenario play out now?

Now we have the database acting as our last line of defense in our war on inconsistent data. The second save operation will generate an ActiveRecord::RecordNotUnique exception.

In Conclusion

Rails does many things, but data integrity validations are not one of them. Your relational database is designed to enforce data integrity; let it.

EDIT

Added example of why you'd use validates_uniqueness_of in addition to the db constraint (per OP's comment):

I think it explains why you need database level validations, but my question also is asking why can't we just have database-level validations.

ANSWER

To further quote thoughtbot's article:

The second save operation will generate an ActiveRecord::RecordNotUnique exception. In most cases, this will result in an application error. If you need to provide a better experience, you can rescue and handle that exception in the controller action or use rescue_from at the class level.

Let's see this in action at the class level.

With database-level constraint only:

```<code>class Foo < ApplicationRecord
  belongs_to :bar
  validates_presence_of :name
end

class Bar < ApplicationRecord
  has_many :foos
end

> Foo.create!(bar_id: 1, name: 'Poop')
> Foo.create!(bar_id: 1, name: 'Poop')
ActiveRecord::RecordNotUnique: PG::UniqueViolation: ERROR:  duplicate key value violates unique constraint "index_foos_on..."
</code>```

With database constraint and application-level validation (a la validates_uniqueness_of):

```<code>class Foo < ApplicationRecord
  belongs_to :bar
  validates_presence_of :name
  validates_uniqueness_of :name, scope: :bar_id
end

> Foo.create!(bar_id: 1, name: 'Poop')
> Foo.create!(bar_id: 1, name: 'Poop')
ActiveRecord::RecordInvalid: Validation failed: Name has already been taken
</code>```

Body:
I see a table that has both db-level and code-level validations in Rails.

CREATE UNIQUE INDEX some_index_name ON joined_table_name USING btree (user_id, restriction_id);

and code level:

class SomeJoinTable
validates_uniqueness_of :restriction_id, :scope => :user_id
end

What's the benefit of having both?

Body:
To quote an excellent article by thoughtbot:

When you persist a user instance, Rails will validate your model by running a SELECT query to see if any user records already exist with the provided email. Assuming the record proves to be valid, Rails will run the INSERT statement to persist the user. This works great in development and may even work in production if you’re running a single instance of a single process web server.

But you’re not running a lone instance of WEBrick, are you? No, to maximize requests per minute, you’re running Unicorn on multiple Heroku dynos, each with multiple web processes. Let’s take a look at what happens if just two of these processes are trying to create a user with the same email address at around the same time:

...you can create the unique index when generating the migration or model with:

rails generate model user email:string:uniq

With the index in place, how does the above scenario play out now?

Now we have the database acting as our last line of defense in our war on inconsistent data. The second save operation will generate an ActiveRecord::RecordNotUnique exception.

In Conclusion

Rails does many things, but data integrity validations are not one of them. Your relational database is designed to enforce data integrity; let it.

EDIT

Added example of why you'd use validates_uniqueness_of in addition to the db constraint (per OP's comment):

I think it explains why you need database level validations, but my question also is asking why can't we just have database-level validations.

ANSWER

To further quote thoughtbot's article:

The second save operation will generate an ActiveRecord::RecordNotUnique exception. In most cases, this will result in an application error. If you need to provide a better experience, you can rescue and handle that exception in the controller action or use rescue_from at the class level.

Let's see this in action at the class level.

With database-level constraint only:

class Foo < ApplicationRecord
  belongs_to :bar
  validates_presence_of :name
end

class Bar < ApplicationRecord
  has_many :foos
end

> Foo.create!(bar_id: 1, name: 'Poop')
> Foo.create!(bar_id: 1, name: 'Poop')
ActiveRecord::RecordNotUnique: PG::UniqueViolation: ERROR:  duplicate key value violates unique constraint "index_foos_on..."

With database constraint and application-level validation (a la validates_uniqueness_of):

class Foo < ApplicationRecord
  belongs_to :bar
  validates_presence_of :name
  validates_uniqueness_of :name, scope: :bar_id
end

> Foo.create!(bar_id: 1, name: 'Poop')
> Foo.create!(bar_id: 1, name: 'Poop')
ActiveRecord::RecordInvalid: Validation failed: Name has already been taken


问:
Combining 2 arrays of strings to create an array of hashes in Ruby
I have the following data like this:

```<code>fields = ["player_id", "name", "team", "player_id", "name", "team", "player_id", "name", "team"]
values = ["001", "Pound", "Monstars", "002", "Bang", "Monstars", "003", "Jordan", "Looney Tunes"]
</code>```

I want to create an array of hashes, so the data will look like this:

```<code>[{"player_id"=>"001", "name"=>"Pound", "team"=>"Monstars"}, {"player_id"=>"002", "name"=>"Bang", "team"=>"Monstars"}, {"player_id"=>"003", "name"=>"Jordan", "team"=>"Looney Tunes"}]
</code>```

In my quest to improve, I think I'm still doing more steps than necessary:

```<code>sliced_fields = fields.each_slice(3).to_a
=> [["player_id", "name", "team"], ["player_id", "name", "team"], ["player_id", "name", "team"]]

sliced_values = values.each_slice(3).to_a
=> [["001", "Pound", "Monstars"], ["002", "Bang", "Monstars"], ["003", "Jordan", "Looney Tunes"]]

new_array = sliced_values.map { |i| Hash[sliced_fields[sliced_values.index(i)].zip(i)] }
=> [{"player_id"=>"001", "name"=>"Pound", "team"=>"Monstars"}, {"player_id"=>"002", "name"=>"Bang", "team"=>"Monstars"}, {"player_id"=>"003", "name"=>"Jordan", "team"=>"Looney Tunes"}]
</code>```

Is there an easier way to accomplish this?

答:
You were pretty close. zip first, then each_slice:

```<code>fields.zip(values).each_slice(3).map(&:to_h)
</code>```

See it on repl.it: https://repl.it/I7S3

Body:
I have the following data like this:

fields = ["player_id", "name", "team", "player_id", "name", "team", "player_id", "name", "team"]
values = ["001", "Pound", "Monstars", "002", "Bang", "Monstars", "003", "Jordan", "Looney Tunes"]

I want to create an array of hashes, so the data will look like this:

[{"player_id"=>"001", "name"=>"Pound", "team"=>"Monstars"}, {"player_id"=>"002", "name"=>"Bang", "team"=>"Monstars"}, {"player_id"=>"003", "name"=>"Jordan", "team"=>"Looney Tunes"}]

In my quest to improve, I think I'm still doing more steps than necessary:

sliced_fields = fields.each_slice(3).to_a
=> [["player_id", "name", "team"], ["player_id", "name", "team"], ["player_id", "name", "team"]]

sliced_values = values.each_slice(3).to_a
=> [["001", "Pound", "Monstars"], ["002", "Bang", "Monstars"], ["003", "Jordan", "Looney Tunes"]]

new_array = sliced_values.map { |i| Hash[sliced_fields[sliced_values.index(i)].zip(i)] }
=> [{"player_id"=>"001", "name"=>"Pound", "team"=>"Monstars"}, {"player_id"=>"002", "name"=>"Bang", "team"=>"Monstars"}, {"player_id"=>"003", "name"=>"Jordan", "team"=>"Looney Tunes"}]

Is there an easier way to accomplish this?

Body:
You were pretty close. zip first, then each_slice:

fields.zip(values).each_slice(3).map(&:to_h)

See it on repl.it: https://repl.it/I7S3


问:
Selecting an element's parent's previous sibling's child - traversing elements
I know the title is a bit possessive but I had no better way to word it correctly.

Generated HTML:

```<code><ul class="nav nav-tabs" id="orderResultTabs" role="tablist">
      <li class="nav-item">
            <a class="nav-link active" data-toggle="tab" href="#5423788082" role="tab" aria-controls="home" aria-expanded="false">5423788082</a>
      </li>
      <li class="nav-item active">
            <a class="nav-link active" data-toggle="tab" href="#5424163999" role="tab" aria-controls="home" aria-expanded="false">5424163999</a>
      </li>
</ul>
</code>```

I have a set of bootstrap tabs that get appended after an ajax call. However, after each call I'd like the previous tab to be set to inactive. Making the newest tab the focus. Essentially all previous a.nav-links should have their active class removed after each ajax call.

JS:

```<code>$("#orderResultTabs > li > a:last").parent().prevAll().siblings().find(".active").removeClass("active");
$("#orderResultTabs > li > a:last").addClass("active");
</code>```

Ajax:

```<code> $.ajax({
        type: "POST",
        url: "orders",
        data: "order_id=" + orderID + "&flag=" + flag,
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        success: function(data) {
            // var table = $("#orderOutput");
            var tabNav = $("#orderResultTabs");
            var tabContent = $('.tab-content');
            for (var i = data.length - 1; i >= 0; i--) {
                orderID = data[i].orders_id;
                orderLoop(i, data, tabNav, orderID, tabContent);
            }
            $('.loader').hide(); //hide loader
            $('.clear').show();
            $("#orderResultTabs > li > a:last").parent().prevAll().siblings().find(".active").removeClass("active");

            $("#orderResultTabs > li > a:last").addClass("active");
            $("input[type=orderID]").val("");
            $('#ordersOutput').show();

        },
        error: function(data) {
            alert('error');
            console.log(data);
        }
    });
</code>```

orderLoop()

```<code>function orderLoop(i, data, tabNav, orderID, tabContent) {
    tabNav.append("<li class='nav-item'><a class='nav-link active' data-toggle='tab' href=#" + data[i].orders_id + " role='tab' aria-controls='home' aria-expanded='false'>" + data[i].orders_id + "</a></li>");

    for (var j = data.length - 1; j >= 0; j--) {
        tabContent.append("<div class='tab-pane fade' id=" + data[j].orders_id + " role='tabpanel'><div class='tab'><div class='col'><table class='table table-sm table-responsive' id='orderOutput'></table><form role='form'><button id='viewOrderItems' value='NO ORDER ID' type='button' class='btn btn-primary btn-sm btn-block'>View Order Items</button></form></div></div></div>");
        var table = $(".tab-pane#" + data[j].orders_id + " > .tab > .col > table");
        table.append("<tr><th>ADDRESS ID</th><td>" + data[j].address+ "</td></tr>");
        table.append("<tr><th>CURRENCY</th><td>" + data[j].currency + "</td></tr>");
        table.append("<tr><th>MEMBER ID</th><td>" + data[j].member+ "</td></tr>");
        table.append("<tr><th>STORE ID</th><td>" + data[j].store+ "</td></tr>");
        table.append("<tr><th>TIMEPLACED</th><td>" + moment(data[j].timeplaced).format("MMMM D, YYYY @ h:mm A") + "</td></tr>");
        table.append("<tr><th>TOTAL ADJUSTMENT</th><td>$" + data[j].adjust+ "</td></tr>");
        table.append("<tr><th>TOTAL PRODUCT</th><td>$" + data[j].prod+ "</td></tr>");
        table.append("<tr><th>TOTAL SHIPPING</th><td>$" + data[j].totalshipping + "</td></tr>");
        table.append("<tr><th>TOTAL TAX</th><td>$" + data[j].tax+ "</td></tr>");
        table.append("<tr><th>TOTAL SHIPPING TAX</th><td>$" + data[j].shiptax+ "</td></tr>");
        table.append("<tr><th>TYPE</th><td>" + data[j].type + "</td></tr>");
        var button = $(".tab-pane#" + data[j].orders_id + " > .tab > .col > form > button");
        button.val(data[i].orders_id);
        $('.nav-tabs a:last').tab('show');

    }
}
</code>```

If anyone has ideas on how to do this, I'd love to hear from you.

After @varlogtim's suggestions:

```<code><ul class="nav nav-tabs" id="orderResultTabs" role="tablist">
      <li class="nav-item active">
            <a class="nav-link" data-toggle="tab" href="#5423788082" role="tab" aria-controls="home" aria-expanded="false">5423788082</a>
            </li>
      <li class="nav-item">
            <a class="nav-link active" data-toggle="tab" href="#5424163999" role="tab" aria-controls="home" aria-expanded="false">5424163999</a>
      </li>
</ul>
</code>```

When I click, the list item goes active, the tab content is shown, but the nav-link remains inactive. I've attempted to the following:

```<code>$(".nav-link").on("click", function() {
    $(this).addClass("active");
});
</code>```

After commenting: // $("#orderResultTabs > li:last").addClass("active");

Initial:

```<code><div id="ordersOutput">
      <div role="tabpanel">
            <ul class="nav nav-tabs" id="orderResultTabs" role="tablist">
            </ul>
            <div class="tab-content clearfix">
            </div>
      </div>
</div>
</code>```

First Run:

```<code><div id="ordersOutput" style="display: block;">
      <div role="tabpanel">
            <ul class="nav nav-tabs" id="orderResultTabs" role="tablist">
                  <li class="nav-item"><a class="nav-link **active**" data-toggle="tab" href="#5423788082" role="tab" aria-controls="home" aria-expanded="false">5423788082</a></li>
            </ul>
            <div class="tab-content clearfix">
                  <div class="tab-pane **active**" id="5423788082" role="tabpanel">
                        <div class="tab">
                              <div class="col">
                                    <table class="table table-sm table-responsive" id="orderOutput">
                                    </table>
                                    <form role="form">
                                    </form>
                              </div>
                        </div>
                  </div>
            </div>
      </div>
</div>
</code>```

Second Run:

```<code><div id="ordersOutput" style="display: block;">
      <div role="tabpanel">
            <ul class="nav nav-tabs" id="orderResultTabs" role="tablist">
                  <li class="nav-item"><a class="nav-link" data-toggle="tab" href="#idAlpha" role="tab" aria-controls="home" aria-expanded="false">idAlpha</a></li>
                  <li class="nav-item"><a class="nav-link **active**" data-toggle="tab" href="#idBeta" role="tab" aria-controls="home" aria-expanded="false">idBeta</a></li>
            </ul>
            <div class="tab-content clearfix">
                  <div class="tab-pane" id="idAlpha" role="tabpanel">
                        <div class="tab">
                              <div class="col">
                                    <table class="table table-sm table-responsive" id="orderOutput">
                                    </table>
                                    <form role="form" lpformnum="2">
                                    </form>
                              </div>
                        </div>
                  </div>
                  <div class="tab-pane **active**" id="idBeta" role="tabpanel">
                        <div class="tab">
                              <div class="col">
                                    <table class="table table-sm table-responsive" id="orderOutput">
                                    </table>
                                    <form role="form">
                                    </form>
                              </div>
                        </div>
                  </div>
            </div>
      </div>
</div>
</code>```

After Second Run - When I click the first tab:

Notice that even though I have activated/clicked the (.nav-link) for the first tab (#idAlpha), the (.nav-link) for the second tab (#idBeta) remains active. This should not be. I put a "**_**" around the active classes and the one designated with : _**active**_ is the issue.

```<code><div id="ordersOutput" style="display: block;">
      <div role="tabpanel">
            <ul class="nav nav-tabs" id="orderResultTabs" role="tablist">
                  <li class="nav-item **active**"><a class="nav-link" data-toggle="tab" href="#idAlpha" role="tab" aria-controls="home" aria-expanded="false">idAlpha</a></li>
                  <li class="nav-item"><a class="nav-link _**active**_" data-toggle="tab" href="#idBeta" role="tab" aria-controls="home" aria-expanded="false">idBeta</a></li>
            </ul>
            <div class="tab-content clearfix">
                  <div class="tab-pane **active**" id="idAlpha" role="tabpanel">
                        <div class="tab">
                              <div class="col">
                                    <table class="table table-sm table-responsive" id="orderOutput">
                                    </table>
                                    <form role="form" lpformnum="2">
                                    </form>
                              </div>
                        </div>
                  </div>
                  <div class="tab-pane" id="idBeta" role="tabpanel">
                        <div class="tab">
                              <div class="col">
                                    <table class="table table-sm table-responsive" id="orderOutput">
                                    </table>
                                    <form role="form" lpformnum="3">
                                    </form>
                              </div>
                        </div>
                  </div>
            </div>
      </div>
</div>
</code>```

The most recent tab should not remain active. Once it is outputted the tabs should return back to normal bootstrap functionality.

答:
you should first remove the active class from all the elements then assign it to the last one.</p>

```<code>   $("#orderResultTabs > li > a").find(".active").removeClass("active");
    $("#orderResultTabs > li > a:last").addClass("active");
</code>```

Body:
I know the title is a bit possessive but I had no better way to word it correctly.

Generated HTML:

            5423788082

            5424163999

I have a set of bootstrap tabs that get appended after an ajax call. However, after each call I'd like the previous tab to be set to inactive. Making the newest tab the focus. Essentially all previous a.nav-links should have their active class removed after each ajax call.

JS:

$("#orderResultTabs > li > a:last").parent().prevAll().siblings().find(".active").removeClass("active");
$("#orderResultTabs > li > a:last").addClass("active");

Ajax:

 $.ajax({
        type: "POST",
        url: "orders",
        data: "order_id=" + orderID + "&flag=" + flag,
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        success: function(data) {
            // var table = $("#orderOutput");
            var tabNav = $("#orderResultTabs");
            var tabContent = $('.tab-content');
            for (var i = data.length - 1; i >= 0; i--) {
                orderID = data[i].orders_id;
                orderLoop(i, data, tabNav, orderID, tabContent);
            }
            $('.loader').hide(); //hide loader
            $('.clear').show();
            $("#orderResultTabs > li > a:last").parent().prevAll().siblings().find(".active").removeClass("active");

            $("#orderResultTabs > li > a:last").addClass("active");
            $("input[type=orderID]").val("");
            $('#ordersOutput').show();

        },
        error: function(data) {
            alert('error');
            console.log(data);
        }
    });

orderLoop()

function orderLoop(i, data, tabNav, orderID, tabContent) {
    tabNav.append("
" + data[i].orders_id + "
");

    for (var j = data.length - 1; j >= 0; j--) {
        tabContent.append("

<form role='form'><button id='viewOrderItems' value='NO ORDER ID' type='button' class='btn btn-primary btn-sm btn-block'>View Order Items</button></form>

");
        var table = $(".tab-pane#" + data[j].orders_id + " > .tab > .col > table");
        table.append("
ADDRESS ID	" + data[j].address+ "
");
        table.append("
CURRENCY	" + data[j].currency + "
");
        table.append("
MEMBER ID	" + data[j].member+ "
");
        table.append("
STORE ID	" + data[j].store+ "
");
        table.append("
TIMEPLACED	" + moment(data[j].timeplaced).format("MMMM D, YYYY @ h:mm A") + "
");
        table.append("
TOTAL ADJUSTMENT	$" + data[j].adjust+ "
");
        table.append("
TOTAL PRODUCT	$" + data[j].prod+ "
");
        table.append("
TOTAL SHIPPING	$" + data[j].totalshipping + "
");
        table.append("
TOTAL TAX	$" + data[j].tax+ "
");
        table.append("
TOTAL SHIPPING TAX	$" + data[j].shiptax+ "
");
        table.append("
TYPE	" + data[j].type + "
");
        var button = $(".tab-pane#" + data[j].orders_id + " > .tab > .col > form > button");
        button.val(data[i].orders_id);
        $('.nav-tabs a:last').tab('show');

    }
}

If anyone has ideas on how to do this, I'd love to hear from you.

After @varlogtim's suggestions:

            5423788082

            5424163999

When I click, the list item goes active, the tab content is shown, but the nav-link remains inactive. I've attempted to the following:

$(".nav-link").on("click", function() {
    $(this).addClass("active");
});

After commenting: // $("#orderResultTabs > li:last").addClass("active");

Initial:

First Run:

5423788082

                                    <form role="form">
                                    </form>

Second Run:

idAlpha

idBeta

                                    <form role="form" lpformnum="2">
                                    </form>

                                    <form role="form">
                                    </form>

After Second Run - When I click the first tab:

Notice that even though I have activated/clicked the (.nav-link) for the first tab (#idAlpha), the (.nav-link) for the second tab (#idBeta) remains active. This should not be. I put a "**_**" around the active classes and the one designated with : _**active**_ is the issue.

idAlpha

idBeta

                                    <form role="form" lpformnum="2">
                                    </form>

                                    <form role="form" lpformnum="3">
                                    </form>

The most recent tab should not remain active. Once it is outputted the tabs should return back to normal bootstrap functionality.

Body:
you should first remove the active class from all the elements then assign it to the last one.

   $("#orderResultTabs > li > a").find(".active").removeClass("active");
    $("#orderResultTabs > li > a:last").addClass("active");


问:
Sending e-mails with Spring Email
I'm trying to send an e-mail with Spring Email.

My bean:

```<code>@Bean
public JavaMailSender getJavaMailSender() {
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setHost(„???“);
    mailSender.setPort(587);

    mailSender.setUsername(„???“);
    mailSender.setPassword(„???“);

    Properties props = mailSender.getJavaMailProperties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.debug", "true");

    return mailSender;
}
</code>```

Send function:

```<code>public void sendSimpleMessage(String to, String subject, String text) {

    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo(to);
    message.setSubject(subject);
    message.setText(text);
    emailSender.send(message);
}
</code>```

I'm receiving a positive response, but the e-mail is not delivered.

```<code>250 OK id=1dHroI-0002US-95
DEBUG SMTP: message successfully delivered to mail server
QUIT
221 smtprelay07.ispgateway.de closing connection
</code>```

Can anyone please tell what could be wrong? Thank you.

答: message.setFrom(...) solved the problem!</p>

Title: Sending e-mails with Spring Email

Body:
I'm trying to send an e-mail with Spring Email.

My bean:

@Bean
public JavaMailSender getJavaMailSender() {
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setHost(„???“);
    mailSender.setPort(587);

    mailSender.setUsername(„???“);
    mailSender.setPassword(„???“);

    Properties props = mailSender.getJavaMailProperties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.debug", "true");

    return mailSender;
}

Send function:

public void sendSimpleMessage(String to, String subject, String text) {

    SimpleMailMessage message = new SimpleMailMessage();
    message.setTo(to);
    message.setSubject(subject);
    message.setText(text);
    emailSender.send(message);
}

I'm receiving a positive response, but the e-mail is not delivered.

250 OK id=1dHroI-0002US-95
DEBUG SMTP: message successfully delivered to mail server
QUIT
221 smtprelay07.ispgateway.de closing connection

Can anyone please tell what could be wrong? Thank you.


问:
How to download and save excel file using UFT?
I need to download and save excel to a specific location using UFT.

Step 1: Click on hyperlink as seen below

Step 2: Save the downloaded excel as shown below.

Can you please advice on how to automate this scenario using uft?

答:
I have had to apply a workaround of my own to manage the saving of files from this setup.  Here's the code I used:

```<code>If Browser("AFBHome").WinObject("Notification").Exist(6) Then
    LOG_Write "Notification received - click Save dropdown to get file."
    Browser("AFBHome").WinObject("Notification").WinButton("SaveDropdown").Click micNoCoordinate,micNoCoordinate,micRightBtn
    Browser("AFBHome").WinObject("Notification").WinButton("SaveDropdown").Click
    Wait 0,500 ' Allow the dropdown to render
    Browser("AFBHome").WinObject("Notification").WinButton("SaveDropdown").Type "a"
    Dialog("Save As").Activate
    Wait 0,500
    LOG_Write "Getting file from AFB: " & Dialog("Save As").WinEdit("FileName").GetROProperty("text")
    Dialog("Save As").WinEdit("FileName").SetSelection 0,Len(Dialog("Save As").WinEdit("FileName").GetROProperty("text"))
    Dialog("Save As").WinEdit("FileName").Type sSaveLocation & sFilename
    LOG_Write "Attempting to save export file as " & sSaveLocation & sFilename
    Dialog("Save As").WinButton("Save").Click
End If
</code>```

I had to learn the Notification Bar into the OR as a WinObject, and the SaveDropdown object is attached to the down arrow on the end.  I also had to use the .SetSelection and .Type methods rather than the normal .Set as the SaveAs dialog would end up saving the file to whatever was originally specified rather than the desired path and filename.

You can ignore the LOG_Write statements, as they are a custom function I use to track progress through my scripts.

Body:
I have had to apply a workaround of my own to manage the saving of files from this setup.  Here's the code I used:

If Browser("AFBHome").WinObject("Notification").Exist(6) Then
    LOG_Write "Notification received - click Save dropdown to get file."
    Browser("AFBHome").WinObject("Notification").WinButton("SaveDropdown").Click micNoCoordinate,micNoCoordinate,micRightBtn
    Browser("AFBHome").WinObject("Notification").WinButton("SaveDropdown").Click
    Wait 0,500 ' Allow the dropdown to render
    Browser("AFBHome").WinObject("Notification").WinButton("SaveDropdown").Type "a"
    Dialog("Save As").Activate
    Wait 0,500
    LOG_Write "Getting file from AFB: " & Dialog("Save As").WinEdit("FileName").GetROProperty("text")
    Dialog("Save As").WinEdit("FileName").SetSelection 0,Len(Dialog("Save As").WinEdit("FileName").GetROProperty("text"))
    Dialog("Save As").WinEdit("FileName").Type sSaveLocation & sFilename
    LOG_Write "Attempting to save export file as " & sSaveLocation & sFilename
    Dialog("Save As").WinButton("Save").Click
End If

I had to learn the Notification Bar into the OR as a WinObject, and the SaveDropdown object is attached to the down arrow on the end.  I also had to use the .SetSelection and .Type methods rather than the normal .Set as the SaveAs dialog would end up saving the file to whatever was originally specified rather than the desired path and filename.

You can ignore the LOG_Write statements, as they are a custom function I use to track progress through my scripts.