问:
3rd level child on breadcrumbs in woocommerce not working
I have here a code that works fine except for the woocommerce product page

for example:

```<code>Home > category1 > category2 > category3
</code>```

but when I go to the product page it shows only like this

```<code>Home > category1 > product
</code>```

I need it to show in the product page

```<code>Home > category1 > category2 > category3 > product
</code>```

I think this is where to modify the code
( if ( get_post_type() == 'product' ) {} )

Here is the code below:

```<code>function limelight_breadcrumbs()
{
global $post, $wp_query;
if ( ! $home ) $home = __( 'Home', 'limelight' );
$home_link = home_url();
$delimiter = ' » ';
$currentBefore = '<span class="current">';
$currentAfter = '</span>';
$wrap_before = ' <nav id="breadcrumbs">';
$wrap_after = '</nav> ';

if ( get_option('woocommerce_prepend_shop_page_to_urls') == "yes" && woocommerce_get_page_id( 'shop' ) &&   get_option( 'page_on_front' ) !== woocommerce_get_page_id( 'shop' ) )
$prepend = '<a href="' . get_permalink( woocommerce_get_page_id('shop') ) . '">' . get_the_title( woocommerce_get_page_id('shop') ) . '</a> ' . $delimiter;
else $prepend = '';

if ( ( ! is_front_page() && ! ( is_post_type_archive() && get_option( 'page_on_front' ) == woocommerce_get_page_id( 'shop' ) ) ) || is_paged() ) {

    echo $wrap_before . '<a class="home" href="' . $home_link . '">' . $home . '</a> ' . $delimiter ;

    if ( is_category() ) {

        $cat_obj = $wp_query->get_queried_object();
        $this_category = get_category( $cat_obj->term_id );

        if ( $this_category->parent != 0 ) {
            $parent_category = get_category( $this_category->parent );
            echo get_category_parents($parent_category, TRUE, $delimiter );
        }

        echo $currentBefore . single_cat_title( '', false ) . $currentAfter;

    } elseif ( is_home() ) {

        echo $currentBefore . 'Blog' . $currentAfter;

    } elseif ( is_tax('product_cat') ) {

        echo $prepend;
        $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );

        $parents = array();
        $parent = $term->parent;
        while ( $parent ) {
            $parents[] = $parent;
            $new_parent = get_term_by( 'id', $parent, get_query_var( 'taxonomy' ) );
            $parent = $new_parent->parent;
        }

        if ( ! empty( $parents ) ) {
            $parents = array_reverse( $parents );
            foreach ( $parents as $parent ) {
                $item = get_term_by( 'id', $parent, get_query_var( 'taxonomy' ));
                echo '<a href="' . get_term_link( $item->slug, 'product_cat' ) . '">' . $item->name . '</a>' . $delimiter;
            }
        }

        $queried_object = $wp_query->get_queried_object();
        echo $currentBefore . $queried_object->name . $currentAfter;

    } elseif ( is_tax('product_tag') ) {

        $queried_object = $wp_query->get_queried_object();
        echo $prepend . $currentBefore . __('Products tagged “', 'limelight') . $queried_object->name . '”' . $currentAfter;

    } elseif ( is_search() ) {

        echo $currentBefore . __( 'Search results for “', 'limelight' ) . get_search_query() . '”' . $currentAfter;

    } elseif ( is_day() ) {

        echo '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a>' . $delimiter;
        echo '<a href="' . get_month_link(get_the_time('Y'),get_the_time('m')) . '">' . get_the_time('F') . '</a>' . $delimiter;
        echo $currentBefore . get_the_time('d') . $currentAfter;

    } elseif ( is_month() ) {

        echo '<a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a>' . $delimiter;
        echo $currentBefore . get_the_time('F') . $currentAfter;

    } elseif ( is_year() ) {

        echo $currentBefore . get_the_time('Y') . $currentAfter;

    } elseif ( is_post_type_archive('product') && get_option('page_on_front') !== woocommerce_get_page_id('shop') ) {

        $_name = woocommerce_get_page_id( 'shop' ) ? get_the_title( woocommerce_get_page_id( 'shop' ) ) : ucwords( get_option( 'woocommerce_shop_slug' ) );

        if ( is_paged() ) {

            echo $currentBefore . '<a href="' . get_post_type_archive_link('product') . '">' . $_name . '</a>' . $currentAfter;

        } else {

            echo $currentBefore . $_name . $currentAfter;

        }

    } elseif ( is_single() && !is_attachment() ) { // *****************************************************************************************************************

        if ( get_post_type() == 'product' ) {

            echo $prepend;

            if ( $terms = wp_get_object_terms( $post->ID, 'product_cat' ) ) {
                $term = current( $terms );
                $parents = array();
                $parent = $term->parent;

                while ( $parent ) {
                    $parents[] = $parent;
                    $new_parent = get_term_by( 'id', $parent, 'product_cat' );
                    $parent = $new_parent->parent;
                }

                if ( ! empty( $parents ) ) {
                    $parents = array_reverse($parents);
                    foreach ( $parents as $parent ) {
                        $item = get_term_by( 'id', $parent, 'product_cat');
                        echo '<a href="' . get_term_link( $item->slug, 'product_cat' ) . '">' . $item->name . '</a>' . $delimiter;
                    }
                }

                echo '<a href="' . get_term_link( $term->slug, 'product_cat' ) . '">' . $term->name . '</a>' . $delimiter;

            }

            echo $currentBefore . get_the_title();

        } elseif ( get_post_type() != 'post' ) {

            $post_type = get_post_type_object( get_post_type() );
            $slug = $post_type->rewrite;
                echo $currentBefore . '<a href="' . get_post_type_archive_link( get_post_type() ) . '">' . $post_type->labels->singular_name . '</a>' . $currentAfter . $delimiter;
            echo $currentBefore . get_the_title() . $currentAfter;

        } else {

            $cat = current( get_the_category() );
            echo '<a href="http://localhost/optikinetics/blog/">BLOG</a>' .$delimiter;
            echo $currentBefore . get_the_title() . $currentAfter;

        }

    } elseif ( is_404() ) {

        echo $currentBefore . __( 'Error 404', 'limelight' ) . $currentAfter;

    } elseif ( ! is_single() && ! is_page() && get_post_type() != 'post' ) {

        $post_type = get_post_type_object( get_post_type() );

        if ( $post_type )
            echo $currentBefore . $post_type->labels->singular_name . $currentAfter;

    } elseif ( is_attachment() ) {

        $parent = get_post( $post->post_parent );
        $cat = get_the_category( $parent->ID );
        $cat = $cat[0];
        echo get_category_parents( $cat, true, '' . $delimiter );
        echo $currentBefore . '<a href="' . get_permalink( $parent ) . '">' . $parent->post_title . '</a>' . $currentAfter . $delimiter;
        echo $currentBefore . get_the_title() . $currentAfter;

    } elseif ( is_page() && !$post->post_parent ) {

        echo $currentBefore . get_the_title() . $currentAfter;

    } elseif ( is_page() && $post->post_parent ) {

        $parent_id  = $post->post_parent;
        $breadcrumbs = array();

        while ( $parent_id ) {
            $page = get_page( $parent_id );
            $breadcrumbs[] = '<a href="' . get_permalink($page->ID) . '">' . get_the_title( $page->ID ) . '</a>';
            $parent_id  = $page->post_parent;
        }

        $breadcrumbs = array_reverse( $breadcrumbs );

        foreach ( $breadcrumbs as $crumb )
            echo $crumb . '' . $delimiter;

        echo $currentBefore . get_the_title() . $currentAfter;

    } elseif ( is_tag() ) {

            echo $currentBefore . __( 'Posts tagged “', 'limelight' ) . single_tag_title('', false) . '”' . $currentAfter;

    } elseif ( is_author() ) {
                global $author;
        $userdata = get_userdata($author);
        echo $currentBefore . __( 'Author:', 'limelight' ) . ' ' . $userdata->display_name . $currentAfter;

    }

    if ( get_query_var( 'paged' ) )
        echo ' (' . __( 'Page', 'limelight' ) . ' ' . get_query_var( 'paged' ) . ')';

    echo $wrap_after;

}
}
</code>```

I can't seem to do anything on this and I don't know how.

答:
solved it by inserting pieces of code

```<code>    $taxonomy = 'product_cat'; //change to your taxonomy name

    // get the term IDs assigned to post.
    $post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
    // separator between links
    $separator = $delimiter;

    if ( !empty( $post_terms ) && !is_wp_error( $post_terms ) ) {

        $term_ids = implode( ',' , $post_terms );
    $terms = wp_list_categories( 'title_li=&style=none&echo=0&taxonomy=' . $taxonomy . '&include=' . $term_ids );
    $terms = rtrim( trim(  str_replace( '<br />',  $separator, $terms ) ), $separator );

    // display post categories
    echo  $terms . $delimiter;
    }
</code>```

so this will show all the categories related to the product, hope i am right... but works fine

Body:
I have here a code that works fine except for the woocommerce product page

for example:

Home > category1 > category2 > category3

but when I go to the product page it shows only like this

Home > category1 > product

I need it to show in the product page

Home > category1 > category2 > category3 > product

I think this is where to modify the code
( if ( get_post_type() == 'product' ) {} )

Here is the code below:

