问:
Call PHP function in ajax, Synchronous XMLHttpRequest deprecarted
Completely new to php/ajax. Every tutorial seems to be outdated in one way or another. Spent about 30 hours already trying to come up with a simple insert/retrieve script. Please help! Once i see the code working its alot easier for me to fiddle with it understand the documentation.

Im getting the following error.

```<code>[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.
</code>```

My index.php relevant data, the error is on the xmlhttp.open line.

```<code>disp_data();
function disp_data(){

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", "update.php?status=disp",false);
</code>```

This is my update.php relevant code. On the tutorial, it is supposed to load my data upon refresh, but its blank. I'm not sure why the tutorial sets it to false, when the documentation ive read at w3schools seems I should make it true, but neither work.

```<code>$status = $_GET["status"];

if ($status == "disp") {
  $link = mysqli_connect("localhost", "root", "");
  mysqli_select_db($link, "checkbox");
</code>```

      $res = mysqli_query($link, "SELECT * FROM table1");

my full index.php

```<code><div id ="disp_data"></div>

<script src="jquery-3.2.1.min.js"></script>
<script type ="text/javascript">

(function() {
  var newXHR = null;

  function sendXHR(type, url, data, callback) {
    newXHR = new XMLHttpRequest() || new window.ActiveXObject("Microsoft.XMLHTTP");
    newXHR.open(type, url, true); // Use async = true to avoid bad user experience for waiting a Sychronous request that might block the UI.
    newXHR.send(data);

    newXHR.onreadystatechange = function() {
      if (this.status === 200 && this.readyState === 4) {
        callback(this.response); // Callback function to process the response.
      }
    };
  }

  sendXHR("GET", "update.php?status=disp", null, function(response) {
    document.getElementById("disp_data").innerHTML=newXHR.responseText;
  });

})();

</script>

</body>
</code>```

my full update.php file

```<code>$status = $_GET["status"];
if($status=="disp")
{
$link = mysqli_connect("localhost", "root", "");
mysqli_select_db($link,"checkbox");
$res = mysqli_query($link,"SELECT * FROM table1");

echo "<table>";
while($row = mysqli_fetch_array($res))
{
echo "<tr>";
echo "<td>";   echo $row["id"]; echo "</td>";
echo "<td>";  echo $row["name"];  echo "</td>";
echo "<td>";  echo $row["city"];  echo "</td>";

echo "</tr>";
}
echo "</table>";
}
</code>```

答:
XMLHttpRequest? try the "new" Fetch API. See: Browser Support for Fetch.

Ok, it is not supported in IE. In my defense, IE 11 is the only version of IE in support, and if they have IE 11, they probably have Edge.

This is a very simple example:

```<code>fetch("example.com")
.then(
    function(response)
    {
        response.text()
        .then(
            function(result)
            {
                console.log(result);
            }
        );
    }
);
</code>```

Of couse, you would change "example.com" to your url.

The following is a more elaborate example, showcasing different options such as headers, request methods, redirections, control credentials (do you want to send cookies and http auth?) and catch exceptions. I recommend to read the MDN article on Using Fetch for more details.

Note: you can pass GET parameters in the url as expected. For a POST request you have to add the member body to the initialization of the Request object.

```<code>var headers = new Headers();
headers.append('X-Requested-With', 'XMLHttpRequest'); // #lies
var request = new Request(
    "example.com",
    {
        method: "GET",
        headers: headers,
        mode: 'cors',
        credentials: 'same-origin',
        cache: 'default',
        redirect: 'follow'}
);
fetch(request)
.then(
    function(response)
    {
        // response status
        console.log('ok: ' + response.ok);
        console.log('status: ' + response.status); //e.g: 200
        // response headers
        console.log('X-Header: ' + response.headers.get('X-Header'));
        // response url (redirections)
        console.log(response.url);
        // body as text
        response.text()
        .then(
            function(result)
            {
                console.log(result);
            }
        );
    }
)
.catch(
    function(err)
    {
        console.log(err);
    }
);
</code>```

Note: in the examples I use the method text to get the text of the body of the response. You may also use the method json that will get the body and parse it directly. There is also a blob method, which can be useful if the response is multimedia among other things.

Body:
Completely new to php/ajax. Every tutorial seems to be outdated in one way or another. Spent about 30 hours already trying to come up with a simple insert/retrieve script. Please help! Once i see the code working its alot easier for me to fiddle with it understand the documentation.

Im getting the following error.

