问:
Bootstrap 3 Fixed Top Navbar 'Flickering' On Mobile Scrolling using jQuery One-Page Scrolling Effect
thanks for checking out this issue.

I was wondering if there is a way to prevent a Bootstrap 3 fixed top navigation bar from 'flickering' or jumping up and down when auto-scrolled using a jQuery plugin.

An active example is here:

http://startbootstrap.com/templates/grayscale/

If you look at this template on a mobile phone (I am using an iPhone 4) use the menu bar and click on a link. The jQuery plugin takes you to the section of the page, but watch the top menu bar. It flickers and dances all around like crazy, and doesn't really stay put.

Here is the code associated with this example, but most other examples I've seen of people doing the same thing in different ways with Bootstrap fixed top nav's have been the same.

HTML:

```<code><body id="page-top" data-spy="scroll" data-target=".navbar-custom">

<nav class="navbar navbar-custom navbar-fixed-top" role="navigation">
    <div class="container">
        <div class="navbar-header page-scroll">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">
                <i class="fa fa-bars"></i>
            </button>
            <a class="navbar-brand" href="#page-top">
                <i class="fa fa-play-circle"></i>  <span class="light">Start</span> Bootstrap
            </a>
        </div>

        <!-- Collect the nav links, forms, and other content for toggling -->
        <div class="collapse navbar-collapse navbar-right navbar-main-collapse">
            <ul class="nav navbar-nav">
                <!-- Hidden li included to remove active class from about link when scrolled up past about section -->
                <li class="hidden">
                    <a href="#page-top"></a>
                </li>
                <li class="page-scroll">
                    <a href="#about">About</a>
                </li>
                <li class="page-scroll">
                    <a href="#download">Download</a>
                </li>
                <li class="page-scroll">
                    <a href="#contact">Contact</a>
                </li>
            </ul>
        </div>
        <!-- /.navbar-collapse -->
    </div>
    <!-- /.container -->
</nav>

...
</code>```

jQuery:

```<code>//jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
    $('.page-scroll a').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 1500, 'easeInOutExpo');
        event.preventDefault();
    });
});
</code>```

CSS:

Combination of the default Bootstrap 3 CSS and the following custom styles:

```<code>.navbar {
    margin-bottom: 0;
    border-bottom: 1px solid rgba(255,255,255,.3);
    text-transform: uppercase;
    font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif;
    background-color: #000;
}

.navbar-brand {
    font-weight: 700;
}

.navbar-brand:focus {
    outline: 0;
}

.navbar-custom a {
    color: #fff;
}

.navbar-custom .nav li a {
    -webkit-transition: background .3s ease-in-out;
    -moz-transition: background .3s ease-in-out;
    transition: background .3s ease-in-out;
}

.navbar-custom .nav li a:hover,
.navbar-custom .nav li a:focus,
.navbar-custom .nav li.active {
    outline: 0;
    background-color: rgba(255,255,255,.2);
}

.navbar-toggle {
    padding: 4px 6px;
    font-size: 16px;
    color: #fff;
}

.navbar-toggle:focus,
.navbar-toggle:active {
    outline: 0;
}
</code>```

Again, the best way to replicate the problem is by testing this sample site using a mobile device:

http://startbootstrap.com/templates/grayscale/

When tested on a PC, the problem does not occur.

Thanks for reading! If you've already found a fix for this problem I'd love to hear it, or if you're willing to take a crack at this it would be much appreciated!

答:
I had also 1px jumping problem with bootstrap navbar.

Solved by adding this to parent element (in my case )

```<code>  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
  position: fixed;
  z-index: 1000;
</code>```

Body:
thanks for checking out this issue.

I was wondering if there is a way to prevent a Bootstrap 3 fixed top navigation bar from 'flickering' or jumping up and down when auto-scrolled using a jQuery plugin.

An active example is here:

http://startbootstrap.com/templates/grayscale/

If you look at this template on a mobile phone (I am using an iPhone 4) use the menu bar and click on a link. The jQuery plugin takes you to the section of the page, but watch the top menu bar. It flickers and dances all around like crazy, and doesn't really stay put.

Here is the code associated with this example, but most other examples I've seen of people doing the same thing in different ways with Bootstrap fixed top nav's have been the same.

HTML:

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">

            </button>

                  Start Bootstrap

                    About

                    Download

                    Contact

...

jQuery:

//jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
    $('.page-scroll a').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 1500, 'easeInOutExpo');
        event.preventDefault();
    });
});

CSS:

Combination of the default Bootstrap 3 CSS and the following custom styles:

.navbar {
    margin-bottom: 0;
    border-bottom: 1px solid rgba(255,255,255,.3);
    text-transform: uppercase;
    font-family: Montserrat,"Helvetica Neue",Helvetica,Arial,sans-serif;
    background-color: #000;
}

.navbar-brand {
    font-weight: 700;
}

.navbar-brand:focus {
    outline: 0;
}

.navbar-custom a {
    color: #fff;
}

.navbar-custom .nav li a {
    -webkit-transition: background .3s ease-in-out;
    -moz-transition: background .3s ease-in-out;
    transition: background .3s ease-in-out;
}

.navbar-custom .nav li a:hover,
.navbar-custom .nav li a:focus,
.navbar-custom .nav li.active {
    outline: 0;
    background-color: rgba(255,255,255,.2);
}

.navbar-toggle {
    padding: 4px 6px;
    font-size: 16px;
    color: #fff;
}

.navbar-toggle:focus,
.navbar-toggle:active {
    outline: 0;
}

Again, the best way to replicate the problem is by testing this sample site using a mobile device:

http://startbootstrap.com/templates/grayscale/

When tested on a PC, the problem does not occur.

Thanks for reading! If you've already found a fix for this problem I'd love to hear it, or if you're willing to take a crack at this it would be much appreciated!

Body:
I had also 1px jumping problem with bootstrap navbar.

Solved by adding this to parent element (in my case <header>)

  -webkit-backface-visibility: hidden;
  backface-visibility: hidden;
  position: fixed;
  z-index: 1000;


来源: stackexchange

问:
How to find unique values in a field of a nested struct
I have a nested struct user.data and I want to find the unique values of the field touristicRoute (user.data.touristicRoute)

I have tried this code:

```<code>for m=1:size(Cluster_USERS,1)
    for i=1:size(userTouristicTraj(m).touristicData,2)
        if (user(m).data(i).touristicRoute~=0)
            uniqueValues=unique(user(m).data(i).touristicRoute)
        end
    end
end
</code>```

but it doesn't give me the right value, can you help me?

答:
The unique value of a single struct is that value itself. If you want to see the unique values of all structs, then you need to extract them first.</p>

```<code>for m=1:size(Cluster_USERS,1)
    for i=1:size(userTouristicTraj(m).touristicData,2)
        if (user(m).data(i).touristicRoute~=0)
            for jj=size(user(m).data(i).touristicRoute,1)
            values=unique([(user(m).data(i).touristicRoute{jj}).' values]);
            end
        end
    end
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a nested struct user.data and I want to find the unique values of the field touristicRoute (user.data.touristicRoute)

I have tried this code:

for m=1:size(Cluster_USERS,1)
    for i=1:size(userTouristicTraj(m).touristicData,2)
        if (user(m).data(i).touristicRoute~=0)
            uniqueValues=unique(user(m).data(i).touristicRoute)
        end
    end
end

but it doesn't give me the right value, can you help me?

Body:
The unique value of a single struct is that value itself. If you want to see the unique values of all structs, then you need to extract them first.

for m=1:size(Cluster_USERS,1)
    for i=1:size(userTouristicTraj(m).touristicData,2)
        if (user(m).data(i).touristicRoute~=0)
            for jj=size(user(m).data(i).touristicRoute,1)
            values=unique([(user(m).data(i).touristicRoute{jj}).' values]);
            end
        end
    end
end


问:
Hybris Commerce Cuppy extension installation failure
My Environment: Win10 + Java 8 + Hybris Commerse 6.3

I've followed the tutorial steps available on https://help.hybris.com for the Cuppy installation. And after rebuild and launch of the application I faced the following exception:

```<code>ERROR [localhost-startStop-1] [ContextLoader] Context initialization failed org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: You cannot use a spring-security-2.0.xsd or spring-security-3.0.xsd or spring-security-3.1.xsd schema or spring-security-3.2.xsd schema or spring-security-4.0.xsd schema with Spring Security 4.1. Please update your schema declarations to the 4.1 schema.
Offending resource: class path resource [cuppy/cuppy-spring-security.xml]
        at org.springframework.beans.factory.parsing.FailFastProblemReporter.fatal(FailFastProblemReporter.java:60) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