function limelight_breadcrumbs()
{
global $post, $wp_query;
if ( ! $home ) $home = __( 'Home', 'limelight' );
$home_link = home_url();
$delimiter = ' » ';
$currentBefore = '';
$currentAfter = '';
$wrap_before = ' ';
$wrap_after = ' ';

if ( get_option('woocommerce_prepend_shop_page_to_urls') == "yes" && woocommerce_get_page_id( 'shop' ) &&   get_option( 'page_on_front' ) !== woocommerce_get_page_id( 'shop' ) )
$prepend = '' . get_the_title( woocommerce_get_page_id('shop') ) . ' ' . $delimiter;
else $prepend = '';

if ( ( ! is_front_page() && ! ( is_post_type_archive() && get_option( 'page_on_front' ) == woocommerce_get_page_id( 'shop' ) ) ) || is_paged() ) {

    echo $wrap_before . '' . $home . ' ' . $delimiter ;

    if ( is_category() ) {

        $cat_obj = $wp_query->get_queried_object();
        $this_category = get_category( $cat_obj->term_id );

        if ( $this_category->parent != 0 ) {
            $parent_category = get_category( $this_category->parent );
            echo get_category_parents($parent_category, TRUE, $delimiter );
        }

        echo $currentBefore . single_cat_title( '', false ) . $currentAfter;

    } elseif ( is_home() ) {

        echo $currentBefore . 'Blog' . $currentAfter;

    } elseif ( is_tax('product_cat') ) {

        echo $prepend;
        $term = get_term_by( 'slug', get_query_var( 'term' ), get_query_var( 'taxonomy' ) );

        $parents = array();
        $parent = $term->parent;
        while ( $parent ) {
            $parents[] = $parent;
            $new_parent = get_term_by( 'id', $parent, get_query_var( 'taxonomy' ) );
            $parent = $new_parent->parent;
        }

        if ( ! empty( $parents ) ) {
            $parents = array_reverse( $parents );
            foreach ( $parents as $parent ) {
                $item = get_term_by( 'id', $parent, get_query_var( 'taxonomy' ));
                echo 'slug, 'product_cat' ) . '">' . $item->name . '' . $delimiter;
            }
        }

        $queried_object = $wp_query->get_queried_object();
        echo $currentBefore . $queried_object->name . $currentAfter;

    } elseif ( is_tax('product_tag') ) {

        $queried_object = $wp_query->get_queried_object();
        echo $prepend . $currentBefore . __('Products tagged “', 'limelight') . $queried_object->name . '”' . $currentAfter;

    } elseif ( is_search() ) {

        echo $currentBefore . __( 'Search results for “', 'limelight' ) . get_search_query() . '”' . $currentAfter;

    } elseif ( is_day() ) {

        echo '' . get_the_time('Y') . '' . $delimiter;
        echo '' . get_the_time('F') . '' . $delimiter;
        echo $currentBefore . get_the_time('d') . $currentAfter;

    } elseif ( is_month() ) {

        echo '' . get_the_time('Y') . '' . $delimiter;
        echo $currentBefore . get_the_time('F') . $currentAfter;

    } elseif ( is_year() ) {

        echo $currentBefore . get_the_time('Y') . $currentAfter;

    } elseif ( is_post_type_archive('product') && get_option('page_on_front') !== woocommerce_get_page_id('shop') ) {

        $_name = woocommerce_get_page_id( 'shop' ) ? get_the_title( woocommerce_get_page_id( 'shop' ) ) : ucwords( get_option( 'woocommerce_shop_slug' ) );

        if ( is_paged() ) {

            echo $currentBefore . '' . $_name . '' . $currentAfter;

        } else {

            echo $currentBefore . $_name . $currentAfter;

        }

    } elseif ( is_single() && !is_attachment() ) { // *****************************************************************************************************************

        if ( get_post_type() == 'product' ) {

            echo $prepend;

            if ( $terms = wp_get_object_terms( $post->ID, 'product_cat' ) ) {
                $term = current( $terms );
                $parents = array();
                $parent = $term->parent;

                while ( $parent ) {
                    $parents[] = $parent;
                    $new_parent = get_term_by( 'id', $parent, 'product_cat' );
                    $parent = $new_parent->parent;
                }

                if ( ! empty( $parents ) ) {
                    $parents = array_reverse($parents);
                    foreach ( $parents as $parent ) {
                        $item = get_term_by( 'id', $parent, 'product_cat');
                        echo 'slug, 'product_cat' ) . '">' . $item->name . '' . $delimiter;
                    }
                }

                echo 'slug, 'product_cat' ) . '">' . $term->name . '' . $delimiter;

            }

            echo $currentBefore . get_the_title();

        } elseif ( get_post_type() != 'post' ) {

            $post_type = get_post_type_object( get_post_type() );
            $slug = $post_type->rewrite;
                echo $currentBefore . '' . $post_type->labels->singular_name . '' . $currentAfter . $delimiter;
            echo $currentBefore . get_the_title() . $currentAfter;

        } else {

            $cat = current( get_the_category() );
            echo 'BLOG' .$delimiter;
            echo $currentBefore . get_the_title() . $currentAfter;

        }

    } elseif ( is_404() ) {

        echo $currentBefore . __( 'Error 404', 'limelight' ) . $currentAfter;

    } elseif ( ! is_single() && ! is_page() && get_post_type() != 'post' ) {

        $post_type = get_post_type_object( get_post_type() );

        if ( $post_type )
            echo $currentBefore . $post_type->labels->singular_name . $currentAfter;

    } elseif ( is_attachment() ) {

        $parent = get_post( $post->post_parent );
        $cat = get_the_category( $parent->ID );
        $cat = $cat[0];
        echo get_category_parents( $cat, true, '' . $delimiter );
        echo $currentBefore . '' . $parent->post_title . '' . $currentAfter . $delimiter;
        echo $currentBefore . get_the_title() . $currentAfter;

    } elseif ( is_page() && !$post->post_parent ) {

        echo $currentBefore . get_the_title() . $currentAfter;

    } elseif ( is_page() && $post->post_parent ) {

        $parent_id  = $post->post_parent;
        $breadcrumbs = array();

        while ( $parent_id ) {
            $page = get_page( $parent_id );
            $breadcrumbs[] = 'ID) . '">' . get_the_title( $page->ID ) . '';
            $parent_id  = $page->post_parent;
        }

        $breadcrumbs = array_reverse( $breadcrumbs );

        foreach ( $breadcrumbs as $crumb )
            echo $crumb . '' . $delimiter;

        echo $currentBefore . get_the_title() . $currentAfter;

    } elseif ( is_tag() ) {

            echo $currentBefore . __( 'Posts tagged “', 'limelight' ) . single_tag_title('', false) . '”' . $currentAfter;

    } elseif ( is_author() ) {
                global $author;
        $userdata = get_userdata($author);
        echo $currentBefore . __( 'Author:', 'limelight' ) . ' ' . $userdata->display_name . $currentAfter;

    }

    if ( get_query_var( 'paged' ) )
        echo ' (' . __( 'Page', 'limelight' ) . ' ' . get_query_var( 'paged' ) . ')';

    echo $wrap_after;

}
}

I can't seem to do anything on this and I don't know how.

Body:
solved it by inserting pieces of code

    $taxonomy = 'product_cat'; //change to your taxonomy name

    // get the term IDs assigned to post.
    $post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
    // separator between links
    $separator = $delimiter;

    if ( !empty( $post_terms ) && !is_wp_error( $post_terms ) ) {

        $term_ids = implode( ',' , $post_terms );
    $terms = wp_list_categories( 'title_li=&style=none&echo=0&taxonomy=' . $taxonomy . '&include=' . $term_ids );
    $terms = rtrim( trim(  str_replace( '<br />',  $separator, $terms ) ), $separator );

    // display post categories
    echo  $terms . $delimiter;
    }

so this will show all the categories related to the product, hope i am right... but works fine


来源: stackexchange

问:
How to get results from PDF file to Android app?
I am working in a bank project where I have a lots of PDF files stored online containing information of user bank account where data is in the form of tables.
I want to create an app where a user can get his information on the app by just entering there bank account number.

My question is there any way to access the data through online without downloading those PDF files on my system.

答: Without downloading , your data will not be able to access, as you can see in other banking applications, first you need to bring that data into raw format or original text format, then you can easily access the data using a network call. </p>

ContentLicense: CC BY-SA 3.0


问:
Converting string with time to minutes
I am working on an Android app that gets a time (duration) value as string.

For example, the app can get a value like: 6 hours 43 mins

or a value like: 15 mins

I am looking for a way to convert this strings to an integer value in minutes.

I have tried using this function, but I can´t extract the needed values:

```<code>str = str.replaceAll("[^\\d.]", "");
</code>```

Edit:

it could be possible a result like 6 hours, the only known condition is that minutes are always rounded to an integer, the minimum value is 1 min

答:
Using a Regex to get each couple numeric/time_unit. You can easily parse that with :

```<code>(\\d+) (\\w+)
</code>```

Group 1 : numeric value

Group 2 : time unit