[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.

My index.php relevant data, the error is on the xmlhttp.open line.

disp_data();
function disp_data(){

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", "update.php?status=disp",false);

This is my update.php relevant code. On the tutorial, it is supposed to load my data upon refresh, but its blank. I'm not sure why the tutorial sets it to false, when the documentation ive read at w3schools seems I should make it true, but neither work.

$status = $_GET["status"];

if ($status == "disp") {
  $link = mysqli_connect("localhost", "root", "");
  mysqli_select_db($link, "checkbox");

      $res = mysqli_query($link, "SELECT * FROM table1");

my full index.php

my full update.php file

$status = $_GET["status"];
if($status=="disp")
{
$link = mysqli_connect("localhost", "root", "");
mysqli_select_db($link,"checkbox");
$res = mysqli_query($link,"SELECT * FROM table1");

echo "
";
while($row = mysqli_fetch_array($res))
{
echo "
";
echo "";   echo $row["id"]; echo "	";
echo "";  echo $row["name"];  echo "	";
echo "";  echo $row["city"];  echo "	";

echo "
";
}
echo "
";
}

Body:
XMLHttpRequest? try the "new" Fetch API. See: Browser Support for Fetch.

Ok, it is not supported in IE. In my defense, IE 11 is the only version of IE in support, and if they have IE 11, they probably have Edge.

This is a very simple example:

fetch("example.com")
.then(
    function(response)
    {
        response.text()
        .then(
            function(result)
            {
                console.log(result);
            }
        );
    }
);

Of couse, you would change "example.com" to your url.

The following is a more elaborate example, showcasing different options such as headers, request methods, redirections, control credentials (do you want to send cookies and http auth?) and catch exceptions. I recommend to read the MDN article on Using Fetch for more details.

Note: you can pass GET parameters in the url as expected. For a POST request you have to add the member body to the initialization of the Request object.

var headers = new Headers();
headers.append('X-Requested-With', 'XMLHttpRequest'); // #lies
var request = new Request(
    "example.com",
    {
        method: "GET",
        headers: headers,
        mode: 'cors',
        credentials: 'same-origin',
        cache: 'default',
        redirect: 'follow'}
);
fetch(request)
.then(
    function(response)
    {
        // response status
        console.log('ok: ' + response.ok);
        console.log('status: ' + response.status); //e.g: 200
        // response headers
        console.log('X-Header: ' + response.headers.get('X-Header'));
        // response url (redirections)
        console.log(response.url);
        // body as text
        response.text()
        .then(
            function(result)
            {
                console.log(result);
            }
        );
    }
)
.catch(
    function(err)
    {
        console.log(err);
    }
);

Note: in the examples I use the method text to get the text of the body of the response. You may also use the method json that will get the body and parse it directly. There is also a blob method, which can be useful if the response is multimedia among other things.


来源: stackexchange

问:
Python: ' __init__() takes 7 positional arguments but 8 were given' -- but both statements seem wrong
I have a class that is called in a couple of contexts:

```<code>class Datamodel:
    def __init__(self, habvalues, hablist=[], orglist=[], genlist=[]):
        self.habvalues = habvalues
        self.uses_database = False
        if hablist and orglist and genlist:
            self.hablist = hablist
            self.orglist = orglist
            self.genlist = genlist
            self.uses_database = True
</code>```

There is one method that calls this class using only the habvalues parameter, and it seems to work fine.  However, when called using all the parameters, with lists that are shown by my logging calls to contain valid data, I get the following error message:

__ init__() takes 7 positional arguments but 8 were given

The calling function reads like this:

```<code>self.newmodel = evocontrol.Datamodel(self.habvalues, self.habRecords, self.orgRecords, self.genlist)
</code>```

So, the error message seems to be wrong.  There are not 7 positional arguments in my code, only 4.  And only 4 are given.

What could be the source of a miscount such as this?  What kinds of things should I be looking for here?

答:
Please, try passing the arguments as keyword arguments</p>

```<code>self.newmodel = evocontrol.Datamodel(self.habvalues, hablist=self.habRecords, orglist=self.orgRecords, genlist=self.genlist)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a class that is called in a couple of contexts:

class Datamodel:
    def __init__(self, habvalues, hablist=[], orglist=[], genlist=[]):
        self.habvalues = habvalues
        self.uses_database = False
        if hablist and orglist and genlist:
            self.hablist = hablist
            self.orglist = orglist
            self.genlist = genlist
            self.uses_database = True

There is one method that calls this class using only the habvalues parameter, and it seems to work fine.  However, when called using all the parameters, with lists that are shown by my logging calls to contain valid data, I get the following error message:

__ init__() takes 7 positional arguments but 8 were given

The calling function reads like this:

self.newmodel = evocontrol.Datamodel(self.habvalues, self.habRecords, self.orgRecords, self.genlist)

So, the error message seems to be wrong.  There are not 7 positional arguments in my code, only 4.  And only 4 are given.

What could be the source of a miscount such as this?  What kinds of things should I be looking for here?

Body:
Please, try passing the arguments as keyword arguments

self.newmodel = evocontrol.Datamodel(self.habvalues, hablist=self.habRecords, orglist=self.orgRecords, genlist=self.genlist)


问:
jQuery can't catch the parent element
I am trying to access the parent element up to the button element to modify its css. I can access the span element via id. But when I try to go to the parent img it says undefined

Here is my html code

```<code><button type="button" class="buttonLike">\
    <img src = "../Image/thumbsUp.png" clas="test">\
            <span class="postID" id=' + idPost + '>' + likesPost + '</span>\
    </img>\
 </button>\
</code>```

and here is my jquery code that access the span element

```<code>$.each(result, function (index,data) {
                var liked = data.liked;
                if (liked == true) {
                    console.log($("#" + postId).parent("img").attr("src"));
                }
   });
</code>```

How can i do this right.

答:
try using this

```<code>.parent().find('img').attr('src')
</code>```

console.log($("#idPost").parent().find('img').attr('src'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="buttonLike">
    <img src = "Image/thumbsUp.png" class="test">
    <span class="postID" id='idPost'>likesPost </span>

 </button></code>```

Title: jQuery can't catch the parent element

Body:
I am trying to access the parent element up to the button element to modify its css. I can access the span element via id. But when I try to go to the parent img it says undefined

Here is my html code

<button type="button" class="buttonLike">\
    \
            ' + likesPost + '\
    \
 </button>\

and here is my jquery code that access the span element

$.each(result, function (index,data) {
                var liked = data.liked;
                if (liked == true) {
                    console.log($("#" + postId).parent("img").attr("src"));
                }
   });

How can i do this right.

Body:
try using this

.parent().find('img').attr('src')

console.log($("#idPost").parent().find('img').attr('src'));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="buttonLike">
    <img src = "Image/thumbsUp.png" class="test">
    <span class="postID" id='idPost'>likesPost </span>

 </button>


问:
Akka HTTP Ajax call with parameters
I am working with a use case where I need to make a call to Azkaban via AJAX APi provided by Azkaban which is like

```<code>curl -k -X POST --data "session.id=9089beb2-576d-47e3-b040-86dbdc7f523e&name=aaaa&description=11" https://localhost:8443/manager?action=create
</code>```

Now how using akka HTTP rest services can I send a payload with --data parameter
ie --data "session.id=9089beb2-576d-47e3-b040-86dbdc7f523e&name=aaaa&description=11" part

I tried using RequestBuilding

```<code>   object AzkabanTest extends App{
      implicit val system = ActorSystem()
      implicit val materializer = ActorMaterializer()
      implicit val executor: ExecutionContext = system.dispatcher

      val payloadObject ="action=login&username=amdin&password=admin"
      val url = "https://127.0.0.1:8443"
      val request = Post(url, payloadObject)
      val result: Future[HttpResponse] = Http()
        .singleRequest(request)

      def extract(responseFuture: Future[HttpResponse]): HttpResponse = Await.result(responseFuture, 10.seconds)

      val res = extract(result).entity.toString
      println(res)
    }
The Result should be JsonObject but
    {
      "session.id" : "ee39c901-eac9-48cd-9b3a-b25c00e8bde2",
      "status" : "success"
    }
</code>```

its generating empty List()

Error

```<code>Exception in thread "main" javax.net.ssl.SSLHandshakeException: General SSLEngine problem
    at sun.security.ssl.Handshaker.checkThrown(Handshaker.java:1431)
    at sun.security.ssl.SSLEngineImpl.checkTaskThrown(SSLEngineImpl.java:535)
    at sun.security.ssl.SSLEngineImpl.writeAppRecord(SSLEngineImpl.java:1214)
    at sun.security.ssl.SSLEngineImpl.wrap(SSLEngineImpl.java:1186)
    at javax.net.ssl.SSLEngine.wrap(SSLEngine.java:469)
    at akka.stream.impl.io.TLSActor.akka$stream$impl$io$TLSActor$$doWrap(TLSActor.scala:348)
    at akka.stream.impl.io.TLSActor.akka$stream$impl$io$TLSActor$$doOutbound(TLSActor.scala:317)
    at akka.stream.impl.io.TLSActor$$anonfun$1.apply$mcV$sp(TLSActor.scala:228)
    at akka.stream.impl.Pump$class.pump(Transfer.scala:199)
    at akka.stream.impl.io.TLSActor.pump(TLSActor.scala:48)
    at akka.stream.impl.BatchingInputBuffer.enqueueInputElement(ActorProcessor.scala:90)
    at akka.stream.impl.BatchingInputBuffer$$anonfun$upstreamRunning$1.applyOrElse(ActorProcessor.scala:141)
    at scala.runtime.AbstractPartialFunction.apply(AbstractPartialFunction.scala:36)
    at akka.stream.impl.SubReceive.apply(Transfer.scala:16)
    at akka.stream.impl.FanIn$InputBunch$$anonfun$subreceive$1.applyOrElse(FanIn.scala:234)
    at scala.runtime.AbstractPartialFunction.apply(AbstractPartialFunction.scala:36)
    at akka.stream.impl.SubReceive.apply(Transfer.scala:16)
    at akka.stream.impl.SubReceive.apply(Transfer.scala:12)
    at scala.PartialFunction$class.applyOrElse(PartialFunction.scala:123)
    at akka.stream.impl.SubReceive.applyOrElse(Transfer.scala:12)
    at scala.PartialFunction$OrElse.applyOrElse(PartialFunction.scala:170)
    at akka.actor.Actor$class.aroundReceive(Actor.scala:484)
    at akka.stream.impl.io.TLSActor.aroundReceive(TLSActor.scala:48)
    at akka.actor.ActorCell.receiveMessage(ActorCell.scala:526)
    at akka.actor.ActorCell.invoke(ActorCell.scala:495)
    at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:257)
    at akka.dispatch.Mailbox.run(Mailbox.scala:224)
    at akka.dispatch.Mailbox.exec(Mailbox.scala:234)
    at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
    at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
    at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
    at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
Caused by: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
    at sun.security.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1728)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:304)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:296)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1509)
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
    at sun.security.ssl.Handshaker.processLoop(Handshaker.java:979)
    at sun.security.ssl.Handshaker$1.run(Handshaker.java:919)
    at sun.security.ssl.Handshaker$1.run(Handshaker.java:916)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.security.ssl.Handshaker$DelegatedTask.run(Handshaker.java:1369)
    at akka.stream.impl.io.TLSActor.runDelegatedTasks(TLSActor.scala:402)
    at akka.stream.impl.io.TLSActor.akka$stream$impl$io$TLSActor$$doUnwrap(TLSActor.scala:371)
    at akka.stream.impl.io.TLSActor.akka$stream$impl$io$TLSActor$$doInbound(TLSActor.scala:290)
    at akka.stream.impl.io.TLSActor$$anonfun$1.apply$mcV$sp(TLSActor.scala:225)
    ... 24 more
Caused by: java.security.cert.CertificateException: No subject alternative names present
    at sun.security.util.HostnameChecker.matchIP(HostnameChecker.java:144)
    at sun.security.util.HostnameChecker.match(HostnameChecker.java:93)
    at sun.security.ssl.X509TrustManagerImpl.checkIdentity(X509TrustManagerImpl.java:455)
    at sun.security.ssl.X509TrustManagerImpl.checkIdentity(X509TrustManagerImpl.java:436)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:252)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:136)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1496)
    ... 34 more
</code>```

答:
If your intention is to send single request only you should use Request-Level Client-Side API with Post request:

```<code>import akka.http.scaladsl.Http
import akka.http.scaladsl.client.RequestBuilding._

val request = Post(url, payloadObject)

val result: Future[YourTargetResult] = Http()
  .singleRequest(request)
  .flatMap(handleResponse)

def handleResponse(response: HttpResponse): YourTargetResult = ...
</code>```

payloadObject should be serializable according to the format of choice. In your particular case you might want to make it just a string with desired payload. In more sophisticated cases where XML/JSON is needed you'll need to provide marshallers into desired format (i.e. Spray JSON).

UPD: According to curl man page, in order to build a payload similar to what curl would have for multiple --data parameters, just concatenate the values with &:

-d, --data

If any of these options is used more than once on the same command line, the data pieces specified will be merged together with a separating &-symbol. Thus, using '-d name=daniel -d skill=lousy' would generate a post chunk that looks like 'name=daniel&skill=lousy'.

Title: Akka HTTP Ajax call with parameters

Body:
I am working with a use case where I need to make a call to Azkaban via AJAX APi provided by Azkaban which is like

curl -k -X POST --data "session.id=9089beb2-576d-47e3-b040-86dbdc7f523e&name=aaaa&description=11" https://localhost:8443/manager?action=create

Now how using akka HTTP rest services can I send a payload with --data parameter
ie --data "session.id=9089beb2-576d-47e3-b040-86dbdc7f523e&name=aaaa&description=11" part

I tried using RequestBuilding

   object AzkabanTest extends App{
      implicit val system = ActorSystem()
      implicit val materializer = ActorMaterializer()
      implicit val executor: ExecutionContext = system.dispatcher

      val payloadObject ="action=login&username=amdin&password=admin"
      val url = "https://127.0.0.1:8443"
      val request = Post(url, payloadObject)
      val result: Future[HttpResponse] = Http()
        .singleRequest(request)

      def extract(responseFuture: Future[HttpResponse]): HttpResponse = Await.result(responseFuture, 10.seconds)

      val res = extract(result).entity.toString
      println(res)
    }
The Result should be JsonObject but
    {
      "session.id" : "ee39c901-eac9-48cd-9b3a-b25c00e8bde2",
      "status" : "success"
    }

its generating empty List()

Error

Exception in thread "main" javax.net.ssl.SSLHandshakeException: General SSLEngine problem
    at sun.security.ssl.Handshaker.checkThrown(Handshaker.java:1431)
    at sun.security.ssl.SSLEngineImpl.checkTaskThrown(SSLEngineImpl.java:535)
    at sun.security.ssl.SSLEngineImpl.writeAppRecord(SSLEngineImpl.java:1214)
    at sun.security.ssl.SSLEngineImpl.wrap(SSLEngineImpl.java:1186)
    at javax.net.ssl.SSLEngine.wrap(SSLEngine.java:469)
    at akka.stream.impl.io.TLSActor.akka$stream$impl$io$TLSActor$$doWrap(TLSActor.scala:348)
    at akka.stream.impl.io.TLSActor.akka$stream$impl$io$TLSActor$$doOutbound(TLSActor.scala:317)
    at akka.stream.impl.io.TLSActor$$anonfun$1.apply$mcV$sp(TLSActor.scala:228)
    at akka.stream.impl.Pump$class.pump(Transfer.scala:199)
    at akka.stream.impl.io.TLSActor.pump(TLSActor.scala:48)
    at akka.stream.impl.BatchingInputBuffer.enqueueInputElement(ActorProcessor.scala:90)
    at akka.stream.impl.BatchingInputBuffer$$anonfun$upstreamRunning$1.applyOrElse(ActorProcessor.scala:141)
    at scala.runtime.AbstractPartialFunction.apply(AbstractPartialFunction.scala:36)
    at akka.stream.impl.SubReceive.apply(Transfer.scala:16)
    at akka.stream.impl.FanIn$InputBunch$$anonfun$subreceive$1.applyOrElse(FanIn.scala:234)
    at scala.runtime.AbstractPartialFunction.apply(AbstractPartialFunction.scala:36)
    at akka.stream.impl.SubReceive.apply(Transfer.scala:16)
    at akka.stream.impl.SubReceive.apply(Transfer.scala:12)
    at scala.PartialFunction$class.applyOrElse(PartialFunction.scala:123)
    at akka.stream.impl.SubReceive.applyOrElse(Transfer.scala:12)
    at scala.PartialFunction$OrElse.applyOrElse(PartialFunction.scala:170)
    at akka.actor.Actor$class.aroundReceive(Actor.scala:484)
    at akka.stream.impl.io.TLSActor.aroundReceive(TLSActor.scala:48)
    at akka.actor.ActorCell.receiveMessage(ActorCell.scala:526)
    at akka.actor.ActorCell.invoke(ActorCell.scala:495)
    at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:257)
    at akka.dispatch.Mailbox.run(Mailbox.scala:224)
    at akka.dispatch.Mailbox.exec(Mailbox.scala:234)
    at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
    at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
    at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
    at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
Caused by: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
    at sun.security.ssl.SSLEngineImpl.fatal(SSLEngineImpl.java:1728)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:304)
    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:296)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1509)
    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
    at sun.security.ssl.Handshaker.processLoop(Handshaker.java:979)
    at sun.security.ssl.Handshaker$1.run(Handshaker.java:919)
    at sun.security.ssl.Handshaker$1.run(Handshaker.java:916)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.security.ssl.Handshaker$DelegatedTask.run(Handshaker.java:1369)
    at akka.stream.impl.io.TLSActor.runDelegatedTasks(TLSActor.scala:402)
    at akka.stream.impl.io.TLSActor.akka$stream$impl$io$TLSActor$$doUnwrap(TLSActor.scala:371)
    at akka.stream.impl.io.TLSActor.akka$stream$impl$io$TLSActor$$doInbound(TLSActor.scala:290)
    at akka.stream.impl.io.TLSActor$$anonfun$1.apply$mcV$sp(TLSActor.scala:225)
    ... 24 more
