问:
Varnish not working with WooCommerce
We are attempting to add Varnish to our Woocommerce setup and are running into some troubles.

On a product page (lets say /product/television),  if you press the "add to cart" button, you are now redirected to the cart page, as expected, but the item has not been added to the cart.

However, if you do the same thing while logged into an account, it will work fine.  I have posted my varnish.vcl below and if anyone has any insight as to what is wrong please let me know.

```<code>    # This is an example VCL file for Wordpress/WooCommerce/Varnish.
    #

    # Updated to work with Varnish 4

    # Marker to tell the VCL compiler that this VCL has been adapted to the
    # new 4.0 format.
    vcl 4.0;

    # Default backend definition. Set this to point to your content server.
    backend default {
        .host = "web";
        .port = "80";
        .connect_timeout = 600s;
        .first_byte_timeout = 600s;
        .between_bytes_timeout = 600s;
        .max_connections = 800;
    }

    # Only allow purging from specific IPs
    acl purge {
        "localhost";
    }

    # This function is used when a request is send by a HTTP client (Browser)
    sub vcl_recv {
        # Normalize the header, remove the port (in case you're testing this on various TCP ports)
        set req.http.Host = regsub(req.http.Host, ":[0-9]+", "");

        # The code below makes sure the AJAX "add to cart" function works
        set req.url = regsub(req.url, "add-to-cart=\d+_\d+&", "");

        # Allow purging from ACL
        if (req.method == "PURGE") {
            # If not allowed then a error 405 is returned
            if (!client.ip ~ purge) {
                return(synth(405, "This IP is not allowed to send PURGE requests."));
            }
            # If allowed, do a cache_lookup -> vlc_hit() or vlc_miss()
            return (purge);
        }

        # Post requests will not be cached
        if (req.http.Authorization || req.method == "POST") {
            return (pass);
        }

        # --- Wordpress specific configuration

        # Did not cache the RSS feed
        if (req.url ~ "/feed") {
            return (pass);
        }

        # Blitz hack
            if (req.url ~ "/mu-.*") {
                    return (pass);
            }

        # Do not cache the admin and login pages
        if (req.url ~ "/wp-(login|admin)") {
            return (pass);
        }

        # Do not cache the WooCommerce pages

        if (req.url ~ "/(cart|my-account|checkout|addons)") {
            return (pass);
        }

        if (req.url ~ "/?add-to-cart=") {
            return (pass);
        }

        # Remove the "has_js" cookie
        set req.http.Cookie = regsuball(req.http.Cookie, "has_js=[^;]+(; )?", "");

        # Remove any Google Analytics based cookies
        set req.http.Cookie = regsuball(req.http.Cookie, "__utm.=[^;]+(; )?", "");

        # Remove the Quant Capital cookies (added by some plugin, all __qca)
        set req.http.Cookie = regsuball(req.http.Cookie, "__qc.=[^;]+(; )?", "");

        # Remove the wp-settings-1 cookie
        set req.http.Cookie = regsuball(req.http.Cookie, "wp-settings-1=[^;]+(; )?", "");

        # Remove the wp-settings-time-1 cookie
        set req.http.Cookie = regsuball(req.http.Cookie, "wp-settings-time-1=[^;]+(; )?", "");

        # Remove the wp test cookie
        set req.http.Cookie = regsuball(req.http.Cookie, "wordpress_test_cookie=[^;]+(; )?", "");

        # Are there cookies left with only spaces or that are empty?
        if (req.http.cookie ~ "^ *$") {
                unset req.http.cookie;
        }

        # Cache the following files extensions
        if (req.url ~ "\.(css|js|png|gif|jp(e)?g|swf|ico)") {
            unset req.http.cookie;
        }

        # Normalize Accept-Encoding header and compression
        # https://www.varnish-cache.org/docs/3.0/tutorial/vary.html
        if (req.http.Accept-Encoding) {
            # Do no compress compressed files...
            if (req.url ~ "\.(jpg|png|gif|gz|tgz|bz2|tbz|mp3|ogg)$") {
                    unset req.http.Accept-Encoding;
            } elsif (req.http.Accept-Encoding ~ "gzip") {
                    set req.http.Accept-Encoding = "gzip";
            } elsif (req.http.Accept-Encoding ~ "deflate") {
                    set req.http.Accept-Encoding = "deflate";
            } else {
                unset req.http.Accept-Encoding;
            }
        }

        # Check the cookies for wordpress-specific items
        if (req.http.Cookie ~ "wordpress_" || req.http.Cookie ~ "comment_") {
            return (pass);
        }
        if (!req.http.cookie) {
            unset req.http.cookie;
        }

        # --- End of Wordpress specific configuration

        # Did not cache HTTP authentication and HTTP Cookie
        if (req.http.Authorization || req.http.Cookie) {
            # Not cacheable by default
            return (pass);
        }

        # Cache all others requests
        return (hash);
    }

    sub vcl_pipe {
        return (pipe);
    }

    sub vcl_pass {
        return (fetch);
    }

    # The data on which the hashing will take place
    sub vcl_hash {
        hash_data(req.url);
        if (req.http.host) {
            hash_data(req.http.host);
        } else {
            hash_data(server.ip);
        }

        # If the client supports compression, keep that in a different cache
            if (req.http.Accept-Encoding) {
                hash_data(req.http.Accept-Encoding);
        }

        return (lookup);
    }

    # This function is used when a request is sent by our backend (Nginx server)
    sub vcl_backend_response {
        # Remove some headers we never want to see
        unset beresp.http.Server;
        unset beresp.http.X-Powered-By;

        # For static content strip all backend cookies
        if (bereq.url ~ "\.(css|js|png|gif|jp(e?)g)|swf|ico") {
            unset beresp.http.cookie;
        }

        # Only allow cookies to be set if we're in admin area
        if (beresp.http.Set-Cookie && bereq.url !~ "^/wp-(login|admin)") {
                unset beresp.http.Set-Cookie;
            }

        # don't cache response to posted requests or those with basic auth
        if ( bereq.method == "POST" || bereq.http.Authorization ) {
                set beresp.uncacheable = true;
            set beresp.ttl = 120s;
            return (deliver);
            }

            # don't cache search results
        if ( bereq.url ~ "\?s=" ){
            set beresp.uncacheable = true;
                    set beresp.ttl = 120s;
                    return (deliver);
        }

        # only cache status ok
        if ( beresp.status != 200 ) {
            set beresp.uncacheable = true;
                    set beresp.ttl = 120s;
                    return (deliver);
        }

        # A TTL of 24h
        set beresp.ttl = 24h;
        # Define the default grace period to serve cached content
        set beresp.grace = 30s;

        return (deliver);
    }

    # The routine when we deliver the HTTP request to the user
    # Last chance to modify headers that are sent to the client
    sub vcl_deliver {
        if (obj.hits > 0) {
            set resp.http.X-Cache = "cached";
        } else {
            set resp.http.x-Cache = "uncached";
        }

        # Remove some headers: PHP version
        unset resp.http.X-Powered-By;

        # Remove some headers: Apache version & OS
        unset resp.http.Server;

        # Remove some heanders: Varnish
        unset resp.http.Via;
        unset resp.http.X-Varnish;

        return (deliver);
    }

    sub vcl_init {
        return (ok);
    }

    sub vcl_fini {
        return (ok);
    }
</code>```

答:
I found the solution to this problem here:
https://guides.wp-bullet.com/fix-empty-cart-with-woocommerce-redirect-to-checkout-varnish-4/

Basically when you add an item to the cart, Woocommerce issues a 302 redirect and sends you to the cart (you can disable this behaviour from the settings). In Varnish you have to be sure not to remove any cookies from the backend response when this event occurs.

```<code>sub vcl_backend_response {
   if (!(bereq.url ~ "wp-(login|admin)|cart|my-account|wc-api|resetpass") &&
    !bereq.http.cookie ~ "wordpress_logged_in|woocommerce_items_in_cart|resetpass" &&
    !beresp.status == 302 ) {
       unset beresp.http.set-cookie;
       set beresp.ttl = 1w;
       set beresp.grace = 1d;
   }
}
</code>```

Title: Varnish not working with WooCommerce

Body:
We are attempting to add Varnish to our Woocommerce setup and are running into some troubles.

On a product page (lets say /product/television),  if you press the "add to cart" button, you are now redirected to the cart page, as expected, but the item has not been added to the cart.