...
java.lang.IllegalStateException: LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context:
Root WebApplicationContext - /cuppy: startup date [Thu Mar 30 13:15:10 EEST 2017]; parent: hybris Application context - master
</code>```

答:
It looks like Cuppy extension was not upgraded for spring security 4.1
Cuppy has the following configuration in cuppy-spring-security.xml:

```<code><beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-4.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd"
</code>```

and it should be changed to the following

```<code><beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-4.1.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd"
</code>```

Body:
My Environment: Win10 + Java 8 + Hybris Commerse 6.3

I've followed the tutorial steps available on https://help.hybris.com for the Cuppy installation. And after rebuild and launch of the application I faced the following exception:

ERROR [localhost-startStop-1] [ContextLoader] Context initialization failed org.springframework.beans.factory.parsing.BeanDefinitionParsingException: Configuration problem: You cannot use a spring-security-2.0.xsd or spring-security-3.0.xsd or spring-security-3.1.xsd schema or spring-security-3.2.xsd schema or spring-security-4.0.xsd schema with Spring Security 4.1. Please update your schema declarations to the 4.1 schema.
Offending resource: class path resource [cuppy/cuppy-spring-security.xml]
        at org.springframework.beans.factory.parsing.FailFastProblemReporter.fatal(FailFastProblemReporter.java:60) ~[spring-beans-4.3.3.RELEASE.jar:4.3.3.RELEASE]
...
java.lang.IllegalStateException: LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context:
Root WebApplicationContext - /cuppy: startup date [Thu Mar 30 13:15:10 EEST 2017]; parent: hybris Application context - master

Body:
It looks like Cuppy extension was not upgraded for spring security 4.1
Cuppy has the following configuration in cuppy-spring-security.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-4.0.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd"

and it should be changed to the following

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-4.1.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd"


问:
How to implement a generic method in Java to mange properties of a class?
I have a Container class with two sets: one of type A and the other one of type B. I want to have a single method in my class which can receive an argument of type A or B and add it to the corresponding set.
btw, I'm not sure if the interface Something should be used. Note that I want to avoid checking the class type of the received parameter with getClass() or instanceof since I have lots of sets in my project.

How can I achieve this?

Thanks,

```<code>public class Container{

privte Set<A> a;
privte Set<B> b;

public Container(){
    a = new HashSet<>();
    b = new HashSet<>();
}

//getters and setters

//generic method
public void addAorB(Something instance){
    //add to the coresponding Set
}
}

public class A implements Something{

}

public class B implements Something{

}
</code>```

答:
Assuming the generic types are disjunct I would put all sets into a map, each set's type as key. To avoid duplicated code I also would create a method which creates the set and puts it into the map.

```<code>private final Map<Class<?>, Set<? extends Something>> sets = new HashMap<>();

public Container() {
    a = createAndPut(A.class);
    b = createAndPut(B.class);
}

private <T extends Something> Set<T> createAndPut(Class<T> type) {
    Set<T> set = new HashSet<>();
    sets.put(type, set);
    return set;
}
</code>```

If you only need the set-instances to add the elements, you may discard them. You can add a null-check if there is no set registered for the given instance.

```<code>public void addAorB(Something instance){
        Set<? extends Something> set = sets.get(instance.getClass());
        if (set == null)
            set = createAndPut(instance.getClass());
        ((Set<Something>) set).add(instance);
}
</code>```

Body:
I have a Container class with two sets: one of type A and the other one of type B. I want to have a single method in my class which can receive an argument of type A or B and add it to the corresponding set.
btw, I'm not sure if the interface Something should be used. Note that I want to avoid checking the class type of the received parameter with getClass() or instanceof since I have lots of sets in my project.

How can I achieve this?

Thanks,

public class Container{

privte Set a;
privte Set b;

public Container(){
    a = new HashSet<>();
    b = new HashSet<>();
}

//getters and setters

//generic method
public void addAorB(Something instance){
    //add to the coresponding Set
}
}

public class A implements Something{

}

public class B implements Something{

}

Body:
Assuming the generic types are disjunct I would put all sets into a map, each set's type as key. To avoid duplicated code I also would create a method which creates the set and puts it into the map.

private final Map<Class<?>, Set<? extends Something>> sets = new HashMap<>();

public Container() {
    a = createAndPut(A.class);
    b = createAndPut(B.class);
}

private <T extends Something> Set<T> createAndPut(Class<T> type) {
    Set<T> set = new HashSet<>();
    sets.put(type, set);
    return set;
}

If you only need the set-instances to add the elements, you may discard them. You can add a null-check if there is no set registered for the given instance.

public void addAorB(Something instance){
        Set<? extends Something> set = sets.get(instance.getClass());
        if (set == null)
            set = createAndPut(instance.getClass());
        ((Set<Something>) set).add(instance);
}


问:
Android: icon drawable padding
I created icon resource on Android Asset Studio with no padding. The icon has a blank on the left and right side. When I set it as a source in ImageView, the ImageView looks like having padding on left and right.

How can I remove the blank on the left and right of the icon in the ImageView?

Here is my icon:

答:
i think your image may be small size.In these case  your  imageview add the property  scaleType as centerCrop.

```<code>android:scaleType="centerCrop"
</code>```

The dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding).

for more details refer ImageView.ScaleType

Title: Android: icon drawable padding

Body:
i think your image may be small size.In these case  your  imageview add the property  scaleType as centerCrop.

android:scaleType="centerCrop"

The dimensions (width and height) of the image will be equal to or larger than the corresponding dimension of the view (minus padding).

for more details refer ImageView.ScaleType


问:
FrameLayout, how to move item under other item
I create a layout with button, this button have logic and i dont want to integrate it.

So i think like:

When i have button, i need to add a char $, so i create a frameLayout and add here a TextView, i do this, but my TextView is under button, so i didnt see this TextView,

Here is my code:

```<code>  <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true">

        <Button
            android:id="@+id/button_cash"
            android:layout_width="80dp"
            android:layout_height="wrap_content"
            android:background="@drawable/button_radius"
            android:paddingRight="12dp"
            android:text="@string/_5000"
            android:textColor="@color/white"
            android:textSize="14sp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:layout_marginRight="14dp"
            android:layout_marginTop="15dp"
            android:text="@string/dollar_$"
            android:textColor="@color/white"
            android:textSize="14sp" />
    </FrameLayout>
</code>```

And my question is, how to move item under other item in FrameLayout?
Thanks for advice

答:
This is probably due to the elevation parameter. By default a Button has a non-zero value of elevation while TextView's elevation is 0dp.

Try manipulating elevation (either increase elevation for TextView or decrease elevation for Button) to match your exact case.

I suggest you apply both:

```<code>app:elevation="<your_value_in_dp>"
android:elevation="<your_value_in_dp>"
</code>```

Body:
I create a layout with button, this button have logic and i dont want to integrate it.

So i think like:

When i have button, i need to add a char $, so i create a frameLayout and add here a TextView, i do this, but my TextView is under button, so i didnt see this TextView,

Here is my code:

  <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true">

        <Button
            android:id="@+id/button_cash"
            android:layout_width="80dp"
            android:layout_height="wrap_content"
            android:background="@drawable/button_radius"
            android:paddingRight="12dp"
            android:text="@string/_5000"
            android:textColor="@color/white"
            android:textSize="14sp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:layout_marginRight="14dp"
            android:layout_marginTop="15dp"
            android:text="@string/dollar_$"
            android:textColor="@color/white"
            android:textSize="14sp" />
    </FrameLayout>

And my question is, how to move item under other item in FrameLayout?
Thanks for advice

Body:
This is probably due to the elevation parameter. By default a Button has a non-zero value of elevation while TextView's elevation is 0dp.

Try manipulating elevation (either increase elevation for TextView or decrease elevation for Button) to match your exact case.

I suggest you apply both:

app:elevation="<your_value_in_dp>"
android:elevation="<your_value_in_dp>"


问:
Javascript click start / stop interval function
I want to start a interval / function if the user clicks on a button and stop that if the user clicks on stop. But somehow it immidietly starts the startRecord function. What am I doing wrong.

HTML:

window.onload = startRecord;

startRecord = document.getElementById('startRecord');
stopRecord = document.getElementById('stopRecord');

function startRecord() {
  startRecord.onclick = generateImg(true);
  startRecord.style.display = "none";
  stopRecord.style.display = "block";
}

function stopRecord() {
  stopRecord.onclick = generateImg(false);
  startRecord.style.display = "block";
  stopRecord.style.display = "none";
}

function generateImg(start) {
  if (start) {
    var startInterval = setInterval(function() {
      console.log("foo")
    }, 1000);
  } else {
    clearInterval(startInterval);
    console.log("stop foo")
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="btn-group">
  <button type="button" class="btn btn-default btn-lg" id="startRecord">
            Start
        </button>
  <button type="button" class="btn btn-default btn-lg" id="stopRecord">
            Stop
        </button>
</div></code>```

