问:
SSMS Joins and COUNT function
I've got a database which records all the jobs that we complete for the various departments in the business.

Table 1 is Department – this stores the name of the department alongside it's ID

Table 2 is Section – this stores the name of section alongside it's ID (one department could have several sections)

Table 3 is User – name of the person who completed the task, alongside the department and section id that the task was for)

Table 4 is date of completion – this contains the name of the person who completed the task and the date it was submitted to the system

Big boss wants me to provide a report that will detail how many jobs each department and section have submitted within a certain time frame.

So far I have got this:

```<code>SELECT  Dept.DepartmenttId,
Name.SectionId,
count (Name.DepartmentId)
FROM    Name
LEFT join Job on Name.UserId = Job.UserId
WHERE Job.DateSubmitted > '2017-09-01 00:00:00.000' and Job.DateSubmitted <'2017-09-30 23:59:59.000'
Group by Name.DepartmentId, Name.SectionId
</code>```

That gives me results like:

```<code>BOB      2    3
STEVE    1    2
</code>```

where I am getting the name of person alongside the department ID and section ID.

What I want is:

```<code>Bob    IT    Development
</code>```

so I can see the name of the department and section rather than the IDs.

I've been playing around with joins, but everything I try breaks the count part. Is there a way to get the count and the names within one query? Have I gone wrong in the way I've structured what I have so far?

Current tables:

DEPARTMENT

```<code>DepartmentId :: DepartmentName
1 :: IT
2 :: Marketing
3 :: Finance
</code>```

SECTION

```<code>SectionId :: SectionName
1 :: Development
2 :: Helpdesk
3 :: Architecture
4 :: Procurement
</code>```

NAME

```<code>Name :: JobId :: DepartmentId :: SectionId
Bob :: J1234 :: 1 :: 2
Steve :: J1235 :: 3 :: 4
</code>```

JOB

```<code>JOBId :: DateSubmitted
J1234 :: 02/09/2017
J1235 :: 04/09/2017
</code>```

答:
Please check following SQL Select

```<code>SELECT
    Name.Name, DepartmentName, SectionName
FROM Name
INNER JOIN Job on Name.JobId = Job.JobId
INNER JOIN DEPARTMENT on Name.DepartmentID = DEPARTMENT.DepartmentID
INNER JOIN Section on Name.SectionID = Section.SectionID
WHERE
    Job.DateSubmitted between '2017-09-01 00:00:00.000' and '2017-09-30 23:59:59.000'
</code>```

For displaying job count, you can use following SQL query

```<code>SELECT
    DepartmentName, SectionName, Count(*) as JobCount
FROM Job
INNER JOIN DEPARTMENT on Name.DepartmentID = DEPARTMENT.DepartmentID
INNER JOIN Section on Name.SectionID = Section.SectionID
WHERE
    Job.DateSubmitted between '2017-09-01 00:00:00.000' and '2017-09-30 23:59:59.000'
Group By
    DepartmentName, SectionName
</code>```

Title: SSMS Joins and COUNT function

Body:
I've got a database which records all the jobs that we complete for the various departments in the business.

Table 1 is Department – this stores the name of the department alongside it's ID

Table 2 is Section – this stores the name of section alongside it's ID (one department could have several sections)

Table 3 is User – name of the person who completed the task, alongside the department and section id that the task was for)

Table 4 is date of completion – this contains the name of the person who completed the task and the date it was submitted to the system

Big boss wants me to provide a report that will detail how many jobs each department and section have submitted within a certain time frame.

So far I have got this:

SELECT  Dept.DepartmenttId,
Name.SectionId,
count (Name.DepartmentId)
FROM    Name
LEFT join Job on Name.UserId = Job.UserId
WHERE Job.DateSubmitted > '2017-09-01 00:00:00.000' and Job.DateSubmitted <'2017-09-30 23:59:59.000'
Group by Name.DepartmentId, Name.SectionId

That gives me results like:

BOB      2    3
STEVE    1    2

where I am getting the name of person alongside the department ID and section ID.

What I want is:

Bob    IT    Development

so I can see the name of the department and section rather than the IDs.

I've been playing around with joins, but everything I try breaks the count part. Is there a way to get the count and the names within one query? Have I gone wrong in the way I've structured what I have so far?

Current tables:

DEPARTMENT

DepartmentId :: DepartmentName
1 :: IT
2 :: Marketing
3 :: Finance

SECTION

SectionId :: SectionName
1 :: Development
2 :: Helpdesk
3 :: Architecture
4 :: Procurement

NAME

Name :: JobId :: DepartmentId :: SectionId
Bob :: J1234 :: 1 :: 2
Steve :: J1235 :: 3 :: 4

JOB

JOBId :: DateSubmitted
J1234 :: 02/09/2017
J1235 :: 04/09/2017

Body:
Please check following SQL Select

SELECT
    Name.Name, DepartmentName, SectionName
FROM Name
INNER JOIN Job on Name.JobId = Job.JobId
INNER JOIN DEPARTMENT on Name.DepartmentID = DEPARTMENT.DepartmentID
INNER JOIN Section on Name.SectionID = Section.SectionID
WHERE
    Job.DateSubmitted between '2017-09-01 00:00:00.000' and '2017-09-30 23:59:59.000'

For displaying job count, you can use following SQL query

SELECT
    DepartmentName, SectionName, Count(*) as JobCount
FROM Job
INNER JOIN DEPARTMENT on Name.DepartmentID = DEPARTMENT.DepartmentID
INNER JOIN Section on Name.SectionID = Section.SectionID
WHERE
    Job.DateSubmitted between '2017-09-01 00:00:00.000' and '2017-09-30 23:59:59.000'
Group By
    DepartmentName, SectionName


来源: stackexchange

问:
Composite Application Project POM Editor doesn't show dependencies of certain maven projects
In WSO2 Enterprise Integrator Tooling (aka Eclipse Mars.2 Release 4.5.2 with their plugins) I have 2 projects:

Composite Application Project (CAP)

Registry Resources Project (RRP)

The Design view of the Composite Aplication Project POM Editor doesn't show the resources of the RRP or others projects.

Does anybody know why?

答:
After a lot of research I found that if You set a parent in the pom.xml of the Registry Resources Project and delete the tags groupId and version of the pom.xml, because it isn't neccesary because it's on the pom parent, then, the Composite Application Project POM Editor doesn't show you the artifacts of this project.

See it in action:

In the Resources Registry Project:

```<code>  <parent>
    <groupId>com.example</groupId>
    <artifactId>padre</artifactId>
    <version>1.0.0</version>
  </parent>

  <groupId>com.example.recursos</groupId>
  <artifactId>recursos</artifactId>
  <version>1.0.0</version>
</code>```

or simply:

```<code><groupId>com.example.recursos</groupId>
<artifactId>recursos</artifactId>
<version>1.0.0</version>
</code>```

The Design View in the CAP project:

In the Resources Registry Project:

```<code> <parent>
    <groupId>com.example</groupId>
    <artifactId>padre</artifactId>
    <version>1.0.0</version>
 </parent>
 <artifactId>recursos</artifactId>
</code>```

The Design View in the CAP project:

Maven even encourages you to avoid setting the groupId and version in a child project

Other hint:
When you open the pom.xml of a CAP in the Composite Aplication Project POM Editor, it allways set de groupId and version when you save it. Even although you have set the parent and delete both.

ContentLicense: CC BY-SA 3.0

Body:
After a lot of research I found that if You set a parent in the pom.xml of the Registry Resources Project and delete the tags groupId and version of the pom.xml, because it isn't neccesary because it's on the pom parent, then, the Composite Application Project POM Editor doesn't show you the artifacts of this project.

See it in action:

In the Resources Registry Project:

  <parent>
    <groupId>com.example</groupId>
    <artifactId>padre</artifactId>
    <version>1.0.0</version>
  </parent>

  <groupId>com.example.recursos</groupId>
  <artifactId>recursos</artifactId>
  <version>1.0.0</version>

or simply:

<groupId>com.example.recursos</groupId>
<artifactId>recursos</artifactId>
<version>1.0.0</version>

The Design View in the CAP project:

In the Resources Registry Project:

 <parent>
    <groupId>com.example</groupId>
    <artifactId>padre</artifactId>
    <version>1.0.0</version>
 </parent>
 <artifactId>recursos</artifactId>

The Design View in the CAP project:

Maven even encourages you to avoid setting the groupId and version in a child project

Other hint:
When you open the pom.xml of a CAP in the Composite Aplication Project POM Editor, it allways set de groupId and version when you save it. Even although you have set the parent and delete both.


问:
JS: add onclick function to table cell
I've created a minimal example: https://jsfiddle.net/n2r5t91v/

var myvalue = 20 // abbreviating how I calculate myvalue
var cell = document.getElementById("mytd");
cell.setAttribute('onclick', 'addToCell(' + myvalue + ');');