However, if you do the same thing while logged into an account, it will work fine.  I have posted my varnish.vcl below and if anyone has any insight as to what is wrong please let me know.

    # This is an example VCL file for Wordpress/WooCommerce/Varnish.
    #

    # Updated to work with Varnish 4

    # Marker to tell the VCL compiler that this VCL has been adapted to the
    # new 4.0 format.
    vcl 4.0;

    # Default backend definition. Set this to point to your content server.
    backend default {
        .host = "web";
        .port = "80";
        .connect_timeout = 600s;
        .first_byte_timeout = 600s;
        .between_bytes_timeout = 600s;
        .max_connections = 800;
    }

    # Only allow purging from specific IPs
    acl purge {
        "localhost";
    }

    # This function is used when a request is send by a HTTP client (Browser)
    sub vcl_recv {
        # Normalize the header, remove the port (in case you're testing this on various TCP ports)
        set req.http.Host = regsub(req.http.Host, ":[0-9]+", "");

        # The code below makes sure the AJAX "add to cart" function works
        set req.url = regsub(req.url, "add-to-cart=\d+_\d+&", "");

        # Allow purging from ACL
        if (req.method == "PURGE") {
            # If not allowed then a error 405 is returned
            if (!client.ip ~ purge) {
                return(synth(405, "This IP is not allowed to send PURGE requests."));
            }
            # If allowed, do a cache_lookup -> vlc_hit() or vlc_miss()
            return (purge);
        }

        # Post requests will not be cached
        if (req.http.Authorization || req.method == "POST") {
            return (pass);
        }

        # --- Wordpress specific configuration

        # Did not cache the RSS feed
        if (req.url ~ "/feed") {
            return (pass);
        }

        # Blitz hack
            if (req.url ~ "/mu-.*") {
                    return (pass);
            }

        # Do not cache the admin and login pages
        if (req.url ~ "/wp-(login|admin)") {
            return (pass);
        }

        # Do not cache the WooCommerce pages

        if (req.url ~ "/(cart|my-account|checkout|addons)") {
            return (pass);
        }

        if (req.url ~ "/?add-to-cart=") {
            return (pass);
        }

        # Remove the "has_js" cookie
        set req.http.Cookie = regsuball(req.http.Cookie, "has_js=[^;]+(; )?", "");

        # Remove any Google Analytics based cookies
        set req.http.Cookie = regsuball(req.http.Cookie, "__utm.=[^;]+(; )?", "");

        # Remove the Quant Capital cookies (added by some plugin, all __qca)
        set req.http.Cookie = regsuball(req.http.Cookie, "__qc.=[^;]+(; )?", "");

        # Remove the wp-settings-1 cookie
        set req.http.Cookie = regsuball(req.http.Cookie, "wp-settings-1=[^;]+(; )?", "");

        # Remove the wp-settings-time-1 cookie
        set req.http.Cookie = regsuball(req.http.Cookie, "wp-settings-time-1=[^;]+(; )?", "");

        # Remove the wp test cookie
        set req.http.Cookie = regsuball(req.http.Cookie, "wordpress_test_cookie=[^;]+(; )?", "");

        # Are there cookies left with only spaces or that are empty?
        if (req.http.cookie ~ "^ *$") {
                unset req.http.cookie;
        }

        # Cache the following files extensions
        if (req.url ~ "\.(css|js|png|gif|jp(e)?g|swf|ico)") {
            unset req.http.cookie;
        }

        # Normalize Accept-Encoding header and compression
        # https://www.varnish-cache.org/docs/3.0/tutorial/vary.html
        if (req.http.Accept-Encoding) {
            # Do no compress compressed files...
            if (req.url ~ "\.(jpg|png|gif|gz|tgz|bz2|tbz|mp3|ogg)$") {
                    unset req.http.Accept-Encoding;
            } elsif (req.http.Accept-Encoding ~ "gzip") {
                    set req.http.Accept-Encoding = "gzip";
            } elsif (req.http.Accept-Encoding ~ "deflate") {
                    set req.http.Accept-Encoding = "deflate";
            } else {
                unset req.http.Accept-Encoding;
            }
        }

        # Check the cookies for wordpress-specific items
        if (req.http.Cookie ~ "wordpress_" || req.http.Cookie ~ "comment_") {
            return (pass);
        }
        if (!req.http.cookie) {
            unset req.http.cookie;
        }

        # --- End of Wordpress specific configuration

        # Did not cache HTTP authentication and HTTP Cookie
        if (req.http.Authorization || req.http.Cookie) {
            # Not cacheable by default
            return (pass);
        }

        # Cache all others requests
        return (hash);
    }

    sub vcl_pipe {
        return (pipe);
    }

    sub vcl_pass {
        return (fetch);
    }

    # The data on which the hashing will take place
    sub vcl_hash {
        hash_data(req.url);
        if (req.http.host) {
            hash_data(req.http.host);
        } else {
            hash_data(server.ip);
        }

        # If the client supports compression, keep that in a different cache
            if (req.http.Accept-Encoding) {
                hash_data(req.http.Accept-Encoding);
        }

        return (lookup);
    }

    # This function is used when a request is sent by our backend (Nginx server)
    sub vcl_backend_response {
        # Remove some headers we never want to see
        unset beresp.http.Server;
        unset beresp.http.X-Powered-By;

        # For static content strip all backend cookies
        if (bereq.url ~ "\.(css|js|png|gif|jp(e?)g)|swf|ico") {
            unset beresp.http.cookie;
        }

        # Only allow cookies to be set if we're in admin area
        if (beresp.http.Set-Cookie && bereq.url !~ "^/wp-(login|admin)") {
                unset beresp.http.Set-Cookie;
            }

        # don't cache response to posted requests or those with basic auth
        if ( bereq.method == "POST" || bereq.http.Authorization ) {
                set beresp.uncacheable = true;
            set beresp.ttl = 120s;
            return (deliver);
            }

            # don't cache search results
        if ( bereq.url ~ "\?s=" ){
            set beresp.uncacheable = true;
                    set beresp.ttl = 120s;
                    return (deliver);
        }

        # only cache status ok
        if ( beresp.status != 200 ) {
            set beresp.uncacheable = true;
                    set beresp.ttl = 120s;
                    return (deliver);
        }

        # A TTL of 24h
        set beresp.ttl = 24h;
        # Define the default grace period to serve cached content
        set beresp.grace = 30s;

        return (deliver);
    }

    # The routine when we deliver the HTTP request to the user
    # Last chance to modify headers that are sent to the client
    sub vcl_deliver {
        if (obj.hits > 0) {
            set resp.http.X-Cache = "cached";
        } else {
            set resp.http.x-Cache = "uncached";
        }

        # Remove some headers: PHP version
        unset resp.http.X-Powered-By;

        # Remove some headers: Apache version & OS
        unset resp.http.Server;

        # Remove some heanders: Varnish
        unset resp.http.Via;
        unset resp.http.X-Varnish;

        return (deliver);
    }

    sub vcl_init {
        return (ok);
    }

    sub vcl_fini {
        return (ok);
    }

Body:
I found the solution to this problem here:
https://guides.wp-bullet.com/fix-empty-cart-with-woocommerce-redirect-to-checkout-varnish-4/

Basically when you add an item to the cart, Woocommerce issues a 302 redirect and sends you to the cart (you can disable this behaviour from the settings). In Varnish you have to be sure not to remove any cookies from the backend response when this event occurs.

sub vcl_backend_response {
   if (!(bereq.url ~ "wp-(login|admin)|cart|my-account|wc-api|resetpass") &&
    !bereq.http.cookie ~ "wordpress_logged_in|woocommerce_items_in_cart|resetpass" &&
    !beresp.status == 302 ) {
       unset beresp.http.set-cookie;
       set beresp.ttl = 1w;
       set beresp.grace = 1d;
   }
}


来源: stackexchange

问:
How to convert a nested complex scala Map to Java
I'm trying to use a Scala library in my Java program and I have some difficulties to convert a complex Scala Map to Java.

My used Scala object method has the following return type: scala.collection.mutable.Map<String, Map<Object, Seq<Object>>>

How do I convert that to a Java equivalent of Map<String, Map<Object, List<Object>>> ?

I already played around with the JavaConversions and JavaConvertors packages but no luck :(

```<code>public void getPartitionAssignmentForTopics(final List<String> topics) {
    final Seq<String> seqTopics =         scala.collection.JavaConversions.asScalaBuffer(topics).toList();
    scala.collection.mutable.Map<String, Map<Object, Seq<Object>>> map2 = zkUtils
            .getPartitionAssignmentForTopics(seqTopics);

    val map:scala.collection.mutable.Map[String, Map[Object, Seq[Object]]] = scala.collection.mutable.Map()
    map:
    collection.mutable.Map[String, Map[Object, Seq[Object]]] =Map()
    map.mapValues(_.mapValues(_.asJava).asJava).asJava
    res2:
    java.util.Map[String, java.util.Map[Object, java.util.List[Object]]] ={}
}
</code>```

This does not compile :)

With playing around I meant that I use the following code to convert from Scala Seq to Java List:
scala.collection.JavaConversions.seqAsJavaList(zkUtils.getAllTopics());

答:
I ended up with the following code. Not really nice :D</p>

```<code>public java.util.Map<String, java.util.Map<Integer, java.util.List<Integer>>> getPartitionAssignmentForTopics(final List<String> topics) {
    final scala.collection.Seq<String> seqTopics = scala.collection.JavaConversions.asScalaBuffer(topics).toList();
    scala.collection.mutable.Map<String, scala.collection.Map<Object, scala.collection.Seq<Object>>> tmpMap1 =
            zkUtils.getPartitionAssignmentForTopics(seqTopics);

    final java.util.Map<String, java.util.Map<Integer, java.util.List<Integer>>> result = new HashMap<>();
    java.util.Map<String, Map<Object, Seq<Object>>> tmpMap2 = JavaConversions.mapAsJavaMap(tmpMap1);
    tmpMap2.forEach((k1, v1) -> {
        String topic = (String)k1;
        java.util.Map<Object, Seq<Object>> objectSeqMap = JavaConversions.mapAsJavaMap(v1);
        java.util.Map<Integer, List<Integer>> tmpResultMap = new HashMap<>();
        objectSeqMap.forEach((k2, v2) -> {
            Integer tmpInt = (Integer)k2;
            List<Integer> tmpList = (List<Integer>)(Object)JavaConversions.seqAsJavaList(v2);
            tmpResultMap.put(tmpInt, tmpList);
        });
        result.put(topic, tmpResultMap);
    });

    return result;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to use a Scala library in my Java program and I have some difficulties to convert a complex Scala Map to Java.

My used Scala object method has the following return type: scala.collection.mutable.Map<String, Map<Object, Seq<Object>>>

How do I convert that to a Java equivalent of Map<String, Map<Object, List<Object>>> ?

I already played around with the JavaConversions and JavaConvertors packages but no luck :(

public void getPartitionAssignmentForTopics(final List<String> topics) {
    final Seq<String> seqTopics =         scala.collection.JavaConversions.asScalaBuffer(topics).toList();
    scala.collection.mutable.Map<String, Map<Object, Seq<Object>>> map2 = zkUtils
            .getPartitionAssignmentForTopics(seqTopics);

    val map:scala.collection.mutable.Map[String, Map[Object, Seq[Object]]] = scala.collection.mutable.Map()
    map:
    collection.mutable.Map[String, Map[Object, Seq[Object]]] =Map()
    map.mapValues(_.mapValues(_.asJava).asJava).asJava
    res2:
    java.util.Map[String, java.util.Map[Object, java.util.List[Object]]] ={}
}

This does not compile :)

With playing around I meant that I use the following code to convert from Scala Seq to Java List:
scala.collection.JavaConversions.seqAsJavaList(zkUtils.getAllTopics());

Body:
I ended up with the following code. Not really nice :D

public java.util.Map<String, java.util.Map<Integer, java.util.List<Integer>>> getPartitionAssignmentForTopics(final List<String> topics) {
    final scala.collection.Seq<String> seqTopics = scala.collection.JavaConversions.asScalaBuffer(topics).toList();
    scala.collection.mutable.Map<String, scala.collection.Map<Object, scala.collection.Seq<Object>>> tmpMap1 =
            zkUtils.getPartitionAssignmentForTopics(seqTopics);

    final java.util.Map<String, java.util.Map<Integer, java.util.List<Integer>>> result = new HashMap<>();
    java.util.Map<String, Map<Object, Seq<Object>>> tmpMap2 = JavaConversions.mapAsJavaMap(tmpMap1);
    tmpMap2.forEach((k1, v1) -> {
        String topic = (String)k1;
        java.util.Map<Object, Seq<Object>> objectSeqMap = JavaConversions.mapAsJavaMap(v1);
        java.util.Map<Integer, List<Integer>> tmpResultMap = new HashMap<>();
        objectSeqMap.forEach((k2, v2) -> {
            Integer tmpInt = (Integer)k2;
            List<Integer> tmpList = (List<Integer>)(Object)JavaConversions.seqAsJavaList(v2);
            tmpResultMap.put(tmpInt, tmpList);
        });
        result.put(topic, tmpResultMap);
    });

    return result;
}


问:
How JVM works internally
ALL,

At work we have a software written in JAVA. It is operational and works fine. In couple of sources we have a statements like this:

```<code>import x.y.z
</code>```

There is no source file where we use

```<code>import x.y.*
</code>```

Recently we had a scan from the Software Assurance team and they found couple of deficiencies.

An example would be this:

```<code>The code is using MD5 encryption algorithm.
</code>```

Our code does not even import a class connected to the MD5 let alone use it.

So, my question would be:

If I have an import for the class Foo, does JVM actually pulls everything from the JAR/library ?

Thank you.

答:
If I have an import for the class Foo, does JVM actually pulls everything from the JAR/library ?

No.  Only the classes that are needed at runtime will be loaded by the JVM.

However, if your class A uses library class L1, and class L1 uses another library class L2, then both L1 and L2 will be loaded.  Thus you cannot determine if MD5 is used simply by looking at your classes import statements.  (There are other reasons too ...)

One way to determine the classes that are actually used is to start the JVM with the command line option -verbose:class.  This displays info about each loaded class, including library classes.

Title: How JVM works internally

Body:
ALL,

At work we have a software written in JAVA. It is operational and works fine. In couple of sources we have a statements like this:

import x.y.z

There is no source file where we use

import x.y.*

Recently we had a scan from the Software Assurance team and they found couple of deficiencies.

An example would be this:

The code is using MD5 encryption algorithm.

Our code does not even import a class connected to the MD5 let alone use it.

So, my question would be:

If I have an import for the class Foo, does JVM actually pulls everything from the JAR/library ?

Thank you.


问:
How can i hold a first letter of `h1` content after pressing backspace
How can i hold a first letter of h1 content after pressing backspace. Here i used keyup function but its not allowing to write in h1. Can someone know how to do it?

Here is the link: https://jsfiddle.net/5brr7sj1/3/

CODE:

$(document).ready(function(){

var txt = $('.editor').text();
var splitTxt = txt.split('');

 $('.editor').keyup(function(){
 $(this).text(splitTxt[1]);
 });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.editor {
  border:1px solid #d9d9d9;
  height:40px;
  line-height:40px;
  padding:0 15px;
}</code>```

    Click here to edit content