答:
Issues with your code:

Your variable name and function name is same:

startRecord = document.getElementById('startRecord');
function startRecord() {
```

<p>as the variables are hoisted, <code>startRecord</code> will hold last assigned value.</p>

<ul>
<li>Its a bad idea to use <code>onclick = function</code>. Every assignment would replace previous value. Use <code>.addEventListener</code> instead.</li>
<li>You are updating UI states on <code>startRecord</code> and <code>endRecord</code> but on click, these function are not called. Use a function to do all that in one function and use that as event handler.</li>
<li><code>startInterval</code> is a local variable. So when you click on stop, it has lost its scope. Define it as a global variable.</li>
</ul>

<p><strong>Sample Code</strong></p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var startInterval = null;

var startRecordBtn = document.getElementById('startRecord');
var stopRecordBtn = document.getElementById('stopRecord');

function registerEvents(){
  startRecordBtn.addEventListener("click", startRecord);
  stopRecordBtn.addEventListener("click", stopRecord);
}

function startRecord() {
  generateImg(true);
  startRecordBtn.style.display = "none";
  stopRecordBtn.style.display = "block";
}

function stopRecord() {
  generateImg(false);
  startRecordBtn.style.display = "block";
  stopRecordBtn.style.display = "none";
}

function generateImg(start) {
  if (start) {
    startInterval = setInterval(function() {
      console.log("foo")
    }, 1000);
  } else {
    clearInterval(startInterval);
    console.log("stop foo")
  }
}

registerEvents();
window.addEventListener("load", startRecord);</code>```

  <button type="button" class="btn btn-default btn-lg" id="startRecord">
    Start
  </button>
  <button type="button" class="btn btn-default btn-lg" id="stopRecord">
    Stop
  </button>

```

Body:
I want to start a interval / function if the user clicks on a button and stop that if the user clicks on stop. But somehow it immidietly starts the startRecord function. What am I doing wrong.

HTML:

window.onload = startRecord;

startRecord = document.getElementById('startRecord');
stopRecord = document.getElementById('stopRecord');

function startRecord() {
  startRecord.onclick = generateImg(true);
  startRecord.style.display = "none";
  stopRecord.style.display = "block";
}

function stopRecord() {
  stopRecord.onclick = generateImg(false);
  startRecord.style.display = "block";
  stopRecord.style.display = "none";
}

function generateImg(start) {
  if (start) {
    var startInterval = setInterval(function() {
      console.log("foo")
    }, 1000);
  } else {
    clearInterval(startInterval);
    console.log("stop foo")
  }
}

  <button type="button" class="btn btn-default btn-lg" id="startRecord">
            Start
        </button>
  <button type="button" class="btn btn-default btn-lg" id="stopRecord">
            Stop
        </button>

Body:
Issues with your code:

Your variable name and function name is same:

startRecord = document.getElementById('startRecord');
function startRecord() {

as the variables are hoisted, startRecord will hold last assigned value.

Its a bad idea to use onclick = function. Every assignment would replace previous value. Use .addEventListener instead.

You are updating UI states on startRecord and endRecord but on click, these function are not called. Use a function to do all that in one function and use that as event handler.

startInterval is a local variable. So when you click on stop, it has lost its scope. Define it as a global variable.

Sample Code

var startInterval = null;

var startRecordBtn = document.getElementById('startRecord');
var stopRecordBtn = document.getElementById('stopRecord');

function registerEvents(){
  startRecordBtn.addEventListener("click", startRecord);
  stopRecordBtn.addEventListener("click", stopRecord);
}

function startRecord() {
  generateImg(true);
  startRecordBtn.style.display = "none";
  stopRecordBtn.style.display = "block";
}

function stopRecord() {
  generateImg(false);
  startRecordBtn.style.display = "block";
  stopRecordBtn.style.display = "none";
}

function generateImg(start) {
  if (start) {
    startInterval = setInterval(function() {
      console.log("foo")
    }, 1000);
  } else {
    clearInterval(startInterval);
    console.log("stop foo")
  }
}

registerEvents();
window.addEventListener("load", startRecord);

<div class="btn-group">
  <button type="button" class="btn btn-default btn-lg" id="startRecord">
    <a href="#" class="btn btn-default glyphicon glyphicon-hand-up">Start</a>
  </button>
  <button type="button" class="btn btn-default btn-lg" id="stopRecord">
    <a href="#" class="btn btn-default glyphicon glyphicon-hand-up">Stop</a>
  </button>
</div>


问:
Send mail if date in cell is 2 years older than the current date
I have created a macro which lists the name, path, Creation date, modification date of all the files and subfolders in an excel worksheet, this macro is working absolutely fine.

However now I want to create a macro which can check the entire list of files and folders and if the Date creation date (Column F ) of any listed files/folders is greater than 2 years from the current date, it should send an automated mail giving the name of the file, its path and the creation and modification information (basically copy all the information of that particular row) to me.

Please find below the code in which I am getting the error (Run time Error) on
this line :

```<code>Sub send_files()
Dim OutApp As Object
Dim OutMail As Object
Dim sh As Worksheet
Dim cell As Range
Dim FileCell As Range
Dim rng As Range
Dim sDate As String

With Application
    .EnableEvents = False
    .ScreenUpdating = False
End With

Set sh = ThisWorkbook.Sheets("Sheet1")
Set OutApp = CreateObject("Outlook.Application")
sDate = Date

For Each cell In sh.Columns("F").Cells
    Days = DateDiff("yyyy", Cells.Value, sDate)
    If Days > 2 Then
                Set OutMail = OutApp.CreateItem(0)

        With OutMail
            .to = cell.Value
            .Subject = "Testfile"
            .Body = "Hi " & cell.Offset(0, -1).Value
            .send

        End With
    End If
Next cell

Set OutApp = Nothing
With Application
    .EnableEvents = True
    .ScreenUpdating = True
End With
End Sub
</code>```

The error occurs on:

```<code>Days = DateDiff("yyyy", Cells.Value, sDate)
</code>```

Can anyone assist with this error?

答:
Try changing

```<code>Days = DateDiff("yyyy", Cells.Value, sDate)
</code>```

to

```<code>Days = DateDiff("yyyy", cell.Value, sDate)
</code>```

Body:
I have created a macro which lists the name, path, Creation date, modification date of all the files and subfolders in an excel worksheet, this macro is working absolutely fine.

However now I want to create a macro which can check the entire list of files and folders and if the Date creation date (Column F ) of any listed files/folders is greater than 2 years from the current date, it should send an automated mail giving the name of the file, its path and the creation and modification information (basically copy all the information of that particular row) to me.

Please find below the code in which I am getting the error (Run time Error) on
this line :

Sub send_files()
Dim OutApp As Object
Dim OutMail As Object
Dim sh As Worksheet
Dim cell As Range
Dim FileCell As Range
Dim rng As Range
Dim sDate As String

With Application
    .EnableEvents = False
    .ScreenUpdating = False
End With

Set sh = ThisWorkbook.Sheets("Sheet1")
Set OutApp = CreateObject("Outlook.Application")
sDate = Date

For Each cell In sh.Columns("F").Cells
    Days = DateDiff("yyyy", Cells.Value, sDate)
    If Days > 2 Then
                Set OutMail = OutApp.CreateItem(0)

        With OutMail
            .to = cell.Value
            .Subject = "Testfile"
            .Body = "Hi " & cell.Offset(0, -1).Value
            .send

        End With
    End If
Next cell

Set OutApp = Nothing
With Application
    .EnableEvents = True
    .ScreenUpdating = True
End With
End Sub

The error occurs on:

Days = DateDiff("yyyy", Cells.Value, sDate)

Can anyone assist with this error?

Body:
Try changing

Days = DateDiff("yyyy", Cells.Value, sDate)

to

Days = DateDiff("yyyy", cell.Value, sDate)


问:
Custom Constraint Validation Calling isValid twice, throwing NullPointerException
I have created a custom constraint validator which I am using to check validation on a username, the validator is accessing a database and checking if the record already exists and if it complies with a regex. I am getting  rather strange error as the validator is working correctly if the username already exists, however when entering a valid input (a username that doesn't exist) It is throwing a NullPointerException.

I have placed a counter and some statements to let me track where the application is crashing which I will include in the stack trace. The application seems to be calling the initialise and isValid method twice, the second time around it is throwing a NullPointer. I have looked at this question which says to add <property name="javax.persistence.validation.mode" value="none"/> to my persistence.xml file, which I have done and has made no change.

I am thinking that maybe I have to disable this somewhere else as I have not used my persistence.xml to configure the application, instead using a jpaContext.xml file.

If anyone has any advise/prior experience on hoot fix/where I should be looking to find a fix I would appreciate it.

custom constraint validator

```<code>public class UserNameConstraintValidator implements ConstraintValidator<UserName, String> {
@Autowired
private HouseholdService householdService;

private int counter = 0;

public void initialize(UserName userName) {
    System.out.println("counter inside initialize is at count : " + counter);
}

public boolean isValid(String userName, ConstraintValidatorContext cxt) {
    System.out.println(userName);
    counter ++;
    System.out.println("counter is at count : " + counter);

    if(householdService.checkForUser(userName) || userName == null) {      //line 26
        System.out.println(userName);
        System.out.println("counter inside if statement is at count : " + counter);
        return false;
    }
    else {
        System.out.println(userName);
        System.out.println("counter inside else statement is at count : " + counter);
        return (userName.matches("^[a-zA-Z0-9]+([a-zA-Z0-9](_|-| )[a-zA-Z0-9])*[a-zA-Z0-9]+$"));
    }
}
}
</code>```

StackTrace

```<code>        counter inside initialize is at count : 0
        newUser
        counter is at count : 1
        Tue Mar 28 19:18:23 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
        Mar 28, 2017 7:18:23 PM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
        INFO: HHH000397: Using ASTQueryTranslatorFactory
        Hibernate: select household0_.id as id1_1_, household0_.password as password2_1_, household0_.userName as userName3_1_ from Households household0_ where household0_.userName like ? limit ?
        Hibernate: select household0_.id as id1_1_, household0_.password as password2_1_, household0_.userName as userName3_1_ from Households household0_ where household0_.userName like ? limit ?
        inside HouseholdRepository, if statement has returned : 0
        newUser
        counter inside else statement is at count : 1
        Tue Mar 28 19:18:24 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
        Tue Mar 28 19:18:24 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
        Hibernate: select next_val as id_val from hibernate_sequence for update
        Hibernate: update hibernate_sequence set next_val= ? where next_val=?
        counter inside initialize is at count : 0
        newUser
        counter is at count : 1
        Mar 28, 2017 7:18:24 PM org.apache.catalina.core.StandardWrapperValve invoke
        SEVERE: Servlet.service() for servlet [springDispatcherServlet] in context with path [/Bill_Calculator] threw exception [Request processing failed; nested exception is javax.validation.ValidationException: HV000028: Unexpected exception during isValid call.] with root cause
        java.lang.NullPointerException
            at com.chrishammer.view.UserNameConstraintValidator.isValid(UserNameConstraintValidator.java:26)
            at com.chrishammer.view.UserNameConstraintValidator.isValid(UserNameConstraintValidator.java:1)
            at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateSingleConstraint(ConstraintTree.java:446)
            at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:127)
            at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:87)
            at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:73)
            at org.hibernate.validator.internal.engine.ValidatorImpl.validateMetaConstraint(ValidatorImpl.java:616)
            at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:581)
            at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForSingleDefaultGroupElement(ValidatorImpl.java:527)
            at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:495)
            at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:460)
            at org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:410)
            at org.hibernate.validator.internal.engine.ValidatorImpl.validate(ValidatorImpl.java:207)
            at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:116)
            at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.onPreInsert(BeanValidationEventListener.java:80)
            at org.hibernate.action.internal.EntityInsertAction.preInsert(EntityInsertAction.java:205)
            at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:82)
            at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:586)
            at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:460)
            at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
            at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
            at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1428)
            at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1414)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
            at java.lang.reflect.Method.invoke(Method.java:498)
            at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:298)
            at com.sun.proxy.$Proxy36.flush(Unknown Source)
            at com.chrishammer.repository.HouseholdRepositoryImpl.save(HouseholdRepositoryImpl.java:23)
            at com.chrishammer.service.HouseholdServiceImpl.save(HouseholdServiceImpl.java:24)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
            at java.lang.reflect.Method.invoke(Method.java:498)
            at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
            at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
            at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
            at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
            at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
            at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
            at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
            at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
            at com.sun.proxy.$Proxy41.save(Unknown Source)
            at com.chrishammer.controller.CreateAccountController.submitUser(CreateAccountController.java:34)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
            at java.lang.reflect.Method.invoke(Method.java:498)
            at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
            at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
            at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
            at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
            at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
            at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
            at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
            at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
            at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
            at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
            at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
            at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
            at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
            at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
            at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
            at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
            at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
            at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
            at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
            at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
            at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:495)
            at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
            at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:767)
            at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1347)
            at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
            at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
            at java.lang.Thread.run(Thread.java:745)
