问:
add_fee() is adding the fee twice on checkout total
I am trying to add fee on the checkout page based on the field user selects.

When I use WC_cart add_fee() method, it adds the fee twice on the total whereas it shows only once on the checkout. So the checkout total is calculating wrong.

Here is the code I am trying:

```<code>add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge',50 );
function woocommerce_custom_surcharge(WC_Cart $cart) {
      global $woocommerce;

    $eu_array = array('BE','BG','CZ','DK','DE','EE','IE','GR','ES','FR','HR','CY','LV','LT','LU','HU','MT','NL','AT','PT','RO','SI','SK','FI','GB');

    if(preg_match("#customer_type=company#", $_POST['post_data']) ){

        if(in_array($_POST['s_country'], $eu_array)){
            $woocommerce->cart->add_discount(sanitize_text_field( 'cart_company_dis' ));
            $ship = $cart->shipping_total;
            $shipp = $ship - ($ship*100/122);
            wc()->cart->add_fee('Exclude shipping VAT', -$shipp);
        }
    }elseif(preg_match("#customer_type=customer#", $_POST['post_data']) ){
        $woocommerce->cart->remove_coupon(sanitize_text_field( 'cart_company_dis' ));

    }
}
</code>```

The code applies the discount on the checkout page and adds fee as well based on the customer type and country.

The discount gets reduced correctly but fee is added twice.

How can I avoid this issue?

Thanks.

答:
You can use WC_Cart method get_fees() to check if a particular fee is already applied in cart, avoiding the duplicated fee issue.

So your code is going to be a little changed:

```<code>// NOTE:
// No need of "global woocommerce" and "woocommerce->cart" (old syntax) replaced by "WC()->cart"
// Here "$cart_obj" replace "WC()->cart" everywhere, as it included as argument in the function…

add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge',50 );
function woocommerce_custom_surcharge( $cart_obj ) {

    $eu_array = array('BE','BG','CZ','DK','DE','EE','IE','GR','ES','FR','HR',
        'CY','LV','LT','LU','HU','MT','NL','AT','PT','RO','SI','SK','FI','GB');

    if(preg_match("#customer_type=company#", $_POST['post_data']) ){

        if(in_array($_POST['s_country'], $eu_array)){
            $cart_obj->add_discount(sanitize_text_field( 'cart_company_dis' ));

            $ship = $cart_obj->shipping_total;
            $shipp = $ship - ($ship * 100 / 122);

            // Getting the cart fees
            $cart_fees = $cart_obj->get_fees();
            $has_the_fee = true;

            // Iterating through each cart fees
            foreach($cart_fees as $fee_obj)
                if( 'exclude-shipping-vat' != $fee_obj->id ){}
                    $has_the_fee = false; // Has not 'Exclude shipping VAT' fee

            // Add the fee if it doesn't exist yet (avoiding duplicate fee)
            if( empty($cart_fees) || $has_the_fee )
                $cart_obj->add_fee( __( 'Exclude shipping VAT', 'woocommerce' ), -$shipp );
        }
    } elseif( preg_match( "#customer_type=customer#", $_POST['post_data'] ) ){
        $cart_obj->remove_coupon( sanitize_text_field( 'cart_company_dis' ) );

    }
}
</code>```

The Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works.

Body:
I am trying to add fee on the checkout page based on the field user selects.

When I use WC_cart add_fee() method, it adds the fee twice on the total whereas it shows only once on the checkout. So the checkout total is calculating wrong.

Here is the code I am trying:

add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge',50 );
function woocommerce_custom_surcharge(WC_Cart $cart) {
      global $woocommerce;

    $eu_array = array('BE','BG','CZ','DK','DE','EE','IE','GR','ES','FR','HR','CY','LV','LT','LU','HU','MT','NL','AT','PT','RO','SI','SK','FI','GB');

    if(preg_match("#customer_type=company#", $_POST['post_data']) ){

        if(in_array($_POST['s_country'], $eu_array)){
            $woocommerce->cart->add_discount(sanitize_text_field( 'cart_company_dis' ));
            $ship = $cart->shipping_total;
            $shipp = $ship - ($ship*100/122);
            wc()->cart->add_fee('Exclude shipping VAT', -$shipp);
        }
    }elseif(preg_match("#customer_type=customer#", $_POST['post_data']) ){
        $woocommerce->cart->remove_coupon(sanitize_text_field( 'cart_company_dis' ));

    }
}

The code applies the discount on the checkout page and adds fee as well based on the customer type and country.

The discount gets reduced correctly but fee is added twice.

How can I avoid this issue?

Thanks.

Body:
You can use WC_Cart method get_fees() to check if a particular fee is already applied in cart, avoiding the duplicated fee issue.

So your code is going to be a little changed:

// NOTE:
// No need of "global woocommerce" and "woocommerce->cart" (old syntax) replaced by "WC()->cart"
// Here "$cart_obj" replace "WC()->cart" everywhere, as it included as argument in the function…

add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge',50 );
function woocommerce_custom_surcharge( $cart_obj ) {

    $eu_array = array('BE','BG','CZ','DK','DE','EE','IE','GR','ES','FR','HR',
        'CY','LV','LT','LU','HU','MT','NL','AT','PT','RO','SI','SK','FI','GB');

    if(preg_match("#customer_type=company#", $_POST['post_data']) ){

        if(in_array($_POST['s_country'], $eu_array)){
            $cart_obj->add_discount(sanitize_text_field( 'cart_company_dis' ));

            $ship = $cart_obj->shipping_total;
            $shipp = $ship - ($ship * 100 / 122);

            // Getting the cart fees
            $cart_fees = $cart_obj->get_fees();
            $has_the_fee = true;

            // Iterating through each cart fees
            foreach($cart_fees as $fee_obj)
                if( 'exclude-shipping-vat' != $fee_obj->id ){}
                    $has_the_fee = false; // Has not 'Exclude shipping VAT' fee

            // Add the fee if it doesn't exist yet (avoiding duplicate fee)
            if( empty($cart_fees) || $has_the_fee )
                $cart_obj->add_fee( __( 'Exclude shipping VAT', 'woocommerce' ), -$shipp );
        }
    } elseif( preg_match( "#customer_type=customer#", $_POST['post_data'] ) ){
        $cart_obj->remove_coupon( sanitize_text_field( 'cart_company_dis' ) );

    }
}

The Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works.


来源: stackexchange

问:
Scaling messes up the z-index
I have a set of absolute divs having background images which contains animation.
when i apply scale property to the divs it messes up my z-index totally
here is the link to the fiddle https://jsfiddle.net/kq2soozp/3/ (Uncomment transform:scale() line)

The HTML Code

```<code><div class='me'>

            <div class="torso">
                <div class="left leg">
                    <div class="left thigh">
                        <div class="left shin">
                            <div class="left foot">
                                <div class="left toes"></div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="right leg">
                    <div class="right thigh">
                        <div class="right shin">
                            <div class="right foot">
                                <div class="right toes"></div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="left arm">
                    <div class="left bicep">
                        <div class="left forearm">
                            <div class="kite"></div>
                        </div>
                    </div>
                </div>

                <div class="right arm">
                    <div class="right bicep">
                        <div class="right forearm"></div>
                    </div>
                </div>

            </div>
        </div>
</code>```

The CSS