```

答:
Are you looking like this https://jsfiddle.net/5brr7sj1/14/</p>

```<code>$(document).ready(function(){

var txt = $('.editor').text();
var splitTxt = txt.split('');

 $('.editor').keyup(function(){
 if($('.editor').text().length == 0){
    $(this).text(splitTxt[1]);
 }

 });

});
</code>```

Body:
How can i hold a first letter of h1 content after pressing backspace. Here i used keyup function but its not allowing to write in h1. Can someone know how to do it?

Here is the link: https://jsfiddle.net/5brr7sj1/3/

CODE:

$(document).ready(function(){

var txt = $('.editor').text();
var splitTxt = txt.split('');

 $('.editor').keyup(function(){
 $(this).text(splitTxt[1]);
 });

});

.editor {
  border:1px solid #d9d9d9;
  height:40px;
  line-height:40px;
  padding:0 15px;
}

    Click here to edit content

Body:
Are you looking like this https://jsfiddle.net/5brr7sj1/14/

$(document).ready(function(){

var txt = $('.editor').text();
var splitTxt = txt.split('');

 $('.editor').keyup(function(){
 if($('.editor').text().length == 0){
    $(this).text(splitTxt[1]);
 }

 });

});


问:
Redirecting urls in IIS 8.5

I'm using IIS 8.5 now and need to redirect from

http://mydomain.de/produkte.asp?produkt=someID

to

http://mydomain.de/produkte/someID.html

Thanks!

答:
One day work and here it is:

```<code><rule name="Products" stopProcessing="true">
<match url="produkte\.asp" />
<conditions logicalGrouping="MatchAny">
    <add input="{REQUEST_URI}" pattern="^(.*)produkte\.asp\?produkt=(.*)$" />
</conditions>
<action type="Redirect" url="produkte/{C:2}.html" appendQueryString="false" redirectType="Temporary" />
</code>```

Title: Redirecting urls in IIS 8.5

Body:
One day work and here it is:

<rule name="Products" stopProcessing="true">
<match url="produkte\.asp" />
<conditions logicalGrouping="MatchAny">
    <add input="{REQUEST_URI}" pattern="^(.*)produkte\.asp\?produkt=(.*)$" />
</conditions>
<action type="Redirect" url="produkte/{C:2}.html" appendQueryString="false" redirectType="Temporary" />


问:
How to get values from a Java HashMap in javascript function using Rhino
I am using Rhino library to execute JavaScript functions in android. I have a javascript function like,

```<code>var exucuteJS = function(controlValues) {
var valueSelected = controlValues['country'];
valueSelected = valueSelected.toUpperCase();
 switch (valueSelected) {
    case "INDIA":
        return "IND_HOME";
    case "NEPAL":
        return "NEP_HOME";
    default:
        return "DEF_HOME"
 }
}
</code>```

I am passing a Java HashMap object as parameter, say controlValues to the function executeJS. The problem is , the Rhino cant javascript code, to get the value from the key.

```<code>var valueSelected = controlValues['country'];
</code>```

the return value is undefined.

it works fine with this line,

```<code>var valueSelected = controlValues.get('country');
</code>```

but its not valid javascript code.

The same javascript is to be executed both in android and iOS. the above line will not supported in iOS. Please suggest. I am using latest version of Rhino.

答:
Simpler solution where you do not have to implement a NullCallable class is

```<code>new JsonParser(context, scope).parseValue("{\"this is\":\"JSON\"}");
</code>```

which I found at Rhino: return JSON from within Java

Body:
I am using Rhino library to execute JavaScript functions in android. I have a javascript function like,

var exucuteJS = function(controlValues) {
var valueSelected = controlValues['country'];
valueSelected = valueSelected.toUpperCase();
 switch (valueSelected) {
    case "INDIA":
        return "IND_HOME";
    case "NEPAL":
        return "NEP_HOME";
    default:
        return "DEF_HOME"
 }
}

I am passing a Java HashMap object as parameter, say controlValues to the function executeJS. The problem is , the Rhino cant javascript code, to get the value from the key.

var valueSelected = controlValues['country'];

the return value is undefined.

it works fine with this line,

var valueSelected = controlValues.get('country');

but its not valid javascript code.

The same javascript is to be executed both in android and iOS. the above line will not supported in iOS. Please suggest. I am using latest version of Rhino.

Body:
Simpler solution where you do not have to implement a NullCallable class is

new JsonParser(context, scope).parseValue("{\"this is\":\"JSON\"}");

which I found at Rhino: return JSON from within Java


问:
String Pattern Question - Core Java (repeatSeparator)
Write a Java function such that Given two strings, word and a separator, return a big string made of count occurences of the word, separated by the separator string.

```<code>repeatSeparator("Word", "X", 3) → "WordXWordXWord"
repeatSeparator("This", "And", 2) → "ThisAndThis"
repeatSeparator("This", "And", 1) → "This"
</code>```

My code is as below but is not working

```<code>public String repeatSeparator(String word, String sep, int count) {
    if(count == 1) {
        return word;
    }
    if(count > 1) {
        for (int i = 0; i < count-1; i++){
            word = word + sep + word;
        }
    }
   return word;
}
</code>```

Example Output ::

```<code>                                   Expected         Run                  Result
repeatSeparator("Word", "X", 3) → "WordXWordXWord" "WordXWordXWordXWord" X
</code>```

答:
The below function should do what you need:</p>

```<code>public String repeatSeparator(String word, String sep, int count) {
    StringBuffer buffer = new StringBuffer();

    while (count > 0) {
        buffer.append(word);
        count--;
        if (count > 0) {
            buffer.append(sep);
        }
    }

    return buffer.toString();
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Write a Java function such that Given two strings, word and a separator, return a big string made of count occurences of the word, separated by the separator string.

repeatSeparator("Word", "X", 3) → "WordXWordXWord"
repeatSeparator("This", "And", 2) → "ThisAndThis"
repeatSeparator("This", "And", 1) → "This"

My code is as below but is not working

public String repeatSeparator(String word, String sep, int count) {
    if(count == 1) {
        return word;
    }
    if(count > 1) {
        for (int i = 0; i < count-1; i++){
            word = word + sep + word;
        }
    }
   return word;
}

Example Output ::

                                   Expected         Run                  Result
repeatSeparator("Word", "X", 3) → "WordXWordXWord" "WordXWordXWordXWord" X

Body:
The below function should do what you need:

public String repeatSeparator(String word, String sep, int count) {
    StringBuffer buffer = new StringBuffer();

    while (count > 0) {
        buffer.append(word);
        count--;
        if (count > 0) {
            buffer.append(sep);
        }
    }

    return buffer.toString();
}


问:
How to get photo bucket consumer key
I have to use photo bucket api in one of my project. But i can't be able to get consumer key for it. I have already create developer account. But i can't go further without consumer key.
Can anyone tell me the way to get it and how to use it in photobucket. Thanks in advance.</p>

答:
As I understand photobucket doesn't support any API from 2010 year.

All developer sub-domains not working.

Email pbdl-api@photobucket.com  that reuqest API key doesn't exists.

Title: How to get photo bucket consumer key


问:
Linq select only newest of duplicates
I have searched through posts but this is bugging me:
I am trying to remove duplicates from an XML and keep only newest:

The XML structure is:

```<code><?xml version="1.0" encoding="utf-8"?>
<scanneditems>
  <item>
    <itemnumber>5701075006328</itemnumber>
    <description>Item 1</description>
    <timestamp>16-06-2017 10:40:39</timestamp>
   </item>
  <item>
    <itemnumber>5701075006328</itemnumber>
    <description>Item 1 duplicate</description>
    <timestamp>08-06-2017 14:25:51</timestamp>
   </item>
</scanneditems>
</code>```

The code is:

```<code>XDocument xDoc = XDocument.Load(@"C:\\fixthis.xml");

var item = xDoc.Element("scanneditems")
    .Elements("item")
    .GroupBy(c => c.Element("itemnumber").Value)

    .OrderByDescending(p => p.Elements("timestamp").ToString());

XDocument doc = new XDocument(new XElement("scanneditems", item));
doc.Save("C:\\fixedfile.xml");
</code>```

Problem: How do I limit result of each duplicate to newest?

答:
If I understand correctly you need to take latest item from each duplicate.

So use OrderBy.. inside grouped items

```<code>XDocument xDoc = XDocument.Load(@"C:\\fixthis.xml");
var items =
    xDoc.Element("scanneditems")
        .Elements("item")
        .GroupBy(c => c.Element("itemnumber").Value)
        .Select(g => g.OrderByDescending(c => c.Element("timestamp").Value).First());

var doc = new XDocument(new XElement("scanneditems", items));
doc.Save("C:\\fixedfile.xml");
</code>```

Title: Linq select only newest of duplicates

Body:
I have searched through posts but this is bugging me:
I am trying to remove duplicates from an XML and keep only newest:

The XML structure is:

<?xml version="1.0" encoding="utf-8"?>
<scanneditems>
  <item>
    <itemnumber>5701075006328</itemnumber>
    <description>Item 1</description>
    <timestamp>16-06-2017 10:40:39</timestamp>
   </item>
  <item>
    <itemnumber>5701075006328</itemnumber>
    <description>Item 1 duplicate</description>
    <timestamp>08-06-2017 14:25:51</timestamp>
   </item>
</scanneditems>

The code is:

XDocument xDoc = XDocument.Load(@"C:\\fixthis.xml");

var item = xDoc.Element("scanneditems")
    .Elements("item")
    .GroupBy(c => c.Element("itemnumber").Value)

    .OrderByDescending(p => p.Elements("timestamp").ToString());

XDocument doc = new XDocument(new XElement("scanneditems", item));
doc.Save("C:\\fixedfile.xml");

Problem: How do I limit result of each duplicate to newest?

Body:
If I understand correctly you need to take latest item from each duplicate.

So use OrderBy.. inside grouped items

XDocument xDoc = XDocument.Load(@"C:\\fixthis.xml");
var items =
    xDoc.Element("scanneditems")
        .Elements("item")
        .GroupBy(c => c.Element("itemnumber").Value)
        .Select(g => g.OrderByDescending(c => c.Element("timestamp").Value).First());

var doc = new XDocument(new XElement("scanneditems", items));
doc.Save("C:\\fixedfile.xml");


问:
web3j not working with contract function?
This is my simple contract in my private network

```<code>contract AB {
    /* This creates an array with all balances */
    mapping (address => uint256) public balanceOf;

    /* Initializes contract with initial supply tokens to the creator of the contract */
    function AB () {
        balanceOf[msg.sender] = 1200;              // Give the creator all initial tokens
    }

    /* Send coins */
    function transfer(address _to, uint256 _value) {
        if (balanceOf[msg.sender] < _value) throw;           // Check if the sender has enough
        if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
        balanceOf[msg.sender] -= _value;                     // Subtract from the sender
        balanceOf[_to] += _value;                            // Add the same to the recipient
    }

    function gettokenBalance(address to)constant returns (uint256){
          return balanceOf[to];
       }
}
</code>```

I have generated smart contract wrappers using web3J and there is function like

```<code>public Future<Uint256> gettokenBalance(Address to) {
        Function function = new Function("gettokenBalance",
                Arrays.<Type>asList(to),
                Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}));
        return executeCallSingleValueReturnAsync(function);
    }
</code>```

when i am trying to access my contract function like

```<code>AB newAB = AB.load(contractaddress, web3j, credentials, gasprice, gaslimit);
        Future<Uint256> result = newAB.gettokenBalance(new Address(address));
        LOGGER.info("result:::"+result.get());
</code>```

it is giving me a exception like

```<code> java.util.concurrent.ExecutionException: java.lang.IndexOutOfBoundsException: Index: 0
    at java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:357) ~[na:1.8.0_91]
    at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1895) ~[na:1.8.0_91]
    at com.belrium.service.UserWalletService.check(UserWalletService.java:197) ~[classes/:na]
    at com.belrium.controller.UserController.check(UserController.java:119) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_91]
</code>```

Please help.

答:
Futures are asynchronous, so get() will try to fetch the result value, which is currently still being computed. It only works after the computation is done.

I think the Java Future API does not support what you want. Instead, I can recommend using CompletableFuture, which has a join() method that does exactly what you want: wait and get.

When I generated code from contracts, I had the same problem. So I ditched the generator and replaced all the Futures in my generated code with CompletableFutures. I think it's an oversight from web3j, although maybe there is a different way to deal with this problem that I don't know about!

Body:
This is my simple contract in my private network

contract AB {
    /* This creates an array with all balances */
    mapping (address => uint256) public balanceOf;

    /* Initializes contract with initial supply tokens to the creator of the contract */
    function AB () {
        balanceOf[msg.sender] = 1200;              // Give the creator all initial tokens
    }

    /* Send coins */
    function transfer(address _to, uint256 _value) {
        if (balanceOf[msg.sender] < _value) throw;           // Check if the sender has enough
        if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
        balanceOf[msg.sender] -= _value;                     // Subtract from the sender
        balanceOf[_to] += _value;                            // Add the same to the recipient
    }

    function gettokenBalance(address to)constant returns (uint256){
          return balanceOf[to];
       }
}

I have generated smart contract wrappers using web3J and there is function like

public Future<Uint256> gettokenBalance(Address to) {
        Function function = new Function("gettokenBalance",
                Arrays.<Type>asList(to),
                Arrays.<TypeReference<?>>asList(new TypeReference<Uint256>() {}));
        return executeCallSingleValueReturnAsync(function);
    }

when i am trying to access my contract function like

AB newAB = AB.load(contractaddress, web3j, credentials, gasprice, gaslimit);
        Future<Uint256> result = newAB.gettokenBalance(new Address(address));
        LOGGER.info("result:::"+result.get());

it is giving me a exception like

 java.util.concurrent.ExecutionException: java.lang.IndexOutOfBoundsException: Index: 0
    at java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:357) ~[na:1.8.0_91]
    at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1895) ~[na:1.8.0_91]
    at com.belrium.service.UserWalletService.check(UserWalletService.java:197) ~[classes/:na]
    at com.belrium.controller.UserController.check(UserController.java:119) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_91]