(note that I used a space between the two (could be optional if you want)

Using Java Pattern class to use that regex

```<code>    Pattern p = Pattern.compile("(\\d+) (\\w+)");
</code>```

Then you just have to iterate on each match to get the couple type/value

```<code>    Matcher m = p.matcher(s);
    while(m.find()){
        String type = m.group(2);
        int value = Integer.parseInt(m.group(1))
        ...
    }

</code>```

From that, just use a switch to convert the number into minute and add it to the variable, omitting the break to have a nice (but not efficient) converter :

```<code>switch(type){
//Add more time unit in the correct order if needed
case "days":
    value *= 24;
case "hours":
    value *= 60;
case "mins":
    mins += value;
    break;
}
</code>```

Each type will convert the value into a correct number of minute, at the end, you will have the result in minutes.

Title: Converting string with time to minutes

Body:
I am working on an Android app that gets a time (duration) value as string.

For example, the app can get a value like: 6 hours 43 mins

or a value like: 15 mins

I am looking for a way to convert this strings to an integer value in minutes.

I have tried using this function, but I can´t extract the needed values:

str = str.replaceAll("[^\\d.]", "");

Edit:

it could be possible a result like 6 hours, the only known condition is that minutes are always rounded to an integer, the minimum value is 1 min

Body:
Using a Regex to get each couple numeric/time_unit. You can easily parse that with :

(\\d+) (\\w+)

Group 1 : numeric value

Group 2 : time unit

(note that I used a space between the two (could be optional if you want)

Using Java Pattern class to use that regex

    Pattern p = Pattern.compile("(\\d+) (\\w+)");

Then you just have to iterate on each match to get the couple type/value

    Matcher m = p.matcher(s);
    while(m.find()){
        String type = m.group(2);
        int value = Integer.parseInt(m.group(1))
        ...
    }

From that, just use a switch to convert the number into minute and add it to the variable, omitting the break to have a nice (but not efficient) converter :

switch(type){
//Add more time unit in the correct order if needed
case "days":
    value *= 24;
case "hours":
    value *= 60;
case "mins":
    mins += value;
    break;
}

Each type will convert the value into a correct number of minute, at the end, you will have the result in minutes.


问:
Text field from Vuetify has no underline
I am trying to use vuetify's text field. It looks like this:

After applying focus it looks like this:

I have read this this, but my app IS wrapped in v-app. Is there anything else I could try?

HINT:
Dark theme doesn't work for me as well,but for example, I can use classes like "red", "text--red", to apply colors.

Proof, that there is v-app involved below:

EDIT:
I tried to wrap it with v-content as well, but it didn't help.

```<code><v-app>
  <v-content>
    <router-view></router-view>
  </v-content>
</v-app>
</code>```

答: unpkg.com links to the latest version of vuetify, which is currently 0.17.0. To use 0.16.9 css from unpkg you have to use this link: https://unpkg.com/vuetify@0.16.9/dist/vuetify.min.css

Body:
I am trying to use vuetify's text field. It looks like this:

After applying focus it looks like this:

I have read this this, but my app IS wrapped in v-app. Is there anything else I could try?

HINT:
Dark theme doesn't work for me as well,but for example, I can use classes like "red", "text--red", to apply colors.

Proof, that there is v-app involved below:

EDIT:
I tried to wrap it with v-content as well, but it didn't help.

<v-app>
  <v-content>
    <router-view></router-view>
  </v-content>
</v-app>


问:
Prevent multiple user registrations to game a referral system
I'm working on a free service web application where a user registers with username, email, password... standard user account stuff. There is a referral system where if the user refers three other users to sign up (using their referral code) the original user gets account upgrades.

There is incentive to game this by creating three other accounts using their referral code. Any ideas on how to prevent this? Could block IP or use a cookie but these seem like they are easily defeated. I want to make it easy for a user to create an account so I'd rather not do anything that requires extensive effort in account creation.

答: You could send them a text message and make them reply via text message or email from the mobile.</p>

ContentLicense: CC BY-SA 2.5


问:
How to set string resource length limit in Android?
It is known that Androd string resources support xliff namespace to annotate non-translatable string formatting placeholders, like this

```<code>    <string name="max_file_size_exceeded_template">File
         <xliff:g example="some_image.jpg" id="file_name">%1$s</xliff:g>
         is too big and could not be uploaded.</string>
</code>```

It helps translators to undestand what parts of string should not be modified. But sometimes I need to annotate some strings max length it they are used in UI control with limited size. What I want is add text length limit to warn translators about this. Something like max-length="24" max-lines="2" length-unit="char" Maybe, xliff supports such thing or it can be achieved in other way.
I use Weblate for translations if it matters.

答:
You can set this in Weblate, the Andoid format does not support this directly.

Click on edit (pencil) icon next to flags on the string.

Enter max-length:LENGTH as check flag.

See also https://docs.weblate.org/en/latest/admin/translating.html#additional-information-on-source-strings

Body:
It is known that Androd string resources support xliff namespace to annotate non-translatable string formatting placeholders, like this

    <string name="max_file_size_exceeded_template">File
         <xliff:g example="some_image.jpg" id="file_name">%1$s</xliff:g>
         is too big and could not be uploaded.</string>

It helps translators to undestand what parts of string should not be modified. But sometimes I need to annotate some strings max length it they are used in UI control with limited size. What I want is add text length limit to warn translators about this. Something like max-length="24" max-lines="2" length-unit="char" Maybe, xliff supports such thing or it can be achieved in other way.
I use Weblate for translations if it matters.


问:
Maven: Create distribution assembly containing site (multi module)
I'm creating a distribution assembly (with format "dir") for my multi module project using the maven-assembly-plugin. The project looks like this:

```<code>+ my-project
   +-- my-child-project-1
   +-- my-child-project-2
</code>```

The child projects inherit from my-project. my-project is an aggregation, i.e. defines the child project in the <modules>-section.

The assembly contains artifacts, sources, etc. How do I need to setup my project to include the site?

The my-project site's links to child-modules have to work. As far as I know the links won't work before deployment. Therefore, I guess I have to stage-deploy the site first (?). According to the docs, the staging is only possible after creating the site:

This goal requires the site to already have been generated using the site goal, such as by calling mvn site.

How can I achieve this?

Is there a way to get everything assembled with one single mvn package? How does my assembly-descriptior have to look like?

答:
I don't know, if this is a good solution, but there were no other answers, so I came up with this:

1. Move the assembly build into a separate child module

Important: I don't know if this is necessary, however I don't have the time to check whether it also works, if the assembly is configured in the root project. Otherwise you have to define a dependency in my-project to my-project itself with different classifier in step 2, and I think this won't work. Feel free to edit this answer, if I'm wrong.

```<code>+ my-project
   +-- my-child-project-1
   +-- my-child-project-2
   +-- my-project-build
</code>```

2. Define dependencies for all modules with classifier site in the build project

```<code><!-- Yes, also for the parent project. However, not for the build project itself -->
<dependency>
    <groupId>${project.groupId}</groupId>
    <artifactId>my-project</artifactId>
    <version>${project.version}</version>
    <classifier>site</version>
</dependency>
<dependency>
    <groupId>${project.groupId}</groupId>
    <artifactId>my-project</artifactId>
    <version>${project.version}</version>
    <classifier>site</version>
</dependency>
...
</code>```

3. Define dependencySets in the assembly descriptor. Fix broken links by moving sub module site content to respective sub-directories of the main module's site directory.

The idea is to use the site-jar artifacts generated due to the site-classifier dependencies and unpack them. The module links are relative, so unpacking the content into sub-directories named by their artifactIds will fix those links.

```<code><dependencySets>

    <dependencySet>
        <outputDirectory>site</outputDirectory>
        <useProjectArtifact>true</useProjectArtifact>
        <useProjectAttachments>true</useProjectAttachments>
        <unpack>true</unpack>
        <includes>
            <include>*:my-project:jar:site</include>
        </includes>
    </dependencySet>

    <!-- sites of sub modules -->
    <dependencySet>
        <includes>
            <include>*:my-child-project-1:jar:site</include>
            <include>*:my-child-project-2:jar:site</include>
            <include>*:my-project-build:jar:site</include>
        </includes>
        <outputDirectory>site/${artifact.artifactId}</outputDirectory>
        <useProjectArtifact>true</useProjectArtifact>
        <useProjectAttachments>true</useProjectAttachments>
        <unpack>true</unpack>
    </dependencySet>

    <!-- sites of sub-sub modules (if required) -->
    <dependencySet>
        <includes>
            ...
        </includes>
        <outputDirectory>site/${artifact.parent.artifactId}/${artifact.artifactId}</outputDirectory>
        <useProjectArtifact>true</useProjectArtifact>
        <useProjectAttachments>true</useProjectAttachments>
        <unpack>true</unpack>
    </dependencySet>

    ...
</dependencySets>
</code>```

4. Define the site:jar goal in the root project

This goal is by default executed in the package phase and generates the "site"-attachments (e.g. my-parent-1.0.0-site.jar), which are defined as dependencies in step 2 and unpacked in step 3:

```<code><build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-site-plugin</artifactId>
            <version>3.4</version>
            <executions>
                <execution>
                    <goals>
                        <goal>jar</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
</code>```

5. Run mvn package to generate your assembly

The result is a sub-directory "site" in your assembly containing the complete site with working links.

Body:
I'm creating a distribution assembly (with format "dir") for my multi module project using the maven-assembly-plugin. The project looks like this:

+ my-project
   +-- my-child-project-1
   +-- my-child-project-2

The child projects inherit from my-project. my-project is an aggregation, i.e. defines the child project in the <modules>-section.

The assembly contains artifacts, sources, etc. How do I need to setup my project to include the site?

The my-project site's links to child-modules have to work. As far as I know the links won't work before deployment. Therefore, I guess I have to stage-deploy the site first (?). According to the docs, the staging is only possible after creating the site:

This goal requires the site to already have been generated using the site goal, such as by calling mvn site.

How can I achieve this?

Is there a way to get everything assembled with one single mvn package? How does my assembly-descriptior have to look like?

Body:
I don't know, if this is a good solution, but there were no other answers, so I came up with this:

1. Move the assembly build into a separate child module

Important: I don't know if this is necessary, however I don't have the time to check whether it also works, if the assembly is configured in the root project. Otherwise you have to define a dependency in my-project to my-project itself with different classifier in step 2, and I think this won't work. Feel free to edit this answer, if I'm wrong.

+ my-project
   +-- my-child-project-1
   +-- my-child-project-2
   +-- my-project-build

2. Define dependencies for all modules with classifier site in the build project

<!-- Yes, also for the parent project. However, not for the build project itself -->
<dependency>
    <groupId>${project.groupId}</groupId>
    <artifactId>my-project</artifactId>
    <version>${project.version}</version>
    <classifier>site</version>
</dependency>
<dependency>
    <groupId>${project.groupId}</groupId>
    <artifactId>my-project</artifactId>
    <version>${project.version}</version>
    <classifier>site</version>
</dependency>
...

3. Define dependencySets in the assembly descriptor. Fix broken links by moving sub module site content to respective sub-directories of the main module's site directory.

The idea is to use the site-jar artifacts generated due to the site-classifier dependencies and unpack them. The module links are relative, so unpacking the content into sub-directories named by their artifactIds will fix those links.

<dependencySets>

    <dependencySet>
        <outputDirectory>site</outputDirectory>
        <useProjectArtifact>true</useProjectArtifact>
        <useProjectAttachments>true</useProjectAttachments>
        <unpack>true</unpack>
        <includes>
            <include>*:my-project:jar:site</include>
        </includes>
    </dependencySet>

    <!-- sites of sub modules -->
    <dependencySet>
        <includes>
            <include>*:my-child-project-1:jar:site</include>
            <include>*:my-child-project-2:jar:site</include>
            <include>*:my-project-build:jar:site</include>
        </includes>
        <outputDirectory>site/${artifact.artifactId}</outputDirectory>
        <useProjectArtifact>true</useProjectArtifact>
        <useProjectAttachments>true</useProjectAttachments>
        <unpack>true</unpack>
    </dependencySet>

    <!-- sites of sub-sub modules (if required) -->
    <dependencySet>
        <includes>
            ...
        </includes>
        <outputDirectory>site/${artifact.parent.artifactId}/${artifact.artifactId}</outputDirectory>
        <useProjectArtifact>true</useProjectArtifact>
        <useProjectAttachments>true</useProjectAttachments>
        <unpack>true</unpack>
    </dependencySet>

    ...
</dependencySets>

4. Define the site:jar goal in the root project

This goal is by default executed in the package phase and generates the "site"-attachments (e.g. my-parent-1.0.0-site.jar), which are defined as dependencies in step 2 and unpacked in step 3:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-site-plugin</artifactId>
            <version>3.4</version>
            <executions>
                <execution>
                    <goals>
                        <goal>jar</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

5. Run mvn package to generate your assembly

The result is a sub-directory "site" in your assembly containing the complete site with working links.


问:
Binding List of user controls to flipview?
I am planning to implement horizontal list of user controls, which i want to add it to the flip view during runtime, I tried the following code:

```<code><FlipView Grid.Row="2" Name="SlideFlipView"
              ItemsSource="{x:Bind SlideViews}"
              SelectionChanged="SlideFlipView_SelectionChanged"
              Background="AliceBlue">
        <FlipView.ItemTemplate>
            <DataTemplate>
                <Frame Name="MenuDetailFrame" SourcePageType="{Binding}"/>
            </DataTemplate>
        </FlipView.ItemTemplate>
</FlipView>
</code>```

Class looks like the following code:

```<code> public sealed partial class MenuDetailPage : Page
 {
    private List<object> SlideViews;

    public MenuDetailPage()
    {
        this.InitializeComponent();
        LoadInitials();
    }

    private void LoadInitials()
    {
        SlideViews = new List<object>
        {
            typeof(TopImageBottomTextControl),
            typeof(TopTextBottomImageControl)
        };
    }
 }
</code>```

but the user control doesn't appear in the flip when I run the program. Let me know if I am missing something here

答:
following code without datatemplate worked for me:

```<code><FlipView Grid.Row="2"
          Name="SlideFlipView"
          ItemsSource="{x:Bind SlideViews}"
          SelectionChanged="SlideFlipView_SelectionChanged"
          Background="AliceBlue">
</FlipView>
</code>```

initialization of slideviews object in Class looks like

```<code>private void LoadInitials()
{
  SlideViews = new List<object>
  {
    new UserControl1(),
    new UserControl2()
  };
}
</code>```

Body:
I am planning to implement horizontal list of user controls, which i want to add it to the flip view during runtime, I tried the following code:

<FlipView Grid.Row="2" Name="SlideFlipView"
              ItemsSource="{x:Bind SlideViews}"
              SelectionChanged="SlideFlipView_SelectionChanged"
              Background="AliceBlue">
        <FlipView.ItemTemplate>
            <DataTemplate>
                <Frame Name="MenuDetailFrame" SourcePageType="{Binding}"/>
            </DataTemplate>
        </FlipView.ItemTemplate>
</FlipView>

Class looks like the following code:

 public sealed partial class MenuDetailPage : Page
 {
    private List<object> SlideViews;

    public MenuDetailPage()
    {
        this.InitializeComponent();
        LoadInitials();
    }

    private void LoadInitials()
    {
        SlideViews = new List<object>
        {
            typeof(TopImageBottomTextControl),
            typeof(TopTextBottomImageControl)
        };
    }
 }

but the user control doesn't appear in the flip when I run the program. Let me know if I am missing something here

Body:
following code without datatemplate worked for me:

<FlipView Grid.Row="2"
          Name="SlideFlipView"
          ItemsSource="{x:Bind SlideViews}"
          SelectionChanged="SlideFlipView_SelectionChanged"
          Background="AliceBlue">
</FlipView>

initialization of slideviews object in Class looks like

private void LoadInitials()
{
  SlideViews = new List<object>
  {
    new UserControl1(),
    new UserControl2()
  };
}


问:
Want to change application icon when desktop size Changed
I Want to change application icon when desktop size Changed.Please see the picture i want to update my application icon whenever user change size. Currently i am using 256*256 icon when ever user change size it become blurred.</p>

答:
get parent window size using an event handler.

```<code>Rectangle resolution = Screen.PrimaryScreen.Bounds;
</code>```

Then set the icon according to the parent window size

```<code>If(resolution> "expected size")
{
 ico = ico_small;
}
</code>```

Body:
get parent window size using an event handler.

Rectangle resolution = Screen.PrimaryScreen.Bounds;

Then set the icon according to the parent window size

If(resolution> "expected size")
{
 ico = ico_small;
}


问:
Scanf in functions repeats input request twice
```<code>//Main Function of Calculator Project
int main (void)
{
        int input, result, result1, result2, result3, result4;

        printf ("===================================\n");
        printf ( "WELCOME TO THE CALCULATOR PROJECT\n");
        printf ("===================================\n\n");

        printf ("Option 1. ADDITION\n");
        printf ("Option 2. SUBTRACTION\n");
        printf ("Option 3. MULTIPLICATION\n");
        printf ("Option 4. DIVISION\n\n");

        printf ("Enter Option:>> ");
        scanf  ("%d", &input);

        switch (input)
        {
                case 1:
                        addition(result1);
                        printf ("Result: %d\n", addition(result1));
                        break;
                case 2:
                        subtraction(result2);
                        printf ("Result: %d\n", subtraction(result2));
                        break;
                case 3:
                        multiplication(result3);
                        printf ("Result: %d\n", multiplication(result3));
                        break;
                case 4:
                        division(result4);
                        printf ("Result: %d\n", division(result1));
                        break;
                default:
                        printf ("Invalid Input\n");
 }
           return 0;

}
</code>```

When ever the program runs it return the correct calculations however always asks for the input twice no matter what user function runs.

答:
You're calling the functions that ask for input and perform the calculation twice:

```<code>case 1:
    addition(result1); // You first call it here
    printf ("Result: %d\n", addition(result1)); // You call it again here
    break;
</code>```

You're also passing an uninitialized variable as the argument. That variable should be used to hold the return value, not as an argument.

So you call it once, assign the result to a variable, then print that variable.

```<code>int result = -1;
case 1:
    result = addition();
    break;
case 2:
    result = subtraction();
    break;
case 3:
    result = multiplication();
    break;
case 4:
    result = division();
    break;
default:
    printf("Invalid input\n");
}
printf("Result: %d\n", result);
</code>```

Body:
//Main Function of Calculator Project
int main (void)
{
        int input, result, result1, result2, result3, result4;

        printf ("===================================\n");
        printf ( "WELCOME TO THE CALCULATOR PROJECT\n");
        printf ("===================================\n\n");

        printf ("Option 1. ADDITION\n");
        printf ("Option 2. SUBTRACTION\n");
        printf ("Option 3. MULTIPLICATION\n");
        printf ("Option 4. DIVISION\n\n");

        printf ("Enter Option:>> ");
        scanf  ("%d", &input);

        switch (input)
        {
                case 1:
                        addition(result1);
                        printf ("Result: %d\n", addition(result1));
                        break;
                case 2:
                        subtraction(result2);
                        printf ("Result: %d\n", subtraction(result2));
                        break;
                case 3:
                        multiplication(result3);
                        printf ("Result: %d\n", multiplication(result3));
                        break;
                case 4:
                        division(result4);
                        printf ("Result: %d\n", division(result1));
                        break;
                default:
                        printf ("Invalid Input\n");
 }
           return 0;

}

When ever the program runs it return the correct calculations however always asks for the input twice no matter what user function runs.

Body:
You're calling the functions that ask for input and perform the calculation twice:

case 1:
    addition(result1); // You first call it here
    printf ("Result: %d\n", addition(result1)); // You call it again here
    break;

You're also passing an uninitialized variable as the argument. That variable should be used to hold the return value, not as an argument.

So you call it once, assign the result to a variable, then print that variable.

int result = -1;
case 1:
    result = addition();
    break;
case 2:
    result = subtraction();
    break;
case 3:
    result = multiplication();
    break;
case 4:
    result = division();
    break;
default:
    printf("Invalid input\n");
}
printf("Result: %d\n", result);


问:
Out of Memory exception while wrting 300dpi Images
I have a requirement that to create a image with 300DPI, but during the composition of image, like addding the resources (font, images) I am getting out of memory exception.

```<code>using (Bitmap pg = new Bitmap(GetPixelsFromInches(float.Parse(pageWidth), dpi, actualDpi), GetPixelsFromInches(float.Parse(pageHeight), dpi, actualDpi)))
{
    pg.SetResolution(float.Parse(dpi), float.Parse(dpi));

    Graphics gr = Graphics.FromImage(pg);
    gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

    System.Drawing.Rectangle pgRect = new System.Drawing.Rectangle(0, 0, pg.Width, pg.Height);
    SolidBrush solidWhite = new SolidBrush(Color.White);
    gr.FillRectangle(solidWhite, pgRect);

    currentPageDisplayed = xNode.Attributes["id"].Value;

    foreach (XmlElement xElement in xNode)
    {
        //Here I am writing each elements, like texts or images.
        DrawImageForElements(xElement, , dpi, actualDpi);

    }

    MemoryStream myMemoryStream = new MemoryStream();
    //pg.Save(myMemoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
    String filename=@"c:\images\" + currentPageDisplayed + "+.png";
    pg.Save(filename, System.Drawing.Imaging.ImageFormat.Png);

    myMemoryStream.Dispose();
    gr.Dispose();
    pg.Dispose();
}
</code>```

Please suggest if there is any other better option!!

答:
There are two basic options here that I see.

Get a wider architecture.  You'll probably need to do this on an x64 machine with plenty of swap space.  A 24-bit pixmap of those dimensions would take up 300 × 300 × 12 × 12 × 11 × 15 × 3 = 6,415,200,000 bytes of memory, which is within reason on an x64 machine, but larger than the virtual memory space an x86 is capable of addressing.

Banding or tiling.  Create a series of smaller pixmaps, one at a time, each corresponding to some subsection of the image and render that portion.  (Banding would imply strips from one side of the image to the other, while tiling chops along both dimensions.)  I'm not entirely sure how you'd go about stitching those pieces together given the tools in the System.Drawing.** toolbox, though.

Body:
I have a requirement that to create a image with 300DPI, but during the composition of image, like addding the resources (font, images) I am getting out of memory exception.

using (Bitmap pg = new Bitmap(GetPixelsFromInches(float.Parse(pageWidth), dpi, actualDpi), GetPixelsFromInches(float.Parse(pageHeight), dpi, actualDpi)))
{
    pg.SetResolution(float.Parse(dpi), float.Parse(dpi));

    Graphics gr = Graphics.FromImage(pg);
    gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;

    System.Drawing.Rectangle pgRect = new System.Drawing.Rectangle(0, 0, pg.Width, pg.Height);
    SolidBrush solidWhite = new SolidBrush(Color.White);
    gr.FillRectangle(solidWhite, pgRect);

    currentPageDisplayed = xNode.Attributes["id"].Value;

    foreach (XmlElement xElement in xNode)
    {
        //Here I am writing each elements, like texts or images.
        DrawImageForElements(xElement, , dpi, actualDpi);

    }

    MemoryStream myMemoryStream = new MemoryStream();
    //pg.Save(myMemoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
    String filename=@"c:\images\" + currentPageDisplayed + "+.png";
    pg.Save(filename, System.Drawing.Imaging.ImageFormat.Png);

    myMemoryStream.Dispose();
    gr.Dispose();
    pg.Dispose();
}

Please suggest if there is any other better option!!


问:
Adding seconds to timestamp in python
I have tons of timestamp strings like this one 2017-04-18 05:03:40.966084 and the script needs to add seconds to the timestamp. I have been trying to turn the string into a legit timestamp object and then add seconds to it with timedelta but for some reason it isn't working.

This is what I have so far:

```<code>duration = "150.100"
timestamp = datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S.%f")
timestamp_e = timestamp+timedelta(seconds=duration)
</code>```

Am I going at this the right way?

答:
Yes timedelta is a good way to adjust a timestamp. However note that your duration variable is a string. As per the documentation it should be an integer or float:

All arguments are optional and default to 0. Arguments may be integers or floats, and may be positive or negative.

Title: Adding seconds to timestamp in python

Body:
I have tons of timestamp strings like this one 2017-04-18 05:03:40.966084 and the script needs to add seconds to the timestamp. I have been trying to turn the string into a legit timestamp object and then add seconds to it with timedelta but for some reason it isn't working.

This is what I have so far:

duration = "150.100"
timestamp = datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S.%f")
timestamp_e = timestamp+timedelta(seconds=duration)

Am I going at this the right way?


问:
Javascript - URL Detection in other instance of IE Browser window
I am using the below code for URL Detection if it is already opened in any of the browser window or tab and i have achieved it so far but failing in one instance i.e., if the url is already opened in other window and then if i launch the application in another window of IE then it should not launch as one instance is already opened and the already opened instance should be set to focus....

please guide me.....

```<code>var memberURL = document.URL;
var newWindowCopy = document.URL;
var winBrowser = window.clientInformation.appName;
var stringText = window.clientInformation.userAgent.toString();
var localVariable = "IamAliveInLocalStorage";

if (winBrowser == "Microsoft Internet Explorer" || stringText.indexOf('MSIE') >= 0) {
    if (localStorage.getItem("MyStorage") == localVariable) {
            open(memberURL, newWindowCopy).close();
    }
    else {
        localStorage.setItem("MyStorage", localVariable);
        window.onbeforeunload = function () {
            localStorage.removeItem("MyStorage");
            localStorage.clear();
        };
    }
}
else { }
</code>```

答:
There is no direct way to focus a window or tab of which you are not having a reference i.e only the child windows your page opens can be focused with window.focus() method.

But there is a trick which you can use i.e alert() fetches the focus to its window.

So on your page you can add a check

```<code>function focusOnOpenedTab() {
    var temp = localStorage.getItem('focusOnTab');
    localStorage.setItem('focusOnTab',JSON.stringify(~~temp+1));
}
if(// page is open in any window){
    focusOnOpenedTab()
} else {
    window.addEventListener("storage", message_receive);

    function message_receive(ev) {
        if (ev.key == 'focusOnTab') {
            var message=JSON.parse(ev.newValue);
            alert('focused');
        }
    }
}
</code>```

Your page will get focused and get an alert with message focused.

Body:
I am using the below code for URL Detection if it is already opened in any of the browser window or tab and i have achieved it so far but failing in one instance i.e., if the url is already opened in other window and then if i launch the application in another window of IE then it should not launch as one instance is already opened and the already opened instance should be set to focus....

please guide me.....

var memberURL = document.URL;
var newWindowCopy = document.URL;
var winBrowser = window.clientInformation.appName;
var stringText = window.clientInformation.userAgent.toString();
var localVariable = "IamAliveInLocalStorage";

if (winBrowser == "Microsoft Internet Explorer" || stringText.indexOf('MSIE') >= 0) {
    if (localStorage.getItem("MyStorage") == localVariable) {
            open(memberURL, newWindowCopy).close();
    }
    else {
        localStorage.setItem("MyStorage", localVariable);
        window.onbeforeunload = function () {
            localStorage.removeItem("MyStorage");
            localStorage.clear();
        };
    }
}
else { }

Body:
There is no direct way to focus a window or tab of which you are not having a reference i.e only the child windows your page opens can be focused with window.focus() method.

But there is a trick which you can use i.e alert() fetches the focus to its window.

So on your page you can add a check

function focusOnOpenedTab() {
    var temp = localStorage.getItem('focusOnTab');
    localStorage.setItem('focusOnTab',JSON.stringify(~~temp+1));
}
if(// page is open in any window){
    focusOnOpenedTab()
} else {
    window.addEventListener("storage", message_receive);

    function message_receive(ev) {
        if (ev.key == 'focusOnTab') {
            var message=JSON.parse(ev.newValue);
            alert('focused');
        }
    }
}

Your page will get focused and get an alert with message focused.


问:
Bootstrap Tab won't switch
I have two tabs in my sidebar at the right: http://www.futurebusinesscouncil.com/join-3/

Below the search you can see "Popular" and "Recent". I want to swtich that to Popular. Normally it should work with this code:

jQuery('#tabs a[href="#tab-popular"]').tab('show');

But sadly, it isn't switching the tab. Just the color is changing like it is active. But it isn't... Where is my failure?

Kind regards

答:
Use these lines of code</p>

```<code>jQuery('#tabs a[href="#tab-recent"]').parent().removeClass("active")
jQuery('#tabs a[href="#tab-popular"]').parent().addClass("active")
</code>```

Title: Bootstrap Tab won't switch

Body:
Use these lines of code

jQuery('#tabs a[href="#tab-recent"]').parent().removeClass("active")
jQuery('#tabs a[href="#tab-popular"]').parent().addClass("active")


问:
Generating gradients programmatically?
Given 2 rgb colors and a rectangular area, I'd like to generate a basic linear gradient between the colors. I've done a quick search and the only thing I've been able to find is this blog entry, but the example code seems to be missing, or at least it was as of this posting. Anything helps, algorithms, code examples, whatever. This will be written in Java, but the display layer is already taken care of, I just need to figure out how to figure out what to display.</p>

答:
Following up on the execllent answer of David Crow, here's a Kotlin example implementation</p>

```<code>fun gradientColor(x: Double, minX: Double, maxX: Double,
                  from: Color = Color.RED, to: Color = Color.GREEN): Color {
    val range = maxX - minX
    val p = (x - minX) / range

   return Color(
        from.red * p + to.red * (1 - p),
        from.green * p + to.green * (1 - p),
        from.blue * p + to.blue * (1 - p),
        1.0
    )
}
</code>```

OwnerDisplayName: Paul Wicks

Title: Generating gradients programmatically?

Body:
Following up on the execllent answer of David Crow, here's a Kotlin example implementation

fun gradientColor(x: Double, minX: Double, maxX: Double,
                  from: Color = Color.RED, to: Color = Color.GREEN): Color {
    val range = maxX - minX
    val p = (x - minX) / range

   return Color(
        from.red * p + to.red * (1 - p),
        from.green * p + to.green * (1 - p),
        from.blue * p + to.blue * (1 - p),
        1.0
    )
}


问:
declare a view height dynamically
my xml is below in xml we have declare a view height how we declare view height in dynamically.

```<code>    </TableRow>
    <View android:layout_height="1dip" android:background="#FF909090" />
</code>```

答:
You would need to give you view and android:id field like

```<code></TableRow>
<View android:id="@+id/someidvalue"
  android:layout_height="1dip"
  android:background="#FF909090" />
</code>```

Then, in your activity, you'll need to use the method .

```<code>View myView = (View)findViewById(R.id.someidvalue)
</code>```

Then use either setMinimumHeight (which I think may be what you are looking for) or setLayoutParams to modify how your View is displayed

```<code>myView.setMinimumHeight(height)
myView.setLayoutParams(new ViewGroup.LayoutParam(width, height))
</code>```

where height and width some values you'd like the view to have for height and width

Title: declare a view height dynamically

Body:
my xml is below in xml we have declare a view height how we declare view height in dynamically.

    </TableRow>
    <View android:layout_height="1dip" android:background="#FF909090" />

Body:
You would need to give you view and android:id field like

</TableRow>
<View android:id="@+id/someidvalue"
  android:layout_height="1dip"
  android:background="#FF909090" />

Then, in your activity, you'll need to use the method .

View myView = (View)findViewById(R.id.someidvalue)

Then use either setMinimumHeight (which I think may be what you are looking for) or setLayoutParams to modify how your View is displayed

myView.setMinimumHeight(height)
myView.setLayoutParams(new ViewGroup.LayoutParam(width, height))

where height and width some values you'd like the view to have for height and width


问:
day instead of month is saved in db when updating cell in gridview in webforms
When I try to save the new value in a gridview's cell (it is asp.net - webforms) - the date - it is saved in a wrong way - day is set to month and month is set to day in databae after updating.
This is a the line of binding the field in gridview:

```<code><asp:BoundField HeaderText="Date" DataField="AcDate" DataFormatString="{0:dd-MM-yyyy HH:mm:ss}" ApplyFormatInEditMode="true" htmlencode="False" SortExpression="AcDate" />
</code>```

For example there was 05-04-2013 17:00:00 before updating. After updating (without making any changes manually - just entering the edit mode and saving after that) - 04-05-2013 17:00:00
What is the problem?

答:
I solved the problem adding to aspx page first line parameters of culture:</p>

```<code><%@ Page Language="C#" AutoEventWireup="true" .......... Culture="ru-RU" UICulture="ru-RU"
</code>```

Body:
When I try to save the new value in a gridview's cell (it is asp.net - webforms) - the date - it is saved in a wrong way - day is set to month and month is set to day in databae after updating.
This is a the line of binding the field in gridview:

<asp:BoundField HeaderText="Date" DataField="AcDate" DataFormatString="{0:dd-MM-yyyy HH:mm:ss}" ApplyFormatInEditMode="true" htmlencode="False" SortExpression="AcDate" />

For example there was 05-04-2013 17:00:00 before updating. After updating (without making any changes manually - just entering the edit mode and saving after that) - 04-05-2013 17:00:00
What is the problem?

Body:
I solved the problem adding to aspx page first line parameters of culture:

<%@ Page Language="C#" AutoEventWireup="true" .......... Culture="ru-RU" UICulture="ru-RU"


问:
.Net Core 2.0 default template - overriding bootstrap
I created a default web project (ASP.NET Core Web Application, Web Application Model-View-Controller, ASP.NET Core 2.0) using VS 2017 version 15.0.26929.2.

I want to override the background color for the bootstrap pills as shown here:
Changing color of Twitter bootstrap Nav-Pills

Markup

```<code><ul class="nav nav-pills red">
  <li class="active"><a href="#tab1" data-toggle="tab">Overview</a></li>
  <li><a href="#tab2" data-toggle="tab">Sample</a></li>
  <li><a href="#tab3" data-toggle="tab">Sample</a></li>
</ul>
</code>```

CSS

```<code>.red .active a,
.red .active a:hover {
    background-color: red;
}
</code>```

I added the markup to the index.cshtml view and the css to site.css file.

When I use Firebug to detect why the style changes are not applied I see that the bootstrap.css file is downloaded twice. Once before the site.css and again after.

Why is bootstrap.css downloaded again ?

Please note that I have not have any other changes to this project.

答:
It's not loaded twice. The status code 304 is telling the client that it is about to recieve a bootrap file that is not modified, meaning if it already has a cached one it don't need to load it. The 200 says that it has loaded a file.

You can solve the design by either changing the bootrap files themselves, or you could mark your css code with !important like:

```<code>.red .active a:hover {
background-color: red !important;
</code>```

}