function addToCell(value) {
  var td_cell = document.getElementById("mytd");
  td_cell.value = td_cell.value + ' ' + value;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
  <tr>
    <td id="mytd">
      test
    </td>
  </tr>
</table></code>```

I expect the value of that  cell to change from "test" to "test 20" upon clicking. Why doesn't it work like this?

答:
The reason why it does not work is the jsfiddle is set to run onload so the code actually looks like

```<code>window.addEventListener("load", function () {
  var myvalue = 20 // abbreviating how I calculate myvalue
  var cell = document.getElementById("mytd");
  cell.setAttribute('onclick', 'addToCell(' + myvalue + ');');

  function addToCell (value) {
    var td_cell = document.getElementById("mytd");
    td_cell.value = td_cell.value + ' ' + value;
  }
})
</code>```

Now since you are adding the event in a bad way (using attributes) the function execute in global scope. So the function that is defined inside of the onload method can not be seen by the click handler.

So you either need to set the JavaScript to run at the bottom of the body (jsFiddle Settings), you need to make the function global, or best solution, bind the event the correct way with addEventListener.

And inputs do not have a value, they have HTML and text. So it needs to be innerHTML.

```<code>  var myvalue = 20 // abbreviating how I calculate myvalue
  var cell = document.getElementById("mytd");
  cell.addEventListener('click', function () { addToCell(myvalue); });

  function addToCell(value){
    var td_cell = document.getElementById("mytd");
    td_cell.innerHTML = td_cell.innerHTML + ' ' + value;
  }
</code>```

Title: JS: add onclick function to table cell

Body:
I've created a minimal example: https://jsfiddle.net/n2r5t91v/

var myvalue = 20 // abbreviating how I calculate myvalue
var cell = document.getElementById("mytd");
cell.setAttribute('onclick', 'addToCell(' + myvalue + ');');

function addToCell(value) {
  var td_cell = document.getElementById("mytd");
  td_cell.value = td_cell.value + ' ' + value;
}

      test

I expect the value of that  cell to change from "test" to "test 20" upon clicking. Why doesn't it work like this?

Body:
The reason why it does not work is the jsfiddle is set to run onload so the code actually looks like

window.addEventListener("load", function () {
  var myvalue = 20 // abbreviating how I calculate myvalue
  var cell = document.getElementById("mytd");
  cell.setAttribute('onclick', 'addToCell(' + myvalue + ');');

  function addToCell (value) {
    var td_cell = document.getElementById("mytd");
    td_cell.value = td_cell.value + ' ' + value;
  }
})

Now since you are adding the event in a bad way (using attributes) the function execute in global scope. So the function that is defined inside of the onload method can not be seen by the click handler.

So you either need to set the JavaScript to run at the bottom of the body (jsFiddle Settings), you need to make the function global, or best solution, bind the event the correct way with addEventListener.

And inputs do not have a value, they have HTML and text. So it needs to be innerHTML.

  var myvalue = 20 // abbreviating how I calculate myvalue
  var cell = document.getElementById("mytd");
  cell.addEventListener('click', function () { addToCell(myvalue); });

  function addToCell(value){
    var td_cell = document.getElementById("mytd");
    td_cell.innerHTML = td_cell.innerHTML + ' ' + value;
  }


问:
Laravel Vue & Vuex by Webpack
Laravel give you app.js for Vue.js out of the box.
So when I try to create component everything is ok.

```<code>//app.js file

require('./bootstrap');

window.Vue = require('vue');

Vue.component('example', require('./components/Example.vue'));

const app = new Vue({
    el: '#app',
});
</code>```

But how to add Vuex???
I have tried import modules inside app.js and bootstrap.js  and every time got error - like Vue not defined or Vuex not defined.
How to do it right? I use all out of box, Webpack for compiling app.js i public folder.

答:
Added

```<code>window.Vuex = require('vuex');
</code>```

to bootstrap.js

Title: Laravel Vue & Vuex by Webpack

Body:
Laravel give you app.js for Vue.js out of the box.
So when I try to create component everything is ok.

//app.js file

require('./bootstrap');

window.Vue = require('vue');

Vue.component('example', require('./components/Example.vue'));

const app = new Vue({
    el: '#app',
});

But how to add Vuex???
I have tried import modules inside app.js and bootstrap.js  and every time got error - like Vue not defined or Vuex not defined.
How to do it right? I use all out of box, Webpack for compiling app.js i public folder.

Body:
Added

window.Vuex = require('vuex');

to bootstrap.js


问:
Cassandra driver exception "All host(s) tried for query failed" occurs every few hours without explanation
I have an issue with my Cassandra cluster (4 node cluster). Cassandra version is 2.2.9 and driver version is 3.0.3.

After a couple of hours (~ 3 hours) I see the following issues in the driver log:

OutOfDirectMemoryError (Occurs sporadic and most of the time without impact)

No protocol version matching integer version

Unknown response opcode

Heartbeat query timed out

All host(s) tried for query failed --> Can't query Cassandra anymore

The Cassandra cluster is healthy and when I restart the app everything works again for a couple of hours.

Log snippet:

```<code>First Time                       Count  Message
2017-11-11 19:03:03 +0100            51  [/??.???.??.??:????] preparing to open ? new connections, total = ???
2017-11-11 19:03:03 +0100            49  [/??.???.??.??:????] Connection[/??.???.??.??:????-???, inFlight=?, closed=false] Transport initialized, connection ready
2017-11-11 19:03:03 +0100            24  [/??.???.??.??:????] Connection[/??.???.??.??:????-???, inFlight=?, closed=true] closed, remaining = ???
2017-11-11 19:03:29 +0100             1  Defuncting Connection[/??.???.??.??:????-???, inFlight=???, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: io.netty.util.internal.OutOfDirectMemoryError: failed to allocate ??????? byte(s) of direct memory (used: ???????, max: ????????))
2017-11-11 19:03:29 +0100            14  [/??.???.??.??:????] Connection[/??.???.??.??:????-???, inFlight=???, closed=false] failed, remaining = ???
2017-11-11 19:03:29 +0100             7  [/??.???.??.??:????] Connection[/??.???.??.??:????-???, inFlight=??, closed=false] failed, remaining = ???
2017-11-11 19:03:29 +0100             1  Defuncting Connection[/??.???.??.??:????-???, inFlight=??, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: java.lang.IllegalArgumentException: No protocol version matching integer version ?)
2017-11-11 19:03:29 +0100             5  Defuncting Connection[/??.???.??.??:????-???, inFlight=??, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode ??)
2017-11-11 19:03:29 +0100             4  Defuncting Connection[/??.???.??.??:????-???, inFlight=???, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode ?)
2017-11-11 19:03:29 +0100             3  Defuncting Connection[/??.???.??.??:????-???, inFlight=???, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode -???)
2017-11-11 19:03:30 +0100             3  Defuncting Connection[/??.???.??.??:????-???, inFlight=???, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode ??)
2017-11-11 19:03:30 +0100             2  Defuncting Connection[/??.???.??.??:????-???, inFlight=?, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode ??)
2017-11-11 19:03:30 +0100           401  [/??.???.??.??:????] Connection[/??.???.??.??:????-???, inFlight=?, closed=false] failed, remaining = ???
2017-11-11 19:03:33 +0100             1  Defuncting Connection[/??.???.??.??:????-???, inFlight=???, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode ???)
2017-11-11 19:03:41 +0100           722  Defuncting Connection[/??.???.??.??:????-???, inFlight=?, closed=false] because: [/??.???.??.??:????] Heartbeat query timed out
2017-11-11 19:03:41 +0100             8  [/??.???.??.??:????] Connection[/??.???.??.??:????-?, inFlight=?, closed=false] failed, remaining = ???
2017-11-11 19:03:41 +0100            11  Defuncting Connection[/??.???.??.??:????-?, inFlight=?, closed=false] because: [/??.???.??.??:????] Heartbeat query timed out
2017-11-11 19:03:41 +0100            67  [/??.???.??.??:????] Connection[/??.???.??.??:????-??, inFlight=?, closed=false] failed, remaining = ???
2017-11-11 19:03:41 +0100           115  Defuncting Connection[/??.???.??.??:????-??, inFlight=?, closed=false] because: [/??.???.??.??:????] Heartbeat query timed out
2017-11-11 19:03:44 +0100             2  Defuncting Connection[/??.???.??.??:????-???, inFlight=??, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode ?)
2017-11-11 19:03:51 +0100             2  Defuncting Connection[/??.???.??.??:????-???, inFlight=???, closed=false] because: [/??.???.??.??:????] Heartbeat query timed out
2017-11-11 19:03:51 +0100           265  Failed to post timeseries data Error Returned -
2017-11-11 19:03:57 +0100             3  Defuncting Connection[/??.???.??.??:????-???, inFlight=??, closed=false] because: [/??.???.??.??:????] Heartbeat query timed out
2017-11-11 19:04:01 +0100            39  Defuncting Connection[/??.???.??.??:????-???, inFlight=?, closed=false] because: [/??.???.??.??:????] Operation timed out
2017-11-11 19:04:01 +0100            12  Error processing jobs: execution of statement failed:All host(s) tried for query failed (tried: /??.???.??.??:???? (com.datastax.driver.core.exceptions.DriverException: Timeout while trying to acquire available connection (you may want to increase the driver number of per-host connections)), /??.???.??.??:???? (com.datastax.driver.core.exceptions.DriverException: Timeout while trying to acquire available connection (you may want to increase the driver number of per-host connections)), /??.???.??.??:???? (com.datastax.driver.core.exceptions.DriverException: Timeout while trying to acquire available connection (you may want to increase the driver number of per-host connections)), /??.???.??.??:???? [only showing errors of first ? hosts, use getErrors() for more details])
</code>```

Does somebody have an idea what could be the root cause?

答: Please check the direct memory settings you are using for your application. Ensure that there is enough memory available which can be allocated by the driver. Cassandra needs to allocate the direct memory. In cases where it cannot allocate the memory I already saw similar issues where it was reported as NoHostAvailableException even if it was memory related.</p>

Body:
I have an issue with my Cassandra cluster (4 node cluster). Cassandra version is 2.2.9 and driver version is 3.0.3.

After a couple of hours (~ 3 hours) I see the following issues in the driver log:

OutOfDirectMemoryError (Occurs sporadic and most of the time without impact)

No protocol version matching integer version

Unknown response opcode

Heartbeat query timed out

All host(s) tried for query failed --> Can't query Cassandra anymore

The Cassandra cluster is healthy and when I restart the app everything works again for a couple of hours.

Log snippet:

First Time                       Count  Message
2017-11-11 19:03:03 +0100            51  [/??.???.??.??:????] preparing to open ? new connections, total = ???
2017-11-11 19:03:03 +0100            49  [/??.???.??.??:????] Connection[/??.???.??.??:????-???, inFlight=?, closed=false] Transport initialized, connection ready
2017-11-11 19:03:03 +0100            24  [/??.???.??.??:????] Connection[/??.???.??.??:????-???, inFlight=?, closed=true] closed, remaining = ???
2017-11-11 19:03:29 +0100             1  Defuncting Connection[/??.???.??.??:????-???, inFlight=???, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: io.netty.util.internal.OutOfDirectMemoryError: failed to allocate ??????? byte(s) of direct memory (used: ???????, max: ????????))
2017-11-11 19:03:29 +0100            14  [/??.???.??.??:????] Connection[/??.???.??.??:????-???, inFlight=???, closed=false] failed, remaining = ???
2017-11-11 19:03:29 +0100             7  [/??.???.??.??:????] Connection[/??.???.??.??:????-???, inFlight=??, closed=false] failed, remaining = ???
2017-11-11 19:03:29 +0100             1  Defuncting Connection[/??.???.??.??:????-???, inFlight=??, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: java.lang.IllegalArgumentException: No protocol version matching integer version ?)
2017-11-11 19:03:29 +0100             5  Defuncting Connection[/??.???.??.??:????-???, inFlight=??, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode ??)
2017-11-11 19:03:29 +0100             4  Defuncting Connection[/??.???.??.??:????-???, inFlight=???, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode ?)
2017-11-11 19:03:29 +0100             3  Defuncting Connection[/??.???.??.??:????-???, inFlight=???, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode -???)
2017-11-11 19:03:30 +0100             3  Defuncting Connection[/??.???.??.??:????-???, inFlight=???, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode ??)
2017-11-11 19:03:30 +0100             2  Defuncting Connection[/??.???.??.??:????-???, inFlight=?, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode ??)
2017-11-11 19:03:30 +0100           401  [/??.???.??.??:????] Connection[/??.???.??.??:????-???, inFlight=?, closed=false] failed, remaining = ???
2017-11-11 19:03:33 +0100             1  Defuncting Connection[/??.???.??.??:????-???, inFlight=???, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode ???)
2017-11-11 19:03:41 +0100           722  Defuncting Connection[/??.???.??.??:????-???, inFlight=?, closed=false] because: [/??.???.??.??:????] Heartbeat query timed out
2017-11-11 19:03:41 +0100             8  [/??.???.??.??:????] Connection[/??.???.??.??:????-?, inFlight=?, closed=false] failed, remaining = ???
2017-11-11 19:03:41 +0100            11  Defuncting Connection[/??.???.??.??:????-?, inFlight=?, closed=false] because: [/??.???.??.??:????] Heartbeat query timed out
2017-11-11 19:03:41 +0100            67  [/??.???.??.??:????] Connection[/??.???.??.??:????-??, inFlight=?, closed=false] failed, remaining = ???
2017-11-11 19:03:41 +0100           115  Defuncting Connection[/??.???.??.??:????-??, inFlight=?, closed=false] because: [/??.???.??.??:????] Heartbeat query timed out
2017-11-11 19:03:44 +0100             2  Defuncting Connection[/??.???.??.??:????-???, inFlight=??, closed=false] because: [/??.???.??.??:????] Unexpected exception triggered (io.netty.handler.codec.DecoderException: com.datastax.driver.core.exceptions.DriverInternalError: Unknown response opcode ?)
2017-11-11 19:03:51 +0100             2  Defuncting Connection[/??.???.??.??:????-???, inFlight=???, closed=false] because: [/??.???.??.??:????] Heartbeat query timed out
2017-11-11 19:03:51 +0100           265  Failed to post timeseries data Error Returned -
2017-11-11 19:03:57 +0100             3  Defuncting Connection[/??.???.??.??:????-???, inFlight=??, closed=false] because: [/??.???.??.??:????] Heartbeat query timed out
2017-11-11 19:04:01 +0100            39  Defuncting Connection[/??.???.??.??:????-???, inFlight=?, closed=false] because: [/??.???.??.??:????] Operation timed out
2017-11-11 19:04:01 +0100            12  Error processing jobs: execution of statement failed:All host(s) tried for query failed (tried: /??.???.??.??:???? (com.datastax.driver.core.exceptions.DriverException: Timeout while trying to acquire available connection (you may want to increase the driver number of per-host connections)), /??.???.??.??:???? (com.datastax.driver.core.exceptions.DriverException: Timeout while trying to acquire available connection (you may want to increase the driver number of per-host connections)), /??.???.??.??:???? (com.datastax.driver.core.exceptions.DriverException: Timeout while trying to acquire available connection (you may want to increase the driver number of per-host connections)), /??.???.??.??:???? [only showing errors of first ? hosts, use getErrors() for more details])

Does somebody have an idea what could be the root cause?


问:
How to run an Hyper-V host on a Windows Server 2008 R2 VM on ESXi?
I have a server with ESXi. One of the virtual Machines has a WinSrv 2008 R2 and I want to host Hyper-V on it.

First of all: is it possible? I keep being told that no, it is not, due to hardware requirements, namely hardware enabled virtualization capabilities.

Second of all: if it is possible, how can I configure my VM to do so?

Thanks in advance!

答:
Running a VM inside a VM is usually not possible due to hardware limitations.  The exception is "pure emulation" implementation (like Bochs).   But even when it is possible, it is not recommended due to severe performance degradation.

Hyper-V requires a CPU that supports hardware-assisted virtualization.  Comercial hypervisors like ESXi do not emulate the CPU features that are required for Hyper-V.

ContentLicense: CC BY-SA 2.5


问:
Android: SQLite part or full word search not working using SELECT query
I have 10 movie names in SQLite database. I am searching in the database using SearchView and storing result data into ArrayList and then displaying in custom ListView.
The problem is, it works sometimes only. For example, when I search for "the god" or "god" it returns "The Godfather" but when I search for "the shaw" or "shaw" it doesn't return "The Shawshank Redemption". Also, when searching "the" it returns all the movie names starting with "the" like The Godfather, The good, bad and the ugly, the Shawshank redemption etc. I have the below code. Also "Not found" toast is never getting triggered.

SearchActivity.java

```<code>            searchView = findViewById(R.id.searchBar);
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {

                    myDB = new DatabaseHelper(SearchActivity.this);

                    data = myDB.searchRecord(query);//Sends search term to database helper which returns all data found according to the search term

                    if (data==null){
                        Toasty.error(SearchActivity.this, "Not found", Toast.LENGTH_SHORT, true);
                    }else {
                        searchResultMethod();//Calling method which stores curser data in arraylist
                    }
            return false;
            }

        private void searchResultMethod() {
            if(data == null)
            {
                Toast toastem = Toasty.warning(SearchActivity.this, "Database is empty", Toast.LENGTH_SHORT, true);
                toastem.show();
             }else{
                while(data.moveToNext())
                {
                    arrayListTitle.add(data.getString(1));
                    arrayListYear.add(data.getString(2));
                    arrayListRating.add(data.getString(3));
                    arrayListThumb.add(data.getString(4));
                    arrayListUrl.add(data.getString(5));
                 }
        }
         CustomSearchListAdapter customSearchListAdapter = new CustomSearchListAdapter(SearchActivity.this,arrayListTitle, arrayListYear, arrayListRating, arrayListThumb, arrayListUrl);

    searchListView.setAdapter(customSearchListAdapter);
    searchListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Intent webActivityIntent = new Intent(SearchActivity.this, WebViewActivity.class);
                                            webActivityIntent.putExtra("url_list",arrayListUrl);//Sending imdb url to web view activity
                                            webActivityIntent.putExtra("position",i);
                                            startActivity(webActivityIntent);

   }
 });

}
</code>```

searchRecord() method in DatabaseHelper.java

```<code>public Cursor searchRecord(String searchTerm)
{
    db = this.getReadableDatabase();
    String query ="SELECT  *  FROM " + TABLE_NAME + " WHERE title LIKE '%" + searchTerm + "%' OR '" + searchTerm + "%' OR '%" + searchTerm + "'";

    Cursor c = db.rawQuery(query, null);

    if (c == null) {
        return null;
    } else if (!c.moveToFirst()) {
        c.close();
        return null;
    }

    return c;
}
</code>```

I can not figure out what I am doing wrong. Any help is appreciated.

答:
I am not sure but this should be enough for you,</p>

```<code>String query ="SELECT  *  FROM " + TABLE_NAME + " WHERE title LIKE '%" + searchTerm + "%';
</code>```

Body:
I have 10 movie names in SQLite database. I am searching in the database using SearchView and storing result data into ArrayList and then displaying in custom ListView.
The problem is, it works sometimes only. For example, when I search for "the god" or "god" it returns "The Godfather" but when I search for "the shaw" or "shaw" it doesn't return "The Shawshank Redemption". Also, when searching "the" it returns all the movie names starting with "the" like The Godfather, The good, bad and the ugly, the Shawshank redemption etc. I have the below code. Also "Not found" toast is never getting triggered.

SearchActivity.java

            searchView = findViewById(R.id.searchBar);
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {

                    myDB = new DatabaseHelper(SearchActivity.this);

                    data = myDB.searchRecord(query);//Sends search term to database helper which returns all data found according to the search term

                    if (data==null){
                        Toasty.error(SearchActivity.this, "Not found", Toast.LENGTH_SHORT, true);
                    }else {
                        searchResultMethod();//Calling method which stores curser data in arraylist
                    }
            return false;
            }

        private void searchResultMethod() {
            if(data == null)
            {
                Toast toastem = Toasty.warning(SearchActivity.this, "Database is empty", Toast.LENGTH_SHORT, true);
                toastem.show();
             }else{
                while(data.moveToNext())
                {
                    arrayListTitle.add(data.getString(1));
                    arrayListYear.add(data.getString(2));
                    arrayListRating.add(data.getString(3));
                    arrayListThumb.add(data.getString(4));
                    arrayListUrl.add(data.getString(5));
                 }
        }
         CustomSearchListAdapter customSearchListAdapter = new CustomSearchListAdapter(SearchActivity.this,arrayListTitle, arrayListYear, arrayListRating, arrayListThumb, arrayListUrl);

    searchListView.setAdapter(customSearchListAdapter);
    searchListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Intent webActivityIntent = new Intent(SearchActivity.this, WebViewActivity.class);
                                            webActivityIntent.putExtra("url_list",arrayListUrl);//Sending imdb url to web view activity
                                            webActivityIntent.putExtra("position",i);
                                            startActivity(webActivityIntent);

   }
 });

}

searchRecord() method in DatabaseHelper.java

public Cursor searchRecord(String searchTerm)
{
    db = this.getReadableDatabase();
    String query ="SELECT  *  FROM " + TABLE_NAME + " WHERE title LIKE '%" + searchTerm + "%' OR '" + searchTerm + "%' OR '%" + searchTerm + "'";

    Cursor c = db.rawQuery(query, null);

    if (c == null) {
        return null;
    } else if (!c.moveToFirst()) {
        c.close();
        return null;
    }

    return c;
}

I can not figure out what I am doing wrong. Any help is appreciated.

Body:
I am not sure but this should be enough for you,

String query ="SELECT  *  FROM " + TABLE_NAME + " WHERE title LIKE '%" + searchTerm + "%';


问:
How to migrate from bower to npm
I am working with jhipster project, in this both bower and npm are used.

Now we have to deprecate use of bower. Move to npm packages.

How can I move bower to npm with npm, not Yarn or other commands?

答:
There are many blog articles and even tools about it as this part is not related to JHipster.
The only JHipster part is build process using gulp and bower for injecting bower_components into index.html (see gulp/inject.js) which relies on main-bower-files.

Moving away from gulp to webpack is probably much more work.

Title: How to migrate from bower to npm


问:
How to split an XML file using XSLT 2.0 in Python
I have an XML file which I want to split into multiple XML by processing it through xslt 2.0 file. How do I do it? I am currently using Python 2.7.6.  I have tried to use the following code:

```<code>import lxml.etree as ET