Please help.


答:
word = word + sep + word;

Think carefully about what this does the second time around. Hint: word has changed since the first time around.

Solution: Use a different variable to hold the results, so that you append the same word each time. (Free hint: use a StringBuffer or StringBuilder instead.)

Title: String Pattern Question - Core Java (repeatSeparator)


问:
How display 'dropdown-menu' without submit button?
I would like create and display menu for my element only after click in small button.

I have a small button which run function "doAction"

```<code><i class="fa fa-ellipsis-h" ng-click="doAction(\'OpenMenu\', $event)"></i>
</code>```

In my function 'doAction' a would like fetch position X Y from event mouse click and display in this place my menu.
Almost everything work... I have problem with 'dropdown-menu'.
More precisely, i see button discribed above and button from this code (id=test):

```<code> var menu = angular.element('<div class="dropdown">' +
                '<button id="test" class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown"><span class="caret"></span></button>'+
                '<ul class="dropdown-menu">'+
                '<li><a href="#">HTML</a></li>'+
                '<li><a href="#">CSS</a></li>'+
                '<li><a href="#">JavaScript</a></li>'+
                '</ul>'+
                '</div>');

            menu.css({
                position: 'absolute',
                left: event.clientX,
                top: event.clientY,
                zIndex: '999'
            });

            var body = angular.element(document).find('body').eq(0);
            body.append(menu);
</code>```

Now, i have to click on first button 'fa-ellipsis-h' later button "test", and only then i see my menu.
I don't know how remove button 'id = test' from variable "menu" and open menu immediately after the press first  button 'fa fa-ellipsis-h'.

答:
First, are you sure that you need those single quotes escaped in your function? I copied and pasted your HTML into a jsbin, and it immediately failed because of that.

If I understand what you're asking, you want your menu to open after the first click, instead of after clicking the  element, and THEN clicking the test button.

It is working for me here in this bin: working example
Menu