```<code>.me,.me div{
    background-repeat: no-repeat;
    position: absolute;
    -webkit-animation-duration: 2000ms;
    -webkit-animation-iteration-count: infinite;
    -webkit-animation-timing-function: linear;
    //-webkit-transform: scale(0.9);
}
.me{
    top: 80px;
    left: 350px;
    -webkit-animation-name: me;
}
.torso{
    height: 274px;
    width: 86px;
    background-image: url("https://s9.postimg.org/41xfy5cin/torso.png");
}

.arm{
    left: 12px;
    -webkit-transform-origin: 20px 10px;
}

.kite{

    width: 395px;
    height: 424px;
    top: -115px;
    left: 0px;

    background-image: url("https://s3.postimg.org/ix240ioab/kite.png");
    -webkit-transform: rotate(45deg) scale(0.6);

}
.right.bicep{
    width: 51px;
    height: 124px;
    background-image: url("https://s3.postimg.org/mlrszzyb7/right-bicep.png");
}
.left.bicep{
    width: 52px;
    : 126px;
    background-image: url("https://s3.postimg.org/jb3g048dv/left-bicep.png");
}
.left.forearm{
    width: 37px;
    height: 124px;
    background-image: url("https://s3.postimg.org/7ahzze0z7/left-forearm.png");
    -webkit-transform: rotate(-45deg);
}
.right.forearm{
    width: 36px;
    height: 121px;
    background-image: url("https://s3.postimg.org/q6noj82ur/right-forearm.png");
    -webkit-animation-name: right-forearm;
}
.left.thigh{
    width: 69px;
    height: 144px;
    background-image: url("https://s3.postimg.org/577krq16b/left-thigh.png");
}
.right.thigh{
    width: 69px;
    height: 144px;
    background-image: url("https://s3.postimg.org/72ud2vq0j/right-thigh.png");
}
.shin{
    width: 53px;
    height: 173px;
    background-image: url("https://s3.postimg.org/3xecqews3/shin.png");
}
.foot{
    width: 67px;
    height: 34px;
    background-image: url("https://s3.postimg.org/l0cj86o37/foot.png");
}
.toes{
    width: 28px;
    height: 25px;
    background-image: url("https://s3.postimg.org/vm0zxxjsj/toes.png");
}

.right.arm{
    top: 93px;
    -webkit-animation-name: right-bicep;

}
.left.arm{
    top: 87px;
    -webkit-transform: rotate(-26deg);
}
.forearm{
    top: 108px;
    left: 14px;
    -webkit-transform-origin: 3px 7px;
}
.leg{
    left: 6px;
    -webkit-transform-origin: 30px 20px;
    -webkit-animation-name: thigh;
}
.right.leg{
    top: 235px;
    -webkit-animation-name: right-thigh;
}
.left.leg{
    top:225px;
    -webkit-animation-name: left-thigh;
}
.shin{
    top: 115px;
    -webkit-transform-origin: 30px 25px;
}
.right.shin {
    -webkit-animation-name: right-shin;
}
.left.shin {
    -webkit-animation-name: left-shin;
}
.foot{
    top: 155px;
    left: 2px;
    -webkit-transform-origin: 0 50%;
}
.right.foot {
    -webkit-animation-name: right-foot;
}
.left.foot {
    -webkit-animation-name: left-foot;
}
.toes{
    top: 9px;
    left: 66px;
    -webkit-transform-origin: 0% 100%;
}
.right.toes {
    -webkit-animation-name: right-toes;
}
.left.toes {
    -webkit-animation-name: left-toes;
}
div.right.arm { z-index: 1; }
div.left.arm { z-index: -3; }
div.arm > div.bicep > div.forearm { z-index: -1; }

div.right.leg { z-index: -1; }
div.left.leg { z-index: -2; }
div.leg > div.thigh > div.shin { z-index: -1; }

@-webkit-keyframes me {
    0% { -webkit-transform:   rotate(5deg) translate( 10px,   0px); }
    25% { -webkit-transform:  rotate(5deg) translate(-5px, -14px); }
    50% { -webkit-transform:  rotate(5deg) translate( 10px,   0px); }
    75% { -webkit-transform:  rotate(5deg) translate(-5px, -14px); }
    100% { -webkit-transform: rotate(5deg) translate( 10px,   0px); }
}
@-webkit-keyframes right-bicep {
    0%   { -webkit-transform: rotate(26deg); }
    50%  { -webkit-transform: rotate(-20deg); }
    100% { -webkit-transform: rotate(26deg); }
}

/*@-webkit-keyframes left-bicep {
    0%   { -webkit-transform: rotate(-20deg); }
    50%  { -webkit-transform: rotate(26deg); }
    100% { -webkit-transform: rotate(-20deg); }
}*/

@-webkit-keyframes right-forearm {
    0%   { -webkit-transform: rotate(-10deg); }
    50%  { -webkit-transform: rotate(-65deg); }
    100% { -webkit-transform: rotate(-10deg); }
}

/*@-webkit-keyframes left-forearm {
    0%   { -webkit-transform: rotate(-45deg); }
    50%  { -webkit-transform: rotate(-10deg); }
    100% { -webkit-transform: rotate(-45deg); }
}*/

@-webkit-keyframes right-thigh {
    0%   { -webkit-transform: rotate(-45deg); }
    50%  { -webkit-transform: rotate(10deg); }
    100% { -webkit-transform: rotate(-45deg); }
}

@-webkit-keyframes left-thigh {
    0%   { -webkit-transform: rotate(10deg); }
    50%  { -webkit-transform: rotate(-45deg); }
    100% { -webkit-transform: rotate(10deg); }
}

@-webkit-keyframes right-shin {
    0%   { -webkit-transform: rotate(30deg); }
    25%  { -webkit-transform: rotate(20deg); }
    50%  { -webkit-transform: rotate(20deg); }
    75%  { -webkit-transform: rotate(85deg); }
    100% { -webkit-transform: rotate(30deg); }
}

@-webkit-keyframes left-shin {
    0%   { -webkit-transform: rotate(20deg); }
    25%  { -webkit-transform: rotate(85deg); }
    50%  { -webkit-transform: rotate(30deg); }
    75%  { -webkit-transform: rotate(20deg); }
    100% { -webkit-transform: rotate(20deg); }
}

@-webkit-keyframes right-foot {
    0%   { -webkit-transform: rotate(-5deg); }
    25%  { -webkit-transform: rotate(-7deg); }
    50%  { -webkit-transform: rotate(-16deg); }
    75%  { -webkit-transform: rotate(-10deg); }
    100% { -webkit-transform: rotate(-5deg); }
}

@-webkit-keyframes left-foot {
    0%   { -webkit-transform: rotate(-16deg); }
    25%  { -webkit-transform: rotate(-10deg); }
    50%  { -webkit-transform: rotate(-5deg); }
    75%  { -webkit-transform: rotate(-7deg); }
    100% { -webkit-transform: rotate(-16deg); }
}

@-webkit-keyframes right-toes {
    0%   { -webkit-transform: rotate(0deg); }
    25%  { -webkit-transform: rotate(-10deg); }
    50%  { -webkit-transform: rotate(-10deg); }
    75%  { -webkit-transform: rotate(-25deg); }
    100% { -webkit-transform: rotate(0deg); }
}

@-webkit-keyframes left-toes {
    0%   { -webkit-transform: rotate(-10deg); }
    25%  { -webkit-transform: rotate(-25deg); }
    50%  { -webkit-transform: rotate(0deg); }
    75%  { -webkit-transform: rotate(-10deg); }
    100% { -webkit-transform: rotate(-10deg); }
}
</code>```

Please help me solve this issue. I looked into the other post about this  problem but I am not able to correct it.
Thank you

答:
You can read this one

z-index is canceled by setting transform(rotate)

basically, transforming an element using 'transform' which gives the element its own stacking context that is different than other element which is not transformed. What you can do is make all element to transform, for example:

```<code><div class="a"><img src="..."></div>
<div class="b"><img src="..."></div>
</code>```

you want div 'a' to scale(0.9) and be on top of 'b'. you can make the div 'b' to transform to translate(0,0) or scale(0) which won't make any different. Or you can just transform the content inside of it (for my example it's an image element) instead of the div that wrapping it. then just apply the z-index to div.

ContentLicense: CC BY-SA 3.0

Title: Scaling messes up the z-index

Body:
I have a set of absolute divs having background images which contains animation.
when i apply scale property to the divs it messes up my z-index totally
here is the link to the fiddle https://jsfiddle.net/kq2soozp/3/ (Uncomment transform:scale() line)

The HTML Code

The CSS

.me,.me div{
    background-repeat: no-repeat;
    position: absolute;
    -webkit-animation-duration: 2000ms;
    -webkit-animation-iteration-count: infinite;
    -webkit-animation-timing-function: linear;
    //-webkit-transform: scale(0.9);
}
.me{
    top: 80px;
    left: 350px;
    -webkit-animation-name: me;
}
.torso{
    height: 274px;
    width: 86px;
    background-image: url("https://s9.postimg.org/41xfy5cin/torso.png");
}

.arm{
    left: 12px;
    -webkit-transform-origin: 20px 10px;
}

.kite{

    width: 395px;
    height: 424px;
    top: -115px;
    left: 0px;

    background-image: url("https://s3.postimg.org/ix240ioab/kite.png");
    -webkit-transform: rotate(45deg) scale(0.6);

}
.right.bicep{
    width: 51px;
    height: 124px;
    background-image: url("https://s3.postimg.org/mlrszzyb7/right-bicep.png");
}
.left.bicep{
    width: 52px;
    : 126px;
    background-image: url("https://s3.postimg.org/jb3g048dv/left-bicep.png");
}
.left.forearm{
    width: 37px;
    height: 124px;
    background-image: url("https://s3.postimg.org/7ahzze0z7/left-forearm.png");
    -webkit-transform: rotate(-45deg);
}
.right.forearm{
    width: 36px;
    height: 121px;
    background-image: url("https://s3.postimg.org/q6noj82ur/right-forearm.png");
    -webkit-animation-name: right-forearm;
}
.left.thigh{
    width: 69px;
    height: 144px;
    background-image: url("https://s3.postimg.org/577krq16b/left-thigh.png");
}
.right.thigh{
    width: 69px;
    height: 144px;
    background-image: url("https://s3.postimg.org/72ud2vq0j/right-thigh.png");
}
.shin{
    width: 53px;
    height: 173px;
    background-image: url("https://s3.postimg.org/3xecqews3/shin.png");
}
.foot{
    width: 67px;
    height: 34px;
    background-image: url("https://s3.postimg.org/l0cj86o37/foot.png");
}
.toes{
    width: 28px;
    height: 25px;
    background-image: url("https://s3.postimg.org/vm0zxxjsj/toes.png");
}

.right.arm{
    top: 93px;
    -webkit-animation-name: right-bicep;

}
.left.arm{
    top: 87px;
    -webkit-transform: rotate(-26deg);
}
.forearm{
    top: 108px;
    left: 14px;
    -webkit-transform-origin: 3px 7px;
}
.leg{
    left: 6px;
    -webkit-transform-origin: 30px 20px;
    -webkit-animation-name: thigh;
}
.right.leg{
    top: 235px;
    -webkit-animation-name: right-thigh;
}
.left.leg{
    top:225px;
    -webkit-animation-name: left-thigh;
}
.shin{
    top: 115px;
    -webkit-transform-origin: 30px 25px;
}
.right.shin {
    -webkit-animation-name: right-shin;
}
.left.shin {
    -webkit-animation-name: left-shin;
}
.foot{
    top: 155px;
    left: 2px;
    -webkit-transform-origin: 0 50%;
}
.right.foot {
    -webkit-animation-name: right-foot;
}
.left.foot {
    -webkit-animation-name: left-foot;
}
.toes{
    top: 9px;
    left: 66px;
    -webkit-transform-origin: 0% 100%;
}
.right.toes {
    -webkit-animation-name: right-toes;
}
.left.toes {
    -webkit-animation-name: left-toes;
}
div.right.arm { z-index: 1; }
div.left.arm { z-index: -3; }
div.arm > div.bicep > div.forearm { z-index: -1; }