dom = ET.parse(xml_filename)
xslt = ET.parse(xsl_filename)
transform = ET.XSLT(xslt)
newdom = transform(dom)
print(ET.tostring(newdom, pretty_print=True))
</code>```

But this returns None.

Example XML File

```<code><?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <name>dataset containing bounding box labels on images</name>
    <comment>created by BBTag</comment>
    <tags>
        <tag name="Perimeter-SVT" color="#f9e99c"/>
        <tag name="Perimeter-Vivon" color="#032585"/>
        <tag name="ScoreBoard-Vivon" color="#bf5786"/>
        <tag name="Perimeter-StarSports" color="#12dadd"/>
    </tags>
    <images>
        <image file="/var/www/html/tamsports.com/resources/videos/STAR_SPORTS_2_20170812/STAR_SPORTS_2_20170812-0011.jpg">
            <box top="505" left="327" width="56" height="29">
                <label>ScoreBoard-Vivon</label>
            </box>
            <box top="218" left="387" width="67" height="24">
                <label>Perimeter-SVT</label>
            </box>
        </image>
        <image file="/var/www/html/tamsports.com/resources/videos/STAR_SPORTS_2_20170812/STAR_SPORTS_2_20170812-0005.jpg">
            <box top="254" left="159" width="64" height="23">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="255" left="225" width="61" height="20">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="254" left="285" width="63" height="23">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="253" left="357" width="58" height="24">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="254" left="424" width="56" height="25">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="256" left="484" width="65" height="23">
                <label>Perimeter-Vivon</label>
            </box>
            <box top="507" left="326" width="58" height="26">
                <label>ScoreBoard-Vivon</label>
            </box>
        </image>
        <image file="/var/www/html/tamsports.com/resources/videos/STAR_SPORTS_2_20170812/STAR_SPORTS_2_20170812-0009.jpg">
            <box top="249" left="400" width="59" height="29">
                <label>Perimeter-StarSports</label>
            </box>
        </image>
    </images>