Clicking the  immediately opens the menu (I added in some text for those elements, because I don't have the fontawesome library included).

Body:
I would like create and display menu for my element only after click in small button.

I have a small button which run function "doAction"

In my function 'doAction' a would like fetch position X Y from event mouse click and display in this place my menu.
Almost everything work... I have problem with 'dropdown-menu'.
More precisely, i see button discribed above and button from this code (id=test):

 var menu = angular.element('
' +
                '<button id="test" class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown"></button>'+
                '
'+
                '
HTML
'+
                '
CSS
'+
                '
JavaScript
'+
                '
'+
                '
');

            menu.css({
                position: 'absolute',
                left: event.clientX,
                top: event.clientY,
                zIndex: '999'
            });

            var body = angular.element(document).find('body').eq(0);
            body.append(menu);

Now, i have to click on first button 'fa-ellipsis-h' later button "test", and only then i see my menu.
I don't know how remove button 'id = test' from variable "menu" and open menu immediately after the press first  button 'fa fa-ellipsis-h'.

Body:
First, are you sure that you need those single quotes escaped in your function? I copied and pasted your HTML into a jsbin, and it immediately failed because of that.

If I understand what you're asking, you want your menu to open after the first click, instead of after clicking the <i> element, and THEN clicking the test button.

It is working for me here in this bin: working example
<i class="fa fa-ellipsis-h" data-ng-click="doAction('OpenMenu', $event)">Menu</i>

Clicking the  immediately opens the menu (I added in some text for those elements, because I don't have the fontawesome library included).


问:
Can't print elements in a DIV tag
I am using a Drag-able and re-sizeable DIV's in this HTML file. Where the user will place the DIV tag to his desired place in a main parent DIV tag. Now I want to print this main DIV tag, but the problem is that the code which I'm using to PRINT this main DIV is printing in a sequence, like not the way user has arranged the DIV's. Also it doesn't take up  the main DIV background IMAGE.
here is the code.

JAVASCRIPT & CSS

```<code><link rel="stylesheet" type="text/css" href="byrei-dyndiv_0.5.css">
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.1.min.js" > </script>
<script type="text/javascript" src="byrei-dyndiv_1.0rc1.js"></script>
<script language="javascript" type="text/javascript">
function change(boxid,divtoaffect) {
content = document.getElementById("" + boxid + "").value.replace(/\n/g, '<br>');
document.getElementById(divtoaffect).innerHTML = content;
}
function select1() {
test=document.getElementById("changeMe");
test.style.backgroundImage="url('Sunset.jpg')";
}

function select2() {
test=document.getElementById("changeMe");
test.style.backgroundImage="url('Blue hills.jpg')";
}

    function PrintElem(elem)
    {
        Popup($(elem).text());
    }

    function Popup(data)
    {
        var mywindow = window.open('', 'my div', 'height=400,width=600');
        mywindow.document.write('<html><head><title>my div</title>');
        /*optional stylesheet*/ //mywindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />');
        mywindow.document.write('</head><body >');
        mywindow.document.write(data);
        mywindow.document.write('</body></html>');
        mywindow.document.close();
        mywindow.print();
        return true;
    }

//  Print DIV

function printContent(id){
                            str=document.getElementById(id).innerHTML
                            newwin=window.open('','printwin','left=100,top=100,width=400,height=400')
                            newwin.document.write('<HTML>\n<HEAD>\n')
                            newwin.document.write('<TITLE>Print Page</TITLE>\n')
                            newwin.document.write('<script>\n')
                            newwin.document.write('function chkstate(){\n')
                            newwin.document.write('if(document.readyState=="complete"){\n')
                            newwin.document.write('window.close()\n')
                            newwin.document.write('}\n')
                            newwin.document.write('else{\n')
                            newwin.document.write('setTimeout("chkstate()",2000)\n')
                            newwin.document.write('}\n')
                            newwin.document.write('}\n')
                            newwin.document.write('function print_win(){\n')
                            newwin.document.write('window.print();\n')
                            newwin.document.write('chkstate();\n')
                            newwin.document.write('}\n')
                            newwin.document.write('<\/script>\n')
                            newwin.document.write('</HEAD>\n')
                            newwin.document.write('<BODY onload="print_win()">\n')
                            newwin.document.write(str)
                            newwin.document.write('</BODY>\n')
                            newwin.document.write('</HTML>\n')
                            newwin.document.close()
                        }

</script>
</head>
<body>
<style type="text/css">
#output1,#output2 ,#output3 {
width: 300px;
word-wrap: break-word;
border: solid 1px black;
}

</style>
</code>```

HTML

```<code><div style="width:650px;height:300px;" id="changeMe" >

        <table cellpadding="5" cellspacing="0" width="100%" style="margin:auto;">
            <tr>
                <td><div class="dynDiv_moveDiv" id="output1" style="font-weight:bold;height:20px;margin-top:40px;">
                    <div class="dynDiv_resizeDiv_tl"></div>
                     <div class="dynDiv_resizeDiv_tr"></div>
                     <div class="dynDiv_resizeDiv_bl"></div>
                     <div class="dynDiv_resizeDiv_br"></div>
                    </div>
                    </td>
            </tr>
            <tr>
                <td><div class="dynDiv_moveDiv" id="output2" style="height:40px;margin-top:30px;">
                    <div class="dynDiv_resizeDiv_tl"></div>
                     <div class="dynDiv_resizeDiv_tr"></div>
                     <div class="dynDiv_resizeDiv_bl"></div>
                     <div class="dynDiv_resizeDiv_br"></div>
                    </div></td>
            </tr>
            <tr>
                <td><div class="dynDiv_moveDiv" id="output3" style="height:50px;margin-top:40px;">
                    <div class="dynDiv_resizeDiv_tl"></div>
                     <div class="dynDiv_resizeDiv_tr"></div>
                     <div class="dynDiv_resizeDiv_bl"></div>
                     <div class="dynDiv_resizeDiv_br"></div>
                    </div></td>
            </tr>
        </table>
    </div>
<tr>
    <td align="center"><input type="button" value="Print Div" onClick="printContent('changeMe')" />
    </td>
</tr>
</code>```

here is the image to be more clearer

答:
For Chrome and Safari you can add the following in your CSS:</p>

```<code>@media print
{
    * {-webkit-print-color-adjust:exact;}
}
</code>```

Title: Can't print elements in a DIV tag

Body:
I am using a Drag-able and re-sizeable DIV's in this HTML file. Where the user will place the DIV tag to his desired place in a main parent DIV tag. Now I want to print this main DIV tag, but the problem is that the code which I'm using to PRINT this main DIV is printing in a sequence, like not the way user has arranged the DIV's. Also it doesn't take up  the main DIV background IMAGE.
here is the code.

JAVASCRIPT & CSS

<link rel="stylesheet" type="text/css" href="byrei-dyndiv_0.5.css">

HTML

    <input type="button" value="Print Div" onClick="printContent('changeMe')" />

here is the image to be more clearer

Body:
For Chrome and Safari you can add the following in your CSS:

@media print
{
    * {-webkit-print-color-adjust:exact;}
}


问:
(PHP) Web form inserting blank values into the database! Error - array(1) { [“g-recaptcha-response”]=> string(484)-
When sending information from my web form, it inserts blank values into the database. The auto increments on the ID work fine. When performing an Var Dump $_POST, I get this response:

```<code>array(1) { ["g-recaptcha-response"]=> string(484) + random letters and numbers
</code>```

I am trying to pass three values into my database from the user. First Name. Last Name and Email. It checks the values on my web site and looks like the Google Recaptcha V2 is working the way it was intended. I think it has something to do with the Recaptcha PHP script is not passing it to my insert PHP script.

Any Ideas? Thanks for taking the time to help me out.

PHP:

```<code><?php
function post_captcha($user_response) {
    $fields_string = '';
    $fields = array(
        'secret' => '',
        'response' => $user_response
    );
    foreach($fields as $key=>$value)
    $fields_string .= $key . '=' . $value . '&';
    $fields_string = rtrim($fields_string, '&');

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
    curl_setopt($ch, CURLOPT_POST, count($fields));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);

    $result = curl_exec($ch);
    curl_close($ch);

    return json_decode($result, true);
}

// Call the function post_captcha
$res = post_captcha($_POST['g-recaptcha-response']);

if (!$res['success']) {
    // What happens when the CAPTCHA wasn't checked
    echo '<p>Please Check the Security CAPTCHA Box.</p><br>';
} else {
    // If CAPTCHA is successfully completed...
    // Paste mail function or whatever else you want to happen here!

$dbhost = "localhost";
$dbname = "";
$dbusername = "";
$dbpassword = "";

try {
$link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$statement = $link->prepare("INSERT INTO MailV2(Fname, Lname, Email) VALUES(:Fname, :Lname, :Email)");

$FirstName = $_POST['Fname'];
$LastName = $_POST['Lname'];
$Email = $_POST['Email'];

$statement->execute(array(
":Fname" => "$FirstName",
":Lname" => "$LastName",
":Email" => "$Email"));
 // Echo Successful attempt
        echo "<p Data added to database.</p></br></br>";

    }
    catch (PDOException $e) {
        echo "Error: " . $e->getMessage();
    }
      }
?>
</code>```

HTML:

```<code><article class="contact-form">
    <form action="" method="POST">
        <div class="col-md-5 col-md-offset-1 contact-form-left">
            <input class="Fname" type="text" placeholder="FIRST NAME*">
            <input class="Lname" type="text" placeholder="LAST NAME*">
            <input class="Email" type="email" placeholder="EMAIL*">
        </div>
        <div class="col-md-5 contact-form-right text-right">
            <div class="g-recaptcha" data-sitekey=""></div>
            <br>
            <input type="submit" class="submit-btn" value="Subscribe">
        </div>
    </form>
</article>
</code>```

答: In your html form, the name and email fields don't have a name attribute so they aren't included in the response.</p>

Body:
When sending information from my web form, it inserts blank values into the database. The auto increments on the ID work fine. When performing an Var Dump $_POST, I get this response:

array(1) { ["g-recaptcha-response"]=> string(484) + random letters and numbers

I am trying to pass three values into my database from the user. First Name. Last Name and Email. It checks the values on my web site and looks like the Google Recaptcha V2 is working the way it was intended. I think it has something to do with the Recaptcha PHP script is not passing it to my insert PHP script.

Any Ideas? Thanks for taking the time to help me out.

PHP:

<?php
function post_captcha($user_response) {
    $fields_string = '';
    $fields = array(
        'secret' => '',
        'response' => $user_response
    );
    foreach($fields as $key=>$value)
    $fields_string .= $key . '=' . $value . '&';
    $fields_string = rtrim($fields_string, '&');

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
    curl_setopt($ch, CURLOPT_POST, count($fields));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);

    $result = curl_exec($ch);
    curl_close($ch);

    return json_decode($result, true);
}

// Call the function post_captcha
$res = post_captcha($_POST['g-recaptcha-response']);

if (!$res['success']) {
    // What happens when the CAPTCHA wasn't checked
    echo '
Please Check the Security CAPTCHA Box.

';
} else {
    // If CAPTCHA is successfully completed...
    // Paste mail function or whatever else you want to happen here!

$dbhost = "localhost";
$dbname = "";
$dbusername = "";
$dbpassword = "";

try {
$link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$statement = $link->prepare("INSERT INTO MailV2(Fname, Lname, Email) VALUES(:Fname, :Lname, :Email)");

$FirstName = $_POST['Fname'];
$LastName = $_POST['Lname'];
$Email = $_POST['Email'];

$statement->execute(array(
":Fname" => "$FirstName",
":Lname" => "$LastName",
":Email" => "$Email"));
 // Echo Successful attempt
        echo "getMessage();
    }
      }
?>

HTML:

    <form action="" method="POST">

            <input class="Fname" type="text" placeholder="FIRST NAME*">
            <input class="Lname" type="text" placeholder="LAST NAME*">
            <input class="Email" type="email" placeholder="EMAIL*">

            <input type="submit" class="submit-btn" value="Subscribe">

    </form>


问:
Laravel: left join query
I have such SQL query, which works fine:

```<code>SELECT A.program_id FROM A
LEFT JOIN B
ON A.program_id = B.program_id
WHERE
B.program_id IS NULL
</code>```

But i want it to rewrite into LARAVEL style, like this:

```<code>\DB::table('A')
->join('B', 'A.program_id', '=', 'B.program_id')
->select('A.program_id')
->whereNull('B.program_id')
->get()->toArray();
</code>```

But this code returns me 0 results.

答:
You are using join instead of left join

Try this

```<code>\DB::table('A')
->leftjoin('B', 'A.program_id', '=', 'B.program_id')
->select('A.program_id')
->whereNull('B.program_id')
->where('A.student_id', '=', 5)
->get()->toArray();
</code>```

It will produce a query like

Title: Laravel: left join query

Body:
I have such SQL query, which works fine:

SELECT A.program_id FROM A
LEFT JOIN B
ON A.program_id = B.program_id
WHERE
B.program_id IS NULL

But i want it to rewrite into LARAVEL style, like this:

\DB::table('A')
->join('B', 'A.program_id', '=', 'B.program_id')
->select('A.program_id')
->whereNull('B.program_id')
->get()->toArray();

But this code returns me 0 results.

Body:
You are using join instead of left join

Try this

\DB::table('A')
->leftjoin('B', 'A.program_id', '=', 'B.program_id')
->select('A.program_id')
->whereNull('B.program_id')
->where('A.student_id', '=', 5)
->get()->toArray();

It will produce a query like


问:
problem regarding crystal reports
Actually when I drag fields from a database onto a report and when I run the report, only the first row data is shown i.e. if CourseID field is dragged onto a report and when I run it should show CourseID1 and below it CourseID2. But, it shows only CourseID1. I know it is a silly thing, but as I'm new to crystal reports, I'm unable to solve it. So, please help me out...thanks in advance...</p>

答: Make sure you are dragging the field into the Details section of the report.  If it is in the header or other section, you may get only the first row.</p>

Title: problem regarding crystal reports


问:
IS PHAsset image unique globally for all iPhones?
When fetching images using the Photo framework, I am getting all images of the gallery from the PHAsset object. My question is if the images from PHAsset are globally unique or are they device specific. Can I use the same PHAsset image on different iPhones? i don't want to convert the UIImage to NSData and convert it again from NSData to UIImage.</p>

```<code>PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];

//set up fetch options, mediaType is image.
PHFetchOptions *options = [[PHFetchOptions alloc] init];
options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
options.predicate = [NSPredicate predicateWithFormat:@"mediaType = %d",PHAssetMediaTypeImage];

for (NSInteger i =0; i < smartAlbums.count; i++) {
    PHAssetCollection *assetCollection = smartAlbums[i];
    PHFetchResult *assetsFetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:options];

    NSLog(@"sub album title is %@, count is %ld", assetCollection.localizedTitle, (unsigned long)assetsFetchResult.count);
    if (assetsFetchResult.count > 0 && ![assetCollection.localizedTitle isEqualToString: @"Recently Deleted"]) {

        for (PHAsset *asset in assetsFetchResult) {
            PHImageRequestOptions *option = [PHImageRequestOptions new];
            option.synchronous = YES;

            [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:CGSizeMake(self.view.frame.size.width, self.view.frame.size.height-100) contentMode:PHImageContentModeAspectFit options:option resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                [mutArrAsset addObject:asset];

                [self.imagesURLArray addObject:result];
            }];

            NSLog(@"asset are %@", asset);
        }}}
</code>```

答:
A PHAsset represent a pointer to an image in the user's photo library.  People have different images on their phone so it doesn't make sense to pass that pointer to a different phone.  PHAsset's id is explicted called localIdentifier for this reason.

If you want to transfer an image from one device to a different device you have to transfer it as NSData.

Body:
When fetching images using the Photo framework, I am getting all images of the gallery from the PHAsset object. My question is if the images from PHAsset are globally unique or are they device specific. Can I use the same PHAsset image on different iPhones? i don't want to convert the UIImage to NSData and convert it again from NSData to UIImage.

PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];

//set up fetch options, mediaType is image.
PHFetchOptions *options = [[PHFetchOptions alloc] init];
options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
options.predicate = [NSPredicate predicateWithFormat:@"mediaType = %d",PHAssetMediaTypeImage];

for (NSInteger i =0; i < smartAlbums.count; i++) {
    PHAssetCollection *assetCollection = smartAlbums[i];
    PHFetchResult *assetsFetchResult = [PHAsset fetchAssetsInAssetCollection:assetCollection options:options];

    NSLog(@"sub album title is %@, count is %ld", assetCollection.localizedTitle, (unsigned long)assetsFetchResult.count);
    if (assetsFetchResult.count > 0 && ![assetCollection.localizedTitle isEqualToString: @"Recently Deleted"]) {

        for (PHAsset *asset in assetsFetchResult) {
            PHImageRequestOptions *option = [PHImageRequestOptions new];
            option.synchronous = YES;

            [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:CGSizeMake(self.view.frame.size.width, self.view.frame.size.height-100) contentMode:PHImageContentModeAspectFit options:option resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                [mutArrAsset addObject:asset];

                [self.imagesURLArray addObject:result];
            }];

            NSLog(@"asset are %@", asset);
        }}}


问:
Capture speaker output
I've seen that I can capture the microphone and sound-files with elements in the Windows.Media.Audio namespace. I'm looking to capture the speaker output, though. For example, I click on something and the system sounds the alert sound - I want to be able to capture that.

Is there any way of doing that using elements in Windows.Media.Audio (instead of going more low level into Win32 calls)?

答:
Well, even with "low level Win32 calls", you can't do any loopback recording in UWP.

This is traditionally done with WASAPI, but due to the sandboxed execution of universal applications, you can't open any capture streams on audio render devices in WASAPI.

In general, if you dive into COM APIs which have been ported to UWP, you will notice that there have been a lot of restrictions.

Title: Capture speaker output


问:
Maven: Error putting Weblogic libs into local repository
I want to put Weblogic libs into local repository (Installing and Configuring Maven for Build Automation and Dependency Management) I have the Weblogic version is 12.1.2 installed in my workstation.

I run this command:

```<code>mvn -X com.oracle.maven:oracle-maven-sync:push -Doracle-maven-sync.oracleHome=C:\Oracle\product\11.2.0\client_x86 -Doracle-maven-sync.testingOnly=false
</code>```

but I got this error:

```<code>[ERROR] Failed to execute goal com.oracle.maven:oracle-maven-sync:12.2.1-2-0:push (default-cli) on project standalone-pom: Synchronization execution failed:
No resources were processed by the sync plugin -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal com.oracle.maven:oracle-maven-sync:12.2.1-2-0:push (default-cli)
on project standalone-pom: Synchronization execution failed
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:216)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
        at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
        at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
        at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
        at org.apache.maven.cli.MavenCli.execute(MavenCli.java:862)
        at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:286)
        at org.apache.maven.cli.MavenCli.main(MavenCli.java:197)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
        at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
        at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.plugin.MojoExecutionException: Synchronization execution failed
        at com.oracle.maven.sync.ODMPushMojo.execute(ODMPushMojo.java:242)
        at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
        ... 20 more
Caused by: com.oracle.maven.sync.SyncException: No resources were processed by the sync plugin
        at com.oracle.maven.sync.ODMPusher.handleError(ODMPusher.java:458)
        at com.oracle.maven.sync.ODMPusher.push(ODMPusher.java:117)
        at com.oracle.maven.sync.ODMPushMojo.execute(ODMPushMojo.java:240)
        ... 22 more
[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

C:\Users\carbonell>
</code>```

答:
Check that you refer to weblogic's libraries from maven as a dependency in the following way:

```<code><dependency>
  <groupId>com.oracle.weblogic</groupId>
  <artifactId>weblogic-server-pom</artifactId>
  <version>12.1.2-0-0</version>
  <type>pom</type>
  <scope>provided</scope>
</dependency>
</code>```

Then, you must try this, from this reference:

```<code>mvn com.oracle.maven:oracle-maven-sync:push -Doracle-maven-sync.oracleHome=%MW_HOME% -Doracle-maven-sync.testingOnly=false
</code>```

If nothing works, see also this very related issue

Body:
I want to put Weblogic libs into local repository (Installing and Configuring Maven for Build Automation and Dependency Management) I have the Weblogic version is 12.1.2 installed in my workstation.

I run this command:

mvn -X com.oracle.maven:oracle-maven-sync:push -Doracle-maven-sync.oracleHome=C:\Oracle\product\11.2.0\client_x86 -Doracle-maven-sync.testingOnly=false

but I got this error:

[ERROR] Failed to execute goal com.oracle.maven:oracle-maven-sync:12.2.1-2-0:push (default-cli) on project standalone-pom: Synchronization execution failed:
No resources were processed by the sync plugin -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal com.oracle.maven:oracle-maven-sync:12.2.1-2-0:push (default-cli)
on project standalone-pom: Synchronization execution failed
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:216)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
        at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
        at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
        at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
        at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
        at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
        at org.apache.maven.cli.MavenCli.execute(MavenCli.java:862)
        at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:286)
        at org.apache.maven.cli.MavenCli.main(MavenCli.java:197)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
        at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
        at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
        at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.plugin.MojoExecutionException: Synchronization execution failed
        at com.oracle.maven.sync.ODMPushMojo.execute(ODMPushMojo.java:242)
        at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
        at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:208)
        ... 20 more
