问:
Take excel sheet value as it is input to java program
I want excel sheet value as a input for my program, but 24hr time format changed in 12hr format after program run.Example:Excel contains 23:34:10 but when i run program in netbean, output is 11:34:10.I want 23:34:10 as a output.

```<code>public class DateTime {

    public static void main(String[] args) throws Exception{

        File f=new File("D:\\BCCIDT.xls");

        Workbook wb=Workbook.getWorkbook(f);
        Sheet s=wb.getSheet(0);

        int row=s.getRows();
        int col=s.getColumns();

       for(int j=0;j<row;j++){
            Cell c=s.getCell(0, j);
            System.out.println(c.getContents()+"\n");

            String msg=c.getContents();

             Date date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse(msg);
               String newString = new SimpleDateFormat("kk").format(date);
               System.out.println("Time = " + newString +"\n");
              }
       }
}
</code>```

Input is-23:00:35  Output-11:00:35

But i want Output-23:00:35

答:
Please check the patterns for SimpleDateFormat(..).
Try SimpleDateFormat("HH:mm:ss")

Body:
I want excel sheet value as a input for my program, but 24hr time format changed in 12hr format after program run.Example:Excel contains 23:34:10 but when i run program in netbean, output is 11:34:10.I want 23:34:10 as a output.

public class DateTime {

    public static void main(String[] args) throws Exception{

        File f=new File("D:\\BCCIDT.xls");

        Workbook wb=Workbook.getWorkbook(f);
        Sheet s=wb.getSheet(0);

        int row=s.getRows();
        int col=s.getColumns();

       for(int j=0;j<row;j++){
            Cell c=s.getCell(0, j);
            System.out.println(c.getContents()+"\n");

            String msg=c.getContents();

             Date date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").parse(msg);
               String newString = new SimpleDateFormat("kk").format(date);
               System.out.println("Time = " + newString +"\n");
              }
       }
}

Input is-23:00:35  Output-11:00:35

But i want Output-23:00:35


来源: stackexchange

问:
Change cart item prices based on custom cart item data in Woocommerce
currently i create a form in product single page so that customer can enter  height and width of the product . So the product price vary based on the entered height and width .

I created this form in

woocommerce->single-product->add-to-cart->simple.php

Before modification  the form is

```<code><form class="cart" method="post" enctype='multipart/form-data'>
    <?php
        /**
         * @since 2.1.0.
         */
        do_action( 'woocommerce_before_add_to_cart_button' );

        /**
         * @since 3.0.0.
         */
        do_action( 'woocommerce_before_add_to_cart_quantity' );

        woocommerce_quantity_input( array(
            'min_value'   => apply_filters( 'woocommerce_quantity_input_min', $product->get_min_purchase_quantity(), $product ),
            'max_value'   => apply_filters( 'woocommerce_quantity_input_max', $product->get_max_purchase_quantity(), $product ),
            'input_value' => isset( $_POST['quantity'] ) ? wc_stock_amount( $_POST['quantity'] ) : $product->get_min_purchase_quantity(),
        ) );

        /**
         * @since 3.0.0.
         */
        do_action( 'woocommerce_after_add_to_cart_quantity' );
    ?>

    <button type="submit" name="add-to-cart" value="<?php echo esc_attr( $product->get_id() ); ?>" class="single_add_to_cart_button button alt"><?php echo esc_html( $product->single_add_to_cart_text() ); ?></button>

    <?php
        /**
         * @since 2.1.0.
         */
        do_action( 'woocommerce_after_add_to_cart_button' );
    ?>
</form>
</code>```

After modification form is

```<code><form class="cart" method="post" enctype='multipart/form-data'>
    <p>width  <input type="text" name="new-width" class="new-width"></p>
    <p>Height <input type="text" name="new-height" class="new-height"></p>
        <?php
            /**
             * @since 2.1.0.
             */
            do_action( 'woocommerce_before_add_to_cart_button' );

            /**
             * @since 3.0.0.
             */
            do_action( 'woocommerce_before_add_to_cart_quantity' );

            woocommerce_quantity_input( array(
                'min_value'   => apply_filters( 'woocommerce_quantity_input_min', $product->get_min_purchase_quantity(), $product ),
                'max_value'   => apply_filters( 'woocommerce_quantity_input_max', $product->get_max_purchase_quantity(), $product ),
                'input_value' => isset( $_POST['quantity'] ) ? wc_stock_amount( $_POST['quantity'] ) : $product->get_min_purchase_quantity(),
            ) );

            /**
             * @since 3.0.0.
             */
            do_action( 'woocommerce_after_add_to_cart_quantity' );
        ?>

        <button type="submit" name="add-to-cart" value="<?php echo esc_attr( $product->get_id() ); ?>" class="single_add_to_cart_button button alt"><?php echo esc_html( $product->single_add_to_cart_text() ); ?></button>

        <?php
            /**
             * @since 2.1.0.
             */
            do_action( 'woocommerce_after_add_to_cart_button' );
        ?>
    </form>
</code>```

After this i used   the following code and for testing pupose i set value to 30 . But it is not working . what i missed  ?

```<code>add_filter( 'woocommerce_add_cart_item' , 'set_woo_prices');

function set_woo_prices( $woo_data ) {

  if(isset( $_POST['new-width']))  { $woo_data['new-width'] =$_POST['new-width']; }
  if(isset( $_POST['new-height'])) { $woo_data['new-height'] =$_POST['new-height']; }
  if( $_POST['new-width'] !=="" && $_POST['new-height']!=="" ){

     $woo_data['data']->set_price( "30" );
    }
     return $woo_data;

}
</code>```

Please advice . My aim is to change product price based on user entered width and height .

答:
You need to use 2 different hooks:

The first one just as yours without trying to change the price in it.

The second one where you will change your cart item price

The code:

```<code>add_filter( 'woocommerce_add_cart_item', 'add_custom_cart_item_data', 10, 2 );
function add_custom_cart_item_data( $cart_item_data, $cart_item ) {

    if( isset( $_POST['new-width'] ) )
        $cart_item_data['new-width'] = $_POST['new-width'];
    if(isset( $_POST['new-height'] ) )
       $cart_item_data['new-height'] = $_POST['new-height'];

    return $cart_item_data;
}

add_action( 'woocommerce_before_calculate_totals', 'set_custom_cart_item_price', 20, 1 );
function set_custom_cart_item_price( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // First loop to check if product 11 is in cart
    foreach ( $cart->get_cart() as $cart_item ){
        if( isset($cart_item['new-width']) && isset($cart_item['new-height'])
        && ! empty($cart_item['new-width']) && ! empty($cart_item['new-height']) )
            $cart_item['data']->set_price( '30' );
    }
}
</code>```

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

Tested and works

ContentLicense: CC BY-SA 4.0

Body:
currently i create a form in product single page so that customer can enter  height and width of the product . So the product price vary based on the entered height and width .

I created this form in

woocommerce->single-product->add-to-cart->simple.php

Before modification  the form is

<form class="cart" method="post" enctype='multipart/form-data'>
    <?php
        /**
         * @since 2.1.0.
         */
        do_action( 'woocommerce_before_add_to_cart_button' );

        /**
         * @since 3.0.0.
         */
        do_action( 'woocommerce_before_add_to_cart_quantity' );

        woocommerce_quantity_input( array(
            'min_value'   => apply_filters( 'woocommerce_quantity_input_min', $product->get_min_purchase_quantity(), $product ),
            'max_value'   => apply_filters( 'woocommerce_quantity_input_max', $product->get_max_purchase_quantity(), $product ),
            'input_value' => isset( $_POST['quantity'] ) ? wc_stock_amount( $_POST['quantity'] ) : $product->get_min_purchase_quantity(),
        ) );

        /**
         * @since 3.0.0.
         */
        do_action( 'woocommerce_after_add_to_cart_quantity' );
    ?>

    <button type="submit" name="add-to-cart" value="<?php echo esc_attr( $product->get_id() ); ?>" class="single_add_to_cart_button button alt"><?php echo esc_html( $product->single_add_to_cart_text() ); ?></button>

    <?php
        /**
         * @since 2.1.0.
         */
        do_action( 'woocommerce_after_add_to_cart_button' );
    ?>
</form>

After modification form is

<form class="cart" method="post" enctype='multipart/form-data'>

width  <input type="text" name="new-width" class="new-width">

Height <input type="text" name="new-height" class="new-height">

        <?php
            /**
             * @since 2.1.0.
             */
            do_action( 'woocommerce_before_add_to_cart_button' );

            /**
             * @since 3.0.0.
             */
            do_action( 'woocommerce_before_add_to_cart_quantity' );

            woocommerce_quantity_input( array(
                'min_value'   => apply_filters( 'woocommerce_quantity_input_min', $product->get_min_purchase_quantity(), $product ),
                'max_value'   => apply_filters( 'woocommerce_quantity_input_max', $product->get_max_purchase_quantity(), $product ),
                'input_value' => isset( $_POST['quantity'] ) ? wc_stock_amount( $_POST['quantity'] ) : $product->get_min_purchase_quantity(),
            ) );

            /**
             * @since 3.0.0.
             */
            do_action( 'woocommerce_after_add_to_cart_quantity' );
        ?>

        <button type="submit" name="add-to-cart" value="<?php echo esc_attr( $product->get_id() ); ?>" class="single_add_to_cart_button button alt"><?php echo esc_html( $product->single_add_to_cart_text() ); ?></button>

        <?php
            /**
             * @since 2.1.0.
             */
            do_action( 'woocommerce_after_add_to_cart_button' );
        ?>
    </form>

After this i used   the following code and for testing pupose i set value to 30 . But it is not working . what i missed  ?

add_filter( 'woocommerce_add_cart_item' , 'set_woo_prices');

function set_woo_prices( $woo_data ) {

  if(isset( $_POST['new-width']))  { $woo_data['new-width'] =$_POST['new-width']; }
  if(isset( $_POST['new-height'])) { $woo_data['new-height'] =$_POST['new-height']; }
  if( $_POST['new-width'] !=="" && $_POST['new-height']!=="" ){

     $woo_data['data']->set_price( "30" );
    }
     return $woo_data;

}

Please advice . My aim is to change product price based on user entered width and height .

Body:
You need to use 2 different hooks:

The first one just as yours without trying to change the price in it.

The second one where you will change your cart item price

The code:

add_filter( 'woocommerce_add_cart_item', 'add_custom_cart_item_data', 10, 2 );
function add_custom_cart_item_data( $cart_item_data, $cart_item ) {

    if( isset( $_POST['new-width'] ) )
        $cart_item_data['new-width'] = $_POST['new-width'];
    if(isset( $_POST['new-height'] ) )
       $cart_item_data['new-height'] = $_POST['new-height'];

    return $cart_item_data;
}