</dataset>
</code>```

XSLT 2.0 File

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xsl:template match="//dataset/tags">
      <xsl:for-each select="./tag">
            <xsl:variable name="tagName" select="@name" />

                <xsl:result-document method="xml" href="{$tagName}.xml">
                    <dataset>
                        <xsl:copy-of select="/dataset/name"/>
                        <xsl:copy-of select="/dataset/comment"/>
                        <tags>
                            <xsl:copy-of select="/dataset/tags/tag[./@name = $tagName]"/>
                        </tags>
                        <images>
                        <xsl:for-each select="/dataset/images/image[./box/label/text() = $tagName]">
                            <image>
                                <xsl:copy-of select="./@file"/>
                                <xsl:copy-of select="./box[./label[./text() = $tagName]]"/>
                            </image>
                        </xsl:for-each>
                        </images>
                    </dataset>
                </xsl:result-document>
      </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>
</code>```

答:
Python uses libxslt which supports the EXSLT exsl:document http://exslt.org/exsl/index.html:

```<code><?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:exsl="http://exslt.org/common"
    extension-element-prefixes="exsl">
  <xsl:template match="dataset/tags">
    <xsl:for-each select="tag">
      <xsl:variable name="tagName" select="@name" />

      <exsl:document method="xml" href="{$tagName}.xml">
        <dataset>
          <xsl:copy-of select="/dataset/name"/>
          <xsl:copy-of select="/dataset/comment"/>
          <tags>
            <xsl:copy-of select="/dataset/tags/tag[@name = $tagName]"/>
          </tags>
          <images>
            <xsl:for-each select="/dataset/images/image[box/label = $tagName]">
              <image>
                <xsl:copy-of select="@file"/>
                <xsl:copy-of select="box[label = $tagName]"/>
              </image>
            </xsl:for-each>
          </images>
        </dataset>
      </exsl:document>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have an XML file which I want to split into multiple XML by processing it through xslt 2.0 file. How do I do it? I am currently using Python 2.7.6.  I have tried to use the following code:

import lxml.etree as ET

dom = ET.parse(xml_filename)
xslt = ET.parse(xsl_filename)
transform = ET.XSLT(xslt)
newdom = transform(dom)
print(ET.tostring(newdom, pretty_print=True))

But this returns None.

Example XML File

<?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <name>dataset containing bounding box labels on images</name>
    <comment>created by BBTag</comment>
    <tags>
        <tag name="Perimeter-SVT" color="#f9e99c"/>
        <tag name="Perimeter-Vivon" color="#032585"/>
        <tag name="ScoreBoard-Vivon" color="#bf5786"/>
        <tag name="Perimeter-StarSports" color="#12dadd"/>
    </tags>
    <images>
        <image file="/var/www/html/tamsports.com/resources/videos/STAR_SPORTS_2_20170812/STAR_SPORTS_2_20170812-0011.jpg">
            <box top="505" left="327" width="56" height="29">
                ScoreBoard-Vivon
            </box>
            <box top="218" left="387" width="67" height="24">
                Perimeter-SVT
            </box>
        </image>
        <image file="/var/www/html/tamsports.com/resources/videos/STAR_SPORTS_2_20170812/STAR_SPORTS_2_20170812-0005.jpg">
            <box top="254" left="159" width="64" height="23">
                Perimeter-Vivon
            </box>
            <box top="255" left="225" width="61" height="20">
                Perimeter-Vivon
            </box>
            <box top="254" left="285" width="63" height="23">
                Perimeter-Vivon
            </box>
            <box top="253" left="357" width="58" height="24">
                Perimeter-Vivon
            </box>
            <box top="254" left="424" width="56" height="25">
                Perimeter-Vivon
            </box>
            <box top="256" left="484" width="65" height="23">
                Perimeter-Vivon
            </box>
            <box top="507" left="326" width="58" height="26">
                ScoreBoard-Vivon
            </box>
        </image>
        <image file="/var/www/html/tamsports.com/resources/videos/STAR_SPORTS_2_20170812/STAR_SPORTS_2_20170812-0009.jpg">
            <box top="249" left="400" width="59" height="29">
                Perimeter-StarSports
            </box>
        </image>
    </images>
</dataset>

XSLT 2.0 File

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xsl:template match="//dataset/tags">
      <xsl:for-each select="./tag">
            <xsl:variable name="tagName" select="@name" />

                <xsl:result-document method="xml" href="{$tagName}.xml">
                    <dataset>
                        <xsl:copy-of select="/dataset/name"/>
                        <xsl:copy-of select="/dataset/comment"/>
                        <tags>
                            <xsl:copy-of select="/dataset/tags/tag[./@name = $tagName]"/>
                        </tags>
                        <images>
                        <xsl:for-each select="/dataset/images/image[./box/label/text() = $tagName]">
                            <image>
                                <xsl:copy-of select="./@file"/>
                                <xsl:copy-of select="./box[./label[./text() = $tagName]]"/>
                            </image>
                        </xsl:for-each>
                        </images>
                    </dataset>
                </xsl:result-document>
      </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

Body:
Python uses libxslt which supports the EXSLT exsl:document http://exslt.org/exsl/index.html:

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:exsl="http://exslt.org/common"
    extension-element-prefixes="exsl">
  <xsl:template match="dataset/tags">
    <xsl:for-each select="tag">
      <xsl:variable name="tagName" select="@name" />

      <exsl:document method="xml" href="{$tagName}.xml">
        <dataset>
          <xsl:copy-of select="/dataset/name"/>
          <xsl:copy-of select="/dataset/comment"/>
          <tags>
            <xsl:copy-of select="/dataset/tags/tag[@name = $tagName]"/>
          </tags>
          <images>
            <xsl:for-each select="/dataset/images/image[box/label = $tagName]">
              <image>
                <xsl:copy-of select="@file"/>
                <xsl:copy-of select="box[label = $tagName]"/>
              </image>
            </xsl:for-each>
          </images>
        </dataset>
      </exsl:document>
    </xsl:for-each>
  </xsl:template>
</xsl:stylesheet>


问:
What is this method doing? (Arrays and random numbers)
My textbook gave me this code to help count the amount of times a certain number shows up in an array of integers. I tried to apply the code my textbook gave me to my assignment but it doesn't seem to be working. Basically, I have to generate 30 random integers in an array, with the upper bound being 15 and lower bond being -5.

I want to find out how many times a number in the array is equal to 0, 1, 2... all the way until 10. The first code is the one my textbook gave me. They also used a random number generator but instead of finding how many elements is equal to 0, 1, etc, they want to find how many times each number appears. (The scores array is simply the random number generator, and their upper bound is 100). The second code is mine.

```<code>int[] counts = new int [100];
for (int i = 0; i < scores.length; i++) {
int index = scores[i];
counts[index]++;
}

 //This is my code
 public static void main(String[] args) {
    int []a = arrayHist ();
    printArray (a);
}

public static int randomInt (int low, int high) {
    int range = (high - low) +1;
    return (int) (Math.random() * range) + low;

}

public static int[] randomIntArray (int x) {
    int[] random = new int[x];
    for (int i = 0; i< x; i++) {
        random [i] = randomInt (-5, 15);

    }
    return random;
}

public static int[] arrayHist () {
    int[] counts = new int [30];
    int[] hist = randomIntArray (30);
    for (int i = 0; i < 10 && i >= 0; i++) {
        int index = hist[i];
        counts[index]++;
    }
    return hist;
}

