问:
Modify style of a html tag inside of a id-element
On my website I have a style like this:

#titlebar a {
  display: inline-block;
}
```

<p>and html:</p>

```

    test
    test
    test
    test

```

<p>I want to change the style of all the <code><a></code> tags in the <code><div></code> with the id <code>titlebar</code>. <code>display</code> should be changed from <code>inline-block</code> to <code>block</code>. Is this possible with JavaScript or do I have to search a different way to do this?</p>

<p>https://jsfiddle.net/Ln0a235v/2/</p>

<p><strong>Complete Context:</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// Using Gurvinder's solution.

menu = false;

function toggleMenu() {
  if (menu) {
    document.getElementById("titlebar").style.maxHeight = "4em";
    document.getElementById("fab").style.top = "calc(4em - 32px)";
    document.querySelectorAll("#titlebar a").forEach(function(el) {
      el.style.display = "inline-block";
    });
  } else {
    document.getElementById("titlebar").style.maxHeight = "500px";
    document.getElementById("fab").style.top = "0px";
    document.querySelectorAll("#titlebar a").forEach(function(el) {
      el.style.display = "block";
    });
  }
  menu = !menu;
}</code>```

body {
  background: #ffffff;
  font-family: sans-serif;
}

#titlebar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #3f51b5;
  min-height: 4em;
  max-height: 4em;
  box-shadow: 0px 4px 8px #757575;
  transition: max-height 0.3s;
}

#titlebar a {
  font-variant: small-caps;
  line-height: 4em;
  display: inline-block;
  padding: 0px 16px;
  margin: 0px;
  color: #ffffff;
  text-decoration: none;
  transition: background 0.2s, display 1s;
  outline: none;
}

#titlebar a:hover {
  background: #ff4081;
}

#fab {
  position: fixed;
  width: 64px;
  height: 64px;
  z-index: 100;
  /*right: 64px;*/
  right: 3%;
  top: calc(4em - 32px);
  transition: top 0.3s;
}

.main {
  box-shadow: 0px 4px 8px #757575;
  width: 80%;
  margin: 0 auto;
  margin-bottom: 64px;
}

.content {
  padding: 6em 0;
  margin: 0 10%;
}

hr {
  border: 1px solid #c5cae9;
}