Caused by: java.security.cert.CertificateException: No subject alternative names present
    at sun.security.util.HostnameChecker.matchIP(HostnameChecker.java:144)
    at sun.security.util.HostnameChecker.match(HostnameChecker.java:93)
    at sun.security.ssl.X509TrustManagerImpl.checkIdentity(X509TrustManagerImpl.java:455)
    at sun.security.ssl.X509TrustManagerImpl.checkIdentity(X509TrustManagerImpl.java:436)
    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:252)
    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:136)
    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1496)
    ... 34 more

Body:
If your intention is to send single request only you should use Request-Level Client-Side API with Post request:

import akka.http.scaladsl.Http
import akka.http.scaladsl.client.RequestBuilding._

val request = Post(url, payloadObject)

val result: Future[YourTargetResult] = Http()
  .singleRequest(request)
  .flatMap(handleResponse)

def handleResponse(response: HttpResponse): YourTargetResult = ...

payloadObject should be serializable according to the format of choice. In your particular case you might want to make it just a string with desired payload. In more sophisticated cases where XML/JSON is needed you'll need to provide marshallers into desired format (i.e. Spray JSON).

UPD: According to curl man page, in order to build a payload similar to what curl would have for multiple --data parameters, just concatenate the values with &:

-d, --data

If any of these options is used more than once on the same command line, the data pieces specified will be merged together with a separating &-symbol. Thus, using '-d name=daniel -d skill=lousy' would generate a post chunk that looks like 'name=daniel&skill=lousy'.


问:
How to finish an android application?
I need to finish an android application. For that i wrote

```<code>@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure You want to exit")
        .setCancelable(false)
        .setPositiveButton("YES"),
        new DialogInterface.OnClickListener() {
            // On
            // clicking
            // "Yes"
            // button

            public void onClick(DialogInterface dialog,int id) {
                System.out.println(" onClick ");
                closeApplication(); // Close Application method called
            }
        })
        .setNegativeButton("NO"),
        new DialogInterface.OnClickListener() {
            // On
            // clicking
            // "No"
            // button
            public void onClick(DialogInterface dialog,int id) {
                dialog.cancel();
            }
        });

        AlertDialog alert = builder.create();
        alert.show();
    }

    private void closeApplication() {
        System.out.println("closeApplication ");
        this.finish();
    }
}
</code>```

But if any activity is not finished in the application, when i tried to exit the application that activity is finished first and the application is not exiting.. i tried 2 times to exit this application... How i can finish all the activities in an application when i need to exit... or is there any way to finish the entire application

答:
whenever you are starting a new activity use </p>

```<code>myintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myintent);
</code>```

<p>and in manifest file mention that activity as </p>

```<code><activity android:name=".<Activity Name>" >
        <intent-filter>
        <action android:name="android.intent.action.VIEW"/>
     <category android:name="android.intent.category.DEFAULT" />
     </intent-filter>
       </activity>
</code>```

Title: How to finish an android application?

Body:
I need to finish an android application. For that i wrote

@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Are you sure You want to exit")
        .setCancelable(false)
        .setPositiveButton("YES"),
        new DialogInterface.OnClickListener() {
            // On
            // clicking
            // "Yes"
            // button

            public void onClick(DialogInterface dialog,int id) {
                System.out.println(" onClick ");
                closeApplication(); // Close Application method called
            }
        })
        .setNegativeButton("NO"),
        new DialogInterface.OnClickListener() {
            // On
            // clicking
            // "No"
            // button
            public void onClick(DialogInterface dialog,int id) {
                dialog.cancel();
            }
        });

        AlertDialog alert = builder.create();
        alert.show();
    }

    private void closeApplication() {
        System.out.println("closeApplication ");
        this.finish();
    }
}

But if any activity is not finished in the application, when i tried to exit the application that activity is finished first and the application is not exiting.. i tried 2 times to exit this application... How i can finish all the activities in an application when i need to exit... or is there any way to finish the entire application

Body:
whenever you are starting a new activity use

myintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myintent);

and in manifest file mention that activity as

<activity android:name=".<Activity Name>" >
        <intent-filter>
        <action android:name="android.intent.action.VIEW"/>
     <category android:name="android.intent.category.DEFAULT" />
     </intent-filter>
       </activity>

ContentLicense: CC BY-SA 2.5


问:
Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
I'm trying to allow communication between my nodeJs docker image with my redis docker image (Mac OS X environment):

nodeJs Dockerfile:

```<code>FROM node:4.7.0-slim
EXPOSE 8100
COPY . /nodeExpressDB
CMD ["node", "nodeExpressDB/bin/www"]
</code>```

redis Dockerfile:

```<code>FROM ubuntu:14.04.3
EXPOSE 6379
RUN apt-get update && apt-get install -y redis-server
</code>```

nodeJs code which is trying to connect to redis is:

```<code>var redis = require('redis');
var client = redis.createClient();
</code>```

docker build steps:

```<code>docker build -t redis-docker .
docker build -t node-docker .
</code>```

docker run images steps flow:

```<code>docker run -p 6379:6379 redis-docker
docker run -p 8100:8100 node-docker
</code>```

ERROR:

```<code>Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
    at Object.exports._errnoException (util.js:907:11)
    at exports._exceptionWithHostPort (util.js:930:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1078:14)
</code>```

What should I do inorder to connect to Redis from node-docker?

答:
You can also change your /etc/hosts file to update the dockerip of the redis container.

Find the docker ip by using docker inspect

Body:
I'm trying to allow communication between my nodeJs docker image with my redis docker image (Mac OS X environment):

nodeJs Dockerfile:

FROM node:4.7.0-slim
EXPOSE 8100
COPY . /nodeExpressDB
CMD ["node", "nodeExpressDB/bin/www"]

redis Dockerfile:

FROM ubuntu:14.04.3
EXPOSE 6379
RUN apt-get update && apt-get install -y redis-server

nodeJs code which is trying to connect to redis is:

var redis = require('redis');
var client = redis.createClient();

docker build steps:

docker build -t redis-docker .
docker build -t node-docker .

docker run images steps flow:

docker run -p 6379:6379 redis-docker
docker run -p 8100:8100 node-docker

ERROR:

Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379
    at Object.exports._errnoException (util.js:907:11)
    at exports._exceptionWithHostPort (util.js:930:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1078:14)

What should I do inorder to connect to Redis from node-docker?


问:
How to Construct Xpath of an Element
The Xpath which the Selenium IDE generates automatically is not working, I mean the script fails as it doesn't find any element with such Xpath?

Is there any way to generate Xpath manually?

```<code><div id="ext-gen1252" class="x-trigger-index-0 x-form-trigger x-form-arrow-trigger x-form-trigger-last x-unselectable" role="button" style="-moz-user-select: none;"></div>
</code>```

This the HTML of that Drop down which is annoying me.

```<code>driver.findElement(By.xpath("//div[2]/div/div/div/div/div/div[6]/em/button")).click();
</code>```

This is the java/webdriver because that was exported from IDE

Please give me some solution ASAP

Thanks!

答:
firepath and xpath helper and many other extensions just generate a based on id elements, it's generally not what you want.

If you are using chrome, you could try the extension which generates xpath smartly with pointing to the element

Title: How to Construct Xpath of an Element

Body:
The Xpath which the Selenium IDE generates automatically is not working, I mean the script fails as it doesn't find any element with such Xpath?

Is there any way to generate Xpath manually?

This the HTML of that Drop down which is annoying me.

driver.findElement(By.xpath("//div[2]/div/div/div/div/div/div[6]/em/button")).click();

This is the java/webdriver because that was exported from IDE

Please give me some solution ASAP

Thanks!


问:
How to integrate gitext to VS 2017?
After I install it, it doesn't show up as a menu anywhere.

Am I missing something or does it not support vs2017?

答:
Seems it has been official now.

Visual Studio plugin for using Git Extensions. VS 2017 supported too.

https://marketplace.visualstudio.com/items?itemName=HenkWesthuis.GitExtensions

Title: How to integrate gitext to VS 2017?


问:
How to unpivot columns and GROUP BY based on values in SQL Server?
I want to calculate distinct PID and VID counts per year.

Condition:

```<code>1. Separate count for column A or B or C or D  having value 1  ( A_to_D)
2. Separate count for column E  having value 1  (E)
3. Separate count for column F  having value 1   (F)
4. Separate count for ALL A to F column are NULL  (ALL_NULL)
</code>```

In the output I want a separate new column Alpha with the following values:

```<code>A_to_D, E, F and ALL_Null
</code>```

Current output of table:

```<code>PID VID Flag    Date        A       B       C       D       E       F
1   A1  0       10/17/2013  NULL    NULL    NULL    NULL    NULL    NULL
2   A2  1       5/27/2014   1       NULL    NULL    1       NULL    NULL
3   A3  NULL    2/23/2015   NULL    NULL    NULL    NULL    1       NULL
4   A4  NULL    12/6/2013   NULL    0       NULL    NULL    NULL    NULL
5   A5  NULL    7/14/2016   NULL    NULL    NULL    NULL    NULL    1
6   A6  NULL    4/29/2015   NULL    1       1       NULL    NULL    NULL
7   A7  1       9/30/2016   1       NULL    NULL    NULL    NULL    NULL
8   A8  NULL    6/28/2016   NULL    NULL    NULL    NULL    NULL    NULL
9   A9  1       11/20/2013  NULL    NULL    NULL    NULL    NULL    NULL
10  A10 2       10/8/2015   NULL    1       NULL    NULL    NULL    NULL
</code>```

Here:

```<code>select datepart(Year,date) ,Count(distinct PID) ,Count( distinct VID)
from table
where A is not null or B is Not NUll or C is not null
   or D is not null or E is not Null or F is not null
group by datepart(Year,date)
</code>```

Expected output:

```<code>Year        Count_PID       Count_VID       Alpha
2013                                        A_to_D
2013                                        E
2013                                        F
2013            2               2           ALL_NULL
2014            1               1           A_to_D
2014                                        E
2014                                        F
2014                                        ALL_NULL
2015            2               2           A_to_D
2015            1               1           E
2015                                        F
2015                                        ALL_NULL
2016            2               2           A_to_D
2016                                        E
2016            1                           F
2016            1                           ALL_NULL
</code>```

答:
To be honest I am a little lost on the flag because it doesn't appear that you are treating it the same from year to year when identifying your DISTINCT count of VID.  so if you can elaborate I can easily help you identify where to use it as criteria to filter out the VID appropriately.  But this might get you close. Basic steps find all years and alphas create a cross join and determine if the table row for that year meets the criteria if it does count it.