public static void printArray (int[] a) {
    for (int i = 0; i < a.length; i++) {
        System.out.println (a[i]);
    }
}
</code>```

I'm supposed to be getting only 11 elements, but instead I get 30 random numbers again. Why is that?

答:
Your arrayHist() method just returns the array with the random numbers. It should be more like this:</p>

```<code>public static int[] arrayHist() {
    // generate array with random numbers
    int[] hist = randomIntArray(30);
    // initialize the array for counting
    int[] counts = new int[11];
    // step through the random numbers array and increase corresponding counter if the number's values is between 0 and 10
    for (int j = 0; j < hist.length; j++) {
        int number = hist[j];
        if (number > -1 && number < 11) {
            counts[number]++;
        }
    }
    return counts;
}
</code>```

Body:
My textbook gave me this code to help count the amount of times a certain number shows up in an array of integers. I tried to apply the code my textbook gave me to my assignment but it doesn't seem to be working. Basically, I have to generate 30 random integers in an array, with the upper bound being 15 and lower bond being -5.

I want to find out how many times a number in the array is equal to 0, 1, 2... all the way until 10. The first code is the one my textbook gave me. They also used a random number generator but instead of finding how many elements is equal to 0, 1, etc, they want to find how many times each number appears. (The scores array is simply the random number generator, and their upper bound is 100). The second code is mine.

int[] counts = new int [100];
for (int i = 0; i < scores.length; i++) {
int index = scores[i];
counts[index]++;
}

 //This is my code
 public static void main(String[] args) {
    int []a = arrayHist ();
    printArray (a);
}

public static int randomInt (int low, int high) {
    int range = (high - low) +1;
    return (int) (Math.random() * range) + low;

}

public static int[] randomIntArray (int x) {
    int[] random = new int[x];
    for (int i = 0; i< x; i++) {
        random [i] = randomInt (-5, 15);

    }
    return random;
}

public static int[] arrayHist () {
    int[] counts = new int [30];
    int[] hist = randomIntArray (30);
    for (int i = 0; i < 10 && i >= 0; i++) {
        int index = hist[i];
        counts[index]++;
    }
    return hist;
}

public static void printArray (int[] a) {
    for (int i = 0; i < a.length; i++) {
        System.out.println (a[i]);
    }
}

I'm supposed to be getting only 11 elements, but instead I get 30 random numbers again. Why is that?

Body:
Your arrayHist() method just returns the array with the random numbers. It should be more like this:

public static int[] arrayHist() {
    // generate array with random numbers
    int[] hist = randomIntArray(30);
    // initialize the array for counting
    int[] counts = new int[11];
    // step through the random numbers array and increase corresponding counter if the number's values is between 0 and 10
    for (int j = 0; j < hist.length; j++) {
        int number = hist[j];
        if (number > -1 && number < 11) {
            counts[number]++;
        }
    }
    return counts;
}


问:
How to create temp table with dynamic SQL query result
I have this stored procedure:

```<code>Declare @MarketID AS NVARCHAR(MAX) = '1.136529848';
Declare @UserID AS NVARCHAR(MAX) = '6a309d84-d1c6-434d-b9df-4f96a74da912';

DECLARE @colsSelect AS NVARCHAR(MAX);
DECLARE @colsTemp AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);