div.right.leg { z-index: -1; }
div.left.leg { z-index: -2; }
div.leg > div.thigh > div.shin { z-index: -1; }

@-webkit-keyframes me {
    0% { -webkit-transform:   rotate(5deg) translate( 10px,   0px); }
    25% { -webkit-transform:  rotate(5deg) translate(-5px, -14px); }
    50% { -webkit-transform:  rotate(5deg) translate( 10px,   0px); }
    75% { -webkit-transform:  rotate(5deg) translate(-5px, -14px); }
    100% { -webkit-transform: rotate(5deg) translate( 10px,   0px); }
}
@-webkit-keyframes right-bicep {
    0%   { -webkit-transform: rotate(26deg); }
    50%  { -webkit-transform: rotate(-20deg); }
    100% { -webkit-transform: rotate(26deg); }
}

/*@-webkit-keyframes left-bicep {
    0%   { -webkit-transform: rotate(-20deg); }
    50%  { -webkit-transform: rotate(26deg); }
    100% { -webkit-transform: rotate(-20deg); }
}*/

@-webkit-keyframes right-forearm {
    0%   { -webkit-transform: rotate(-10deg); }
    50%  { -webkit-transform: rotate(-65deg); }
    100% { -webkit-transform: rotate(-10deg); }
}

/*@-webkit-keyframes left-forearm {
    0%   { -webkit-transform: rotate(-45deg); }
    50%  { -webkit-transform: rotate(-10deg); }
    100% { -webkit-transform: rotate(-45deg); }
}*/

@-webkit-keyframes right-thigh {
    0%   { -webkit-transform: rotate(-45deg); }
    50%  { -webkit-transform: rotate(10deg); }
    100% { -webkit-transform: rotate(-45deg); }
}

@-webkit-keyframes left-thigh {
    0%   { -webkit-transform: rotate(10deg); }
    50%  { -webkit-transform: rotate(-45deg); }
    100% { -webkit-transform: rotate(10deg); }
}

@-webkit-keyframes right-shin {
    0%   { -webkit-transform: rotate(30deg); }
    25%  { -webkit-transform: rotate(20deg); }
    50%  { -webkit-transform: rotate(20deg); }
    75%  { -webkit-transform: rotate(85deg); }
    100% { -webkit-transform: rotate(30deg); }
}

@-webkit-keyframes left-shin {
    0%   { -webkit-transform: rotate(20deg); }
    25%  { -webkit-transform: rotate(85deg); }
    50%  { -webkit-transform: rotate(30deg); }
    75%  { -webkit-transform: rotate(20deg); }
    100% { -webkit-transform: rotate(20deg); }
}

@-webkit-keyframes right-foot {
    0%   { -webkit-transform: rotate(-5deg); }
    25%  { -webkit-transform: rotate(-7deg); }
    50%  { -webkit-transform: rotate(-16deg); }
    75%  { -webkit-transform: rotate(-10deg); }
    100% { -webkit-transform: rotate(-5deg); }
}

@-webkit-keyframes left-foot {
    0%   { -webkit-transform: rotate(-16deg); }
    25%  { -webkit-transform: rotate(-10deg); }
    50%  { -webkit-transform: rotate(-5deg); }
    75%  { -webkit-transform: rotate(-7deg); }
    100% { -webkit-transform: rotate(-16deg); }
}

@-webkit-keyframes right-toes {
    0%   { -webkit-transform: rotate(0deg); }
    25%  { -webkit-transform: rotate(-10deg); }
    50%  { -webkit-transform: rotate(-10deg); }
    75%  { -webkit-transform: rotate(-25deg); }
    100% { -webkit-transform: rotate(0deg); }
}

@-webkit-keyframes left-toes {
    0%   { -webkit-transform: rotate(-10deg); }
    25%  { -webkit-transform: rotate(-25deg); }
    50%  { -webkit-transform: rotate(0deg); }
    75%  { -webkit-transform: rotate(-10deg); }
    100% { -webkit-transform: rotate(-10deg); }
}

Please help me solve this issue. I looked into the other post about this  problem but I am not able to correct it.
Thank you

Body:
You can read this one

z-index is canceled by setting transform(rotate)

basically, transforming an element using 'transform' which gives the element its own stacking context that is different than other element which is not transformed. What you can do is make all element to transform, for example:

<div class="a"><img src="..."></div>
<div class="b"><img src="..."></div>

you want div 'a' to scale(0.9) and be on top of 'b'. you can make the div 'b' to transform to translate(0,0) or scale(0) which won't make any different. Or you can just transform the content inside of it (for my example it's an image element) instead of the div that wrapping it. then just apply the z-index to div.


问:
replace string php with html mailto tag
I have an string email address that comes from user input($option['footer_email']) and I want to replace it with mailto html tag. So far I tried couple of approaches and tried to use str_replace() as followed, but it didn't work out.

```<code>$email = array($option['footer_email']);
$replace = array('<a href="mailto:$option['footer_email']">$option['footer_email']</a>');
echo str_replace($email, $replace, $option['footer_email']);
</code>```

and it returns syntax error, unexpected 'footer_email' (T_STRING), expecting ')'

I also tried to use preg_replace() but that one didn't help. How can I fix this issue?

答:
```<code><?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$email = array($option['footer_email']);
$replace = array('<a href="mailto:"' . $option['footer_email'] . '">' .$option['footer_email'] . '</a>');
echo str_replace($email, $replace, $option['footer_email']);
</code>```

Title: replace string php with html mailto tag

Body:
I have an string email address that comes from user input($option['footer_email']) and I want to replace it with mailto html tag. So far I tried couple of approaches and tried to use str_replace() as followed, but it didn't work out.

$email = array($option['footer_email']);
$replace = array('$option['footer_email']');
echo str_replace($email, $replace, $option['footer_email']);

and it returns syntax error, unexpected 'footer_email' (T_STRING), expecting ')'

I also tried to use preg_replace() but that one didn't help. How can I fix this issue?