Caused by: com.oracle.maven.sync.SyncException: No resources were processed by the sync plugin
        at com.oracle.maven.sync.ODMPusher.handleError(ODMPusher.java:458)
        at com.oracle.maven.sync.ODMPusher.push(ODMPusher.java:117)
        at com.oracle.maven.sync.ODMPushMojo.execute(ODMPushMojo.java:240)
        ... 22 more
[ERROR]
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

C:\Users\carbonell>

Body:
Check that you refer to weblogic's libraries from maven as a dependency in the following way:

<dependency>
  <groupId>com.oracle.weblogic</groupId>
  <artifactId>weblogic-server-pom</artifactId>
  <version>12.1.2-0-0</version>
  <type>pom</type>
  <scope>provided</scope>
</dependency>

Then, you must try this, from this reference:

mvn com.oracle.maven:oracle-maven-sync:push -Doracle-maven-sync.oracleHome=%MW_HOME% -Doracle-maven-sync.testingOnly=false

If nothing works, see also this very related issue


问:
Changing the Date Format for GROUPED dates in a PIVOT TABLE
I'm working in Excel 2010

Let's say you have a legitimate date field in your raw data with dates such as 1/1/2015. Then you create a pivot table with your date field in the row labels.

Now assume you want to show results by month, so you right click "Group Field" and select to group it by month.

Now, your data is displayed in months with the Mmm format.  How would you change it the Mmmm format? Or what if you want to display it as a Number (i.e. Jan is displayed as 1)

How about for dates that have timestamps and you group by Day. The pivot table will display the date as D-Mmm. What if I want MM/DD/YYYY?

Yes, I've already tried changing it through right clicking -> field settings -> number format.  It didn't work.

答: If you select the columns where the date is broken up (within the pivot - years, quarter, etc.) and go data-ungroup.  It will get you to the date format.</p>


问:
React Native Stylesheet: what does {flex:1} do?
React Native uses flexbox for layout. In all of the examples I've seen, they do something like this:

```<code>var styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row'
  }
});
</code>```

I'm curious about the flex: 1 part. Based on Chris Coyier's definition here https://css-tricks.com/snippets/css/a-guide-to-flexbox/, flex: 1 should be the same as flex-grow: 1, but to me it looks like flex: 1 in React Native is equivalent to display: flex in CSS.

Here's a CodePen that demonstrates that flex: 1 the way React Native examples use it doesn't do anything in CSS:

http://codepen.io/johnnyo/pen/BoKbpb

It's not until we use display: flex in CSS until flexbox starts to work:

http://codepen.io/johnnyo/pen/epZXgz

So does this mean that flex: 1 in React Native is equivalent to display: flex in CSS?

答:
Like you I struggled to understand this tag that isn't documented properly on Facebook Code, but I eventually discovered that it does two things:

Containers consider any children with a flex attribute to have a height of 0 for the purpose of determining how much space they take up.

Components with flex: X expand to take up any room remaining in their container after other components have been laid out. They share this extra space in proportion with their X values.

The first item is why flex: 1 can appear to have the same effect as display: flex. Consider the following JSX code:

```<code><ExampleAppContainer>
    <Text>
        I get printed.
    </Text>
    <Text style={{flex: 1}}>
        But I don't :(
    </Text>
</ExampleAppContainer>
</code>```