SELECT
    @colsSelect = STUFF((SELECT distinct ',' +
                    '''''' + ' as ' + QUOTENAME(name)
                         FROM RunnersInfoes  AS t
                         WHERE marketID = @MarketID
                         FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') , 1, 1, '');

PRINT @colsSelect

SET @query= ';WITH cte AS
             (
                  SELECT
                      id, ParentId, 0 AS Level, Share, AccountTypeName, FirstName
                  FROM
                      dbo.View_UserProfile
                  WHERE
                      View_UserProfile.id = ' + '''' + @UserID + '''' +'
                  UNION ALL
                  SELECT
                      t.id, t.ParentId, Level + 1 AS Level, t.Share, t.AccountTypeName, t.FirstName
                  FROM
                      View_UserProfile t
                  INNER JOIN
                      cte ON t.ParentId = cte.id
             )
             SELECT
                 ID, AccountTypeName AS Type, FirstName AS Name, ' + @colsSelect + '
             FROM cte AS t'

EXECUTE (@query)
</code>```

and it's generating this result:

I want to create temp table or variable type table for following result , remember the column of this result are dynamically rendered. Sometimes result returns more columns and sometimes with less but first 3 columns remain the same for every result. So kindly help for creating dynamic table inside the stored procedure.

答:
To create a temp table that is filled by a dynamic query, use global temp tables like this example.

For the select ... into ... statement to work, you need to make sure every column from the select has a name.

```<code>declare @query varchar(1000) = 'select 1 as ID, ''test'' as Column_1 into ##mytable'

exec (@Query)

select * from ##mytable

drop table ##mytable
</code>```

Do not forget to drop the temp table when your done.

Body:
I have this stored procedure:

Declare @MarketID AS NVARCHAR(MAX) = '1.136529848';
Declare @UserID AS NVARCHAR(MAX) = '6a309d84-d1c6-434d-b9df-4f96a74da912';

DECLARE @colsSelect AS NVARCHAR(MAX);
DECLARE @colsTemp AS NVARCHAR(MAX);
DECLARE @query AS NVARCHAR(MAX);

SELECT
    @colsSelect = STUFF((SELECT distinct ',' +
                    '''''' + ' as ' + QUOTENAME(name)
                         FROM RunnersInfoes  AS t
                         WHERE marketID = @MarketID
                         FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') , 1, 1, '');

PRINT @colsSelect

SET @query= ';WITH cte AS
             (
                  SELECT
                      id, ParentId, 0 AS Level, Share, AccountTypeName, FirstName
                  FROM
                      dbo.View_UserProfile
                  WHERE
                      View_UserProfile.id = ' + '''' + @UserID + '''' +'
                  UNION ALL
                  SELECT
                      t.id, t.ParentId, Level + 1 AS Level, t.Share, t.AccountTypeName, t.FirstName
                  FROM
                      View_UserProfile t
                  INNER JOIN
                      cte ON t.ParentId = cte.id
             )
             SELECT
                 ID, AccountTypeName AS Type, FirstName AS Name, ' + @colsSelect + '
             FROM cte AS t'

EXECUTE (@query)

and it's generating this result:

I want to create temp table or variable type table for following result , remember the column of this result are dynamically rendered. Sometimes result returns more columns and sometimes with less but first 3 columns remain the same for every result. So kindly help for creating dynamic table inside the stored procedure.

Body:
To create a temp table that is filled by a dynamic query, use global temp tables like this example.

For the select ... into ... statement to work, you need to make sure every column from the select has a name.

declare @query varchar(1000) = 'select 1 as ID, ''test'' as Column_1 into ##mytable'

exec (@Query)

select * from ##mytable

drop table ##mytable

Do not forget to drop the temp table when your done.


问:
EntityFramework nulls FK relationship when saving
In EF6, I load my airport from the DB:

```<code>var existingAirport = db.Airports.SingleOrDefault(a => a.ID == airportID)
//airport is loaded, it has a countryID and virtual Country object
</code>```

I perform some logic which makes some modifications to alter the relationship, changing both the country object and FK ID:

```<code>//it's a bit more complex, but simplified:
existingAirport.Country = //the someOtherCountryObject
existingAirport.CountyID = //the someOtherCountryObject.ID
</code>```

I save the change (which should assign the airport the new country)

```<code>db.SaveChanges();
</code>```

The problem is EF decides to null the relationship in both the DB and memory (existingAirport.Country and existingAirport.CountyID are both now null). The airport is now associated with neither the new or old country.

Can anyone think of a reason EF is doing this? The new FK points to a valid country.

答:
Looks like you are trying to add a new Country and I don't see that your new Country entity is added to the context.

Please refer to these posts to get an idea.
Updating child objects in Entity Framework 6 and Entity Framework 6: Adding child object to parent's list vs. setting child's navigation property to parent

Body:
In EF6, I load my airport from the DB:

var existingAirport = db.Airports.SingleOrDefault(a => a.ID == airportID)
//airport is loaded, it has a countryID and virtual Country object

I perform some logic which makes some modifications to alter the relationship, changing both the country object and FK ID:

//it's a bit more complex, but simplified:
existingAirport.Country = //the someOtherCountryObject
existingAirport.CountyID = //the someOtherCountryObject.ID

I save the change (which should assign the airport the new country)

db.SaveChanges();

The problem is EF decides to null the relationship in both the DB and memory (existingAirport.Country and existingAirport.CountyID are both now null). The airport is now associated with neither the new or old country.

Can anyone think of a reason EF is doing this? The new FK points to a valid country.


问:
How to debug Firefox running from Windows service without ability to set "Allow service to interact with desktop"
I have automated tests setup which runs product tests in 3 browsers on Windows: IE 11, Chrome and Firefox (55.0.3 and 56.0.b7 were tried).
Manual run of tests works fine in all 3 browsers on the particular machine from particular user.

But if to run test using Jenkins slave running as Windows service from the same user, it works just with IE 11 and Chrome but fails with Firefox in the beginning.
Since Firefox is running from Windows service, there is no UI so I can't get what Firefox needs to get working.

I suspect that it hangs on some dialog like "Do you want to make me default browser?".
The particular setting is set to false in about:config for test profile but I was not able to find full list of such dialogs anywhere so I can't be sure that I've switched off all of them.

The main problem is that I can't see the issue: if I enable "Allow service to interact with desktop" for Jenkins slave, it gets working fine. Unfortunately, it is not possible to keep this option on for Jenkins slave since it has to run from particular user and there is no such option for the case.

Any idea how to debug what Firefox needs if you can't see the browser ui?
I've already tried to capture Firefox log using NSPR_LOG_MODULES=all:5 and
NSPR_LOG_FILE=<path-to-log> but did not find any clue in the log.

What else can I do to find the root cause of the issue?
Can I connect to running Firefox remotely to see what it does or waits for?
Can I capture other logs probably?

Some test setup details

Build system is based on Jenkins and the particular step is running via Jenkins slave on Windows 7 machine running as Windows service from particular user.
The tests are node.js scripts which do the following steps:

run local http server to serve test page and resources it uses

run browser to load the page (for Firefox it is the following command line:
<full path to firefox>/firefox.exe -no-remote -profile <full-path-for-prepared-profile> <url-to-test-page>)

wait for http request from browser to confirm that page is
ready to run tests

...

In case of failure the request on step 3 never comes so it looks like Firefox can't load the page due to unknown reason.

答:
After long-long-long investigation my colleague found the root cause and how to fix it (to work it around if to be more precise).

It appeared that in such condition Bug1400637 happens and to work it around in Firefox v57.0 it requires to set security.sandbox.content.level to 4 in about:config.

Also I've learned that in Firefox for issues like this it could be worth to look at about:crashes, it helps to find root causes and even find the solution.


问:
Info needed for an inventory system
I'm building a point of sale for a meat market and need specific information as it relates to how inventory should be tracked. I want to design the database for this system but lack the knowledge needed. I already have a basic database that will handle products but need to implement something additional that will handle the weight of the meats.

There will be bulk inventory such as meat plus products that are sold. Is there anyone here that has some in-depth inventory control experience that can share ideas with me or maybe tell me where I can find this info without having to become an expert on the subject myself?

For example: The store owner purchases 100 lbs of beef brisket on Monday and enters that into his inventory and then on Tuesday purchases an additional 100 lbs from a different vendor at a different price. Both items have their respective ids in the database. If the store owner has for example 10 different vendors selling the exact same product, does that mean that I should store 10 different item ids in the database?

答: A point of concern in inventory system, is basically looking into how to incorporate overheads, labour cost, value-added tax charges (if any) into your inventory, and how do you recognise their cost of sales when a delivery is made. Bitxwise has come out with some neat schema, and artoure put it, understand the accounting policy and tax ruling of your client before you start designing out the tables.   </p>

Title: Info needed for an inventory system


问:
Rmarkdown presentation slide tickers
I am using rmarkdown to make beamer presentations in RStudio. I would want to get slide tickers on the top of presentation. Dresden theme should support those tickersDresden

So is it possible to get those tickers by using rmarkdown? When I knit pdf I get presentation without slide tickers.

Example code:

```<code>---
title: "Example"
output: beamer_presentation
theme: Dresden
---

# R Markdown

This is an R Markdown presentation. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.

When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document.

# Slide with Bullets

- Bullet 1
- Bullet 2
- Bullet 3

# Slide with R Code and Output

```{r}
summary(cars)
```

# Slide with Plot

```{r, echo=FALSE}
plot(cars)
```
</code>```

答:
I think the slide_level option might be what you are looking for:

The slide_level option defines the heading level that defines individual slides. By default this is the highest header level in the hierarchy that is followed immediately by content, and not another header, somewhere in the document. This default can be overridden by specifying an explicit slide_level
  documentation source

For example with the slide_level: 2:

```<code>---
title: "Example"
output:
  beamer_presentation:
    slide_level: 2
theme: Dresden
---
</code>```

gives you the following output

However you need to provide a lower level of the heading for the slide title, e.g.

```<code># R Markdown

## Description
This is an R Markdown presentation. Markdown is a simple formatting
syntax for authoring HTML, PDF, and MS Word documents. For more
details on using R Markdown see <http://rmarkdown.rstudio.com>.

When you click the **Knit** button a document will be generated that
includes both content as well as the output of any embedded R code
chunks within the document.
</code>```

Edit To get the output same as in the image you have attached, you section your presentation in the following way:

```<code>---
title: "Example"
output:
  beamer_presentation:
    slide_level: 3
theme: Dresden
---
# Section 1
## Subsection 1
### Title A
### Title B
## Subsection 2
### Title A
## Subsection 3
### Title A
### Title B
### Title C
# Section 2
## Subsection 1
### Title A
### Title B
</code>```

and the following presentation heading is generated:

Title: Rmarkdown presentation slide tickers

Body:
I am using rmarkdown to make beamer presentations in RStudio. I would want to get slide tickers on the top of presentation. Dresden theme should support those tickersDresden

So is it possible to get those tickers by using rmarkdown? When I knit pdf I get presentation without slide tickers.

Example code:

---
title: "Example"
output: beamer_presentation
theme: Dresden
---

# R Markdown

This is an R Markdown presentation. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.

When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document.

# Slide with Bullets

- Bullet 1
- Bullet 2
- Bullet 3

# Slide with R Code and Output

```{r}
summary(cars)
```

# Slide with Plot

```{r, echo=FALSE}
plot(cars)
```

Body:
I think the slide_level option might be what you are looking for:

The slide_level option defines the heading level that defines individual slides. By default this is the highest header level in the hierarchy that is followed immediately by content, and not another header, somewhere in the document. This default can be overridden by specifying an explicit slide_level
  documentation source

For example with the slide_level: 2:

---
title: "Example"
output:
  beamer_presentation:
    slide_level: 2
theme: Dresden
---

gives you the following output

However you need to provide a lower level of the heading for the slide title, e.g.

# R Markdown

## Description
This is an R Markdown presentation. Markdown is a simple formatting
syntax for authoring HTML, PDF, and MS Word documents. For more
details on using R Markdown see <http://rmarkdown.rstudio.com>.

When you click the **Knit** button a document will be generated that
includes both content as well as the output of any embedded R code
chunks within the document.

Edit To get the output same as in the image you have attached, you section your presentation in the following way:

---
title: "Example"
output:
  beamer_presentation:
    slide_level: 3
theme: Dresden
---
# Section 1
## Subsection 1
### Title A
### Title B
## Subsection 2
### Title A
## Subsection 3
### Title A
### Title B
### Title C
# Section 2
## Subsection 1
### Title A
### Title B

and the following presentation heading is generated:


问:
R ggplot2 : continuous x + colors
I'm trying to create a boxplot using ggplot2 with :

X as a continuous variable

Colors for different groups

Here is an example :

```<code>    x <- sample(c(1,2,5),300,replace = TRUE)
    y <- sapply(x,function(mu) rnorm(1,mean = mu))
    color <- sample(c("color 1","color 2"),300,replace = TRUE)
    data <- data.frame(x, y, color)
</code>```

I can either have colors and x as a factor :

```<code>   ggplot(data = data) + geom_boxplot(aes(x = factor(x),y = y,col = color))
</code>```

or x as a continuous variable and no colors :

```<code>  ggplot(data = data) + geom_boxplot(aes(x = x,y = y,group = x))
</code>```

But not both.
Does somebody know how to do this ?
Thanks

答:
You can use scales to change the x-axis scale.

```<code>library(ggplot2)
library(scales)

x <- sample(c(1,2,5),300,replace = TRUE)
y <- sapply(x,function(mu) rnorm(1,mean = mu))
color <- sample(c("color 1","color 2"),300,replace = TRUE)
data <- data.frame(x, y, color)

ggplot(data = data) + geom_boxplot(aes(x = factor(x),y = y,col = color)) + scale_x_discrete(limit = c('1','2','3','4','5'))
</code>```

Hack for dynamic limits:

```<code>min = min(data$x)

max = max(data$x)

limits <- as.character(seq(min:max))

ggplot(data = data) + geom_boxplot(aes(x = factor(x),y = y,col = color)) + scale_x_discrete(limit = limits)
</code>```

Title: R ggplot2 : continuous x + colors

Body:
I'm trying to create a boxplot using ggplot2 with :

X as a continuous variable

Colors for different groups

Here is an example :

    x <- sample(c(1,2,5),300,replace = TRUE)
    y <- sapply(x,function(mu) rnorm(1,mean = mu))
    color <- sample(c("color 1","color 2"),300,replace = TRUE)
    data <- data.frame(x, y, color)

I can either have colors and x as a factor :

   ggplot(data = data) + geom_boxplot(aes(x = factor(x),y = y,col = color))

or x as a continuous variable and no colors :

  ggplot(data = data) + geom_boxplot(aes(x = x,y = y,group = x))

But not both.
Does somebody know how to do this ?
Thanks

Body:
You can use scales to change the x-axis scale.

library(ggplot2)
library(scales)

x <- sample(c(1,2,5),300,replace = TRUE)
y <- sapply(x,function(mu) rnorm(1,mean = mu))
color <- sample(c("color 1","color 2"),300,replace = TRUE)
data <- data.frame(x, y, color)

ggplot(data = data) + geom_boxplot(aes(x = factor(x),y = y,col = color)) + scale_x_discrete(limit = c('1','2','3','4','5'))

Hack for dynamic limits:

min = min(data$x)

max = max(data$x)

limits <- as.character(seq(min:max))

ggplot(data = data) + geom_boxplot(aes(x = factor(x),y = y,col = color)) + scale_x_discrete(limit = limits)


问:
Fetch only specific objects from JSON via javascript or jQuery
I would like to fetch only specific objects from the below JSON such as only those JSON objects which have a classDefinition = "com.sap.bpm.wfs.UserTask". Please suggest on how to do this:</p>

```<code>var metadata = {
    "contents": {
        "83eaead8-cfae-459b-9bdd-8b12e32d6715": {
            "classDefinition": "com.sap.bpm.wfs.StartEvent",
            "id": "startevent1",
            "name": "StartEvent1"
        },
        "13583ac9-596d-4375-b9e1-e5f6f21e829f": {
            "classDefinition": "com.sap.bpm.wfs.EndEvent",
            "id": "endevent1",
            "name": "EndEvent1"
        },
        "6c2b0935-444b-4299-ac8e-92973ce93558": {
            "classDefinition": "com.sap.bpm.wfs.UserTask",
            "subject": "Upload document",
            "description": "{context.description}",
            "priority": "MEDIUM",
            "isHiddenInLogForParticipant": false,
            "userInterface": "sapui5://html5apps/saptest/com.sap.test",
            "recipientUsers": "I311520, I310811",
            "id": "usertask1",
            "name": "UserTask1"
        },
        "6728bf81-3d4e-4ae3-a428-1700a2096d34": {
            "classDefinition": "com.sap.bpm.wfs.SequenceFlow",
            "id": "sequenceflow1",
            "name": "SequenceFlow1",
            "sourceRef": "83eaead8-cfae-459b-9bdd-8b12e32d6715",
            "targetRef": "6c2b0935-444b-4299-ac8e-92973ce93558"
        },
        "aa99931e-2523-44c3-86b3-d522acdbde10": {
            "classDefinition": "com.sap.bpm.wfs.ui.Diagram",
            "symbols": {
                "760f0725-3400-4d48-b082-5c69ad79d697": {},
                "aa9a0d10-63be-4af8-9ac2-4d2b648a18fc": {},
                "7fbd11bb-cf82-4a27-97d7-e80dda2014ee": {},
                "20c66c48-6058-465e-b500-d69d6e54c028": {},
                "2e8f324c-5361-4512-a09a-fc7693f206ba": {}
            }
        }
    }
};
</code>```

答:
A simple for loop can be used to get the desired fields:</p>

```<code>var temp = [];

for (var index in metadata.contents) {
    if (metadata.contents[index].classDefinition == "com.sap.bpm.wfs.UserTask") {
        temp.push(metadata.contents[index]);
    }
}
</code>```

Body:
I would like to fetch only specific objects from the below JSON such as only those JSON objects which have a classDefinition = "com.sap.bpm.wfs.UserTask". Please suggest on how to do this:

var metadata = {
    "contents": {
        "83eaead8-cfae-459b-9bdd-8b12e32d6715": {
            "classDefinition": "com.sap.bpm.wfs.StartEvent",
            "id": "startevent1",
            "name": "StartEvent1"
        },
        "13583ac9-596d-4375-b9e1-e5f6f21e829f": {
            "classDefinition": "com.sap.bpm.wfs.EndEvent",
            "id": "endevent1",
            "name": "EndEvent1"
        },
        "6c2b0935-444b-4299-ac8e-92973ce93558": {
            "classDefinition": "com.sap.bpm.wfs.UserTask",
            "subject": "Upload document",
            "description": "{context.description}",
            "priority": "MEDIUM",
            "isHiddenInLogForParticipant": false,
            "userInterface": "sapui5://html5apps/saptest/com.sap.test",
            "recipientUsers": "I311520, I310811",
            "id": "usertask1",
            "name": "UserTask1"
        },
        "6728bf81-3d4e-4ae3-a428-1700a2096d34": {
            "classDefinition": "com.sap.bpm.wfs.SequenceFlow",
            "id": "sequenceflow1",
            "name": "SequenceFlow1",
            "sourceRef": "83eaead8-cfae-459b-9bdd-8b12e32d6715",
            "targetRef": "6c2b0935-444b-4299-ac8e-92973ce93558"
        },
        "aa99931e-2523-44c3-86b3-d522acdbde10": {
            "classDefinition": "com.sap.bpm.wfs.ui.Diagram",
            "symbols": {
                "760f0725-3400-4d48-b082-5c69ad79d697": {},
                "aa9a0d10-63be-4af8-9ac2-4d2b648a18fc": {},
                "7fbd11bb-cf82-4a27-97d7-e80dda2014ee": {},
                "20c66c48-6058-465e-b500-d69d6e54c028": {},
                "2e8f324c-5361-4512-a09a-fc7693f206ba": {}
            }
        }
    }
};

Body:
A simple for loop can be used to get the desired fields:

var temp = [];

for (var index in metadata.contents) {
    if (metadata.contents[index].classDefinition == "com.sap.bpm.wfs.UserTask") {
        temp.push(metadata.contents[index]);
    }
}


问:
How to make a spiral rotate?
I have successfully coded a static spiral using lines, and now I'm supposed to make the spiral rotate from frame to frame. I tried incrementing the angle used for the x and y positions of the end of the lines with each frame, but the spiral doesn't move at all.

```<code>void draw() {
    for (int i = 0; i < 15 * NUM_LINES; i++) {
        float lineEndX = width / 2 + radius * cos(angle + startAngle);
        float lineEndY = height / 2 + radius * sin(angle + startAngle);
        line (lineStartX, lineStartY, lineEndX, lineEndY);
        lineStartX = lineEndX;
        lineStartY = lineEndY;

        radius = radius + 0.047;
        angle += 0.01 % (TWO_PI * NUM_TURNS);
    }
    startAngle += START_ANGLE_CHANGE;
    angle = 0;
}
</code>```

答:
Add background(255); to your draw function. Also define lineStartX, lineStartY and radius there so their values are reset every time the function is called.

```<code>void draw() {
    background(255);
    float lineEndX = width / 2;
    float lineEndY = height / 2;
    float radius = 5;

    for (int i = 0; i < 15 * NUM_LINES; i++) {
        float lineEndX = width / 2 + radius * cos(angle + startAngle);
        float lineEndY = height / 2 + radius * sin(angle + startAngle);
        line (lineStartX, lineStartY, lineEndX, lineEndY);
        lineStartX = lineEndX;
        lineStartY = lineEndY;

        radius = radius + 0.047;
        angle += 0.01 % (TWO_PI * NUM_TURNS);
    }
    startAngle += START_ANGLE_CHANGE;
    angle = 0;
}
</code>```

Working example here.

Title: How to make a spiral rotate?

Body:
I have successfully coded a static spiral using lines, and now I'm supposed to make the spiral rotate from frame to frame. I tried incrementing the angle used for the x and y positions of the end of the lines with each frame, but the spiral doesn't move at all.

void draw() {
    for (int i = 0; i < 15 * NUM_LINES; i++) {
        float lineEndX = width / 2 + radius * cos(angle + startAngle);
        float lineEndY = height / 2 + radius * sin(angle + startAngle);
        line (lineStartX, lineStartY, lineEndX, lineEndY);
        lineStartX = lineEndX;
        lineStartY = lineEndY;

        radius = radius + 0.047;
        angle += 0.01 % (TWO_PI * NUM_TURNS);
    }
    startAngle += START_ANGLE_CHANGE;
    angle = 0;
}

Body:
Add background(255); to your draw function. Also define lineStartX, lineStartY and radius there so their values are reset every time the function is called.

void draw() {
    background(255);
    float lineEndX = width / 2;
    float lineEndY = height / 2;
    float radius = 5;

    for (int i = 0; i < 15 * NUM_LINES; i++) {
        float lineEndX = width / 2 + radius * cos(angle + startAngle);
        float lineEndY = height / 2 + radius * sin(angle + startAngle);
        line (lineStartX, lineStartY, lineEndX, lineEndY);
        lineStartX = lineEndX;
        lineStartY = lineEndY;

        radius = radius + 0.047;
        angle += 0.01 % (TWO_PI * NUM_TURNS);
    }
    startAngle += START_ANGLE_CHANGE;
    angle = 0;
}

Working example here.


问:
remove 'Processing' instead of hide
When we start sorting or other things datatables has option to show 'Process' message. All is fine , only when it hides 'Processing' there is still stay space where 'Processing' is placed. So html table jumping down when Processing showing then when data have been loaded Processing hidding but html table isn't jumping back up so there is stay visible place for it.
Question, how to make datatable to remove Processing tag instead of just hide. Thanks

EDIT. I add html code

```<code><div id="search_table_processing" class="dataTables_processing" style="visibility: hidden;">Processing...<img alt="< <" src="/themes/third_party/linkedin_search/img/165.gif"></div>
</code>```

答:
If you want the text to go away while the backdrop should be there, why not just add:

div.dataTables_processing{ color: transparent; }

Title: remove 'Processing' instead of hide

Body:
When we start sorting or other things datatables has option to show 'Process' message. All is fine , only when it hides 'Processing' there is still stay space where 'Processing' is placed. So html table jumping down when Processing showing then when data have been loaded Processing hidding but html table isn't jumping back up so there is stay visible place for it.
Question, how to make datatable to remove Processing tag instead of just hide. Thanks

EDIT. I add html code

Processing...<img alt="< <" src="/themes/third_party/linkedin_search/img/165.gif">


问:
How to iterate over a list of String and change it in RHS in drools
My use case i want to iterate over a List of String and Change the entries that match with the condition in LHS

Here is the json

```<code>{
  "name":[
    "james",
    "harry",
    "potter",
    "james"
    ]
}
</code>```

And Here is my drl

```<code>when
    $names:Names($nameslist:name)
    $value:String()  from $nameslist
    Boolean(booleanValue == true) from $value == "james"
    then
    System.out.println("Pojo Welcome-------");
end
</code>```

My requirement is i want to change list such that
where name is james i want to chnage it into Peter.
How should i do it?

Here is my pojo class

```<code>package pojo_Classes;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"name"
})
public class Assignment1News {

@JsonProperty("name")
private List<String> name = null;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

@JsonProperty("name")
public List<String> getName() {
return name;
}

@JsonProperty("name")
public void setName(List<String> name) {
this.name = name;
}

@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

}
</code>```

My requirement is i want to change list such that
where name is james i want to chnage it into Peter.
How should i do it?

答:
There is no point in avoiding a simple function (or static method) that does the simple work of updating the list.</p>

```<code>rule "james to peter"
when
$names:Names($nlist:name contains "james")
then
  modify( $names ){ setName( replace( $nlist, "james", "peter" ) ); }