问:
Python/Django displaying images
I'm new in django and i got a problem. I have a html table with images and some data and depending on which one you select image should be displayed on next page, but i have problem with displaying the image, all i get is broken icon. Images work on first page but something is wrong with the selected page.
Could anyone help me? (I'm using django 1.10)

models.py

```<code>class Tags(models.Model):
    tag_name = models.CharField(max_length=250)
    tag_chip_type = models.CharField(max_length=250)
    tag_size = models.CharField(max_length=250)
    tag_frequency = models.CharField(max_length=250)
    tag_standards = models.CharField(max_length=250, null=True, blank=True)
    tag_memory = models.CharField(max_length=250)
    tag_reading_distance = models.CharField(max_length=250)
    tag_environment = models.CharField(max_length=250)
    tag_mounting_method = models.CharField(max_length=250)
    tag_operating_temperature = models.CharField(max_length=250, null=True, blank=True)
    tag_storage_temperature = models.CharField(max_length=250, null=True, blank=True)
    tag_chemical_and_environmental_resistances = models.CharField(max_length=500, null=True, blank=True)
    tag_image = models.FileField()

    def __unicode__(self):
        return self.tag_name + ' ' + self.tag_image.url

    def get_absolute_url(self):
        return reverse('tag:index')
</code>```

views.py

```<code>def selected(request):
    tags = request.GET.getlist('selected')
    return render(request, 'tag/selected.html', {'all_tags':tags})
</code>```

urls.py

```<code>if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
</code>```

index.html

```<code><form action="{% url 'tag:selected' %}" method="get">
        <table id="selected" class="white-table table-bordered table-hover" style="width:95%; margin: 3% auto;">
             <thead>
                 <tr>
                     <th style="text-align:center;"><input type="checkbox" onClick="toggle(this)"></th>
                     <th></th>
                     <th style="text-align:center;">Name</th>
                     <th style="text-align:center;">Chip Type</th>
                     <th style="text-align:center;">Size</th>
                     <th style="text-align:center;">Frequency</th>
                     <th style="text-align:center;">Memory</th>
                     <th style="text-align:center;">Reading distance</th>
                     <th class="null" style="text-align:center;">Environment</th>
                     <th class="null" style="text-align:center;">Mounting method</th>
                 </tr>
             </thead>
  <tbody>
  {% for tags in all_tags %}

            <tr>
            <td style="text-align:center;"><input type="checkbox"  name="selected" value="{{ tags.tag_image.url }}"></td>
            <td><a href="{% url 'tag:detail' tags.id %}"> <img src="{{ tags.tag_image.url }}" class="img-responsive" style="width: 60px; height:80px; margin:auto;" /> </a></td>
            <td style="text-align:center;"> {{ tags.tag_name }} </td>
            <td style="text-align:center;"> {{ tags.tag_chip_type }} </td>
            <td style="text-align:center;"> {{ tags.tag_size }} </td>
            <td style="text-align:center;"> {{ tags.tag_frequency }} </td>
            <td style="text-align:center;"> {{ tags.tag_memory }} </td>
            <td style="text-align:center;"> {{ tags.tag_reading_distance }} </td>
            <td class="null" style="text-align:center;"> {{ tags.tag_environment }} </td>
            <td class="null" style="text-align:center;"> {{ tags.tag_mounting_method }} </td>
            </tr>
  {% endfor %}
            </tbody>
        </table>
        <input class="btn-primary" style="float:right; margin-right:2.5%; margin-bottom:3%;" type="submit" value="Submit">
    </form>

{% endblock %}
</code>```

settings.py

```<code>MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
</code>```

selected.html

```<code>{% block body %}

{% for tags in all_tags %}
    <div class=" col-md-4">
            <div class="panel panel-default">
                <div class="panel-body">
<img src=" '/media/'{{ tags.tag_image.url }}" class="img-responsive" style="width: 60px; height:80px; margin:auto;" />
        </div>
    </div>
</div>
{% endfor %}
{% endblock %}
</code>```

答:
You have to add url pattern :</p>

```<code>urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
</code>```

Title: Python/Django displaying images

Body:
I'm new in django and i got a problem. I have a html table with images and some data and depending on which one you select image should be displayed on next page, but i have problem with displaying the image, all i get is broken icon. Images work on first page but something is wrong with the selected page.
Could anyone help me? (I'm using django 1.10)

models.py

class Tags(models.Model):
    tag_name = models.CharField(max_length=250)
    tag_chip_type = models.CharField(max_length=250)
    tag_size = models.CharField(max_length=250)
    tag_frequency = models.CharField(max_length=250)
    tag_standards = models.CharField(max_length=250, null=True, blank=True)
    tag_memory = models.CharField(max_length=250)
    tag_reading_distance = models.CharField(max_length=250)
    tag_environment = models.CharField(max_length=250)
    tag_mounting_method = models.CharField(max_length=250)
    tag_operating_temperature = models.CharField(max_length=250, null=True, blank=True)
    tag_storage_temperature = models.CharField(max_length=250, null=True, blank=True)
    tag_chemical_and_environmental_resistances = models.CharField(max_length=500, null=True, blank=True)
    tag_image = models.FileField()

    def __unicode__(self):
        return self.tag_name + ' ' + self.tag_image.url

    def get_absolute_url(self):
        return reverse('tag:index')

views.py

def selected(request):
    tags = request.GET.getlist('selected')
    return render(request, 'tag/selected.html', {'all_tags':tags})

urls.py

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

index.html

<form action="{% url 'tag:selected' %}" method="get">

                     <input type="checkbox" onClick="toggle(this)">

                     Name
                     Chip Type
                     Size
                     Frequency
                     Memory
                     Reading distance
                     Environment
                     Mounting method

  {% for tags in all_tags %}

            <input type="checkbox"  name="selected" value="{{ tags.tag_image.url }}">

             {{ tags.tag_name }}
             {{ tags.tag_chip_type }}
             {{ tags.tag_size }}
             {{ tags.tag_frequency }}
             {{ tags.tag_memory }}
             {{ tags.tag_reading_distance }}
             {{ tags.tag_environment }}
             {{ tags.tag_mounting_method }}

  {% endfor %}

        <input class="btn-primary" style="float:right; margin-right:2.5%; margin-bottom:3%;" type="submit" value="Submit">
    </form>

{% endblock %}

settings.py

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

selected.html

{% block body %}

{% for tags in all_tags %}

{% endfor %}
{% endblock %}

Body:
You have to add url pattern :

urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


问:
How to add +1 value on the entire column of my database table?
Just new in programming I created a database using XAMPP with 3 columns (f_name, l_name, age).

I created a index.php page where I have only 1 button present, what I am expecting to happen is that if I click that button the entire column age will commit +1 to all current values inside the age. Is it possible?

But unfortunately I don't know how to create the code. I would like to see a simple example of code that will add +1 to the entire column of age. At lease a base logic that will help me figure it out how to do it.

答:
```<code>mysqli_query($connection, "UPDATE `table` SET `age` = `age` + 1");
</code>```


问:
Java - JpaRepository SQL Error
I use hibernate for O/R mapping and further I use the JpaRepository for my DAOs.

I want to compare two java.util.date objects if they have the same day. Currently I'm using this query, which is not working:

```<code>@Query(value = "SELECT e FROM Event e WHERE day(e.startDate) = day(?1)")
public Set<Event> findEventsByDate(Date date);
</code>```

This was also recommended here:
Date Compare in HQL without timestamp

Unfortunately I get the following error:

org.springframework.dao.invaliddataaccessresourceusageexception: could not prepare statement

and

org.hsqldb.HsqlException: data type cast needed for parameter or null literal

It seems like it has something to do with the parameter "?1" from the DAO method. Because if I try the following, it works like a charm:

```<code>SELECT e FROM Event e WHERE day(e.startDate) = day(e.startDate)
</code>```

(I use HSQLDB)

UPDATE

Here is the stacktrace:

```<code>    org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:261)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:491)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy118.findEventsByDate(Unknown Source)
    at *.service.impl.EventServiceImpl.findEventsByDate(EventServiceImpl.java:331)
    at *.service.impl.EventServiceImpl$$FastClassBySpringCGLIB$$f6beca54.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:721)
    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.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656)
    at *.service.impl.EventServiceImpl$$EnhancerBySpringCGLIB$$d66b254.findEventsByDate(<generated>)
    at *.EventServiceImplTest.findEventsByStartDate(EventServiceImplTest.java:347)
    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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.hibernate.exception.SQLGrammarException: could not prepare statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:182)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:148)
    at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1929)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1898)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1876)
    at org.hibernate.loader.Loader.doQuery(Loader.java:919)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336)
    at org.hibernate.loader.Loader.doList(Loader.java:2617)
    at org.hibernate.loader.Loader.doList(Loader.java:2600)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2429)
    at org.hibernate.loader.Loader.list(Loader.java:2424)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:501)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:371)
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1326)
    at org.hibernate.internal.QueryImpl.list(QueryImpl.java:87)
    at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:606)
    at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:483)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute(JpaQueryExecution.java:118)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:82)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:116)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:482)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:460)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    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.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    ... 48 more
Caused by: java.sql.SQLSyntaxErrorException: data type cast needed for parameter or null literal
    at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
    at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
    at org.hsqldb.jdbc.JDBCPreparedStatement.<init>(Unknown Source)
    at org.hsqldb.jdbc.JDBCConnection.prepareStatement(Unknown Source)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:146)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:172)
    ... 79 more
Caused by: org.hsqldb.HsqlException: data type cast needed for parameter or null literal
    at org.hsqldb.error.Error.error(Unknown Source)
    at org.hsqldb.error.Error.error(Unknown Source)
    at org.hsqldb.FunctionSQL.resolveTypes(Unknown Source)
    at org.hsqldb.FunctionCustom.resolveTypes(Unknown Source)
    at org.hsqldb.ExpressionLogical.resolveTypes(Unknown Source)
    at org.hsqldb.QuerySpecification.resolveExpressionTypes(Unknown Source)
    at org.hsqldb.QuerySpecification.resolveTypesPartOne(Unknown Source)
    at org.hsqldb.QueryExpression.resolve(Unknown Source)
    at org.hsqldb.ParserDQL.compileCursorSpecification(Unknown Source)
    at org.hsqldb.ParserCommand.compilePart(Unknown Source)
    at org.hsqldb.ParserCommand.compileStatement(Unknown Source)
    at org.hsqldb.Session.compileStatement(Unknown Source)
    at org.hsqldb.StatementManager.compile(Unknown Source)
    at org.hsqldb.Session.execute(Unknown Source)
    ... 83 more
</code>```

UPDATE 2

I don't know why but it works perfectly when I use a mysql database. But nevertheless it would be great if someone could explain why this does not work with hsqldb because I use this in-memory-database for unit testing and I want to keep that updated and as good as possible.

答:
Looks like hsqldb does not have day() function. You can try using extract function as

EXTRACT ( DAY FROM ?1 )

Reference : http://hsqldb.org/doc/guide/builtinfunctions-chapt.html#bfc_datetime_functions

Also refer to : https://blog.jooq.org/2015/02/25/how-to-extract-a-date-part-in-sql/

Title: Java - JpaRepository SQL Error

Body:
I use hibernate for O/R mapping and further I use the JpaRepository for my DAOs.

I want to compare two java.util.date objects if they have the same day. Currently I'm using this query, which is not working:

@Query(value = "SELECT e FROM Event e WHERE day(e.startDate) = day(?1)")
public Set<Event> findEventsByDate(Date date);

This was also recommended here:
Date Compare in HQL without timestamp

Unfortunately I get the following error:

org.springframework.dao.invaliddataaccessresourceusageexception: could not prepare statement

and

org.hsqldb.HsqlException: data type cast needed for parameter or null literal

It seems like it has something to do with the parameter "?1" from the DAO method. Because if I try the following, it works like a charm:

SELECT e FROM Event e WHERE day(e.startDate) = day(e.startDate)

(I use HSQLDB)

UPDATE

Here is the stacktrace:

    org.springframework.dao.InvalidDataAccessResourceUsageException: could not prepare statement; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:261)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:491)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy118.findEventsByDate(Unknown Source)
    at *.service.impl.EventServiceImpl.findEventsByDate(EventServiceImpl.java:331)
    at *.service.impl.EventServiceImpl$$FastClassBySpringCGLIB$$f6beca54.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:721)
    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.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:656)
    at *.service.impl.EventServiceImpl$$EnhancerBySpringCGLIB$$d66b254.findEventsByDate(<generated>)
    at *.EventServiceImplTest.findEventsByStartDate(EventServiceImplTest.java:347)
    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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.hibernate.exception.SQLGrammarException: could not prepare statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:182)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:148)
    at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1929)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1898)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1876)
    at org.hibernate.loader.Loader.doQuery(Loader.java:919)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336)
    at org.hibernate.loader.Loader.doList(Loader.java:2617)
    at org.hibernate.loader.Loader.doList(Loader.java:2600)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2429)
    at org.hibernate.loader.Loader.list(Loader.java:2424)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:501)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:371)
    at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216)
    at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1326)
    at org.hibernate.internal.QueryImpl.list(QueryImpl.java:87)
    at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:606)
    at org.hibernate.jpa.internal.QueryImpl.getResultList(QueryImpl.java:483)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution$CollectionExecution.doExecute(JpaQueryExecution.java:118)
    at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:82)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:116)
    at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:106)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:482)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:460)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    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.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    ... 48 more