</code>```

Persistence.xml

```<code><persistence    xmlns="http:://java.sun.com/xml/ns.persistence"
            xmlns:xsi="http:://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http:://java.sun.com/xml/ns.persistence
                                http:://java.sun.com/xml/ns/persistence_2_0.xsd"
            version ="2.0" >

<persistence-unit name="punit">
    <property name="javax.persistence.validation.mode" value="none"/>
</persistence-unit>

</persistence>
</code>```

jpaContext.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

<context:annotation-config />
<context:component-scan base-package="com.chrishammer" />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="punit" />
    <property name="dataSource" ref="dataSource" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="showSql" value="true" />
        </bean>
    </property>
    <property name ="jpaPropertyMap">
        <map>
            <entry key="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
            <entry key="hibernate.hbm2ddl.auto" value="update" />
            <entry key="hivernate.format_sql" value="true" />
        </map>
    </property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<tx:annotation-driven />

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/testingDb?autoReconnect=true" />
    <property name="username" value="root" />
    <property name="password" value="root" />
</bean>
</beans>
</code>```

If you need anything else let me know, any help would be much appreciated.

答: I have fixed this issue. While looking through the documents on hibernate bean validation found here, I noticed that the <property> tag in the persistence.xml file was surrounded by a <properties> tag. Simply adding this to my persistence.xml file solved my issue.