end
</code>```

Body:
My use case i want to iterate over a List of String and Change the entries that match with the condition in LHS

Here is the json

{
  "name":[
    "james",
    "harry",
    "potter",
    "james"
    ]
}

And Here is my drl

when
    $names:Names($nameslist:name)
    $value:String()  from $nameslist
    Boolean(booleanValue == true) from $value == "james"
    then
    System.out.println("Pojo Welcome-------");
end

My requirement is i want to change list such that
where name is james i want to chnage it into Peter.
How should i do it?

Here is my pojo class

package pojo_Classes;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"name"
})
public class Assignment1News {

@JsonProperty("name")
private List<String> name = null;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();

@JsonProperty("name")
public List<String> getName() {
return name;
}

@JsonProperty("name")
public void setName(List<String> name) {
this.name = name;
}

@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}

@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}

}

My requirement is i want to change list such that
where name is james i want to chnage it into Peter.
How should i do it?

Body:
There is no point in avoiding a simple function (or static method) that does the simple work of updating the list.

rule "james to peter"
when
$names:Names($nlist:name contains "james")
then
  modify( $names ){ setName( replace( $nlist, "james", "peter" ) ); }
end


问:
Displaying Map Annotation Callouts in a Specific Language
I have an application with Google maps functionality using a MKMapView.

The application's language is Arabic. The application's users won't know English.

Is there any way to display annotation callout information in Arabic?

答:
The map will display in the language of the country it is displaying, often with English (or maybe your local language) as a second language. Open the Maps app on your phone and type in Dubai or Cairo, Egypt, for example, and you'll see Arabic text for cities and streets.

The same is true of other languages. Type Shanghai, China and you'll get Chinese text, Tokyo, Japan and you'll get Japanese text, etc.


问:
Structure of google project in developer console
I am implementing Google Drive API and Google Sheets API to my application. How should I go about structuring the project in Google Developers console?

First I created the Drive connection and Oauth2 for it, then filled the verification request with scopes

https://www.googleapis.com/auth/drive.file

https://www.googleapis.com/auth/userinfo.email

which was verified.

Then I created another Oauth2 for Sheets API and after trying to verify the scopes

https://www.googleapis.com/auth/spreadsheets

But my request got denied with message that I already have https://www.googleapis.com/auth/drive.file scope.

So should I create separate project for each API or use same Oauth2 for both of them?

答:
Each application is a project in Google developer console.  Assuming you are trying to access user data then you should create Oauth2 credentials and request all of the scopes that you will need for the application.

If the application is using

https://www.googleapis.com/auth/drive.file

https://www.googleapis.com/auth/userinfo.email

https://www.googleapis.com/auth/spreadsheets

Then you would need to active all three APIs in the Google Developer console.   However I think that drive.file scope gives you the same access to all the files in Google drive there fore you dont need the spreadsheets scope.

https://www.googleapis.com/auth/drive.file View and manage Google Drive files and folders that you have opened or created with this app

vs

https://www.googleapis.com/auth/spreadsheets   View and manage your spreadsheets in Google Drive


问:
What is fundamental difference between item.Axes.GetDescendants() and item.Axes.selectitems() in sitecore
What is fundamental/Performance difference between item.Axes.GetDescendants() and item.Axes.selectitems() in sitecore?

答:
item.Axes.GetDescendants() get all the descendants of the item using Sitecore API. It calls item.Children, and then for each child again child.Children recursively. And it adds all those items to an array.

item.Axes.Selectitems(string query) executes Sitecore query passed in the argument in the context of the current item.

So those 2 methods are completely different.


问:
Abstract class --> get a new instace of current derived class
Is it possible to get a new instance of the current derived class that is calling a function of the base abstract class? For example:

```<code>class Bar1 : Foo
{

}
class Bar2 : Foo
{

}