Caused by: java.sql.SQLSyntaxErrorException: data type cast needed for parameter or null literal
    at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
    at org.hsqldb.jdbc.JDBCUtil.sqlException(Unknown Source)
    at org.hsqldb.jdbc.JDBCPreparedStatement.<init>(Unknown Source)
    at org.hsqldb.jdbc.JDBCConnection.prepareStatement(Unknown Source)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:146)
    at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:172)
    ... 79 more
Caused by: org.hsqldb.HsqlException: data type cast needed for parameter or null literal
    at org.hsqldb.error.Error.error(Unknown Source)
    at org.hsqldb.error.Error.error(Unknown Source)
    at org.hsqldb.FunctionSQL.resolveTypes(Unknown Source)
    at org.hsqldb.FunctionCustom.resolveTypes(Unknown Source)
    at org.hsqldb.ExpressionLogical.resolveTypes(Unknown Source)
    at org.hsqldb.QuerySpecification.resolveExpressionTypes(Unknown Source)
    at org.hsqldb.QuerySpecification.resolveTypesPartOne(Unknown Source)
    at org.hsqldb.QueryExpression.resolve(Unknown Source)
    at org.hsqldb.ParserDQL.compileCursorSpecification(Unknown Source)
    at org.hsqldb.ParserCommand.compilePart(Unknown Source)
    at org.hsqldb.ParserCommand.compileStatement(Unknown Source)
    at org.hsqldb.Session.compileStatement(Unknown Source)
    at org.hsqldb.StatementManager.compile(Unknown Source)
    at org.hsqldb.Session.execute(Unknown Source)
    ... 83 more

UPDATE 2

I don't know why but it works perfectly when I use a mysql database. But nevertheless it would be great if someone could explain why this does not work with hsqldb because I use this in-memory-database for unit testing and I want to keep that updated and as good as possible.


问:
Boolean != false
In Java, you would usually say that

if(someBool != false)

is the same as

if(someBool)

But what if someBool is not of type boolean but  Boolean, and its value is null?

答:
I did a little test:

```<code>    Boolean o = null;
    try {
        System.out.println(o ? "yes" : "no");
    } catch (Exception e) {
        e.printStackTrace();
    }
    try {
        System.out.println((o != false) ? "yes" : "no");
    } catch (Exception e) {
        e.printStackTrace();
    }
</code>```

The output is surprising:

```<code>java.lang.NullPointerException
    at btest.main(btest.java:10)
java.lang.NullPointerException
    at btest.main(btest.java:15)
</code>```

The first NPE is to be expected, because o will be autounboxed (and that fails because it's null). The second happens for the same reason, but it doesn't feel natural. Anyway, the solution is to do:

```<code>System.out.println(!Boolean.FALSE.equals(o) ? "yes" : "no");
</code>```

ContentLicense: CC BY-SA 2.5

Title: Boolean != false

Body:
I did a little test:

    Boolean o = null;
    try {
        System.out.println(o ? "yes" : "no");
    } catch (Exception e) {
        e.printStackTrace();
    }
    try {
        System.out.println((o != false) ? "yes" : "no");
    } catch (Exception e) {
        e.printStackTrace();
    }

The output is surprising:

java.lang.NullPointerException
    at btest.main(btest.java:10)
java.lang.NullPointerException
    at btest.main(btest.java:15)

The first NPE is to be expected, because o will be autounboxed (and that fails because it's null). The second happens for the same reason, but it doesn't feel natural. Anyway, the solution is to do:

System.out.println(!Boolean.FALSE.equals(o) ? "yes" : "no");


问:
Fit element's width to wrapped text
In the below snippet, notice how the paragraph element is actually wider than its wrapped content. Is it possible to make the paragraph's width to exactly equal text width? I don't want to set p width explicitly, because it needs to be responsive.

div {
  width: 110px;
}

p {
  background-color: #ff0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <p>
    asda sdzxf vzfsdf   asdsdsdsddf dfsdf
  </p>
  </div></code>```

edit:

So I've managed to achieve the result I've wanted. Sorry if I wasn't precise enough with my question. Here it is:

div {
  background-color: #f0f;
  width: 10%;
  display: flex;
  align-items: baseline;
}

p {
  background-color: #ff0;
  display: inline;
}

i {
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>

  <p>
    asda sdzxf vzfsdf asdsdsdsddf dfsdf
  </p>
  <i>icon</i>
</div></code>```

答:
div {
  width: Auto;
}

p {
  width:Auto !important;
  background-color: #ff0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <p>
    asda sdzxf vzfsdf   asdsdsdsddf dfsdf
  </p>
  </div></code>```

Title: Fit element's width to wrapped text

Body:
In the below snippet, notice how the paragraph element is actually wider than its wrapped content. Is it possible to make the paragraph's width to exactly equal text width? I don't want to set p width explicitly, because it needs to be responsive.

div {
  width: 110px;
}

p {
  background-color: #ff0;
}

    asda sdzxf vzfsdf   asdsdsdsddf dfsdf

edit:

So I've managed to achieve the result I've wanted. Sorry if I wasn't precise enough with my question. Here it is:

div {
  background-color: #f0f;
  width: 10%;
  display: flex;
  align-items: baseline;
}

p {
  background-color: #ff0;
  display: inline;
}

i {
  display: inline-block;
}

    asda sdzxf vzfsdf asdsdsdsddf dfsdf

  icon

Body:
div {
  width: Auto;
}

p {
  width:Auto !important;
  background-color: #ff0;
}

<div>
  <p>
    asda sdzxf vzfsdf   asdsdsdsddf dfsdf
  </p>
  </div>


问:
Android DatePicker dialog, date should come from tomorrow
```<code> Calendar calender = Calendar.getInstance();
    final CustomDatePickerDialog pickerDialog = new CustomDatePickerDialog(LabCheckOutActivity.this,
    myDateListener, calender.get(Calendar.YEAR), calender.get(Calendar.MONTH),
    calender.get(Calendar.DAY_OF_MONTH)+1);
    pickerDialog.getDatePicker().setMinDate(System.currentTimeMillis()-1000);
    pickerDialog.show();
</code>```

by Using this code, in dialog date is pointed to tomorrow but user can also select todays date.I want user can select date from tomorrow not today.

public class CustomDatePickerDialog extends DatePickerDialog {

```<code>int maxYear;
int maxMonth;
int maxDay;

public CustomDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
    super(context, callBack, year, monthOfYear, dayOfMonth);
}

public void setMaxDate(long maxDate) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        getDatePicker().setMaxDate(System.currentTimeMillis());
    } else {
        final Calendar c = Calendar.getInstance();
        c.setTimeInMillis(maxDate);
        maxYear = c.get(Calendar.YEAR);
        maxMonth = c.get(Calendar.MONTH);
        maxDay = c.get(Calendar.DAY_OF_MONTH);
    }
}

@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        super.onDateChanged(view, year, monthOfYear, dayOfMonth);
    } else {
        if (year > maxYear)
            view.updateDate(maxYear, maxMonth, maxDay);

        if (monthOfYear > maxMonth && year == maxYear)
            view.updateDate(maxYear, maxMonth, maxDay);

        if (dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth)
            view.updateDate(maxYear, maxMonth, maxDay);
    }
}

}
</code>```

答:
Please see complete implementation below:

DialogFragment class

```<code>public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener
{

    public DatePickerFragment()
    {

    }

    public void setiDateTimeListener(IDateTimeListener iDateTimeListener)
    {
        this.iDateTimeListener = iDateTimeListener;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState)
    {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), this, year, month, day);

        //        Set minimum date as tommorw
        datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() + 24*60*60*1000);

        //        If need to set max date then use this also
        //        datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis());

        // Create a new instance of DatePickerDialog and return it
        return datePickerDialog;
    }

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
    {
        try
        {
            String selectedDt = dayOfMonth+"-"+(monthOfYear + 1)+"-"+year;

            iDateTimeListener.onDateSet(selectedDt);

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

}
</code>```

Interface must be implemented in date picker calling class

```<code>public interface IDateTimeListener
{
    public void onDateSet(String date);
}
</code>```

Calling dialog fragment

```<code>public void showDatePickerDialog()
{
    DatePickerFragment datePickerFragment = new DatePickerFragment();
    datePickerFragment.setiDateTimeListener(this);
 datePickerFragment.show(getActivity().getSupportFragmentManager(),"datePicker");
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
 Calendar calender = Calendar.getInstance();
    final CustomDatePickerDialog pickerDialog = new CustomDatePickerDialog(LabCheckOutActivity.this,
    myDateListener, calender.get(Calendar.YEAR), calender.get(Calendar.MONTH),
    calender.get(Calendar.DAY_OF_MONTH)+1);
    pickerDialog.getDatePicker().setMinDate(System.currentTimeMillis()-1000);
    pickerDialog.show();

by Using this code, in dialog date is pointed to tomorrow but user can also select todays date.I want user can select date from tomorrow not today.

public class CustomDatePickerDialog extends DatePickerDialog {

int maxYear;
int maxMonth;
int maxDay;

public CustomDatePickerDialog(Context context, OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) {
    super(context, callBack, year, monthOfYear, dayOfMonth);
}

public void setMaxDate(long maxDate) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        getDatePicker().setMaxDate(System.currentTimeMillis());
    } else {
        final Calendar c = Calendar.getInstance();
        c.setTimeInMillis(maxDate);
        maxYear = c.get(Calendar.YEAR);
        maxMonth = c.get(Calendar.MONTH);
        maxDay = c.get(Calendar.DAY_OF_MONTH);
    }
}

@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        super.onDateChanged(view, year, monthOfYear, dayOfMonth);
    } else {
        if (year > maxYear)
            view.updateDate(maxYear, maxMonth, maxDay);

        if (monthOfYear > maxMonth && year == maxYear)
            view.updateDate(maxYear, maxMonth, maxDay);

        if (dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth)
            view.updateDate(maxYear, maxMonth, maxDay);
    }
}

}