Test Data:

```<code>DECLARE @Table AS TABLE (PID INT, VID VARCHAR(3), Flag INT, [Date] DATE, A INT, B INT, C INT, D INT, E INT, F INT)

INSERT INTO @Table VALUES
(1 ,'A1',0   ,'10/17/2013',NULL,NULL,NULL,NULL,NULL,NULL)
,(2 ,'A2',1   ,'5/27/2014',1   ,NULL,NULL,1   ,NULL,NULL)
,(3 ,'A3',NULL,'2/23/2015',NULL,NULL,NULL,NULL,1   ,NULL)
,(4 ,'A4',NULL,'12/6/2013',NULL,0   ,NULL,NULL,NULL,NULL)
,(5 ,'A5',NULL,'7/14/2016',NULL,NULL,NULL,NULL,NULL,1     )
,(6 ,'A6',NULL,'4/29/2015',NULL,1   ,1   ,NULL,NULL,NULL)
,(7 ,'A7',1   ,'9/30/2016',1   ,NULL,NULL,NULL,NULL,NULL)
,(8 ,'A8',NULL,'6/28/2016',NULL,NULL,NULL,NULL,NULL,NULL)
,(9 ,'A9',1   ,'11/20/2013',NULL,NULL,NULL,NULL,NULL,NULL)
,(10,'A10',2   ,'10/8/2015',NULL,1   ,NULL,NULL,NULL,NULL)
</code>```

Query:

```<code>;WITH cteYears AS (
    SELECT DISTINCT [Year] = YEAR([Date])
    FROM
       @Table
)
, cteAlphas AS (
    SELECT Alpha
    FROM
       (VALUES ('A_to_D'),('E'),('F'),('ALL_NULL')) t(Alpha)
)

, cteMeetsCriteria AS (
    SELECT
       y.[Year]
       ,t.PID
       ,t.VID
       ,t.Flag
       ,a.Alpha
       ,MeetsCriteria = CASE
          WHEN a.Alpha = 'A_to_D' AND (t.A = 1 OR t.B = 1 OR t.C = 1 OR t.D = 1) THEN 1
          WHEN a.Alpha = 'E' AND t.E = 1 THEN 1
          WHEN a.Alpha = 'F' AND t.F = 1 THEN 1
          WHEN a.Alpha = 'ALL_NULL' AND COALESCE(t.A,t.B,t.C,t.D,t.E,t.F) IS NULL THEN 1
          ELSE 0
       END
    FROM
       cteYears y
       CROSS JOIN cteAlphas a
       LEFT JOIN @Table t
       ON y.[Year] = YEAR(t.[Date])
)

SELECT
    [Year]
    ,Count_PID = NULLIF(COUNT(DISTINCT IIF(MeetsCriteria = 1, PID, NULL)),0)
    ,Count_VID = NULLIF(COUNT(DISTINCT IIF(MeetsCriteria = 1 AND Flag IS NOT NULL, VID, NULL)),0)
    ,Alpha
FROM
    cteMeetsCriteria
GROUP BY
    [Year]
    ,Alpha
ORDER BY
    [Year]
    ,CASE Alpha WHEN 'A_to_D' THEN 1 WHEN 'E' THEN 2 WHEN 'F' THEN 3 WHEN 'ALL_NULL' THEN 4 ELSE 5 END
</code>```

note if a row meets more than 1 criteria it will be counted more than once in the results!

Link showing how it works: http://rextester.com/ITVT9711

If is very easy to move the Flag to different locations to filter or change up the cteMeetsCriteria to be able to treat the flag differently depending on what the alpha is.

Body:
I want to calculate distinct PID and VID counts per year.

Condition:

1. Separate count for column A or B or C or D  having value 1  ( A_to_D)
2. Separate count for column E  having value 1  (E)
3. Separate count for column F  having value 1   (F)
4. Separate count for ALL A to F column are NULL  (ALL_NULL)

In the output I want a separate new column Alpha with the following values:

A_to_D, E, F and ALL_Null

Current output of table:

PID VID Flag    Date        A       B       C       D       E       F
1   A1  0       10/17/2013  NULL    NULL    NULL    NULL    NULL    NULL
2   A2  1       5/27/2014   1       NULL    NULL    1       NULL    NULL
3   A3  NULL    2/23/2015   NULL    NULL    NULL    NULL    1       NULL
4   A4  NULL    12/6/2013   NULL    0       NULL    NULL    NULL    NULL
5   A5  NULL    7/14/2016   NULL    NULL    NULL    NULL    NULL    1
6   A6  NULL    4/29/2015   NULL    1       1       NULL    NULL    NULL
7   A7  1       9/30/2016   1       NULL    NULL    NULL    NULL    NULL
8   A8  NULL    6/28/2016   NULL    NULL    NULL    NULL    NULL    NULL
9   A9  1       11/20/2013  NULL    NULL    NULL    NULL    NULL    NULL
10  A10 2       10/8/2015   NULL    1       NULL    NULL    NULL    NULL

Here:

select datepart(Year,date) ,Count(distinct PID) ,Count( distinct VID)
from table
where A is not null or B is Not NUll or C is not null
   or D is not null or E is not Null or F is not null
group by datepart(Year,date)

Expected output:

Year        Count_PID       Count_VID       Alpha
2013                                        A_to_D
2013                                        E
2013                                        F
2013            2               2           ALL_NULL
2014            1               1           A_to_D
2014                                        E
2014                                        F
2014                                        ALL_NULL
2015            2               2           A_to_D
2015            1               1           E
2015                                        F
2015                                        ALL_NULL
2016            2               2           A_to_D
2016                                        E
2016            1                           F
2016            1                           ALL_NULL

Body:
To be honest I am a little lost on the flag because it doesn't appear that you are treating it the same from year to year when identifying your DISTINCT count of VID.  so if you can elaborate I can easily help you identify where to use it as criteria to filter out the VID appropriately.  But this might get you close. Basic steps find all years and alphas create a cross join and determine if the table row for that year meets the criteria if it does count it.

Test Data:

DECLARE @Table AS TABLE (PID INT, VID VARCHAR(3), Flag INT, [Date] DATE, A INT, B INT, C INT, D INT, E INT, F INT)

INSERT INTO @Table VALUES
(1 ,'A1',0   ,'10/17/2013',NULL,NULL,NULL,NULL,NULL,NULL)
,(2 ,'A2',1   ,'5/27/2014',1   ,NULL,NULL,1   ,NULL,NULL)
,(3 ,'A3',NULL,'2/23/2015',NULL,NULL,NULL,NULL,1   ,NULL)
,(4 ,'A4',NULL,'12/6/2013',NULL,0   ,NULL,NULL,NULL,NULL)
,(5 ,'A5',NULL,'7/14/2016',NULL,NULL,NULL,NULL,NULL,1     )
,(6 ,'A6',NULL,'4/29/2015',NULL,1   ,1   ,NULL,NULL,NULL)
,(7 ,'A7',1   ,'9/30/2016',1   ,NULL,NULL,NULL,NULL,NULL)
,(8 ,'A8',NULL,'6/28/2016',NULL,NULL,NULL,NULL,NULL,NULL)
,(9 ,'A9',1   ,'11/20/2013',NULL,NULL,NULL,NULL,NULL,NULL)
,(10,'A10',2   ,'10/8/2015',NULL,1   ,NULL,NULL,NULL,NULL)

Query:

;WITH cteYears AS (
    SELECT DISTINCT [Year] = YEAR([Date])
    FROM
       @Table
)
, cteAlphas AS (
    SELECT Alpha
    FROM
       (VALUES ('A_to_D'),('E'),('F'),('ALL_NULL')) t(Alpha)
)

, cteMeetsCriteria AS (
    SELECT
       y.[Year]
       ,t.PID
       ,t.VID
       ,t.Flag
       ,a.Alpha
       ,MeetsCriteria = CASE
          WHEN a.Alpha = 'A_to_D' AND (t.A = 1 OR t.B = 1 OR t.C = 1 OR t.D = 1) THEN 1
          WHEN a.Alpha = 'E' AND t.E = 1 THEN 1
          WHEN a.Alpha = 'F' AND t.F = 1 THEN 1
          WHEN a.Alpha = 'ALL_NULL' AND COALESCE(t.A,t.B,t.C,t.D,t.E,t.F) IS NULL THEN 1
          ELSE 0
       END
    FROM
       cteYears y
       CROSS JOIN cteAlphas a
       LEFT JOIN @Table t
       ON y.[Year] = YEAR(t.[Date])
)

SELECT
    [Year]
    ,Count_PID = NULLIF(COUNT(DISTINCT IIF(MeetsCriteria = 1, PID, NULL)),0)
    ,Count_VID = NULLIF(COUNT(DISTINCT IIF(MeetsCriteria = 1 AND Flag IS NOT NULL, VID, NULL)),0)
    ,Alpha
FROM
    cteMeetsCriteria
GROUP BY
    [Year]
    ,Alpha
ORDER BY
    [Year]
    ,CASE Alpha WHEN 'A_to_D' THEN 1 WHEN 'E' THEN 2 WHEN 'F' THEN 3 WHEN 'ALL_NULL' THEN 4 ELSE 5 END

note if a row meets more than 1 criteria it will be counted more than once in the results!

Link showing how it works: http://rextester.com/ITVT9711

If is very easy to move the Flag to different locations to filter or change up the cteMeetsCriteria to be able to treat the flag differently depending on what the alpha is.


问:
How do we make keyboard appear below textView in swift?
I have done keyboard appearing below textfield using

on View did Load adding a observer()

```<code>    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(Gold_Loan_First_ViewController.keyboardDidShow(_:)), name: UIKeyboardDidShowNotification, object: nil)

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(Gold_Loan_First_ViewController.keyboardWillBeHidden(_:)), name: UIKeyboardWillHideNotification, object: nil)
</code>```

And then updating the frame

```<code>weak var activeField: UITextField?

func textFieldDidEndEditing(textField: UITextField) {
    self.activeField = nil

}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if textField==txtOTP {
        txtOTP.errorMessage=""
    }
  return true
}
func textFieldDidBeginEditing(textField: UITextField) {
    self.activeField = textField

}

func keyboardDidShow(notification: NSNotification)
{
    if let activeField = self.activeField,
        let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
        let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize.height, right: 0.0)
        self.scrollView.contentInset = contentInsets
        self.scrollView.scrollIndicatorInsets = contentInsets
        var aRect = self.view.frame
        aRect.size.height -= keyboardSize.size.height
        if (!CGRectContainsPoint(aRect, activeField.frame.origin)) {
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }

}

func keyboardWillBeHidden(notification: NSNotification)
{
    let contentInsets = UIEdgeInsetsZero
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
}
</code>```

But how do I do it for a textView. I tried the same code with didBeginEditing  of textView with no positive effect

答:
I have gone through such a situation. For this first I added extension in my UiViewController :

