问:
hbase rest api start error
I am trying to start the rest API on our hbase installation but keep getting the following error, even when specifying the port.</p>

```<code> # hbase rest start --p 8087

java.net.BindException: Port in use: 0.0.0.0:8085

at
org.apache.hadoop.hbase.http.HttpServer.openListeners(HttpServer.java:1014)
    at org.apache.hadoop.hbase.http.HttpServer.start(HttpServer.java:950)
    at org.apache.hadoop.hbase.http.InfoServer.start(InfoServer.java:90)
    at org.apache.hadoop.hbase.rest.RESTServer.main(RESTServer.java:248)
 Caused by: java.net.BindException: Address already in use
    at sun.nio.ch.Net.bind0(Native Method)
    at sun.nio.ch.Net.bind(Net.java:437)
    at sun.nio.ch.Net.bind(Net.java:429)
    at
   sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
    at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
    at

   org.mortbay.jetty.nio.SelectChannelConnector.open(SelectChannel
   Connector.java:216)
    at

 org.apache.hadoop.hbase.http.HttpServer.openListeners(HttpServer.java:1009)
    ... 3 more
</code>```

答:
REST port (--p option) is 8080. 8085 - is port linked as  hbase.rest.info.port (from config).

Use --infoport 8087 argument to modify it.

Title: hbase rest api start error

Body:
I am trying to start the rest API on our hbase installation but keep getting the following error, even when specifying the port.

 # hbase rest start --p 8087

java.net.BindException: Port in use: 0.0.0.0:8085

at
org.apache.hadoop.hbase.http.HttpServer.openListeners(HttpServer.java:1014)
    at org.apache.hadoop.hbase.http.HttpServer.start(HttpServer.java:950)
    at org.apache.hadoop.hbase.http.InfoServer.start(InfoServer.java:90)
    at org.apache.hadoop.hbase.rest.RESTServer.main(RESTServer.java:248)
 Caused by: java.net.BindException: Address already in use
    at sun.nio.ch.Net.bind0(Native Method)
    at sun.nio.ch.Net.bind(Net.java:437)
    at sun.nio.ch.Net.bind(Net.java:429)
    at
   sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:223)
    at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:74)
    at

   org.mortbay.jetty.nio.SelectChannelConnector.open(SelectChannel
   Connector.java:216)
    at

 org.apache.hadoop.hbase.http.HttpServer.openListeners(HttpServer.java:1009)
    ... 3 more


来源: stackexchange

问:
Passing string in angular directive
I have an angular directive:

```<code>angular.module("App").directive("myButtons", function () {
    return {
        restrict: "E",
        scope:
            {
                teststring: '@'
            },
        templateUrl: "test.html"
    }
});
</code>```

with the following template:

```<code><div>
    <input type="button" onclick="teststring" value="Hi" />
</div>
</code>```

This is the directive in the HTML:

```<code><my-buttons teststring="Whatsup" />
</code>```

I want the value that I pass into teststring to appear in the rendered html.

At the moment I just get onclick="teststring".

What am I doing wrong. I've tried added {{ }} on the template and also @, = and & on the scope value.

答:
you can use ng-bind-html to set up the html in the js and dynamically render to the DOM

change the template to this

And add a link function to the directive like this

```<code> angular.module("app").directive("myButtons", function($sce) {
     return {
         restrict: "E",
         scope: {
             teststring: '@'
         },
         template: `<div>
                <div ng-bind-html="trust(sampleCode)">
            </div>`,
         link: function(scope) {
             scope.sampleCode = '<input type="button" onclick="' + scope.teststring + '" value="Hi" />';

             scope.trust = function(html) {
                 return $sce.trustAsHtml(html);
             }
         }
     }
 });
</code>```

also, inject the $sce as a service to the directive

Demo

angular.module("app",[])
.controller("ctrl",function($scope){

})
 angular.module("app").directive("myButtons", function($sce) {
 return {
     restrict: "E",
     scope: {
         teststring: '@'
     },
     template: `

`,
     link: function(scope) {
         scope.sampleCode = '<input type="button" onclick="' + scope.teststring + '" value="Hi" />';

         scope.trust = function(html) {
             return $sce.trustAsHtml(html);
         }
     }
 }
 });```
<pre class="snippet-code-css lang-css prettyprint-override"><code> </code>```

 <my-buttons teststring="Whatsup" />

```

ContentLicense: CC BY-SA 3.0

Title: Passing string in angular directive

Body:
I have an angular directive:

angular.module("App").directive("myButtons", function () {
    return {
        restrict: "E",
        scope:
            {
                teststring: '@'
            },
        templateUrl: "test.html"
    }
});

with the following template:

    <input type="button" onclick="teststring" value="Hi" />

This is the directive in the HTML:

<my-buttons teststring="Whatsup" />

I want the value that I pass into teststring to appear in the rendered html.

At the moment I just get onclick="teststring".

What am I doing wrong. I've tried added {{ }} on the template and also @, = and & on the scope value.

Body:
you can use ng-bind-html to set up the html in the js and dynamically render to the DOM

change the template to this

And add a link function to the directive like this

 angular.module("app").directive("myButtons", function($sce) {
     return {
         restrict: "E",
         scope: {
             teststring: '@'
         },
         template: `<div>
                <div ng-bind-html="trust(sampleCode)">
            </div>`,
         link: function(scope) {
             scope.sampleCode = '<input type="button" onclick="' + scope.teststring + '" value="Hi" />';

             scope.trust = function(html) {
                 return $sce.trustAsHtml(html);
             }
         }
     }
 });

also, inject the $sce as a service to the directive

Demo

angular.module("app",[])
.controller("ctrl",function($scope){

})
 angular.module("app").directive("myButtons", function($sce) {
 return {
     restrict: "E",
     scope: {
         teststring: '@'
     },
     template: `<div>
            <div ng-bind-html="trust(sampleCode)">
        </div>`,
     link: function(scope) {
         scope.sampleCode = '<input type="button" onclick="' + scope.teststring + '" value="Hi" />';

         scope.trust = function(html) {
             return $sce.trustAsHtml(html);
         }
     }
 }
 });

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
 <my-buttons teststring="Whatsup" />
</div>


问:
Is @$array['possibly_missing_key'] an anti-pattern?
Is it OK to use @ when extracting a possibly missing value from a PHP array? Example:

```<code>$value = @$array['possibly_missing_key'];
</code>```

The intended behavior:

```<code>if (isset($array['possibly_missing_key'])) {
    $value = $array['possibly_missing_key'];
} else {
    $value = null;
}
</code>```

I want to know, before spreading the usage pattern.

答:
The second block of code (or Mark Baker's alternative which will work exactly the same) is better. I'm not entirely sure about PHP, but in many other programming languages, to simply ignore a variable would almost definitely throw an error. At least with the second block you are initializing the variable to some value or memory location.

Error suppression should be more commonly used if you expect a function to throw an expected error in the end-product (however, much of the time this will not be the case).

Good luck!

Dennis M.

ContentLicense: CC BY-SA 2.5

Body:
Is it OK to use @ when extracting a possibly missing value from a PHP array? Example:

$value = @$array['possibly_missing_key'];

The intended behavior:

if (isset($array['possibly_missing_key'])) {
    $value = $array['possibly_missing_key'];
} else {
    $value = null;
}

I want to know, before spreading the usage pattern.


问:
Javascript get HTML of selected text nodes
I got the following HTML:

```<code><div id="editable_phrase">
   <span data-id="42">My</span>
   <span data-id="43">very</span>
   <span data-id="1">first</span>
   <span data-id="21">phrase</span>
</div>
</code>```

and I need to get the data-id attributes when I select (highlight) with a mouse these words. I use the following code:

```<code>var data = window.getSelection().getRangeAt(0).cloneContents();//this gets the data for all selected words
console.log(data);
</code>```

It works fine except that when I select last word phrase, it selects only text without html contents. Any ideas how to fix that? I can use jQuery.

If I select 2 or 3 words, I need to get their data-ids respectively to each word, as it is with getRangeAt(0).cloneContents(). The problem is only with the last word, which does not return HTML code.

Thank you.

答:
    My
    very
    first
    phrase

```

Body:
I got the following HTML:

   My
   very
   first
   phrase

and I need to get the data-id attributes when I select (highlight) with a mouse these words. I use the following code:

var data = window.getSelection().getRangeAt(0).cloneContents();//this gets the data for all selected words
console.log(data);

It works fine except that when I select last word phrase, it selects only text without html contents. Any ideas how to fix that? I can use jQuery.

If I select 2 or 3 words, I need to get their data-ids respectively to each word, as it is with getRangeAt(0).cloneContents(). The problem is only with the last word, which does not return HTML code.

Thank you.

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

<div id="editable_phrase">
    <span data-id="42">My</span>
    <span data-id="43">very</span>
    <span data-id="1">first</span>
    <span data-id="21">phrase</span>
</div>
<script>
    $('#editable_phrase').on('click','span',function(){
        var res = $(this).attr('data-id');
        alert(res);
    })
</script>


问:
add custom string helpers in wiremock
I need to add custom helper functions in wiremock which generates a string as per input value in query string.
Need to add multiple functions.
looking for working sample on this.</p>