Body:
I have created a custom constraint validator which I am using to check validation on a username, the validator is accessing a database and checking if the record already exists and if it complies with a regex. I am getting  rather strange error as the validator is working correctly if the username already exists, however when entering a valid input (a username that doesn't exist) It is throwing a NullPointerException.

I have placed a counter and some statements to let me track where the application is crashing which I will include in the stack trace. The application seems to be calling the initialise and isValid method twice, the second time around it is throwing a NullPointer. I have looked at this question which says to add <property name="javax.persistence.validation.mode" value="none"/> to my persistence.xml file, which I have done and has made no change.

I am thinking that maybe I have to disable this somewhere else as I have not used my persistence.xml to configure the application, instead using a jpaContext.xml file.

If anyone has any advise/prior experience on hoot fix/where I should be looking to find a fix I would appreciate it.

custom constraint validator

public class UserNameConstraintValidator implements ConstraintValidator<UserName, String> {
@Autowired
private HouseholdService householdService;

private int counter = 0;

public void initialize(UserName userName) {
    System.out.println("counter inside initialize is at count : " + counter);
}

public boolean isValid(String userName, ConstraintValidatorContext cxt) {
    System.out.println(userName);
    counter ++;
    System.out.println("counter is at count : " + counter);

    if(householdService.checkForUser(userName) || userName == null) {      //line 26
        System.out.println(userName);
        System.out.println("counter inside if statement is at count : " + counter);
        return false;
    }
    else {
        System.out.println(userName);
        System.out.println("counter inside else statement is at count : " + counter);
        return (userName.matches("^[a-zA-Z0-9]+([a-zA-Z0-9](_|-| )[a-zA-Z0-9])*[a-zA-Z0-9]+$"));
    }
}
}

StackTrace

        counter inside initialize is at count : 0
        newUser
        counter is at count : 1
        Tue Mar 28 19:18:23 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
        Mar 28, 2017 7:18:23 PM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
        INFO: HHH000397: Using ASTQueryTranslatorFactory
        Hibernate: select household0_.id as id1_1_, household0_.password as password2_1_, household0_.userName as userName3_1_ from Households household0_ where household0_.userName like ? limit ?
        Hibernate: select household0_.id as id1_1_, household0_.password as password2_1_, household0_.userName as userName3_1_ from Households household0_ where household0_.userName like ? limit ?
        inside HouseholdRepository, if statement has returned : 0
        newUser
        counter inside else statement is at count : 1
        Tue Mar 28 19:18:24 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
        Tue Mar 28 19:18:24 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
        Hibernate: select next_val as id_val from hibernate_sequence for update
        Hibernate: update hibernate_sequence set next_val= ? where next_val=?
        counter inside initialize is at count : 0
        newUser
        counter is at count : 1
        Mar 28, 2017 7:18:24 PM org.apache.catalina.core.StandardWrapperValve invoke
        SEVERE: Servlet.service() for servlet [springDispatcherServlet] in context with path [/Bill_Calculator] threw exception [Request processing failed; nested exception is javax.validation.ValidationException: HV000028: Unexpected exception during isValid call.] with root cause
        java.lang.NullPointerException
            at com.chrishammer.view.UserNameConstraintValidator.isValid(UserNameConstraintValidator.java:26)
            at com.chrishammer.view.UserNameConstraintValidator.isValid(UserNameConstraintValidator.java:1)
            at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateSingleConstraint(ConstraintTree.java:446)
            at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:127)
            at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:87)
            at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:73)
            at org.hibernate.validator.internal.engine.ValidatorImpl.validateMetaConstraint(ValidatorImpl.java:616)
            at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraint(ValidatorImpl.java:581)
            at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForSingleDefaultGroupElement(ValidatorImpl.java:527)
            at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForDefaultGroup(ValidatorImpl.java:495)
            at org.hibernate.validator.internal.engine.ValidatorImpl.validateConstraintsForCurrentGroup(ValidatorImpl.java:460)
            at org.hibernate.validator.internal.engine.ValidatorImpl.validateInContext(ValidatorImpl.java:410)
            at org.hibernate.validator.internal.engine.ValidatorImpl.validate(ValidatorImpl.java:207)
            at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.validate(BeanValidationEventListener.java:116)
            at org.hibernate.cfg.beanvalidation.BeanValidationEventListener.onPreInsert(BeanValidationEventListener.java:80)
            at org.hibernate.action.internal.EntityInsertAction.preInsert(EntityInsertAction.java:205)
            at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:82)
            at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:586)
            at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:460)
            at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
            at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
            at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1428)
            at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1414)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
            at java.lang.reflect.Method.invoke(Method.java:498)
            at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:298)
            at com.sun.proxy.$Proxy36.flush(Unknown Source)
            at com.chrishammer.repository.HouseholdRepositoryImpl.save(HouseholdRepositoryImpl.java:23)
            at com.chrishammer.service.HouseholdServiceImpl.save(HouseholdServiceImpl.java:24)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
            at java.lang.reflect.Method.invoke(Method.java:498)
            at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333)
            at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
            at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
            at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
            at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
            at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
            at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
            at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
            at com.sun.proxy.$Proxy41.save(Unknown Source)
            at com.chrishammer.controller.CreateAccountController.submitUser(CreateAccountController.java:34)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
            at java.lang.reflect.Method.invoke(Method.java:498)
            at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
            at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
            at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
            at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
            at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
            at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
            at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
            at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
            at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
            at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
            at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
            at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
            at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
            at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
            at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
            at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
            at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
            at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
            at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
            at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
            at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
            at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:495)
            at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
            at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:767)
            at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1347)
            at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
            at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
            at java.lang.Thread.run(Thread.java:745)

Persistence.xml

<persistence    xmlns="http:://java.sun.com/xml/ns.persistence"
            xmlns:xsi="http:://www.w3.org/2001/XMLSchema-instance"
            xsi:schemaLocation="http:://java.sun.com/xml/ns.persistence
                                http:://java.sun.com/xml/ns/persistence_2_0.xsd"
            version ="2.0" >

<persistence-unit name="punit">
    <property name="javax.persistence.validation.mode" value="none"/>
</persistence-unit>

</persistence>

jpaContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

<context:annotation-config />
<context:component-scan base-package="com.chrishammer" />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitName" value="punit" />
    <property name="dataSource" ref="dataSource" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="showSql" value="true" />
        </bean>
    </property>
    <property name ="jpaPropertyMap">
        <map>
            <entry key="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
            <entry key="hibernate.hbm2ddl.auto" value="update" />
            <entry key="hivernate.format_sql" value="true" />
        </map>
    </property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<tx:annotation-driven />

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/testingDb?autoReconnect=true" />
    <property name="username" value="root" />
    <property name="password" value="root" />
</bean>
</beans>

If you need anything else let me know, any help would be much appreciated.


问:
Data structures for bioinformatics
What are some data structures that should be known by somebody involved in bioinformatics? I guess that anyone is supposed to know about lists, hashes, balanced trees, etc., but I expect that there are domain specific data structures. Is there any book devoted to this subject?</p>

答:
A lot of introductory books on bioinformatics will cover some of the basic structures you'd use. I'm not sure what the standard textbook is, but I'm sure you can find that. It might be useful to look at some of the language-specific books:

Bioinformatics Programming With Python

Beginning Perl for Bioinformatics

I chose those two as examples because they're published by O'Reilly, which, in my experience, publishes good quality books.

I just so happen to have the Python book on my hard drive, and a great deal of it talks about processing strings for bioinformatics using Python. It doesn't seem like bioinformatics uses any fancy special data structures, just existing ones.

Title: Data structures for bioinformatics

ContentLicense: CC BY-SA 2.5


问:
Azure git ignore
I have a .NET web application that uses some settings from a web.config file. Various instances of this app are installed on azure and each installation has a different connection string in its web.config file that controls the connection with the database. Azure picks the binaries for this app from bitbucket.
In other words, 10 azure web sites that use the same code, all of them are connected to the same repository in bitbucket and each one of them has a different connection string to a different database.
Each time I create a new release, Azure gets this new release from bitbucket and overwrites web.config of each application. Is there away to instruct Azure to ignore the web.config file from bitbucket when pulling a new Release?</p>

答: After some research,in order to get Azure seetings for a PHP app use http://blog.syntaxc4.net/post/2012/07/26/accessing-app-settings-configured-in-microsoft-azure-web-sites-using-php-and-node-js.aspx and for a .NET app use this https://azure.microsoft.com/en-us/blog/windows-azure-web-sites-how-application-strings-and-connection-strings-work/</p>

Title: Azure git ignore


问:
Facebook - Get unpublished and hidden posts with Real-Time API
I'm trying to subscribe to the promotable_posts endpoint of the Facebook page to get updates for unpublished and hidden posts ("dark posts"). According to Facebook it should be possible to subscribe to that endpoint: https://developers.facebook.com/docs/pages/realtime#data

But that endpoint is not listed on https://developers.facebook.com/apps/[APP_ID]/webhooks/ and I can't add the subscription of the endpoint via the API either. It's working for endpoints like feed.

How can I subscribe to that endpoint? And how can I get hidden posts? Normally I would use https://graph.facebook.com/[PAGE_ID]/promotable_posts?include_hidden=true&access_token=... to get those posts when I'm polling, but I can't tell Facebook to include hidden posts when I subscribe to an endpoint.

答:
is_hidden
  If this post is marked as hidden (Applies to Pages only)

From Facebook documentation here.

This flag tells you if the posts are hidden also known as unpublished or "dark posts". Basically it's a post that is shown in public feed but not in the page feed.
However, when you make a call to FB Graph API you still get all the posts, just add this flag in your request in order to filter them later.

The best approach would be pull the data from the api, and manage it in your side, since there is no way to filter them on your calls.


问:
How to resize all forms to specific resolution including controls
I am able to resize my current main form by doing this:

```<code>Form1.Hight = Screen.TwipsPerPixelY * 600
Form1.Width = Screen.TwipsPerPixelX * 800
</code>```

The issue is my program contains more forms that open up. I want them all to resize to this resolution, including the controls.

How can I do this?

答:
Create a function that loops through all the controls in your project and create global variables that will be accessed in that function.

Use this function when you want to resize

Body:
I am able to resize my current main form by doing this:

Form1.Hight = Screen.TwipsPerPixelY * 600
Form1.Width = Screen.TwipsPerPixelX * 800

The issue is my program contains more forms that open up. I want them all to resize to this resolution, including the controls.

How can I do this?


问:
java regex pattern matching vs schema validation
Please consider the regex pattern : .*[a-zA-Z0-9\\-\\_].*.

If I use Java regex pattern matching to match "-", it says it is true.

```<code>String regexCostcode1=".*[a-zA-Z0-9\\-\\_].*";
Pattern regex_costcode=Pattern.compile(regexCostcode1);
String test="-";
Matcher m = regex_costcode.matcher(test);
System.out.println(m.matches());
</code>```

This prints true.

But same regex fails for "-" in XSD schema validation.

I checked using http://regexr.com/ it fails to match "-".

So why it is matching using Java pattern matching?

答:
Mind that in a Java string literal you need 2 backslashes to define a literal backslash. When you use \\ at the regexr.com, or in XML Schema regex, you use 2 literal backslashes that match a literal backslash in the input string, and the [\\-\\] construct matches a single \.

In XML Schema, you need to define the regex as

```<code><xs:pattern value=".*[a-zA-Z0-9_-].*"/>
</code>```