```<code>    extension CCViewController : UITextViewDelegate {
        func textViewDidBeginEditing(_ textView: UITextView) {
            // write code as per your requirements
        }

        func textViewDidEndEditing(_ textView: UITextView) {
             // write code as per your requirements
        }

        func textViewDidChange(_ textView: UITextView) {
            self.p_adjustMessageFieldFrameForTextView(textView)
        }
    }

    // Defining the p_adjustMessageFieldFrameForTextView method

    fileprivate func p_adjustMessageFieldFrameForTextView(_ textView : UITextView) {
            var finalheight : CGFloat = textView.contentSize.height + 10
            var kMaxMessageFieldHeight : CGFloat = 50
            if  (finalheight > kMaxMessageFieldHeight) {
                finalheight = kMaxMessageFieldHeight;
            } else if (finalheight < kCommentTextViewHeight){
                finalheight = kCommentTextViewHeight;
            }

            scrollView!.view.frame = CGRect(x: 0, y: kNavBarHeight + statuBarHeight, width: SCREEN_WIDTH,height: SCREEN_HEIGHT - finalheight - keyboardRect!.size.height - kNavBarHeight - statuBarHeight)
// It is there for understanding that we have to calculate the exact frame of scroll view

            commentTextView!.frame = CGRect(x: 0, y: bottomOfView(scrollView!.view), width: SCREEN_WIDTH, height: finalheight)
            self.p_setContentOffsetWhenKeyboardIsVisible()
        }

    // Defining the p_setContentOffsetWhenKeyboardIsVisible method

    fileprivate func p_setContentOffsetWhenKeyboardIsVisible() {
            // here you can set the offset of your scroll view
        }
</code>```

Also there is a method named bottomView() :

```<code>func bottomOfView(_ view : UIView) -> CGFloat {
        return view.frame.origin.y + view.frame.size.height
    }
</code>```

Body:
I have done keyboard appearing below textfield using

on View did Load adding a observer()

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(Gold_Loan_First_ViewController.keyboardDidShow(_:)), name: UIKeyboardDidShowNotification, object: nil)

    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(Gold_Loan_First_ViewController.keyboardWillBeHidden(_:)), name: UIKeyboardWillHideNotification, object: nil)

And then updating the frame

weak var activeField: UITextField?

func textFieldDidEndEditing(textField: UITextField) {
    self.activeField = nil

}
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    if textField==txtOTP {
        txtOTP.errorMessage=""
    }
  return true
}
func textFieldDidBeginEditing(textField: UITextField) {
    self.activeField = textField

}

func keyboardDidShow(notification: NSNotification)
{
    if let activeField = self.activeField,
        let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
        let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize.height, right: 0.0)
        self.scrollView.contentInset = contentInsets
        self.scrollView.scrollIndicatorInsets = contentInsets
        var aRect = self.view.frame
        aRect.size.height -= keyboardSize.size.height
        if (!CGRectContainsPoint(aRect, activeField.frame.origin)) {
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }

}

func keyboardWillBeHidden(notification: NSNotification)
{
    let contentInsets = UIEdgeInsetsZero
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
}

But how do I do it for a textView. I tried the same code with didBeginEditing  of textView with no positive effect

Body:
I have gone through such a situation. For this first I added extension in my UiViewController :

    extension CCViewController : UITextViewDelegate {
        func textViewDidBeginEditing(_ textView: UITextView) {
            // write code as per your requirements
        }

        func textViewDidEndEditing(_ textView: UITextView) {
             // write code as per your requirements
        }

        func textViewDidChange(_ textView: UITextView) {
            self.p_adjustMessageFieldFrameForTextView(textView)
        }
    }

    // Defining the p_adjustMessageFieldFrameForTextView method

    fileprivate func p_adjustMessageFieldFrameForTextView(_ textView : UITextView) {
            var finalheight : CGFloat = textView.contentSize.height + 10
            var kMaxMessageFieldHeight : CGFloat = 50
            if  (finalheight > kMaxMessageFieldHeight) {
                finalheight = kMaxMessageFieldHeight;
            } else if (finalheight < kCommentTextViewHeight){
                finalheight = kCommentTextViewHeight;
            }

            scrollView!.view.frame = CGRect(x: 0, y: kNavBarHeight + statuBarHeight, width: SCREEN_WIDTH,height: SCREEN_HEIGHT - finalheight - keyboardRect!.size.height - kNavBarHeight - statuBarHeight)
// It is there for understanding that we have to calculate the exact frame of scroll view

            commentTextView!.frame = CGRect(x: 0, y: bottomOfView(scrollView!.view), width: SCREEN_WIDTH, height: finalheight)
            self.p_setContentOffsetWhenKeyboardIsVisible()
        }

    // Defining the p_setContentOffsetWhenKeyboardIsVisible method

    fileprivate func p_setContentOffsetWhenKeyboardIsVisible() {
            // here you can set the offset of your scroll view
        }

Also there is a method named bottomView() :

func bottomOfView(_ view : UIView) -> CGFloat {
        return view.frame.origin.y + view.frame.size.height
    }


问:
SlickGrid callback onRowSelect?
I want to add a callback when the user selects a row in the table, but I can't figure out how to do so...

Here's what I have so far:

```<code>    <script src="/js/jquery-1.4.2.min.js"></script>
    <script src="jquery-ui-1.8.8.custom.min.js"></script>
    <script src="jquery.event.drag.2.0.min.js"></script>
    <script src="slick.core.js"></script>
    <script src="slick.rowselectionmodel.js"></script>
    <script src="slick.grid.js"></script>
    <script>
        var grid;
        var columns = [ /* my column definitons */ ];
        var options = {
            enableCellNavigation: true,
            enableColumnReorder: false,
            enableAddRow: true
        };

        $(function() {
            $.getJSON('/actions/unit_list.php', function (data) {
                grid = new Slick.Grid("#myGrid", data, columns, options);
                grid.setSelectionModel(new Slick.RowSelectionModel());
                $('#myGrid').show();
            });
        });
    </script>
</code>```

With this, I can select the row (as per this example), but I've no idea how to add a callback when the rows are selected (preferably something that returns the row id(s), since I want to use those to load something else on the page).

Can anyone help me with this?

答: You can get selected rows by calling grid.getSelectedRows().

Title: SlickGrid callback onRowSelect?

Body:
I want to add a callback when the user selects a row in the table, but I can't figure out how to do so...

Here's what I have so far:

With this, I can select the row (as per this example), but I've no idea how to add a callback when the rows are selected (preferably something that returns the row id(s), since I want to use those to load something else on the page).

Can anyone help me with this?


问:
Listview to XML in asp.net
I need to write my listview data into XML file and download it.

my listview like as follows

```<code><asp:ListView ID="lstBrand" runat="server">
        <LayoutTemplate>
            <table>
                <thead>
                    <tr>
                        <th>
                            S.No.
                        </th>
                        <th>
                            Category Name
                        </th>
                     </tr>
                </thead>
                <tbody>
                    <asp:PlaceHolder ID="ItemPlaceHolder" runat="server"></asp:PlaceHolder>
                </tbody>
            </table>
        </LayoutTemplate>
        <EmptyDataTemplate>
            <asp:Label ID="Label" runat="server" Text="No Records Found" ForeColor="Red" Font-Bold="true"></asp:Label>
        </EmptyDataTemplate>
        <ItemTemplate>
            <tr>
                <td align="center" width="30px">
                    <asp:Label ID="lblIndex" runat="server" Text='<%# Container.DataItemIndex + 1 %>' />
                </td>
                <td>
                    <asp:Label ID="lblBrandName" runat="server" Text='<%#Eval("Name") %>' />
                </td>
            </tr>
        </ItemTemplate>
    </asp:ListView>
</code>```

Here my .cs

```<code>string str = "attachment; filename=" + xmlfileName + ".xml";
        currentPage.Response.ClearContent();
        currentPage.Response.AddHeader("content-disposition", str);
        currentPage.Response.ContentType = "application/xml";
        StringWriter writer = new StringWriter();
        HtmlTextWriter writer2 = new HtmlTextWriter(writer);
        HtmlForm child = new HtmlForm();
        lstBrand.Parent.Controls.Add(child);
        child.Attributes["runat"] = "server";
        child.Controls.Add(lstBrand);
        child.RenderControl(writer2);
        currentPage.Response.Write(writer.ToString());
        currentPage.Response.End();
</code>```

Its export the listview sourcecode as it is. How to export my listview data into xml.

答:
You will need to write is as an xml document.

Create a new xml document:

```<code>XmlDocument doc = new XmlDocument();
</code>```

append your data to the document and save it.

Use this as reference: Inserting data into XmlDoument

Title: Listview to XML in asp.net

Body:
I need to write my listview data into XML file and download it.

my listview like as follows

<asp:ListView ID="lstBrand" runat="server">
        <LayoutTemplate>

                            S.No.

                            Category Name

                    <asp:PlaceHolder ID="ItemPlaceHolder" runat="server"></asp:PlaceHolder>

        </LayoutTemplate>
        <EmptyDataTemplate>
            <asp:Label ID="Label" runat="server" Text="No Records Found" ForeColor="Red" Font-Bold="true"></asp:Label>
        </EmptyDataTemplate>
        <ItemTemplate>

                    <asp:Label ID="lblIndex" runat="server" Text='<%# Container.DataItemIndex + 1 %>' />

                    <asp:Label ID="lblBrandName" runat="server" Text='<%#Eval("Name") %>' />

        </ItemTemplate>
    </asp:ListView>

Here my .cs

string str = "attachment; filename=" + xmlfileName + ".xml";
        currentPage.Response.ClearContent();
        currentPage.Response.AddHeader("content-disposition", str);
        currentPage.Response.ContentType = "application/xml";
        StringWriter writer = new StringWriter();
        HtmlTextWriter writer2 = new HtmlTextWriter(writer);
        HtmlForm child = new HtmlForm();
        lstBrand.Parent.Controls.Add(child);
        child.Attributes["runat"] = "server";
        child.Controls.Add(lstBrand);
        child.RenderControl(writer2);
        currentPage.Response.Write(writer.ToString());
        currentPage.Response.End();

Its export the listview sourcecode as it is. How to export my listview data into xml.

Body:
You will need to write is as an xml document.

Create a new xml document:

XmlDocument doc = new XmlDocument();

append your data to the document and save it.

Use this as reference: Inserting data into XmlDoument


问:
How to retrieve git pull history
Whenever I git pulled from remote repo into my local repo, did Git store the information of WHEN I pull? Can I see the log of pulls that I did in my local repo?

Title: How to retrieve git pull history

Body:
You can try and see the content of your git reflog... but that will be limited in time (90 days by default)