.content img {
  float: right;
  margin-left: 32px;
  margin-bottom: 32px;
  width: 30%;
  min-width: 256px;
  box-shadow: 0px 4px 8px #757575;
  padding: 8px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="titlebar">
  <nav>
    ToggleMenu
    test
    test
    test
  </nav>
</div>

<div class="main">
  <div class="content">
    <h1>Lorem ipsum</h1>
    <p>
      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
      sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
      rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
      At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore
      eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
      euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate
      velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis
      eleifend option congue nihil imperdiet doming id quod mazim placerat facer
    </p>
    <hr/>
    <h1>Lorem ipsum</h1>
    <p>
      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
      sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
      rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
      At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore
      eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
      euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate
      velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis
      eleifend option congue nihil imperdiet doming id quod mazim placerat facer
    </p>
  </div>
</div></code>```

答:
Iterate over each control and set the display to block

```<code>var ctrls = document.getElementById("titlebar").getElementsByTagName("a");
for (var i = 0; i < ctrls.length; i++)
  ctrls[i].style.display = "block";
</code>```

You can check the fiddle at here

Do not know the context, so as you asked giving you the javascript suggestion but it can also be done using css

Body:
On my website I have a style like this:

#titlebar a {
  display: inline-block;
}

and html:

    test
    test
    test
    test

I want to change the style of all the  tags in the
 with the id titlebar. display should be changed from inline-block to block. Is this possible with JavaScript or do I have to search a different way to do this?

https://jsfiddle.net/Ln0a235v/2/

Complete Context:

// Using Gurvinder's solution.

menu = false;

function toggleMenu() {
  if (menu) {
    document.getElementById("titlebar").style.maxHeight = "4em";
    document.getElementById("fab").style.top = "calc(4em - 32px)";
    document.querySelectorAll("#titlebar a").forEach(function(el) {
      el.style.display = "inline-block";
    });
  } else {
    document.getElementById("titlebar").style.maxHeight = "500px";
    document.getElementById("fab").style.top = "0px";
    document.querySelectorAll("#titlebar a").forEach(function(el) {
      el.style.display = "block";
    });
  }
  menu = !menu;
}

body {
  background: #ffffff;
  font-family: sans-serif;
}

#titlebar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #3f51b5;
  min-height: 4em;
  max-height: 4em;
  box-shadow: 0px 4px 8px #757575;
  transition: max-height 0.3s;
}

#titlebar a {
  font-variant: small-caps;
  line-height: 4em;
  display: inline-block;
  padding: 0px 16px;
  margin: 0px;
  color: #ffffff;
  text-decoration: none;
  transition: background 0.2s, display 1s;
  outline: none;
}

#titlebar a:hover {
  background: #ff4081;
}

#fab {
  position: fixed;
  width: 64px;
  height: 64px;
  z-index: 100;
  /*right: 64px;*/
  right: 3%;
  top: calc(4em - 32px);
  transition: top 0.3s;
}

.main {
  box-shadow: 0px 4px 8px #757575;
  width: 80%;
  margin: 0 auto;
  margin-bottom: 64px;
}

.content {
  padding: 6em 0;
  margin: 0 10%;
}

hr {
  border: 1px solid #c5cae9;
}

.content img {
  float: right;
  margin-left: 32px;
  margin-bottom: 32px;
  width: 30%;
  min-width: 256px;
  box-shadow: 0px 4px 8px #757575;
  padding: 8px;
}

    ToggleMenu
    test
    test
    test

Lorem ipsum

      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
      sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
      rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
      At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore
      eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
      euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate
      velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis
      eleifend option congue nihil imperdiet doming id quod mazim placerat facer

Lorem ipsum

      Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata
      sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea
      rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
      At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore
      eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh
      euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate
      velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis
      eleifend option congue nihil imperdiet doming id quod mazim placerat facer

Body:
Iterate over each control and set the display to block

var ctrls = document.getElementById("titlebar").getElementsByTagName("a");
for (var i = 0; i < ctrls.length; i++)
  ctrls[i].style.display = "block";

You can check the fiddle at here

Do not know the context, so as you asked giving you the javascript suggestion but it can also be done using css


来源: stackexchange

问:
Date range Query in kibana 5.6.3 not working with @timestamp
mapping:

```<code>  "mappings": {
                "test-engine": {
                  "properties": {
                    "@timestamp": {
                      "type": "date"
                    } ....
             },
</code>```

sample record:

```<code>     {
    "_index": "application-log",
    "_type": "test-engine",
    "_id": "AV9pKiMHlm36MlYWarx3",
    "_score": 1,
    "_source": {
      "@timestamp": "2017-10-29T17:24:50.026+0000",
      "message": "Initialize connection to node -1 for sending metadata request",
      "host": "54.205.134.57",
      "severity": "DEBUG",
      "thread": "Thread-4",
      "logger": "org.apache.kafka.clients.NetworkClient"
    }
</code>```

the query which I have tried:

```<code>     GET application-log/_mapping
     {
      "range": {
        "@timestamp": {
          "gte": "2017-10-26T17:24:50.026+0000",
          "lte": "2017-10-28T17:24:50.026+0000"
        }
      }
    }
</code>```

I tried the query with above mappings and records still the date range is not working in kibana

答:
You need to use the _search endpoint no the _mapping one and wrap the range query inside a query section

```<code> GET application-log/_search
 {
   "query": {
     "range": {
       "@timestamp": {
         "gte": "2017-10-26T17:24:50.026+0000",
         "lte": "2017-10-28T17:24:50.026+0000"
       }
     }
   }
 }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
mapping:

  "mappings": {
                "test-engine": {
                  "properties": {
                    "@timestamp": {
                      "type": "date"
                    } ....
             },

sample record:

     {
    "_index": "application-log",
    "_type": "test-engine",
    "_id": "AV9pKiMHlm36MlYWarx3",
    "_score": 1,
    "_source": {
      "@timestamp": "2017-10-29T17:24:50.026+0000",
      "message": "Initialize connection to node -1 for sending metadata request",
      "host": "54.205.134.57",
      "severity": "DEBUG",
      "thread": "Thread-4",
      "logger": "org.apache.kafka.clients.NetworkClient"
    }

the query which I have tried:

     GET application-log/_mapping
     {
      "range": {
        "@timestamp": {
          "gte": "2017-10-26T17:24:50.026+0000",
          "lte": "2017-10-28T17:24:50.026+0000"
        }
      }
    }

I tried the query with above mappings and records still the date range is not working in kibana

Body:
You need to use the _search endpoint no the _mapping one and wrap the range query inside a query section

 GET application-log/_search
 {
   "query": {
     "range": {
       "@timestamp": {
         "gte": "2017-10-26T17:24:50.026+0000",
         "lte": "2017-10-28T17:24:50.026+0000"
       }
     }
   }
 }

ContentLicense: CC BY-SA 3.0


问:
Finding string in file with batch and call other batch
I am on a need to finde if an output log ends with a desired string, and call another batch if it does.

I have already tried some solutions at StackOverflow but it is still not working.

```<code>title Validate daily execution

findstr /C: "Exiting with code 0" .\logs\20171116.log
if %errorlevel%==0 (
BBBB
CALL  AutoLogEmail
) else (
AAAAAAAa

)
</code>```

And the file that I am looking for in a sub folder, with the name above has the values

16-11-2017  6:50:00,75 START PROCESS XXXXXXX.ISPAC Microsoft (R) SQL
  Server Execute Package Utility Version 11.0.2100.60 for 64-bit
  Copyright (C) Microsoft Corporation. All rights reserved.

Started:  06:50:00 DTExec: The package execution returned
  DTSER_SUCCESS (0). Started:  06:50:00 Finished: 06:52:03 Elapsed:
  122.929 seconds 16-11-2017  6:52:04,00 END PROCESS XXXXXXXX.ISPAC : Exiting with code 0

Is there any especific function that I shall use? Can someone point me the error and explain why it is not working?

Thanks in advance
Helder

答:
The Space between /c: and the string in your findstr command is your problem.

With that Space in the place indicated, findstr will generate a syntax-error message and set errorlevel to 2.

Remove it and findstr will attempt to find the string in the file.

Body:
I am on a need to finde if an output log ends with a desired string, and call another batch if it does.

I have already tried some solutions at StackOverflow but it is still not working.

title Validate daily execution

findstr /C: "Exiting with code 0" .\logs\20171116.log
if %errorlevel%==0 (
BBBB
CALL  AutoLogEmail
) else (
AAAAAAAa

)

And the file that I am looking for in a sub folder, with the name above has the values

16-11-2017  6:50:00,75 START PROCESS XXXXXXX.ISPAC Microsoft (R) SQL
  Server Execute Package Utility Version 11.0.2100.60 for 64-bit
  Copyright (C) Microsoft Corporation. All rights reserved.

Started:  06:50:00 DTExec: The package execution returned
  DTSER_SUCCESS (0). Started:  06:50:00 Finished: 06:52:03 Elapsed:
  122.929 seconds 16-11-2017  6:52:04,00 END PROCESS XXXXXXXX.ISPAC : Exiting with code 0

Is there any especific function that I shall use? Can someone point me the error and explain why it is not working?

Thanks in advance
Helder


问:
SWI Prolog backtracking behavior after `read/1` call
I was looking at another Prolog question on StackOverflow and encountered this situation.

Suppose I have the following facts:

```<code>foo(1).
foo(2).
foo(3).
foo(4).
</code>```

At the SWI Prolog (version 7.4.2) prompt, I exercised this:

```<code>2 ?- write('Enter number: '), read(X), nl, foo(Y), Y > X.
Enter number: 1.

X = 1,
Y = 2.

3 ?-
</code>```

As you can see, SWI Prolog provides one solution with no prompt for additional solutions (which do exist). It does not backtrack.

In GNU Prolog (version 1.4.4), the behavior is more what I would expect:

```<code>| ?- write('Enter number: '), read(X), nl, foo(Y), Y > X.
Enter number: 1.

X = 1
Y = 2 ? ;

X = 1
Y = 3 ? ;

X = 1
Y = 4

yes
| ?-
</code>```

Thanks to @trivelt for a reduction of the problem to simply:

```<code>?- foo(X).           % Backtracks and finds all solutions for X
?- read(_), foo(X).  % Does not backtrack and finds only one solution for X
</code>```

Is this a bug in the SWI version 7.4.2 implementation? Or are these alternative acceptable/expected behaviors?

答:
At the very least, I would regard it as a severe deficit of the SWI toplevel that an interaction with a program may interfere in this unexpected way with the toplevel control.

In SWI-Prolog, this is filed as issue #166:

Using read/1 on the toplevel commits unexpectedly

This shortcoming of the SWI toplevel prevents users to see all solutions in many cases of practical relevance.

Since ECLiPSe has already fixed this issue, maybe someone will fix it in SWI too at some point.

Body:
I was looking at another Prolog question on StackOverflow and encountered this situation.

Suppose I have the following facts:

foo(1).
foo(2).
foo(3).
foo(4).

At the SWI Prolog (version 7.4.2) prompt, I exercised this:

2 ?- write('Enter number: '), read(X), nl, foo(Y), Y > X.
Enter number: 1.

X = 1,
Y = 2.

3 ?-

As you can see, SWI Prolog provides one solution with no prompt for additional solutions (which do exist). It does not backtrack.

In GNU Prolog (version 1.4.4), the behavior is more what I would expect:

| ?- write('Enter number: '), read(X), nl, foo(Y), Y > X.
Enter number: 1.

X = 1
Y = 2 ? ;

X = 1
Y = 3 ? ;

X = 1
Y = 4

yes
| ?-

Thanks to @trivelt for a reduction of the problem to simply:

?- foo(X).           % Backtracks and finds all solutions for X
?- read(_), foo(X).  % Does not backtrack and finds only one solution for X

Is this a bug in the SWI version 7.4.2 implementation? Or are these alternative acceptable/expected behaviors?


问:
Resume file transfer for a half way failed file transfer
I am using this jsch library ( http://www.jcraft.com/jsch/ )in my ColdFusion application. My application wants to implement a retry mechanism - if a file transfer fails half way through then I want to resume (or continue) the file transfer from where it left off. Is this possible to achieve using this jsch library?</p>

答:
Just reconnect and start an upload again with RESUME flag:

```<code>channelSftp.put(src, dst, ChannelSftp.RESUME);
</code>```

The RESUME flag will make JSch query size of a partial remote file and restart the transfer from there. If the file is already uploaded completely, it transfers nothing.

Body:
Just reconnect and start an upload again with RESUME flag:

channelSftp.put(src, dst, ChannelSftp.RESUME);

The RESUME flag will make JSch query size of a partial remote file and restart the transfer from there. If the file is already uploaded completely, it transfers nothing.


问:
mule/java - reading a property file which is inside of jar dependency from java class
Here my requirement is, I have created one mule application which has java class. Some of the values which I don't want to keep it as a hard-coded so I am trying to externalize it. I kept this values in mule-app.properties file and used FileInputStream as below.

```<code>String propFileName = "src/main/app/mule-app.properties"
Properties property = new Properties();
property.load(new FileInputStream(propFileName));
</code>```

But this code needs to be deployed on CloudHub; there its failing saying that file not found. I Tried with give path of the file name as

```<code>String propFileName = "target/classes/mule-app.properties"
</code>```

for both the cases its running fine locally but gives same results on CloudHub as "File Not Found".

What could be the solution?

Another thing is I have a common code in which we are keeping all the properties related to different environment. Packaging of this common code is in the form of jar. So, can I keep properties which I am using in above code and read it from jar itself.

If Yes, then How?

答:
To achieve this we can do one thing. Using expression component set variable for each property you want to fetch.

```<code><expression-component doc:name="setVariable"><![CDATA[flowVars.clientId="${poc.clientId}";]]></expression-component>
</code>```

This flow Variable is accessible in Java class irrespective of where it is been kept i.e. mule-app.properties or on cloudhub run time properties.

In Java class, using below code we can read this Flow Variable.

```<code>String clientId = eventContext.getMessage().getInvocationProperty("clientId");
</code>```

Body:
Here my requirement is, I have created one mule application which has java class. Some of the values which I don't want to keep it as a hard-coded so I am trying to externalize it. I kept this values in mule-app.properties file and used FileInputStream as below.

String propFileName = "src/main/app/mule-app.properties"
Properties property = new Properties();
property.load(new FileInputStream(propFileName));

But this code needs to be deployed on CloudHub; there its failing saying that file not found. I Tried with give path of the file name as

String propFileName = "target/classes/mule-app.properties"

for both the cases its running fine locally but gives same results on CloudHub as "File Not Found".

What could be the solution?

Another thing is I have a common code in which we are keeping all the properties related to different environment. Packaging of this common code is in the form of jar. So, can I keep properties which I am using in above code and read it from jar itself.

If Yes, then How?

Body:
To achieve this we can do one thing. Using expression component set variable for each property you want to fetch.

<expression-component doc:name="setVariable"><![CDATA[flowVars.clientId="${poc.clientId}";]]></expression-component>

This flow Variable is accessible in Java class irrespective of where it is been kept i.e. mule-app.properties or on cloudhub run time properties.

In Java class, using below code we can read this Flow Variable.

String clientId = eventContext.getMessage().getInvocationProperty("clientId");


问:
Checkbox onclick in knockout is not updating viewmodel
I have list of check boxes, on click of any checkbox i need to get all checked check boxes. To do that I am calling the java script function "ChangeColumnSelection".

The issue is, the clicked check box is not updating view model immediately. When i click next text box, I am seeing that the previously check box value got updated in the view model.

```<code> <ul class="list-group" data-bind="foreach: SelectionColumnList">
      <li class="list-group-item">
          <input type="checkbox" data-bind="attr: {onclick: 'javascript:ChangeColumnSelection(\'' + ColumnID + '\')'}, checked: IsSelected"
                        class="pull-xs-left push-down rightmargin" />
          <span data-bind="text: ColumnName"></span>
     </li>
 </ul>
</code>```

Update:

My view model is

```<code>  var dynamicGridViewModel = {
        SelectionColumnList: ko.observableArray([])
   };

    selectionInfo.ColumnID = columnInfo.ColumnID;
    selectionInfo.ColumnName = columnInfo.ColumnName;
    selectionInfo.DisplayOrder = columnInfo.DisplayOrder;
    selectionInfo.SortType = 'None';
    selectionInfo.IsSelected = true;
    dynamicGridViewModel.SelectionColumnList.push(selectionInfo);
</code>```

答:
You don't need onclick events. You can achieve this just with checked binding:

var array = [{
  ColumnID: 1,
  ColumnName: "ColumnName 1"
}, {
  ColumnID: 2,
  ColumnName: "ColumnName 2"
}]

var viewModel = function() {
  var self = this;
  self.SelectionColumnList = ko.observableArray(array);

  // no need to populate the array manually. Knockout will take care of it
  self.chosenItems = ko.observableArray();

  // every time chosenItems array changes, subscribe callback function gets triggered
  self.chosenItems.subscribe(function() {
    console.log(self.chosenItems());
  })
}

ko.applyBindings(new viewModel());```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<ul class="list-group" data-bind="foreach: SelectionColumnList">
  <li class="list-group-item">
    <input type="checkbox" data-bind="checkedValue: ColumnID, checked: $parent.chosenItems" />
    <span data-bind="text: ColumnName"></span>
  </li>
</ul></code>```

Here, ColumnId is set as the value of checkbox input. Hence, the chosenItems array will be an array of selected ColumnIds.

The great thing about Knockout is that, it allows not only primitive types like string, number or bool for checkedValue, but objects too. If you want the entire Column object to be populated in chosenItems, then you can set the checkedValue like this:

```<code><input type="checkbox" data-bind="checkedValue: $data, checked: $parent.chosenItems" />
</code>```

If you want to perform some operation upon changing of any checkbox's state, you can perform that inside the subscribe callback. This function gets triggered every time the array changes.

(Also, the proper way to add a click binding is data-bind="click: clickFunction")

UPDATE:

You're using an object literal as your viewModel. I suggest you create viewModel function and use the new operator. If you want to bind checked to a boolean property of Column, then you can create a computed property and subscribe to that computed property:

var columns = [{
  ColumnID: 1,
  ColumnName: "ColumnName 1",
  IsSelected: false
}, {
  ColumnID: 2,
  ColumnName: "ColumnName 2",
  IsSelected: true
}];

var viewModel = function() {
  var self = this;
  self.SelectionColumnList = ko.observableArray([]);

  // this property has the selected ColumnIds
  self.selectedItems = ko.computed(() => {
    // If you're using ES6 systax
    // return self.SelectionColumnList()
    //  .filter(column => column.IsSelected())
    //   .map(column => column.ColumnID);

    // out of the columns, get the ColumnIds with IsSelected as true
    return self.SelectionColumnList()
      .filter(function(column) {
        return column.IsSelected();
      })
      .map(function(column) {
        return column.ColumnID
      });
  });

  // gets triggered everytime checkbox is checked/unchecked
  self.selectedItems.subscribe(function() {
    console.log(self.selectedItems());
  });
}

// create a new instance of the viewmodel
var dynamicGridViewModel = new viewModel();

// loop through the columns and populate the observableArray
columns.forEach(function(columnInfo) {
  var selectionInfo = {};

  selectionInfo.ColumnID = columnInfo.ColumnID;
  selectionInfo.ColumnName = columnInfo.ColumnName;

  // this property must be an observable
  selectionInfo.IsSelected = ko.observable(columnInfo.IsSelected);

  dynamicGridViewModel.SelectionColumnList.push(selectionInfo);
})

ko.applyBindings(dynamicGridViewModel);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<ul class="list-group" data-bind="foreach: SelectionColumnList">
  <li class="list-group-item">
    <input type="checkbox" data-bind="checked: IsSelected" />
    <span data-bind="text: ColumnName"></span>
  </li>
</ul></code>```

Here's a fiddle for testing

Body:
I have list of check boxes, on click of any checkbox i need to get all checked check boxes. To do that I am calling the java script function "ChangeColumnSelection".

The issue is, the clicked check box is not updating view model immediately. When i click next text box, I am seeing that the previously check box value got updated in the view model.

          <input type="checkbox" data-bind="attr: {onclick: 'javascript:ChangeColumnSelection(\'' + ColumnID + '\')'}, checked: IsSelected"
                        class="pull-xs-left push-down rightmargin" />

Update:

My view model is

  var dynamicGridViewModel = {
        SelectionColumnList: ko.observableArray([])
   };

    selectionInfo.ColumnID = columnInfo.ColumnID;
    selectionInfo.ColumnName = columnInfo.ColumnName;
    selectionInfo.DisplayOrder = columnInfo.DisplayOrder;
    selectionInfo.SortType = 'None';
    selectionInfo.IsSelected = true;
    dynamicGridViewModel.SelectionColumnList.push(selectionInfo);

Body:
You don't need onclick events. You can achieve this just with checked binding:

var array = [{
  ColumnID: 1,
  ColumnName: "ColumnName 1"
}, {
  ColumnID: 2,
  ColumnName: "ColumnName 2"
}]

var viewModel = function() {
  var self = this;
  self.SelectionColumnList = ko.observableArray(array);

  // no need to populate the array manually. Knockout will take care of it
  self.chosenItems = ko.observableArray();

  // every time chosenItems array changes, subscribe callback function gets triggered
  self.chosenItems.subscribe(function() {
    console.log(self.chosenItems());
  })
}

ko.applyBindings(new viewModel());

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<ul class="list-group" data-bind="foreach: SelectionColumnList">
  <li class="list-group-item">
    <input type="checkbox" data-bind="checkedValue: ColumnID, checked: $parent.chosenItems" />
    <span data-bind="text: ColumnName"></span>
  </li>
</ul>

Here, ColumnId is set as the value of checkbox input. Hence, the chosenItems array will be an array of selected ColumnIds.

The great thing about Knockout is that, it allows not only primitive types like string, number or bool for checkedValue, but objects too. If you want the entire Column object to be populated in chosenItems, then you can set the checkedValue like this:

<input type="checkbox" data-bind="checkedValue: $data, checked: $parent.chosenItems" />

If you want to perform some operation upon changing of any checkbox's state, you can perform that inside the subscribe callback. This function gets triggered every time the array changes.

(Also, the proper way to add a click binding is data-bind="click: clickFunction")

UPDATE:

You're using an object literal as your viewModel. I suggest you create viewModel function and use the new operator. If you want to bind checked to a boolean property of Column, then you can create a computed property and subscribe to that computed property:

var columns = [{
  ColumnID: 1,
  ColumnName: "ColumnName 1",
  IsSelected: false
}, {
  ColumnID: 2,
  ColumnName: "ColumnName 2",
  IsSelected: true
}];

var viewModel = function() {
  var self = this;
  self.SelectionColumnList = ko.observableArray([]);

  // this property has the selected ColumnIds
  self.selectedItems = ko.computed(() => {
    // If you're using ES6 systax
    // return self.SelectionColumnList()
    //  .filter(column => column.IsSelected())
    //   .map(column => column.ColumnID);

    // out of the columns, get the ColumnIds with IsSelected as true
    return self.SelectionColumnList()
      .filter(function(column) {
        return column.IsSelected();
      })
      .map(function(column) {
        return column.ColumnID
      });
  });

  // gets triggered everytime checkbox is checked/unchecked
  self.selectedItems.subscribe(function() {
    console.log(self.selectedItems());
  });
}

// create a new instance of the viewmodel
var dynamicGridViewModel = new viewModel();

// loop through the columns and populate the observableArray
columns.forEach(function(columnInfo) {
  var selectionInfo = {};

  selectionInfo.ColumnID = columnInfo.ColumnID;
  selectionInfo.ColumnName = columnInfo.ColumnName;

  // this property must be an observable
  selectionInfo.IsSelected = ko.observable(columnInfo.IsSelected);

  dynamicGridViewModel.SelectionColumnList.push(selectionInfo);
})

ko.applyBindings(dynamicGridViewModel);

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<ul class="list-group" data-bind="foreach: SelectionColumnList">
  <li class="list-group-item">
    <input type="checkbox" data-bind="checked: IsSelected" />
    <span data-bind="text: ColumnName"></span>
  </li>
</ul>

Here's a fiddle for testing


问:
Possible to get latest data with observeSingleEvent + persistence enabled?
I am trying to get some data from firebase. Any idea how can I get the latest data (not from cache) when I have persistence enabled? I tried keepSynced; I still get stale data. Is this the correct usage?

```<code>userRef = FIRDatabase.database().reference().child("<path>")
userRef.keepSynced(true)
userRef.observeSingleEvent(of: .value, with: { snapshot in
   ...stale data here...
})
</code>```

Or the only option is to use observe instead of observeSingleEvent? I don't like the fact that with observe I get the cache data first, and then the event triggers a second time with data from the server. So with observe, when I navigate to this screen, first I see a blank table, then I see the table with stale data, and then I see the table with latest data.

Thanks.

EDIT:

https://stackoverflow.com/a/34487195/1373592 -
This post says keeySynced should work. But it's not working for me. I would like to know if I am doing something wrong.

答:
I retrieve some explanation, I think it might help you in your case :

ObserveSingleEventType with keepSycned will not work if the Firebase
  connection cannot be established on time. This is especially true
  during appLaunch or in the appDelegate where there is a delay in the
  Firebase connection and the cached result is given instead. It will
  also not work at times if persistence is enabled and
  observeSingleEvent might give the cached data first. In situations
  like these, a continuous ObserveEventType is preferred and should be
  used if you absolutely need fresh data.

I think you don't have the choice to use a continuous listener. But to avoid performance issues why you don't remove yourself your listeners when you don't it anymore.

Body:
I am trying to get some data from firebase. Any idea how can I get the latest data (not from cache) when I have persistence enabled? I tried keepSynced; I still get stale data. Is this the correct usage?

userRef = FIRDatabase.database().reference().child("<path>")
userRef.keepSynced(true)
userRef.observeSingleEvent(of: .value, with: { snapshot in
   ...stale data here...
})

Or the only option is to use observe instead of observeSingleEvent? I don't like the fact that with observe I get the cache data first, and then the event triggers a second time with data from the server. So with observe, when I navigate to this screen, first I see a blank table, then I see the table with stale data, and then I see the table with latest data.

Thanks.

EDIT:

https://stackoverflow.com/a/34487195/1373592 -
This post says keeySynced should work. But it's not working for me. I would like to know if I am doing something wrong.


答:
You can simply have a correlated sub-query that calculates the tbl2 sum:</p>

```<code>select tbl1.name,
       SUM(tbl1.total),
       SUM(COALESCE((select SUM(tbl2.qty)
                     from tbl2
                     where tbl1.id = tbl2.id), 0)) as qty_tot
from tbl1
GROUP by tbl1.name
</code>```

Title: SQL - How can I JOIN two tables and SUM a column based on IDs between them?

Body:
I have two tables. One table is with master data

Table tbl1:

+-------------+------------+------------+
| ID          | Name       | Total      |
+-------------+------------+------------+
| 1           | a          | 10         |
| 2           | b          | 5          |
| 3           | c          | 4          |
| 4           | a          | 4          |
+-------------+------------+------------+

Second table tbl2 contains child data. The key between tables is ID

Table tbl2:

+-------------+------------+
|id           | qty        |
+-------------+------------+
| 1           | 4          |
| 1           | 3          |
| 1           | 1          |
| 3           | 1          |
| 3           | 3          |
+-------------+------------+

I need to get output like this:

Output:

+-------------+------------+------------+
| name        | sum_tot    | sum_qty    |
+-------------+------------+------------+
| a           | 14         | 8          |
| b           | 5          | 0          |
| c           | 4          | 4          |
+-------------+------------+------------+

I had tried with this:

select tbl1.name, SUM(tbl1.total), SUM(tbl2.qty)
from tbl1
left join tbl2 ON tbl1.id = tbl2.id
GROUP by tbl1.name

The output that I get is:

Output:

+-------------+------------+------------+
| name        | sum_tot    | sum_qty    |
+-------------+------------+------------+
| a           | 34         | 8          |
| b           | 5          |null        |
| c           | 8          | 4          |
+-------------+------------+------------+

Which is not correct.

Here is the sql fiddle:

The summary from first table is not in relation with second table. It seems that somehow query runs three times.

Body:
You can simply have a correlated sub-query that calculates the tbl2 sum:

select tbl1.name,
       SUM(tbl1.total),
       SUM(COALESCE((select SUM(tbl2.qty)
                     from tbl2
                     where tbl1.id = tbl2.id), 0)) as qty_tot
from tbl1
GROUP by tbl1.name


问:
Launch share intent on Onesignal notification action button click
I am able to successfully send notifications in onesignal. All of the features are working fine. But today when I tried to implement action buttons to the notifications, its not working. I tried to add an action button with id "ActionOne", on click of this action button below notification, it should start a share intent to share the text which i want. But each time I do that the app crashes. However when I tried to add a simple toast to another action button with id "ActionTwo", it worked. Please help me out of this. Here is the code -

```<code>public class MyNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
    @Override
    public void notificationOpened(OSNotificationOpenResult result) {
        OSNotificationAction.ActionType actionType = result.action.type;
        JSONObject data = result.notification.payload.additionalData;
        String open;

    if (data != null) {
        open = data.optString("open", null);

        if (open != null && open.equals("activitytwo")) {
            Log.i("OneSignalExample", "customkey set with value: " + open);
            Intent intent = new Intent(MyApplication.getContext(), Activitytwo.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
            MyApplication.getContext().startActivity(intent);
        } else {
            Intent intent = new Intent(MyApplication.getContext(), MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
            MyApplication.getContext().startActivity(intent);
        }

    }

    if (actionType == OSNotificationAction.ActionType.ActionTaken){
        Log.i("OneSignalExample", "Button pressed with id: " + result.action.actionID);

        if (result.action.actionID.equals("ActionOne")) {

            Intent sharingIntent = new Intent(Intent.ACTION_SEND);
            sharingIntent.setType("text/plain");
            String shareBodyText = "hello";
            sharingIntent.putExtra(Intent.EXTRA_SUBJECT,"");
            sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBodyText);
            MyApplication.getContext().startActivity(Intent.createChooser(sharingIntent, "Share via"));

        }else if (result.action.actionID.equals("ActionTwo")) {
            Toast.makeText(MyApplication.getContext(), "ActionTwo Button was pressed", Toast.LENGTH_LONG).show();
        }
      }
   }
}
</code>```

Here is the logcat when notification is received -

```<code>11-16 18:57:47.266 26067-26067/com.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
                                                             Process: com.myapplication, PID: 26067
                                                             java.lang.RuntimeException: Unable to start receiver com.onesignal.NotificationOpenedReceiver: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
                                                                 at android.app.ActivityThread.handleReceiver(ActivityThread.java:2851)
                                                                 at android.app.ActivityThread.access$1700(ActivityThread.java:178)
                                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1547)
                                                                 at android.os.Handler.dispatchMessage(Handler.java:111)
                                                                 at android.os.Looper.loop(Looper.java:194)
                                                                 at android.app.ActivityThread.main(ActivityThread.java:5653)
                                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                                 at java.lang.reflect.Method.invoke(Method.java:372)
                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                                                              Caused by: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
                                                                 at android.app.ContextImpl.startActivity(ContextImpl.java:1372)
                                                                 at android.app.ContextImpl.startActivity(ContextImpl.java:1359)
                                                                 at android.content.ContextWrapper.startActivity(ContextWrapper.java:323)
                                                                 at com.myapplication.MyNotificationOpenedHandler.notificationOpened(MyNotificationOpenedHandler.java:52)
                                                                 at com.onesignal.OneSignal$15.run(OneSignal.java:1486)
                                                                 at com.onesignal.OSUtils.runOnMainUIThread(OSUtils.java:204)
                                                                 at com.onesignal.OneSignal.fireNotificationOpenedHandler(OneSignal.java:1483)
                                                                 at com.onesignal.OneSignal.runNotificationOpenedCallback(OneSignal.java:1432)
                                                                 at com.onesignal.OneSignal.handleNotificationOpen(OneSignal.java:1519)
                                                                 at com.onesignal.NotificationOpenedProcessor.processIntent(NotificationOpenedProcessor.java:116)
                                                                 at com.onesignal.NotificationOpenedProcessor.processFromContext(NotificationOpenedProcessor.java:51)
                                                                 at com.onesignal.NotificationOpenedReceiver.onReceive(NotificationOpenedReceiver.java:38)
                                                                 at android.app.ActivityThread.handleReceiver(ActivityThread.java:2844)
                                                                 at android.app.ActivityThread.access$1700(ActivityThread.java:178)
                                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1547)
                                                                 at android.os.Handler.dispatchMessage(Handler.java:111)
                                                                 at android.os.Looper.loop(Looper.java:194)
                                                                 at android.app.ActivityThread.main(ActivityThread.java:5653)
                                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                                 at java.lang.reflect.Method.invoke(Method.java:372)
                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
</code>```

答:
Finally after a lot of struggle i got the solution :)

Here's the final code of sharing intent -

```<code>Log.i("OneSignalExample", "button id called: " + result.action.actionID);
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBodyText = "hello";
sharingIntent.setFlags(FLAG_ACTIVITY_NEW_TASK);
sharingIntent.putExtra(Intent.EXTRA_SUBJECT,"share");
sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBodyText);
Intent share = Intent.createChooser(sharingIntent, "share via");
share.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MyApplication.getContext().startActivity(share);
</code>```

Body:
I am able to successfully send notifications in onesignal. All of the features are working fine. But today when I tried to implement action buttons to the notifications, its not working. I tried to add an action button with id "ActionOne", on click of this action button below notification, it should start a share intent to share the text which i want. But each time I do that the app crashes. However when I tried to add a simple toast to another action button with id "ActionTwo", it worked. Please help me out of this. Here is the code -

public class MyNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
    @Override
    public void notificationOpened(OSNotificationOpenResult result) {
        OSNotificationAction.ActionType actionType = result.action.type;
        JSONObject data = result.notification.payload.additionalData;
        String open;

    if (data != null) {
        open = data.optString("open", null);

        if (open != null && open.equals("activitytwo")) {
            Log.i("OneSignalExample", "customkey set with value: " + open);
            Intent intent = new Intent(MyApplication.getContext(), Activitytwo.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
            MyApplication.getContext().startActivity(intent);
        } else {
            Intent intent = new Intent(MyApplication.getContext(), MainActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
            MyApplication.getContext().startActivity(intent);
        }

    }

    if (actionType == OSNotificationAction.ActionType.ActionTaken){
        Log.i("OneSignalExample", "Button pressed with id: " + result.action.actionID);

        if (result.action.actionID.equals("ActionOne")) {

            Intent sharingIntent = new Intent(Intent.ACTION_SEND);
            sharingIntent.setType("text/plain");
            String shareBodyText = "hello";
            sharingIntent.putExtra(Intent.EXTRA_SUBJECT,"");
            sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBodyText);
            MyApplication.getContext().startActivity(Intent.createChooser(sharingIntent, "Share via"));

        }else if (result.action.actionID.equals("ActionTwo")) {
            Toast.makeText(MyApplication.getContext(), "ActionTwo Button was pressed", Toast.LENGTH_LONG).show();
        }
      }
   }
}

Here is the logcat when notification is received -

11-16 18:57:47.266 26067-26067/com.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
                                                             Process: com.myapplication, PID: 26067
                                                             java.lang.RuntimeException: Unable to start receiver com.onesignal.NotificationOpenedReceiver: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
                                                                 at android.app.ActivityThread.handleReceiver(ActivityThread.java:2851)
                                                                 at android.app.ActivityThread.access$1700(ActivityThread.java:178)
                                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1547)
                                                                 at android.os.Handler.dispatchMessage(Handler.java:111)
                                                                 at android.os.Looper.loop(Looper.java:194)
                                                                 at android.app.ActivityThread.main(ActivityThread.java:5653)
                                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                                 at java.lang.reflect.Method.invoke(Method.java:372)
                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                                                              Caused by: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity  context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
                                                                 at android.app.ContextImpl.startActivity(ContextImpl.java:1372)
                                                                 at android.app.ContextImpl.startActivity(ContextImpl.java:1359)
                                                                 at android.content.ContextWrapper.startActivity(ContextWrapper.java:323)
                                                                 at com.myapplication.MyNotificationOpenedHandler.notificationOpened(MyNotificationOpenedHandler.java:52)
                                                                 at com.onesignal.OneSignal$15.run(OneSignal.java:1486)
                                                                 at com.onesignal.OSUtils.runOnMainUIThread(OSUtils.java:204)
                                                                 at com.onesignal.OneSignal.fireNotificationOpenedHandler(OneSignal.java:1483)
                                                                 at com.onesignal.OneSignal.runNotificationOpenedCallback(OneSignal.java:1432)
                                                                 at com.onesignal.OneSignal.handleNotificationOpen(OneSignal.java:1519)
                                                                 at com.onesignal.NotificationOpenedProcessor.processIntent(NotificationOpenedProcessor.java:116)
                                                                 at com.onesignal.NotificationOpenedProcessor.processFromContext(NotificationOpenedProcessor.java:51)
                                                                 at com.onesignal.NotificationOpenedReceiver.onReceive(NotificationOpenedReceiver.java:38)
                                                                 at android.app.ActivityThread.handleReceiver(ActivityThread.java:2844)
                                                                 at android.app.ActivityThread.access$1700(ActivityThread.java:178)
                                                                 at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1547)
                                                                 at android.os.Handler.dispatchMessage(Handler.java:111)
                                                                 at android.os.Looper.loop(Looper.java:194)
                                                                 at android.app.ActivityThread.main(ActivityThread.java:5653)
                                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                                 at java.lang.reflect.Method.invoke(Method.java:372)
                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

Body:
Finally after a lot of struggle i got the solution :)

Here's the final code of sharing intent -

Log.i("OneSignalExample", "button id called: " + result.action.actionID);
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBodyText = "hello";
sharingIntent.setFlags(FLAG_ACTIVITY_NEW_TASK);
sharingIntent.putExtra(Intent.EXTRA_SUBJECT,"share");
sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBodyText);
Intent share = Intent.createChooser(sharingIntent, "share via");
share.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MyApplication.getContext().startActivity(share);


问:
GWT 2.5.0 mvn install error "Rebind result <class> must be a class"
Problem: I run mvn install on my GWT 2.5.0 project that I built with the gwt-maven-plugin and get the error Rebind result 'c3gw.fwk.gui.client.ClientFactory' must be a class.

This is a snippet of my pom.xml:

```<code>  <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>gwt-maven-plugin</artifactId>
    <version>2.5.0</version>
    <executions>
      <execution>
         <goals>
             <goal>compile</goal>
             <goal>test</goal>
             <goal>i18n</goal>
             <goal>resources</goal>
             <goal>generateAsync</goal>
         </goals>
      </execution>
     </executions>
     <configuration>
       <runTarget>C3gwGui.html</runTarget>
       <hostedWebapp>${webappDirectory}</hostedWebapp>
       <i18nMessagesBundle>c3gw.fwk.gui.client.Messages</i18nMessagesBundle>
     </configuration>
  </plugin>

  <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-war-plugin</artifactId>
      <version>2.1.1</version>
      <executions>
          <execution>
              <phase>compile</phase>
              <goals>
                  <goal>exploded</goal>
              </goals>
          </execution>
      </executions>
      <configuration>
          <webappDirectory>${webappDirectory}</webappDirectory>
      </configuration>
  </plugin>
</code>```

This is a snippet of my C3gwGui.gwt.xml:

```<code><replace-with class="c3gw.fwk.gui.client.ClientFactoryImpl">
    <when-type-is class="c3gw.fwk.gui.client.ClientFactory" />
</replace-with>
</code>```

This is a snippet of the line where the error is thrown:

```<code>public void onModuleLoad() {
    ClientFactory clientFactory = GWT.create(ClientFactory.class);

    ...
}
</code>```

ClientFactory is an interface and ClientFactoryImpl implements the interface.

What I've figured out so far: The code works perfectly fine in Eclipse when I run debug, it just doesn't work when I do mvn install. I've run all the goals available for gwt-maven-plugin (clean, compile, sources, etc...) and they all work so the only conclusion I can have at this point is that something is happening during the maven-war-plugin phase or much later.

I also took the basics of this code from the following google tutorial and they use an interface so it should work, assuming that the example project also works that is.

答: Removing war:exploded, as Thomas indicated, solved the issue.</p>

Body:
Problem: I run mvn install on my GWT 2.5.0 project that I built with the gwt-maven-plugin and get the error Rebind result 'c3gw.fwk.gui.client.ClientFactory' must be a class.

This is a snippet of my pom.xml:

  <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>gwt-maven-plugin</artifactId>
    <version>2.5.0</version>
    <executions>
      <execution>
         <goals>
             <goal>compile</goal>
             <goal>test</goal>
             <goal>i18n</goal>
             <goal>resources</goal>
             <goal>generateAsync</goal>
         </goals>
      </execution>
     </executions>
     <configuration>
       <runTarget>C3gwGui.html</runTarget>
       <hostedWebapp>${webappDirectory}</hostedWebapp>
       <i18nMessagesBundle>c3gw.fwk.gui.client.Messages</i18nMessagesBundle>
     </configuration>
  </plugin>

  <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-war-plugin</artifactId>
      <version>2.1.1</version>
      <executions>
          <execution>
              <phase>compile</phase>
              <goals>
                  <goal>exploded</goal>
              </goals>
          </execution>
      </executions>
      <configuration>
          <webappDirectory>${webappDirectory}</webappDirectory>
      </configuration>
  </plugin>

This is a snippet of my C3gwGui.gwt.xml:

<replace-with class="c3gw.fwk.gui.client.ClientFactoryImpl">
    <when-type-is class="c3gw.fwk.gui.client.ClientFactory" />
</replace-with>

This is a snippet of the line where the error is thrown:

public void onModuleLoad() {
    ClientFactory clientFactory = GWT.create(ClientFactory.class);

    ...
}

ClientFactory is an interface and ClientFactoryImpl implements the interface.

What I've figured out so far: The code works perfectly fine in Eclipse when I run debug, it just doesn't work when I do mvn install. I've run all the goals available for gwt-maven-plugin (clean, compile, sources, etc...) and they all work so the only conclusion I can have at this point is that something is happening during the maven-war-plugin phase or much later.

I also took the basics of this code from the following google tutorial and they use an interface so it should work, assuming that the example project also works that is.


问:
How to add hidden field in form element in masterpage
I want to add hidden field to every view i have through jquery or javascript. But i want that code to be in MasterPage.Master so i write code at one place and it adds on every view i have. Can i do this if yes then how? Im using asp.net mvc 2</p>

答:
In your master:

```<code>$(function() {
    $('body').append(
        $('<input/>')
            .attr('type', 'hidden')
            .attr('name', 'foo')
            .val('some value')
    );
});
</code>```

or replace $('body') with some other selector to a placeholder you've put somewhere in your master page if you want this hidden field to be inserted in some specific position. You could also insert it into existing <form> by giving them some id or class (if you have more of them on the same page and you wanted to insert this hidden field in each form).

ContentLicense: CC BY-SA 2.5

Body:
In your master:

$(function() {
    $('body').append(
        $('<input/>')
            .attr('type', 'hidden')
            .attr('name', 'foo')
            .val('some value')
    );
});

or replace $('body') with some other selector to a placeholder you've put somewhere in your master page if you want this hidden field to be inserted in some specific position. You could also insert it into existing <form> by giving them some id or class (if you have more of them on the same page and you wanted to insert this hidden field in each form).


问:
Dynamic center div bootstrap
I'm trying to create a responsive div list

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

```

As you can see, from above i have four divs and when i only have 3 divs, they will in left

Is it possible do it dynamically when there is only 3 div  and they will be centered ?

If yes, how can i do that. Thanks in advance and sorry for my bad english

答:
If I'm understanding the question correctly, changing col-sm-6 and col-xs-6 to -4 should give you the behavior you would like. If not, feel free to comment on this answer and explain how you'd like it to look.

```<code><div class="container">
  <div class="col-lg-3 col-md-3 col-sm-4 col-xs-4">
    <a href="#">
      <img src="https://dummyimage.com/250x250/000/fff">
    </a>
  </div>
  <div class="col-lg-3 col-md-3 col-sm-4 col-xs-4">
    <a href="#">
      <img src="https://dummyimage.com/250x250/000/fff">
    </a>
  </div>
  <div class="col-lg-3 col-md-3 col-sm-4 col-xs-4">
    <a href="#">
      <img src="https://dummyimage.com/250x250/000/fff">
    </a>
  </div>
  <div class="col-lg-3 col-md-3 col-sm-4 col-xs-4">
    <a href="#">
      <img src="https://dummyimage.com/250x250/000/fff">
    </a>
  </div>
</div>
</code>```

Title: Dynamic center div bootstrap

Body:
I'm trying to create a responsive div list

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

As you can see, from above i have four divs and when i only have 3 divs, they will in left

Is it possible do it dynamically when there is only 3 div  and they will be centered ?

If yes, how can i do that. Thanks in advance and sorry for my bad english

Body:
If I'm understanding the question correctly, changing col-sm-6 and col-xs-6 to -4 should give you the behavior you would like. If not, feel free to comment on this answer and explain how you'd like it to look.

<div class="container">
  <div class="col-lg-3 col-md-3 col-sm-4 col-xs-4">
    <a href="#">
      <img src="https://dummyimage.com/250x250/000/fff">
    </a>
  </div>
  <div class="col-lg-3 col-md-3 col-sm-4 col-xs-4">
    <a href="#">
      <img src="https://dummyimage.com/250x250/000/fff">
    </a>
  </div>
  <div class="col-lg-3 col-md-3 col-sm-4 col-xs-4">
    <a href="#">
      <img src="https://dummyimage.com/250x250/000/fff">
    </a>
  </div>
  <div class="col-lg-3 col-md-3 col-sm-4 col-xs-4">
    <a href="#">
      <img src="https://dummyimage.com/250x250/000/fff">
    </a>
  </div>
</div>


问:
How to make purchasing one in-app product several times possible?
I'm trying to implement in-app billing system in my app to serve ads free version to users. I learned these steps and finally I succeeded to buy my product by using my test account. (I got the OK resposeCode through onPurchasesUpdated() method.)

However I could not buy it again. There was no response after calling launchBillingFlow(). I don't know why. Even if my product is ads free version (I mean permanent item.), I want to know that buying one item several times. Please let me know.

答:
Once a managed product is purchased, it is considered to be "owned".
  Managed products in the "owned" state cannot be purchased from Google
  Play. You must send a consumption request for the "owned" managed
  product before Google Play makes it available for purchase again.
  Consuming the managed product reverts it to the "unowned" state, and
  discards the previous purchase data

As soon as the User buys a product from your application, just consume it and keep track of the purchase some other way. By storing the credits on your server may be.

More on the developer site


问:
Is it possible to tell the compiler that a method always throws an Exception
Generally speaking, the Java compiler does not propagate the information that a method "always" throw an Exception, and therefore, does not detect that all code paths are complete.

(This is due to the fact that Java compiler compiles each class independently).

It's a problem when you want to write something like that.

```<code>public class ErrorContext {
    public void fatalISE(String message) {
        String context = "gather lots of information about the context of the error";
        throw new IllegalStateException(context +": " + message);
    }
}

public class A {
    public MyObject myMethod() {
        if (allIsGood()) {
            return new MyObject();
        }
        ErrorContext.fatalISE("all is not good");
    }
}
</code>```

(ie, a kind of "assertion helper" that gathers context information).

Because the compiler will complain that myMethod does not always return a MyObject.

To my knowledge, there is no specific annotation to indicate that a method always throws.

答:
I just came across this use case but with a method that should always throw 2 or more type of exceptions.

To make the code compile you can add return null; As MouseEvent said.

or better replace it with throw new AssertionError() that prevent returning null value, improve readability and ensure that if someone modify checkAndAlwaysThrowException() it wil continue to Always throw exception

```<code>public Object myMehtod() throws ExceptionType1, ExceptionType2 {
    //....
    checkAndAlwaysThrowException();
    throw new AssertionError("checkAndAlwaysThrowException should have throw exception");
}

public void checkAndAlwaysThrowException() throws ExceptionType1, ExceptionType2 {
    if (cond) {
        throw new ExceptionType1();
    } else {
        throw new ExceptionType2();
    }
}
</code>```

Body:
Generally speaking, the Java compiler does not propagate the information that a method "always" throw an Exception, and therefore, does not detect that all code paths are complete.

(This is due to the fact that Java compiler compiles each class independently).

It's a problem when you want to write something like that.

public class ErrorContext {
    public void fatalISE(String message) {
        String context = "gather lots of information about the context of the error";
        throw new IllegalStateException(context +": " + message);
    }
}

public class A {
    public MyObject myMethod() {
        if (allIsGood()) {
            return new MyObject();
        }
        ErrorContext.fatalISE("all is not good");
    }
}

(ie, a kind of "assertion helper" that gathers context information).

Because the compiler will complain that myMethod does not always return a MyObject.

To my knowledge, there is no specific annotation to indicate that a method always throws.

Body:
I just came across this use case but with a method that should always throw 2 or more type of exceptions.

To make the code compile you can add return null; As MouseEvent said.

or better replace it with throw new AssertionError() that prevent returning null value, improve readability and ensure that if someone modify checkAndAlwaysThrowException() it wil continue to Always throw exception

public Object myMehtod() throws ExceptionType1, ExceptionType2 {
    //....
    checkAndAlwaysThrowException();
    throw new AssertionError("checkAndAlwaysThrowException should have throw exception");
}

public void checkAndAlwaysThrowException() throws ExceptionType1, ExceptionType2 {
    if (cond) {
        throw new ExceptionType1();
    } else {
        throw new ExceptionType2();
    }
}


问:
Difference in methods for converting std string to char*
I know there are a ton questions on how to convert a std::string to a char* and through my research, I have adopted a few different options.  However, the only one that seems to work for me is const_cast from the c_str() method.

So I am using that for now, but would like to know more information as to why the other methods do not work.  What am I missing in my understanding as to why this isn't working as intended which seems to work for many others.

```<code>#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    char* test = "Hello World";
    string testStr(test);

    vector<char> testVec2(testStr.begin(), testStr.end());
    // testVec2[0] = 'F';
    char* test2 = reinterpret_cast<char*>(testVec2.data());

    vector<char> testVec3(testStr.begin(), testStr.end());
    // testVec3[0] = 'G';
    char* test3 = &testVec3[0];

    // The only one that works
    char* test4 = const_cast<char*>(testStr.c_str());

    cout << "char* test: " << test << " [" << strlen(test) << "]" << endl;
    cout << "str test: " << testStr << " [" << testStr.length() << "]" <<     endl;
    cout << "=== conv testing === " << endl;
    cout << "char* test2: " << test2 << " [" << strlen(test2) << "]" <<     endl;
    cout << "char* test3: " << test3 << " [" << strlen(test3) << "]" << endl;
    cout << "char* test4: " << test4 << " [" << strlen(test4) << "]" << endl;

    cin.get();
    return 0;
}
</code>```

I know the pitfalls of using const_cast but it works for my situation at the moment.  I simply take the string from the user, pass it to a C API and do nothing else with it (no worries of it being modified).

Here is a sample of the output
https://imgur.com/a/2S1HD

So what am I doing wrong and is there a better way to do this?

UPDATE
Thanks to everyone for the extremely fast answers.  It seems that my underlying confusion was the assumption of the null terminating character not being in the new buffer that I was assigning to the char* variable.  Hence why my output was showing random characters after the string (that should have been my clue but it has been so long since I've done C/C++)

I also should have tagged this C++17 originally (since fixed) as that is what I am aiming for.  I did not have that enabled in my console app in Visual Studio which made the solution by Passer By below work.  That is the method I will use going forward.

Bottom line, changing my target to C++17 this works as expected

```<code>char* test = "Hello World";
string testStr(test);
vector<char> testVec2(testStr.begin(), testStr.end());
char* test2 = testStr.data();
</code>```

答:
```<code>vector<char> testVec2(testStr.begin(), testStr.end());
</code>```

this will create the following vector:

```<code>vector<char> testVec2 = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'};
</code>```

Anything jumps at you from that? It should. It doesn't contain the null terminator character. Any attempt to use testVec2.data() as a C string will result in Undefined Behavior because of this.

Although from C++11 std::string's underlying buffer has to contain the null terminator character, the begin - end range doesn't include it.

Body:
I know there are a ton questions on how to convert a std::string to a char* and through my research, I have adopted a few different options.  However, the only one that seems to work for me is const_cast from the c_str() method.

So I am using that for now, but would like to know more information as to why the other methods do not work.  What am I missing in my understanding as to why this isn't working as intended which seems to work for many others.

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>

using namespace std;

int main()
{
    char* test = "Hello World";
    string testStr(test);

    vector<char> testVec2(testStr.begin(), testStr.end());
    // testVec2[0] = 'F';
    char* test2 = reinterpret_cast<char*>(testVec2.data());

    vector<char> testVec3(testStr.begin(), testStr.end());
    // testVec3[0] = 'G';
    char* test3 = &testVec3[0];

    // The only one that works
    char* test4 = const_cast<char*>(testStr.c_str());

    cout << "char* test: " << test << " [" << strlen(test) << "]" << endl;
    cout << "str test: " << testStr << " [" << testStr.length() << "]" <<     endl;
    cout << "=== conv testing === " << endl;
    cout << "char* test2: " << test2 << " [" << strlen(test2) << "]" <<     endl;
    cout << "char* test3: " << test3 << " [" << strlen(test3) << "]" << endl;
    cout << "char* test4: " << test4 << " [" << strlen(test4) << "]" << endl;

    cin.get();
    return 0;
}

I know the pitfalls of using const_cast but it works for my situation at the moment.  I simply take the string from the user, pass it to a C API and do nothing else with it (no worries of it being modified).

Here is a sample of the output
https://imgur.com/a/2S1HD

So what am I doing wrong and is there a better way to do this?

UPDATE
Thanks to everyone for the extremely fast answers.  It seems that my underlying confusion was the assumption of the null terminating character not being in the new buffer that I was assigning to the char* variable.  Hence why my output was showing random characters after the string (that should have been my clue but it has been so long since I've done C/C++)

I also should have tagged this C++17 originally (since fixed) as that is what I am aiming for.  I did not have that enabled in my console app in Visual Studio which made the solution by Passer By below work.  That is the method I will use going forward.

Bottom line, changing my target to C++17 this works as expected

char* test = "Hello World";
string testStr(test);
vector<char> testVec2(testStr.begin(), testStr.end());
char* test2 = testStr.data();

Body:
vector<char> testVec2(testStr.begin(), testStr.end());

this will create the following vector:

vector<char> testVec2 = {'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'};

Anything jumps at you from that? It should. It doesn't contain the null terminator character. Any attempt to use testVec2.data() as a C string will result in Undefined Behavior because of this.

Although from C++11 std::string's underlying buffer has to contain the null terminator character, the begin - end range doesn't include it.


问:
Problems In Merged CHM Help file
I've succeeded to merge 2 chm files into one but

Application context sensitive help is not working now. Before, links were like "HELP/Outline1.htm". If I keep like that, it founds the subject in contents, locates it there but no help is displayed but page not found. Then, if I click on the subject, help text appears. If I change the link to HELP.chm::/HELP/Outline1.htm, help text appears but it cannot locate the subject on the left.

I wonder what is needed to open a help page in a merged help file and locate its subject in contents?

Is it possible to dive a chm file into two but context hierarchy should be same. What I mean is, I don't want to create another book. I need to open help context from another help file in a link

A

-- A.a

-- A.b

B

Currently I can only divide such a CHM into two but it becomes like below

A

-- A.a

B

A.b

Is it possible to divide chm and keep the content list as same

Regards,
Burak

答:
I haven't really dove into merged chms yet, but I can share some urls from my notes. They are fairly common ones, so you might already have them. The second one is explicitely about context ids in merged help

http://www.helpware.net/htmlhelp/how_to_merge.htm

http://www.helpware.net/htmlhelp/how_to_merge_ctx2.htm

Title: Problems In Merged CHM Help file


问:
req.body is empty in POST express nodejs
Below is my code for HTML form to post data on server side.

HTML Code:

```<code><form action="/Device_Data" method="post">
    <select name="deviceSelect" id="deviceSelect" class="selectdevice" type = "text" style="margin-top:1.5%">
        <option value="" selected="selected">Choose Device</option>
        <option value="Device1">Device 1</option>
        <option value="Device2">Device 2</option>
        <option value="Device3">Device 3</option>
        <option value="Device4">Device 4</option>
        <option value="Device5">Device 5</option>
        <option value="Device6">Device 6</option>
        <option value="Device7">Device 7</option>
        <option value="Device8">Device 8</option>
    </select>
    <button id="Import" value="Import" class="button1" type="button" formenctype="text/plain">Import</button>
</form>
</code>```

Server code:

```<code>var express = require('express');
//require the body-parser nodejs module
var bodyParser = require('body-parser');
var path = require('path');
var qs = require('querystring');
var app = express();
// var server = http.createServer(app);

//support parsing of application/json type post data
app.use(bodyParser.json());

//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: false }));

app.post("/Device_Data", function (req, res) {

  // result.entries contains entities matching the query
 //res.setHeader('Content-Type', 'application/json');
  console.log(req.body);
  res.send(200, req.body);
});
</code>```

Output:

```<code>{}
Thu, 16 Nov 2017 14:05:13 GMT express deprecated res.send(status, body): Use res.status(status).send(body) instead at server.js:122:7
</code>```

Can anyone help me?
Thanks in advance.

I just want to print the req.body data.

答:
Change type of your button to submit and remove formenctype from this button.

```<code> <button id="Import" value="Import" class="button1" type="submit">Import</button>
</code>```

Body:
Below is my code for HTML form to post data on server side.

HTML Code:

<form action="/Device_Data" method="post">
    <select name="deviceSelect" id="deviceSelect" class="selectdevice" type = "text" style="margin-top:1.5%">
        <option value="" selected="selected">Choose Device</option>
        <option value="Device1">Device 1</option>
        <option value="Device2">Device 2</option>
        <option value="Device3">Device 3</option>
        <option value="Device4">Device 4</option>
        <option value="Device5">Device 5</option>
        <option value="Device6">Device 6</option>
        <option value="Device7">Device 7</option>
        <option value="Device8">Device 8</option>
    </select>
    <button id="Import" value="Import" class="button1" type="button" formenctype="text/plain">Import</button>
</form>

Server code:

var express = require('express');
//require the body-parser nodejs module
var bodyParser = require('body-parser');
var path = require('path');
var qs = require('querystring');
var app = express();
// var server = http.createServer(app);

//support parsing of application/json type post data
app.use(bodyParser.json());

//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: false }));

app.post("/Device_Data", function (req, res) {

  // result.entries contains entities matching the query
 //res.setHeader('Content-Type', 'application/json');
  console.log(req.body);
  res.send(200, req.body);
});

Output:

{}
Thu, 16 Nov 2017 14:05:13 GMT express deprecated res.send(status, body): Use res.status(status).send(body) instead at server.js:122:7

Can anyone help me?
Thanks in advance.

I just want to print the req.body data.

Body:
Change type of your button to submit and remove formenctype from this button.

 <button id="Import" value="Import" class="button1" type="submit">Import</button>


问:
WebDriver -- Selenium I can not select the dropdown option
I can not understand what the problem is, tried different ways of choosing, I give examples below...
1. You must select or click a selection.
2. Select or click the desired language.
But WebDriver does not see, does not find these elements, but in DOM they are.
You need to go to LinkedIn profile, settings, language selection.</p>

```<code>//Before select dropdown.
WebElement language = driver.findElement(By.id("setting-select-language"));
language.click();
//Select dropdown.
Select make = new Select(driver.findElement(By.name("selectLanguage")));
make.selectByValue("en_US");
//Or
Actions act = new Actions(driver);
//XPath of dropdown.
act.moveToElement(driver.findElement(By.name("selectLanguage"))).click().perform();
//XPath of option in the dropdown.
act.moveToElement(driver.findElement(By.xpath("//*[@id='setting-select-language-content']/form/div/select/option[16]"))).click().perform();
</code>```

答:
I believe you locator for the select is incorrect, try something like the below code:</p>

```<code>WebElement language = driver.findElement(By.id("setting-select-language"));
language.click();
Select make = new Select(driver.findElement(By.name("//*[@id='setting-select-language-content']/form/div/select")));
make.selectByValue("en_US");
</code>```

Body:
I can not understand what the problem is, tried different ways of choosing, I give examples below...
1. You must select or click a selection.
2. Select or click the desired language.
But WebDriver does not see, does not find these elements, but in DOM they are.
You need to go to LinkedIn profile, settings, language selection.

//Before select dropdown.
WebElement language = driver.findElement(By.id("setting-select-language"));
language.click();
//Select dropdown.
Select make = new Select(driver.findElement(By.name("selectLanguage")));
make.selectByValue("en_US");
//Or
Actions act = new Actions(driver);
//XPath of dropdown.
act.moveToElement(driver.findElement(By.name("selectLanguage"))).click().perform();
//XPath of option in the dropdown.
act.moveToElement(driver.findElement(By.xpath("//*[@id='setting-select-language-content']/form/div/select/option[16]"))).click().perform();

Body:
I believe you locator for the select is incorrect, try something like the below code:

WebElement language = driver.findElement(By.id("setting-select-language"));
language.click();
Select make = new Select(driver.findElement(By.name("//*[@id='setting-select-language-content']/form/div/select")));
make.selectByValue("en_US");


问:
I am trying to use custom php function in twig, what am I doing wrong?
I tried to use my custom php function in twig.
When I type {{current_url}} in my page.html.twig nothing happens.
I also tried {{kint(current_url)}}, it outputs NULL
This is my code

```<code><?php
namespace Drupal\nextprev\plugin\block\customtwigoutput;

use Drupal\Core\Template\TwigExtension;
use  Drupal\nextprev\nextprevmodule\path;
use \Symfony\Component\HttpFoundation\Request;

class AppExtension extends \Twig_Extension {

public function url() {
   $current_path = \Drupal::service('path.current')->getPath();
   return $current_path;
}

  public function getFilters() {
     return array(
       'current_url' => new \Twig_Function_Function(array('Drupal\nextprev\plugin\block\customtwigoutput\AppExtension', 'url')),
     );
   }
}
</code>```

What am I doing wrong?

答:
Did you add services.yml to it? This is a sample;</p>

```<code>twig.url:
    class: AppBundle\Twig\Extension\AppExtension
    tags:
        - { twig.extension }
</code>```

Body:
I tried to use my custom php function in twig.
When I type {{current_url}} in my page.html.twig nothing happens.
I also tried {{kint(current_url)}}, it outputs NULL
This is my code

<?php
namespace Drupal\nextprev\plugin\block\customtwigoutput;

use Drupal\Core\Template\TwigExtension;
use  Drupal\nextprev\nextprevmodule\path;
use \Symfony\Component\HttpFoundation\Request;

class AppExtension extends \Twig_Extension {

public function url() {
   $current_path = \Drupal::service('path.current')->getPath();
   return $current_path;
}

  public function getFilters() {
     return array(
       'current_url' => new \Twig_Function_Function(array('Drupal\nextprev\plugin\block\customtwigoutput\AppExtension', 'url')),
     );
   }
}

What am I doing wrong?

Body:
Did you add services.yml to it? This is a sample;

twig.url:
    class: AppBundle\Twig\Extension\AppExtension
    tags:
        - { twig.extension }


问:
Finding specific instance of class?
I've just started learning java and I'm trying to create an application to register students.

Based on this question how-would-i-create-a-new-object... I created a while loop to create an instance of a class.

```<code>    public class RegStudent {

    ArrayList<Student> studentList = new ArrayList<>();

    Scanner input = new Scanner(System.in);

    public void reggaStudent(int start) {

        while (start != 0) {
            String programNamn, studNamn;
            int totalPoint, antalKurser;

            System.out.println("Vad heter programmet?");
            programNamn = input.nextLine();
            System.out.println("Vad heter studenten");
            studNamn = input.nextLine();
            System.out.println("Hur många poäng har studenten?");
            totalPoint = input.nextInt();
            System.out.println("Hur många kurser är studenten registrerad på?");
            antalKurser = input.nextInt();

            // Add student to list of students
            studentList.add(new Student(totalPoint, antalKurser,
                                        programNamn, studNamn));
            System.out.println("Vill du registrera in en fler studenter? "
                                + "Skriv 1 för ja och 0 för nej");
            start = input.nextInt();
            input.nextLine();
        } // End of whileloop

    }
}
</code>```

The class is:

```<code>public class Student {
    private int totalPoint;
    private int antalKurser;
    private String programNamn;
    private String studNamn;
    private static int counter;

    public Student(int totalPoint, int antalKurser, String program, String studNamn) {

        this.totalPoint = totalPoint;
        this.antalKurser = antalKurser;
        this.programNamn = program;
        this.studNamn = studNamn;
        counter++;
    }

    public int getTotalPoint() {
        return totalPoint;
    }

    public void setTotalPoint(int totalPoint) {
        this.totalPoint = totalPoint;
    }

    public int getAntalKurser() {
        return antalKurser;
    }

    public void setAntalKurser(int antalKurser) {
        this.antalKurser = antalKurser;
    }

    public String getProgramNamn() {
        return programNamn;
    }

    public void setProgramNamn(String programNamn) {
        this.programNamn = programNamn;
    }

    public String getStudNamn() {
        return studNamn;
    }

    public void setStudNamn(String studNamn) {
        this.studNamn = studNamn;
    }
    public static int getCount(){

        return counter;
    }
    @Override
    public String toString() {

        return String.format(" Namn: %s, Program: %s, Antal poäng: %d, "
        + "Antal kurser: %d\n ", studNamn, programNamn, totalPoint, antalKurser);
    }

}
</code>```

How do I go about to get and set the instance variables in specific instance? I.e find the instances.

I understand it might be bad design but in that case I would appreciate some input on how to solve a case where i wanna instantiate an unknown number of students.

I've added a counter just to see I actually created some instances of the class.

答:
```<code> studentList.add(new Student(totalPoint, antalKurser,
                                    programNamn, studNamn));
</code>```

You now have your Student objects in a list. I assume you have something like

```<code>List<Student> studentList = new ArrayList<>();
</code>```

somewhere in your code. After you populate the list with Student objects, you can use it to find instances. You need to decide what criteria to use for a search. Do you want to find a student with a specific name? Do you want to find all students in a given program? Do you want to find students with more than a certain number of points?

Maybe you want to do each of these. Start by picking one and then get a piece of paper to write out some ideas of how you would do the search. For example, say you want to find a student with the name "Bill". Imagine that you were given a stack of cards with information about students. This stack of cards represents the list in your program. How would you search this stack of cards for the card with Bill's name on it? Describe the steps you need to take in words. Don't worry about how you will code this yet. The first step in writing a computer program is breaking the solution down into small steps. After you have a clear idea how you might do this by hand in the physical world, you can translate your description into Java code.

Title: Finding specific instance of class?

Body:
I've just started learning java and I'm trying to create an application to register students.

Based on this question how-would-i-create-a-new-object... I created a while loop to create an instance of a class.

    public class RegStudent {

    ArrayList<Student> studentList = new ArrayList<>();

    Scanner input = new Scanner(System.in);

    public void reggaStudent(int start) {

        while (start != 0) {
            String programNamn, studNamn;
            int totalPoint, antalKurser;

            System.out.println("Vad heter programmet?");
            programNamn = input.nextLine();
            System.out.println("Vad heter studenten");
            studNamn = input.nextLine();
            System.out.println("Hur många poäng har studenten?");
            totalPoint = input.nextInt();
            System.out.println("Hur många kurser är studenten registrerad på?");
            antalKurser = input.nextInt();

            // Add student to list of students
            studentList.add(new Student(totalPoint, antalKurser,
                                        programNamn, studNamn));
            System.out.println("Vill du registrera in en fler studenter? "
                                + "Skriv 1 för ja och 0 för nej");
            start = input.nextInt();
            input.nextLine();
        } // End of whileloop

    }
}

The class is:

public class Student {
    private int totalPoint;
    private int antalKurser;
    private String programNamn;
    private String studNamn;
    private static int counter;

    public Student(int totalPoint, int antalKurser, String program, String studNamn) {

        this.totalPoint = totalPoint;
        this.antalKurser = antalKurser;
        this.programNamn = program;
        this.studNamn = studNamn;
        counter++;
    }

    public int getTotalPoint() {
        return totalPoint;
    }

    public void setTotalPoint(int totalPoint) {
        this.totalPoint = totalPoint;
    }

    public int getAntalKurser() {
        return antalKurser;
    }

    public void setAntalKurser(int antalKurser) {
        this.antalKurser = antalKurser;
    }

    public String getProgramNamn() {
        return programNamn;
    }

    public void setProgramNamn(String programNamn) {
        this.programNamn = programNamn;
    }

    public String getStudNamn() {
        return studNamn;
    }

    public void setStudNamn(String studNamn) {
        this.studNamn = studNamn;
    }
    public static int getCount(){

        return counter;
    }
    @Override
    public String toString() {

        return String.format(" Namn: %s, Program: %s, Antal poäng: %d, "
        + "Antal kurser: %d\n ", studNamn, programNamn, totalPoint, antalKurser);
    }

}

How do I go about to get and set the instance variables in specific instance? I.e find the instances.

I understand it might be bad design but in that case I would appreciate some input on how to solve a case where i wanna instantiate an unknown number of students.

I've added a counter just to see I actually created some instances of the class.

Body:
 studentList.add(new Student(totalPoint, antalKurser,
                                    programNamn, studNamn));

You now have your Student objects in a list. I assume you have something like

List<Student> studentList = new ArrayList<>();

somewhere in your code. After you populate the list with Student objects, you can use it to find instances. You need to decide what criteria to use for a search. Do you want to find a student with a specific name? Do you want to find all students in a given program? Do you want to find students with more than a certain number of points?

Maybe you want to do each of these. Start by picking one and then get a piece of paper to write out some ideas of how you would do the search. For example, say you want to find a student with the name "Bill". Imagine that you were given a stack of cards with information about students. This stack of cards represents the list in your program. How would you search this stack of cards for the card with Bill's name on it? Describe the steps you need to take in words. Don't worry about how you will code this yet. The first step in writing a computer program is breaking the solution down into small steps. After you have a clear idea how you might do this by hand in the physical world, you can translate your description into Java code.