add_action( 'woocommerce_before_calculate_totals', 'set_custom_cart_item_price', 20, 1 );
function set_custom_cart_item_price( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;

    // First loop to check if product 11 is in cart
    foreach ( $cart->get_cart() as $cart_item ){
        if( isset($cart_item['new-width']) && isset($cart_item['new-height'])
        && ! empty($cart_item['new-width']) && ! empty($cart_item['new-height']) )
            $cart_item['data']->set_price( '30' );
    }
}

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

Tested and works


问:
How to load javascript file1 first before javascript file2
I have two javascript file one with the functions and another with the eventlistener. This is how I declare them

```<code><body>
    <script src="../script/Main%20Functions.js"></script>
    <script src="../script/Main-events.js"></script>
</body>
</code>```

Main Functions.js

```<code>checklike(userId,postId);
function checkLike(userId, postId) {
    $.ajax({

        type: "POST",
        url: "../Main.asmx/get_liked",
        data: "{'userID':'" + userId + "', 'postID':'" + postId + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var result = response.d;
            console.log('ok');
            $.each(result, function (index, data) {
                var liked = data.liked;
                if (liked == true) {
                    $("#" + postId).prev().parent("button").css("background", "#ccc");
                }
                else {
                    $("#" + postId).prev().parent("button").css("background", "white");
                }
            });

        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert('Function Error "checkLike"');
        }

    });
}
</code>```

Main-events.js

```<code>const d = document.querySelector.bind(document);
const D = document.querySelectorAll.bind(document);
const logOut = d('.lOut h3');
const iFrame = d('#if1');
const alias = d('.codename-label h2');
const monito = d('.monito-label');
const monitoChecklists = D('.monito-checklist');
const displayPicture = d('#displayPic');
const btnReveal = d('.btn-reveal');
const btnSubmit = d('.btn-submit');
const btnLike = D('.buttonLike');
console.log('ok2');
btnLike.forEach(function (like) {
    like.addEventListener('click', function (e) {
        console.log(this);
    })
});
</code>```

but when I open the html the console.log('ok2'); executes first not the console.log('ok') . Is there a way on telling the javascript to load specific file first before executing the file for eventlistener?

EDIT 1: The adding of eventlistener for the btnLike loads first before the javascript added the elemet on the page.

EDIT 2: Okay upon investigation

Before trying eventlistener I use this jquery code

```<code>$(document).on('click', '.buttonLike', function () {
    var color = $(this).css("background-color");
    var id = $(this).find(".postID").attr("id");
    if (color == "rgb(204, 204, 204)") {
        $(this).css("background-color", "white");
        var number = parseInt($("#" + id).html().substring(0, $("#" + id).html().indexOf(" "))) - 1;
        if (number > 1) {
            number = number + " Likes";
        }
        else {
            number = number + " Like";
        }
        $("#" + id).html(number);
        Remove_Like(id);
    }
    else {
        $(this).css("background-color", "#ccc");
        var number = parseInt($("#" + id).html().substring(0, $("#" + id).html().indexOf(" "))) + 1;
        if (number > 1) {
            number = number + " Likes";
        }
        else {
            number = number + " Like";
        }
        $("#" + id).html(number);
        Add_Like(id);
    }
});
</code>```

it works fine and I found out that it uses the document and check if the target has class name .buttonLike am i right?

答:
If you want to load another js file in your ajax call than you can use this

jQuery's $.getScript() is buggy sometimes, so I use my own implementation of it like:

```<code>jQuery.loadScript = function (url, callback) {
    jQuery.ajax({
        url: url,
        dataType: 'script',
        success: callback,
        async: true
    });
}
</code>```

and use it like:

```<code>if (typeof someObject == 'undefined') $.loadScript('url_to_someScript.js', function(){
    //Stuff to do after someScript has loaded
});
</code>```

or simply

You can listen to the script's load event, and do things with the results as you would. So:

```<code>var script = document.createElement('script');
script.onload = function () {
    //do stuff with the script
};
script.src = something;

document.head.appendChild(script); //or something of the likes
</code>```

Another option

 will fire when a script is finished loading.

You will not be able to do something like:

```<code><script src="/foo.js"></script>
<script src="/bar.js"></script>
<script>
function alertonload(src){
   console.log(src+' is loaded');
}
scripts = document.getElementsByTagName('script');
for(var i=0; i<scripts.length; i++){
    scripts[i].onload = function(){ alertonload(scripts[i].src); };
}
</script>
</code>```

This is pure conjecture and speculation; I have not tried it and there's probably better ways to write it, but this will not do what you're looking to do. EDIT: The scripts are loaded as the browser sees them, not after the fact. They will be loaded before this occurs.

ContentLicense: CC BY-SA 3.0

Body:
I have two javascript file one with the functions and another with the eventlistener. This is how I declare them

Main Functions.js

checklike(userId,postId);
function checkLike(userId, postId) {
    $.ajax({

        type: "POST",
        url: "../Main.asmx/get_liked",
        data: "{'userID':'" + userId + "', 'postID':'" + postId + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var result = response.d;
            console.log('ok');
            $.each(result, function (index, data) {
                var liked = data.liked;
                if (liked == true) {
                    $("#" + postId).prev().parent("button").css("background", "#ccc");
                }
                else {
                    $("#" + postId).prev().parent("button").css("background", "white");
                }
            });

        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert('Function Error "checkLike"');
        }

    });
}

Main-events.js

const d = document.querySelector.bind(document);
const D = document.querySelectorAll.bind(document);
const logOut = d('.lOut h3');
const iFrame = d('#if1');
const alias = d('.codename-label h2');
const monito = d('.monito-label');
const monitoChecklists = D('.monito-checklist');
const displayPicture = d('#displayPic');
const btnReveal = d('.btn-reveal');
const btnSubmit = d('.btn-submit');
const btnLike = D('.buttonLike');
console.log('ok2');
btnLike.forEach(function (like) {
    like.addEventListener('click', function (e) {
        console.log(this);
    })
});

but when I open the html the console.log('ok2'); executes first not the console.log('ok') . Is there a way on telling the javascript to load specific file first before executing the file for eventlistener?

EDIT 1: The adding of eventlistener for the btnLike loads first before the javascript added the elemet on the page.

EDIT 2: Okay upon investigation

Before trying eventlistener I use this jquery code

$(document).on('click', '.buttonLike', function () {
    var color = $(this).css("background-color");
    var id = $(this).find(".postID").attr("id");
    if (color == "rgb(204, 204, 204)") {
        $(this).css("background-color", "white");
        var number = parseInt($("#" + id).html().substring(0, $("#" + id).html().indexOf(" "))) - 1;
        if (number > 1) {
            number = number + " Likes";
        }
        else {
            number = number + " Like";
        }
        $("#" + id).html(number);
        Remove_Like(id);
    }
    else {
        $(this).css("background-color", "#ccc");
        var number = parseInt($("#" + id).html().substring(0, $("#" + id).html().indexOf(" "))) + 1;
        if (number > 1) {
            number = number + " Likes";
        }
        else {
            number = number + " Like";
        }
        $("#" + id).html(number);
        Add_Like(id);
    }
});

it works fine and I found out that it uses the document and check if the target has class name .buttonLike am i right?

Body:
If you want to load another js file in your ajax call than you can use this

jQuery's $.getScript() is buggy sometimes, so I use my own implementation of it like:

jQuery.loadScript = function (url, callback) {
    jQuery.ajax({
        url: url,
        dataType: 'script',
        success: callback,
        async: true
    });
}

and use it like:

if (typeof someObject == 'undefined') $.loadScript('url_to_someScript.js', function(){
    //Stuff to do after someScript has loaded
});

or simply

You can listen to the script's load event, and do things with the results as you would. So:

var script = document.createElement('script');
script.onload = function () {
    //do stuff with the script
};
script.src = something;

document.head.appendChild(script); //or something of the likes

Another option

 will fire when a script is finished loading.

You will not be able to do something like:

<script src="/foo.js"></script>
<script src="/bar.js"></script>
<script>
function alertonload(src){
   console.log(src+' is loaded');
}
scripts = document.getElementsByTagName('script');
for(var i=0; i<scripts.length; i++){
    scripts[i].onload = function(){ alertonload(scripts[i].src); };
}
</script>

This is pure conjecture and speculation; I have not tried it and there's probably better ways to write it, but this will not do what you're looking to do. EDIT: The scripts are loaded as the browser sees them, not after the fact. They will be loaded before this occurs.


问:
Javascript: Set Value of Form inside of iFrame Not Working
I'm working on setting a value for the credit card number on this website and I can't seem to figure it out. I was told that the form is inside of an iFrame and it can't be accessed. How would I set the value for the card number through the console. I've seen other auto-fill successfully accomplish this successfully. Thank you.

On my console I just keep getting this error:

VM531:3 Uncaught TypeError: Cannot set property 'value' of null at
  :3:11

var numb = document.getElementById('number');
numb.value = "222";```
<pre class="snippet-code-html lang-html prettyprint-override"><code><iframe class="card-fields-iframe" id="card-fields-number-s80xmtdp1g000000" name="card-fields-number-s80xmtdp1g000000" scrolling="no" src="https://checkout.shopifycs.com/number?identifier=61d81845e21cfa9cd0cc2e43a6a8c9a1&location=https%3A%2F%2Fyeezysupply.com%2F17655971%2Fcheckouts%2F61d81845e21cfa9cd0cc2e43a6a8c9a1%3F_ga%3D2.37031328.1462446110.1512281869-2081311403.1511598208" style="height: 43px;" frameborder="0"></iframe>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, height=device-height, minimum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" media="all" href="https://checkout.shopifycs.com/build/inputs-2762b8ff87.css">

  </head>
  <body>
    <form>

        <label for="number" class="visually-hidden" aria-hidden="true">Credit Card Number</label>

          <input autocomplete="cc-number" id="number" name="number" aria-describedby="error-for-number tooltip-for-number" data-current-field="number" class="input-placeholder-color--lvl-30" style="color: rgb(171, 171, 171); font-family: Helvetica\ Neue, sans-serif; padding: 0.94em 0.8em; transition: padding 0.2s ease-out 0s;" placeholder="Card number" type="tel">
          <span id="error-for-number" class="input-error-message visually-hidden"></span>

        <label for="name" class="visually-hidden" aria-hidden="true">Name on card</label>

          <input autocomplete="cc-name" id="name" name="name" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="text">

        <label for="expiry_month" class="visually-hidden" aria-hidden="true">Expiry month</label>

          <input autocomplete="cc-exp-month" id="expiry_month" name="expiry_month" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="tel">

        <label for="expiry_year" class="visually-hidden" aria-hidden="true">Expiry year</label>

          <input autocomplete="cc-exp-year" id="expiry_year" name="expiry_year" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="tel">

        <label for="expiry" class="visually-hidden" aria-hidden="true">MM / YY</label>

          <input autocomplete="cc-exp" id="expiry" name="expiry" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="tel">

        <label for="verification_value" class="visually-hidden" aria-hidden="true">CVV</label>

          <input autocomplete="off" id="verification_value" name="verification_value" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="tel">

        <label for="issue_date" class="visually-hidden" aria-hidden="true">Issue date (MM / YY)</label>

          <input autocomplete="off" id="issue_date" name="issue_date" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="tel">

        <label for="issue_number" class="visually-hidden" aria-hidden="true">Issue number</label>

          <input autocomplete="off" id="issue_number" name="issue_number" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="tel">

      <button type="submit" class="visually-hidden" tabindex="-1"></button>
    </form>
    <script src="https://checkout.shopifycs.com/build/boot-6e4b6e821a.js"></script>

</body></code>```