vonc@VONCAVN7 D:\git\git
> git reflog --date=iso|grep pull
3ec7d702a HEAD@{2017-09-10 17:42:57 +0200}: pull --no-commit origin master: Fast-forward
b3622a4ee HEAD@{2017-08-12 10:36:08 +0200}: pull: Fast-forward
97e2ff464 HEAD@{2017-06-17 18:43:28 +0200}: pull: Fast-forward
8d1b10321 HEAD@{2017-06-08 20:36:08 +0200}: pull: Fast-forward
10c78a162 HEAD@{2017-05-21 21:22:58 +0200}: pull: Fast-forward
b06d36431 HEAD@{2017-05-14 07:36:49 +0200}: pull: checkout b06d3643105c8758ed019125a4399cb7efdcce2c
1d1bdafd6 HEAD@{2016-12-22 00:36:52 +0100}: pull --no-commit origin master: checkout 1d1bdafd64266e5ee3bd46c6965228f32e4022ea
3ab228137 HEAD@{2016-11-12 08:25:02 +0100}: pull: checkout 3ab228137f980ff72dbdf5064a877d07bec76df9
2632c897f HEAD@{2016-08-20 21:52:51 +0200}: pull: checkout 2632c897f74b1cc9b5533f467da459b9ec725538
2376d3178 HEAD@{2016-08-13 09:19:54 +0200}: pull: checkout 2376d31787760af598db23bb3982a57419854e5c
f8f7adce9 HEAD@{2016-07-31 13:34:44 +0200}: pull: checkout f8f7adce9fc50a11a764d57815602dcb818d1816
ab7797dbe HEAD@{2016-06-22 11:53:20 +0200}: pull: checkout ab7797dbe95fff38d9265869ea367020046db118


问:
Async storage returning null value
I am saving a value in async storage react native. But when I try to get the value it returns null. Below is my code . Any help would be appreciated. Value printed in console is fine but async storage returns null.</p>

```<code> var userID = responseJson[0].UserId;
 console.log("User id"+userID +userID.toString())
 AsyncStorage.setItem("UserId",userID.toString());
 AsyncStorage.getItem("UserId", (UserId) => {
   console.log("get user details"+UserId )
 });
</code>```

答:
As far I understand it's Async method so you won't get it right after you save it.
You have to get it in callback function. See snippet below:

```<code>AsyncStorage.setItem('UID123', JSON.stringify(UID123_object), () => {
  AsyncStorage.mergeItem('UID123', JSON.stringify(UID123_delta), () => {
    AsyncStorage.getItem('UID123', (err, result) => {
      console.log(result);
    });
  });
});
</code>```

Snippet source

In your example it will be like:

```<code> var userID = responseJson[0].UserId;
            console.log("User id"+userID +userID.toString())
            AsyncStorage.setItem("UserId",userID.toString(), () => {
               AsyncStorage.getItem("UserId", (UserId) => {
                    console.log("get user details"+UserId )}
            });
</code>```

Title: Async storage returning null value

Body:
I am saving a value in async storage react native. But when I try to get the value it returns null. Below is my code . Any help would be appreciated. Value printed in console is fine but async storage returns null.

 var userID = responseJson[0].UserId;
 console.log("User id"+userID +userID.toString())
 AsyncStorage.setItem("UserId",userID.toString());
 AsyncStorage.getItem("UserId", (UserId) => {
   console.log("get user details"+UserId )
 });

Body:
As far I understand it's Async method so you won't get it right after you save it.
You have to get it in callback function. See snippet below:

AsyncStorage.setItem('UID123', JSON.stringify(UID123_object), () => {
  AsyncStorage.mergeItem('UID123', JSON.stringify(UID123_delta), () => {
    AsyncStorage.getItem('UID123', (err, result) => {
      console.log(result);
    });
  });
});

Snippet source