just load it after your bootrap css file.

Body:
I created a default web project (ASP.NET Core Web Application, Web Application Model-View-Controller, ASP.NET Core 2.0) using VS 2017 version 15.0.26929.2.

I want to override the background color for the bootstrap pills as shown here:
Changing color of Twitter bootstrap Nav-Pills

Markup

Overview

Sample

Sample

CSS

.red .active a,
.red .active a:hover {
    background-color: red;
}

I added the markup to the index.cshtml view and the css to site.css file.

When I use Firebug to detect why the style changes are not applied I see that the bootstrap.css file is downloaded twice. Once before the site.css and again after.

Why is bootstrap.css downloaded again ?

Please note that I have not have any other changes to this project.

Body:
It's not loaded twice. The status code 304 is telling the client that it is about to recieve a bootrap file that is not modified, meaning if it already has a cached one it don't need to load it. The 200 says that it has loaded a file.

You can solve the design by either changing the bootrap files themselves, or you could mark your css code with !important like:

.red .active a:hover {
background-color: red !important;

}

just load it after your bootrap css file.


问:
How to connect Ionic App with SQL Server 2012 database?
I have website with SQL Server database, and now I want to create ionic mobile app using same database. Can anyone guide me how to connect Ionic app with SQL Server?</p>

答:
First of all you need to create a connection that you Ionic App can communicate with your Website.