Only the first text component gets printed, because the second one is considered to have a height of 0. ExampleAppContainer allocates enough space for the first text component, and there isn't any room for the second one to expand.

Now consider this code:

```<code><ExampleAppContainer style={{flex:1}}>
    <Text>
        I get printed.
    </Text>
    <Text style={{flex: 1}}>
        And so do I!
    </Text>
</ExampleAppContainer>
</code>```

Since ExampleAppContainer has flex: 1, it expands to take up as much room as it can. Assuming that it is the root component for the React part of your app, this is usually going to be the entire phone screen. Next it allocates sufficient space for the first text component, and allows the second text component to expand, taking up the rest of the screen.

In this fashion you will often need to apply flex: 1 all the way down you component hierarchy in order to allow your innermost components with flex: N room to expand properly.

Body:
React Native uses flexbox for layout. In all of the examples I've seen, they do something like this:

var styles = StyleSheet.create({
  container: {
    flex: 1,
    flexDirection: 'row'
  }
});

I'm curious about the flex: 1 part. Based on Chris Coyier's definition here https://css-tricks.com/snippets/css/a-guide-to-flexbox/, flex: 1 should be the same as flex-grow: 1, but to me it looks like flex: 1 in React Native is equivalent to display: flex in CSS.

Here's a CodePen that demonstrates that flex: 1 the way React Native examples use it doesn't do anything in CSS:

http://codepen.io/johnnyo/pen/BoKbpb

It's not until we use display: flex in CSS until flexbox starts to work:

http://codepen.io/johnnyo/pen/epZXgz

So does this mean that flex: 1 in React Native is equivalent to display: flex in CSS?

Body:
Like you I struggled to understand this tag that isn't documented properly on Facebook Code, but I eventually discovered that it does two things:

Containers consider any children with a flex attribute to have a height of 0 for the purpose of determining how much space they take up.

Components with flex: X expand to take up any room remaining in their container after other components have been laid out. They share this extra space in proportion with their X values.

The first item is why flex: 1 can appear to have the same effect as display: flex. Consider the following JSX code:

<ExampleAppContainer>
    <Text>
        I get printed.
    </Text>
    <Text style={{flex: 1}}>
        But I don't :(
    </Text>
</ExampleAppContainer>

Only the first text component gets printed, because the second one is considered to have a height of 0. ExampleAppContainer allocates enough space for the first text component, and there isn't any room for the second one to expand.

Now consider this code:

<ExampleAppContainer style={{flex:1}}>
    <Text>
        I get printed.
    </Text>
    <Text style={{flex: 1}}>
        And so do I!
    </Text>
</ExampleAppContainer>

Since ExampleAppContainer has flex: 1, it expands to take up as much room as it can. Assuming that it is the root component for the React part of your app, this is usually going to be the entire phone screen. Next it allocates sufficient space for the first text component, and allows the second text component to expand, taking up the rest of the screen.

In this fashion you will often need to apply flex: 1 all the way down you component hierarchy in order to allow your innermost components with flex: N room to expand properly.


问:
PCL compilation error LNK2019
I'm currently trying to build PCL so that i can use RTABmaps
I ran into some issues while trying to build the PCL 1.7.2 using the command line to configure it and then build it. I'm using CMake 3.9 and Visual Studios 10 2010 to build the PCL from source. I have already downloaded the dependencies from pointclouds.org/downloads/windows.html and followed the instructions at https://github.com/introlab/rtabmap/wiki/Installation#windows to build the PCL from source.

The build failed and the following errors were shown:
 image

The following are the directories that are in the Path:

C:\Users\qlin\Desktop\RTABmap compilation\pcl-pcl-1.7.2\build\bin;

C:\Program Files\zlib\bin;

C:\Program Files\CMake\bin;

I thought it could be because of the version so i tried anoher version :PCL 1.8. However the same results happened.

I did some research on the error LNK2019 and it says that the linker can't find a matching definition for an external symbol in any of the link files. I saw the tutorial that shows how to build it from source using the CMake Gui but am not ableto solve the problems.

I did some more research and found that this issue has been solved before but the answer to it is too vague for me to understand. it says that there was a mismatch error in between PCL 1.8.0 and 1.6.0 ,and the mismatch was in choosing the Dependencies version of Boost, eigen, flann, OpenNI and VTK 5.8.0.
How do i resolve this error

I hope someone could help me

答:
The all-in-one installer found here makes building PCL a much easier process.
http://unanancyowen.com/en/pcl18/</p>

Title: PCL compilation error LNK2019


问:
CI Active record, Select record from multiple table
I have two table. First is product in which Admin will add the Products and another is product_detail in which vendors will add the detail. Multiple vendors can add same product with the product detail like selling price, offer price etc.

"I want to select products from products table and want to select product detail from product_detail table but only one row of product detail which has less  selling price".

So i want to use CI active records to get the final output as product list with its detail.

答:
You first should make getters and setters in your model and using CI active record + pdo It'as more safe from my point of view.

Best regards.


问:
How do you remove all the alphabetic characters from a string?
I have a string containg alphabetic characters, for example:

254.69 meters

26.56 cm

23.36 inches

100.85 ft

I want to remove all the alphabetic characters (units) from the above mentioned strings so that I can call the double.Parse() method.

答:
Using LINQ:</p>

```<code>using System.Linq;

string input ="57.20000 KG ";
string output = new string(input.Where(c=>(Char.IsDigit(c)||c=='.'||c==',')).ToArray());
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Using LINQ:

using System.Linq;

string input ="57.20000 KG ";
string output = new string(input.Where(c=>(Char.IsDigit(c)||c=='.'||c==',')).ToArray());


问:
Web user expectations
When designing a good Web GUI what expectations can we expect from an end user?

I've come up with the following, but I wonder if there are any others which can suggest..

If I click on a hyperlink it will take me to another page/part of this page

If I tick/untick a checkbox it might alter the page state (enable/disable elements)

If I click on a button I expect it to do something to data.

If I click on a button I expect something to happen immediately (either to the current page, or for me to be taken to another page)

If I have clicked on a hyperlink and it has taken me to another page, I expect to be able to use the Back button to get back to the previous page in a state similar to that which I left it in

If I change something in a form, I can change it back to its previous value if necessary

Unless I click on the 'Submit' button nothing should happen to my data.

If I bookmark/favourite a page then it should show the same related data each time I visit it

If text is underlined and looks like a link, it should be a link and act as one

The reasoning behind this question is more a 'UI from hell' one. For example I have come across pages which checking a tickbox next to a record will delete it, straight away, via ajax. To me that just seems wrong, a checkbox is a toggle - something which a delete operation definitely isn't!

答: If an ad says i've won a million dollars, give me the money. If not, make the ad go away.</p>

OwnerDisplayName: Ash

Title: Web user expectations

LastEditorDisplayName: cletus

OwnerDisplayName: Arve Systad


问:
Uses of static variables inside functions
I have been writing C code for many years, but I recently came accross a feature that I have never used: a static variable inside a function. Therefore, I was wondering what are some ways that you have used this feature and it was the right design decision.

E.g.

```<code>int count(){
    static int n;
    n = n + 1;
    return n;
}
</code>```

is a BAD design decision. why? because later you might want to decrement the count which would involve changing the function parameters, changing all calling code, ...

Hopefully this is clear enough,
thanks!

答:
```<code>void first_call()
{
   static int n = 0;

   if(!n) {
     /* do stuff here only on first call */
     n++;
   }

   /* other stuff here */
}
</code>```

Body:
I have been writing C code for many years, but I recently came accross a feature that I have never used: a static variable inside a function. Therefore, I was wondering what are some ways that you have used this feature and it was the right design decision.

E.g.

int count(){
    static int n;
    n = n + 1;
    return n;
}

is a BAD design decision. why? because later you might want to decrement the count which would involve changing the function parameters, changing all calling code, ...

Hopefully this is clear enough,
thanks!


问:
ORDER one row normally, but second row on other value of a third JOIN row
In these tables

```<code>[   id    -   title   -   meta ]
[    1    -     A     -    A1  ]
[    2    -     A     -    A2  ]
[    3    -     A     -    A3  ]
[    4    -     C     -    A1  ]
[    5    -     C     -    A3  ]
[    6    -     B     -    B1  ]
[    7    -     B     -    B2  ]

[    id     -    rating  -     title     -   meta  ]
[    1      -       9    -       A       -    A1   ]
[    2      -       5    -       C       -    A1   ]
[    3      -       4    -       A       -    A2   ]
[    4      -       6    -       A       -    A3   ]
[    5      -       8    -       B       -    B1   ]
[    6      -       18   -       C       -    A3   ]
[    7      -       12   -       B       -    B2   ]
</code>```

And right now my query is

```<code>"SELECT DISTINCT a.title, a.meta, SUM(ra.vote) as rating
FROM table1 a LEFT JOIN table2 b ON a.meta = b.meta AND a.title = b.title
WHERE a.title = :title
ORDER BY a.title, rating DESC"
</code>```

in my PHP codes, I echo the column title value DISTINCT then i put all the values of the metas where its title is duplicated under it.

Now my problem is that i want to ORDER the metas values depending on its rating

What i get is a random order, But i want it to be like this

```<code>                A
      A1(9) -> A3(6) -> A2(4)

                B
         B2(12) -> B1(8)

                C
         A3(18) -> A1(5)