Body:
Please see complete implementation below:

DialogFragment class

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener
{

    public DatePickerFragment()
    {

    }

    public void setiDateTimeListener(IDateTimeListener iDateTimeListener)
    {
        this.iDateTimeListener = iDateTimeListener;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState)
    {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(), this, year, month, day);

        //        Set minimum date as tommorw
        datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() + 24*60*60*1000);

        //        If need to set max date then use this also
        //        datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis());

        // Create a new instance of DatePickerDialog and return it
        return datePickerDialog;
    }

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
    {
        try
        {
            String selectedDt = dayOfMonth+"-"+(monthOfYear + 1)+"-"+year;

            iDateTimeListener.onDateSet(selectedDt);

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

}

Interface must be implemented in date picker calling class

public interface IDateTimeListener
{
    public void onDateSet(String date);
}

Calling dialog fragment

public void showDatePickerDialog()
{
    DatePickerFragment datePickerFragment = new DatePickerFragment();
    datePickerFragment.setiDateTimeListener(this);
 datePickerFragment.show(getActivity().getSupportFragmentManager(),"datePicker");
}


答:
Try This</p>

```<code>$option['footer_email']="waseem@waseem.com";
    $email = array($option['footer_email']);
    $replace = '<a href="mailto:'.$option['footer_email'].'">'.$option['footer_email'].'</a>';
    $replace_val= str_replace($email, $replace, $option['footer_email']);
    //check By var_dump
    var_dump($replace_val);
    //check By Print_r
    print_r($replace_val);
    //check By echo
    echo $replace_val;
</code>```

Title: replace string php with html mailto tag

Body:
Try This

$option['footer_email']="waseem@waseem.com";
    $email = array($option['footer_email']);
    $replace = '<a href="mailto:'.$option['footer_email'].'">'.$option['footer_email'].'</a>';
    $replace_val= str_replace($email, $replace, $option['footer_email']);
    //check By var_dump
    var_dump($replace_val);
    //check By Print_r
    print_r($replace_val);
    //check By echo
    echo $replace_val;


问:
I can`t connect to database on my server it displays blank page
```<code><!Doctype html>
<html>
<head>
<title>Orders Database</title>
</head>
<body>
<?php
$con = mysql_connect('localhost','wrobell1_1','123');
$db = mysql_select_db('wrobell1_orders',$con);

if($con){
echo 'succefully connected'}
?>
</body>
</html>
</code>```

<p>What can be wrong? I put it on the server in public html folder and nothing displays </p>

答:
Can it be because of the hosting server?<br>
If anyone could paste the proper code I would be very grateful I have one hour to complete it ;( </p>

Body:
<!Doctype html>

<title>Orders Database</title>

<?php
$con = mysql_connect('localhost','wrobell1_1','123');
$db = mysql_select_db('wrobell1_orders',$con);

if($con){
echo 'succefully connected'}
?>

What can be wrong? I put it on the server in public html folder and nothing displays

Body:
Can it be because of the hosting server?

If anyone could paste the proper code I would be very grateful I have one hour to complete it ;(


问:
TensorFlow 0.12 tutorials produce warning: "Rank of input Tensor should be the same as output_rank for column
I have some experience with writing machine learning programs in python, but I'm new to TensorFlow and am checking it out. My dev environment is a lubuntu 14.04 64-bit virtual machine. I've created a python 3.5 conda environment from miniconda and installed TensorFlow 0.12 and its dependencies. I began trying to run some example code from TensorFlow's tutorials and encountered this warning when calling fit() in the boston.py example for input functions: source.

WARNING:tensorflow:Rank of input Tensor (1) should be the same as
  output_rank (2) for column. Will attempt to expand dims. It is highly
  recommended that you resize your input, as this behavior may change.

After some searching in Google, I found other people encountered this same warning:

https://github.com/tensorflow/tensorflow/issues/6184

https://github.com/tensorflow/tensorflow/issues/5098

Tensorflow - Boston Housing Data Tutorial Errors

However, they also experienced errors which prevent code execution from completing. In my case, the code executes with the above warning. Unfortunately, I couldn't find a single answer in those links regarding what caused the warning and how to fix the warning. They all focused on the error. How does one remove the warning? Or is the warning safe to ignore?

Cheers!

Extra info, I also see the following warnings when running the aforementioned boston.py example.

WARNING:tensorflow:*******************************************************
  WARNING:tensorflow:TensorFlow's V1 checkpoint format has been
  deprecated. WARNING:tensorflow:Consider switching to the more
  efficient V2 format: WARNING:tensorflow:

  'tf.train.Saver(write_version=tf.train.SaverDef.V2)'
  WARNING:tensorflow:now on by default.
  WARNING:tensorflow:*******************************************************

and

WARNING:tensorflow:From
  /home/kade/miniconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined.py:1053
  in predict.: calling BaseEstimator.predict (from
  tensorflow.contrib.learn.python.learn.estimators.estimator) with x is
  deprecated and will be removed after 2016-12-01. Instructions for
  updating: Estimator is decoupled from Scikit Learn interface by moving
  into separate class SKCompat. Arguments x, y and batch_size are only
  available in the SKCompat class, Estimator will only accept input_fn.
  Example conversion:   est = Estimator(...) -> est =
  SKCompat(Estimator(...))

UPDATE (2016-12-22):
I've tracked the warning to this file:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/layers/python/layers/feature_column_ops.py

and this code block:

```<code>except NotImplementedError:
    with variable_scope.variable_scope(
        None,
        default_name=column.name,
        values=columns_to_tensors.values()):
      tensor = column._to_dense_tensor(transformed_tensor)
      tensor = fc._reshape_real_valued_tensor(tensor, 2, column.name)
      variable = [
          contrib_variables.model_variable(
              name='weight',
              shape=[tensor.get_shape()[1], num_outputs],
              initializer=init_ops.zeros_initializer(),
              trainable=trainable,
              collections=weight_collections)
      ]
      predictions = math_ops.matmul(tensor, variable[0], name='matmul')
</code>```

Note the line: tensor = fc._reshape_real_valued_tensor(tensor, 2, column.name)

The method signature is: _reshape_real_valued_tensor(input_tensor, output_rank, column_name=None)

The value 2 is hardcoded as the value of output_rank, but the boston.py example is passing in an input_tensor of rank 1. I will continue to investigate.

答:
After I specify the shape of the tensor explicitly.

```<code>continuous_cols = {k: tf.constant(df[k].values, shape=[df[k].size, 1]) for k in CONTINUOUS_COLUMNS}
</code>```

It works!

Body:
I have some experience with writing machine learning programs in python, but I'm new to TensorFlow and am checking it out. My dev environment is a lubuntu 14.04 64-bit virtual machine. I've created a python 3.5 conda environment from miniconda and installed TensorFlow 0.12 and its dependencies. I began trying to run some example code from TensorFlow's tutorials and encountered this warning when calling fit() in the boston.py example for input functions: source.

WARNING:tensorflow:Rank of input Tensor (1) should be the same as
  output_rank (2) for column. Will attempt to expand dims. It is highly
  recommended that you resize your input, as this behavior may change.

After some searching in Google, I found other people encountered this same warning:

https://github.com/tensorflow/tensorflow/issues/6184

https://github.com/tensorflow/tensorflow/issues/5098

Tensorflow - Boston Housing Data Tutorial Errors

However, they also experienced errors which prevent code execution from completing. In my case, the code executes with the above warning. Unfortunately, I couldn't find a single answer in those links regarding what caused the warning and how to fix the warning. They all focused on the error. How does one remove the warning? Or is the warning safe to ignore?

Cheers!

Extra info, I also see the following warnings when running the aforementioned boston.py example.

WARNING:tensorflow:*******************************************************
  WARNING:tensorflow:TensorFlow's V1 checkpoint format has been
  deprecated. WARNING:tensorflow:Consider switching to the more
  efficient V2 format: WARNING:tensorflow:

  'tf.train.Saver(write_version=tf.train.SaverDef.V2)'
  WARNING:tensorflow:now on by default.
  WARNING:tensorflow:*******************************************************

and

WARNING:tensorflow:From
  /home/kade/miniconda3/envs/tensorflow/lib/python3.5/site-packages/tensorflow/contrib/learn/python/learn/estimators/dnn_linear_combined.py:1053
  in predict.: calling BaseEstimator.predict (from
  tensorflow.contrib.learn.python.learn.estimators.estimator) with x is
  deprecated and will be removed after 2016-12-01. Instructions for
  updating: Estimator is decoupled from Scikit Learn interface by moving
  into separate class SKCompat. Arguments x, y and batch_size are only
  available in the SKCompat class, Estimator will only accept input_fn.
  Example conversion:   est = Estimator(...) -> est =
  SKCompat(Estimator(...))

UPDATE (2016-12-22):
I've tracked the warning to this file:
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/layers/python/layers/feature_column_ops.py

and this code block:

except NotImplementedError:
    with variable_scope.variable_scope(
        None,
        default_name=column.name,
        values=columns_to_tensors.values()):
      tensor = column._to_dense_tensor(transformed_tensor)
      tensor = fc._reshape_real_valued_tensor(tensor, 2, column.name)
      variable = [
          contrib_variables.model_variable(
              name='weight',
              shape=[tensor.get_shape()[1], num_outputs],
              initializer=init_ops.zeros_initializer(),
              trainable=trainable,
              collections=weight_collections)
      ]
      predictions = math_ops.matmul(tensor, variable[0], name='matmul')

Note the line: tensor = fc._reshape_real_valued_tensor(tensor, 2, column.name)

The method signature is: _reshape_real_valued_tensor(input_tensor, output_rank, column_name=None)

The value 2 is hardcoded as the value of output_rank, but the boston.py example is passing in an input_tensor of rank 1. I will continue to investigate.

Body:
After I specify the shape of the tensor explicitly.

continuous_cols = {k: tf.constant(df[k].values, shape=[df[k].size, 1]) for k in CONTINUOUS_COLUMNS}

It works!


问:
Disabling android's chrome pull-down-to-refresh feature
I've created a small HTML5 web application for my company.

This application displays a list of items and everything works fine.

The application is mainly used on android phones and Chrome as browser. Also, the site is saved on the home screen so Android manage the whole thing as an app (using a WebView I guess).

Chrome Beta (and I think also the Android System WebView) has introduced a "pull down to refresh" feature (See this link for example).

This is an handy feature but I was wondering if it can be disabled with some meta tag (or javascript stuff) because the refresh can be easily triggered by the user while navigating the list and the whole app is reloaded.

Also this is a feature not needed by the application.

I know that this feature is still available only in Chrome beta, but I have the sensation that this is landing on the stable app, too.

Thank you!

Edit: I've uninstalled Chrome Beta and the link pinned to the home screen now opens with the stable Chrome. So the pinned links starts with Chrome and not with a webview.

Edit: today (2015-03-19) the pull-down-to-refresh has come to the stable chrome.

Edit: from @Evyn answer I follow this link and got this javascript/jquery code that work.

var lastTouchY = 0;
var preventPullToRefresh = false;

$('body').on('touchstart', function (e) {
    if (e.originalEvent.touches.length != 1) { return; }
    lastTouchY = e.originalEvent.touches[0].clientY;
    preventPullToRefresh = window.pageYOffset == 0;
});

$('body').on('touchmove', function (e) {
    var touchY = e.originalEvent.touches[0].clientY;
    var touchYDelta = touchY - lastTouchY;
    lastTouchY = touchY;
    if (preventPullToRefresh) {
        // To suppress pull-to-refresh it is sufficient to preventDefault the first overscrolling touchmove.
        preventPullToRefresh = false;
        if (touchYDelta > 0) {
            e.preventDefault();
            return;
        }
    }
});```

As @bcintegrity pointed out, I hope for a site manifest solution (and/or a meta-tag) in the future.

Moreover suggestions for the code above are welcome.

答:
After many hours of trying, this solution works for me</p>

```<code>$("html").css({
    "touch-action": "pan-down"
});
</code>```

Body:
I've created a small HTML5 web application for my company.

This application displays a list of items and everything works fine.

The application is mainly used on android phones and Chrome as browser. Also, the site is saved on the home screen so Android manage the whole thing as an app (using a WebView I guess).

Chrome Beta (and I think also the Android System WebView) has introduced a "pull down to refresh" feature (See this link for example).

This is an handy feature but I was wondering if it can be disabled with some meta tag (or javascript stuff) because the refresh can be easily triggered by the user while navigating the list and the whole app is reloaded.

Also this is a feature not needed by the application.

I know that this feature is still available only in Chrome beta, but I have the sensation that this is landing on the stable app, too.

Thank you!

Edit: I've uninstalled Chrome Beta and the link pinned to the home screen now opens with the stable Chrome. So the pinned links starts with Chrome and not with a webview.

Edit: today (2015-03-19) the pull-down-to-refresh has come to the stable chrome.

Edit: from @Evyn answer I follow this link and got this javascript/jquery code that work.

var lastTouchY = 0;
var preventPullToRefresh = false;

$('body').on('touchstart', function (e) {
    if (e.originalEvent.touches.length != 1) { return; }
    lastTouchY = e.originalEvent.touches[0].clientY;
    preventPullToRefresh = window.pageYOffset == 0;
});

$('body').on('touchmove', function (e) {
    var touchY = e.originalEvent.touches[0].clientY;
    var touchYDelta = touchY - lastTouchY;
    lastTouchY = touchY;
    if (preventPullToRefresh) {
        // To suppress pull-to-refresh it is sufficient to preventDefault the first overscrolling touchmove.
        preventPullToRefresh = false;
        if (touchYDelta > 0) {
            e.preventDefault();
            return;
        }
    }
});

As @bcintegrity pointed out, I hope for a site manifest solution (and/or a meta-tag) in the future.

Moreover suggestions for the code above are welcome.

Body:
After many hours of trying, this solution works for me

$("html").css({
    "touch-action": "pan-down"
});


问:
USING IF WITH OUTER APPLY IN MSSQL
I want to write IF conditition in OUTER APPLY. I need to return more than one column so i don't want to write subqueries

```<code>SELECT name FROM v_users
OUTER APPLY
(
    IF CAST(reg_date AS DATE)<CAST('03/25/2017' AS DATE)
   SELECT gender,email,age,class FROM tb_register_old WHERE id=v_users.user_id;
ELSE
   SELECT gender,email,age,class FROM tb_register_new WHERE id=v_users.user_id;
)s
</code>```

答:
Maybe this?</p>

```<code>SELECT name FROM v_users
OUTER APPLY
(
 SELECT gender,email,age,class
 FROM tb_register_old
 WHERE id=v_users.user_id and CAST(reg_date AS DATE)<CAST('03/25/2017' AS DATE)

 UNION ALL

 SELECT gender,email,age,class
 FROM tb_register_new
 WHERE id=v_users.user_id and CAST(reg_date AS DATE) >= CAST('03/25/2017' AS DATE)
)s
</code>```

Title: USING IF WITH OUTER APPLY IN MSSQL

Body:
I want to write IF conditition in OUTER APPLY. I need to return more than one column so i don't want to write subqueries

SELECT name FROM v_users
OUTER APPLY
(
    IF CAST(reg_date AS DATE)<CAST('03/25/2017' AS DATE)
   SELECT gender,email,age,class FROM tb_register_old WHERE id=v_users.user_id;
ELSE
   SELECT gender,email,age,class FROM tb_register_new WHERE id=v_users.user_id;
)s

Body:
Maybe this?

SELECT name FROM v_users
OUTER APPLY
(
 SELECT gender,email,age,class
 FROM tb_register_old
 WHERE id=v_users.user_id and CAST(reg_date AS DATE)<CAST('03/25/2017' AS DATE)

 UNION ALL

 SELECT gender,email,age,class
 FROM tb_register_new
 WHERE id=v_users.user_id and CAST(reg_date AS DATE) >= CAST('03/25/2017' AS DATE)
)s


问:
__NSAutoreleaseNoPool(): Object 0x753c2f0 of class General autoreleased with no pool in place - just leaking
I haven't noticed my console output for a while and I've suddenly noticed lots of weird errors.

__NSAutoreleaseNoPool(): Object 0x753c2f0 of class General autoreleased with no pool in place - just leaking

__NSAutoreleaseNoPool(): Object 0x753c300 of class __NSArrayM autoreleased with no pool in place - just leaking

I've no idea where this happening?

Edit..

I use this

```<code>[self performSelectorInBackground:@selector(startupStuff) withObject:sender];
</code>```

With statupStuff I have this

```<code>General *rdb = [[General alloc] autorelease];
[rdb refreshDBData];
</code>```

The Errors happen shortly after code in the refreshDBData method.

答:
Try this

```<code>[self performSelectorInBackground:@selector(startupStuff) withObject:sender];

-(void)startupStuff:(id)sender
{

   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

   General *rdb = [[General alloc] init];

   [rdb refreshDBData];

   [rdb release];

   [pool release];

}
</code>```

If its not working too then you need to check refreshDBData method.. you are doing something wrong there

Body:
I haven't noticed my console output for a while and I've suddenly noticed lots of weird errors.

__NSAutoreleaseNoPool(): Object 0x753c2f0 of class General autoreleased with no pool in place - just leaking

__NSAutoreleaseNoPool(): Object 0x753c300 of class __NSArrayM autoreleased with no pool in place - just leaking

I've no idea where this happening?

Edit..

I use this

[self performSelectorInBackground:@selector(startupStuff) withObject:sender];

With statupStuff I have this

General *rdb = [[General alloc] autorelease];
[rdb refreshDBData];

The Errors happen shortly after code in the refreshDBData method.

Body:
Try this

[self performSelectorInBackground:@selector(startupStuff) withObject:sender];

-(void)startupStuff:(id)sender
{

   NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

   General *rdb = [[General alloc] init];

   [rdb refreshDBData];

   [rdb release];

   [pool release];

}

If its not working too then you need to check refreshDBData method.. you are doing something wrong there


答:
You need to test whether there's a syntax error on your page first. I usually do this with a simple echo. if the code below does not shows the message There is NO syntax error. then there is an syntax error.

I also test the connection directly after making it.

```<code><!Doctype html>
<html>
<head>
<title>Orders Database</title>
</head>
<body>
<?php
// is there a syntax error?
echo 'There is NO syntax error.<br>';
// connect
$con = mysql_connect('localhost','wrobell1_1','123');
if ($con) echo 'We successfully connected.<br>';
          echo 'The connection failed.<br>';
// select database
$db = mysql_select_db('wrobell1_orders',$con);
if ($db) echo 'We successfully selected.<br>';
          echo 'The selection failed.<br>';
?>
</body>
</html>
</code>```

And you already know the mysql extension should not be used. Use mysqli or PDO.

Title: I can`t connect to database on my server it displays blank page

Body:
You need to test whether there's a syntax error on your page first. I usually do this with a simple echo. if the code below does not shows the message There is NO syntax error. then there is an syntax error.

I also test the connection directly after making it.

<!Doctype html>
<html>
<head>
<title>Orders Database</title>
</head>
<body>
<?php
// is there a syntax error?
echo 'There is NO syntax error.<br>';
// connect
$con = mysql_connect('localhost','wrobell1_1','123');
if ($con) echo 'We successfully connected.<br>';
          echo 'The connection failed.<br>';
// select database
$db = mysql_select_db('wrobell1_orders',$con);
if ($db) echo 'We successfully selected.<br>';
          echo 'The selection failed.<br>';
?>
</body>
</html>

And you already know the mysql extension should not be used. Use mysqli or PDO.


问:
MySQL Get Different services for each IP
I have the following table:

```<code>|    **IP**   | **PORT** | **SERVICE** | **VERSION** |
|:-------:|:----:|:-------:|:-------:|
| 1.2.3.4 |  80  |   HTTP  |   1.1   |
| 1.2.3.4 |  443 |   HTTP  |   1.2   |
| 1.2.3.4 |  25  |   SMTP  |   a     |
| 2.3.4.5 |  80  |   HTTP  |   1.2   |
| 2.3.4.5 |  443 |   HTTP  |   1.2   |
| 2.3.4.5 |  25  |   SMTP  |   a     |
| 3.4.5.6 |  25  |   SMTP  |   b     |
| 3.4.5.6 |  443 |   HTTP  |   1.2   |
| 0.0.0.1 |  25  |   SMTP  |   b     |
| 0.0.0.2 |  443 |   HTTP  |   1.2   |
</code>```

And I want to get a list of the different services by port, service and version between some of the IPs, for example the result for the IPs 1.2.3.4, 2.3.4.5 and 3.4.5.6 should be similar to the following: As the rest of the services on those IPs are the same port, service and version.

Different services for IPs 1.2.3.4, 2.3.4.5 and 3.4.5.6:

```<code>|    IP   | PORT | SERVICE | VERSION |
|:-------:|:----:|:-------:|:-------:|
| 1.2.3.4 |  80  |   HTTP  |   1.1   |
| 1.2.3.4 |  25  |   SMTP  |   a     |
| 2.3.4.5 |  80  |   HTTP  |   1.2   |
| 2.3.4.5 |  25  |   SMTP  |   a     |
| 3.4.5.6 |  25  |   SMTP  |   b     |
</code>```

Not sure how to get them on a Query.

Thanks in advance

答:
If i understand correctly, the requirement is to group by ip and service.</p>

```<code>select t.*
from t where t.ip in ('1.2.3.4', '2.3.4.5', '3.4.5.6')
group by ip,service;
</code>```

Body:
I have the following table:

|    **IP**   | **PORT** | **SERVICE** | **VERSION** |
|:-------:|:----:|:-------:|:-------:|
| 1.2.3.4 |  80  |   HTTP  |   1.1   |
| 1.2.3.4 |  443 |   HTTP  |   1.2   |
| 1.2.3.4 |  25  |   SMTP  |   a     |
| 2.3.4.5 |  80  |   HTTP  |   1.2   |
| 2.3.4.5 |  443 |   HTTP  |   1.2   |
| 2.3.4.5 |  25  |   SMTP  |   a     |
| 3.4.5.6 |  25  |   SMTP  |   b     |
| 3.4.5.6 |  443 |   HTTP  |   1.2   |
| 0.0.0.1 |  25  |   SMTP  |   b     |
| 0.0.0.2 |  443 |   HTTP  |   1.2   |

And I want to get a list of the different services by port, service and version between some of the IPs, for example the result for the IPs 1.2.3.4, 2.3.4.5 and 3.4.5.6 should be similar to the following: As the rest of the services on those IPs are the same port, service and version.

Different services for IPs 1.2.3.4, 2.3.4.5 and 3.4.5.6:

|    IP   | PORT | SERVICE | VERSION |
|:-------:|:----:|:-------:|:-------:|
| 1.2.3.4 |  80  |   HTTP  |   1.1   |
| 1.2.3.4 |  25  |   SMTP  |   a     |
| 2.3.4.5 |  80  |   HTTP  |   1.2   |
| 2.3.4.5 |  25  |   SMTP  |   a     |
| 3.4.5.6 |  25  |   SMTP  |   b     |

Not sure how to get them on a Query.

Thanks in advance

Body:
If i understand correctly, the requirement is to group by ip and service.

select t.*
from t where t.ip in ('1.2.3.4', '2.3.4.5', '3.4.5.6')
group by ip,service;


问:
Default to home route if no param passed
I have some basic routes setup on my index.js

```<code>import { Router,
  Route,
  hashHistory,
  Link } from 'react-router';

ReactDOM.render(
               <Router history={hashHistory}>
                <Route path="/" component={Users} />
                <Route path="/posts/:id" component={Posts} />
              </Router>
            ,
document.getElementById('root')
</code>```

Can I redirect the to the home route if no parameter is passed to the posts route?

答:
You can add a <Redirect> for that route:

```<code><Router history={ hashHistory }>
  <Route path="/" component={ Users } />
  <Redirect from="/posts/" to="/" />
  <Route path="/posts/:id" component={ Posts } />
</Router>
</code>```

Body:
I have some basic routes setup on my index.js

import { Router,
  Route,
  hashHistory,
  Link } from 'react-router';

ReactDOM.render(
               <Router history={hashHistory}>
                <Route path="/" component={Users} />
                <Route path="/posts/:id" component={Posts} />
              </Router>
            ,
document.getElementById('root')

Can I redirect the to the home route if no parameter is passed to the posts route?

Body:
You can add a <Redirect> for that route:

<Router history={ hashHistory }>
  <Route path="/" component={ Users } />
  <Redirect from="/posts/" to="/" />
  <Route path="/posts/:id" component={ Posts } />
</Router>


问:
SQL: How to dynamically loop & add N number of column with NULL value into temp table
Due to a certain requirement, I need to create two temp tables in Stored Procedure, after processing some data into them, I need to combine the two temp tables to show as one result set and generate into excel. So I'm thinking to use UNION when I want to show the final result set.

The issue is, the first temp table (Table A) is fixed to 20 columns, and the second temp table has 50 columns (Table B). My plan is, before processing data for Table A, I want to add 30 nullable columns and insert data for first 20 columns, and the rest is all NULL

After I process the data for Table B, I use UNION to combine Table A & B so that they will show as one result set.

What I can think of right now is to hard code some columns that are destined to have null values when I declare the temp table:

```<code>Declare @tmpTableA table (
  ....
  ProcessDate datetime,
  Mode int,
  Col21 varchar(10)
  Col22 varchar(10)
  ....
  Col50 varchar(50)
)
</code>```

When I insert data into Table A, I have to manually add null from Col21 onwards

```<code>Insert into(.... Col21, Col22, Col23....)
Values (.... NULL, NULL, NULL....)
</code>```

After I complete processing data for Table A & B, I use UNION to merge Table A and B

```<code>Select *....Col49,Col50 From Table A
Union
Select *....CompleteDate,ContactPerson From Table B
</code>```

Instead of hard-coding Col21 to Col50 into Table A, is there any elegant way to achieve that like using while loop to dynamically add N number of columns into Table A?

EDIT:
According to latest requirement, Table B has not only 50 columns but 100 columns! I really need a way to dynamically loop those columns rather than hard-coding for over 80 columns

答:
You don't need to add columns to table A, just add 30 NULLs to select from Table A.

```<code>Select *,NULL,...,NULL,NULL From Table A
Union
Select * From Table B
</code>```

You could add aliases to make the result a bit cleaner

```<code>Select *,...,NULL CompleteDate, NULL ContactPerson From Table A
Union
Select * From Table B
</code>```

Body:
Due to a certain requirement, I need to create two temp tables in Stored Procedure, after processing some data into them, I need to combine the two temp tables to show as one result set and generate into excel. So I'm thinking to use UNION when I want to show the final result set.

The issue is, the first temp table (Table A) is fixed to 20 columns, and the second temp table has 50 columns (Table B). My plan is, before processing data for Table A, I want to add 30 nullable columns and insert data for first 20 columns, and the rest is all NULL

After I process the data for Table B, I use UNION to combine Table A & B so that they will show as one result set.

What I can think of right now is to hard code some columns that are destined to have null values when I declare the temp table:

Declare @tmpTableA table (
  ....
  ProcessDate datetime,
  Mode int,
  Col21 varchar(10)
  Col22 varchar(10)
  ....
  Col50 varchar(50)
)

When I insert data into Table A, I have to manually add null from Col21 onwards

Insert into(.... Col21, Col22, Col23....)
Values (.... NULL, NULL, NULL....)

After I complete processing data for Table A & B, I use UNION to merge Table A and B

Select *....Col49,Col50 From Table A
Union
Select *....CompleteDate,ContactPerson From Table B

Instead of hard-coding Col21 to Col50 into Table A, is there any elegant way to achieve that like using while loop to dynamically add N number of columns into Table A?

EDIT:
According to latest requirement, Table B has not only 50 columns but 100 columns! I really need a way to dynamically loop those columns rather than hard-coding for over 80 columns

Body:
You don't need to add columns to table A, just add 30 NULLs to select from Table A.

Select *,NULL,...,NULL,NULL From Table A
Union
Select * From Table B

You could add aliases to make the result a bit cleaner

Select *,...,NULL CompleteDate, NULL ContactPerson From Table A
Union
Select * From Table B