That is Called an API. If we dont use any big tech Words to explain this. The Common practice is build a REST-API first.

Its a Link, and when you goto the link, the link will give you data in a Format JSON or XML. So your App can Parse the JSON/XML Data and display in your Ionic App.

Example.

```<code>www.yourwebsite.com/getusers
www.yourwebsite.com/adduser
</code>```

you will call the first link from your App in GET protocol and this will give u a list of users in JSON Format.

you will call the second link from your App in POST protocol with User Parameters and this will add a user and Will give you Success or Error Json/XML Response.

So first you need to learn a bit about REST-API and how to build them. You can build them in any language.

REST API FOR BEGINNERS

Then plan which language is the best for you and follow up a good tutorial.

And Finally follow this on how to call an API from IONIC CALL API FROM IONIC

Body:
First of all you need to create a connection that you Ionic App can communicate with your Website.

That is Called an API. If we dont use any big tech Words to explain this. The Common practice is build a REST-API first.

Its a Link, and when you goto the link, the link will give you data in a Format JSON or XML. So your App can Parse the JSON/XML Data and display in your Ionic App.

Example.

www.yourwebsite.com/getusers
www.yourwebsite.com/adduser

you will call the first link from your App in GET protocol and this will give u a list of users in JSON Format.

you will call the second link from your App in POST protocol with User Parameters and this will add a user and Will give you Success or Error Json/XML Response.