答:
```<code>//I am able to get the sample code working
            Helper<String> serialNumberHelper = new Helper<String>() {
                // @Override    Helper<String> stringLengthHelper = new Helper<String>() {
                    // @Override
                    public Object apply(String context, Options options)
                            throws IOException {
                        return context.length();
                    }
                };
                public Object apply(String context, Options options)
                        throws IOException {
                    return context.substring(2);
                }
            };

            Map<String, Helper> helpers = new HashMap<String, Helper>();
            helpers.put("GetLength", stringLengthHelper);
            helpers.put("GetSerialNumber", serialNumberHelper);

            wireMockServer = new WireMockServer(
                    wireMockConfig().port(8080).options().extensions(
                            new ResponseTemplateTransformer(false, helpers)));
// and able to use the same in response.

            wireMockServer
                    .stubFor(get(urlMatching("/vis/([a-z]*)\\?unitid=([0-9]*)"))
                            .willReturn(aResponse()
                                    .withHeader("Content-Type", "text/plain")
                                    .withBody(
                                            "{{GetSerialNumber request.query.unitid.[0]}}")
                                    .withTransformers("response-template")));
</code>```

Title: add custom string helpers in wiremock


问:
Two way binding will work in index.html in angular 4?
Is two way binding work in index.html? I have some links and meta info in index.html. How can we set head parameters in component

```<code><head>
<meta name="og:title" content={{titleValue}}>
<meta name="og:url" content={{urlValue}}>
<script src="{{scriptLink}}" type="text/javascript"></script>
</head>
</code>```

will this approach work ? I dint find any info like this.

答: No, it will not work. Angular process templates starting from the root component which is defined in the module you bootstrap the application with. I looks for this component element inside  tag of index.html. The bindings will only work for views defined for templates of child components of the root component.

Body:
Is two way binding work in index.html? I have some links and meta info in index.html. How can we set head parameters in component

<meta name="og:title" content={{titleValue}}>
<meta name="og:url" content={{urlValue}}>

will this approach work ? I dint find any info like this.

Body: No, it will not work. Angular process templates starting from the root component which is defined in the module you bootstrap the application with. I looks for this component element inside <body> tag of index.html. The bindings will only work for views defined for templates of child components of the root component.


问:
Getting hidden inputs fields and can't even get the page source with selenium and BeautifulSoup
I am trying to get page source. so, i can make query with post requests and retrieve data from result. but, initially i don't even get page source.

```<code>from selenium import webdriver
from bs4 import BeautifulSoup

browser=webdriver.Firefox()

browser.get('url.aspx')

soup=BeautifulSoup(browser.page_source)

print soup.prettify()
</code>```

i am getting following page source:

```<code>...
</script>
  <noscript>
   Please enable JavaScript to view the page content.
  </noscript>
 </head>
 <body onload="challenge()">
  <form action="/corpweb/CorpSearch/CorpSearch.aspx" method="POST">
   <input name="TS019ab495_id" type="hidden" value="3"/>
   <input name="TS019ab495_cr" type="hidden"
value="c4fb95a11ceaf83e82fc10400957ab7c:yvyz:a9qeoPYm:1996871542"/>
   <input name="TS019ab495_76" type="hidden" value="0"/>
   <input name="TS019ab495_md" type="hidden" value="1"/>
   <input name="TS019ab495_rf" type="hidden" value="0"/>
   <input name="TS019ab495_ct" type="hidden" value="0"/>
   <input name="TS019ab495_pd" type="hidden" value="0"/>
  </form>
 </body>
</html>
</code>```

答:
```<code>from selenium import webdriver
from bs4 import BeautifulSoup
import time

profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override", "Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0")
profile.set_preference("javascript.enabled", True)
broswer = webdriver.Firefox(profile)
broswer.get('http://corp.sec.state.ma.us/corpweb/CorpSearch/CorpSearch.aspx')
time.sleep(5)

print(broswer.page_source)
</code>```

try this, hope it will solve the javascript problem

Body:
I am trying to get page source. so, i can make query with post requests and retrieve data from result. but, initially i don't even get page source.

from selenium import webdriver
from bs4 import BeautifulSoup

browser=webdriver.Firefox()

browser.get('url.aspx')

soup=BeautifulSoup(browser.page_source)

print soup.prettify()

i am getting following page source:

...
</script>

   Please enable JavaScript to view the page content.

  <form action="/corpweb/CorpSearch/CorpSearch.aspx" method="POST">
   <input name="TS019ab495_id" type="hidden" value="3"/>
   <input name="TS019ab495_cr" type="hidden"
value="c4fb95a11ceaf83e82fc10400957ab7c:yvyz:a9qeoPYm:1996871542"/>
   <input name="TS019ab495_76" type="hidden" value="0"/>
   <input name="TS019ab495_md" type="hidden" value="1"/>
   <input name="TS019ab495_rf" type="hidden" value="0"/>
   <input name="TS019ab495_ct" type="hidden" value="0"/>
   <input name="TS019ab495_pd" type="hidden" value="0"/>
  </form>

Body:
from selenium import webdriver
from bs4 import BeautifulSoup
import time

profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override", "Mozilla/5.0 (X11; Linux x86_64; rv:38.0) Gecko/20100101 Firefox/38.0")
profile.set_preference("javascript.enabled", True)
broswer = webdriver.Firefox(profile)
broswer.get('http://corp.sec.state.ma.us/corpweb/CorpSearch/CorpSearch.aspx')
time.sleep(5)

print(broswer.page_source)

try this, hope it will solve the javascript problem


问:
Regex - Match URL Paths that contain a trailing /
I am trying to match on any incoming requests that don't have a trailing slash. I also want to capture the URL path, to use in a capture group.  Here is what I've gotten so far.

Incoming URL:   http://www.example.com/path/to/

Regex:  http:\/\/www.example.com\/(.*)[.\/]

Here's a link to the regex tester results

This captures what I want, but it always matches on all URLs - not the URLs that don't contain a trailing slash.

The regex processor is PERL based.

What do I need to change?

答:
You want a not-capture group at the end and match line start/end like this

^http:\/\/www.example.com\/(.*)[^\/]$ (replace "match period or /" [.\/] with "not /" [^\/], and surround with ^$)

(You where so close!)

Add s? to make https? to allow an optional s if you don't care which protocol is being used.


问:
group by date of timestamp
How can you group by a the date portion of a timestamp column in mysql and still take advantage of an index on that ?

Of course you can use solutions like

```<code>select date(thetime) from mytable group by date(thetime)
</code>```

however this query will not be able to use an index on thetime but will instead require a temporary table as you are transforming the column using a function before grouping by it.

```<code>+----+-------------+-------------+-------+---------------+-------------+---------+------+-------+----------------------------------------------+
| id | select_type | table       | type  | possible_keys | key         | key_len | ref  | rows  | Extra                                        |
+----+-------------+-------------+-------+---------------+-------------+---------+------+-------+----------------------------------------------+
|  1 | SIMPLE      | mytable     | index | NULL          | thetime     | 4       | NULL | 48183 | Using index; Using temporary; Using filesort |
+----+-------------+-------------+-------+---------------+-------------+---------+------+-------+----------------------------------------------+
</code>```

Theoretically there's no reason why it shouldn't be able to use a range scan on an index on that column and not need a temporary table. Is there any syntax that can persuade the query optimizer to execute the query to do that?

答:
From what I can understand the database already does what you want? The index is being scanned (rather than the table itself) as evident in xplan.

But you cannot get around the fact that an intermediate table is needed to hold the dates during the grouping (distinct) operation.

Title: group by date of timestamp

Body:
How can you group by a the date portion of a timestamp column in mysql and still take advantage of an index on that ?

Of course you can use solutions like

select date(thetime) from mytable group by date(thetime)

however this query will not be able to use an index on thetime but will instead require a temporary table as you are transforming the column using a function before grouping by it.

+----+-------------+-------------+-------+---------------+-------------+---------+------+-------+----------------------------------------------+
| id | select_type | table       | type  | possible_keys | key         | key_len | ref  | rows  | Extra                                        |
+----+-------------+-------------+-------+---------------+-------------+---------+------+-------+----------------------------------------------+
|  1 | SIMPLE      | mytable     | index | NULL          | thetime     | 4       | NULL | 48183 | Using index; Using temporary; Using filesort |
+----+-------------+-------------+-------+---------------+-------------+---------+------+-------+----------------------------------------------+

Theoretically there's no reason why it shouldn't be able to use a range scan on an index on that column and not need a temporary table. Is there any syntax that can persuade the query optimizer to execute the query to do that?


问:
List Sorting with HTML5 Drag'n'Drop - Drop Above or Below Depending on Mouse

Background

I am working on a sortable list, to avoid having to manually type in sorting order numbers in a database. It works via HTML5's drag'n'drop functionality, i.e. the new drag* events in Javascript.

I currently have it working for the most part. I can click, and drag, and it'll sort itself.

Problem

From what I can tell, the drop, along with the dragstart and dragend events, only are aware of the element they are going into. They can't tell if the mouse is on the top half of the dropzone, or the bottom half.

What I'd like, is when I'm hovering over the top half of a list item, for the dragged content to be placed ABOVE the item. Then if I'm hovering over the bottom half, for the dragged content to be placed BELOW the item.

Currently:

In the screencap below, I show a working (simplified) example of my code. I'm using a border-bottom on the drop target to show that it's the target. Notice how when "Item 1" is above "Item 2", "Item 2" is lit up on the bottom, regardless of if I'm hovering over the top half or bottom half.

Code

var dragging = null;

document.addEventListener('dragstart', function(event) {
  dragging = event.target;
    event.dataTransfer.setData('text/html', dragging);
});

document.addEventListener('dragover', function(event) {
    event.preventDefault();
});

document.addEventListener('dragenter', function(event) {
    event.target.style['border-bottom'] = 'solid 4px blue';
});