In your example it will be like:

 var userID = responseJson[0].UserId;
            console.log("User id"+userID +userID.toString())
            AsyncStorage.setItem("UserId",userID.toString(), () => {
               AsyncStorage.getItem("UserId", (UserId) => {
                    console.log("get user details"+UserId )}
            });


问:
Twilio call button and user input
so I've created this application that allows me to call a phone number from my Twilio account through localhost. I just have to put a / after the port # and the phone number I want to call(localhost:2222/7786453738) and it will send out a call. but I want the user to be able to make that call by inputting a phone number on to the webpage then clicking a button. is that possible? here's my code so far in the index.js file. I run it by going node index.js in the command terminal.</p>

```<code>const express = require("express");
const app = express();

const port = 2222;

app.get("/", function(req, resp){
resp.end("welcome to my app");
});

app.get("/:data", function(req, resp){

var accountSid = 'accountSid'
var authToken = 'authtoken'

var client = require('twilio')(accountSid, authToken);

client.calls.create({
url: 'https://demo.twilio.com/welcome/voice/',
to: req.params.data,
from: '6043302056',
},  function(err, call) {
if(err) {
    console.log(err);
} else {
    console.log(call.sid);
}

})

console.log(req.params.data);
if(req.params.data == "me"){
    resp.end("hi raj");

    //resp.sendFile(__dirname+"/public/index.html)
} else {
    resp.end("Now calling: "+req.params.data);
}
});

app.listen(port, function(err){
if(err){
    console.log("error starting "+err);
    return false;
}

console.log("port is running. "+port);
})
</code>```

答:
Yes,

first: you can do that, but you need to write the code in HTML File or at least include this code in html file, and call the Twilo's function after you click on the respective button. For that first, render a HTML page, after user enters the address, on that HTML Page give input number and call now button feature. and after user clicks on the button, do:

```<code>function callNow() {
var num = document.getElementById('number').value;

  client.calls.create({
    url: 'https://demo.twilio.com/welcome/voice/',
    to: num,
    from: '6043302056',
  },  function(err, call) {
  if(err) {
     console.log(err);
  } else {
     console.log(call.sid);
  }
{
</code>```

Your HTML Code should be:

```<code><input id="number">
<button onclick="callNow()">Call Now</button>
</code>```

You can include twilio cdn and use this feature. I am just giving you the concept, I hope you will find this helpful.

Title: Twilio call button and user input

Body:
so I've created this application that allows me to call a phone number from my Twilio account through localhost. I just have to put a / after the port # and the phone number I want to call(localhost:2222/7786453738) and it will send out a call. but I want the user to be able to make that call by inputting a phone number on to the webpage then clicking a button. is that possible? here's my code so far in the index.js file. I run it by going node index.js in the command terminal.

const express = require("express");
const app = express();

const port = 2222;

app.get("/", function(req, resp){
resp.end("welcome to my app");
});

app.get("/:data", function(req, resp){

var accountSid = 'accountSid'
var authToken = 'authtoken'

var client = require('twilio')(accountSid, authToken);

client.calls.create({
url: 'https://demo.twilio.com/welcome/voice/',
to: req.params.data,
from: '6043302056',
},  function(err, call) {
if(err) {
    console.log(err);
} else {
    console.log(call.sid);
}

})

console.log(req.params.data);
if(req.params.data == "me"){
    resp.end("hi raj");

    //resp.sendFile(__dirname+"/public/index.html)
} else {
    resp.end("Now calling: "+req.params.data);
}
});

app.listen(port, function(err){
if(err){
    console.log("error starting "+err);
    return false;
}

console.log("port is running. "+port);
})

Body:
Yes,

first: you can do that, but you need to write the code in HTML File or at least include this code in html file, and call the Twilo's function after you click on the respective button. For that first, render a HTML page, after user enters the address, on that HTML Page give input number and call now button feature. and after user clicks on the button, do:

function callNow() {
var num = document.getElementById('number').value;

  client.calls.create({
    url: 'https://demo.twilio.com/welcome/voice/',
    to: num,
    from: '6043302056',
  },  function(err, call) {
  if(err) {
     console.log(err);
  } else {
     console.log(call.sid);
  }
{

Your HTML Code should be:

<input id="number">
<button onclick="callNow()">Call Now</button>

You can include twilio cdn and use this feature. I am just giving you the concept, I hope you will find this helpful.


问:
Spring Boot shows the String instead of the HTML file from an Angular2 Single Page app
I'm trying to map all GET requests to unmapped url of the site to show the index.html file.

So, I created the following @RestController:

```<code>@RequestMapping(method=RequestMethod.GET)
public String redirectToIndex() {
    return "index.html";
}
</code>```

My index.html is in resources/static/index.html. I also tried the following controller:

```<code>@RequestMapping(method=RequestMethod.GET)
public String redirectToIndex() {
    return "/static/index.html";
}
</code>```

However, in both cases, browser literally shows the strings index.html and /static/index.html respectively instead of showing the html file. I tried a lot of different other approaches to similar questions here but can't get it to resolve... Please help.

EDIT:

My fill @RequestController class:

```<code>@RestController
public class FeedbackController {
    @Autowired
    private FeedbackService feedbackService;

    @RequestMapping(method=RequestMethod.POST, value="/feedback")
    public Feedback addFeedback(@RequestBody Feedback feedback) {
        return feedbackService.addFeedback(feedback);
    }

    @RequestMapping(method=RequestMethod.GET)
    public String redirectToIndex() {
        return "index.html";
    }

}
</code>```

My pom.xml:

```<code><parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</code>```

答:
With @RestController annotation ResponseBody will be generated. In this case String will be generated as string instead of your view mapping.

In your case you will have to use @Controller and you will have to use redirect or create proper index.jsp and return "index"

Below is the code i can think of

add these into your application.properties

```<code>   spring.mvc.view.prefix=/WEB-INF/view/
   spring.mvc.view.suffix=.jsp
</code>```

Add index.jsp under /main/webapp/WEB-INF/view folder.  for controller add the following code

```<code>@Controller
public class MyController {

    @RequestMapping("/index")
     public String index() {
        return "index"
     }
}
</code>```

Body:
I'm trying to map all GET requests to unmapped url of the site to show the index.html file.

So, I created the following @RestController:

@RequestMapping(method=RequestMethod.GET)
public String redirectToIndex() {
    return "index.html";
}

My index.html is in resources/static/index.html. I also tried the following controller:

@RequestMapping(method=RequestMethod.GET)
public String redirectToIndex() {
    return "/static/index.html";
}

However, in both cases, browser literally shows the strings index.html and /static/index.html respectively instead of showing the html file. I tried a lot of different other approaches to similar questions here but can't get it to resolve... Please help.

EDIT:

My fill @RequestController class:

@RestController
public class FeedbackController {
    @Autowired
    private FeedbackService feedbackService;

    @RequestMapping(method=RequestMethod.POST, value="/feedback")
    public Feedback addFeedback(@RequestBody Feedback feedback) {
        return feedbackService.addFeedback(feedback);
    }

    @RequestMapping(method=RequestMethod.GET)
    public String redirectToIndex() {
        return "index.html";
    }

}

My pom.xml:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath />
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

Body:
With @RestController annotation ResponseBody will be generated. In this case String will be generated as string instead of your view mapping.

In your case you will have to use @Controller and you will have to use redirect or create proper index.jsp and return "index"

Below is the code i can think of

add these into your application.properties

   spring.mvc.view.prefix=/WEB-INF/view/
   spring.mvc.view.suffix=.jsp

Add index.jsp under /main/webapp/WEB-INF/view folder.  for controller add the following code

@Controller
public class MyController {

    @RequestMapping("/index")
     public String index() {
        return "index"
     }
}


问:
How to configure phpunit located in vendor/bin directory?
I'm trying to set the database for the tests I'm going to run but I have one problem:

I can't run phpunit because I have an older version.

I've already read all posts related to upgrade phpunit in a global context but I've failed doing that. I tried everything and I just couldn't upgrade phpunit globally so I started to use vendor/bin/phpunit instead and everything works fine. Now that led me to a second problem:

How can I set the database where I am going to run my tests?

I know I need to set all the information about the database in the phpunit.xml file but the one that is in the base path works only for the global phpunit version. So where can I set the database information for the vendor/bin phunit version?

答:
phpunit.xml works for both local and global phpunit installation. You don't need a global phpunit. Just run your test using ./vendor/bin/phpunit.

For the database configuration add the following to your phpunit.xml:

```<code>    <!-- To use sqlite in memory (Faster)
    <env name="DB_CONNECTION" value="sqlite"/>
    <env name="DB_DATABASE" value=":memory:"/>

    <!-- To use Mysql -->
    <!--<env name="DB_DATABASE" value="databse_test"/>-->
</code>```

Body:
phpunit.xml works for both local and global phpunit installation. You don't need a global phpunit. Just run your test using ./vendor/bin/phpunit.

For the database configuration add the following to your phpunit.xml:

    <!-- To use sqlite in memory (Faster)
    <env name="DB_CONNECTION" value="sqlite"/>
    <env name="DB_DATABASE" value=":memory:"/>

    <!-- To use Mysql -->
    <!--<env name="DB_DATABASE" value="databse_test"/>-->


问:
d3 library installed with npm doesn't load json file
I just installed d3 using npm. In package.json it shows on dependencies "d3": "^4.11.0" version,.

I tried to load a simple json file with the next code:

```<code>const d3 = require('d3')

d3.json('jsonfile.json', (err, data) => {
  if (err) {
    console.log(err)
  }
  data.keys.map((t) => {
    console.log(t)
  })
})
</code>```

But I got this error:

```<code>SyntaxError: Unexpected token T in JSON at position 0
</code>```

The json file is actually ok. I verified using this tool: https://codebeautify.org/jsonvalidator.

However, when I removed this line const d3 = require('d3') and inserted the script directly in the HTML file:

```<code><script type='text/javascript' src='/js/d3.min.js'></script>
</code>```

...using 3.5.5 version, the json file was loaded.

Is there something new in d3 version ^4.11.0 in order to load local files?

答:
If you want to run your code as a node app you have to load json with the full url:

```<code>const d3 = require('d3');
//use full url to where the json file is
d3.json('http://localhost:8080/jsonfile.json', (err, data) => {
  if (err) {
    console.log(err)
  }
  data.keys.map((t) => {
    console.log(t)
  })
});
</code>```

If you want to run the code as a node app and load the file from disk you could load the file like so:

```<code>fs = require('fs');
const readFile = (file,encoding) =>
  new Promise(
    (resolve,reject)=>
      fs.readFile(
        file
        ,encoding
        ,(err,data) => {
          if(err !== null){
            reject(err);return;
          }
          resolve(data);
        }
      )
    )
;

readFile("./static/jsonfile.json",'utf8')
.then(
  data =>
    data.toString()
).then(
  text =>
    console.log("Got file content:\n",text)
  ,err =>
    console.error("Failed to load file:",err)
);
</code>```

If your code runs in a browser but you want to use npm as dependency management then you can use requirejs (old way) or webpack (better but a bit more complicated to learn and set up). If you are using your code in a browser I wonder how you do not get an error on const d3 = require('d3');.

Body:
I just installed d3 using npm. In package.json it shows on dependencies "d3": "^4.11.0" version,.

I tried to load a simple json file with the next code:

const d3 = require('d3')

d3.json('jsonfile.json', (err, data) => {
  if (err) {
    console.log(err)
  }
  data.keys.map((t) => {
    console.log(t)
  })
})

But I got this error:

SyntaxError: Unexpected token T in JSON at position 0

The json file is actually ok. I verified using this tool: https://codebeautify.org/jsonvalidator.

However, when I removed this line const d3 = require('d3') and inserted the script directly in the HTML file:

...using 3.5.5 version, the json file was loaded.

Is there something new in d3 version ^4.11.0 in order to load local files?

Body:
If you want to run your code as a node app you have to load json with the full url:

const d3 = require('d3');
//use full url to where the json file is
d3.json('http://localhost:8080/jsonfile.json', (err, data) => {
  if (err) {
    console.log(err)
  }
  data.keys.map((t) => {
    console.log(t)
  })
});

If you want to run the code as a node app and load the file from disk you could load the file like so:

fs = require('fs');
const readFile = (file,encoding) =>
  new Promise(
    (resolve,reject)=>
      fs.readFile(
        file
        ,encoding
        ,(err,data) => {
          if(err !== null){
            reject(err);return;
          }
          resolve(data);
        }
      )
    )
;

readFile("./static/jsonfile.json",'utf8')
.then(
  data =>
    data.toString()
).then(
  text =>
    console.log("Got file content:\n",text)
  ,err =>
    console.error("Failed to load file:",err)
);

If your code runs in a browser but you want to use npm as dependency management then you can use requirejs (old way) or webpack (better but a bit more complicated to learn and set up). If you are using your code in a browser I wonder how you do not get an error on const d3 = require('d3');.


问:
Get Tasks completed by a user(past tasks information)
I want to see the tasks handled by a particular user say 'xyz'.
I see that Tasks API provide only the count of completed tasks, However I couldn't find the task details.

Thank You!

答:
Twilio developer evangelist here.

Tasks are somewhat ephemeral within TaskRouter. The documentation says:

Important: Tasks are deleted 5 minutes after either they are canceled or completed. You can still query events that occurred for a Task via the Events API.

You can query against past tasks using the Events API.

The documentation does also say that if deleting tasks breaks your usecase then do please get in touch with support with what you are trying to achieve.

Let me know if that helps at all.


问:
Can't convert model to tensorflow's lite format
I'm having a trained rnn that I try to use on mobile. Problem is, when I use toco to convert my .pb file to .tflite it fails with the following error message:

```<code>WARNING: Config values are not defined in any .rc file: opt.
INFO: Found 1 target...
Target //tensorflow/contrib/lite/toco:toco up-to-date:
  bazel-bin/tensorflow/contrib/lite/toco/toco
INFO: Elapsed time: 0.287s, Critical Path: 0.00s

INFO: Running command line: bazel-bin/tensorflow/contrib/lite/toco/toco '--input_file=/Users/valentinradu/Playgrounds/char-rnn-tensorflow/remote_save/latest/graph_frz.pb' '--output_file=/Users/valentinradu/Playgrounds/char-rnn-tensorflow/remote_save/latest/graph.tflite' '--input_format=TENSORFLOW_GRAPHDEF' '--output_format=TFLITE' '--input_type=FLOAT' '--inference_type=FLOAT' '--input_shapes=1,128:1,50,50' '--input_arrays=state_in,data_in' '--output_arrays=state_out,data_out'
2017-11-16 06:48:00.156091: I tensorflow/contrib/lite/toco/import_tensorflow.cc:937] Converting unsupported operation: Fill
2017-11-16 06:48:00.156811: I tensorflow/contrib/lite/toco/import_tensorflow.cc:937] Converting unsupported operation: Fill
2017-11-16 06:48:00.156821: I tensorflow/contrib/lite/toco/import_tensorflow.cc:937] Converting unsupported operation: Pack
2017-11-16 06:48:00.156829: I tensorflow/contrib/lite/toco/import_tensorflow.cc:937] Converting unsupported operation: Pack
2017-11-16 06:48:00.156841: I tensorflow/contrib/lite/toco/import_tensorflow.cc:937] Converting unsupported operation: Unpack
2017-11-16 06:48:00.156856: I tensorflow/contrib/lite/toco/import_tensorflow.cc:937] Converting unsupported operation: StridedSlice
2017-11-16 06:48:00.156872: I tensorflow/contrib/lite/toco/import_tensorflow.cc:937] Converting unsupported operation: StridedSlice
2017-11-16 06:48:00.157260: I tensorflow/contrib/lite/toco/import_tensorflow.cc:937] Converting unsupported operation: Pack
2017-11-16 06:48:00.157277: I tensorflow/contrib/lite/toco/import_tensorflow.cc:937] Converting unsupported operation: Pack
2017-11-16 06:48:00.158053: I tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.cc:39] Before general graph transformations: 40 operators, 64 arrays (0 quantized)
2017-11-16 06:48:00.158141: F tensorflow/contrib/lite/toco/graph_transformations/propagate_fixed_sizes.cc:793] Check failed: indices_shape.dimensions_count() == 1 (2 vs. 1)
</code>```

Now, I understand that this is because toco expects my model to have only one input, however, in the example I've found so far people are using 2 inputs with no problem.

Does it have to do with an operation I use inside my model?
Is this a known limitation or is it a bug?

Here is how I build my model.

答:
It seems that unfortunately it's a limitation of the gather operator. I'll leave this here in case anybody else hits this problem in the future.

If anybody with greater experience with tensorflow, or from the team can confirm this, it would be great!.

Body:
I'm having a trained rnn that I try to use on mobile. Problem is, when I use toco to convert my .pb file to .tflite it fails with the following error message:

WARNING: Config values are not defined in any .rc file: opt.
INFO: Found 1 target...
Target //tensorflow/contrib/lite/toco:toco up-to-date:
  bazel-bin/tensorflow/contrib/lite/toco/toco
INFO: Elapsed time: 0.287s, Critical Path: 0.00s

INFO: Running command line: bazel-bin/tensorflow/contrib/lite/toco/toco '--input_file=/Users/valentinradu/Playgrounds/char-rnn-tensorflow/remote_save/latest/graph_frz.pb' '--output_file=/Users/valentinradu/Playgrounds/char-rnn-tensorflow/remote_save/latest/graph.tflite' '--input_format=TENSORFLOW_GRAPHDEF' '--output_format=TFLITE' '--input_type=FLOAT' '--inference_type=FLOAT' '--input_shapes=1,128:1,50,50' '--input_arrays=state_in,data_in' '--output_arrays=state_out,data_out'
2017-11-16 06:48:00.156091: I tensorflow/contrib/lite/toco/import_tensorflow.cc:937] Converting unsupported operation: Fill
2017-11-16 06:48:00.156811: I tensorflow/contrib/lite/toco/import_tensorflow.cc:937] Converting unsupported operation: Fill
2017-11-16 06:48:00.156821: I tensorflow/contrib/lite/toco/import_tensorflow.cc:937] Converting unsupported operation: Pack
2017-11-16 06:48:00.156829: I tensorflow/contrib/lite/toco/import_tensorflow.cc:937] Converting unsupported operation: Pack
2017-11-16 06:48:00.156841: I tensorflow/contrib/lite/toco/import_tensorflow.cc:937] Converting unsupported operation: Unpack
2017-11-16 06:48:00.156856: I tensorflow/contrib/lite/toco/import_tensorflow.cc:937] Converting unsupported operation: StridedSlice
2017-11-16 06:48:00.156872: I tensorflow/contrib/lite/toco/import_tensorflow.cc:937] Converting unsupported operation: StridedSlice
2017-11-16 06:48:00.157260: I tensorflow/contrib/lite/toco/import_tensorflow.cc:937] Converting unsupported operation: Pack
2017-11-16 06:48:00.157277: I tensorflow/contrib/lite/toco/import_tensorflow.cc:937] Converting unsupported operation: Pack
2017-11-16 06:48:00.158053: I tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.cc:39] Before general graph transformations: 40 operators, 64 arrays (0 quantized)
2017-11-16 06:48:00.158141: F tensorflow/contrib/lite/toco/graph_transformations/propagate_fixed_sizes.cc:793] Check failed: indices_shape.dimensions_count() == 1 (2 vs. 1)