So first you need to learn a bit about REST-API and how to build them. You can build them in any language.

REST API FOR BEGINNERS

Then plan which language is the best for you and follow up a good tutorial.

And Finally follow this on how to call an API from IONIC CALL API FROM IONIC


问:
Why is there no padding in the structure for only "char" type members?
I have declared only char type members in the structure.

```<code>#include <stdio.h>

struct st
{
    char c1;
    char c2;
    char c3;
    char c4;
    char c5;
};

int main() {
    struct st s;
    printf("%zu\n", sizeof(s));
    return 0;
}
</code>```

Output: [Live Demo]

```<code>5
</code>```

So, why is there no padding in the structure for only char type members?

答:
The padding in structure exist (mostly) to enforce that the individual members are aligned to their fundamental alignment requirement, i.e. (C11 3.2p1):

requirement that objects of a particular type be located on storage boundaries with addresses that are particular multiples of a byte address

The padding in the middle and at the end of the structure is used to ensure that even within an array of these structures, each member will be still aligned according to their alignment requirement. C11 6.2.8p1:

Complete object types have alignment requirements which place restrictions on the addresses at which objects of that type may be allocated. An alignment is an implementation-defined integer value representing the number of bytes between successive addresses at which a given object can be allocated. An object type imposes an alignment requirement on every object of that type: stricter alignment can be requested using the _Alignas keyword.

Now, the alignment requirement of every other type is implementation-defined, but one thing is implied: since the alignment requirement is expressed in size_t; sizeof (char) is 1, and pointers to character types can be used to address each individual character in other types, a character type cannot have a fundamental alignment requirement of more than 1. Surprisingly this is not spelt out in the C standard at all; it just has this this vague wording (C11 6.2.8p6):

The types char, signed char, and unsigned char shall have the weakest alignment requirement.

As the alignment of char is at most 1, the compiler need not add any padding, because even if the structure is exactly 5 bytes long, then even in an array, with some structures starting at odd address, each of the members of those structures would still be properly aligned.

Body:
I have declared only char type members in the structure.

#include <stdio.h>

struct st
{
    char c1;
    char c2;
    char c3;
    char c4;
    char c5;
};

int main() {
    struct st s;
    printf("%zu\n", sizeof(s));
    return 0;
}

Output: [Live Demo]

5

So, why is there no padding in the structure for only char type members?


问:
Does sql_variant in dbplyr work as it should?
Let's take a look at the example in ?sql_variant:

We define a new translator function for aggregated functions, expanded from the default one:

```<code>postgres_agg <- sql_translator(.parent = base_agg,
  cor = sql_prefix("corr"),
  cov = sql_prefix("covar_samp"),
  sd =  sql_prefix("stddev_samp"),
  var = sql_prefix("var_samp")
)
</code>```

We then define a new variant, which is made from translation functions of the 3 different types (here 2):

```<code>postgres_var <- sql_variant(
  base_scalar,
  postgres_agg
)

translate_sql(cor(x, y), variant = postgres_var)
# <SQL> COR("x", "y")
translate_sql(sd(income / years), variant = postgres_var)
# <SQL> SD("income" / "years")
</code>```

These don't look translated to me, shouldn't they be "CORR" and "STDDEV_SAMP" ?

```<code># Original comment:
# Any functions not explicitly listed in the converter will be translated
# to sql as is, so you don't need to convert all functions.
translate_sql(regr_intercept(y, x), variant = postgres_var)
# <SQL> REGR_INTERCEPT("y", "x")
</code>```

This one behaves as expected, which is just like the other 2.

On the other hand default translated functions work, see:

```<code>translate_sql(mean(x), variant = postgres_var)
#<SQL> avg("x") OVER ()
</code>```

It's a bug right ? or am I missing something ?

My goal is to create some variants for Oracle and use it in the following fashion,then for more complicated functions (example with SQLite to be reproducible):

```<code>con <- DBI::dbConnect(RSQLite::SQLite(), path = ":memory:")
copy_to(con, cars, "cars")
con %>% tbl("cars") %>% summarize(dist = group_concat(dist)) # works as expected, as we're stealing the keyword from sqlite directly
sqlite_variant <- sql_variant(aggregate=sql_translator(.parent = base_agg,gpc = sql_prefix("group_concat")))
con %>% tbl("cars") %>% summarize(dist = gpc(dist)) # how do I make this work ?
</code>```

EDIT:

One bounty later still no solution, I've cross posted the issue in the dplyr/dbplyr github page directly where I'm not sure if it has or will get attention, but in case I (or someone else) don't update this in time, check this url : https://github.com/tidyverse/dplyr/issues/3117

答:
This is what Hadley Wickham answered on provided github link:

translate_sql() doesn't have a variant argument any more

Indeed the variant argument is not documented, though the examples use it, I suppose it will be corrected for next version.

Asked how to define custom SQL translations he had this to offer:

Have a look at http://dbplyr.tidyverse.org/articles/new-backend.html
  and http://dbplyr.tidyverse.org/articles/sql-translation.html

I guess another option is to get the older version of dbplyr::sql_variant.

Body:
Let's take a look at the example in ?sql_variant:

We define a new translator function for aggregated functions, expanded from the default one:

postgres_agg <- sql_translator(.parent = base_agg,
  cor = sql_prefix("corr"),
  cov = sql_prefix("covar_samp"),
  sd =  sql_prefix("stddev_samp"),
  var = sql_prefix("var_samp")
)

We then define a new variant, which is made from translation functions of the 3 different types (here 2):

postgres_var <- sql_variant(
  base_scalar,
  postgres_agg
)

translate_sql(cor(x, y), variant = postgres_var)
# <SQL> COR("x", "y")
translate_sql(sd(income / years), variant = postgres_var)
# <SQL> SD("income" / "years")

These don't look translated to me, shouldn't they be "CORR" and "STDDEV_SAMP" ?

# Original comment:
# Any functions not explicitly listed in the converter will be translated
# to sql as is, so you don't need to convert all functions.
translate_sql(regr_intercept(y, x), variant = postgres_var)
# <SQL> REGR_INTERCEPT("y", "x")

This one behaves as expected, which is just like the other 2.

On the other hand default translated functions work, see:

translate_sql(mean(x), variant = postgres_var)
#<SQL> avg("x") OVER ()

It's a bug right ? or am I missing something ?

My goal is to create some variants for Oracle and use it in the following fashion,then for more complicated functions (example with SQLite to be reproducible):

con <- DBI::dbConnect(RSQLite::SQLite(), path = ":memory:")
copy_to(con, cars, "cars")
con %>% tbl("cars") %>% summarize(dist = group_concat(dist)) # works as expected, as we're stealing the keyword from sqlite directly
sqlite_variant <- sql_variant(aggregate=sql_translator(.parent = base_agg,gpc = sql_prefix("group_concat")))
con %>% tbl("cars") %>% summarize(dist = gpc(dist)) # how do I make this work ?

EDIT:

One bounty later still no solution, I've cross posted the issue in the dplyr/dbplyr github page directly where I'm not sure if it has or will get attention, but in case I (or someone else) don't update this in time, check this url : https://github.com/tidyverse/dplyr/issues/3117


问:
Sendgrid API with Alamofire
I am using the Sendgrid API with Alamofire in my swift app. We are sending emails and everything is working find. With Sendgrid when a email is sent successfully, the response is nothing. Alamofire sees this as an error. Here is my code

```<code>switch response.result {
case .success(let value):
    print ("return email: \(value)")
case .failure(let error):
    print ("error: \(error)")
}
</code>```

I get this when the email sends successfully. "error: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)
did connect socket"

This makes sense of course since the response is nothing but we want to take actions when the email has been sent successfully. What is the best way to handle this? We do want to know if there is an error as well.

答:
It happens because there is not response, in this case you should check HTTP status code. If you are using Alamofire: </p>

```<code>if let statusCode = response.response?.statusCode {
    if statusCode == 200 {
    }
}
</code>```

Title: Sendgrid API with Alamofire

Body:
I am using the Sendgrid API with Alamofire in my swift app. We are sending emails and everything is working find. With Sendgrid when a email is sent successfully, the response is nothing. Alamofire sees this as an error. Here is my code

switch response.result {
case .success(let value):
    print ("return email: \(value)")
case .failure(let error):
    print ("error: \(error)")
}

I get this when the email sends successfully. "error: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)
did connect socket"

This makes sense of course since the response is nothing but we want to take actions when the email has been sent successfully. What is the best way to handle this? We do want to know if there is an error as well.

Body:
It happens because there is not response, in this case you should check HTTP status code. If you are using Alamofire:

if let statusCode = response.response?.statusCode {
    if statusCode == 200 {
    }
}


问:
Subqueries are not allowed after VALUES?
```<code>INSERT INTO t_MT_User (ID, Badge, Name, Scope, comp_code, dept_code, [status])
VALUES ((SELECT MAX(ID) + 1 FROM t_MT_User), @userBadgeNumber, @userName, @userScope, @companyCode, @departmentCode, 1)
</code>```

This query throws the following error:

Subqueries are not allowed in this context. Only scalar expressions are allowed.

If I change VALUES to SELECT, I get another error instead:

```<code>INSERT INTO t_MT_User (ID, Badge, Name, Scope, comp_code, dept_code, [status])
    SELECT
        ((SELECT MAX(ID) + 1 FROM t_MT_User),
         @userBadgeNumber, @userName, @userScope, @companyCode,
         @departmentCode, 1)
</code>```

Incorrect syntax near ','.

How do I achieve (SELECT MAX(ID) + 1 FROM t_MT_User) in this context?

答:
your syntax is wrong. Should be</p>

```<code>INSERT INTO t_MT_User (ID, Badge, Name, Scope, comp_code, dept_code, [status])
SELECT MAX(ID) + 1 , @userBadgeNumber, @userName, @userScope,
       @companyCode, @departmentCode, 1
FROM   t_MT_User
</code>```

Body:
INSERT INTO t_MT_User (ID, Badge, Name, Scope, comp_code, dept_code, [status])
VALUES ((SELECT MAX(ID) + 1 FROM t_MT_User), @userBadgeNumber, @userName, @userScope, @companyCode, @departmentCode, 1)

This query throws the following error:

Subqueries are not allowed in this context. Only scalar expressions are allowed.

If I change VALUES to SELECT, I get another error instead:

INSERT INTO t_MT_User (ID, Badge, Name, Scope, comp_code, dept_code, [status])
    SELECT
        ((SELECT MAX(ID) + 1 FROM t_MT_User),
         @userBadgeNumber, @userName, @userScope, @companyCode,
         @departmentCode, 1)

Incorrect syntax near ','.

How do I achieve (SELECT MAX(ID) + 1 FROM t_MT_User) in this context?

Body:
your syntax is wrong. Should be

INSERT INTO t_MT_User (ID, Badge, Name, Scope, comp_code, dept_code, [status])
SELECT MAX(ID) + 1 , @userBadgeNumber, @userName, @userScope,
       @companyCode, @departmentCode, 1
FROM   t_MT_User


问:
Shorthand method to count length of array
I have an array like this

```<code>var arr = [{a:1, ...},{a:1, ...},{c:2, ...},{a:3, ...},{a:1, ...}]
</code>```

how can I get the length of array where arr[x].a != 1 .

I know this can be done using for loop and push but I want to follow the best practise as every decent programmer should do.

P.S FYI I am using AngularJS.

EDIT 1
For anyone facing issues with arrow function in sajeetharan's answer because of ES6 script here is the solution

```<code>arr.filter(function(a){return a.a != 1}).length;
</code>```

答:
Use filter and length

```<code>const result = arrayToCount.filter(i => i.a != 1 ).length;
</code>```

As @Naman Kheterpal mentioned below, Another way is to use reduce

```<code>const result = arrayToCount.reduce((c, o) => o + (o.a === 1), 0)
</code>```

Body:
I have an array like this

var arr = [{a:1, ...},{a:1, ...},{c:2, ...},{a:3, ...},{a:1, ...}]

how can I get the length of array where arr[x].a != 1 .

I know this can be done using for loop and push but I want to follow the best practise as every decent programmer should do.

P.S FYI I am using AngularJS.

EDIT 1
For anyone facing issues with arrow function in sajeetharan's answer because of ES6 script here is the solution

arr.filter(function(a){return a.a != 1}).length;

Body:
Use filter and length

const result = arrayToCount.filter(i => i.a != 1 ).length;

As @Naman Kheterpal mentioned below, Another way is to use reduce

const result = arrayToCount.reduce((c, o) => o + (o.a === 1), 0)


答:
You can use array.prototype.filter and array.length:

```<code>var length = arr.filter(el => el.a !== 1).length
</code>```

Title: Shorthand method to count length of array

Body:
You can use array.prototype.filter and array.length:

var length = arr.filter(el => el.a !== 1).length


问:
Add href in switch case JavaScript
When displaying a picture how to specify a redirect to the site "href"? For each picture separately link.</p>

```<code>var images = document.querySelectorAll('.img');

for (var i = images.length; i--;) images[i].addEventListener('click', change);

function change() {
  switch (this.value) {
    case "colour1":
      image = '<img src="https://"></img>';
      break;
    case "colour2":
      image = '<img src="https://"></img>';
      break;
    case "colour3":
      image = '<img src="https://"></img>';
      break;

    default:
      image = '<img src="#!"></img>';
  }

  document.getElementById("output-image").innerHTML = image;
}
</code>```

答:
Assuming you want to add a link to the image so it can be loaded as a seperate page you just wrap your image in an link tag with image url, if you want that link to not be a link around the image but a link itself, then add it after the image and use css to position style it as you please.

```<code> var images = document.querySelectorAll('.img');

    for (var i = images.length; i--;) images[i].addEventListener('click', change);

    function change() {
      switch (this.value) {
        case "colour1":
          image = '<a target="_blank" href="https://"><img src="https://"></img></a>';
          break;
        case "colour2":
          image = '<a target="_blank" href="https://"><img src="https://"></img>';
          break;
        case "colour3":
          image = '<a target="_blank" href="https://"><img src="https://"></img>';
          break;

    default:
      image = '<a target="_blank" href="#!"><img src="#!"></img></a>';
  }

  document.getElementById("output-image").innerHTML = image;
}
</code>```

Note i use the attribute target="_blank" to instruct the link to open a new window. If i want the link to have wording i would add it after like so:

```<code><a href="https://..." target="_blank">Enlarge</a>
</code>```

Title: Add href in switch case JavaScript

Body:
When displaying a picture how to specify a redirect to the site "href"? For each picture separately link.

var images = document.querySelectorAll('.img');

for (var i = images.length; i--;) images[i].addEventListener('click', change);

function change() {
  switch (this.value) {
    case "colour1":
      image = '';
      break;
    case "colour2":
      image = '';
      break;
    case "colour3":
      image = '';
      break;

    default:
      image = '';
  }

  document.getElementById("output-image").innerHTML = image;
}

Body:
Assuming you want to add a link to the image so it can be loaded as a seperate page you just wrap your image in an link tag with image url, if you want that link to not be a link around the image but a link itself, then add it after the image and use css to position style it as you please.

 var images = document.querySelectorAll('.img');

    for (var i = images.length; i--;) images[i].addEventListener('click', change);

    function change() {
      switch (this.value) {
        case "colour1":
          image = '<a target="_blank" href="https://"><img src="https://"></img></a>';
          break;
        case "colour2":
          image = '<a target="_blank" href="https://"><img src="https://"></img>';
          break;
        case "colour3":
          image = '<a target="_blank" href="https://"><img src="https://"></img>';
          break;

    default:
      image = '<a target="_blank" href="#!"><img src="#!"></img></a>';
  }

  document.getElementById("output-image").innerHTML = image;
}

Note i use the attribute target="_blank" to instruct the link to open a new window. If i want the link to have wording i would add it after like so:

<a href="https://..." target="_blank">Enlarge</a>


问:
Oracle Data Integrator and odiRef.getSession
I'm having some troubles with ODI logs.
I'm trying to get the logs from the Snp_session, using the session number from  this:

```<code>select <%=odiRef.getSession("SESS_NO")%> from dual
</code>```

Unfortunately, it's not always right, and actualy it get the wrong session number quite often, like 1 every 10 times.
Is it an expected behaviour, or is there another way to get the right session?

Edit:
Corrected mistyping error

答:
Not sure why this is working at all… Last time I checked (ODI 11g) this syntax required extra = character (passing over output from ODI Substitution API directly). Can you try:

```<code>SELECT <%=odiRef.getSession("SESS_NO")%> FROM dual
</code>```

?

Body:
I'm having some troubles with ODI logs.
I'm trying to get the logs from the Snp_session, using the session number from  this:

select <%=odiRef.getSession("SESS_NO")%> from dual

Unfortunately, it's not always right, and actualy it get the wrong session number quite often, like 1 every 10 times.
Is it an expected behaviour, or is there another way to get the right session?

Edit:
Corrected mistyping error

Body:
Not sure why this is working at all… Last time I checked (ODI 11g) this syntax required extra = character (passing over output from ODI Substitution API directly). Can you try:

SELECT <%=odiRef.getSession("SESS_NO")%> FROM dual

?


问:
Red has no open function like Rebol?
I want to read 10 lines from the end of a big text file without loading the whole file in memory.

I wanted to try to use Open as explained here for Rebol In Rebol, what is the idiomatic way to read a text file line by line?

But Red doesn't have open function ?

答: Red doesn't have open function yet. Full IO support is planned for 0.7.0. So you have to either wait or use OS calls directly.

Title: Red has no open function like Rebol?


问:
Implement github.com file seamless file navigation
I just noticed a recent change when browsing github repositorys. When you select a file or folder, the new file slides in and pushed the old file out. This is easy enough to do with jquery, but what's really different is that the URL itself actually changes so that bookmarks still work. I've been struggling to create this for a book navigating site I'm working on but haven't been able to update the url without a full page refresh. Any ideas on how github does this?</p>

答:
It's using the new HTML5 API history.pushState/history.replaceState for doing this (so it only works in modern browsers).

See https://developer.mozilla.org/en/DOM/Manipulating_the_browser_history#Adding_and_modifying_history_entries for more details.

If you want a solution for all browsers, then you have to stick to modifying the fragment (the bit after the #)

ContentLicense: CC BY-SA 4.0


问:
Magento 1.9 - Multi Store Product URL Issue
I had Magento 1.9 website which runs with default store only.

Now I have created 1 more store for USA customers with currency $.

Now issue is why every product have 2 urls, different URL for both stores. There is an issue and duplicate content issue with SEO, So I want only 1 URL for both stores.

Ex:

Product: XYZ

Store India URL: xyz.html with price in INR

Store USA URL: xyz.html with price in $

I have used one extension which redirect me on specific store based on user IP.

Thank you.

答:
Can you please check URL Rewrite Management  in Magento
You can see the url re-write details there
_admin->catalog->URL Rewrite Management
you can add manually url re-write settings there

also you can check another method
1)back up the table "core_url_rewrite"
2)truncate the tabel "core_url_rewrite".
3)re-index
and check the URL Rewrite Management part
please do not  forget to  take back of the table