abstract class Foo
{
    public Foo CreateAnotherInstance()
    {
        return new Bar1/Bar2();   // depending on the calling derived class
    }
}
</code>```

Should lead to:

```<code>Bar1 bar1 = new Bar1();
Bar2 bar2 = new Bar2();
Foo bar1_2 = bar1.CreateAnotherInstance();  // Should be a new Bar1 instance
Foo bar2_2 = bar1.CreateAnotherInstance();  // Should be a new Bar2 instance
</code>```

The only way i've found is to create the instance is an abstract method, where the instance is created in each derived class like:

```<code>class Bar1 : Foo
{
    public override Foo CreateAnotherInstance()
    {
        return new Bar1();
    }
}

class Bar2 : Foo
{
    public override Foo CreateAnotherInstance()
    {
        return new Bar2();
    }
}

abstract class Foo
{
    public abstract Foo CreateAnotherInstance();
}
</code>```

But in this way, i have to create the method for each derived class.

Is there a simpler solution for this problem available?

答:
Thanks to René Vogt and mjwills for giving the answer:

Using

```<code>(Foo)Activator.CreateInstance(GetType());
</code>```

So change the abstract class to:

```<code>abstract class Foo
{
    public Foo CreateAnotherInstance()
    {
        return (Foo)Activator.CreateInstance(GetType());
    }
}
</code>```

If the constructor isn't parameterless:

```<code>(Foo)Activator.CreateInstance(GetType(), para1, para2, ...);
</code>```

Body:
Is it possible to get a new instance of the current derived class that is calling a function of the base abstract class? For example:

class Bar1 : Foo
{

}
class Bar2 : Foo
{

}

abstract class Foo
{
    public Foo CreateAnotherInstance()
    {
        return new Bar1/Bar2();   // depending on the calling derived class
    }
}

Should lead to:

Bar1 bar1 = new Bar1();
Bar2 bar2 = new Bar2();
Foo bar1_2 = bar1.CreateAnotherInstance();  // Should be a new Bar1 instance
Foo bar2_2 = bar1.CreateAnotherInstance();  // Should be a new Bar2 instance

The only way i've found is to create the instance is an abstract method, where the instance is created in each derived class like:

class Bar1 : Foo
{
    public override Foo CreateAnotherInstance()
    {
        return new Bar1();
    }
}

class Bar2 : Foo
{
    public override Foo CreateAnotherInstance()
    {
        return new Bar2();
    }
}

abstract class Foo
{
    public abstract Foo CreateAnotherInstance();
}

But in this way, i have to create the method for each derived class.

Is there a simpler solution for this problem available?

Body:
Thanks to René Vogt and mjwills for giving the answer:

Using

(Foo)Activator.CreateInstance(GetType());

So change the abstract class to:

abstract class Foo
{
    public Foo CreateAnotherInstance()
    {
        return (Foo)Activator.CreateInstance(GetType());
    }
}

If the constructor isn't parameterless:

(Foo)Activator.CreateInstance(GetType(), para1, para2, ...);


问:
Display different image for different url
I have a WordPress Woocommerce e-shop.

In every product category, I want this to have a different top image.

The Woocommerce category pages are automatically created so I can't edit them individually.

I have managed to find a way to have my own image on top but I want this image to be different for different categories.

So I thought that if I could handle the images displayed inside this by referring to their URL this would solve the problem.
So let's say for URL

```<code>example.com/category/category1
</code>```

display image-1 and so on.

Something like a CSS selector

```<code>div[this-url-1] {background-image:url(.image-1..);}
div[this-ur2] {background-image:url(.image-2..);}
</code>```

答:
You can use this plug in to do what you want.

https://wordpress.org/plugins/woocommerce-category-banner/

This will allow you to use custom images and positions of images for each category.

Body:
I have a WordPress Woocommerce e-shop.

In every product category, I want this to have a different top image.

The Woocommerce category pages are automatically created so I can't edit them individually.

I have managed to find a way to have my own image on top but I want this image to be different for different categories.

So I thought that if I could handle the images displayed inside this by referring to their URL this would solve the problem.
So let's say for URL

example.com/category/category1

display image-1 and so on.

Something like a CSS selector

div[this-url-1] {background-image:url(.image-1..);}
div[this-ur2] {background-image:url(.image-2..);}


问:
Why should a blank final variable be explicitly initialised in all constructors?
I have just started reading Java. One thing I find confusing is that a blank final variable should be initialized in all constructors of a class. If I have a class with 3 constructors and I initialise a blank final variable in one constructor, why do I need to initialise the same blank final variable in other two constructors also ?</p>

答:
The final variable must be initialized by the time an instance of the class is created (i.e. after the constructor execution is done).

If you create an instance of the class using one of the constructors that don't initialize the blank final variable, the final variable won't be initialized once the constructor's execution is done.

Therefore all constructors must initialize the blank final variable.

This is assuming none of the constructors is calling a different constructor using this().

J.L.S Chapter 16. Definite Assignment

Each local variable (§14.4) and every blank final field (§4.12.4, §8.3.1.2) must have a definitely assigned value when any access of its value occurs.

If you create an instance of your class using a constructor that doesn't initialize the blank final field, you might access that field before it was assigned. Therefore the compiler doesn't allow it.


问:
How to use miniclip algorithm in a TIc-Tac-Toe game(X0) php
Hi I am working on a online TIc-Tac-Toe game using the miniclip algorithm to calculate the best move.I found few examples but i really don't understand the miniclips logic.Some example would be great.

Thanks!

答:
For a game with such a small number of possible states as Tic-Tac-Toe, it's quite feasible to just build a tree of all possible game states and have your AI only take branches that don't end in a loss.

Beyond that, I think what you're looking for is called minimax, and there's an article here that explains a variation of it in the context of Tic-Tac-Toe.

OwnerDisplayName: Bill the Lizard


问:
Doctrine migrations fallback
We're using doctrine migrations and there often are problems when the migration contains multiple actions and one of them fails.

For example, if there is a migration adding 5 foreign keys and the 5th of them fails while fields aren't of the same length, fixing the error with the fields and regenerating migrations does not fix the whole thing, while now there is an error connected with the fact 4 of the keys already exists and don't allow the migration to run successfully.

Is there a stable way to use Doctrine migrations without such obvious problems as mentioned? We've used .sql files previosly, which aren't much better actually, but I'm pretty sure there is the right way of database versioning for a Doctrine-using project?

Generating migrations based on the difference between models and schema is great and I'd like to keep this possibility furthermore.

Thanks

答:
Doctrine migrations can not handle this. Sorry to say that we all have these problems, because the migrations didn't run in a transaction.

You can improve this by adding a plugin. See: Blog-Post

The other possibility is to do a database backup before migrating and if something goes wrong you can reinstall the backup. You can automate this by a shell script

Title: Doctrine migrations fallback


问:
ScalaFX/JavaFX Stylesheet is not delegated completely
So I'm trying to add a stylesheet to my scene. That works just fine, until I come to the second layer of the scene. I have the following style.css:

```<code>.label: {
    -fx-font: 16px "Serif";
    -fx-padding: 5;
}

.root {
    -fx-background: cornflowerblue;
    -fx-fill: orchid;
}
</code>```

I managed to attach that to my scene with the following code:

```<code>private val mainLayout = new BorderPane() {...} // stylesheet missing
private val baseLayout = new StackPane() { // root element, has stylesheet
  children.add(mainLayout)
  ...
}
private val scene: Scene = new Scene(baseLayout) {
  stylesheets.add("style.css") // stylesheet works, but I can only style root
}
</code>```

The root styling works as well but if I click through the layers in the Debugger the stylesheet vanishes after the root element. My root is a StackPane and that contains a BorderPane. The BorderPane already doesn't contain the given stylesheet.

What am I missing? Does the stylesheet not delegate through when I add elements later? I'm not using scene builder at the moment because I had some dependency issues with macro extension in scala.

Thanks in advance

Edit

Breaking down the problem: I have my stylesheet styling root and label. I create my scene:

```<code>var label: Label = new Label()
label.setText("Hello World!")
private val root = new StackPane() {
  children.add(label)
}
private val scene: Scene = new Scene(root) {
  stylesheets.add("style.css")
}
</code>```

The root styling works, the label is unchanged.

I'm using the the scalafx library so all my fx types are from this library (scalafx.scene.layout.Label, scalafx.scene.Scene, etc.)

答:
Alright. Sorry. I have found the error: I added a colon after the label tag in the css. I don't have the IDEA ultimate edition so no css support, thats why I didn't notice. Now it works. Correct css should look like this:</p>

```<code>.label {
    -fx-font: 16px "Serif";
    -fx-padding: 5;
}

.root {
    -fx-background: cornflowerblue;
    -fx-fill: orchid;
}
</code>```

Body:
So I'm trying to add a stylesheet to my scene. That works just fine, until I come to the second layer of the scene. I have the following style.css:

.label: {
    -fx-font: 16px "Serif";
    -fx-padding: 5;
}

.root {
    -fx-background: cornflowerblue;
    -fx-fill: orchid;
}

I managed to attach that to my scene with the following code:

private val mainLayout = new BorderPane() {...} // stylesheet missing
private val baseLayout = new StackPane() { // root element, has stylesheet
  children.add(mainLayout)
  ...
}
private val scene: Scene = new Scene(baseLayout) {
  stylesheets.add("style.css") // stylesheet works, but I can only style root
}

The root styling works as well but if I click through the layers in the Debugger the stylesheet vanishes after the root element. My root is a StackPane and that contains a BorderPane. The BorderPane already doesn't contain the given stylesheet.

What am I missing? Does the stylesheet not delegate through when I add elements later? I'm not using scene builder at the moment because I had some dependency issues with macro extension in scala.

Thanks in advance

Edit

Breaking down the problem: I have my stylesheet styling root and label. I create my scene:

var label: Label = new Label()
label.setText("Hello World!")
private val root = new StackPane() {
  children.add(label)
}
private val scene: Scene = new Scene(root) {
  stylesheets.add("style.css")
}

The root styling works, the label is unchanged.

I'm using the the scalafx library so all my fx types are from this library (scalafx.scene.layout.Label, scalafx.scene.Scene, etc.)

Body:
Alright. Sorry. I have found the error: I added a colon after the label tag in the css. I don't have the IDEA ultimate edition so no css support, thats why I didn't notice. Now it works. Correct css should look like this:

.label {
    -fx-font: 16px "Serif";
    -fx-padding: 5;
}

.root {
    -fx-background: cornflowerblue;
    -fx-fill: orchid;
}