</code>```

So when i get the metas values, it comes ordered by the rating

something like this

```<code>[   id    -   title   -   meta    -    rating ]
[    1    -     A     -    A1     -       9   ]
[    3    -     A     -    A3     -       6   ]
[    3    -     A     -    A2     -       4   ]
[    5    -     B     -    B2     -       12  ]
[    6    -     C     -    A3     -       18  ]
[    2    -     C     -    A1     -       5   ]
</code>```

答:
What i get is a random order

What you get is not random order but random data.

The query:

```<code>SELECT a.title, a.meta
...
GROUP BY a.meta
</code>```

is invalid SQL. For queries that contain the GROUP BY clause, the SELECT clause is allowed to contain only these kinds of expressions:

expressions that also appear in the GROUP BY clause;

GROUP BY aggregate functions;

expressions that are functionally dependent on expressions that appear in the GROUP BY clause.

The expression a.title from the SELECT clause doesn't fit in any of the above categories.

Prior to version 5.7.5, MySQL accepts such queries but, as the documentation explains:

... a MySQL extension to the standard SQL use of GROUP BY permits the select list, HAVING condition, or ORDER BY list to refer to nonaggregated columns even if the columns are not functionally dependent on GROUP BY columns. This causes MySQL to accept the preceding query. In this case, the server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate, which is probably not what you want. Furthermore, the selection of values from each group cannot be influenced by adding an ORDER BY clause.

What that means in plain English?

Take a look at the first two rows from the second table:

```<code>[    id     -    rating  -     title     -   meta  ]
[    1      -       9    -       A       -    A1   ]
[    2      -       5    -       C       -    A1   ]
</code>```

and the relevant part of the query again:

```<code>SELECT a.title, a.meta
...
GROUP BY a.meta
</code>```

MySQL creates a single group from these two rows (because of GROUP BY a.meta). From one group it generates a row in the result set, using the expressions provided in the SELECT clause.

What value should it choose for a.title? As explained above, it picks one of them without any rule.

It can pick A now but if you run the query after the data in the table changes it can pick C, Also, it can pick C if you export the table and import it into a different server (or on the same server after you remove the original table).

Body:
In these tables

[   id    -   title   -   meta ]
[    1    -     A     -    A1  ]
[    2    -     A     -    A2  ]
[    3    -     A     -    A3  ]
[    4    -     C     -    A1  ]
[    5    -     C     -    A3  ]
[    6    -     B     -    B1  ]
[    7    -     B     -    B2  ]

[    id     -    rating  -     title     -   meta  ]
[    1      -       9    -       A       -    A1   ]
[    2      -       5    -       C       -    A1   ]
[    3      -       4    -       A       -    A2   ]
[    4      -       6    -       A       -    A3   ]
[    5      -       8    -       B       -    B1   ]
[    6      -       18   -       C       -    A3   ]
[    7      -       12   -       B       -    B2   ]

And right now my query is

"SELECT DISTINCT a.title, a.meta, SUM(ra.vote) as rating
FROM table1 a LEFT JOIN table2 b ON a.meta = b.meta AND a.title = b.title
WHERE a.title = :title
ORDER BY a.title, rating DESC"

in my PHP codes, I echo the column title value DISTINCT then i put all the values of the metas where its title is duplicated under it.

Now my problem is that i want to ORDER the metas values depending on its rating

What i get is a random order, But i want it to be like this

                A
      A1(9) -> A3(6) -> A2(4)

                B
         B2(12) -> B1(8)

                C
         A3(18) -> A1(5)

So when i get the metas values, it comes ordered by the rating

something like this

[   id    -   title   -   meta    -    rating ]
[    1    -     A     -    A1     -       9   ]
[    3    -     A     -    A3     -       6   ]
[    3    -     A     -    A2     -       4   ]
[    5    -     B     -    B2     -       12  ]
[    6    -     C     -    A3     -       18  ]
[    2    -     C     -    A1     -       5   ]

Body:
What i get is a random order

What you get is not random order but random data.

The query:

SELECT a.title, a.meta
...
GROUP BY a.meta

is invalid SQL. For queries that contain the GROUP BY clause, the SELECT clause is allowed to contain only these kinds of expressions:

expressions that also appear in the GROUP BY clause;

GROUP BY aggregate functions;

expressions that are functionally dependent on expressions that appear in the GROUP BY clause.

The expression a.title from the SELECT clause doesn't fit in any of the above categories.

Prior to version 5.7.5, MySQL accepts such queries but, as the documentation explains:

... a MySQL extension to the standard SQL use of GROUP BY permits the select list, HAVING condition, or ORDER BY list to refer to nonaggregated columns even if the columns are not functionally dependent on GROUP BY columns. This causes MySQL to accept the preceding query. In this case, the server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate, which is probably not what you want. Furthermore, the selection of values from each group cannot be influenced by adding an ORDER BY clause.

What that means in plain English?

Take a look at the first two rows from the second table:

[    id     -    rating  -     title     -   meta  ]
[    1      -       9    -       A       -    A1   ]
[    2      -       5    -       C       -    A1   ]

and the relevant part of the query again:

SELECT a.title, a.meta
...
GROUP BY a.meta

MySQL creates a single group from these two rows (because of GROUP BY a.meta). From one group it generates a row in the result set, using the expressions provided in the SELECT clause.

What value should it choose for a.title? As explained above, it picks one of them without any rule.

It can pick A now but if you run the query after the data in the table changes it can pick C, Also, it can pick C if you export the table and import it into a different server (or on the same server after you remove the original table).


问:
Oracle ManagedDataAccess.EntityFramework Database.SqlQuery binding parameters by position?
I have the following code:

```<code>        var query = Database.SqlQuery<int>(@"

            SELECT CASE WHEN EXISTS (
                SELECT 1
                FROM v$session v, UsersXxxx u
                WHERE v.Client_Info LIKE u.UserName || ';%'
                AND v.UserName = :schemaName
                AND u.SchemaName = :schemaName
                AND v.module = 'XXXX.exe'
                AND u.UserKey = :userKey)
            THEN 1 ELSE 0 END AS LoggedIn FROM DUAL",

            new OracleParameter("schemaName", schemaName),
            new OracleParameter("userKey", userKey));

        return query.First() != 0;
</code>```

Which produces a "ORA-01008: not all variables bound". I suspected something was up with the way the variables are being bound and ended up trying this:

```<code>        var query = Database.SqlQuery<int>(@"

            SELECT CASE WHEN EXISTS (
                SELECT 1
                FROM v$session v, UsersXxxx u
                WHERE v.Client_Info LIKE u.UserName || ';%'
                AND v.UserName = :schemaName
                AND u.SchemaName = :schemaName
                AND v.module = 'XXXX.exe'
                AND u.UserKey = :userKey)
            THEN 1 ELSE 0 END AS LoggedIn FROM DUAL",

            new OracleParameter("asdf", schemaName),
            new OracleParameter("fdsa", schemaName),
            new OracleParameter("userKey", userKey));

        return query.First() != 0;
</code>```

Which works like a charm! I poked around docs and found a blurb that says:

"Binding scalar parameters is supported with ODP.NET and Entity Framework. In Entity Framework, parameter binding by name is supported. Binding by position is not supported."

Somehow I think the docs are lying to me and it's trying to bind by position. I remember fixing this once long ago before the EF support, but I cannot remember what the fix was, much less how to apply the same technique in EF.

My workaround, although kludgy, works but isn't there an option somewhere to make it bind by name instead of by position? If so, what is it?

答:
In in a recent version of the managed driver you are able to add a web.config entry that sets BindByName to true by default.

```<code><oracle.manageddataaccess.client>
<version number="*">
  <settings>
    <setting name="BindByName" value="true" />
  </settings>
</version>
</oracle.manageddataaccess.client>
</code>```

Body:
I have the following code:

        var query = Database.SqlQuery<int>(@"

            SELECT CASE WHEN EXISTS (
                SELECT 1
                FROM v$session v, UsersXxxx u
                WHERE v.Client_Info LIKE u.UserName || ';%'
                AND v.UserName = :schemaName
                AND u.SchemaName = :schemaName
                AND v.module = 'XXXX.exe'
                AND u.UserKey = :userKey)
            THEN 1 ELSE 0 END AS LoggedIn FROM DUAL",

            new OracleParameter("schemaName", schemaName),
            new OracleParameter("userKey", userKey));

        return query.First() != 0;

Which produces a "ORA-01008: not all variables bound". I suspected something was up with the way the variables are being bound and ended up trying this:

        var query = Database.SqlQuery<int>(@"

            SELECT CASE WHEN EXISTS (
                SELECT 1
                FROM v$session v, UsersXxxx u
                WHERE v.Client_Info LIKE u.UserName || ';%'
                AND v.UserName = :schemaName
                AND u.SchemaName = :schemaName
                AND v.module = 'XXXX.exe'
                AND u.UserKey = :userKey)
            THEN 1 ELSE 0 END AS LoggedIn FROM DUAL",

            new OracleParameter("asdf", schemaName),
            new OracleParameter("fdsa", schemaName),
            new OracleParameter("userKey", userKey));

        return query.First() != 0;

Which works like a charm! I poked around docs and found a blurb that says:

"Binding scalar parameters is supported with ODP.NET and Entity Framework. In Entity Framework, parameter binding by name is supported. Binding by position is not supported."

Somehow I think the docs are lying to me and it's trying to bind by position. I remember fixing this once long ago before the EF support, but I cannot remember what the fix was, much less how to apply the same technique in EF.

My workaround, although kludgy, works but isn't there an option somewhere to make it bind by name instead of by position? If so, what is it?

Body:
In in a recent version of the managed driver you are able to add a web.config entry that sets BindByName to true by default.

<oracle.manageddataaccess.client>
<version number="*">
  <settings>
    <setting name="BindByName" value="true" />
  </settings>
</version>
</oracle.manageddataaccess.client>


问:
How to know if textarea cursor reach to the last of the field?
In this example i want to add margin when cursor reach or touch send button and when touched the send button needed to add margin top. As same like current facebook comment field, when cursor touched sticker or emoji icon the icons are shifted to the bottom of fields.

autosize($('textarea'));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>textarea { width:99%;min-height:15px }
div { position:relative }
button { position:absolute;right:10px;bottom:8px }</code>```

<textarea class="textarea"></textarea>
<button>
Send
</button>

```

答:
Here is what you are looking for, try it out:

autosize($('textarea'));

$("#send").on('click', function() {
  console.log("You clicked send!!");
  callSendFunction();
});

$('.textarea').keypress(function(e) {
  if (e.which == 13) {
    console.log("You hit enter!!");
    callSendFunction();
  }
});

function callSendFunction() {
  console.log('Yay, we got it. Do something here..  ');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>textarea {
  width: 99%;
  min-height: 15px
}

div {
  position: relative
}

button {
  position: absolute;
  right: 10px;
  bottom: 8px
}</code>```

  <textarea class="textarea"></textarea>
  <button id="send">
Send
</button>

```

Body:
In this example i want to add margin when cursor reach or touch send button and when touched the send button needed to add margin top. As same like current facebook comment field, when cursor touched sticker or emoji icon the icons are shifted to the bottom of fields.

autosize($('textarea'));

textarea { width:99%;min-height:15px }
div { position:relative }
button { position:absolute;right:10px;bottom:8px }

<textarea class="textarea"></textarea>
<button>
Send
</button>

Body:
Here is what you are looking for, try it out:

autosize($('textarea'));

$("#send").on('click', function() {
  console.log("You clicked send!!");
  callSendFunction();
});

$('.textarea').keypress(function(e) {
  if (e.which == 13) {
    console.log("You hit enter!!");
    callSendFunction();
  }
});

function callSendFunction() {
  console.log('Yay, we got it. Do something here..  ');
}

textarea {
  width: 99%;
  min-height: 15px
}

div {
  position: relative
}

button {
  position: absolute;
  right: 10px;
  bottom: 8px
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/jackmoore/autosize/master/dist/autosize.min.js"></script>

<div>
  <textarea class="textarea"></textarea>
  <button id="send">
Send
</button>
</div>