document.addEventListener('dragleave', function(event) {
    event.target.style['border-bottom'] = '';
});

document.addEventListener('drop', function(event) {
    event.preventDefault();
    event.target.style['border-bottom'] = '';
    event.target.parentNode.insertBefore(dragging, event.target.nextSibling);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul {
  margin:0;
  padding:0
}
li {
  cursor:move;
  display:block;
  padding:20px 10px;
  background:white;
  border-bottom:solid 1px gray;
}</code>```

List Item 1

List Item 2

List Item 3

List Item 4

List Item 5

List Item 6

List Item 7

List Item 8

List Item 9

List Item 10

```

Question

Is there a way I can have it drop either above or below, not always below, depending on the mouse position while dragging?

答:
Answer

So in a twist of fate, a comment response on another question pointed me to the answer here. wolf-war deserves credit here for pointing me to the right event and method.

Anyway, on to the answer. The solution lies in using the dragover event, rather than using the dragenter event. dragover keeps firing as long as you are hovering.

Code Changes From Question Code

We get rid of the dragenter code:

```<code>document.addEventListener('dragenter', function(event) {
    event.target.style['border-bottom'] = 'solid 4px blue';
});
</code>```

Replace it with:

```<code>document.addEventListener('dragover', function(event) {
    event.preventDefault();
    var bounding = event.target.getBoundingClientRect()
    var offset = bounding.y + (bounding.height/2);
    if ( event.clientY - offset > 0 ) {
        event.target.style['border-bottom'] = 'solid 4px blue';
        event.target.style['border-top'] = '';
    } else {
        event.target.style['border-top'] = 'solid 4px blue';
        event.target.style['border-bottom'] = '';
    }
});
</code>```

Then in the drop section, we check to see which border the drop target has, and use that to insert the dragged content either above or below.

Full Working Code:

var dragging = null;

document.addEventListener('dragstart', function(event) {
    var target = getLI( event.target );
    dragging = target;
    event.dataTransfer.setData('text/plain', null);
    event.dataTransfer.setDragImage(self.dragging,0,0);
});

document.addEventListener('dragover', function(event) {
    event.preventDefault();
    var target = getLI( event.target );
    var bounding = target.getBoundingClientRect()
    var offset = bounding.y + (bounding.height/2);
    if ( event.clientY - offset > 0 ) {
        target.style['border-bottom'] = 'solid 4px blue';
        target.style['border-top'] = '';
    } else {
        target.style['border-top'] = 'solid 4px blue';
        target.style['border-bottom'] = '';
    }
});

document.addEventListener('dragleave', function(event) {
    var target = getLI( event.target );
    target.style['border-bottom'] = '';
    target.style['border-top'] = '';
});

document.addEventListener('drop', function(event) {
    event.preventDefault();
    var target = getLI( event.target );
    if ( target.style['border-bottom'] !== '' ) {
        target.style['border-bottom'] = '';
        target.parentNode.insertBefore(dragging, event.target.nextSibling);
    } else {
        target.style['border-top'] = '';
        target.parentNode.insertBefore(dragging, event.target);
    }
});

function getLI( target ) {
    while ( target.nodeName.toLowerCase() != 'li' && target.nodeName.toLowerCase() != 'body' ) {
        target = target.parentNode;
    }
    if ( target.nodeName.toLowerCase() == 'body' ) {
        return false;
    } else {
        return target;
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul {
  margin:0;
  padding:0
}
li {
  cursor:move;
  display:block;
  padding:20px 10px;
  background:white;
  border-bottom:solid 1px gray;
}</code>```

List Item 1

List Item 2

List Item 3

List Item 4

List Item 5

List Item 6

List Item 7

List Item 8

List Item 9

List Item 10

```

Body:
Background

I am working on a sortable list, to avoid having to manually type in sorting order numbers in a database. It works via HTML5's drag'n'drop functionality, i.e. the new drag* events in Javascript.

I currently have it working for the most part. I can click, and drag, and it'll sort itself.

Problem

From what I can tell, the drop, along with the dragstart and dragend events, only are aware of the element they are going into. They can't tell if the mouse is on the top half of the dropzone, or the bottom half.

What I'd like, is when I'm hovering over the top half of a list item, for the dragged content to be placed ABOVE the item. Then if I'm hovering over the bottom half, for the dragged content to be placed BELOW the item.

Currently:

In the screencap below, I show a working (simplified) example of my code. I'm using a border-bottom on the drop target to show that it's the target. Notice how when "Item 1" is above "Item 2", "Item 2" is lit up on the bottom, regardless of if I'm hovering over the top half or bottom half.

Code

var dragging = null;

document.addEventListener('dragstart', function(event) {
  dragging = event.target;
    event.dataTransfer.setData('text/html', dragging);
});

document.addEventListener('dragover', function(event) {
    event.preventDefault();
});

document.addEventListener('dragenter', function(event) {
    event.target.style['border-bottom'] = 'solid 4px blue';
});

document.addEventListener('dragleave', function(event) {
    event.target.style['border-bottom'] = '';
});

document.addEventListener('drop', function(event) {
    event.preventDefault();
    event.target.style['border-bottom'] = '';
    event.target.parentNode.insertBefore(dragging, event.target.nextSibling);
});

ul {
  margin:0;
  padding:0
}
li {
  cursor:move;
  display:block;
  padding:20px 10px;
  background:white;
  border-bottom:solid 1px gray;
}

List Item 1

List Item 2

List Item 3

List Item 4

List Item 5

List Item 6

List Item 7

List Item 8

List Item 9

List Item 10

Question

Is there a way I can have it drop either above or below, not always below, depending on the mouse position while dragging?

Body:
Answer

So in a twist of fate, a comment response on another question pointed me to the answer here. wolf-war deserves credit here for pointing me to the right event and method.

Anyway, on to the answer. The solution lies in using the dragover event, rather than using the dragenter event. dragover keeps firing as long as you are hovering.

Code Changes From Question Code

We get rid of the dragenter code:

document.addEventListener('dragenter', function(event) {
    event.target.style['border-bottom'] = 'solid 4px blue';
});

Replace it with:

document.addEventListener('dragover', function(event) {
    event.preventDefault();
    var bounding = event.target.getBoundingClientRect()
    var offset = bounding.y + (bounding.height/2);
    if ( event.clientY - offset > 0 ) {
        event.target.style['border-bottom'] = 'solid 4px blue';
        event.target.style['border-top'] = '';
    } else {
        event.target.style['border-top'] = 'solid 4px blue';
        event.target.style['border-bottom'] = '';
    }
});

Then in the drop section, we check to see which border the drop target has, and use that to insert the dragged content either above or below.

Full Working Code:

var dragging = null;

document.addEventListener('dragstart', function(event) {
    var target = getLI( event.target );
    dragging = target;
    event.dataTransfer.setData('text/plain', null);
    event.dataTransfer.setDragImage(self.dragging,0,0);
});

document.addEventListener('dragover', function(event) {
    event.preventDefault();
    var target = getLI( event.target );
    var bounding = target.getBoundingClientRect()
    var offset = bounding.y + (bounding.height/2);
    if ( event.clientY - offset > 0 ) {
        target.style['border-bottom'] = 'solid 4px blue';
        target.style['border-top'] = '';
    } else {
        target.style['border-top'] = 'solid 4px blue';
        target.style['border-bottom'] = '';
    }
});

document.addEventListener('dragleave', function(event) {
    var target = getLI( event.target );
    target.style['border-bottom'] = '';
    target.style['border-top'] = '';
});

document.addEventListener('drop', function(event) {
    event.preventDefault();
    var target = getLI( event.target );
    if ( target.style['border-bottom'] !== '' ) {
        target.style['border-bottom'] = '';
        target.parentNode.insertBefore(dragging, event.target.nextSibling);
    } else {
        target.style['border-top'] = '';
        target.parentNode.insertBefore(dragging, event.target);
    }
});

function getLI( target ) {
    while ( target.nodeName.toLowerCase() != 'li' && target.nodeName.toLowerCase() != 'body' ) {
        target = target.parentNode;
    }
    if ( target.nodeName.toLowerCase() == 'body' ) {
        return false;
    } else {
        return target;
    }
}

ul {
  margin:0;
  padding:0
}
li {
  cursor:move;
  display:block;
  padding:20px 10px;
  background:white;
  border-bottom:solid 1px gray;
}

<ul>
    <li draggable="true">List Item 1</li>
    <li draggable="true">List Item 2</li>
    <li draggable="true">List Item 3</li>
    <li draggable="true">List Item 4</li>
    <li draggable="true">List Item 5</li>
    <li draggable="true">List Item 6</li>
    <li draggable="true">List Item 7</li>
    <li draggable="true">List Item 8</li>
    <li draggable="true">List Item 9</li>
    <li draggable="true">List Item 10</li>
</ul>

ContentLicense: CC BY-SA 4.0


问:
php Get the original key value in in_array multidimensional
I have a multidimensional array with some duplicate sub-arrays:

```<code> $data = array(
    2 => array  (
            'User'      => 'cat',
            'File_name' => 'cat.docx',
            'Document'  => 'Document1',
            'Date'      => '2017-03-02',
            'Pages'     => 1
        ),
    3 => array  (
            'User'      => 'dog',
            'File_name' => 'dog.docx',
            'Document'  => 'Document2',
            'Date'      => '2017-03-02',
            'Pages'     => 3
        ),
    4 => array  (
            'User'      => 'shark',
            'File_name' => 'shark.docx',
            'Document'  => 'Document3',
            'Date'      => '2017-03-01',
            'Pages'     => 5
        ),
    5 => array  (
            'User'      => 'dog',
            'File_name' => 'dog.docx',
            'Document'  => 'Document2',
            'Date'      => '2017-03-02',
            'Pages'     => 3
    ),
    6 => array  (
            'User'      => 'dog',
            'File_name' => 'dog.docx',
            'Document'  => 'Document2',
            'Date'      => '2017-03-02',
            'Pages'     => 3
    ),
    //...
);
</code>```

I could recognize which items are duplicated with:

```<code>$final = $dupli = array();
foreach ($data as $key => $array ) {
    if(!in_array($array, $final)){
        $final[$key] = $array;
    }
    else
    {
        $dupli[$key] = $array;
    }
}
print_r($dupli);
</code>```

But I would like to know what index was the first subarray (the key of this) found, as a message, for example:

```<code> $final = $dupli = array();
    foreach ($data as $key => $array ) {
        if(!in_array($array, $final)){
            $final[$key] = $array;
        }
        else
        {
            $dupli[$key] = $array;
            echo "Line " . $key . " duplicated row, the original row is: " . $originalkey;
        }
    }
</code>```

Output:

```<code>Line 5 duplicated row, the original row is: 3
Line 6 duplicated row, the original row is: 3
</code>```

答:
To find the key that has a specific value, you can use array_search().

So, to fetch the key from the final array, this should do it in your else statement:

```<code>$dupli[$key] = $array;
$originalkey = array_search($array, $final);
echo "Line " . $key . " duplicated row, the original row is: " . $originalkey . "\n";
</code>```

Read more about array_search() in the docs

Body:
I have a multidimensional array with some duplicate sub-arrays:

 $data = array(
    2 => array  (
            'User'      => 'cat',
            'File_name' => 'cat.docx',
            'Document'  => 'Document1',
            'Date'      => '2017-03-02',
            'Pages'     => 1
        ),
    3 => array  (
            'User'      => 'dog',
            'File_name' => 'dog.docx',
            'Document'  => 'Document2',
            'Date'      => '2017-03-02',
            'Pages'     => 3
        ),
    4 => array  (
            'User'      => 'shark',
            'File_name' => 'shark.docx',
            'Document'  => 'Document3',
            'Date'      => '2017-03-01',
            'Pages'     => 5
        ),
    5 => array  (
            'User'      => 'dog',
            'File_name' => 'dog.docx',
            'Document'  => 'Document2',
            'Date'      => '2017-03-02',
            'Pages'     => 3
    ),
    6 => array  (
            'User'      => 'dog',
            'File_name' => 'dog.docx',
            'Document'  => 'Document2',
            'Date'      => '2017-03-02',
            'Pages'     => 3
    ),
    //...
);

I could recognize which items are duplicated with:

$final = $dupli = array();
foreach ($data as $key => $array ) {
    if(!in_array($array, $final)){
        $final[$key] = $array;
    }
    else
    {
        $dupli[$key] = $array;
    }
}
print_r($dupli);

But I would like to know what index was the first subarray (the key of this) found, as a message, for example:

 $final = $dupli = array();
    foreach ($data as $key => $array ) {
        if(!in_array($array, $final)){
            $final[$key] = $array;
        }
        else
        {
            $dupli[$key] = $array;
            echo "Line " . $key . " duplicated row, the original row is: " . $originalkey;
        }
    }

Output:

Line 5 duplicated row, the original row is: 3
Line 6 duplicated row, the original row is: 3

Body:
To find the key that has a specific value, you can use array_search().

So, to fetch the key from the final array, this should do it in your else statement:

$dupli[$key] = $array;
$originalkey = array_search($array, $final);
echo "Line " . $key . " duplicated row, the original row is: " . $originalkey . "\n";

Read more about array_search() in the docs


问:
Why does changing the order of two CSS rules change my results?
Why does changing the order of two CSS rules change my results? When I use this it gives me a border that I do not want. This produces the wrong result that I'm going for:

```<code>.menuBar .navbar-nav > li > a::after, .menuBar .navbar-nav > li.active > a::after {
    background-color: #00c4ff;
    bottom: 0;
    content: "";
    display: block;
    height: 1px;
    left: 0;
    margin: auto 0;
    right: 0;
    top: 0;
    transition: width 1s ease-in-out 0s;
    width: 0;
}
.menuBar .navbar-nav > li > a:hover::after, .menuBar .navbar-nav > li.active > a::after {
    width: 100%;
}
</code>```

But if I just change the order of these two CSS rules, then it gives me right result. So what's happening here?

```<code>.menuBar .navbar-nav > li > a:hover::after, .menuBar .navbar-nav > li.active > a::after {
    width: 100%;
}

.menuBar .navbar-nav > li > a::after, .menuBar .navbar-nav > li.active > a::after {
    background-color: #00c4ff;
    bottom: 0;
    content: "";
    display: block;
    height: 1px;
    left: 0;
    margin: auto 0;
    right: 0;
    top: 0;
    transition: width 1s ease-in-out 0s;
    width: 0;
}
</code>```

This is my markup

```<code><div class="menuBar jumplinks">
                <nav class="navbar navbar-default">
                    <div class="navbar-header">
                        <button aria-expanded="false" data-target="#bs-example-navbar-collapse-1" data-toggle="collapse" class="navbar-toggle collapsed" type="button">
                            <span class="sr-only">Toggle navigation</span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                            <span class="icon-bar"></span>
                        </button>
                    </div>
                    <div id="bs-example-navbar-collapse-1" class="collapse navbar-collapse">
                        <ul class="nav navbar-nav navbar-right">
                            <li class="active"><a href="#home">Home</a></li>
                            <li><a href="#about">About</a></li>
                            <li><a href="#services">Services</a></li>
                            <li><a href="#portfolio">Work</a></li>
                            <li><a href="#pricing">Pricing</a></li>
                            <li><a href="#blog">Blog</a></li>
                            <li><a href="#contact">Contact</a></li>
                        </ul>
                    </div>
                </nav>
            </div>
</code>```

答:
Because both of them contain a setting for width, one changes width to 0;

```<code>.menuBar .navbar-nav > li > a::after, .menuBar .navbar-nav > li.active > a::after {
    background-color: #00c4ff;
    bottom: 0;
    content: "";
    display: block;
    height: 1px;
    left: 0;
    margin: auto 0;
    right: 0;
    top: 0;
    transition: width 1s ease-in-out 0s;
    width: 0; /* <------------------------- THIS LINE */
}
</code>```

And another one changes width to 100%;

```<code>.menuBar .navbar-nav > li > a:hover::after, .menuBar .navbar-nav > li.active > a::after {
    width: 100%; /* <------------------------- THIS LINE */
}
</code>```

The reason the appearance is changing is that it's reading what comes before, then after, linearly down the file. This means when it reads width: 100%; the width property will be 100% but when it gets to width: 0; it changes the width  to 0.

Hope this helps! :)

Body:
Why does changing the order of two CSS rules change my results? When I use this it gives me a border that I do not want. This produces the wrong result that I'm going for:

.menuBar .navbar-nav > li > a::after, .menuBar .navbar-nav > li.active > a::after {
    background-color: #00c4ff;
    bottom: 0;
    content: "";
    display: block;
    height: 1px;
    left: 0;
    margin: auto 0;
    right: 0;
    top: 0;
    transition: width 1s ease-in-out 0s;
    width: 0;
}
.menuBar .navbar-nav > li > a:hover::after, .menuBar .navbar-nav > li.active > a::after {
    width: 100%;
}

But if I just change the order of these two CSS rules, then it gives me right result. So what's happening here?

.menuBar .navbar-nav > li > a:hover::after, .menuBar .navbar-nav > li.active > a::after {
    width: 100%;
}

.menuBar .navbar-nav > li > a::after, .menuBar .navbar-nav > li.active > a::after {
    background-color: #00c4ff;
    bottom: 0;
    content: "";
    display: block;
    height: 1px;
    left: 0;
    margin: auto 0;
    right: 0;
    top: 0;
    transition: width 1s ease-in-out 0s;
    width: 0;
}

This is my markup

                        <button aria-expanded="false" data-target="#bs-example-navbar-collapse-1" data-toggle="collapse" class="navbar-toggle collapsed" type="button">
                            Toggle navigation

                        </button>

Home

About

Services

Work

Pricing

Blog

Contact

Body:
Because both of them contain a setting for width, one changes width to 0;

.menuBar .navbar-nav > li > a::after, .menuBar .navbar-nav > li.active > a::after {
    background-color: #00c4ff;
    bottom: 0;
    content: "";
    display: block;
    height: 1px;
    left: 0;
    margin: auto 0;
    right: 0;
    top: 0;
    transition: width 1s ease-in-out 0s;
    width: 0; /* <------------------------- THIS LINE */
}

And another one changes width to 100%;

.menuBar .navbar-nav > li > a:hover::after, .menuBar .navbar-nav > li.active > a::after {
    width: 100%; /* <------------------------- THIS LINE */
}

The reason the appearance is changing is that it's reading what comes before, then after, linearly down the file. This means when it reads width: 100%; the width property will be 100% but when it gets to width: 0; it changes the width  to 0.

Hope this helps! :)


问:
Error message when persisting entity with EmbbededID in Many To One relationship
I'm developing a project in JSF, and I'm trying to persist this Entity below, but I'm receiving a error message. Before I created the relationship, the Conta class was persisting correctly, but with the Many To One with Transacao, I can't.

This is the Transacao class:

```<code>@Id
@GeneratedValue
private long id;
private Conta contaOrigem;
private String agenciaDestino;
private String contaDestino;
private String cpfDestino;
...
</code>```

This is the Conta class:

```<code>public class Conta {

@EmbeddedId
private DadosConta contaUsuario = new DadosConta();
@NotEmpty(message="Senha não pode estar em branco")
private String senha;
@NotEmpty(message="Selecione uma opção")
private String tipoConta;
private double saldo;
private Usuario usuario = new Usuario();
@OneToMany(mappedBy="contaOrigem", fetch = FetchType.LAZY)
private List<Transacao> transacoes = new ArrayList<>();
...
</code>```

And the DadosConta (Embedded ID class):

```<code>@Embeddable
public class DadosConta implements Serializable {

private static final long serialVersionUID = -7021727065659352073L;
@NotEmpty
private String agencia;
@NotEmpty
private String conta;
...
</code>```

And finally, this is the error:

```<code>Foreign key (FK_8k5jlptboiq6xm4oopg9jnh2l:Transacao [contaOrigem])) must have same number of columns as the referenced primary key (conta [agencia,conta])
</code>```

I know that the error message is "explicit", but I don't know how can I persist this Many to One relationship with EmbeddedId, is there any workaround?

Thanks a lot.

答:
Try this in your Transacao class to complete the bi-directional join.

```<code>@ManyToOne
@JoinColumns({@JoinColumn(name = "agencia"), @JoinColumn(name = "conta")})
private Conta contaOrigem;
</code>```

Body:
I'm developing a project in JSF, and I'm trying to persist this Entity below, but I'm receiving a error message. Before I created the relationship, the Conta class was persisting correctly, but with the Many To One with Transacao, I can't.

This is the Transacao class:

@Id
@GeneratedValue
private long id;
private Conta contaOrigem;
private String agenciaDestino;
private String contaDestino;
private String cpfDestino;
...

This is the Conta class:

public class Conta {

@EmbeddedId
private DadosConta contaUsuario = new DadosConta();
@NotEmpty(message="Senha não pode estar em branco")
private String senha;
@NotEmpty(message="Selecione uma opção")
private String tipoConta;
private double saldo;
private Usuario usuario = new Usuario();
@OneToMany(mappedBy="contaOrigem", fetch = FetchType.LAZY)
private List<Transacao> transacoes = new ArrayList<>();
...

And the DadosConta (Embedded ID class):

@Embeddable
public class DadosConta implements Serializable {

private static final long serialVersionUID = -7021727065659352073L;
@NotEmpty
private String agencia;
@NotEmpty
private String conta;
...

And finally, this is the error:

Foreign key (FK_8k5jlptboiq6xm4oopg9jnh2l:Transacao [contaOrigem])) must have same number of columns as the referenced primary key (conta [agencia,conta])

I know that the error message is "explicit", but I don't know how can I persist this Many to One relationship with EmbeddedId, is there any workaround?

Thanks a lot.

Body:
Try this in your Transacao class to complete the bi-directional join.

@ManyToOne
@JoinColumns({@JoinColumn(name = "agencia"), @JoinColumn(name = "conta")})
private Conta contaOrigem;


问:
SpringBoot: running a multi module project
I have a basic SpringBoot app. using Spring Initializer, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.
is a multi-module project with Spring Boot, the project will have 3 modules.
Here the parent module pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

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

    <groupId>com.tdkcloud</groupId>
    <artifactId>tdk-cloud</artifactId>
    <version>0.0.2-SNAPSHOT</version>
    <packaging>pom</packaging>

    <modules>
        <module>tdk-core</module>
        <module>tdk-batch</module>
        <module>tdk-web</module>
    </modules>

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

        <!-- Test dependencies -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>uk.co.jemos.podam</groupId>
            <artifactId>podam</artifactId>
            <version>7.0.5.RELEASE</version>
            <scope>test</scope>
        </dependency>

        <!-- Logging dependencies -->
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>

        <!-- Email dependencies -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

        <!-- Security dependencies -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

        <!-- Spring data -->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>

    </dependencies>

</project>
</code>```

Here the module core

```<code><?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.tdkcloud</groupId>
        <artifactId>tdk-cloud</artifactId>
        <version>0.0.2-SNAPSHOT</version>
    </parent>

  <groupId>com.tdkcloud.core</groupId>
  <artifactId>tdk-core</artifactId>
   <packaging>jar</packaging>

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

  <dependencies>

        <!--  Hibernate dependencies -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

        <dependency>
            <groupId>com.googlecode.libphonenumber</groupId>
            <artifactId>libphonenumber</artifactId>
            <version>8.4.3</version>
        </dependency>

        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <!-- <version>1.10</version> -->
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <!-- <version>2.9.0.pr3</version> -->
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <!-- <version>2.9.0.pr3</version> -->
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>

        <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>1.9.9</version>
</dependency>

    </dependencies>

</project>
</code>```

and here the module web:

```<code><?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.tdkcloud</groupId>
        <artifactId>tdk-cloud</artifactId>
        <version>0.0.2-SNAPSHOT</version>
    </parent>

  <groupId>com.tdkcloud.web</groupId>
  <artifactId>tdk-web</artifactId>
  <packaging>jar</packaging>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
    <start-class>com.tdkcloud.TdkCloudApplication</start-class>
  </properties>

  <dependencies>

        <!-- tdk-core dependencies -->
         <dependency>
            <groupId>com.tdkcloud.core</groupId>
            <artifactId>tdk-core</artifactId>
            <version>0.0.2-SNAPSHOT</version>
        </dependency>

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

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

        <!-- Webjars for JQuery and Bootstrap -->
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.7-1</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.2.0</version>
        </dependency>

        <!-- Spring Security -->
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>
            <!-- <version>3.0.2.RELEASE</version> -->
        </dependency>

   </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>com.tdkcloud.TdkCloudApplication</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

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

</project>
</code>```

from the parent root I generate all the modules using:

```<code>mvn clean package
</code>```

But the problem is that the tdk-web-0.0.2-SNAPSHOT.jar does not contain the tdk-core-0.0.2-SNAPSHOT.jar and then it fails on the startup

Here the maven result:

```<code>MacBook-Pro-de-nunito:tdk-cloud calzada$ mvn clean package -Dmaven.test.skip=true
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Build Order:
[INFO]
[INFO] tdk-cloud
[INFO] tdk-core
[INFO] tdk-batch
[INFO] tdk-web
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building tdk-cloud 0.0.2-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.6.1:clean (default-clean) @ tdk-cloud ---
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building tdk-core 0.0.2-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[WARNING] The POM for com.h2database:h2:jar:1.4.194 is missing, no dependency information available
[INFO]
[INFO] --- maven-clean-plugin:2.6.1:clean (default-clean) @ tdk-core ---
[INFO] Deleting /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-core/target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ tdk-core ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] Copying 1 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ tdk-core ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 52 source files to /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-core/target/classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ tdk-core ---
[INFO] Not copying test resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ tdk-core ---
[INFO] Not compiling test sources
[INFO]
[INFO] --- maven-surefire-plugin:2.18.1:test (default-test) @ tdk-core ---
[INFO] Tests are skipped.
[INFO]
[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ tdk-core ---
[INFO] Building jar: /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-core/target/tdk-core-0.0.2-SNAPSHOT.jar
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building tdk-batch 0.0.2-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.6.1:clean (default-clean) @ tdk-batch ---
[INFO] Deleting /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-batch/target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ tdk-batch ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-batch/src/main/resources
[INFO] skip non existing resourceDirectory /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-batch/src/main/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ tdk-batch ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-batch/target/classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ tdk-batch ---
[INFO] Not copying test resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ tdk-batch ---
[INFO] Not compiling test sources
[INFO]
[INFO] --- maven-surefire-plugin:2.18.1:test (default-test) @ tdk-batch ---
[INFO] Tests are skipped.
[INFO]
[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ tdk-batch ---
[INFO] Building jar: /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-batch/target/tdk-batch-0.0.2-SNAPSHOT.jar
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building tdk-web 0.0.2-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.6.1:clean (default-clean) @ tdk-web ---
[INFO] Deleting /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-web/target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ tdk-web ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 0 resource
[INFO] Copying 339 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ tdk-web ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 25 source files to /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-web/target/classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ tdk-web ---
[INFO] Not copying test resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ tdk-web ---
[INFO] Not compiling test sources
[INFO]
[INFO] --- maven-surefire-plugin:2.18.1:test (default-test) @ tdk-web ---
[INFO] Tests are skipped.
[INFO]
[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ tdk-web ---
[INFO] Building jar: /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-web/target/tdk-web-0.0.2-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:1.5.3.RELEASE:repackage (default) @ tdk-web ---
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] tdk-cloud ....................................... SUCCESS [  0.105 s]
[INFO] tdk-core ........................................ SUCCESS [  1.634 s]
[INFO] tdk-batch ....................................... SUCCESS [  0.114 s]
[INFO] tdk-web ......................................... SUCCESS [  1.506 s]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.663 s
[INFO] Finished at: 2017-05-30T05:37:04+02:00
[INFO] Final Memory: 47M/539M
[INFO] ------------------------------------------------------------------------
MacBook-Pro-de-nunito:tdk-cloud calzada$
</code>```

This is the error I got:

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Field emailService in com.tdkcloud.web.controllers.AppErrorController required a bean of type 'com.tdkcloud.backend.service.EmailService' that could not be found.

Action:

Consider defining a bean of type 'com.tdkcloud.backend.service.EmailService' in your configuration.
</code>```

I unzipped the jar and there is no class of the core module

adding the proposed code to the module web:

```<code><plugin>
                    <artifactId>maven-dependency-plugin</artifactId>
                    <executions>
                        <execution>
                            <phase>install</phase>
                            <goals>
                                <goal>copy-dependencies</goal>
                            </goals>
                            <configuration>
                                <outputDirectory>${project.build.directory}/lib</outputDirectory>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>
</code>```

I have the next error:  Error resolving template "/tdk/login/login", template might not exist or might not be accessible by any of the configured Template Reso

but the template is there:

答:
I think your @ComponentScan annotation is missing, or maybe wrong. (e.g.: @ComponentScan({"com.tdkcloud.web"}) will not find services in com.tdkcloud.backend package). Or maybe @Service annotation is missing from your EmailService.

So to solve this, your code need to look something like this:

App.java (or Webconfig.java)

```<code>@Configuration
@EnableWebMvc
@ComponentScan({"com.tdkcloud"})
@SpringBootApplication
public class App {
   ...
}
</code>```

EmailService.java

```<code>public interface EmailService {
   ...
}
</code>```

EmailServiceImpl.java

```<code>@Service
public class EmailServiceImpl {
   ...
}
</code>```

Body:
I have a basic SpringBoot app. using Spring Initializer, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.
is a multi-module project with Spring Boot, the project will have 3 modules.
Here the parent module pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

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

    <groupId>com.tdkcloud</groupId>
    <artifactId>tdk-cloud</artifactId>
    <version>0.0.2-SNAPSHOT</version>
    <packaging>pom</packaging>

    <modules>
        <module>tdk-core</module>
        <module>tdk-batch</module>
        <module>tdk-web</module>
    </modules>

    <dependencies>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>uk.co.jemos.podam</groupId>
            <artifactId>podam</artifactId>
            <version>7.0.5.RELEASE</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
        </dependency>

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

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

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>

    </dependencies>

</project>

Here the module core

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.tdkcloud</groupId>
        <artifactId>tdk-cloud</artifactId>
        <version>0.0.2-SNAPSHOT</version>
    </parent>

  <groupId>com.tdkcloud.core</groupId>
  <artifactId>tdk-core</artifactId>
   <packaging>jar</packaging>

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

  <dependencies>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

        <dependency>
            <groupId>com.googlecode.libphonenumber</groupId>
            <artifactId>libphonenumber</artifactId>
            <version>8.4.3</version>
        </dependency>

        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>

        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>

        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>

        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>

        <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>1.9.9</version>
</dependency>

    </dependencies>

</project>

and here the module web:

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

  <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.tdkcloud</groupId>
        <artifactId>tdk-cloud</artifactId>
        <version>0.0.2-SNAPSHOT</version>
    </parent>

  <groupId>com.tdkcloud.web</groupId>
  <artifactId>tdk-web</artifactId>
  <packaging>jar</packaging>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
    <start-class>com.tdkcloud.TdkCloudApplication</start-class>
  </properties>

  <dependencies>

         <dependency>
            <groupId>com.tdkcloud.core</groupId>
            <artifactId>tdk-core</artifactId>
            <version>0.0.2-SNAPSHOT</version>
        </dependency>

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

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

        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>bootstrap</artifactId>
            <version>3.3.7-1</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>jquery</artifactId>
            <version>3.2.0</version>
        </dependency>

        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity4</artifactId>

        </dependency>

   </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>com.tdkcloud.TdkCloudApplication</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

from the parent root I generate all the modules using:

mvn clean package

But the problem is that the tdk-web-0.0.2-SNAPSHOT.jar does not contain the tdk-core-0.0.2-SNAPSHOT.jar and then it fails on the startup

Here the maven result:

MacBook-Pro-de-nunito:tdk-cloud calzada$ mvn clean package -Dmaven.test.skip=true
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Build Order:
[INFO]
[INFO] tdk-cloud
[INFO] tdk-core
[INFO] tdk-batch
[INFO] tdk-web
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building tdk-cloud 0.0.2-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.6.1:clean (default-clean) @ tdk-cloud ---
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building tdk-core 0.0.2-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[WARNING] The POM for com.h2database:h2:jar:1.4.194 is missing, no dependency information available
[INFO]
[INFO] --- maven-clean-plugin:2.6.1:clean (default-clean) @ tdk-core ---
[INFO] Deleting /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-core/target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ tdk-core ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 1 resource
[INFO] Copying 1 resource
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ tdk-core ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 52 source files to /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-core/target/classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ tdk-core ---
[INFO] Not copying test resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ tdk-core ---
[INFO] Not compiling test sources
[INFO]
[INFO] --- maven-surefire-plugin:2.18.1:test (default-test) @ tdk-core ---
[INFO] Tests are skipped.
[INFO]
[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ tdk-core ---
[INFO] Building jar: /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-core/target/tdk-core-0.0.2-SNAPSHOT.jar
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building tdk-batch 0.0.2-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.6.1:clean (default-clean) @ tdk-batch ---
[INFO] Deleting /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-batch/target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ tdk-batch ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-batch/src/main/resources
[INFO] skip non existing resourceDirectory /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-batch/src/main/resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ tdk-batch ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 1 source file to /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-batch/target/classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ tdk-batch ---
[INFO] Not copying test resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ tdk-batch ---
[INFO] Not compiling test sources
[INFO]
[INFO] --- maven-surefire-plugin:2.18.1:test (default-test) @ tdk-batch ---
[INFO] Tests are skipped.
[INFO]
[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ tdk-batch ---
[INFO] Building jar: /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-batch/target/tdk-batch-0.0.2-SNAPSHOT.jar
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building tdk-web 0.0.2-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.6.1:clean (default-clean) @ tdk-web ---
[INFO] Deleting /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-web/target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ tdk-web ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 0 resource
[INFO] Copying 339 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ tdk-web ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 25 source files to /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-web/target/classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ tdk-web ---
[INFO] Not copying test resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ tdk-web ---
[INFO] Not compiling test sources
[INFO]
[INFO] --- maven-surefire-plugin:2.18.1:test (default-test) @ tdk-web ---
[INFO] Tests are skipped.
[INFO]
[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ tdk-web ---
[INFO] Building jar: /Users/calzada/Development/J2EE/workspace-sts-3.8.4.RELEASE/tdk-cloud/tdk-web/target/tdk-web-0.0.2-SNAPSHOT.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:1.5.3.RELEASE:repackage (default) @ tdk-web ---
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary:
[INFO]
[INFO] tdk-cloud ....................................... SUCCESS [  0.105 s]
[INFO] tdk-core ........................................ SUCCESS [  1.634 s]
[INFO] tdk-batch ....................................... SUCCESS [  0.114 s]
[INFO] tdk-web ......................................... SUCCESS [  1.506 s]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.663 s
[INFO] Finished at: 2017-05-30T05:37:04+02:00
[INFO] Final Memory: 47M/539M
[INFO] ------------------------------------------------------------------------
MacBook-Pro-de-nunito:tdk-cloud calzada$

This is the error I got:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field emailService in com.tdkcloud.web.controllers.AppErrorController required a bean of type 'com.tdkcloud.backend.service.EmailService' that could not be found.

Action:

Consider defining a bean of type 'com.tdkcloud.backend.service.EmailService' in your configuration.

I unzipped the jar and there is no class of the core module

adding the proposed code to the module web:

<plugin>
                    <artifactId>maven-dependency-plugin</artifactId>
                    <executions>
                        <execution>
                            <phase>install</phase>
                            <goals>
                                <goal>copy-dependencies</goal>
                            </goals>
                            <configuration>
                                <outputDirectory>${project.build.directory}/lib</outputDirectory>
                            </configuration>
                        </execution>
                    </executions>
                </plugin>

I have the next error:  Error resolving template "/tdk/login/login", template might not exist or might not be accessible by any of the configured Template Reso

but the template is there:

Body:
I think your @ComponentScan annotation is missing, or maybe wrong. (e.g.: @ComponentScan({"com.tdkcloud.web"}) will not find services in com.tdkcloud.backend package). Or maybe @Service annotation is missing from your EmailService.

So to solve this, your code need to look something like this:

App.java (or Webconfig.java)

@Configuration
@EnableWebMvc
@ComponentScan({"com.tdkcloud"})
@SpringBootApplication
public class App {
   ...
}

EmailService.java

public interface EmailService {
   ...
}

EmailServiceImpl.java

@Service
public class EmailServiceImpl {
   ...
}


问:
Does Instance ID service initiate callback onTokenRefresh() on app upgrade?
Does Instance ID service initiate callback onTokenRefresh() on app upgrade?

Reference doc states that
"Tokens are unique and secure, but your app or the Instance ID service may need to refresh tokens in the event of a security issue or when a user uninstalls and reinstalls your app during device restoration. Your app must implement a listener to respond to token refresh requests from the Instance ID service."

Can anyone confirm if token refreshing has to be handled by app or Instance ID service initiates callback onTokenRefresh() on app upgrade?

If its handled by Instance ID service, how is token refresh scenario handled after upgrade if old app uses old library for gcm registration(gcm.register) and new app uses new library(Instance ID)

答:
onTokenRefresh() only triggers for specific reasons, where updating the app isn't one of them. See my answer here.

The link you mentioned in the comments is the deprecated way of generating a registration token (GCM2/waaay old GCM), which is different from InstanceID generated tokens (preFCM and FCM). See Ian Barber's answer here.

I'm not sure what you're asking here. The way I understand the flow is FCM identifies if the token needs to be refreshed, if yes, it calls upon the InstanceID service (separate from the client) to generate a new one. As soon as it generates the token and the app goes online, it would trigger onTokenRefresh() to let you know of the new token. What you do with the token depends on you.

Simple as that. No special scenarios AFAIK.


问:
Chart components for Vaadin
Does anyone knows about any UI component library for data visualization (charts, pies, etc.) for vaadin framework?</p>

答:
Take a search at the Vaadin Directory for options: http://vaadin.com/directory

Or you could embed any other charting library. For example FusionCharts.

Title: Chart components for Vaadin


问:
How show json data with database in symfony
I have a little problem, because I have to show json date with database in Symfony3.

My controller

```<code>/**
     * @Route("/api/rest", name="rest_api")
     *
     *
     * @Template
     */
public function indexAction(Request $Request) {

    $Repo = $this->getDoctrine()->getRepository('CommonUserBundle:Comment');
    $row = $Repo->findAll();

    $data = json_encode($row, true);

    return array(
        'comment' => $data
    );
}
</code>```

And this is my layout in html.twig

```<code>{% for comments in comment %}
           {{ comments }}
{% endfor %}
</code>```

But I don't know why nothing show.
Help me please :)

答:
try this:

```<code>  {% for comments in comment %}
       {{ comment }}
  {% endfor %}
</code>```

If it doesn't work try to change and you want to print an array

```<code>$data = json_encode($row, true);
</code>```

to
 $data = json_decode(json_encode($row), true);

if you want to print the string try this inside your twig

```<code>{{ dump(comments) }}
</code>```

instead of this

```<code>{% for comments in comment %}
       {{ comment }}
  {% endfor %}
</code>```

Body:
I have a little problem, because I have to show json date with database in Symfony3.

My controller

/**
     * @Route("/api/rest", name="rest_api")
     *
     *
     * @Template
     */
public function indexAction(Request $Request) {

    $Repo = $this->getDoctrine()->getRepository('CommonUserBundle:Comment');
    $row = $Repo->findAll();

    $data = json_encode($row, true);

    return array(
        'comment' => $data
    );
}

And this is my layout in html.twig

{% for comments in comment %}
           {{ comments }}
{% endfor %}

But I don't know why nothing show.
Help me please :)

Body:
try this:

  {% for comments in comment %}
       {{ comment }}
  {% endfor %}

If it doesn't work try to change and you want to print an array

$data = json_encode($row, true);

to
 $data = json_decode(json_encode($row), true);

if you want to print the string try this inside your twig

{{ dump(comments) }}

instead of this

{% for comments in comment %}
       {{ comment }}
  {% endfor %}


问:
Short record of if / null
I have the following code:

```<code>decimal? sumFreightAmount = (db.Trips
          .Where(p => p.DateTime.Month == i && p.DateTime.Year == DateTime.Now.Year)
          .Sum(p => p.FreightAmount));

if (sumFreightAmount.HasValue)
{
     // my actions
}
else
{
    sumFreightAmount = 0;
}
</code>```

I can write it the following way:

```<code>decimal sumFreightAmount = (
         db.Trips
           .Where(p => p.DateTime.Month == i && p.DateTime.Year == DateTime.Now.Year)
           .Sum(p => p.FreightAmount) != null)
         ?
         (db.Trips
            .Where(p => p.DateTime.Month == i && p.DateTime.Year == DateTime.Now.Year)
            .Sum(p => p.FreightAmount)) : 0;
</code>```

but in this place I call linq extension twice (and have a long record). I have read, that I can write more shorter it in the latest version of C#, like

```<code>decimal sumFreightAmount = (db.Trips.Where(p => p.DateTime.Month == i && p.DateTime.Year == DateTime.Now.Year).Sum(p => p.FreightAmount)?.0;
</code>```

but can't find it. What is the shortest record?

答:
The best way is using GetValueOrDefault

```<code>decimal sumFreightAmount = db.Trips
    .Where(p => p.DateTime.Month == i && p.DateTime.Year == DateTime.Now.Year)
    .Sum(p => p.FreightAmount)
    .GetValueOrDefault();
</code>```

EDIT: As @IvanStoev pointed out, you can also use the null coalescing operator in this case, which is a tad bit shorter:

```<code>decimal sumFreightAmount = db.Trips
    .Where(p => p.DateTime.Month == i && p.DateTime.Year == DateTime.Now.Year)
    .Sum(p => p.FreightAmount) ?? 0;
</code>```

Title: Short record of if / null

Body:
I have the following code:

decimal? sumFreightAmount = (db.Trips
          .Where(p => p.DateTime.Month == i && p.DateTime.Year == DateTime.Now.Year)
          .Sum(p => p.FreightAmount));

if (sumFreightAmount.HasValue)
{
     // my actions
}
else
{
    sumFreightAmount = 0;
}

I can write it the following way:

decimal sumFreightAmount = (
         db.Trips
           .Where(p => p.DateTime.Month == i && p.DateTime.Year == DateTime.Now.Year)
           .Sum(p => p.FreightAmount) != null)
         ?
         (db.Trips
            .Where(p => p.DateTime.Month == i && p.DateTime.Year == DateTime.Now.Year)
            .Sum(p => p.FreightAmount)) : 0;

but in this place I call linq extension twice (and have a long record). I have read, that I can write more shorter it in the latest version of C#, like

decimal sumFreightAmount = (db.Trips.Where(p => p.DateTime.Month == i && p.DateTime.Year == DateTime.Now.Year).Sum(p => p.FreightAmount)?.0;

but can't find it. What is the shortest record?

Body:
The best way is using GetValueOrDefault

decimal sumFreightAmount = db.Trips
    .Where(p => p.DateTime.Month == i && p.DateTime.Year == DateTime.Now.Year)
    .Sum(p => p.FreightAmount)
    .GetValueOrDefault();

EDIT: As @IvanStoev pointed out, you can also use the null coalescing operator in this case, which is a tad bit shorter:

decimal sumFreightAmount = db.Trips
    .Where(p => p.DateTime.Month == i && p.DateTime.Year == DateTime.Now.Year)
    .Sum(p => p.FreightAmount) ?? 0;


问:
Forgot Oracle username and password, how to retrieve?
I have forgotten my Oracle username and password and hence not able to use it. My Oracle version is 11.2.0.1.0(11g). I consulted Internet. They asked me to execute commands like ‘SYSDBA’ but I was unable to do it as once I give ‘SYSDBA’ on Command Prompt screen, it takes the command as the username and next asks for password. I cannot execute any commands suggested by them as whatever I enter is taken as the username, subsequently password is asked and error occurs.</p>

答:
Open your SQL command line and type the following:

```<code>SQL> connect / as sysdba
</code>```

Once connected,you can enter the following query to get details of username and password:

```<code>SQL> select username,password from dba_users;
</code>```

This will list down the usernames,but passwords would not be visible.But you can identify the particular username and then change the password for that user.
For changing the password,use the below query:

```<code>SQL> alter user username identified by password;
</code>```

Here username is the name of user whose password you want to change and password is the new password.

Body:
Open your SQL command line and type the following:

SQL> connect / as sysdba

Once connected,you can enter the following query to get details of username and password:

SQL> select username,password from dba_users;

This will list down the usernames,but passwords would not be visible.But you can identify the particular username and then change the password for that user.
For changing the password,use the below query:

SQL> alter user username identified by password;

Here username is the name of user whose password you want to change and password is the new password.


问:
Hybris addons install concept
How is the best way to work with a default Hybris addon? There are some really nice addon features we want to use in our projects, but of course not exactly the way they are. So what is the best practice to modify them?

Is it the way to copy the addon into the own project and then handle it as an own addon? (So put it under the 'custom' folder and modify it as needed)

答:
How is the best way to work with a default addon from hybris?

Addons are used to extend Hybris platform functionalities without
changing its source code, they are standard extensions, So,
I think that the best way is to create your own addon, so you keep your
code independent of Hybris business logic and modular for future evolution.
In general SAP Hybris recommends the extension of its code without modifying it.

What exactly happens by installing an addon on an extension?

Once you execute the following command :

```<code>ant addoninstall -Daddonnames="myAddOn" -DaddonStorefront.yacceleratorstorefront="myStorefront"
</code>```

ant addoninstall will :

Add myAddOn into extensioninfo.xml as required
for myStorefront  extension

Add myAddOn to addons.less for myStorefront

Generate a new project.properties file from the project.properties.template inside myAddOn.

Configure the myAddOn web spring configuration
myAddOn-web-spring.xml into myStorefront.additionalWebSpringConfigs

When need to uninstall an addon, does it need to use the uninstall
  command?

Yes, you need to execute ant addonuninstall in order to rollback the actions listed in the second response.

Title: Hybris addons install concept

Body:
How is the best way to work with a default addon from hybris?

Addons are used to extend Hybris platform functionalities without
changing its source code, they are standard extensions, So,
I think that the best way is to create your own addon, so you keep your
code independent of Hybris business logic and modular for future evolution.
In general SAP Hybris recommends the extension of its code without modifying it.

What exactly happens by installing an addon on an extension?

Once you execute the following command :

ant addoninstall -Daddonnames="myAddOn" -DaddonStorefront.yacceleratorstorefront="myStorefront"

ant addoninstall will :

Add myAddOn into extensioninfo.xml as required
for myStorefront  extension

Add myAddOn to addons.less for myStorefront

Generate a new project.properties file from the project.properties.template inside myAddOn.

Configure the myAddOn web spring configuration
myAddOn-web-spring.xml into myStorefront.additionalWebSpringConfigs

When need to uninstall an addon, does it need to use the uninstall
  command?

Yes, you need to execute ant addonuninstall in order to rollback the actions listed in the second response.


问:
windows command for grand total
Is there a easy way to calculate the grand total of all the numberic values specified line by line using a windows command (or batch file - least prefer)

suppose

```<code>7612
7724
19844
20092
20184
20468
27100
36456
39428
54264
69008
97208
</code>```

assume this is in a file

I want the total of all the values. thanks in advance

答:
I'm not aware of any command line utility to compute such a sum. But you can use a for loop iterating through the file. Something like this will work but you will need a helper batch file. In Sum.bat dump:</p>

```<code>REM. Turn off echo-ing of individual commands
@echo off

REM. Set variable a to 0. /a mean arithmetic expression
set /a sum = 0

REM. For loop updating the sum as we go
FOR /F %%i IN (file.txt) DO set /a sum += %%i

REM. Output
echo %sum%
</code>```

Title: windows command for grand total

Body:
Is there a easy way to calculate the grand total of all the numberic values specified line by line using a windows command (or batch file - least prefer)

suppose

7612
7724
19844
20092
20184
20468
27100
36456
39428
54264
69008
97208

assume this is in a file

I want the total of all the values. thanks in advance

Body:
I'm not aware of any command line utility to compute such a sum. But you can use a for loop iterating through the file. Something like this will work but you will need a helper batch file. In Sum.bat dump:

REM. Turn off echo-ing of individual commands
@echo off

REM. Set variable a to 0. /a mean arithmetic expression
set /a sum = 0

REM. For loop updating the sum as we go
FOR /F %%i IN (file.txt) DO set /a sum += %%i

REM. Output
echo %sum%


问:
Div content misalignment
Here is my jsfiddle : DEMO

```<code>The text content written within the <div>'s moves up
</code>```

Can someone tell me why is this happening?
What's the fix for this?

Any help would be much appreciated. Thanks!

答:
My answered fiddle : https://jsfiddle.net/inchrvndr/ducyaLan/1/</p>

```<code>.rule{
    height: 8%;
    width: 50%;
    background-color: #aaa;
    text-align: center;
    margin-bottom: 5%;
}
.event {
    height: 8%;
    width: 50%;
    background-color: #aaa;
    text-align: center;
    margin-bottom: 5%;
}
</code>```

Title: Div content misalignment

Body:
Here is my jsfiddle : DEMO

The text content written within the
's moves up

Can someone tell me why is this happening?
What's the fix for this?

Any help would be much appreciated. Thanks!

Body:
My answered fiddle : https://jsfiddle.net/inchrvndr/ducyaLan/1/

.rule{
    height: 8%;
    width: 50%;
    background-color: #aaa;
    text-align: center;
    margin-bottom: 5%;
}
.event {
    height: 8%;
    width: 50%;
    background-color: #aaa;
    text-align: center;
    margin-bottom: 5%;
}


问:
1452 Cannot add or update a child row: a foreign key constraint fails Laravel 5.4
I have two tables :

1) users

```<code>Schema::create('users', function (Blueprint $table) {
            $table->engine = "InnoDB";
            $table->string('id')->unique();
            $table->string('name')->nullable();
            $table->string('surname')->nullable();
            $table->string('email')->unique()->nullable();
            $table->string('address')->nullable();
            $table->string('telephone')->nullable();
            $table->timestamps();
        });
</code>```

2) users_games

```<code>  Schema::create('user_games', function (Blueprint $table) {
            $table->engine = "InnoDB";
            $table->increments('id');
            $table->string('user_id');
            $table->boolean('state')->default(false);
            $table->timestamps();
            $table->foreign('user_id')
                ->references('id')->on('users')
                ->onDelete('cascade');
        });
</code>```

Every user can have many games so i want every game->user_id to match with the user's id.

I have the below function where i create a user :

```<code> public function createNewUser(){

        // Check here if user is about to win,

        $mUniqueID = uniqid("",true); // create an id
        $user = new User();
        $user->id = $mUniqueID;
        $saved = $user->save();

        $user = User::find($mUniqueID);
        $currentGame = new UserGame(['state' => false]); // It is in 'fillable' array - boolean
        $user->games()->save($currentGame);

        $mUserInformation = [
            'mUniqueID' => $mUniqueID,
            'game_id'   => $user->games()->latest()->first(),
        ];

        if($saved)
            return $mUserInformation;
        else
            return redirect()->route('game');
    }
</code>```

The error i get :

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
  update a child row: a foreign key constraint fails
  (db_name.user_games, CONSTRAINT user_games_user_id_foreign
  FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE)
  (SQL: insert into user_games (state, user_id, updated_at,
  created_at) values (0, 59380, 2017-06-07 14:18:52, 2017-06-07
  14:18:52))

I can't understand why this error occurs. If you need any more information please ask and i will provide.

EDIT 1 :

Also, in my database an id of user is : 59380b495c1942.30562655 but the error mentions only 59380, shouldn't it be 59380b495c1942.30562655 ?

EDIT 2:

User.php model

```<code>    class User extends Authenticatable
    {
        use Notifiable;

        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = [
// all fillables here
        ];

        /**
         * The attributes that should be hidden for arrays.
         *
         * @var array
         */
        protected $hidden = [
            'password', 'remember_token',
        ];

        public function games()
        {

            return $this->hasMany('App\UserGame');
        }

    }
</code>```

UserGame.php model

```<code>class UserGame extends Model
{
    protected $fillable = [
        'state'
    ];

    public function user()
    {
        return $this->belongsTo('App\User');
    }
}
</code>```

答:
So if you want to use InnoDB engine in  /config/database.php change  'engine' => null, to 'engine' => 'InnoDB'

To use uuid you can add laravel-uuid by add composer require webpatser/laravel-uuid, after add the aliases in config/app.php

Change Migrations $table->increments('id') to $table->uuid('id') and add $table->primary('id')

In models add public $incrementing = false; Hope help you

In the end add trait

```<code>namespace App;

use Webpatser\Uuid\Uuid;
trait Uuids
{
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $model->{$model->getKeyName()} = Uuid::generate()->string;
        });
    }
}
</code>```

In model also add use Uuids;

Body:
I have two tables :

1) users

Schema::create('users', function (Blueprint $table) {
            $table->engine = "InnoDB";
            $table->string('id')->unique();
            $table->string('name')->nullable();
            $table->string('surname')->nullable();
            $table->string('email')->unique()->nullable();
            $table->string('address')->nullable();
            $table->string('telephone')->nullable();
            $table->timestamps();
        });

2) users_games

  Schema::create('user_games', function (Blueprint $table) {
            $table->engine = "InnoDB";
            $table->increments('id');
            $table->string('user_id');
            $table->boolean('state')->default(false);
            $table->timestamps();
            $table->foreign('user_id')
                ->references('id')->on('users')
                ->onDelete('cascade');
        });

Every user can have many games so i want every game->user_id to match with the user's id.

I have the below function where i create a user :

 public function createNewUser(){

        // Check here if user is about to win,

        $mUniqueID = uniqid("",true); // create an id
        $user = new User();
        $user->id = $mUniqueID;
        $saved = $user->save();

        $user = User::find($mUniqueID);
        $currentGame = new UserGame(['state' => false]); // It is in 'fillable' array - boolean
        $user->games()->save($currentGame);

        $mUserInformation = [
            'mUniqueID' => $mUniqueID,
            'game_id'   => $user->games()->latest()->first(),
        ];

        if($saved)
            return $mUserInformation;
        else
            return redirect()->route('game');
    }

The error i get :

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
  update a child row: a foreign key constraint fails
  (db_name.user_games, CONSTRAINT user_games_user_id_foreign
  FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE)
  (SQL: insert into user_games (state, user_id, updated_at,
  created_at) values (0, 59380, 2017-06-07 14:18:52, 2017-06-07
  14:18:52))

I can't understand why this error occurs. If you need any more information please ask and i will provide.

EDIT 1 :

Also, in my database an id of user is : 59380b495c1942.30562655 but the error mentions only 59380, shouldn't it be 59380b495c1942.30562655 ?

EDIT 2:

User.php model

    class User extends Authenticatable
    {
        use Notifiable;

        /**
         * The attributes that are mass assignable.
         *
         * @var array
         */
        protected $fillable = [
// all fillables here
        ];

        /**
         * The attributes that should be hidden for arrays.
         *
         * @var array
         */
        protected $hidden = [
            'password', 'remember_token',
        ];

        public function games()
        {

            return $this->hasMany('App\UserGame');
        }

    }

UserGame.php model

class UserGame extends Model
{
    protected $fillable = [
        'state'
    ];

    public function user()
    {
        return $this->belongsTo('App\User');
    }
}

Body:
So if you want to use InnoDB engine in  /config/database.php change  'engine' => null, to 'engine' => 'InnoDB'

To use uuid you can add laravel-uuid by add composer require webpatser/laravel-uuid, after add the aliases in config/app.php

Change Migrations $table->increments('id') to $table->uuid('id') and add $table->primary('id')

In models add public $incrementing = false; Hope help you

In the end add trait

namespace App;

use Webpatser\Uuid\Uuid;
trait Uuids
{
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $model->{$model->getKeyName()} = Uuid::generate()->string;
        });
    }
}

In model also add use Uuids;