Put the - at the end of the character class to be parsed as a literal -. The underscore does not need to be escaped at all, as it is never a special char (it is actually a "word" char).

Actually, I'd advise to use ".*[a-zA-Z0-9_-].*" in Java, too, to avoid any ambiguity.

Body:
Please consider the regex pattern : .*[a-zA-Z0-9\\-\\_].*.

If I use Java regex pattern matching to match "-", it says it is true.

String regexCostcode1=".*[a-zA-Z0-9\\-\\_].*";
Pattern regex_costcode=Pattern.compile(regexCostcode1);
String test="-";
Matcher m = regex_costcode.matcher(test);
System.out.println(m.matches());

This prints true.

But same regex fails for "-" in XSD schema validation.

I checked using http://regexr.com/ it fails to match "-".

So why it is matching using Java pattern matching?

Body:
Mind that in a Java string literal you need 2 backslashes to define a literal backslash. When you use \\ at the regexr.com, or in XML Schema regex, you use 2 literal backslashes that match a literal backslash in the input string, and the [\\-\\] construct matches a single \.

In XML Schema, you need to define the regex as

<xs:pattern value=".*[a-zA-Z0-9_-].*"/>

Put the - at the end of the character class to be parsed as a literal -. The underscore does not need to be escaped at all, as it is never a special char (it is actually a "word" char).

Actually, I'd advise to use ".*[a-zA-Z0-9_-].*" in Java, too, to avoid any ambiguity.


问:
How to carry the value of checkbox to a php page and output an .xls file?
I am trying to download the contents from mysql db on checkbox selection and button click in excel format. The program is working. But the problem is that I'm only getting one value instead of the entire row. An error on excel file shows undefined index on the line of query.

```<code>    <form action="connect.php" method="POST">

     <table class= "table table-condensed table-striped">

     <thead>
     <tr class="warning">
     <th></th>
     <th>Delivery No.</th>
     <th>Invoice Number</th>
     <th>Bill Date</th>
     <th>Customer</th>
     <th>Quantity</th>
     <th>Brand</th>

     </tr>

     </thead>

     <?php while ($row = mysql_fetch_array($filter_result)){ ?>
                      <tr>

<td class="border-right" align="center"><input type="checkbox" name="check[]" id="check[]" value= "<?php echo $row['Delivery_no']; ?>" /></td>
<td><?php echo $row['Delivery_no'];?></td>
<td><?php echo $row['Invoice_no'];?></td>
<td><?php echo $row['Bill_date'];?></td>
<td><?php echo $row['Bill_to_party'];?></td>
<td><?php echo $row['Quantity'];?></td>
<td><?php echo $row['Brand']; } ?></td>
                        </tr>

     </table>
     <br>

     <input type= "submit" name="submit" id="submit" value="submit" class="btn btn-primary button-loading">

     </form>
</code>```

PHP CODE

```<code>if (is_array($_REQUEST['check']) and count($_REQUEST['check']) > 0)
{
    $checks = implode(array_map('intval', $_REQUEST['check']));

    $sql = "Select * from $DB_TBLName WHERE Delivery_no IN ($checks)" ;
    echo $sql;
    $result = @mysql_query($sql,$Connect) or die("Couldn't execute query:<br>" . mysql_error(). "<br>" . mysql_errno());
    if(isset($_POST['submit'])){
       if(!empty($_POST['check'])) {
          // Loop to store and display values of individual checked checkbox.
          foreach($_POST['check'] as $selected) {
             echo $selected ;
          }
       }
    }
    $sep = "\t";
    for ($i = 0; $i < mysql_num_fields($result); $i++) {
       echo mysql_field_name($result,$i) . "\t";
    }
    print("\n");
    while($row = mysql_fetch_row($result)){
       $schema_insert = "";
       for($j=0; $j<mysql_num_fields($result);$j++) {
          if(!isset($row[$j]))
             $schema_insert .= "NULL".$sep;
          elseif ($row[$j] != "")
             $schema_insert .= "$row[$j]".$sep;
          else
             $schema_insert .= "".$sep;
       }
       $schema_insert = str_replace($sep."$", "", $schema_insert);
       $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
       $schema_insert .= "\t";
       print(trim($schema_insert));
       print "\n";
    }
    $file_ending = "xls";
    header("Content-Type: application/xls");
    header("Content-Disposition: attachment; filename=$filename.xls");
    header("Pragma: no-cache");
    header("Expires: 0");
}
</code>```

答:
To check a checkbox you need to add the "checked" attribute. So if your $row['Delivery_no'] contains a boolean indicating whether or not the checkbox should be checked, you could try:

```<code><input type="checkbox" name="check[]" id="check[]" <?php if( $row['Delivery_no']) echo "checked"; ?> />
</code>```

Body:
I am trying to download the contents from mysql db on checkbox selection and button click in excel format. The program is working. But the problem is that I'm only getting one value instead of the entire row. An error on excel file shows undefined index on the line of query.

    <form action="connect.php" method="POST">

     Delivery No.
     Invoice Number
     Bill Date
     Customer
     Quantity
     Brand

     <?php while ($row = mysql_fetch_array($filter_result)){ ?>

<input type="checkbox" name="check[]" id="check[]" value= "<?php echo $row['Delivery_no']; ?>" />
<?php echo $row['Delivery_no'];?>
<?php echo $row['Invoice_no'];?>
<?php echo $row['Bill_date'];?>
<?php echo $row['Bill_to_party'];?>
<?php echo $row['Quantity'];?>
<?php echo $row['Brand']; } ?>

     <input type= "submit" name="submit" id="submit" value="submit" class="btn btn-primary button-loading">

     </form>

PHP CODE