Now, I understand that this is because toco expects my model to have only one input, however, in the example I've found so far people are using 2 inputs with no problem.

Does it have to do with an operation I use inside my model?
Is this a known limitation or is it a bug?

Here is how I build my model.


问:
Android studio 3: Outdated Kotlin Runtime
I don't use kotlin in my current a project, but always showing following warning:

When I click to "Update runtime" will be show following popup:

And here dependencies who i used:

Anybody know how to solve this google trick?

**Edit

This is bug of Android studio, because i don't using kotlin. If any body will be any idiom how to fix it can add extra answer to this a question

答:
Add this into your build.gradle (Project)

```<code>buildscript {
ext.kotlin_version = '1.1.60'
repositories {
    google()
    jcenter()
}
dependencies {
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}

allprojects {
repositories {
    google()
    jcenter()
}
}
</code>```

And this code into your build.gradle (Module)

```<code>apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

dependencies {
implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
}
</code>```

This will update your Kotlin version. You can find more in Kotlin Targeting Android

Body:
Add this into your build.gradle (Project)

buildscript {
ext.kotlin_version = '1.1.60'
repositories {
    google()
    jcenter()
}
dependencies {
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}

allprojects {
repositories {
    google()
    jcenter()
}
}

And this code into your build.gradle (Module)

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

dependencies {
implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
}

This will update your Kotlin version. You can find more in Kotlin Targeting Android


问:
Parallel.ForEach and ListView Control
I am having an issue getting the Parallel.ForEach to work properly. I have a listview control that loads a files contents or mutliple files contents (each file represents a log file) into a richtextbox. Had it all working with a Foreach loop but decided that the parallel operation would cut down on the loadtime when loading 100+ files.

Here is the code block I was using for the foreach loop. How do I get a Parallel.Foreach working?

```<code>//Set cursor to WaitCursor Style
this.Cursor = Cursors.WaitCursor;

//Clear Messages RichTexBox
this.rtbMessages.Clear();

//Loop through each selected file
foreach (ListViewItem Item in lvMessageFiles.Items)
{
    //Check if item is selected in the listview
    if (Item.Selected && rtbMessages.TextLength < rtbMessages.MaxLength)
    {
        //Get Path to message file
        filename = String.Format("{0}\\Data\\Log\\{1}.log", Global.AppPath, Item.SubItems[0].Text);

        //Set Timeline Events calendar to selected items created date
        cvTimeline.ShowDate(Convert.ToDateTime(lvMessageFiles.SelectedItems[0].SubItems[2].Text));

        //Check if file exists
        if (File.Exists(filename))
        {
            //streamreader to read the file
            reader = new StreamReader(filename);

            //to copy the read content in to richtextbox
            string MessageContents = String.Format("{0}\n{1}\n", ("file:///" + filename.Replace(" ", "%20").Replace("\\", "/")), reader.ReadToEnd());
            rtbMessages.Text += MessageContents;

            // closing streamreader
            reader.Close();
        }
    }

}

//Set cursor to WaitCursor Style
this.Cursor = Cursors.Default;
</code>```

答:
I am experiencing dejavu with this question... Anyway, take a look at this blog article. It's very simple to my taste but does exactly what you are trying to achieve - update UI while working with concurrent collections using new .NET 4 parallel mechanisms. Though not ForEach but Task.

http://blogs.msdn.com/b/csharpfaq/archive/2010/06/18/parallel-programming-task-schedulers-and-synchronization-context.aspx

Title: Parallel.ForEach and ListView Control

Body:
I am having an issue getting the Parallel.ForEach to work properly. I have a listview control that loads a files contents or mutliple files contents (each file represents a log file) into a richtextbox. Had it all working with a Foreach loop but decided that the parallel operation would cut down on the loadtime when loading 100+ files.

Here is the code block I was using for the foreach loop. How do I get a Parallel.Foreach working?

//Set cursor to WaitCursor Style
this.Cursor = Cursors.WaitCursor;

//Clear Messages RichTexBox
this.rtbMessages.Clear();

//Loop through each selected file
foreach (ListViewItem Item in lvMessageFiles.Items)
{
    //Check if item is selected in the listview
    if (Item.Selected && rtbMessages.TextLength < rtbMessages.MaxLength)
    {
        //Get Path to message file
        filename = String.Format("{0}\\Data\\Log\\{1}.log", Global.AppPath, Item.SubItems[0].Text);

        //Set Timeline Events calendar to selected items created date
        cvTimeline.ShowDate(Convert.ToDateTime(lvMessageFiles.SelectedItems[0].SubItems[2].Text));

        //Check if file exists
        if (File.Exists(filename))
        {
            //streamreader to read the file
            reader = new StreamReader(filename);

            //to copy the read content in to richtextbox
            string MessageContents = String.Format("{0}\n{1}\n", ("file:///" + filename.Replace(" ", "%20").Replace("\\", "/")), reader.ReadToEnd());
            rtbMessages.Text += MessageContents;

            // closing streamreader
            reader.Close();
        }
    }

}

//Set cursor to WaitCursor Style
this.Cursor = Cursors.Default;


问:
Using MSBuild with the new csproj format
I currently got stuck into following problem:

A collegue of mine has ported one of his C# projects to the new csproj format (see http://www.natemcmaster.com/blog/2017/03/09/vs2015-to-vs2017-upgrade/ for details). Using Visual Studio 2017 building works. Unfortunately I am using MSBuild in some console application for compiling these projects too and it seems that the current MSBuild version that is shipped with Visual Studio 2017 gets into trouble when using the new "PackageReference" keyword.

Does anyone has a hint for me?

Update:

Here are some more details:

I have a console application where I am referencing some "Microsoft.Build" assemblies from "Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin". I am using the "BuildManager" for building the code. My collegue is using a lot of nuget package references which were previously defined in the "packages.config" file. This file does not exist any more ... instead all nuget references are now included in the csproj file using "<PackageReference Include=...".

When I start my console application it, I'll get the message "(...) error CS0234: The type or namespace name "CodeAnalysis" does not exist in the namespace 'Microsoft' (...)". "Microsoft.CodeAnalysis" is one of the Nuget packages my collegue is using. It seems that the BuildManager does not restore these nuget packages :(

答:
It seems that the BuildManager does not restore these nuget packages

According to the error messages:

error CS0234: The type or namespace name "CodeAnalysis" does not
  exist in the namespace

Your project may have lost those packages in the location: C:\Users\<username>\.nuget\packages, you can check if it exists.

To resolve this issue, you should open your colleague's project with Visual Studio 2017, then restore the nuget packages manually (Right click the solution->Restore NuGet Packages). That because the class of BuildManager could not be used to restore the nuget package. NuGet package restore supported by NuGet/Visual Studio.

So you should restore those nuget packages, then build it with your console application. Besides, there is a known issue about the "Microsoft.Build" assemblies 15.0. You can refer to this issue on GitHub for detail.

Hope this helps.


问:
JSON.stringify can the "null" parm prevent circular structure?
I am trying to figure out what the "null" means?

```<code>JSON.stringify(myJsonObj, null, 2)
</code>```

I see people using "undefined" or "null"

Couldn't figure out what the "null" was for so I just removed it.

```<code>JSON.stringify(myJsonObj)
</code>```

So now I start getting these

```<code>TypeError: Converting circular structure to JSON
    at JSON.stringify (<anonymous>)
</code>```

Could this be the reason?

What exactly does Null do?

答:
JSON.stringify; can take 3 parameters,
(value,replacer,space)

value is the object you want to stringify, in your case myJsonObj

replacer A function that alters the behavior of the stringification process.

space object that's used to insert white space into the output JSON string for readability purposes

in your case the myJsonObj contains circular structure which needs to be corrected in the replacer function
maybe you can get help from here:
JSON.stringify, avoid TypeError: Converting circular structure to JSON
to know how you can convert you objects within "myJsonObj".

Body:
I am trying to figure out what the "null" means?

JSON.stringify(myJsonObj, null, 2)

I see people using "undefined" or "null"

Couldn't figure out what the "null" was for so I just removed it.

JSON.stringify(myJsonObj)

So now I start getting these

TypeError: Converting circular structure to JSON
    at JSON.stringify (<anonymous>)

Could this be the reason?

What exactly does Null do?


问:
Http get response blank page
I am trying to create  light Angularjs app. I am running api server through irb cli and it is running on port 4567. When i run bundle exec ruby.rb I can confirm that there is data on the address: http://localhost:4567/api/v1/companies:

```<code>[
  {"id": "1",
   "name": "A"
  },
  {
    "id": "2",
    "name": "B",
  }
]
</code>```

I have tried with this code (hello.js):

```<code>var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
        $scope.company=[];
      $http.get("http://localhost:4567/api/v1/companies")
      /*$http.get("http://localhost/fake.json")*/
    .then(function(response) {
        $scope.company = response.data;

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

HTML:

```<code><html>
    <head>
        <title>Hello AngularJS</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
        <script src="hello.js"></script>
    </head>

        <body>
            <div ng-app="myApp" ng-controller="customersCtrl">
            <ul>
                    <li ng-repeat="x in company">
                        {{ 'name: ' + x.name + ',  id:' + x.id }}
                    </li>
            </ul>
            </div>
        </body>
    </html>
</code>```

The thing is, if I change the url to the "http://localhost/fake.json" as commented I see the data response clear. But if I use the local web server I can not see anything. Is there some kind of permissions problem or something else.

答: The problem was sinatra-access-control-allow-origin, I found the solution on: Sinatra access-control-allow-origin for sinatra public folder</p>

Title: Http get response blank page

Body:
I am trying to create  light Angularjs app. I am running api server through irb cli and it is running on port 4567. When i run bundle exec ruby.rb I can confirm that there is data on the address: http://localhost:4567/api/v1/companies:

[
  {"id": "1",
   "name": "A"
  },
  {
    "id": "2",
    "name": "B",
  }
]

I have tried with this code (hello.js):

var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
        $scope.company=[];
      $http.get("http://localhost:4567/api/v1/companies")
      /*$http.get("http://localhost/fake.json")*/
    .then(function(response) {
        $scope.company = response.data;

    });
});

HTML:

        <title>Hello AngularJS</title>

                        {{ 'name: ' + x.name + ',  id:' + x.id }}

The thing is, if I change the url to the "http://localhost/fake.json" as commented I see the data response clear. But if I use the local web server I can not see anything. Is there some kind of permissions problem or something else.