问:
asp.net mvc how to manage urls/links and routing centrally (c# + js)
I keep running into problems with URLs and routing.

Couldn't find an answer on SO.

I would like to manage all of my urls/links in a single place.

This is for my C# MVC code and the js/jquery ajax code.

These urls are scattered throughout my application.

Moving to a production server needs some fixes and I don't like the fact that I need to look for all of the occurrences in the application.

I don't mind fixing this once - but I would like to do it only once.

Any ideas how to manage all of these links/urls as a group will be very appreciated.

Be happy ad enjoy life, Julian

答:
Depends, if you have application reading off certain urls and those urls changed once in a while. then you might want to consider putting all those urls into a database table/etc and retrieve them using specific key.

that way, when your url changed, all you need to do is to change the url on your database and all your application will still be running fine.


问:
Firebase for iOS - console stuck in Not configured for Cloud Messaging
I already configured tons of apps for APNS in Firebase and it was always painless. Today I'm tring to configure another one which I already implemented the entire SDK for Messaging, added the GoogleService-Info.plist, enabled the bundle ID for Push Notifications, runned the app with Firebase smoothly in a device.

But the Firebase console configuration screen for Notifications doesn't let me upload my certificates or my APNs Auth Key (which I already have too).

The upload buttons are missing, the "fields" are not doing anything, I already tried switching browsers and even switching the computer (Windows based).

I'm working with a mac, tried Google Chrome, tried Safari, tried Chrome for Windows (in another computer) and nothing changes... I'm stuck in this screen.

EDIT: I inspected the console webpage and saw that my browser is getting 404 from Firebase server connection getApnsAuthKey:

```<code>{
    "error": {
        "code": 404,
        "message": "APNS cert not found for requested project and bundle ID",
        "status": "NOT_FOUND",
        "details": [
            {
                "@type": "type.googleapis.com/google.internal.firebase.v1.ErrorCode"
            }
        ]
    }
}
</code>```

答:
The Firebase may be updated with new UI -> new elements at this time (November 2017).

Inspect the Upload button

Remove disabled="disabled" attributed in the button tag

Upload button is enabled!

Body:
I already configured tons of apps for APNS in Firebase and it was always painless. Today I'm tring to configure another one which I already implemented the entire SDK for Messaging, added the GoogleService-Info.plist, enabled the bundle ID for Push Notifications, runned the app with Firebase smoothly in a device.

But the Firebase console configuration screen for Notifications doesn't let me upload my certificates or my APNs Auth Key (which I already have too).

The upload buttons are missing, the "fields" are not doing anything, I already tried switching browsers and even switching the computer (Windows based).

I'm working with a mac, tried Google Chrome, tried Safari, tried Chrome for Windows (in another computer) and nothing changes... I'm stuck in this screen.

EDIT: I inspected the console webpage and saw that my browser is getting 404 from Firebase server connection getApnsAuthKey:

{
    "error": {
        "code": 404,
        "message": "APNS cert not found for requested project and bundle ID",
        "status": "NOT_FOUND",
        "details": [
            {
                "@type": "type.googleapis.com/google.internal.firebase.v1.ErrorCode"
            }
        ]
    }
}


问:
JSR 303 - Name of the annotated field in the custom validator
I have a question about  custom annotations. More precisely, do I have access to the name of the annotated field inside the custom validator ?
If yes, how do I access this?

Thanks

答:
You can access path via following exp</p>

```<code>((ConstraintValidatorContextImpl) context).getConstraintViolationCreationContexts().get(0).getPath()
</code>```

Body:
You can access path via following exp

((ConstraintValidatorContextImpl) context).getConstraintViolationCreationContexts().get(0).getPath()


问:
How to pass a string to a var without escape symbol in Kotlin?
I hope to pass the string {"name":"My Settings 1"} to a var aa

I have to write it using the code  var aa=" {\"name\":\"My Settings 1\"} "

Is there a simple way in Kotlin when I use Android Studio 3.0 ?

I know <![CDATA[...]]> is good for XML content

答:
The simplest thing you can do in Kotlin is use raw strings with triple quote marks:

```<code>val a = """{"name":"My Settings 1"}"""
</code>```

For a tooling solution instead of a language solution (so this works both in Kotlin and Java), you can use language injection in Android Studio or IntelliJ.

Create a string, and invoke intention actions on it with Alt + Enter. Select Inject language or reference, and then JSON.

Use Alt + Enter again, and choose Edit JSON Fragment.

Edit the raw JSON in the panel that appears on the bottom, and IntelliJ will automatically mirror its contents into the string, escaping any characters that have to be escaped.

Body:
The simplest thing you can do in Kotlin is use raw strings with triple quote marks:

val a = """{"name":"My Settings 1"}"""

For a tooling solution instead of a language solution (so this works both in Kotlin and Java), you can use language injection in Android Studio or IntelliJ.

Create a string, and invoke intention actions on it with Alt + Enter. Select Inject language or reference, and then JSON.

Use Alt + Enter again, and choose Edit JSON Fragment.

Edit the raw JSON in the panel that appears on the bottom, and IntelliJ will automatically mirror its contents into the string, escaping any characters that have to be escaped.


问:
How to store javascript array or JSON into php
I have a javaScript array which I need to store in PHP so that later I can store it to MySQL database.

index.php

```<code><form method="post">
<button type="submit" class="btn btn-default" id="php-submit" name="php-submit"><span class="glyphicon glyphicon-upload"></span></button>
<table class="table" id="table-1">
  <-- my finalArray gets generated by selecting some of these table cell values -->
</table>
</form>
</code>```

app.js

```<code>$('#php-submit').click(function()
{   // For demo purpose, I have written hardcoded array values here
    var finalArray = ["Nov 2017 0:00 - 0:59", "Dec 2017 0:00 - 0:59", "Nov 2017 1:00 - 1:59", "Dec 2017 1:00 - 1:59"];
    // console.log(finalArray);
    str_json = JSON.stringify(finalArray);
    console.log(str_json);

    $.ajax({
      type: "POST",
      url: "script.php",
      data: {data : str_json},
      cache: false,
      success: function(){
        alert("OK");
      }
    });

    // $.post('script.php', { data: finalArray }, function (data) {
    //  alert("OK");
    // });

});
</code>```

After user clicks ('#php-submit') button,
I want to be display 'finalArray' or 'str_json' on my script.php.

Below are 4 different approaches that I have tried.

script.php

```<code>// approach 1: output --> blank page

   $data = json_decode(stripslashes($_POST['data']));
   foreach($data as $d){
      echo $d;
   }

// approach 2: ouptut --> null

   $data = json_decode(stripslashes($_POST['data']));
   var_dump($data);

// approach 3: output --> null

   header('Content-type: application/json; charset=utf-8');
   $json = file_get_contents('php://input');
   $json_decode = json_decode($json, true);
   $json_encode = json_encode($json_decode);
   echo $json_encode;

// approach 4: output --> array(1) { [0]=> string(4) "null" }

   $data = $_POST['data'];
   $json_encode = json_encode($data);
   $ar = explode(',', $json_encode);
   var_dump($ar);
</code>```

答:
I believe the problem is that you are sending $.ajax request but are checking the script.php from browser tab. to see your ajax request you need to use Chrome Dev Tools. Like:

Open Chrom Dev Tools with Ctrl + Shift + I

Move to Network Tab.

Look for your request in the XHR section:

Now I ran your code and it worked just fine for me. As you can see from the screenshots too.

Edit: Instead of sending an ajax request try submitting a dynaimcally generated <form>, Like:

```<code>$('#php-submit').click(function()
{
    var finalArray = ["Nov 2017 0:00 - 0:59", "Dec 2017 0:00 - 0:59", "Nov 2017 1:00 - 1:59", "Dec 2017 1:00 - 1:59"];
    str_json = JSON.stringify(finalArray);

        var newForm = $('<form>', {
            'action': 'script.php',
            'target': '_top',
            'method': 'POST'
        }).append($('<input>', {
            'name': 'data',
            'value': str_json,
            'type': 'hidden'
        }));
        $(document.body).append(newForm);
        newForm.submit();

});
</code>```

But if you don't want to redirect to another page using <form>.Then in your script.php, do something like this using $_SESSION:

```<code>if(isset($_POST['data']))
{
    $_SESSION['data'] = json_decode(stripslashes($_POST['data']));
}

var_dump($_SESSION);
</code>```

Body:
I have a javaScript array which I need to store in PHP so that later I can store it to MySQL database.

index.php

<form method="post">
<button type="submit" class="btn btn-default" id="php-submit" name="php-submit"></button>

  <-- my finalArray gets generated by selecting some of these table cell values -->

</form>

app.js

$('#php-submit').click(function()
{   // For demo purpose, I have written hardcoded array values here
    var finalArray = ["Nov 2017 0:00 - 0:59", "Dec 2017 0:00 - 0:59", "Nov 2017 1:00 - 1:59", "Dec 2017 1:00 - 1:59"];
    // console.log(finalArray);
    str_json = JSON.stringify(finalArray);
    console.log(str_json);

    $.ajax({
      type: "POST",
      url: "script.php",
      data: {data : str_json},
      cache: false,
      success: function(){
        alert("OK");
      }
    });

    // $.post('script.php', { data: finalArray }, function (data) {
    //  alert("OK");
    // });

});

After user clicks ('#php-submit') button,
I want to be display 'finalArray' or 'str_json' on my script.php.

Below are 4 different approaches that I have tried.

script.php

// approach 1: output --> blank page

   $data = json_decode(stripslashes($_POST['data']));
   foreach($data as $d){
      echo $d;
   }

// approach 2: ouptut --> null

   $data = json_decode(stripslashes($_POST['data']));
   var_dump($data);

// approach 3: output --> null

   header('Content-type: application/json; charset=utf-8');
   $json = file_get_contents('php://input');
   $json_decode = json_decode($json, true);
   $json_encode = json_encode($json_decode);
   echo $json_encode;

// approach 4: output --> array(1) { [0]=> string(4) "null" }

   $data = $_POST['data'];
   $json_encode = json_encode($data);
   $ar = explode(',', $json_encode);
   var_dump($ar);

Body:
I believe the problem is that you are sending $.ajax request but are checking the script.php from browser tab. to see your ajax request you need to use Chrome Dev Tools. Like:

Open Chrom Dev Tools with Ctrl + Shift + I

Move to Network Tab.

Look for your request in the XHR section:

Now I ran your code and it worked just fine for me. As you can see from the screenshots too.

Edit: Instead of sending an ajax request try submitting a dynaimcally generated <form>, Like:

$('#php-submit').click(function()
{
    var finalArray = ["Nov 2017 0:00 - 0:59", "Dec 2017 0:00 - 0:59", "Nov 2017 1:00 - 1:59", "Dec 2017 1:00 - 1:59"];
    str_json = JSON.stringify(finalArray);

        var newForm = $('<form>', {
            'action': 'script.php',
            'target': '_top',
            'method': 'POST'
        }).append($('<input>', {
            'name': 'data',
            'value': str_json,
            'type': 'hidden'
        }));
        $(document.body).append(newForm);
        newForm.submit();

});

But if you don't want to redirect to another page using <form>.Then in your script.php, do something like this using $_SESSION:

if(isset($_POST['data']))
{
    $_SESSION['data'] = json_decode(stripslashes($_POST['data']));
}

var_dump($_SESSION);


问:
SQL Query to add a new column after an existing column in SQL Server 2005
I need a SQL query which add a new column after an existing column, so the column will be added in a specific order.

Please suggest me if any ALTER query which do that.

答:
If you want to alter order for columns in Sql server, There is no direct way to do this in SQL Server currently.

Have a look at http://blog.sqlauthority.com/2008/04/08/sql-server-change-order-of-column-in-database-tables/

You can change order while edit design for table.