答:
You can use content() method.

var iframeBody = $('.card-fields-iframe').content().find('.body')

and get element(number)

```<code> var numberField = iframeBody.find('#number');
 //assign value to element
 numberField.value = "222";
</code>```

Body:
I'm working on setting a value for the credit card number on this website and I can't seem to figure it out. I was told that the form is inside of an iFrame and it can't be accessed. How would I set the value for the card number through the console. I've seen other auto-fill successfully accomplish this successfully. Thank you.

On my console I just keep getting this error:

VM531:3 Uncaught TypeError: Cannot set property 'value' of null at
  :3:11

var numb = document.getElementById('number');
numb.value = "222";

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, height=device-height, minimum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" media="all" href="https://checkout.shopifycs.com/build/inputs-2762b8ff87.css">

    <form>

        Credit Card Number

          <input autocomplete="cc-number" id="number" name="number" aria-describedby="error-for-number tooltip-for-number" data-current-field="number" class="input-placeholder-color--lvl-30" style="color: rgb(171, 171, 171); font-family: Helvetica\ Neue, sans-serif; padding: 0.94em 0.8em; transition: padding 0.2s ease-out 0s;" placeholder="Card number" type="tel">

        Name on card

          <input autocomplete="cc-name" id="name" name="name" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="text">

        Expiry month

          <input autocomplete="cc-exp-month" id="expiry_month" name="expiry_month" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="tel">

        Expiry year

          <input autocomplete="cc-exp-year" id="expiry_year" name="expiry_year" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="tel">

        MM / YY

          <input autocomplete="cc-exp" id="expiry" name="expiry" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="tel">

        CVV

          <input autocomplete="off" id="verification_value" name="verification_value" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="tel">

        Issue date (MM / YY)

          <input autocomplete="off" id="issue_date" name="issue_date" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="tel">

        Issue number

          <input autocomplete="off" id="issue_number" name="issue_number" class="visually-hidden" aria-hidden="true" data-honeypot-field="" tabindex="-1" type="tel">

      <button type="submit" class="visually-hidden" tabindex="-1"></button>
    </form>

Body:
You can use content() method.

var iframeBody = $('.card-fields-iframe').content().find('.body')

and get element(number)

 var numberField = iframeBody.find('#number');
 //assign value to element
 numberField.value = "222";


问:
How can I bypass a command to terminal inside another terminal via python?
In python, we can call any process using subprocess.

I have a situation where I have to work with interactive terminal where I need output of few commands, using python code.

How can I use subprocess module that will open the interactive terminal and I can further bypass few command and get their out to parse them further?

I am able to use subprocess module for 2 different command that where 2nd one is dependent on output of first one like

ps -aux | grep python

first ps -aux can be passed to 1 subprocess obj and that obj will be used as stdin of another subprocess command where grep python will be processed....

答:
you question is not much clear , so i would answer the part which i understand

How can I use subprocess module that will open the interactive terminal and I can further bypass few command and get their out to parse them further?

i have a ubuntu machine and this is the way i invoke a separate terminal and pass command to them

```<code>        from subprocess import Popen,PIPE
        command='who'
        command ='"'+command+' '+';read -n1" '
         #subitem = Popen(['gnome-terminal','--disable-factory','-x','bash','-c',command],stdin =PIPE)
          subitem = Popen(['gnome-terminal','--disable-factory','-x','bash'],stdin =PIPE)
        subitem.communicate(input='your command')
</code>```

You can further play with this using stdin,stdout,communicate method depending on your requirment

Body:
you question is not much clear , so i would answer the part which i understand

How can I use subprocess module that will open the interactive terminal and I can further bypass few command and get their out to parse them further?

i have a ubuntu machine and this is the way i invoke a separate terminal and pass command to them

        from subprocess import Popen,PIPE
        command='who'
        command ='"'+command+' '+';read -n1" '
         #subitem = Popen(['gnome-terminal','--disable-factory','-x','bash','-c',command],stdin =PIPE)
          subitem = Popen(['gnome-terminal','--disable-factory','-x','bash'],stdin =PIPE)
        subitem.communicate(input='your command')

You can further play with this using stdin,stdout,communicate method depending on your requirment


问:
Unmarshal hits unexpected element in nested namespaces
I've searched high and low to find out why my SOAP service get:

```<code>javax.xml.bind.UnmarshalException: unexpected element (uri:"http://xsd.banverket.se/T/Opera/Tagrapportering2.xsd", local:"Tagrapportering"). Expected elements are <{urn:BVTAF}Tagrapportering>,<{urn:BVTAF}MessageHeader>
</code>```

when my web service receives this xml:

```<code><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MessageArray xmlns="urn:BVTAFMessageInbox">
<BVTagrapportering xmlns="urn:BVTAF">
    <MessageHeader><MessageStatus>1</MessageStatus><MessageReference><MessageType MessageTypeCode="0"/><MessageNumber>5572098</MessageNumber><MessageDateTime>2017-10-31T19:56:22.4312743+01:00</MessageDateTime></MessageReference><Sender>10001</Sender><Recipient>10040</Recipient></MessageHeader>
    <Tagrapportering xmlns="http://xsd.banverket.se/T/Opera/Tagrapportering2.xsd">
        <Tag tagnr="xxxxx" avgangsdatum="2017-10-31" tagslag="RST" dest="M" trafikutovare="Trans...(I intentionally clipped the xml here)
</code>```

Unmarshaller stubbornly says that it expects Tagrapportering in urn:BVTAF namespace but it is NOT in that namespace, this is the beginning of my BVTagrapportering class:

```<code>/**
 * <p>The following schema fragment specifies the expected content contained within this class.
 *
 * ```
 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
  *       <sequence>
  *         <element name="MessageHeader" type="{urn:BVTAF}MessageHeader"/>
  *         <element name="Tagrapportering" type="{http://xsd.banverket.se/T/Opera/Tagrapportering2.xsd}Tagrapportering"/>
  *       </sequence>
  *     </restriction>
  *   </complexContent>
  * </complexType>
  * ```
  *
  *
  */

 @XmlAccessorType(XmlAccessType.FIELD)
 @XmlType(name = "",
    propOrder = {
     "messageHeader",
     "tagrapportering",
    }
 )
 @XmlRootElement(name = "BVTagrapportering" )
 public class BVTagrapportering {

     @XmlElement(name = "MessageHeader", namespace = "urn:BVTAF", required = true)
     protected MessageHeader messageHeader;
     @XmlElement(name = "Tagrapportering", namespace = "http://xsd.banverket.se/T/Opera/Tagrapportering2.xsd", required = true)
     protected Tagrapportering tagrapportering;
</code>```

In my package I have this package.info.java:

```<code>@javax.xml.bind.annotation.XmlSchema(namespace = "urn:BVTAF",
    elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED
)
package bvtaf;
</code>```

The thing is that IF I remove the xmlns attribute in the Tagrapportering element from the incoming SOAP message the unmarshalling works like a charm, but I do not control the incoming SOAP messages so this approach is not a possible way forward for me...

I'm using Apache CXF 3.2.1 web service code generator from wsdl to java to generate my classes and I run it in Tomcat 8.5.

Can anyone please help me!? This is driving me insane...

答:
My bad, the painful embarrassing answer to this question is that my compiler silently stopped to compile and publish my changes (just before I added the namespace definition to the @XmlElements in the above java class, which apparently solved my problem although I never became aware of it because my compiler had stopped working)...

The reason to why my compiler stopped is that I upgraded my Mac OS some time ago, which apparently breaks the Eclipse environment (After OSX upgrade, eclipse is missing applescriptengine.jar). I did not notice that my environment broke down because Eclipse was quite subtle about it and I just continued doing what I was doing.

I apologise to everyone who might have spent time on my question - although no one answered for apparent reasons.

Body:
I've searched high and low to find out why my SOAP service get:

javax.xml.bind.UnmarshalException: unexpected element (uri:"http://xsd.banverket.se/T/Opera/Tagrapportering2.xsd", local:"Tagrapportering"). Expected elements are <{urn:BVTAF}Tagrapportering>,<{urn:BVTAF}MessageHeader>

when my web service receives this xml:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<MessageArray xmlns="urn:BVTAFMessageInbox">
<BVTagrapportering xmlns="urn:BVTAF">
    <MessageHeader><MessageStatus>1</MessageStatus><MessageReference><MessageType MessageTypeCode="0"/><MessageNumber>5572098</MessageNumber><MessageDateTime>2017-10-31T19:56:22.4312743+01:00</MessageDateTime></MessageReference><Sender>10001</Sender><Recipient>10040</Recipient></MessageHeader>
    <Tagrapportering xmlns="http://xsd.banverket.se/T/Opera/Tagrapportering2.xsd">
        <Tag tagnr="xxxxx" avgangsdatum="2017-10-31" tagslag="RST" dest="M" trafikutovare="Trans...(I intentionally clipped the xml here)

Unmarshaller stubbornly says that it expects Tagrapportering in urn:BVTAF namespace but it is NOT in that namespace, this is the beginning of my BVTagrapportering class:

/**
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
  *       <sequence>
  *         <element name="MessageHeader" type="{urn:BVTAF}MessageHeader"/>
  *         <element name="Tagrapportering" type="{http://xsd.banverket.se/T/Opera/Tagrapportering2.xsd}Tagrapportering"/>
  *       </sequence>
  *     </restriction>
  *   </complexContent>
  * </complexType>
  *

  *
  *
  */

 @XmlAccessorType(XmlAccessType.FIELD)
 @XmlType(name = "",
    propOrder = {
     "messageHeader",
     "tagrapportering",
    }
 )
 @XmlRootElement(name = "BVTagrapportering" )
 public class BVTagrapportering {

     @XmlElement(name = "MessageHeader", namespace = "urn:BVTAF", required = true)
     protected MessageHeader messageHeader;
     @XmlElement(name = "Tagrapportering", namespace = "http://xsd.banverket.se/T/Opera/Tagrapportering2.xsd", required = true)
     protected Tagrapportering tagrapportering;

In my package I have this package.info.java:

@javax.xml.bind.annotation.XmlSchema(namespace = "urn:BVTAF",
    elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED
)
package bvtaf;

The thing is that IF I remove the xmlns attribute in the Tagrapportering element from the incoming SOAP message the unmarshalling works like a charm, but I do not control the incoming SOAP messages so this approach is not a possible way forward for me...

I'm using Apache CXF 3.2.1 web service code generator from wsdl to java to generate my classes and I run it in Tomcat 8.5.

Can anyone please help me!? This is driving me insane...


问:
MAPE calculation in Python
I want to calculate Mean Absolute percentage error (MAPE) of predicted and true values. I found a solution from here, but this gives error and shows invalid syntax in the line mask = a <> 0

```<code>    def mape_vectorized_v2(a, b):
    mask = a <> 0
    return (np.fabs(a - b)/a)[mask].mean()

   def mape_vectorized_v2(a, b):
       File "<ipython-input-5-afa5c1162e83>", line 1
         def mape_vectorized_v2(a, b):
                                       ^
     SyntaxError: unexpected EOF while parsing
</code>```

I am using spyder3. My predicted value is a type np.array and true value is dataframe

```<code>type(predicted)
Out[7]: numpy.ndarray
type(y_test)
Out[8]: pandas.core.frame.DataFrame
</code>```

How do i clear this error and proceed with MAPE Calculation ?

Edit :

```<code>predicted.head()
Out[22]:
   Total_kWh
0   7.163627
1   6.584960
2   6.638057
3   7.785487
4   6.994427

y_test.head()
Out[23]:
     Total_kWh
79         7.2
148        6.7
143        6.7
189        7.2
17         6.4

np.abs(y_test[['Total_kWh']] - predicted[['Total_kWh']]).head()
Out[24]:
   Total_kWh
0        NaN
1        NaN
2        NaN
3        NaN
4   0.094427
</code>```

答:
In Python for compare by not equal need !=, not <>.

So need:

```<code>def mape_vectorized_v2(a, b):
    mask = a != 0
    return (np.fabs(a - b)/a)[mask].mean()
</code>```

Another solution from stats.stackexchange:

```<code>def mean_absolute_percentage_error(y_true, y_pred):
    y_true, y_pred = np.array(y_true), np.array(y_pred)
    return np.mean(np.abs((y_true - y_pred) / y_true)) * 100
</code>```

Title: MAPE calculation in Python

Body:
I want to calculate Mean Absolute percentage error (MAPE) of predicted and true values. I found a solution from here, but this gives error and shows invalid syntax in the line mask = a <> 0

    def mape_vectorized_v2(a, b):
    mask = a <> 0
    return (np.fabs(a - b)/a)[mask].mean()

   def mape_vectorized_v2(a, b):
       File "<ipython-input-5-afa5c1162e83>", line 1
         def mape_vectorized_v2(a, b):
                                       ^
     SyntaxError: unexpected EOF while parsing

I am using spyder3. My predicted value is a type np.array and true value is dataframe

type(predicted)
Out[7]: numpy.ndarray
type(y_test)
Out[8]: pandas.core.frame.DataFrame

How do i clear this error and proceed with MAPE Calculation ?

Edit :

predicted.head()
Out[22]:
   Total_kWh
0   7.163627
1   6.584960
2   6.638057
3   7.785487
4   6.994427

y_test.head()
Out[23]:
     Total_kWh
79         7.2
148        6.7
143        6.7
189        7.2
17         6.4

np.abs(y_test[['Total_kWh']] - predicted[['Total_kWh']]).head()
Out[24]:
   Total_kWh
0        NaN
1        NaN
2        NaN
3        NaN
4   0.094427

Body:
In Python for compare by not equal need !=, not <>.

So need:

def mape_vectorized_v2(a, b):
    mask = a != 0
    return (np.fabs(a - b)/a)[mask].mean()

Another solution from stats.stackexchange:

def mean_absolute_percentage_error(y_true, y_pred):
    y_true, y_pred = np.array(y_true), np.array(y_pred)
    return np.mean(np.abs((y_true - y_pred) / y_true)) * 100


问:
How to concatenate columns on top of each other in an array
Say I have the following array:

```<code>a = np.array([[1,3,5,2,3],[3,2,5,6,7],[1,7,3,6,5]]);
</code>```

How can I stack the columns on top of each other to form a single column vector to produce the following?

```<code>b =np.array([[1], [3], [1], [3], [2], [7],[5],[5],[3],[2],[6],[6],[3],[7],[5]]);
</code>```

答:
You can use reshape function and the transpose .T operator

```<code>np.reshape(a.T, (a.size,1))
</code>```

Body:
Say I have the following array:

a = np.array([[1,3,5,2,3],[3,2,5,6,7],[1,7,3,6,5]]);

How can I stack the columns on top of each other to form a single column vector to produce the following?

b =np.array([[1], [3], [1], [3], [2], [7],[5],[5],[3],[2],[6],[6],[3],[7],[5]]);

Body:
You can use reshape function and the transpose .T operator

np.reshape(a.T, (a.size,1))


问:
How do I change sort order for release versions in JIRA/Greenhopper planning?
I've created several release versions in JIRA (the closest thing I could find to a "sprint" functionality) but I cannot for the life of me figure out how it decides what order to put them in, nor how to change it.  I thought maybe it would sort them chronologically by start date, or release date, but no dice.

All I want to do is make a bunch of versions so I can assign user stories, but have them appear in the planning view chronologically.

Any ideas?

答:
Go to the Versions section of the main page for your project.  Because you have permissions to create versions, there should be a "Manage Versions" link in the top right of the content area.

This screen is probably where you added the versions to begin with.
In the table is a "Schedule" column which allows you to change the order of the versions, but be careful, this list is showing versions chronologically backwards.  In other words, the first/next sprint should be at the bottom.

ContentLicense: CC BY-SA 2.5


问:
Retrofit_2 http POST return 403 message
I'm trying to convert Java source code to Android. This is Java code which execute http POST then receive data as json. And it works well.

```<code>public String httpPost(){
String url = "https://webapi.com/api?"
  List<NameValuePair> params;
  List<NameValuePair> headers;

  params.add(new BasicNameValuePair("command", commandValue));
  params.add(new BasicNameValuePair("nonce",
  String.valueOf(System.currentTimeMillis())));

  headers.add(new BasicNameValuePair("Key", API_KEY));
  headers.add(new BasicNameValuePair("Sign", SECRET_SIGNATURE);

  HttpPost post = new HttpPost(url);
        post.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
        String str = post.getEntity().toString();

        if (headers != null)
        {
            for (NameValuePair header : headers)
            {
                post.addHeader(header.getName(), header.getValue());
            }
        }

        HttpResponse response = httpClient.execute(post);
        HttpEntity entity = response.getEntity();
        if (entity != null)
        {
           return  EntityUtils.toString(entity);
        }

    return null;
   }
</code>```

This is Android source code using Retrofit 2:

APIServiceInterface.java

```<code> @POST("api")
    Call<Mymodel> httpPost(@Header("Key") String key,
                                                 @Header("Sign") String sign,
                                                 @Query("command") String command,
                                                 @Query("nonce") String nonce);
</code>```

APIClient.java

```<code>public class ApiClient {
    private static Retrofit retrofit = null;

    public static Retrofit getClient(String baseUrl) {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}
</code>```

POST request

```<code>    String url = "https://webapi.com/";
    APIServiceInterface apiService =   ApiClient.getClient(url).create(APIServiceInterface.class);
    Call<MyModel> call = apiService.httpPost(apiKey, secretSignature, commandValue,  String.valueOf(System.currentTimeMillis()));
            call.enqueue(new Callback<MyModel>() {
                @Override
                public void onResponse(Call<MyModel> call, Response<MyModel> response) {
                    int statusCode = response.code();
                        Log.d(TAG,"http  POST:\n[header]:\n" + call.request().headers() +
                    "\n[request]:\n" + call.request().toString() +
                    "\n[body]: \n" + call.request().body().toString()+
                    "\n----------------------------------------------"+
                    "\nResponse:\n[header]:\n" + response.headers() +
                    "\n[body]:\n"+ response.body() +
                    "\n[raw]:" + response.raw() +
                    "\n[status] :" + response.code() +
                    "\n[message] :" + response.message());
                }

                @Override
                public void onFailure(Call<MyModel> call, Throwable t) {
                    // Log error here since request failed
                    Log.e(TAG, "Request failed :" + t.toString());
                }
            });
</code>```

This is debug log

```<code>http  POST:
[header]:
Key: MHKVXY9C-9WE8N6CS-L1ETB10V-TFUA4S8G
Sign: 2534CCB0C58850B4FA621539D5AA5ACB0433B8F47070E6ED13757006F85FF1E4244D3118BDE107C46A7F5587C06BA201F74DE10003330ECBD352757D23E57ACA

[request]:
Request{method=POST, url=https://webapi.com/api?command=commandValue&nonce=nonceValue, tag=null}
[body]:
okhttp3.RequestBody$2@1751ef1
----------------------------------------------
Response:
[header]:
date: Tue, 05 Dec 2017 07:07:50 GMT
content-type: text/html; charset=UTF-8
set-cookie: __cfduid=d0c467a5dbc10a660a569227616baa28f1512457670; expires=Wed, 05-Dec-18 07:07:50 GMT; path=/; domain=.webapi.com; HttpOnly
cf-chl-bypass: 1
cache-control: max-age=2
expires: Tue, 05 Dec 2017 07:07:52 GMT
x-frame-options: SAMEORIGIN
server: cloudflare-nginx
cf-ray: 3c852bb78ea732ef-HKG

[body]:
null
[raw]:Response{protocol=h2, code=403, message=, url=https://webapi.com/api?command=commandValue&nonce=nonceValue}
[status] :403
[message] :
</code>```

However the Android source code doesn't work, it always return 403 message.
Is my code wrong somewhere?

Could anyone help me! Thanks.

答:
Verify Key & Sign headers from server first.

The 403 Forbidden error is an HTTP status code which means that accessing the page or resource you were trying to reach is absolutely forbidden for some reason.

Verify headers which you are passing and content-type, then test in Postman see if works.

If your api doesn't work in postman then there is nothing you can do in Android to make it work.

UPDATE

try passing header along with http client,

```<code>httpClient.addInterceptor(chain -> {
        Request original = chain.request();

        // Request customization: add request headers
        Request.Builder requestBuilder = original.newBuilder()
                .header("Key", API_KEY)
                .header("Sign", SECRET_SIGNATURE);
                .header("Content-Type", "application/json"); // set your content type

        Request request = requestBuilder.build();
        return chain.proceed(request);
    });

    Retrofit retrofit = builder.client(httpClient.build()).build();
</code>```

Post API should be

```<code> @POST("api")
Call<Mymodel> httpPost(
                       @Query("command") String command,
                       @Query("nonce") String nonce);
</code>```

Title: Retrofit_2 http POST return 403 message

Body:
I'm trying to convert Java source code to Android. This is Java code which execute http POST then receive data as json. And it works well.

public String httpPost(){
String url = "https://webapi.com/api?"
  List<NameValuePair> params;
  List<NameValuePair> headers;

  params.add(new BasicNameValuePair("command", commandValue));
  params.add(new BasicNameValuePair("nonce",
  String.valueOf(System.currentTimeMillis())));

  headers.add(new BasicNameValuePair("Key", API_KEY));
  headers.add(new BasicNameValuePair("Sign", SECRET_SIGNATURE);

  HttpPost post = new HttpPost(url);
        post.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
        String str = post.getEntity().toString();

        if (headers != null)
        {
            for (NameValuePair header : headers)
            {
                post.addHeader(header.getName(), header.getValue());
            }
        }

        HttpResponse response = httpClient.execute(post);
        HttpEntity entity = response.getEntity();
        if (entity != null)
        {
           return  EntityUtils.toString(entity);
        }

    return null;
   }

This is Android source code using Retrofit 2:

APIServiceInterface.java

 @POST("api")
    Call<Mymodel> httpPost(@Header("Key") String key,
                                                 @Header("Sign") String sign,
                                                 @Query("command") String command,
                                                 @Query("nonce") String nonce);

APIClient.java

public class ApiClient {
    private static Retrofit retrofit = null;

    public static Retrofit getClient(String baseUrl) {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

POST request

    String url = "https://webapi.com/";
    APIServiceInterface apiService =   ApiClient.getClient(url).create(APIServiceInterface.class);
    Call<MyModel> call = apiService.httpPost(apiKey, secretSignature, commandValue,  String.valueOf(System.currentTimeMillis()));
            call.enqueue(new Callback<MyModel>() {
                @Override
                public void onResponse(Call<MyModel> call, Response<MyModel> response) {
                    int statusCode = response.code();
                        Log.d(TAG,"http  POST:\n[header]:\n" + call.request().headers() +
                    "\n[request]:\n" + call.request().toString() +
                    "\n[body]: \n" + call.request().body().toString()+
                    "\n----------------------------------------------"+
                    "\nResponse:\n[header]:\n" + response.headers() +
                    "\n[body]:\n"+ response.body() +
                    "\n[raw]:" + response.raw() +
                    "\n[status] :" + response.code() +
                    "\n[message] :" + response.message());
                }

                @Override
                public void onFailure(Call<MyModel> call, Throwable t) {
                    // Log error here since request failed
                    Log.e(TAG, "Request failed :" + t.toString());
                }
            });

This is debug log

http  POST:
[header]:
Key: MHKVXY9C-9WE8N6CS-L1ETB10V-TFUA4S8G
Sign: 2534CCB0C58850B4FA621539D5AA5ACB0433B8F47070E6ED13757006F85FF1E4244D3118BDE107C46A7F5587C06BA201F74DE10003330ECBD352757D23E57ACA

[request]:
Request{method=POST, url=https://webapi.com/api?command=commandValue&nonce=nonceValue, tag=null}
[body]:
okhttp3.RequestBody$2@1751ef1
----------------------------------------------
Response:
[header]:
date: Tue, 05 Dec 2017 07:07:50 GMT
content-type: text/html; charset=UTF-8
set-cookie: __cfduid=d0c467a5dbc10a660a569227616baa28f1512457670; expires=Wed, 05-Dec-18 07:07:50 GMT; path=/; domain=.webapi.com; HttpOnly
cf-chl-bypass: 1
cache-control: max-age=2
expires: Tue, 05 Dec 2017 07:07:52 GMT
x-frame-options: SAMEORIGIN
server: cloudflare-nginx
cf-ray: 3c852bb78ea732ef-HKG

[body]:
null
[raw]:Response{protocol=h2, code=403, message=, url=https://webapi.com/api?command=commandValue&nonce=nonceValue}
[status] :403
[message] :

However the Android source code doesn't work, it always return 403 message.
Is my code wrong somewhere?

Could anyone help me! Thanks.

Body:
Verify Key & Sign headers from server first.

The 403 Forbidden error is an HTTP status code which means that accessing the page or resource you were trying to reach is absolutely forbidden for some reason.

Verify headers which you are passing and content-type, then test in Postman see if works.

If your api doesn't work in postman then there is nothing you can do in Android to make it work.

UPDATE

try passing header along with http client,

httpClient.addInterceptor(chain -> {
        Request original = chain.request();

        // Request customization: add request headers
        Request.Builder requestBuilder = original.newBuilder()
                .header("Key", API_KEY)
                .header("Sign", SECRET_SIGNATURE);
                .header("Content-Type", "application/json"); // set your content type

        Request request = requestBuilder.build();
        return chain.proceed(request);
    });

    Retrofit retrofit = builder.client(httpClient.build()).build();

Post API should be

 @POST("api")
Call<Mymodel> httpPost(
                       @Query("command") String command,
                       @Query("nonce") String nonce);


问:
Unable to use crosstab in Postgres
Postgres 9.2.1 on OSX 10.9.2.

If I run the following crosstab example query:

```<code>CREATE EXTENSION tablefunc;

CREATE TABLE ct(id SERIAL, rowid TEXT, attribute TEXT, value TEXT);
INSERT INTO ct(rowid, attribute, value) VALUES('test1','att1','val1');

SELECT *
FROM crosstab(
  'select rowid, attribute, value
   from ct
   where attribute = ''att2'' or attribute = ''att3''
   order by 1,2')
AS ct(row_name text, category_1 text, category_2 text, category_3 text);
</code>```

I get: ERROR:  extension "tablefunc" already exists

But if I comment out CREATE EXTENSION

I get: ERROR:  function crosstab(unknown) does not exist

How can I get out of this vicious circle?  Is it a known issue?

答:
You can change the first line into:</p>

```<code>CREATE EXTENSION IF NOT EXISTS tablefunc;
</code>```

Title: Unable to use crosstab in Postgres

Body:
Postgres 9.2.1 on OSX 10.9.2.

If I run the following crosstab example query:

CREATE EXTENSION tablefunc;

CREATE TABLE ct(id SERIAL, rowid TEXT, attribute TEXT, value TEXT);
INSERT INTO ct(rowid, attribute, value) VALUES('test1','att1','val1');

SELECT *
FROM crosstab(
  'select rowid, attribute, value
   from ct
   where attribute = ''att2'' or attribute = ''att3''
   order by 1,2')
AS ct(row_name text, category_1 text, category_2 text, category_3 text);

I get: ERROR:  extension "tablefunc" already exists

But if I comment out CREATE EXTENSION

I get: ERROR:  function crosstab(unknown) does not exist

How can I get out of this vicious circle?  Is it a known issue?

Body:
You can change the first line into:

CREATE EXTENSION IF NOT EXISTS tablefunc;


问:
How to share entity between REST service between two microservices?
I have created two micro-services using java. I need to make a REST api call from service A to service B. The data sent will be in JSON format. Using jax-rs I need to create entity class in both the service.

Since both the entity class be same in both the projects. Do i

Create an common jar and use is for all my entity/domain objects? Does this make my microservice more tightly coupled?

Do i create the same class in both the microservice projects? This will just mean repeating the work in both the projects?

Is there a better way to communicate between the sevices?

答:
In terms of having your two micro services independent and having them also independent in the future I would also duplicate the code. We had the exact same situation before. Several microservices seem to use some "common" classes that can be put to a seperate jar.
In the end we had following situation:

several (5+) services using the same JAR

turned out that classes that we thought are the same, seemed to have slightly different semantics in different services

a change on one of the classes more or less forced us to have a release on every microservice, when it came to releasing (no independency here anymore)

developers tend to see "common" behavior everywhere, so you most likely end up with some "Helper/Utility" classes there as well which is in the meanwhile considered a code smell in OOP

Long story short, in the meanwhile we switched to having the code duplicated, which gives us the freedom to handle our mircoservices really independently, as we only need to stick to the service contract. What happens internally is fully up to the service and we don't have to release all services in the end of an iteration. I'm not saying that the other option is wrong, but it turned out that it was not suitable for us. If you really see common classes between two services and you are sure you don't mess your common library up with other crap, your save to go.

EDIT

Maybe as follow up, we had the same discussion in regards of tests (unit and integration) having share test code in some common classes. In the end this was hell, as every slight change in code or acceptance criteria made 50% of tests fail. Meanwhile our strategy is to not share anything on test level and have everything  right at the tests place. By that you are super fast in eliminating or changing tests. In the end the lesson for us was to keep business code as clean and elegante as suitable and the test code in a way to give us the least headache possible.

Edit2
Meanwhile, we define all our REST interface with open api specifications and create the actual DTO objects that are exchanged via the maven plugin openapi-generator. The spec resides in the project that implements the interface and it is  published to artifactory. The project implementing the client pulls it and creates DTOs based on that. By that, you have a single point of truth and no need to write DTO boilerplate code.


问:
How to get class name only, not full path?
I am aware that using Context and a method getClass().getName() I can get a string which represent full class name, like com.package1.package2.MainActivity.

How can I get only the last part, class name only? In this case it would be MainActivity string.

I can do it with a simple split() method, but maybe there is a better way, more reliable.

答:
If you want to get the name outside the class you can call:

```<code>MainActivity.class.getSimpleName()
</code>```

in this way you can avoid to make your class static.

Body:
If you want to get the name outside the class you can call:

MainActivity.class.getSimpleName()

in this way you can avoid to make your class static.


问:
Specifying which activity to launch dynamically
I am developing a chat application.

Once logged in, the user should be navigated into the main page next time when he start the app. Like WhatsApp, it does not have a splash screen. So, Where do I do the check if the user has logged in or not next time ? I don't want to launch the login screen again if the user is already logged in.

Can I launch a service or something on the first time in which I can check which activity is shown next?

答:
May be you can create an empty activity which extends Activity (not AppCompatActivity) and do the logic there since we can't launch a service directly.

You don't need to call setContentView there. So no layout file is required. Add this in your manifest android:theme="@android:style/Theme.NoDisplay"


问:
in rails using will_paginate and partials
I have a collection of people that is paginated with will_paginate

```<code>@people = Person.paginate :page => params[:page],
                :limit => 10,
                    :conditions =>   ['company_id = ? ' , @company.id ]
</code>```

The people are shown on the company/view page and rendered with a partial. Note that the partial is in the views of 'people'

```<code><%= render :partial => "people/person" , :locals => { :people => @people }%>
</code>```

in the partial ...

```<code><% for person in @people %>

     ...

<%end%>

<%= will_paginate @people %>
</code>```

Now the partial does work, it renders all of the people and shows the paginate links on the bottom. However it doesn't not actually paginate the collection and instead it shows everything on the first page.

I am clearly missing something rather basic.

Thanks in advance.

答: Are you missing per_page?

OwnerDisplayName: Chris Tosswill

Body:
I have a collection of people that is paginated with will_paginate

@people = Person.paginate :page => params[:page],
                :limit => 10,
                    :conditions =>   ['company_id = ? ' , @company.id ]

The people are shown on the company/view page and rendered with a partial. Note that the partial is in the views of 'people'

<%= render :partial => "people/person" , :locals => { :people => @people }%>

in the partial ...

<% for person in @people %>

     ...

<%end%>

<%= will_paginate @people %>

Now the partial does work, it renders all of the people and shows the paginate links on the bottom. However it doesn't not actually paginate the collection and instead it shows everything on the first page.

I am clearly missing something rather basic.

Thanks in advance.

Body: Are you missing per_page?

OwnerDisplayName: George IV


问:
Workaround for ActiveState Komodo bug with F10 keyboard shortcut?
I'd really like F10 to Step Over in my Komodo IDE, to match Visual Studio. Unfortunately F10 has been hardwired to select the File menu. This is a known bug (see http://bugs.activestate.com/show_bug.cgi?id=81657 ).

Has anyone found a workaround?

I'd rather not reconfigure Visual Studio and my crusty brain. I'm using Komodo version 5.2.4.

答: It's been a while since I've use Komodo so I make no guarantees that this will work, but the first thing I'd try is using an AutoHotKey script that looks for an F10 keypress in a Komodo window and sends instead whatever key sequence Komodo uses for the "Step Over" operation.</p>


问:
Python import updated reference
I would like to import a refence to an object, with its value updated after the initial file which imported the reference has been parsed by python. For example:

runner.py

```<code>from store import modify_var
from importer import a_function

print('>>runner')
modify_var()
a_function()
</code>```

store.py

```<code>my_var = None

def modify_var():
    global my_var
    my_obj = MyObj()
    my_var = my_obj
    print('>>store, my_var has been set to: {0}'.format(my_var))

class MyObj(object):
    x = 2
</code>```

importer.py

```<code>from store import my_var

print('>>importer, my_var outside function (before has been set): {0}'.format(my_var))

def a_function():
   print('>>importer, my_var after is has been set: {0}'.format(my_var))
</code>```

console output after running runner.py

```<code>>>importer, my_var outside function (before has been set): None
>>runner
>>store, my_var has been set to: <tests.store.MyObj object at 0x7fbfc683a1d0>
>>importer, my_var after is has been set: None
</code>```

I am trying to figure out how I can import my_var such that when I call it in a function it's value is not None.

答:
I think it doesn't like the fact that you declare my_var after giving it a value in store.py. Try one of the following:

Inside store.py, make another method that will return my_var as none:

```<code>def my_var_none():
    my_var = None
    return my_var
</code>```

Then, leave runner.py as it is, and inside importer.py:

```<code>from store.py import my_var_none()
</code>```

Title: Python import updated reference

Body:
I would like to import a refence to an object, with its value updated after the initial file which imported the reference has been parsed by python. For example:

runner.py

from store import modify_var
from importer import a_function

print('>>runner')
modify_var()
a_function()

store.py

my_var = None

def modify_var():
    global my_var
    my_obj = MyObj()
    my_var = my_obj
    print('>>store, my_var has been set to: {0}'.format(my_var))

class MyObj(object):
    x = 2

importer.py

from store import my_var

print('>>importer, my_var outside function (before has been set): {0}'.format(my_var))

def a_function():
   print('>>importer, my_var after is has been set: {0}'.format(my_var))

console output after running runner.py

>>importer, my_var outside function (before has been set): None
>>runner
>>store, my_var has been set to: <tests.store.MyObj object at 0x7fbfc683a1d0>
>>importer, my_var after is has been set: None

I am trying to figure out how I can import my_var such that when I call it in a function it's value is not None.

Body:
I think it doesn't like the fact that you declare my_var after giving it a value in store.py. Try one of the following:

Inside store.py, make another method that will return my_var as none:

def my_var_none():
    my_var = None
    return my_var

Then, leave runner.py as it is, and inside importer.py:

from store.py import my_var_none()


问:
Fetching data from zookeeper znode

I tried to get the data from zookeeper's znode using Java API. Followed below link

https://www.tutorialspoint.com/zookeeper/zookeeper_api.htm
Program: ZKGetData.java

I'm getting results like this

"(clusterSecondarynn1node4.test.com �>(�>)"

How to get "node4.test.com" alone.

答:
It is strongly recommended to use some layer against ZK, like Apache Curator, or ZkClient.
Here's an example

```<code>CuratorFramework zkClient = CuratorFrameworkFactory.builder().connectString("localhost:2181").build();
zkClient.start();
boolean isExist = zkClient.checkExists().forPath("/myNode") != null;
if (isExist) {
    byte[] myNodeBytes = zkClient.getData().forPath("/myNode");
    if (myNodeBytes != null && myNodeBytes.length > 0) {
        System.out.println(new String(myNodeBytes));
    }
}
else {
    zkClient.create().withMode(CreateMode.PERSISTENT).forPath("/myNode", "foo".getBytes());
}
</code>```

Title: Fetching data from zookeeper znode

Body:
It is strongly recommended to use some layer against ZK, like Apache Curator, or ZkClient.
Here's an example

CuratorFramework zkClient = CuratorFrameworkFactory.builder().connectString("localhost:2181").build();
zkClient.start();
boolean isExist = zkClient.checkExists().forPath("/myNode") != null;
if (isExist) {
    byte[] myNodeBytes = zkClient.getData().forPath("/myNode");
    if (myNodeBytes != null && myNodeBytes.length > 0) {
        System.out.println(new String(myNodeBytes));
    }
}
else {
    zkClient.create().withMode(CreateMode.PERSISTENT).forPath("/myNode", "foo".getBytes());
}


问:
Tag Helper Embedded in Another Tag Helper's Code Doesn't Render
I'm trying to simplify creation of long forms with the following custom tag helper in .net Core 2.0:

```<code>@model ObApp.Web.Models.ViewComponents.FormFieldViewModel

<span>Debug - Paramater value: @Model.FieldFor</span>
<div class="form-group">
    <label asp-for="@Model.FieldFor"></label>
    <input asp-for="@Model.FieldFor" class="form-control" />
</div>
</code>```

It seems simple, but I'm getting an unexpected (to me) result when I use:

```<code><vc:form-field field-for="PersonEmail"></vc:form-field>
</code>```

Expected Result

```<code><span>Debug - Paramater value: PersonEmail</span>
<div class="form-group">
    <label for="PersonEmail">Email</label>
    <input name="PersonEmail" class="form-control" id="PersonEmail"
        type="text" value="PersonEmail">
</div>
</code>```

Actual Result

```<code><span>Debug - Paramater value: PersonEmail</span>
<div class="form-group">
    <label for="FieldFor">FieldFor</label>
    <input name="FieldFor" class="form-control" id="FieldFor"
        type="text" value="PersonEmail">
</div>
</code>```

I've tried removing the quotes from around @Model.FieldFor, as well as a few other syntactic changes.

Any suggestions?

Thank you!

答:
As was pointed out to me by others, it may not be possible to directly embed tag helpers the way I first desired when I posted this question. As a result I refactored the code to programmatically "new up" the desired tag helpers instead.

My final solution was significantly more work than I had expected but in the long run it will save lots of time developing the form-intensive applications I have planned.

The Objective

My goal is to speed-up creation of forms by using this custom tag helper, for example:

```<code><formfield asp-for="OrganizationName"></formfield>
</code>```

To generate these built-in Razor tag helpers:

```<code><div class="form-group">
    <div class="row">
        <label class="col-md-3 col-form-label" for="OrganizationName">Company Name</label>
        <div class="col-md-9">
            <input name="OrganizationName" class="form-control" id="OrganizationName" type="text" value="" data-val-required="The Company Name field is required." data-val="true" data-val-maxlength-max="50" data-val-maxlength="Maximum company name length is 50 characters.">
            <span class="field-validation-valid" data-valmsg-replace="true" data-valmsg-for="OrganizationName"></span>
        </div>
    </div>
</div>
</code>```

My Initial Working Solution

This is the first-pass test solution for simple cases. I.e. for default hard coded classes and text-box input types.

```<code>using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.TagHelpers;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace ObApp.Web.TagHelpers
{
    // Builds form elements to generate the following (for example):
    // <div class="form-group">
    //     <div class="row">
    //         <input ... >Email</input>
    //         <div>
    //             <input type="text" ... />
    //             <span class="field-validation-valid ... ></span>
    //         </div>
    //     </div>
    // </div>

    public class FormfieldTagHelper : TagHelper
    {
        private const string _forAttributeName = "asp-for";
        private const string _defaultWraperDivClass = "form-group";
        private const string _defaultRowDivClass = "row";
        private const string _defaultLabelClass = "col-md-3 col-form-label";
        private const string _defaultInputClass = "form-control";
        private const string _defaultInnerDivClass = "col-md-9";
        private const string _defaultValidationMessageClass = "";

        public FormfieldTagHelper(IHtmlGenerator generator)
        {
            Generator = generator;
        }

        [HtmlAttributeName(_forAttributeName)]
        public ModelExpression For { get; set; }

        public IHtmlGenerator Generator { get; }

        [ViewContext]
        [HtmlAttributeNotBound]
        public ViewContext ViewContext { get; set; }

        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            // Replace this parent tag helper with div tags wrapping the entire form block
            output.TagName = "div";
            output.Attributes.SetAttribute("class", _defaultWraperDivClass);

            // Manually new-up each child asp form tag helper element
            TagHelperOutput labelElement = await CreateLabelElement(context);
            TagHelperOutput inputElement = await CreateInputElement(context);
            TagHelperOutput validationMessageElement = await CreateValidationMessageElement(context);

            // Wrap input and validation with column div
            IHtmlContent innerDiv = WrapElementsWithDiv(
                    new List<IHtmlContent>()
                    {
                        inputElement,
                        validationMessageElement
                    },
                    _defaultInnerDivClass
                );

            // Wrap all elements with a row div
            IHtmlContent rowDiv = WrapElementsWithDiv(
                    new List<IHtmlContent>()
                    {
                        labelElement,
                        innerDiv
                    },
                    _defaultRowDivClass
                );

            // Put everything into the innerHtml of this tag helper
            output.Content.SetHtmlContent(rowDiv);
        }

        private async Task<TagHelperOutput> CreateLabelElement(TagHelperContext context)
        {
            LabelTagHelper labelTagHelper =
                new LabelTagHelper(Generator)
                {
                    For = this.For,
                    ViewContext = this.ViewContext
                };

            TagHelperOutput labelOutput = CreateTagHelperOutput("label");

            await labelTagHelper.ProcessAsync(context, labelOutput);

            labelOutput.Attributes.Add(
                new TagHelperAttribute("class", _defaultLabelClass));

            return labelOutput;
        }

        private async Task<TagHelperOutput> CreateInputElement(TagHelperContext context)
        {
            InputTagHelper inputTagHelper =
                new InputTagHelper(Generator)
                {
                    For = this.For,
                    ViewContext = this.ViewContext
                };

            TagHelperOutput inputOutput = CreateTagHelperOutput("input");

            await inputTagHelper.ProcessAsync(context, inputOutput);

            inputOutput.Attributes.Add(
                new TagHelperAttribute("class", _defaultInputClass));

            return inputOutput;
        }

        private async Task<TagHelperOutput> CreateValidationMessageElement(TagHelperContext context)
        {
            ValidationMessageTagHelper validationMessageTagHelper =
                new ValidationMessageTagHelper(Generator)
                {
                    For = this.For,
                    ViewContext = this.ViewContext
                };

            TagHelperOutput validationMessageOutput = CreateTagHelperOutput("span");

            await validationMessageTagHelper.ProcessAsync(context, validationMessageOutput);

            return validationMessageOutput;
        }

        private IHtmlContent WrapElementsWithDiv(List<IHtmlContent> elements, string classValue)
        {
            TagBuilder div = new TagBuilder("div");
            div.AddCssClass(classValue);
            foreach(IHtmlContent element in elements)
            {
                div.InnerHtml.AppendHtml(element);
            }

            return div;
        }

        private TagHelperOutput CreateTagHelperOutput(string tagName)
        {
            return new TagHelperOutput(
                tagName: tagName,
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (s, t) =>
                {
                    return Task.Factory.StartNew<TagHelperContent>(
                            () => new DefaultTagHelperContent());
                }
            );
        }
    }
}
</code>```

Next Steps/Suggested Improvements

This is working well for text boxes without validation errors. After tweaking the default CSS the next steps I plan to take are:

Display the correct CSS class attributes for formatting when there are validation errors. At this point the tag helper will be "working" for me.

Move the hard coded CSS classes out to a site configuration file.

Bind to HTML attributes in the view to allow non-default classes to be passed in. Another way to do this would be to pass in non-default form classes through the ViewModel.

Detect non-textbox input types and format accordingly.

Thank you to @Chris Pratt for getting me started in the right direction on this.

Body:
I'm trying to simplify creation of long forms with the following custom tag helper in .net Core 2.0:

@model ObApp.Web.Models.ViewComponents.FormFieldViewModel

Debug - Paramater value: @Model.FieldFor

    <input asp-for="@Model.FieldFor" class="form-control" />

It seems simple, but I'm getting an unexpected (to me) result when I use:

<vc:form-field field-for="PersonEmail"></vc:form-field>

Expected Result

Debug - Paramater value: PersonEmail

    Email
    <input name="PersonEmail" class="form-control" id="PersonEmail"
        type="text" value="PersonEmail">

Actual Result

Debug - Paramater value: PersonEmail

    FieldFor
    <input name="FieldFor" class="form-control" id="FieldFor"
        type="text" value="PersonEmail">

I've tried removing the quotes from around @Model.FieldFor, as well as a few other syntactic changes.

Any suggestions?

Thank you!

Body:
As was pointed out to me by others, it may not be possible to directly embed tag helpers the way I first desired when I posted this question. As a result I refactored the code to programmatically "new up" the desired tag helpers instead.

My final solution was significantly more work than I had expected but in the long run it will save lots of time developing the form-intensive applications I have planned.

The Objective

My goal is to speed-up creation of forms by using this custom tag helper, for example:

<formfield asp-for="OrganizationName"></formfield>

To generate these built-in Razor tag helpers:

<div class="form-group">
    <div class="row">
        <label class="col-md-3 col-form-label" for="OrganizationName">Company Name</label>
        <div class="col-md-9">
            <input name="OrganizationName" class="form-control" id="OrganizationName" type="text" value="" data-val-required="The Company Name field is required." data-val="true" data-val-maxlength-max="50" data-val-maxlength="Maximum company name length is 50 characters.">
            <span class="field-validation-valid" data-valmsg-replace="true" data-valmsg-for="OrganizationName"></span>
        </div>
    </div>
</div>

My Initial Working Solution

This is the first-pass test solution for simple cases. I.e. for default hard coded classes and text-box input types.

using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.TagHelpers;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace ObApp.Web.TagHelpers
{
    // Builds form elements to generate the following (for example):
    // <div class="form-group">
    //     <div class="row">
    //         <input ... >Email</input>
    //         <div>
    //             <input type="text" ... />
    //             <span class="field-validation-valid ... ></span>
    //         </div>
    //     </div>
    // </div>

    public class FormfieldTagHelper : TagHelper
    {
        private const string _forAttributeName = "asp-for";
        private const string _defaultWraperDivClass = "form-group";
        private const string _defaultRowDivClass = "row";
        private const string _defaultLabelClass = "col-md-3 col-form-label";
        private const string _defaultInputClass = "form-control";
        private const string _defaultInnerDivClass = "col-md-9";
        private const string _defaultValidationMessageClass = "";

        public FormfieldTagHelper(IHtmlGenerator generator)
        {
            Generator = generator;
        }

        [HtmlAttributeName(_forAttributeName)]
        public ModelExpression For { get; set; }

        public IHtmlGenerator Generator { get; }

        [ViewContext]
        [HtmlAttributeNotBound]
        public ViewContext ViewContext { get; set; }

        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            // Replace this parent tag helper with div tags wrapping the entire form block
            output.TagName = "div";
            output.Attributes.SetAttribute("class", _defaultWraperDivClass);

            // Manually new-up each child asp form tag helper element
            TagHelperOutput labelElement = await CreateLabelElement(context);
            TagHelperOutput inputElement = await CreateInputElement(context);
            TagHelperOutput validationMessageElement = await CreateValidationMessageElement(context);

            // Wrap input and validation with column div
            IHtmlContent innerDiv = WrapElementsWithDiv(
                    new List<IHtmlContent>()
                    {
                        inputElement,
                        validationMessageElement
                    },
                    _defaultInnerDivClass
                );

            // Wrap all elements with a row div
            IHtmlContent rowDiv = WrapElementsWithDiv(
                    new List<IHtmlContent>()
                    {
                        labelElement,
                        innerDiv
                    },
                    _defaultRowDivClass
                );

            // Put everything into the innerHtml of this tag helper
            output.Content.SetHtmlContent(rowDiv);
        }

        private async Task<TagHelperOutput> CreateLabelElement(TagHelperContext context)
        {
            LabelTagHelper labelTagHelper =
                new LabelTagHelper(Generator)
                {
                    For = this.For,
                    ViewContext = this.ViewContext
                };

            TagHelperOutput labelOutput = CreateTagHelperOutput("label");

            await labelTagHelper.ProcessAsync(context, labelOutput);

            labelOutput.Attributes.Add(
                new TagHelperAttribute("class", _defaultLabelClass));

            return labelOutput;
        }

        private async Task<TagHelperOutput> CreateInputElement(TagHelperContext context)
        {
            InputTagHelper inputTagHelper =
                new InputTagHelper(Generator)
                {
                    For = this.For,
                    ViewContext = this.ViewContext
                };

            TagHelperOutput inputOutput = CreateTagHelperOutput("input");

            await inputTagHelper.ProcessAsync(context, inputOutput);

            inputOutput.Attributes.Add(
                new TagHelperAttribute("class", _defaultInputClass));

            return inputOutput;
        }

        private async Task<TagHelperOutput> CreateValidationMessageElement(TagHelperContext context)
        {
            ValidationMessageTagHelper validationMessageTagHelper =
                new ValidationMessageTagHelper(Generator)
                {
                    For = this.For,
                    ViewContext = this.ViewContext
                };

            TagHelperOutput validationMessageOutput = CreateTagHelperOutput("span");

            await validationMessageTagHelper.ProcessAsync(context, validationMessageOutput);

            return validationMessageOutput;
        }

        private IHtmlContent WrapElementsWithDiv(List<IHtmlContent> elements, string classValue)
        {
            TagBuilder div = new TagBuilder("div");
            div.AddCssClass(classValue);
            foreach(IHtmlContent element in elements)
            {
                div.InnerHtml.AppendHtml(element);
            }

            return div;
        }

        private TagHelperOutput CreateTagHelperOutput(string tagName)
        {
            return new TagHelperOutput(
                tagName: tagName,
                attributes: new TagHelperAttributeList(),
                getChildContentAsync: (s, t) =>
                {
                    return Task.Factory.StartNew<TagHelperContent>(
                            () => new DefaultTagHelperContent());
                }
            );
        }
    }
}

Next Steps/Suggested Improvements

This is working well for text boxes without validation errors. After tweaking the default CSS the next steps I plan to take are:

Display the correct CSS class attributes for formatting when there are validation errors. At this point the tag helper will be "working" for me.

Move the hard coded CSS classes out to a site configuration file.

Bind to HTML attributes in the view to allow non-default classes to be passed in. Another way to do this would be to pass in non-default form classes through the ViewModel.

Detect non-textbox input types and format accordingly.

Thank you to @Chris Pratt for getting me started in the right direction on this.


问:
What is the best way to write a git update hook that rejects invalid submodule commits?
I am attempting to write an update hook for git that bounces if a submodule is being updated to a commit ID that does not exist in the submodule's upstream repository. To say it another way, I want to force users to push changes to the submodule repositories before they push changes to the submodule pointers.

One caveat:

I only want to test submodules whose bare, upstream repositories exist on the same server as the parent repository. Otherwise we start having to do crazy things like call 'git clone' or 'git fetch' from within a git hook, which would not be fun.

I have been playing around with an idea but it feels like there must be a better way to do this. Here is what I was planning on doing in the update hook:

Check the refname passed into the hook to see if we are updating something under refs/heads/. If not, exit early.

Use git rev-list to get a list of revisions being pushed.

For each revision:

Call git show <revision_id> and use a regular expression that looks to see if a submodule was updated (by searching for `+Subproject commit [0-9a-f]+).

If this commit did change a submodule, get the contents of the .gitmodules files as seen by that particular commit (git show <revision_id>:.gitmodules).

Use the results of 3.1 and 3.2 to get a list of submodule URLs and their updated commit IDs.

Check this list created in 3.3 against an external file that maps submodule URLs to local bare git repositories on the filesystem.

cd to the paths found in 3.4 and execute git rev-parse --quiet --verify <updated_submodule_commit_id> to see if that commit exists in that repository. If it does not, exit with a non-zero status.

(Note: I believe the results of 3.2 can potentially be cached across revisions as long as the output to git rev-parse --quiet --verify <revision_id>:.gitmodules doesn't change from one revision to the next. I left this part out to simplify the solution.)

So yeah, this seems pretty complex, and I can't help but wonder if there are some internal git commands that might make my life a lot easier. Or maybe there is a different way to think about the problem?

答:
Edit, much later: As of Git 1.7.7, git-push now has a --recurse-submodules=check option, which refuses to push the parent project if any submodule commits haven't been pushed to their remotes. It doesn't appear that a corresponding push.recurseSubmodules config parameter has been added yet. This of course doesn't entirely address the problem - a clueless user could still push without the check - but it's quite relevant!

I think the best approach, rather than examining each individual commit, is to look at the diff across all of the pushed commits: git diff <old> <new>. You don't want to look at the whole diff though, really; it could be enormous. Unfortunately, the git-submodule porcelain command doesn't work in bare repos, but you should still be able to quickly examine .gitmodules to get a list of paths (and maybe URLs). For each one, you can git diff <old> <new> -- path, and if there is a diff, grab the new submodule commit. (And if you're worried about a 000000 old commit possibility, you can just use git show on the new one, I believe.)

Once you get all that taken care of, you've reduced the problem to checking whether given commits exist in given remote repositories. Unfortunately, as it looks like you've noticed, that's not straightforward, at least as far as I know. Keeping local, up-to-date clones is probably your best bet, and it sounds like you're good there.

By the way, I don't think the caching is going to be relevant here, since the update hook is once per ref. Yes, you could do this in a pre-receive hook, which gets all the refs on stdin, but I don't see why you should bother doing more work. It's not going to be an expensive operation, and with an update hook, you can individually accept or reject the various branches being pushed, instead of preventing all of them from being updated because only one was bad.

If you want to save some trouble, I'd probably just avoid parsing the gitmodules file, and hardcode a list into the hook. I doubt your list of submodules changes very often, so it's probably cheaper to maintain that than to write something automated.


问:
How do I close the timer channel?
I have a timer which is reset by certain events. A go function listens to the channel using range. How do I close the channel so that for loop exits? </p>

```<code>func resetTimer(){
        if rf.electionTimer != nil {
             rf.electionTimer.Stop()
        }
}

rf.electionTimer = time.NewTimer(electionTime)

for _ = range rf.electionTimer.C {
  // Do something
}
</code>```

答:
Use a channel to signal when the loop should exit.

```<code>rf.done := make(chan struct{})
rf.electionTimer = time.NewTimer(electionTime)

func stopTimer(){
    if rf.electionTimer != nil {
         rf.electionTimer.Stop()
         close(rf.done)
    }
}
</code>```

Select on both the signal channel and the timer channel in a loop.  Break out of the loop when signal channel is closed.

```<code>loop:
    for {
        select {
        case t := <-rf.electionTimer.C:
            // Do something
        case <-rf.done:
            break loop
        }
    }
</code>```

Note that it does not make sense to use a loop in the question or this answer if the application does not call Reset on the timer. If the timer is not reset, then only one value will be sent to the timer's channel.

Title: How do I close the timer channel?

Body:
I have a timer which is reset by certain events. A go function listens to the channel using range. How do I close the channel so that for loop exits?

func resetTimer(){
        if rf.electionTimer != nil {
             rf.electionTimer.Stop()
        }
}

rf.electionTimer = time.NewTimer(electionTime)

for _ = range rf.electionTimer.C {
  // Do something
}

Body:
Use a channel to signal when the loop should exit.

rf.done := make(chan struct{})
rf.electionTimer = time.NewTimer(electionTime)

func stopTimer(){
    if rf.electionTimer != nil {
         rf.electionTimer.Stop()
         close(rf.done)
    }
}

Select on both the signal channel and the timer channel in a loop.  Break out of the loop when signal channel is closed.

loop:
    for {
        select {
        case t := <-rf.electionTimer.C:
            // Do something
        case <-rf.done:
            break loop
        }
    }

Note that it does not make sense to use a loop in the question or this answer if the application does not call Reset on the timer. If the timer is not reset, then only one value will be sent to the timer's channel.


问:
I want to read the data in the provided link in R
```<code>read.table("http://people.sc.fsu.edu/~jburkardt/datasets/regression/x06.txt",fill=TRUE,header=FALSE)
            V1      V2    V3       V4       V5
1            4 columns
2           44    rows
3        Index
4          Age      of  fish   (days)
5  Temperature      of water (degrees Celsius)
6       Length      of  fish
7            1      14    25      620
8            2      28    25     1315
9            3      41    25     2120
</code>```

I just want to know how can I read only the data part of this txt link in R?
My read.table function showing Variables as V1 V2...V5 and Variables such as Index, Age of fish etc. in rows. Please have a look at the data by clicking on the link and let me know if it can be done.

Please tell me you know any other way to read this data easily.

答:
You can read like this</p>

```<code>df <- read.table("http://people.sc.fsu.edu/~jburkardt/datasets/regression/x06.txt",fill=TRUE,header=FALSE)[7:50,1:4]
row.names(df) <- NULL
</code>```

Body:
read.table("http://people.sc.fsu.edu/~jburkardt/datasets/regression/x06.txt",fill=TRUE,header=FALSE)
            V1      V2    V3       V4       V5
1            4 columns
2           44    rows
3        Index
4          Age      of  fish   (days)
5  Temperature      of water (degrees Celsius)
6       Length      of  fish
7            1      14    25      620
8            2      28    25     1315
9            3      41    25     2120

I just want to know how can I read only the data part of this txt link in R?
My read.table function showing Variables as V1 V2...V5 and Variables such as Index, Age of fish etc. in rows. Please have a look at the data by clicking on the link and let me know if it can be done.

Please tell me you know any other way to read this data easily.

Body:
You can read like this

df <- read.table("http://people.sc.fsu.edu/~jburkardt/datasets/regression/x06.txt",fill=TRUE,header=FALSE)[7:50,1:4]
row.names(df) <- NULL


问:
load class in war into global classpath (Wildfly)
I want to deploy a war file to a Wildfly 10 server and expose a class to the global class path. I want to be able to use this class within other war files.

Do you know if this is possible at deploytime?

Best Regards
Alex

答:
Different war files in the deployments directory are separated by different class loaders. Hence, you cannot access from one war classes from another war.

If you need "global" functionality that is accessible by all deployments, you can add a new module. Adjust and invoke the following command:

```<code>./jboss-cli.sh -c --command="module add --name=<your-module> --resources=<path-to-file>/<your-jar>.jar --dependencies=<your-dependencies-comma-separated>"
</code>```

This will create a new folder under $JBOSS_HOME\modules with a module.xml file next to your jar. For more information about adding modules look for example here.

Then add a dependency on this new module in your two war files, either by adding the module's name to the Class-Path entry in your MANIFEST.MF file or by supplying a dedicated jboss-deployment-structure.xml file (for more information see here).

Body:
Different war files in the deployments directory are separated by different class loaders. Hence, you cannot access from one war classes from another war.

If you need "global" functionality that is accessible by all deployments, you can add a new module. Adjust and invoke the following command:

./jboss-cli.sh -c --command="module add --name=<your-module> --resources=<path-to-file>/<your-jar>.jar --dependencies=<your-dependencies-comma-separated>"

This will create a new folder under $JBOSS_HOME\modules with a module.xml file next to your jar. For more information about adding modules look for example here.

Then add a dependency on this new module in your two war files, either by adding the module's name to the Class-Path entry in your MANIFEST.MF file or by supplying a dedicated jboss-deployment-structure.xml file (for more information see here).


问:
can not get error in node.js / javascript
I wrote the code and execute but cannot get error message occurred in HTML. I use Eclipse and node.js with express and the GET method.

But when I enter IP and port and push submit, HTML show cHTMLt get ~ip=~;port=~

Is there something I have done wrong?

```<code> index.ejs
<!DOCTYPE html>
<html>
   <head>
    <title><%= title %></title>
     <link rel='stylesheet' href='/stylesheets/style.css' />
   </head>
<body>
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
    <form action="/testget" method="get">
    <input type="text" name="ip"> <p>
    <input type="text" name="port"> <p>
    <input type="submit">
     </form>
  </body>
  </html>

app.js
 var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

if ('development' === app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/users', user.list);

app.get('/testget', function(req,res){

    res.send(req.query.ip + ',' + req.query.port );
});

http.createServer(app).listen(app.get('port'), function(){
   console.log('Express server listening on port ' + app.get('port'));
});
</code>```

答:
you can use</p>

```<code>request.connection.remoteAddress

or

const ip = req.socket.localAddress;
const port = req.socket.localPort;
</code>```

Body:
I wrote the code and execute but cannot get error message occurred in HTML. I use Eclipse and node.js with express and the GET method.

But when I enter IP and port and push submit, HTML show cHTMLt get ~ip=~;port=~

Is there something I have done wrong?

 index.ejs
<!DOCTYPE html>

    <title><%= title %></title>
     <link rel='stylesheet' href='/stylesheets/style.css' />

<%= title %>

Welcome to <%= title %>

    <form action="/testget" method="get">
    <input type="text" name="ip">

    <input type="text" name="port">

    <input type="submit">
     </form>

app.js
 var express = require('express')
  , routes = require('./routes')
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));

if ('development' === app.get('env')) {
  app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/users', user.list);

app.get('/testget', function(req,res){

    res.send(req.query.ip + ',' + req.query.port );
});

http.createServer(app).listen(app.get('port'), function(){
   console.log('Express server listening on port ' + app.get('port'));
});

Body:
you can use

request.connection.remoteAddress

or

const ip = req.socket.localAddress;
const port = req.socket.localPort;