if (is_array($_REQUEST['check']) and count($_REQUEST['check']) > 0)
{
    $checks = implode(array_map('intval', $_REQUEST['check']));

    $sql = "Select * from $DB_TBLName WHERE Delivery_no IN ($checks)" ;
    echo $sql;
    $result = @mysql_query($sql,$Connect) or die("Couldn't execute query:
" . mysql_error(). "
" . mysql_errno());
    if(isset($_POST['submit'])){
       if(!empty($_POST['check'])) {
          // Loop to store and display values of individual checked checkbox.
          foreach($_POST['check'] as $selected) {
             echo $selected ;
          }
       }
    }
    $sep = "\t";
    for ($i = 0; $i < mysql_num_fields($result); $i++) {
       echo mysql_field_name($result,$i) . "\t";
    }
    print("\n");
    while($row = mysql_fetch_row($result)){
       $schema_insert = "";
       for($j=0; $j<mysql_num_fields($result);$j++) {
          if(!isset($row[$j]))
             $schema_insert .= "NULL".$sep;
          elseif ($row[$j] != "")
             $schema_insert .= "$row[$j]".$sep;
          else
             $schema_insert .= "".$sep;
       }
       $schema_insert = str_replace($sep."$", "", $schema_insert);
       $schema_insert = preg_replace("/\r\n|\n\r|\n|\r/", " ", $schema_insert);
       $schema_insert .= "\t";
       print(trim($schema_insert));
       print "\n";
    }
    $file_ending = "xls";
    header("Content-Type: application/xls");
    header("Content-Disposition: attachment; filename=$filename.xls");
    header("Pragma: no-cache");
    header("Expires: 0");
}

Body:
To check a checkbox you need to add the "checked" attribute. So if your $row['Delivery_no'] contains a boolean indicating whether or not the checkbox should be checked, you could try:

<input type="checkbox" name="check[]" id="check[]" <?php if( $row['Delivery_no']) echo "checked"; ?> />


问:
find the minimum and maximum distance between 2 rectangles of any dimension
I have a Rectangle class that represents a  d-dimension rectangle with 2*d numbers for every dimension. For every dimension i have a lower and an upper bound. Dimensionality stores the number of dimensions of the rectangle, and for the lower and upper bounds i use a double array.

I want to create 2 methods that they have as input another rectangle object of the same Dimensionality and return the minimum and maximum distance between the rectangles, im trying to do this using the minimum/maximum distances of each of their projections in every axis. I also have a method that creates the projections.

```<code>//returns 2 position array
    public double[] project(int x)
    {
        //x is the selected dimension
        double proj[] = new double[2];
        proj[0] = this.lb[x];
        proj[1] = this.ub[x];
        return proj;
    }
</code>```

you can see on the third set of shapes what i want to do more clearly

https://s15.postimg.org/l8aijyl1n/imageedit_2_6689786765.jpg

答:
Find mutual orientation of rectangles (as direction of vector between centers, it is enough to get signs of center.x and center.y differences)

Depending on orientation quadrant, get distances from selected edges of the first rectangle to selected edges of the second. Using signs of these distances, find extremal distances:

For the case at the picture (direction in the 4th quadrant) one have to check distances from right bottom corner of the first rectangle to the left and top edges of the second one, and from left top corner of the second - to the right and bottom edges of the first one.

```<code> min_dx = rect2.left - rect1.right
 min_dy = rect2.top - rect.bottom
 if both values > 0 (++ case)
    min_dist = sqrt(min_dx^2 + min_dy^2) //corner-corner case

 +- case
   min_dist = min_dx
 -+ case
   min_dist = min_dy
 -- case
    min_dist = 0
</code>```

Seems the same approach might be used for higher dimensions. Number of cases becomes too high, so it is worth to select planes for checking with indexes corresponding to center-center direction vector components' signs

Body:
I have a Rectangle class that represents a  d-dimension rectangle with 2*d numbers for every dimension. For every dimension i have a lower and an upper bound. Dimensionality stores the number of dimensions of the rectangle, and for the lower and upper bounds i use a double array.

I want to create 2 methods that they have as input another rectangle object of the same Dimensionality and return the minimum and maximum distance between the rectangles, im trying to do this using the minimum/maximum distances of each of their projections in every axis. I also have a method that creates the projections.

//returns 2 position array
    public double[] project(int x)
    {
        //x is the selected dimension
        double proj[] = new double[2];
        proj[0] = this.lb[x];
        proj[1] = this.ub[x];
        return proj;
    }

you can see on the third set of shapes what i want to do more clearly

https://s15.postimg.org/l8aijyl1n/imageedit_2_6689786765.jpg

Body:
Find mutual orientation of rectangles (as direction of vector between centers, it is enough to get signs of center.x and center.y differences)

Depending on orientation quadrant, get distances from selected edges of the first rectangle to selected edges of the second. Using signs of these distances, find extremal distances:

For the case at the picture (direction in the 4th quadrant) one have to check distances from right bottom corner of the first rectangle to the left and top edges of the second one, and from left top corner of the second - to the right and bottom edges of the first one.

 min_dx = rect2.left - rect1.right
 min_dy = rect2.top - rect.bottom
 if both values > 0 (++ case)
    min_dist = sqrt(min_dx^2 + min_dy^2) //corner-corner case

 +- case
   min_dist = min_dx
 -+ case
   min_dist = min_dy
 -- case
    min_dist = 0

Seems the same approach might be used for higher dimensions. Number of cases becomes too high, so it is worth to select planes for checking with indexes corresponding to center-center direction vector components' signs


答:
In the Xml file

android:scaleType="centerCrop"

Title: Android: icon drawable padding

Body:
I created icon resource on Android Asset Studio with no padding. The icon has a blank on the left and right side. When I set it as a source in ImageView, the ImageView looks like having padding on left and right.

How can I remove the blank on the left and right of the icon in the ImageView?

Here is my icon:


问:
Fuzzy queries to database
I'm curious about how works feature on many social sites today.

For example, you enter list of movies you like and system suggests other movies you may like (based on movies that like other people who likes the same movies that you). I think doing it straight-sql way (join list of my movies with movies-users join with user-movies group by movie title and apply count to it ) on large datasets would be just impossible to implement due to "heaviness" of such query.

At the same time we don't need exact solution, approximate would be enough. I wonder is there way to implement something like fuzzy query to traditional RDBMS that would be fast to execute but has some infelicity. Or how such features implemented on real systems.

答:
The term you are looking for is "collaborative filtering"

Read Programming Collective Intelligence, by O'Reilly Press

Title: Fuzzy queries to database


问:
How do I always show the line number of the error in R?
In R you can see the line number of an error using the following option:

```<code>options(show.error.locations = TRUE)
</code>```

Is there anyway to enable this feature by default on starting the R interpreter?

答:
Add the option to your user specific .Rprofile file

```<code>options(show.error.locations = TRUE)
</code>```

You can find the folder in which your user specific .Rprofile file should be using this function:

```<code>path.expand("~")
</code>```

If a .Rprofile file does not already exist here, create it.

Body:
In R you can see the line number of an error using the following option:

options(show.error.locations = TRUE)

Is there anyway to enable this feature by default on starting the R interpreter?

Body:
Add the option to your user specific .Rprofile file

options(show.error.locations = TRUE)

You can find the folder in which your user specific .Rprofile file should be using this function:

path.expand("~")

If a .Rprofile file does not already exist here, create it.


问:
How to Serialize Tree Structure Data From Database to JSON
I have data in a data store which represents a tree structure. Following code represents how it can be described in a simple DataTable in C#.

```<code>using System.Data;

namespace DemoConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable treeData = new DataTable();
            treeData.Clear();
            treeData.Columns.Add("NodeId", typeof(int));
            treeData.Columns.Add("ParentNodeId", typeof(int));
            treeData.Columns.Add("Data", typeof(string));
            treeData.Columns.Add("AbsolutePath", typeof(string));

            DataRow record1 = treeData.NewRow();
            record1["NodeId"] = 1;
            record1["ParentNodeId"] = 0;
            record1["Data"] = "Dairy";
            record1["AbsolutePath"] = "/Dairy/";
            treeData.Rows.Add(record1);

            DataRow record2 = treeData.NewRow();
            record2["NodeId"] = 2;
            record2["ParentNodeId"] = 1;
            record2["Data"] = "Yoghurt";
            record2["AbsolutePath"] = "/Dairy/Yoghurt";
            treeData.Rows.Add(record2);

            DataRow record3 = treeData.NewRow();
            record3["NodeId"] = 3;
            record3["ParentNodeId"] = 1;
            record3["Data"] = "Cheese";
            record3["AbsolutePath"] = "/Dairy/Cheese";
            treeData.Rows.Add(record3);

            DataRow record4 = treeData.NewRow();
            record4["NodeId"] = 4;
            record4["ParentNodeId"] = 2;
            record4["Data"] = "Flavored";
            record4["AbsolutePath"] = "/Dairy/Yoghurt/Flavored";
            treeData.Rows.Add(record4);
        }
    }
}
</code>```

I need to serialize the data into the following structure.

```<code>{
  "TreeData": {
    "NodeId" : "1",
    "Data" : "Dairy",
    "Children": [
      {
        "NodeId": "2",
        "Data": "Yohurt",
        "Children": [
          {
              "NodeId": "4",
              "Data": "Flavored",
              "Children": []
          }
        ]
      },
      {
        "NodeId": "3",
        "Data": "Cheese",
        "Children": []
      }
    ]
  }
}
</code>```

How do i go about achieving this?

答:
Create a new class:

```<code>class Node
{
    public int NodeId;
    public int ParentNodeId;
    public string Data;
    public string AbsolutePath;
    public List<Node> Children = new List<Node>();
}
</code>```

Then iterate over rows of the DataTable, create an appropriate tree structure and simply call JsonConvert.SerializeObject()

```<code>var nodes = new Dictionary<int, Node>();
foreach(DataRow record in treeData.Rows)
{
    var node = new Node { NodeId = (int)record["NodeId"], ParentNodeId = (int)record["ParentNodeId"], Data = (string)record["Data"], AbsolutePath = (string)record["AbsolutePath"] };
    nodes.Add(node.NodeId, node);
}

var rootNodeId = 1;
var rootNode = nodes[rootNodeId];
foreach(var keyValuePair in nodes)
{
    var node = keyValuePair.Value;
    if(node.NodeId != rootNodeId)
    {
        nodes[node.ParentNodeId].Children.Add(node);
    }
}

string json = JsonConvert.SerializeObject(rootNode, Formatting.Indented);
Debug.WriteLine(json);
</code>```

Output:

```<code>{
  "NodeId": 1,
  "ParentNodeId": 1,
  "Data": "Dairy",
  "AbsolutePath": "/Dairy/",
  "Children": [
    {
      "NodeId": 2,
      "ParentNodeId": 1,
      "Data": "Yoghurt",
      "AbsolutePath": "/Dairy/Yoghurt",
      "Children": [
        {
          "NodeId": 4,
          "ParentNodeId": 1,
          "Data": "Flavored",
          "AbsolutePath": "/Dairy/Flavored",
          "Children": []
        }
      ]
    },
    {
      "NodeId": 3,
      "ParentNodeId": 1,
      "Data": "Cheese",
      "AbsolutePath": "/Dairy/Cheese",
      "Children": []
    }
  ]
}
</code>```

Body:
I have data in a data store which represents a tree structure. Following code represents how it can be described in a simple DataTable in C#.

using System.Data;

namespace DemoConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable treeData = new DataTable();
            treeData.Clear();
            treeData.Columns.Add("NodeId", typeof(int));
            treeData.Columns.Add("ParentNodeId", typeof(int));
            treeData.Columns.Add("Data", typeof(string));
            treeData.Columns.Add("AbsolutePath", typeof(string));

            DataRow record1 = treeData.NewRow();
            record1["NodeId"] = 1;
            record1["ParentNodeId"] = 0;
            record1["Data"] = "Dairy";
            record1["AbsolutePath"] = "/Dairy/";
            treeData.Rows.Add(record1);

            DataRow record2 = treeData.NewRow();
            record2["NodeId"] = 2;
            record2["ParentNodeId"] = 1;
            record2["Data"] = "Yoghurt";
            record2["AbsolutePath"] = "/Dairy/Yoghurt";
            treeData.Rows.Add(record2);

            DataRow record3 = treeData.NewRow();
            record3["NodeId"] = 3;
            record3["ParentNodeId"] = 1;
            record3["Data"] = "Cheese";
            record3["AbsolutePath"] = "/Dairy/Cheese";
            treeData.Rows.Add(record3);

            DataRow record4 = treeData.NewRow();
            record4["NodeId"] = 4;
            record4["ParentNodeId"] = 2;
            record4["Data"] = "Flavored";
            record4["AbsolutePath"] = "/Dairy/Yoghurt/Flavored";
            treeData.Rows.Add(record4);
        }
    }
}

I need to serialize the data into the following structure.

{
  "TreeData": {
    "NodeId" : "1",
    "Data" : "Dairy",
    "Children": [
      {
        "NodeId": "2",
        "Data": "Yohurt",
        "Children": [
          {
              "NodeId": "4",
              "Data": "Flavored",
              "Children": []
          }
        ]
      },
      {
        "NodeId": "3",
        "Data": "Cheese",
        "Children": []
      }
    ]
  }
}

How do i go about achieving this?

Body:
Create a new class:

class Node
{
    public int NodeId;
    public int ParentNodeId;
    public string Data;
    public string AbsolutePath;
    public List<Node> Children = new List<Node>();
}

Then iterate over rows of the DataTable, create an appropriate tree structure and simply call JsonConvert.SerializeObject()

var nodes = new Dictionary<int, Node>();
foreach(DataRow record in treeData.Rows)
{
    var node = new Node { NodeId = (int)record["NodeId"], ParentNodeId = (int)record["ParentNodeId"], Data = (string)record["Data"], AbsolutePath = (string)record["AbsolutePath"] };
    nodes.Add(node.NodeId, node);
}

var rootNodeId = 1;
var rootNode = nodes[rootNodeId];
foreach(var keyValuePair in nodes)
{
    var node = keyValuePair.Value;
    if(node.NodeId != rootNodeId)
    {
        nodes[node.ParentNodeId].Children.Add(node);
    }
}

string json = JsonConvert.SerializeObject(rootNode, Formatting.Indented);
Debug.WriteLine(json);

Output:

{
  "NodeId": 1,
  "ParentNodeId": 1,
  "Data": "Dairy",
  "AbsolutePath": "/Dairy/",
  "Children": [
    {
      "NodeId": 2,
      "ParentNodeId": 1,
      "Data": "Yoghurt",
      "AbsolutePath": "/Dairy/Yoghurt",
      "Children": [
        {
          "NodeId": 4,
          "ParentNodeId": 1,
          "Data": "Flavored",
          "AbsolutePath": "/Dairy/Flavored",
          "Children": []
        }
      ]
    },
    {
      "NodeId": 3,
      "ParentNodeId": 1,
      "Data": "Cheese",
      "AbsolutePath": "/Dairy/Cheese",
      "Children": []
    }
  ]
}


问:
DevExpress Report Designer MVC make subreport use main report datasource
I am placing a report designer on my website for users to design reports with.  The user will make a selection from a dropdown and depending on the selection, a DevExpress ReportDesigner loads with the appropriate datasource binded to it.  I have successfully achieved this, however, if the user adds a subreport to the report, the main report datasource is not passed down to the subreport.  How do I accomplish this?</p>

答:
Subreport should use its own DataSource.

but you can pass "master" dataousrce on the "BeforePrint" event.

how to pass datasource to the subreport: one and two


问:
Appending to $(this)
Within a function loop, I need to traverse further into the DOM.

```<code>$('.panel_wrapper .panel').each(function(index) {
   // how can I append to this.  For instance another class = "foo"
   $(this) .foo  /* does not work */
</code>```

This is similar to what I'm trying to do in a function

```<code>$(this) = $('.panel_wrapper .panel');
$(this) .foo
</code>```

The following is a better example:

```<code>$('.panel-wrapper .panel').each(function(index) {
  $('.panel-wrapper .panel:eq(' + index + ') .collection_alt_thumbs img:eq(0)').css({"border-color" : "#9B9B9B", "opacity" : 1});
});
</code>```

Within the function there are additional operations that will be performed, not necessary after the first operation but after a conditional statement.  Can the following be performed:

```<code>$('.panel-wrapper .panel').each(function(index) {
   $(this)  ('.collection_alt_thumbs img:eq(0)').css({"border-color" : "#9B9B9B", "opacity" : 1});
   // conditional statement
   $(this) /* some other element */

});
</code>```

答:
Do you want to append to the selectors (i.e. further limit the items selected) or append to the items selected? @Darin's solution will do the former; if you want to select more items and traverse over them as well you can do one of the following:

```<code>$('.panel_wrapper .panel').add('.foo').each(function(index) {
</code>```

or

```<code>$('.panel_wrapper .panel, .foo').each(function(index) {
</code>```

Title: Appending to $(this)

Body:
Within a function loop, I need to traverse further into the DOM.

$('.panel_wrapper .panel').each(function(index) {
   // how can I append to this.  For instance another class = "foo"
   $(this) .foo  /* does not work */

This is similar to what I'm trying to do in a function

$(this) = $('.panel_wrapper .panel');
$(this) .foo

The following is a better example:

$('.panel-wrapper .panel').each(function(index) {
  $('.panel-wrapper .panel:eq(' + index + ') .collection_alt_thumbs img:eq(0)').css({"border-color" : "#9B9B9B", "opacity" : 1});
});

Within the function there are additional operations that will be performed, not necessary after the first operation but after a conditional statement.  Can the following be performed:

$('.panel-wrapper .panel').each(function(index) {
   $(this)  ('.collection_alt_thumbs img:eq(0)').css({"border-color" : "#9B9B9B", "opacity" : 1});
   // conditional statement
   $(this) /* some other element */

});

Body:
Do you want to append to the selectors (i.e. further limit the items selected) or append to the items selected? @Darin's solution will do the former; if you want to select more items and traverse over them as well you can do one of the following:

$('.panel_wrapper .panel').add('.foo').each(function(index) {

or

$('.panel_wrapper .panel, .foo').each(function(index) {


问:
html 5 DATE doesn't work in Windows Exploror and Firefox
i been working on ticker reservation system and i used date function in forms but , which works fine on chrome but does not work on windows explorer and Firefox. what should i do?</p>

```<code>departure date: <input type="date" name="departuredate"> departure time : <input type="time" name="departuretime"> arrival date : <input type="date" name="arrivaldate"> arrival time : <input type="time" name="arrivaltime">
</code>```

答:
You should use a third party date picker plugin which works on almost all browsers like JQuery UI Datepicker:

See the demo below:

https://jqueryui.com/datepicker/

  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

Date: <input type="text" id="datepicker">
```
</div>
</div>
</p>

<p><strong>How to use</strong></p>

<p>In the <code><head> </head></code> tags of your page insert the following lines:</p>

```  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

```

<p>Now create an input element which will be used as the datepicker like below:</p>

```<input type="text" id="datepicker">
```

<p>Now before closing the body tag (<code></body></code>) copy the following lines:</p>

```
```

Or if you want you can copy these lines in the head tags as well, but I would recommend you put them here.

Body:
i been working on ticker reservation system and i used date function in forms but , which works fine on chrome but does not work on windows explorer and Firefox. what should i do?

departure date: <input type="date" name="departuredate"> departure time : <input type="time" name="departuretime"> arrival date : <input type="date" name="arrivaldate"> arrival time : <input type="time" name="arrivaltime">

Body:
You should use a third party date picker plugin which works on almost all browsers like JQuery UI Datepicker:

See the demo below:

https://jqueryui.com/datepicker/

  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    $( "#datepicker" ).datepicker();
  } );
  </script>

<p>Date: <input type="text" id="datepicker"></p>

How to use

In the <head> </head> tags of your page insert the following lines:

  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

Now create an input element which will be used as the datepicker like below:

<input type="text" id="datepicker">

Now before closing the body tag (</body>) copy the following lines:

  <script>
  $( function() {
    $( "#datepicker" ).datepicker();
  } );
  </script>

Or if you want you can copy these lines in the head tags as well, but I would recommend you put them here.