问:
WooCommerce Add Product Title to Free Sample Order, Cart, Checkout
I think step 3 is not working. In the Orders section in the backend admin I do not see the product name concatenated to the Free Sample text. It works in the Cart Page, it shows Free Sample ( Product Name ) and in Checkout, but it does not work in orders. In Orders I only see "Free Sample" Can anyone help?</p>

```<code>/**
 * @snippet       Add Free Sample to Cart @ Single Product
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 3.9
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

// -------------------------
// 1. Display Free Sample Add to Cart
// Note: change "12345" with Free Sample ID

add_action( 'woocommerce_single_product_summary', 'bbloomer_add_free_sample_add_cart', 35 );

function bbloomer_add_free_sample_add_cart() {
   ?>
      <form class="cart" method="post" enctype='multipart/form-data'>
      <button type="submit" name="add-to-cart" value="111" class="single_add_to_cart_button button alt">Order a Free Sample</button>
      <input type="hidden" name="free_sample" value="<?php the_ID(); ?>">
      </form>
   <?php
}

// -------------------------
// 2. Add the custom field to $cart_item

add_filter( 'woocommerce_add_cart_item_data', 'bbloomer_store_free_sample_id', 9999, 2 );

function bbloomer_store_free_sample_id( $cart_item, $product_id ) {
   if ( isset( $_POST['free_sample'] ) ) {
         $cart_item['free_sample'] = $_POST['free_sample'];
   }
   return $cart_item;
}

// -------------------------
// 3. Concatenate "Free Sample" with product name (CART & CHECKOUT)
// Note: rename "Free Sample" to your free sample product name

add_filter( 'woocommerce_cart_item_name', 'bbloomer_alter_cart_item_name', 9999, 3 );

function bbloomer_alter_cart_item_name( $product_name, $cart_item, $cart_item_key ) {
   if ( $product_name == "Free Sample" ) {
      $product = wc_get_product( $cart_item["free_sample"] );
      $product_name .=  " (" . $product->get_name() . ")";
   }
   return $product_name;
}

// -------------------------
// 4. Add "Free Sample" product name to order meta
// Note: this will show on thank you page, emails and orders

add_action( 'woocommerce_add_order_item_meta', 'bbloomer_save_posted_field_into_order', 9999, 2 );

function bbloomer_save_posted_field_into_order( $itemID, $values ) {
    if ( ! empty( $values['free_sample'] ) ) {
      $product = wc_get_product( $values['free_sample'] );
      $product_name = $product->get_name();
      wc_add_order_item_meta( $itemID, 'Free sample for', $product_name );
    }
}
</code>```

答:
Here is a simple example

function my_add_cart_item_data( $cart_item, $product_id ) {
    $cart_item['my_text'] = 'MY CUSTOM TEXT';
    return $cart_item;
}
add_filter( 'woocommerce_add_cart_item_data', 'my_add_cart_item_data', 10, 2 );

function custom_cart_items_prices( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

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

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ) {

        // Get an instance of the WC_Product object
        $product = $cart_item['data'];

        // Get the product name
        $original_name = $product->get_name();

        // Extra text
        $extra_text = $cart_item['my_text'];

        // Set the new name
        if( method_exists( $product, 'set_name' ) ) {
            $product->set_name( $original_name . ' + ' . $extra_text );
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'custom_cart_items_prices', 10, 1 );
```

<p>With your code example this becomes something like</p>

<pre class="lang-php prettyprint-override"><code>// 1.
add_action( 'woocommerce_single_product_summary', 'bbloomer_add_free_sample_add_cart', 35 );
function bbloomer_add_free_sample_add_cart() {
    ?>
        <form class="cart" method="post" enctype='multipart/form-data'>
        <button type="submit" name="add-to-cart" value="111" class="single_add_to_cart_button button alt">Order a Free Sample</button>
        <input type="hidden" name="free_sample" value="<?php the_ID(); ?>">
        </form>
    <?php
}

// 2.
add_filter( 'woocommerce_add_cart_item_data', 'bbloomer_store_free_sample_id', 9999, 2 );
function bbloomer_store_free_sample_id( $cart_item, $product_id ) {
    if ( isset( $_POST['free_sample'] ) ) {
        $cart_item['free_sample'] = $_POST['free_sample'];
    }
    return $cart_item;
}

// 3
add_action( 'woocommerce_before_calculate_totals', 'custom_cart_items_prices', 10, 1 );
function custom_cart_items_prices( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

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

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ) {

        // Get an instance of the WC_Product object
        $product = $cart_item['data'];

        // Get the product name
        $original_name = $product->get_name();

        // Extra text
        $extra_text = $cart_item['free_sample'];

        // Set the new name
        if( method_exists( $product, 'set_name' ) ) {
            $product->set_name( $original_name . ' + ' . $extra_text );
        }
    }
}
</code>```

Body:
I think step 3 is not working. In the Orders section in the backend admin I do not see the product name concatenated to the Free Sample text. It works in the Cart Page, it shows Free Sample ( Product Name ) and in Checkout, but it does not work in orders. In Orders I only see "Free Sample" Can anyone help?

/**
 * @snippet       Add Free Sample to Cart @ Single Product
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @testedwith    WooCommerce 3.9
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

// -------------------------
// 1. Display Free Sample Add to Cart
// Note: change "12345" with Free Sample ID

add_action( 'woocommerce_single_product_summary', 'bbloomer_add_free_sample_add_cart', 35 );

function bbloomer_add_free_sample_add_cart() {
   ?>
      <form class="cart" method="post" enctype='multipart/form-data'>
      <button type="submit" name="add-to-cart" value="111" class="single_add_to_cart_button button alt">Order a Free Sample</button>
      <input type="hidden" name="free_sample" value="<?php the_ID(); ?>">
      </form>
   <?php
}

// -------------------------
// 2. Add the custom field to $cart_item

add_filter( 'woocommerce_add_cart_item_data', 'bbloomer_store_free_sample_id', 9999, 2 );

function bbloomer_store_free_sample_id( $cart_item, $product_id ) {
   if ( isset( $_POST['free_sample'] ) ) {
         $cart_item['free_sample'] = $_POST['free_sample'];
   }
   return $cart_item;
}

// -------------------------
// 3. Concatenate "Free Sample" with product name (CART & CHECKOUT)
// Note: rename "Free Sample" to your free sample product name

add_filter( 'woocommerce_cart_item_name', 'bbloomer_alter_cart_item_name', 9999, 3 );

function bbloomer_alter_cart_item_name( $product_name, $cart_item, $cart_item_key ) {
   if ( $product_name == "Free Sample" ) {
      $product = wc_get_product( $cart_item["free_sample"] );
      $product_name .=  " (" . $product->get_name() . ")";
   }
   return $product_name;
}

// -------------------------
// 4. Add "Free Sample" product name to order meta
// Note: this will show on thank you page, emails and orders

add_action( 'woocommerce_add_order_item_meta', 'bbloomer_save_posted_field_into_order', 9999, 2 );

function bbloomer_save_posted_field_into_order( $itemID, $values ) {
    if ( ! empty( $values['free_sample'] ) ) {
      $product = wc_get_product( $values['free_sample'] );
      $product_name = $product->get_name();
      wc_add_order_item_meta( $itemID, 'Free sample for', $product_name );
    }
}

Body:
Here is a simple example

function my_add_cart_item_data( $cart_item, $product_id ) {
    $cart_item['my_text'] = 'MY CUSTOM TEXT';
    return $cart_item;
}
add_filter( 'woocommerce_add_cart_item_data', 'my_add_cart_item_data', 10, 2 );

function custom_cart_items_prices( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

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

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ) {

        // Get an instance of the WC_Product object
        $product = $cart_item['data'];

        // Get the product name
        $original_name = $product->get_name();

        // Extra text
        $extra_text = $cart_item['my_text'];

        // Set the new name
        if( method_exists( $product, 'set_name' ) ) {
            $product->set_name( $original_name . ' + ' . $extra_text );
        }
    }
}
add_action( 'woocommerce_before_calculate_totals', 'custom_cart_items_prices', 10, 1 );

With your code example this becomes something like

// 1.
add_action( 'woocommerce_single_product_summary', 'bbloomer_add_free_sample_add_cart', 35 );
function bbloomer_add_free_sample_add_cart() {
    ?>
        <form class="cart" method="post" enctype='multipart/form-data'>
        <button type="submit" name="add-to-cart" value="111" class="single_add_to_cart_button button alt">Order a Free Sample</button>
        <input type="hidden" name="free_sample" value="<?php the_ID(); ?>">
        </form>
    <?php
}

// 2.
add_filter( 'woocommerce_add_cart_item_data', 'bbloomer_store_free_sample_id', 9999, 2 );
function bbloomer_store_free_sample_id( $cart_item, $product_id ) {
    if ( isset( $_POST['free_sample'] ) ) {
        $cart_item['free_sample'] = $_POST['free_sample'];
    }
    return $cart_item;
}

// 3
add_action( 'woocommerce_before_calculate_totals', 'custom_cart_items_prices', 10, 1 );
function custom_cart_items_prices( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

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

    // Loop through cart items
    foreach ( $cart->get_cart() as $cart_item ) {

        // Get an instance of the WC_Product object
        $product = $cart_item['data'];

        // Get the product name
        $original_name = $product->get_name();

        // Extra text
        $extra_text = $cart_item['free_sample'];

        // Set the new name
        if( method_exists( $product, 'set_name' ) ) {
            $product->set_name( $original_name . ' + ' . $extra_text );
        }
    }
}


来源: stackexchange

问:
Python scope of variables in and out of a function
Consider the following code:

```<code>def square(x):
    return x**2.

def cube(x):
    return x**3.

def some_func():
    foo['a'] = 1.
    foo['b'] = 3.

    if foo['b'] > foo['a']:
        bar = square
    else:
        bar = cube

foo = dict()

bar = None

some_func()

print(foo['a'])

print(bar(2))
</code>```

Two different variables are initialised in the beginning, foo, and bar. Then I run a function which doesn't take arguments or return anything, but amends these two variables.

The result of these two is the following:

```<code>1.0
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-7e5e5ac79215> in <module>
     22 print(foo['a'])
     23
---> 24 print(bar(2))

TypeError: 'NoneType' object is not callable
</code>```

So, the dict is happily amended by some_func(), but I cannot assign a function name. Why? How can I go around this?

Edit: I have tried giving bar other values than None, similar behaviour occurs.

答:
Try with a global statement for the thing you need to replace (and not just modify):

```<code>#!/usr/bin/python3

def square(x):
    return x**2.

def cube(x):
    return x**3.

def some_func():
    global bar

    foo['a'] = 1.
    foo['b'] = 3.

    if foo['b'] > foo['a']:
        bar = square
    else:
        bar = cube

foo = dict()

bar = None

some_func()

print(foo['a'])

print(bar(2))
</code>```

HTH

ContentLicense: CC BY-SA 4.0

Body:
Consider the following code:

def square(x):
    return x**2.

def cube(x):
    return x**3.

def some_func():
    foo['a'] = 1.
    foo['b'] = 3.

    if foo['b'] > foo['a']:
        bar = square
    else:
        bar = cube

foo = dict()

bar = None

some_func()

print(foo['a'])

print(bar(2))

Two different variables are initialised in the beginning, foo, and bar. Then I run a function which doesn't take arguments or return anything, but amends these two variables.

The result of these two is the following:

1.0
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-7e5e5ac79215> in <module>
     22 print(foo['a'])
     23
---> 24 print(bar(2))

TypeError: 'NoneType' object is not callable

So, the dict is happily amended by some_func(), but I cannot assign a function name. Why? How can I go around this?

Edit: I have tried giving bar other values than None, similar behaviour occurs.

Body:
Try with a global statement for the thing you need to replace (and not just modify):

#!/usr/bin/python3

def square(x):
    return x**2.

def cube(x):
    return x**3.

def some_func():
    global bar

    foo['a'] = 1.
    foo['b'] = 3.

    if foo['b'] > foo['a']:
        bar = square
    else:
        bar = cube

foo = dict()

bar = None

some_func()

print(foo['a'])

print(bar(2))

HTH


问:
How to measure performance with async functions in javascript
I've created a small app that compares the speeds of WebAssembly and Javascript. To my surprise, JavaScript is way faster at calculating factorials of a large number. Or at least it seems like it is. I am pretty sure this is not right and is caused by the await syntax I'm using. (The functions are the same.) Also, what are some really time heavy tasks I can use to compare those two? This doesn't really seem that time consuming, since it takes less than a 0.1 millisecond.

AssemblyScript (this gets compiled into wasm)

```<code>// The entry file of your WebAssembly module.
export function fib(num: i32): i32 {
  var a: i32 = 1,
    b: i32 = 0,
    temp: i32;

  while (num > 0) {
    temp = a;
    a = a + b;
    b = temp;
    num--;
  }

  return b;
}

</code>```

App.js

```<code>import waApi from "./api";
...
  <button
       onClick={async () => {
       const t0 = performance.now();
       (await waApi).fib(200);
       const t1 = performance.now();
       this.updateGraph(t1 - t0, "wa");
       const t2 = performance.now();
       this.fib(200);
       const t3 = performance.now();
       this.updateGraph(t3 - t2, "js");
       }}>
Calculate with both
  </button>
</code>```

api.js

```<code>import { instantiateStreaming } from "assemblyscript/lib/loader";

export default instantiateStreaming(fetch("./assembly.wasm"));
</code>```

答:
The problem with micro-benchmarks (i.e. benchmarks that analyse the performance of small, very fast function) is that you almost always end up measuring the wrong thing. Your measurements are going to be heavily skewed by:

The overhead involved in invoking WebAssembly functions from JavaScript

The ability of the AssemblyScript compiler (which is very new) to optimise your function

The accuracy of your timer

The time for your JavaScript engine to reach peak optimisation

Just to name a few!

A more realistic benchmark would perform calculations that execute a far greater range of WebAssembly operations, be more 'realistic' in nature (i.e. measure the types of load you really would offload to WebAssembly), and take longer to execute.

Here's a much better benchmark based on a GameBoy emulator:

https://medium.com/@torch2424/webassembly-is-fast-a-real-world-benchmark-of-webassembly-vs-es6-d85a23f8e193

Body:
I've created a small app that compares the speeds of WebAssembly and Javascript. To my surprise, JavaScript is way faster at calculating factorials of a large number. Or at least it seems like it is. I am pretty sure this is not right and is caused by the await syntax I'm using. (The functions are the same.) Also, what are some really time heavy tasks I can use to compare those two? This doesn't really seem that time consuming, since it takes less than a 0.1 millisecond.

AssemblyScript (this gets compiled into wasm)

// The entry file of your WebAssembly module.
export function fib(num: i32): i32 {
  var a: i32 = 1,
    b: i32 = 0,
    temp: i32;

  while (num > 0) {
    temp = a;
    a = a + b;
    b = temp;
    num--;
  }

  return b;
}

App.js

import waApi from "./api";
...
  <button
       onClick={async () => {
       const t0 = performance.now();
       (await waApi).fib(200);
       const t1 = performance.now();
       this.updateGraph(t1 - t0, "wa");
       const t2 = performance.now();
       this.fib(200);
       const t3 = performance.now();
       this.updateGraph(t3 - t2, "js");
       }}>
Calculate with both
  </button>

api.js

import { instantiateStreaming } from "assemblyscript/lib/loader";

export default instantiateStreaming(fetch("./assembly.wasm"));


问:
JavaScript: How to check if a array object contain specific values
I have this array:

[
  {
    "active": true,
    "name": "agency one"
  },
  {
    "active": false,
    "name": "agency two"
  },
  {
    "active": true,
    "name": "agency three"
  },
  {
    "active": false,
    "name": "agency four"
  }
]
```

<p>And some data like this:</p>

<pre class="lang-js prettyprint-override"><code>{
    "domain": "agency one",
    "url": "https://....",
    "title": "some title",
    "img": "https://.....jpg",
    "tag": "some tag",
}
</code>```

How can I check if agancy is active show data?

答:
Assuming variable agencies holds the array included in your post:

```<code>const activeAgencies = agencies.filter(agency => {
    return agency.active === true
  })
</code>```

Then activeAgencies would be a new array holding only the agency objects marked active.

Body:
I have this array:

[
  {
    "active": true,
    "name": "agency one"
  },
  {
    "active": false,
    "name": "agency two"
  },
  {
    "active": true,
    "name": "agency three"
  },
  {
    "active": false,
    "name": "agency four"
  }
]

And some data like this:

{
    "domain": "agency one",
    "url": "https://....",
    "title": "some title",
    "img": "https://.....jpg",
    "tag": "some tag",
}

How can I check if agancy is active show data?

Body:
Assuming variable agencies holds the array included in your post:

const activeAgencies = agencies.filter(agency => {
    return agency.active === true
  })

Then activeAgencies would be a new array holding only the agency objects marked active.


问:
Odd behavior with Static Site hosted in Azure Blob Storage using Custom Domain with CDN
I recently went through the process of building a static website and hosting it on Azure Blob Storage and configuring a custom domain name and https with CDN. I followed all the steps on learn.microsoft.com and configured the DNS in Azure, using Premium Verizon CDN. Everything seems to be working, but I am seeing some odd url behavior

https://website.com - Page cannot be reached

http://website.com -
Site works but QS not passing (/route content has url of base)

https://www.website.com - Perfect experience

http://www.website.com -
Account being accessed does not support http

I have some Custom Rules configured for the CDN, so I assume they may need some tweaking.

Redirecting to Https

Keeping Paths

I know the name of my cdn is there, not that concerned. Any help would be greatly appreciated.

答:
Try following this article: https://www.itexperience.net/2019/04/20/the-account-being-accessed-does-not-support-http-with-blob-sas-url-in-azure/

Go to your Storage Account (top level) in Azure

Go to Settings – Configuration

Set “Secure transfer required” to “Disabled“

Click Save

Retry to access the URL. The file can now be accessed.


问:
Reduce array of objects within ES6 function
I am a little confused about a reduce function I am working on. I intend to reduce an array of objects, which works just fine, if I declare a variable and set it equal to a reduce iteration:

movies = [
  {
    title: 'The Shawshank Redemption',
    rate: '9.3'
  },
  {
    title: 'The Godfather',
    rate: '9.2'
  },
  {
    title: 'The Godfather: Part II',
    rate: '9.0'
  }
  ]

const averageRating = movies.reduce((sum, current) => {
    return (sum + parseFloat(current.rate)) / 3;
  }, 0);

 console.log(averageRating)```
</div>
</div>
</p>

<p>However, if I try to write this as ES6 function, it tells me that sum is not defined:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>movies = [
  {
    title: 'The Shawshank Redemption',
    rate: '9.3'
  },
  {
    title: 'The Godfather',
    rate: '9.2'
  },
  {
    title: 'The Godfather: Part II',
    rate: '9.0'
  }
  ]

ratesAverage = (array) => {
    array.reduce((sum, movies) => {
        return sum + parseFloat(movies.rate);
      }, 0)
}

console.log(ratesAverage(movies))</code>```

What am I missing here?

Thanks a lot in advance

答:
because you're not returning any value in your function

```<code>ratesAverage = (array) => {
    return array.reduce((sum, movies) => {
        return sum + parseFloat(movies.rate);
      }, 0)
}
</code>```

just add return to the result of reduce method.

or you can remove the braces to do implicit return

```<code>ratesAverage = (array) => array.reduce((sum, movies) => {
            return sum + parseFloat(movies.rate);
          }, 0)
</code>```

Body:
I am a little confused about a reduce function I am working on. I intend to reduce an array of objects, which works just fine, if I declare a variable and set it equal to a reduce iteration:

movies = [
  {
    title: 'The Shawshank Redemption',
    rate: '9.3'
  },
  {
    title: 'The Godfather',
    rate: '9.2'
  },
  {
    title: 'The Godfather: Part II',
    rate: '9.0'
  }
  ]

const averageRating = movies.reduce((sum, current) => {
    return (sum + parseFloat(current.rate)) / 3;
  }, 0);

 console.log(averageRating)

However, if I try to write this as ES6 function, it tells me that sum is not defined:

movies = [
  {
    title: 'The Shawshank Redemption',
    rate: '9.3'
  },
  {
    title: 'The Godfather',
    rate: '9.2'
  },
  {
    title: 'The Godfather: Part II',
    rate: '9.0'
  }
  ]

ratesAverage = (array) => {
    array.reduce((sum, movies) => {
        return sum + parseFloat(movies.rate);
      }, 0)
}

console.log(ratesAverage(movies))

What am I missing here?

Thanks a lot in advance

Body:
because you're not returning any value in your function

ratesAverage = (array) => {
    return array.reduce((sum, movies) => {
        return sum + parseFloat(movies.rate);
      }, 0)
}

just add return to the result of reduce method.

or you can remove the braces to do implicit return

ratesAverage = (array) => array.reduce((sum, movies) => {
            return sum + parseFloat(movies.rate);
          }, 0)


问:
What happens with "pure" Python + Cython packages during installation built failure?
I just read the Cython Pure Python Mode documentation and I'm not sure if I understand it right. It sounds as if I could keep all my Python files as they are, add *.pxd files where I declare Cython types. In the setup.py, I still add

```<code>from setuptools import setup
from Cython.Build import cythonize

setup(
    ext_modules = cythonize(
        "A.py",
        compiler_directives={'language_level' : "3"}
      )
)
</code>```

When I run python setup.py build_ext --inplace it actually builds the .so file.

What happens when I create the sdist / bdist, upload them to PyPI and a user does not have a matching platform? They will download the sdist, sure. I guess pip / setuptools will automatically try to compile the extension modules (A.py) and I guess if that works, it is fine. But what if cythonize fails? Will it still install the package and use the pure Python code?

答:
I don't think so. I believe a failure in setup.py aborts installation completely.

You can try to declare an extension optional but there're reports that doesn't really work. Could be an issue with older setuptools.

Body:
I just read the Cython Pure Python Mode documentation and I'm not sure if I understand it right. It sounds as if I could keep all my Python files as they are, add *.pxd files where I declare Cython types. In the setup.py, I still add

from setuptools import setup
from Cython.Build import cythonize

setup(
    ext_modules = cythonize(
        "A.py",
        compiler_directives={'language_level' : "3"}
      )
)

When I run python setup.py build_ext --inplace it actually builds the .so file.

What happens when I create the sdist / bdist, upload them to PyPI and a user does not have a matching platform? They will download the sdist, sure. I guess pip / setuptools will automatically try to compile the extension modules (A.py) and I guess if that works, it is fine. But what if cythonize fails? Will it still install the package and use the pure Python code?


答:
This has to do with the scope in python. You can read more about it in this article: https://www.datacamp.com/community/tutorials/scope-of-variables-python.

The given solution for your code would be to add: global bar inside the function before the if statements to point it to the global variable that you are trying to set.

Title: Python scope of variables in and out of a function


问:
how can I reduce my list of structures based on the other list of Strings in Java?
In my Java application I have a class:

```<code>public class MyStructure {

    SomeClass someClass;
    String[] fields;

    ...
}
</code>```

Now, I have a list of the structures above:

```<code>List< MyStructure> structures = getStructures();
</code>```

I also have a list of Strings:

```<code>List<String> myList = getStrings();
</code>```

I need to filter the first list (structures) so that it only contains elements, that in their fields array contain any of the Strings present on myList.

I thought about writing a for loops, something like:

```<code>List<MyStructure> outcomeStructures = new ArrayList<>();

for (MyStructure mystructure : structures) {
    for (String temp : mystructure.getFields()) {
        if (myList.contains(temp) {
            outcomeStructures.add(mystructure);
        }
    }
}
</code>```

but maybe there's a better way to do so? Thanks!

答:
For the better performance you can convert the List<String> myList = getStrings(); to Set<String> mySet since HashSet time complexity for contains is O(1) always. Then use:

```<code>List<MyStructure> outcomeStructures = structures.stream()
        .filter(st -> Arrays.stream(st.getFields()).anyMatch(mySet::contains))
        .collect(Collectors.toList());
</code>```

Body:
In my Java application I have a class:

public class MyStructure {

    SomeClass someClass;
    String[] fields;

    ...
}

Now, I have a list of the structures above:

List< MyStructure> structures = getStructures();

I also have a list of Strings:

List<String> myList = getStrings();

I need to filter the first list (structures) so that it only contains elements, that in their fields array contain any of the Strings present on myList.

I thought about writing a for loops, something like:

List<MyStructure> outcomeStructures = new ArrayList<>();

for (MyStructure mystructure : structures) {
    for (String temp : mystructure.getFields()) {
        if (myList.contains(temp) {
            outcomeStructures.add(mystructure);
        }
    }
}

but maybe there's a better way to do so? Thanks!

Body:
For the better performance you can convert the List<String> myList = getStrings(); to Set<String> mySet since HashSet time complexity for contains is O(1) always. Then use:

List<MyStructure> outcomeStructures = structures.stream()
        .filter(st -> Arrays.stream(st.getFields()).anyMatch(mySet::contains))
        .collect(Collectors.toList());


问:
Batch script with for loop and pipe
I would like all the csv files in a directory which filename does not contain word "summary". Inside the command prompt I can type the following command

```<code>dir /b my_dir\*.csv | find /V "summary"
</code>```

When I try to transfer the above command into a batch file I run into a problem in that the pipe command is not supported in the for loop. That is I cannot do the following

```<code>FOR /f %%A in ('dir /b my_dir\*.csv | find /V "summary"') do (
rem want to do something here
)
</code>```

Can somebody shed some light to me on how to solve the problem above?

Thanks in advance!

答:
You need to escape the | character to prevent its being interpreted at the time of parsing the loop command. Use ^ to escape it:

```<code>FOR /f "delims=" %%A in ('dir /b "my_dir\*.csv" <b>^|</b> find /V "summary"') do (
rem do what you want with %%A here
)
</code>```

Once escaped, the | becomes part of the '-delimited string. It is only interpreted as a special symbol when that string is parsed separately from the loop, as a "sub-command", according to the syntax. And that is done after parsing the loop.

ContentLicense: CC BY-SA 3.0

Title: Batch script with for loop and pipe

Body:
I would like all the csv files in a directory which filename does not contain word "summary". Inside the command prompt I can type the following command

dir /b my_dir\*.csv | find /V "summary"

When I try to transfer the above command into a batch file I run into a problem in that the pipe command is not supported in the for loop. That is I cannot do the following

FOR /f %%A in ('dir /b my_dir\*.csv | find /V "summary"') do (
rem want to do something here
)

Can somebody shed some light to me on how to solve the problem above?

Thanks in advance!

Body:
You need to escape the | character to prevent its being interpreted at the time of parsing the loop command. Use ^ to escape it:

FOR /f "delims=" %%A in ('dir /b "my_dir\*.csv" ^| find /V "summary"') do (
rem do what you want with %%A here
)

Once escaped, the | becomes part of the '-delimited string. It is only interpreted as a special symbol when that string is parsed separately from the loop, as a "sub-command", according to the syntax. And that is done after parsing the loop.


问:
How to truncate a file in c#?
I am writing actions done by the program in C# into a file by using Trace.Writeln() function. But the file is becoming too large. How to truncate this file when it grows to 1MB?

```<code>TextWriterTraceListener traceListener = new TextWriterTraceListener(File.AppendText("audit.txt"));
Trace.Listeners.Add(traceListener);
Trace.AutoFlush = true;
</code>```

What should be added to the above block

答:
Late answer, but you might try:

```<code>StreamWriter sw = new StreamWriter(YourFileName, false);
sw.Write("");
sw.Flush();
sw.Close();
</code>```

Sending false as the second param of StreamWriter() tells it NOT to append, resulting in it overwriting the file.  In this case with an empty string, effectively truncating it.

Title: How to truncate a file in c#?

Body:
I am writing actions done by the program in C# into a file by using Trace.Writeln() function. But the file is becoming too large. How to truncate this file when it grows to 1MB?

TextWriterTraceListener traceListener = new TextWriterTraceListener(File.AppendText("audit.txt"));
Trace.Listeners.Add(traceListener);
Trace.AutoFlush = true;

What should be added to the above block

Body:
Late answer, but you might try:

StreamWriter sw = new StreamWriter(YourFileName, false);
sw.Write("");
sw.Flush();
sw.Close();

Sending false as the second param of StreamWriter() tells it NOT to append, resulting in it overwriting the file.  In this case with an empty string, effectively truncating it.


答:
In order to assign to the global bar from some_func(), you need to declare it global, like so:

```<code>def some_func():
    foo['a'] = 1.
    foo['b'] = 3.

    global bar

    if foo['b'] > foo['a']:
        bar = square
    else:
        bar = cube
</code>```

See the documentation for global, specifically this section:

The global statement is a declaration which holds for the entire
  current code block. It means that the listed identifiers are to be
  interpreted as globals. While using global names is automatic if they
  are not defined in the local scope, assigning to global names would be
  impossible without global.

Your program clearly demonstrates the difference specified here: your access to foo is using the global name, while your access to bar is assigning to the global name.

Body:
In order to assign to the global bar from some_func(), you need to declare it global, like so:

def some_func():
    foo['a'] = 1.
    foo['b'] = 3.

    global bar

    if foo['b'] > foo['a']:
        bar = square
    else:
        bar = cube

See the documentation for global, specifically this section:

The global statement is a declaration which holds for the entire
  current code block. It means that the listed identifiers are to be
  interpreted as globals. While using global names is automatic if they
  are not defined in the local scope, assigning to global names would be
  impossible without global.

Your program clearly demonstrates the difference specified here: your access to foo is using the global name, while your access to bar is assigning to the global name.


问:
Adding form action in html in laravel
I am unable to pass url in views html form action tag.

```<code><form method="post" action="??what to write here??" accept-charset="UTF-8">
</code>```

I want to set it's action to WelcomeController@log_in function in WelcomeController file in controllers.

Here are my routes:

```<code>Route::get('/','WelcomeController@home');
Route::post('/', array('as' => 'log_in', 'uses' => 'WelcomeController@log_in'));
Route::get('home', 'HomeController@index');
</code>```

After submitting it keeps the same url

```<code>http://localhost:8000/
</code>```

And the main error line

```<code>Whoops, looks like something went wrong.
</code>```

After that there is 1/1 TokenMismatchException in compiled.php line 2440:

答:
For Laravel 2020. Ok, an example:

```<code><form class="modal-content animate" action="{{ url('login_kun')  }}" method="post">
  @csrf   // !!! attention - this string is a must
....
 </form>
</code>```

And then in web.php:

```<code>Route::post("/login_kun", "LoginController@login");
</code>```

And one more in new created LoginController:

```<code> public function login(Request $request){
    dd($request->all());
}
</code>```

and you are done my friend.

Title: Adding form action in html in laravel

Body:
I am unable to pass url in views html form action tag.

<form method="post" action="??what to write here??" accept-charset="UTF-8">

I want to set it's action to WelcomeController@log_in function in WelcomeController file in controllers.

Here are my routes:

Route::get('/','WelcomeController@home');
Route::post('/', array('as' => 'log_in', 'uses' => 'WelcomeController@log_in'));
Route::get('home', 'HomeController@index');

After submitting it keeps the same url

http://localhost:8000/

And the main error line

Whoops, looks like something went wrong.

After that there is 1/1 TokenMismatchException in compiled.php line 2440:

Body:
For Laravel 2020. Ok, an example:

<form class="modal-content animate" action="{{ url('login_kun')  }}" method="post">
  @csrf   // !!! attention - this string is a must
....
 </form>

And then in web.php:

Route::post("/login_kun", "LoginController@login");

And one more in new created LoginController:

 public function login(Request $request){
    dd($request->all());
}

and you are done my friend.


问:
Regex-based string replacement operation not working
I have a file exp.txt with below content

```<code> hi. what are you doing. are you fine?
</code>```

This is my code:

```<code>$a = "are you fine?"

for($i=0;$i -lt $ar.Length; $i++)
{
    (Get-Content "exp.txt") -replace $ar[$i], "$&~" | Set-Content "exp.txt"
}
</code>```

I want to append ~ at the end of whatever text i put in $ar variable. But the above code does not work if i type "are you fine?" in $ar variable. Symbols like "*" "$" "+" also dont work. i need help

答:
The -replace uses regular expressions, so special characters are interpreted.  Looks like you don't want that, so try using

```<code>(Get-Content "exp.txt").Replace("something", "something else")
</code>```

I'm not clear on exactly what you want in the end, but this should get you past the problem with special characters.

Body:
I have a file exp.txt with below content

 hi. what are you doing. are you fine?

This is my code:

$a = "are you fine?"

for($i=0;$i -lt $ar.Length; $i++)
{
    (Get-Content "exp.txt") -replace $ar[$i], "$&~" | Set-Content "exp.txt"
}

I want to append ~ at the end of whatever text i put in $ar variable. But the above code does not work if i type "are you fine?" in $ar variable. Symbols like "*" "$" "+" also dont work. i need help

Body:
The -replace uses regular expressions, so special characters are interpreted.  Looks like you don't want that, so try using

(Get-Content "exp.txt").Replace("something", "something else")

I'm not clear on exactly what you want in the end, but this should get you past the problem with special characters.


问:
How do I get the auth code from the class?
Hi I have class and I am trying to get the auth code but when I do that it displays an error:

My code is this:

```<code>stdClass Object ( [emisor] => 76063822 [codigo] => ZTs3NjA2MzgyMjszOTsxNjAwNjk= [receptor] => 18598968 [fecha] => 2020-01-21 [vencimiento] => [total] => 20000 [dte] => 39 [temporal] => [emitido] => 160069 [pagado] => 2020-01-21 [medio] => webpay [datos] => {"cardDetail":{"cardNumber":"8011","cardExpirationDate":null},"detailOutput":{"authorizationCode":"011323","paymentTypeCode":"VD","responseCode":0,"sharesNumber":0,"amount":"20000","commerceCode":"597034994579","buyOrder":"76063822-39-160069"},"transactionDate":"2020-01-21T16:50:50.835-03:00"} [tienda] =>
</code>```

And I do this:

```<code>$Cobro->datos->detailOutput->authorizationCode
</code>```

and it shows "Trying to get property of non-object"

Why does it not work? because I think that it's correct, could you help me ? Thanks!

答:
You have a JSON string within your object, so first you need to apply json_decode() and then to access the desired property:

```<code>$datos = json_decode($Cobro->datos);
print_r($datos);
echo $datos->detailOutput->authorizationCode;
</code>```

produced $datos object:

```<code>stdClass Object
(
    [cardDetail] => stdClass Object
        (
            [cardNumber] => 8011
            [cardExpirationDate] =>
        )

    [detailOutput] => stdClass Object
        (
            [authorizationCode] => 011323
            [paymentTypeCode] => VD
            [responseCode] => 0
            [sharesNumber] => 0
            [amount] => 20000
            [commerceCode] => 597034994579
            [buyOrder] => 76063822-39-160069
        )

    [transactionDate] => 2020-01-21T16:50:50.835-03:00
)
</code>```

echo output:

```<code>011323
</code>```

Body:
Hi I have class and I am trying to get the auth code but when I do that it displays an error:

My code is this:

stdClass Object ( [emisor] => 76063822 [codigo] => ZTs3NjA2MzgyMjszOTsxNjAwNjk= [receptor] => 18598968 [fecha] => 2020-01-21 [vencimiento] => [total] => 20000 [dte] => 39 [temporal] => [emitido] => 160069 [pagado] => 2020-01-21 [medio] => webpay [datos] => {"cardDetail":{"cardNumber":"8011","cardExpirationDate":null},"detailOutput":{"authorizationCode":"011323","paymentTypeCode":"VD","responseCode":0,"sharesNumber":0,"amount":"20000","commerceCode":"597034994579","buyOrder":"76063822-39-160069"},"transactionDate":"2020-01-21T16:50:50.835-03:00"} [tienda] =>

And I do this:

$Cobro->datos->detailOutput->authorizationCode

and it shows "Trying to get property of non-object"

Why does it not work? because I think that it's correct, could you help me ? Thanks!

Body:
You have a JSON string within your object, so first you need to apply json_decode() and then to access the desired property:

$datos = json_decode($Cobro->datos);
print_r($datos);
echo $datos->detailOutput->authorizationCode;

produced $datos object:

stdClass Object
(
    [cardDetail] => stdClass Object
        (
            [cardNumber] => 8011
            [cardExpirationDate] =>
        )

    [detailOutput] => stdClass Object
        (
            [authorizationCode] => 011323
            [paymentTypeCode] => VD
            [responseCode] => 0
            [sharesNumber] => 0
            [amount] => 20000
            [commerceCode] => 597034994579
            [buyOrder] => 76063822-39-160069
        )

    [transactionDate] => 2020-01-21T16:50:50.835-03:00
)

echo output:

011323


问:
VB6 can't load DLL COM registered in Win10
In Win7, I have an application VB6 that references C:\Windows\SystemWOW64\FM20.dll. This dll is put into SysWOW64 by Office 2010 32 bit. This is a COM dll.

After upgrade to Win10, my application show message error that it can't find FM20.

In Win10, the dll is already registrered because I can find the class in regedit

They have almost same registry but there area light difference

In Win7 (worked) :

In Win10 (not work) :

Anyone has an idea how to make the application work please ? We don't want to move FM20.dll to WOW64 and regsvr32 it for some reason

答:
If the path is stored under the key Win64, my guess is that it is a 64-bit component. If that is correct, then there is no way that you will be able to load it using VB6, which a 32-bit application.

Do you have a 32-bit or a 64-bit version of Microsoft office?

Actually, I am not familiar with 64-bit COM, but I am certain that the key must be Win32 for a 32-bit component.


问:
Cassandra Update Record : Non PRIMARY KEY columns found
I created table in Cassandra database name as information_tbl.
query:

```<code>CREATE TABLE IF NOT EXISTS Information_tbl (id uuid ,
                                      cam_id varchar,
                                      camzone varchar,
                                      msg varchar,
                                      fltr int,
                                      time_stamp int,
                                      PRIMARY KEY (fltr,time_stamp)
                                      )WITH CLUSTERING ORDER BY (time_stamp DESC);
</code>```

when I execute update query, it show error :

Query 1:

```<code>UPDATE information_tbl SET camzone = 'D' WHERE id = c6263cac-450f-4105-a2cc-3705ec741a96;
</code>```

Error:

```<code>message="Some partition key parts are missing: fltr"
</code>```

Query 2:

```<code>UPDATE information_tbl SET camzone = 'D' WHERE fltr=1 AND id = c6263cac-450f-4105-a2cc-3705ec741a96;
</code>```

Error:

```<code>message="Some clustering keys are missing: time_stamp"
</code>```

Query 3:

```<code>UPDATE information_tbl SET camzone = 'D' WHERE fltr=1 AND time_stamp = 1581946832 AND id = c6263cac-450f-4105-a2cc-3705ec741a96;
</code>```

Error:

```<code>message="Non PRIMARY KEY columns found in where clause: id "
</code>```

Any suggestions.

答:
To update Cassandra row in Cassandra, you need Partition Key + Clustering Key. Coming to you error messages

Error 1 : message="Some partition key parts are missing: fltr" in this case you are not passing any partition key columns.

Error 2 : message="Some clustering keys are missing: time_stamp" in this case you are passing a part of partition key columns.

Error 3 : message="Non PRIMARY KEY columns found in where clause: id " in this case you are passing partition key columns along with other columns.

If you have the value of ID available, you can change your data model as below to perform an update.

CREATE TABLE IF NOT EXISTS Information_tbl (id uuid ,
                                      cam_id varchar,
                                      camzone varchar,
                                      msg varchar,
                                      fltr int,
                                      time_stamp int,
                                      PRIMARY KEY (id, fltr,time_stamp)
                                      )WITH CLUSTERING ORDER BY (time_stamp DESC);

```

Body:
I created table in Cassandra database name as information_tbl.
query:

CREATE TABLE IF NOT EXISTS Information_tbl (id uuid ,
                                      cam_id varchar,
                                      camzone varchar,
                                      msg varchar,
                                      fltr int,
                                      time_stamp int,
                                      PRIMARY KEY (fltr,time_stamp)
                                      )WITH CLUSTERING ORDER BY (time_stamp DESC);

when I execute update query, it show error :

Query 1:

UPDATE information_tbl SET camzone = 'D' WHERE id = c6263cac-450f-4105-a2cc-3705ec741a96;

Error:

message="Some partition key parts are missing: fltr"

Query 2:

UPDATE information_tbl SET camzone = 'D' WHERE fltr=1 AND id = c6263cac-450f-4105-a2cc-3705ec741a96;

Error:

message="Some clustering keys are missing: time_stamp"

Query 3:

UPDATE information_tbl SET camzone = 'D' WHERE fltr=1 AND time_stamp = 1581946832 AND id = c6263cac-450f-4105-a2cc-3705ec741a96;

Error:

message="Non PRIMARY KEY columns found in where clause: id "

Any suggestions.


问:
How to create a table on word and add borders using VBA
I simply want to create a table whenever I click on a command button. The table should have 2 rows and 2 columns.

And whenever I add another table, it should add a new one under the one before.

This is my code for now :

```<code>Private Sub CommandButton1_Click()

Set MyRange = ActiveDocument.Content
MyRange.Collapse Direction:=wdCollapseEnd
ActiveDocument.Tables.Add Range:=MyRange, NumRows:=2, NumColumns:=2

End Sub
</code>```

The problem with this code is that I dont see any borders and lines when I add it.

Also, When I click the command button several times, it just add more rows to the existing table, instead of creating other tables underneath the ones before.

I tried to add a line break between tables to fix the situation but it didnt work. I used :

```<code>ActiveDocument.Range.Text = "Foo" & Chr(11) & "Bar"
</code>```

Thank you for your help

答:
Try:</p>

```<code>Sub Demo()
With ActiveDocument.Range
  .InsertAfter vbCr
  .Tables.Add Range:=.Characters.Last, NumRows:=2, NumColumns:=2
  .Tables(.Tables.Count).Borders.Enable = True
End With
End Sub
</code>```

Body:
I simply want to create a table whenever I click on a command button. The table should have 2 rows and 2 columns.

And whenever I add another table, it should add a new one under the one before.

This is my code for now :

Private Sub CommandButton1_Click()

Set MyRange = ActiveDocument.Content
MyRange.Collapse Direction:=wdCollapseEnd
ActiveDocument.Tables.Add Range:=MyRange, NumRows:=2, NumColumns:=2

End Sub

The problem with this code is that I dont see any borders and lines when I add it.

Also, When I click the command button several times, it just add more rows to the existing table, instead of creating other tables underneath the ones before.

I tried to add a line break between tables to fix the situation but it didnt work. I used :

ActiveDocument.Range.Text = "Foo" & Chr(11) & "Bar"

Thank you for your help

Body:
Try:

Sub Demo()
With ActiveDocument.Range
  .InsertAfter vbCr
  .Tables.Add Range:=.Characters.Last, NumRows:=2, NumColumns:=2
  .Tables(.Tables.Count).Borders.Enable = True
End With
End Sub


答:
You can use methods like:

.find()

.filter()

.findIndex()

```<code>const firstActiveAgency = arr.find(item => item.active);

const allActiveAgencies = arr.filter(item => item.active);
</code>```

Title: JavaScript: How to check if a array object contain specific values

Body:
I have this array:

[
  {
    "active": true,
    "name": "agency one"
  },
  {
    "active": false,
    "name": "agency two"
  },
  {
    "active": true,
    "name": "agency three"
  },
  {
    "active": false,
    "name": "agency four"
  }
]

And some data like this:

{
    "domain": "agency one",
    "url": "https://....",
    "title": "some title",
    "img": "https://.....jpg",
    "tag": "some tag",
}

How can I check if agancy is active show data?

Body:
You can use methods like:

.find()

.filter()

.findIndex()

const firstActiveAgency = arr.find(item => item.active);

const allActiveAgencies = arr.filter(item => item.active);


问:
Java's unsigned bitshift right (>>>) is signed shifting
I'm trying to bitshift right in order to isolate certain bits from a byte so I wanted an unsigned shift, the "new" bits should be zeros by my understanding. However, I've found that >>> has no difference to >> in my tests. -128 >> 4 = -8 as expected, but -128 >>> 4 should be 8 but I still get -8.

```<code>byte data = (byte)-128;
System.out.println((byte)(data >>> 4));
System.out.println((byte)(data >> 4));
</code>```

Thanks for the help.

答: The signed right shift operator '>>' uses the sign bit to fill the trailing positions and the unsigned right shift operator '>>' do not use the sign bit to fill the trailing positions. It always fills the trailing positions by 0s</p>

Body:
I'm trying to bitshift right in order to isolate certain bits from a byte so I wanted an unsigned shift, the "new" bits should be zeros by my understanding. However, I've found that >>> has no difference to >> in my tests. -128 >> 4 = -8 as expected, but -128 >>> 4 should be 8 but I still get -8.

byte data = (byte)-128;
System.out.println((byte)(data >>> 4));
System.out.println((byte)(data >> 4));

Thanks for the help.


问:
Xcode: Could not inspect the application package
I am running Xcode 6 and iOS 8 GM. Every other time I run my app I get this message from Xcode:

"Could not inspect the application package"

So I can run and build, I will get the message. I run and build again, everything runs as expected (this is to my device). Then it will rinse and repeat, every other time giving me this error.

I have looked at all the other solutions that have been suggested but cannot stop this error. I have cleaned my project, cleaned the build folder, deleted derived data etc with no luck.

How can I see what is causing this in the first place?

Interestingly, this only happens when running on my device. Not on the simulator. Also, it only happens on my device, when building for debug. If I change the scheme to release, I can build and run endlessly without with error. Ideas?

答: deleting Pods and then calling pod install worked for me</p>


问:
Ambiguity between Haskell Num class and my show-like class
I'm trying to declare my own data with appropriate conversion as class. My code looks like this:

```<code>data SomeData =  SInteger Integer | SElse deriving Show

class Some a where
    toSome :: a -> SomeData

instance Some Int where toSome = SInteger . toInteger

main :: IO ()
main = print $ toSome 3
</code>```

But GHC (7.0.3) becomes angry and says:

```<code>Ambiguous type variable `a0' in the constraints:
      (Some a0) arising from a use of `toSome'
                at minimal_broken.hs:11:16-21
      (Num a0) arising from the literal `3' at minimal_broken.hs:11:23
    Probable fix: add a type signature that fixes these type variable(s)
</code>```

Explicit type signature (like 3::Int) fixes the issue, but it's very inconvenient.

Standard "Show" works just fine, and according to the manual it's declared exactly the same way.

Why standard Show works, but my class doesn't? Did I miss something?

P.S.: Explicit "default (Int)" does not resolve this.

答:
You're right about the overloading. It's a little tricky. Firstly, you will have to give a type signature to resolve  the numeric overloading in your example:

```<code>Ambiguous type variable `a0' in the constraints:
  (Some a0) arising from a use of `toSome' at A.hs:11:16-21
  (Num a0) arising from the literal `3' at A.hs:11:23
</code>```

this means, as you noticed, that you have to pick a particular solution type, such as  Int.

So how does Show work? By the magic of extended defaulting rules. Show is special, and GHCi enables some special defaulting rules to help "default" the type in arguments of Show to Integer.

Your new class isn't one of the magic classes that the extended defaulting feature knows about, so sadly, you will need to give type annotations.

Body:
I'm trying to declare my own data with appropriate conversion as class. My code looks like this:

data SomeData =  SInteger Integer | SElse deriving Show

class Some a where
    toSome :: a -> SomeData

instance Some Int where toSome = SInteger . toInteger

main :: IO ()
main = print $ toSome 3

But GHC (7.0.3) becomes angry and says:

Ambiguous type variable `a0' in the constraints:
      (Some a0) arising from a use of `toSome'
                at minimal_broken.hs:11:16-21
      (Num a0) arising from the literal `3' at minimal_broken.hs:11:23
    Probable fix: add a type signature that fixes these type variable(s)

Explicit type signature (like 3::Int) fixes the issue, but it's very inconvenient.

Standard "Show" works just fine, and according to the manual it's declared exactly the same way.

Why standard Show works, but my class doesn't? Did I miss something?

P.S.: Explicit "default (Int)" does not resolve this.

Body:
You're right about the overloading. It's a little tricky. Firstly, you will have to give a type signature to resolve  the numeric overloading in your example:

Ambiguous type variable `a0' in the constraints:
  (Some a0) arising from a use of `toSome' at A.hs:11:16-21
  (Num a0) arising from the literal `3' at A.hs:11:23

this means, as you noticed, that you have to pick a particular solution type, such as  Int.

So how does Show work? By the magic of extended defaulting rules. Show is special, and GHCi enables some special defaulting rules to help "default" the type in arguments of Show to Integer.

Your new class isn't one of the magic classes that the extended defaulting feature knows about, so sadly, you will need to give type annotations.


问:
PhantomJS can't load correctly web page
I'm currently trying to scrape a web page with PhantomJS and Selenium (python 2.7.9 on Windows 7) but PhantomJS fail to load correctly the web page. If I use Firefox as webdriver I have no problem to see the page as I want.
At first I thought it was a javascript problem (page-side) since with save_screenshot I could see what normally the page shows when javascript is disabled, but if I disable javascript the page show me correctly that "Javascript must be enabled", so it is not a js problem. Maybe some delay would help? I've also tried to put a time.sleep(up to 180 sec) but nothing.
Source code is below.

Any suggestion?

```<code>from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

import time

cap = webdriver.DesiredCapabilities.PHANTOMJS
cap["phantomjs.page.settings.javascriptEnabled"] = True
#options = Options()
#options.headless = True
timeout = 30

driver = webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true', '--ssl-protocol=tslv1.0'])

driver.set_window_size(1024, 768)
driver.implicitly_wait(60)
#WebDriverWait(driver, 10).until(lambda driver: driver.execute_script('return document.readyState') == 'complete')
#executable_path="C:\\userdata\\giom\\Py_exercises\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe"
driver.get("https://account.booking.com/register?op_token=EgVvYXV0aCJ7ChQ2Wjcyb0hPZDM2Tm43emszcGlyaBIJYXV0aG9yaXplGhpodHRwczovL2FkbWluLmJvb2tpbmcuY29tLyo2eyJwYWdlIjoiL3JlZGlyZWN0LXRvLWpvaW5hcHAtbHA_bGFuZz1pdCZhaWQ9MTE4NzM2MCJ9QgRjb2RlKg4QAToAQgBY5dGK8gVgAQ")
#driver.get('https://join.booking.com/category/index.html?label=continue&token=36094c4799610d5826138ec328f43b044b027cbb')
#result_loading = driver.onLoadFinished()
#print result_loading

html = driver.page_source
#print html.encode("utf-8")

driver.save_screenshot("C:\userdata\giom\Py_exercises\sample.png")

driver.close()

#driver.find_element(By.XPATH, "//div[@id='root']")
#driver.find_element_by_xpath("//input[@id='login_name_register']")
</code>```

答:
A bit more information about your usecase would have helped to analyze your issue. However, on windows-10 using Selenium v3.141.0 and phantomjs v2.1.1.0 here is the execution result:

Code Block:

```<code>from selenium import webdriver

driver = webdriver.PhantomJS(executable_path=r'C:\WebDrivers\phantomjs.exe', service_args=['--ignore-ssl-errors=true', '--ssl-protocol=tslv1.0'])
driver.set_window_size(1920, 1080)
driver.get("https://account.booking.com/register?op_token=EgVvYXV0aCJ7ChQ2Wjcyb0hPZDM2Tm43emszcGlyaBIJYXV0aG9yaXplGhpodHRwczovL2FkbWluLmJvb2tpbmcuY29tLyo2eyJwYWdlIjoiL3JlZGlyZWN0LXRvLWpvaW5hcHAtbHA_bGFuZz1pdCZhaWQ9MTE4NzM2MCJ9QgRjb2RlKg4QAToAQgBY5dGK8gVgAQ")
print(driver.page_source)
driver.quit()
</code>```

Console Output:

```C:\Python\lib\site-packages\selenium\webdriver\phantomjs\webdriver.py:49: UserWarning: Selenium support for PhantomJS has been deprecated, please use headless versions of Chrome or Firefox instead
  warnings.warn('Selenium support for PhantomJS has been deprecated, please use headless '
<!DOCTYPE html>
<meta http-equiv="X-UA-Compatible" content="IE=edge">

<title>Booking.com Account</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="referrer" content="origin-when-cross-origin">
<link rel="shortcut icon" href="/favicon.ico">
.
.
.

Title: PhantomJS can't load correctly web page

Body:
I'm currently trying to scrape a web page with PhantomJS and Selenium (python 2.7.9 on Windows 7) but PhantomJS fail to load correctly the web page. If I use Firefox as webdriver I have no problem to see the page as I want.
At first I thought it was a javascript problem (page-side) since with save_screenshot I could see what normally the page shows when javascript is disabled, but if I disable javascript the page show me correctly that "Javascript must be enabled", so it is not a js problem. Maybe some delay would help? I've also tried to put a time.sleep(up to 180 sec) but nothing.
Source code is below.

Any suggestion?

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

import time

cap = webdriver.DesiredCapabilities.PHANTOMJS
cap["phantomjs.page.settings.javascriptEnabled"] = True
#options = Options()
#options.headless = True
timeout = 30

driver = webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true', '--ssl-protocol=tslv1.0'])

driver.set_window_size(1024, 768)
driver.implicitly_wait(60)
#WebDriverWait(driver, 10).until(lambda driver: driver.execute_script('return document.readyState') == 'complete')
#executable_path="C:\\userdata\\giom\\Py_exercises\\phantomjs-2.1.1-windows\\bin\\phantomjs.exe"
driver.get("https://account.booking.com/register?op_token=EgVvYXV0aCJ7ChQ2Wjcyb0hPZDM2Tm43emszcGlyaBIJYXV0aG9yaXplGhpodHRwczovL2FkbWluLmJvb2tpbmcuY29tLyo2eyJwYWdlIjoiL3JlZGlyZWN0LXRvLWpvaW5hcHAtbHA_bGFuZz1pdCZhaWQ9MTE4NzM2MCJ9QgRjb2RlKg4QAToAQgBY5dGK8gVgAQ")
#driver.get('https://join.booking.com/category/index.html?label=continue&token=36094c4799610d5826138ec328f43b044b027cbb')
#result_loading = driver.onLoadFinished()
#print result_loading

html = driver.page_source
#print html.encode("utf-8")

driver.save_screenshot("C:\userdata\giom\Py_exercises\sample.png")

driver.close()

#driver.find_element(By.XPATH, "//div[@id='root']")
#driver.find_element_by_xpath("//input[@id='login_name_register']")

Body:
A bit more information about your usecase would have helped to analyze your issue. However, on windows-10 using Selenium v3.141.0 and phantomjs v2.1.1.0 here is the execution result:

Code Block:

from selenium import webdriver

driver = webdriver.PhantomJS(executable_path=r'C:\WebDrivers\phantomjs.exe', service_args=['--ignore-ssl-errors=true', '--ssl-protocol=tslv1.0'])
driver.set_window_size(1920, 1080)
driver.get("https://account.booking.com/register?op_token=EgVvYXV0aCJ7ChQ2Wjcyb0hPZDM2Tm43emszcGlyaBIJYXV0aG9yaXplGhpodHRwczovL2FkbWluLmJvb2tpbmcuY29tLyo2eyJwYWdlIjoiL3JlZGlyZWN0LXRvLWpvaW5hcHAtbHA_bGFuZz1pdCZhaWQ9MTE4NzM2MCJ9QgRjb2RlKg4QAToAQgBY5dGK8gVgAQ")
print(driver.page_source)
driver.quit()

Console Output:

C:\Python\lib\site-packages\selenium\webdriver\phantomjs\webdriver.py:49: UserWarning: Selenium support for PhantomJS has been deprecated, please use headless versions of Chrome or Firefox instead
  warnings.warn('Selenium support for PhantomJS has been deprecated, please use headless '
<!DOCTYPE html><html class="js" lang="en-us"><head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script async="" src="https://www.google-analytics.com/analytics.js"></script><script nonce="dmA0wdY6a4DdToc" src="https://account.booking.com/error_catcher"></script>
<script nonce="dmA0wdY6a4DdToc">(function(H){H.className=H.className.replace(/\bno-js\b/,'js')})(document.documentElement)</script>
<title>Booking.com Account</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="referrer" content="origin-when-cross-origin">
<link rel="shortcut icon" href="/favicon.ico">
.
.
.
<script nonce="dmA0wdY6a4DdToc"> (function() { var list = []; list.push({"private":{"account_oauth_small_print_footer":"By clicking \"{btn_label}\" you authorize {service_name} to use your {b_companyname} account info according to {service_name} {start_link}Terms of service{end_link}.","account_sign_in_no_venue_input":"Enter your venue name","account_tfa_email_heading":"Two Factor Authentication","account_oauth_review_includes":"Includes:","account_sign_in_menu_create_account":"Create your account","account_create_phone_label":"Phone number","iam_ext_signin_subtitle":"Continue to view the credit card details. ","account_tfa_pulse_verification_header":"Pulse verification code","sal_provider_account_create_consent_continue":"Continue","iam_ext_password_expired_header":"Your password has expired","iam_ap_dropdown_menu_desc":"Useful links menu","account_oauth_service_would_like_to_access":"{start_bold}{service_name}{end_bold} wants to access:","extranet_cant_2fa_no_access_to_phone":"The phone number is correct, but nobody has access to it","account_oauth_service_would_like_to_access_your":"{service_name} wants to access your:","account_modal_forgot_your_password_inform":"No problem – want to reset your password?","account_terms_privacy_footer":"By signing in or creating an account, you agree with our {start_link1}Terms & Conditions{end_link1} and {start_link2}Privacy Statement{end_link2}","account_create_password_different_pw_error":"The passwords you entered didn't match – try again","account_create_account_inform":"Create an account to use {b_companyname} services easily.","account_sign_in_menu_forgot_username":"Forgot your email address?","oauth_scope_title_photo":"Photo","ext_onboarding_create_password_bad_password":"Passwords can't be reused, need to be at least 8 characters long (containing both numbers and letters), and shouldn't use a predictable pattern, word, or phrase.","account_copyright":"Copyright (2006-{year}) – Booking.com™ ","account_recover_no_input":"Enter your email address","oauth_scope_title_birth_date":"Date of birth","account_sign_in_grab":"Sign in with Grab","oauth_scope_title_payment_details":"Payment details","iam_ap_sign_in_link":"Already have an account? {start_link}Sign in{end_link}","account_create_password_phone_inform":"Choose a password for your {b_companyname} account connected to {phone}.","account_social_error_no_email":"We haven't received your email – please try again.","account_signin_add_password_header":"Create a password","account_sign_in_apple":"Sign in with Apple","account_sign_in_no_such_username":"There's no account associated with this username. {start_link}Create an account{end_link} to access our services","account_validation_sms_code_invalid":"Verification code needs to contain 6 digits","account_sign_in_create_header":"Don't have an account yet?","account_modal_forgot_your_password_header":"Forgot your password?","account_create_account_fb":"Register with Facebook","account_create_account_wechat":"Register with WeChat","account_recover_options_header":"Having trouble signing in?","account_tfa_menu_item_other":"Other options","account_create_account_next_cta":"Next","account_sign_in_china_auth_low_header":"Welcome back","account_create_phone_confirm_header":"Phone number verification","account_create_account_user_found":"You already have a {b_companyname} account registered to this email: {email}. You can {start_link}sign in here{end_link}.","account_reset_password_confirm_lbl":"Confirm password","account_confirmation_token_expired":"The verification link has expired – please try again.","account_tfa_customer_service_option_inform":"Call your local customer service at the number listed {start_link}here{end_link} and give us the PIN you see on the screen. The customer service agent will give you a new verification code to enter below.","ext_admin_button_register":"Register","account_reset_password_inform_extranet":"Pick a new password for your {b_companyname} account. It should not contain your property ID or username.","oauth_scope_title_address":"Address","account_terms_conditions":"Terms & conditions","account_sign_in_create_header_ext":"Add your property to {b_companyname}","account_tfa_pulse_verification_help_cta":"Where is the code?","account_tfa_loading":"Loading...","account_phone_verification_signin_cta":"Verify and sign in","account_create_password_short_pw_error":"Your password needs to be at least 8 characters long","account_tfa_verification_methods_header":"Verification method","account_sign_in_no_input":"Enter your email address","account_incorrect_phone":"Enter the phone number linked to your account","account_sign_in_password_inform":"Enter your {b_companyname} password for {start bold}{email_address}{end bold}.","account_sign_in_auth_low_password_header_with_name":"Welcome back, {name}","account_tfa_verification_method_sms":"Text message (SMS)","account_verify_resend_email_cta":"Resend email","account_create_surname_label":"Last name","account_recover_back_to_sign_in":"Back to sign-in","account_locked_inform":"We temporarily locked your account for security reasons. To unlock your account, click \"Resend email\" below and we'll email you a link to reset your password.","account_sign_in_inform":"You can sign in using your {b_companyname} account to access our services.","iam_ext_password_too_small_or_too_big":"Password must be between 8 and 72 characters long","account_reset_password_sign_in_cta":"Sign in","account_sign_in_china_auth_low_cta":"Sign in","account_validation_sms_code_empty":"Enter a verification code","account_tfa_recovery_error_incorrect_phone":"This phone number doesn't match the one in our records – please try again.","account_tabs_phone_lbl":"Mobile number","account_oauth_review_allow_service_to_access":"Allow {start_bold}{service_name}{end_bold} to access:","account_sign_in_auth_low_password_inform":"Looks like you've been away for a while. Please enter your {b_companyname} password for {start_bold}{email_address}{end_bold}. {start_link}Not you?{end_link}","language_exception_account_tfa_timer_1":"This message should arrive in {tfa_timer} second.","account_tfa_timer":"This message should arrive in {tfa_timer} seconds.","account_sign_in_invalid_phone":"Make sure the phone number you entered is correct.","account_validation_password_too_short":"Your new password has to be at least 8 characters long","extranet_cant_2fa_phone_is_incorrect":"The phone number is incorrect, but I can't log in to update it\n","account_recover_go_to_sign_in":"Go to sign-in","iam_ap_signup_link":"Don't have an account yet? {start_link}Sign up{end_link}","account_recover_contact_support_inform":"Unfortunately, we're unable to help you retrieve your username – please contact your local support team.","accounts_lb_session_timedout_inactivity":"Your session timed out due to inactivity. Reenter your password to continue. ","account_error_invalid_username_password_attempt":"The username and password entered don't match – please try again. After {num} attempts, your account will be locked. Forgot your password? Click {start_link}here to reset it{end_link}.","account_error_already_confirmed":"Your account was already verified.","account_create_account_china_header":"Create your account","asi_scalability_partner_login_password_flow_show_password":"Show password","oauth_scope_title_email":"Email address","close":"Close","account_tfa_error_incorrect_code":"This verification code is incorrect – please try again. ","web_ge_week_block_sub_header_sign_in":"You'll get 7 days of Genius travel rewards when you sign in","account_create_title_label_mr":"Mr.","account_sign_in_invalid_email":"Make sure the email address you entered is correct. ","account_reset_password_password_lbl":"New {b_companyname} password","iam_ap_joinapp_header":"Sign up","account_signin_add_password_btn":"Create password and sign in","account_sign_in_china_cta":"Sign in","account_menu_back":"Back","account_validation_name":"Enter your full name and title","account_validation_phone_code_empty":"Enter a verification code","auth_next_step_error_wrong_verification_code":"Enter a valid verification code","loc_social_connect_google_sign_in":"Sign in with Google","account_portal_back_btn_label":"Return to the previous page","account_phone_verification_inform":"You can sign in by verifying your number {start_strong}{phone}{end_strong} through a text.","account_create_account_naver":"Register with Naver","account_create_password_repeat_no_pw_error":"Confirm your password","account_modal_forgot_your_password_cta_yes":"Yes, help me","account_error_password_attempt_when_disabled":"Password not reset","account_add_backup_option_inform":"Set a password so you can still sign in when you don't have access to your phone.","iam_ext_previous_password_used":"Looks like this password was recently updated.","iam_password_policy_indicator_extranet":"Your password should be at least {start_style_one}eight characters{end_style_one} long and contain both {start_style_two}letters{end_style_two} and {start_style_three}numbers{end_style_three}.","account_tfa_select_phone_header":"Select phone number","account_create_account_email_or_phone_lbl":"Email or phone","account_oauth_connect_as":"as: {username}","account_sign_in_china_add_phone_cta":"Verify now","account_signin_method_email":"Sign in with email","account_sign_in_no_such_venue_username":"There's no account associated with this venue/username","account_sign_in_china_add_phone_header":"Verify mobile number","extranet_cant_2fa_phone_not_private":"The phone number is correct, but someone else has access to it","account_tfa_header":"Two Factor Authentication","account_sign_in_china_add_phone_inform":"Verify your mobile number. This will help us confirm your identity and protect your account.","account_sign_in_naver":"Sign in with Naver","account_signin_verify_email_btn":"Send email verification link","iam_ext_signin_title":"Sign in ","we_use_cookies":"This website uses cookies. Click {startlink}here{endlink} for more information.","account_create_property_ext":"Create account","account_tfa_recovery_next_cta":"Next","social_connect_title_apple":"Apple","account_sign_in_auth_low_password_header":"Welcome back","account_sign_in_no_username_input":"Enter your username","accounts_make_changes_with_bno_and_pin":"Make changes to a booking with your {start_link}confirmation number and PIN{end_link}","account_oauth_cancel":"Cancel","account_rights_reserved":"All rights reserved","oauth_scope_title_location":"Location","account_sign_in_china_inform":"Sign in using your {b_companyname} account to access our services.","account_sign_in_email_lbl":"Email","account_tfa_options_submit_cta":"Verify now","account_recover_confirm_email_cta":"Confirm","lxp_copy_bp_account_lightbox_header_password_cta":"Create my password","iam_ext_reassurance":"We're currently improving the way you sign in to the Extranet","iam_ext_customer_service_pin":"Provide {b_companyname} with this PIN:","account_recover_forgot_username":"Forgot your username?","account_tfa_recovery_header":"Confirm phone number","account_validation_phone_empty":"Enter a phone number","account_create_personal_details_header":"Contact details","social_connect_title_grab":"Grab","account_recover_invalid_email":"Double-check your email address is correct","account_sign_in_password_forgot":"Forgot your password?","account_tfa_pulse_help_inform":"Find your verification code in Pulse by following these steps:","account_create_account_or":"or","account_sign_in_china_wrong_password":"Incorrect password – try again.","ugc_error_message_locked_account":"To protect you, we've locked your account after multiple incorrect password entries. Please wait or {start_link}reset your password{end_link} to unlock.","account_oauth_allow_access":"Allow access","account_create_title_label":"Title","account_tfa_verification_code_sent_timer":"The verification code should arrive in {tfa_timer} seconds","account_phone_login_reset_pw_sms":"{b_companyname} password reset link: {url}","account_verify_maybe_later_cta":"I'll do this later","account_signin_methods_inform":"Select a login method","account_create_account_header":"Create your account","ext_login_pw_fail_link":"The login name and password you entered don't match – please try again. After {num} attempts, you'll be locked out of your account. You can reset your password by clicking, {start_link}\"Forget your password?\"{end_link}.","account_sign_in_google":"Sign in with Google","account_tfa_pulse_help_header":"Finding your verification code","language_exception_account_tfa_verification_code_sent_mini_timer_1":"{tfa_timer}s","account_sign_in_fb":"Sign in with Facebook","iam_password_policy_indicator_styling":"Your password needs to have {start_style_one}at least one number{end_style_one} and a {start_style_two}minimum of eight characters{end_style_two}.","account_disabled_header":"Account disabled","account_sign_in_china_auth_low_inform":"To sign in, you need to verify your phone number. We sent a code to {start_strong}{phone}{end_strong}. Enter it below to continue. {start_link}Not your number?{end_link}","account_tfa_select_phone_help_cta":"Unable to verify?","fe_index_list_property_persuasion_text":"Rent out your place on {b_companyname}","account_create_account_phone_found":"You already have a {b_companyname} account registered to this phone: {phone}. You can {start_link}sign in here{end_link}.","language_exception_account_error_invalid_username_password_attempt_1":"The username and password entered don't match – please try again. After {num} attempt, your account will be locked. Forgot your password? Click {start_link}here to reset it{end_link}.","account_tfa_email_context":"We emailed you a temporary verification code that will allow you to access your account.","account_create_account_sign_in_cta":"Sign in","account_signin_method_wechat":"Sign in with WeChat","account_oauth_review_save_cta":"Save","account_input_email_lbl":"Email","account_tfa_verification_code_lbl":"Verification code","account_sign_in_create_inform":"Create an account to use {b_companyname} services easily.","account_sign_in_china_header":"Sign in","account_menu_close":"Close","account_sign_in_inform_ext":"Access the Extranet to manage your property, continue registration or list a new property.","ext_admin_login_page_sign_in_to_manage":"Sign in to manage your property","account_locked_inform_email":"To unlock your account, request an email with a link to reset your password.","account_error_invalid_username_password":"The username and password combination entered doesn't match.","account_tfa_verification_methods_inform":"Select a verification method to complete the sign-in process.","account_tfa_pulse_verification_inform":"To complete your sign-in, open the Pulse app to find your verification code. If you can't verify it, look at these {start_link}other options{end_link}","account_reset_password_header":"Create new password","iam_ext_help_links_old":"Questions about your property or the Extranet? Check out {start_link1}Partner Help{end_link1} or ask another partner on the {start_link2}Partner Forum{end_link2}.","account_create_existing_user_found":"You already have an account registered with this email: {email}. You can {start_link}sign in{end_link} directly.","account_recover_email_lbl":"Email address","account_signin_verify_email_inform":"You're trying to sign in to an account that doesn't have a password. To sign in, verify your email.","account_disabled_inform_cta":"Contact support","social_connect_title_opentable":"OpenTable","account_sign_in_no_such_user":"Looks like there isn't an account associated with this email address. You can {start_link}create an account{end_link} to access our services.","iam_ext_password_not_alphanumeric":"Password must contain a combination of letters and numbers","account_sign_in_password_menu_forgot_pw":"Forgot your password? Reset it here","account_locked_inform_phone":"To unlock your account, request a text with a link to reset your password.","account_tfa_resend_sms":"Resend code","iam_ext_password_not_allowed":"Passwords shouldn't contain easy-to-guess character strings (e.g. your username, hotel ID, email, etc.)","account_sign_in_wechat":"Sign in with WeChat","account_signin_methods_header":"Sign in","account_recover_phone_confirmation_inform":"We just sent a text message with a link to reset your password to {start_bold}{user_name}{end_bold}.","account_error_invalid_email_password":"The email and password combination entered doesn't match.","account_create_account_email_lbl":"Email","account_tfa_customer_service_option_header":"Contact customer service","account_locked_inform_new":"We've locked your {b_companyname} account for security purposes.","account_recover_phone_inform":"Just confirm your phone number, then we'll send you a link to reset your password.","account_modal_forgot_your_password_cta_no":"No, try again","bp_account_lightbox_header_password_2":"Create a password so you can securely manage this booking","account_tfa_recovery_error_no_phone":"Please enter a phone number","account_tfa_pulse_verification_help_back_cta":"Back to verification","account_input_phone_lbl":"Phone","settings_page_error_message":"Sorry, something went wrong. Please try again.","account_validation_new_password_empty":"Please enter your new password","account_signin_verification_sent_inform":"We sent a link to verify your email to {start_strong}{user_name}{end_strong}. Follow the link in the email to continue.","asi_scalability_partner_login_password_flow_hide_password":"Hide password","account_settings_label_language":"Language","account_sign_in_password_header":"Sign in","account_validation_sms_phone_invalid":"Not a valid phone number","account_create_password_header":"Create password","account_sign_in_next_cta":"Next","account_sign_in_or":"or","account_create_phone_confirm_inform":"A text message with a 6-digit verification code was sent to your phone for verification.","account_recover_confirmation_inform":"We just emailed a link to reset your password to {start_bold}{user_name}{end_bold}.","account_tfa_select_phone_for_sms_inform":"Select a phone number to receive your verification code in a text message (SMS)","account_create_account_china_inform":"Create an account to use {b_companyname} services.","account_locked_send_email_cta":"Unlock with email","account_sign_in_email_or_phone_lbl":"Email or phone","web_ge_week_block_promo_message_all_users":"Genius is {b_companyname}'s loyalty program","account_sign_in_china_phone_not_found":"There's no account registered with this number. {start_link}Create an account{end_link} to access our services.","account_tfa_email_lbl":"Verification code","account_create_title_label_ms":"Ms.","account_sign_in_create_inform_ext":"Create a partner account to list and manage your property.","account_sign_in_attractions_no_account_error":"There isn't an account connected to this username. {start_link}Create an account{end_link} to access our services.","extranet_cant_2fa_because_no_call_sms":"The phone number is correct, but I didn't receive a call/text message","account_cookies_close":"Close","account_sign_in_header_new":"Sign in","account_reset_password_cta":"Set new password","account_tfa_menu_item_resend":"Resend code","account_recover_options_inform":"We're here to help. Below are some options to help you get back on track.","account_contact_support_cta":"Contact support","account_sign_in_password_validation_no_pw":"Enter your {b_companyname} password","language_exception_account_tfa_verification_code_sent_mini_timer_0":"{tfa_timer}s","account_social_email_inform":"Enter your email to continue","account_verify_inform_activation":"To confirm your account, follow the link in the email we just sent.","account_list_your_property":"List Your Property","account_oauth_menu_item_sign_out":"Sign out","account_tabs_email_lbl":"Email address","oauth_scope_title_dob":"Date of birth","account_forgot_username":"Forgot your username?","account_settings_security_error_wrong_verification_code":"Enter a valid verification code","account_tfa_ios_verification_device":"iOS devices","social_connect_title_google":"Google","account_recover_heading":"Forgot your password?\n\n","iam_ext_password_expired_inform":"To keep your account secure, you'll need to reset your password. We sent a reset link to {start_bold}{email}{end_bold}.","ext_admin_button_register_another_property":"Register another property","account_create_title_label_mrs":"Mrs.","account_tfa_options_back_cta":"Back to verification","partner_fraud_verification_portal_attempts_header":"Sorry, too many attempts","web_ge_week_block_sub_header_create_account":"You'll get 7 days of Genius travel rewards when you create an account","account_signin_method_phone":"Sign in with phone number","account_create_account_get_started_cta":"Get started","iam_ap_joinapp_inform":"Create an account to list and manage your property.","account_tfa_verification_method_pulse":"Pulse app","login_error_wrong":"Incorrect email address or password. Please try again.","ext_admin_login_name":"Login name","account_tfa_verification_method_call":"Phone call","account_please_verify_header":"Verify your account","account_please_verify_inform":"In order to access {start_bold}{service_name}{end_bold} you have to verify your {b_companyname} account.","account_tfa_andorid_device":"Android devices","account_sign_in_china_auth_low_inform_v2":"Sign in by verifying your number {start_strong}{phone}{end_strong} by text. {start_link}Not your number?{end_link}","language_exception_account_tfa_email_timer_1":"This email should arrive in {tfa_timer} second.","account_signin_verify_email_header":"Verify your email","social_connect_title_naver":"Naver","account_validation_phone_acc_exists":"You already have an account registered with this number. Continue with verification to sign in.","account_tfa_recovery_phone_lbl":"Phone number","account_tfa_verification_code_sent_inform":"We sent a verification code to your phone: {start_bold}{phone_number}{end_bold}. If you still can't verify it, review these {start_link}other options{end_link}","account_sign_in_password_validation_combo":"The email and password combination you entered doesn't match.","account_verify_inform":"We sent an email with a verification link to {start_bold}{email}{end_bold}.","account_create_password_create_cta":"Create account","account_recover_confirmation_header":"Check your inbox","account_tfa_verification_code_call_timer":"You should get a phone call soon","account_locked_header":"Account locked","account_tfa_verification_code_andorid":"Find code in Pulse for Android","account_confirmation_problem":"Something went wrong","account_oauth_edit_information":"Manage permissions","account_tfa_select_phone_cta":"Call now","account_phone_verification_header":"Verify your number","account_tfa_menu_item_close":"Close","account_locked_resend_email_cta":"Resend email","account_reset_password_confirmed_header":"New password confirmed","account_connect_social_password_header":"Confirm your password","oauth_scope_title_genius":"Genius status","bba_register_b4b_2":"Interested in {start_link}{b_companyname} for Business?{end_link}","account_tfa_an_sms_sent":"We sent a verification code to your phone. Please enter this code in the box below.  If you can't use the verification code, check out these {start_link}other options{end_link}.","account_create_password_pw_lbl":"Create password","account_sign_in_cta":"Sign in","iam_ext_partner_hep_centre_link":"Have any questions about your property or the Extranet? Check out {start_link}Partner Help{end_link} to learn more.","account_sign_in_password_cta":"Sign in","account_tfa_verification_code_call_inform":"Enter the verification code provided to you by {b_companyname}. If you can't verify it, review these {start_link}other options{end_link}","language_exception_account_tfa_verification_code_sent_timer_1":"The verification code should arrive in {tfa_timer} second","account_create_first_name_label":"First name","account_business_bookers":"Interested in {start_link}{b_companyname} for Business?{end_link}","account_recover_contact_support_header":"Contact local support team","account_tfa_customer_service_option2_inform":"Keep in mind that for security reasons we can only authorize logins verified by a call/text message. If you can't use any of your saved phone numbers right now, try waiting until you can use them. If you have an urgent issue but don't have access to these phone numbers, {start_link}contact us here{end_link}.","account_recover_inform":"Just confirm your email, then we'll send you a link to reset your password","account_validation_phone_code_invalid":"Verification code needs to contain 6 digits","oauth_scope_title_phone":"Phone number","account_create_account_google":"Register with Google","account_create_password_repeat_pw_lbl":"Confirm password","account_email_confirmed_thanks":"Thanks for confirming your email address.","account_tfa_error_no_code":"Please provide a verification code","account_oauth_not_you":"Not you?","account_tfa_code_lbl":"Verification code","account_tfa_menu_item_back":"Back","account_signin_password_header":"Sign in with password","account_signin_add_password_inform":"Create a password for your account to avoid this later.","iam_a11y_current_language_aria_label":"Select your language. Your current language is {/language_options/[language]/name}","account_oauth_service_would_like_to_access_no_sharing":"None of your {b_companyname} account info will be shared with {service_name}","account_locked_send_sms_cta":"Unlock with text message","language_exception_ext_login_pw_fail_link_1":"The login name and password you entered don't match – please try again. After {num} attempt, you'll be locked out of your account. You can reset your password by clicking, {start_link}\"Forget your password?\"{end_link}.","account_tfa_email_timer":"This email should arrive in {tfa_timer} seconds.","account_reset_password_confirmed_inform":"Welcome back! Your new password was confirmed","iam_ap_dropdown_menu_btn_label":"Useful links","account_disabled_inform":"For security reasons, this {b_companyname} account belonging to {user_name} was disabled from accessing our products and services.","account_signin_continue_with_wechat":"Continue with WeChat","account_tfa_select_phone_sms_cta":"Send verification code","account_tfa_send_sms":"Send code","social_connect_title_facebook":"Facebook","account_oauth_connect_to":"Connect to {start_bold}{service_name}{end_bold}","account_tfa_options_header":"Reasons for verification issues","web_ge_week_block_header_all_users":"It's Genius Week!","account_validation_sms_phone_empty":"Enter a phone number","account_validation_last_name_empty":"Enter your last name","account_locked_incorrect_password_limit":"We temporarily locked your account because you entered an incorrect password several times. To unlock your account, click \"Resend email\" below and we'll email you a link to reset your password.","sal_provider_account_create_consent_header":"You're about to sign in to {b_companyname}
.
.
.
<iframe name="_hjRemoteVarsFrame" title="_hjRemoteVarsFrame" id="_hjRemoteVarsFrame" src="https://vars.hotjar.com/box-469cf41adb11dc78be68c1ae7f9457a4.html" style="display: none !important; width: 1px !important; height: 1px !important; opacity: 0 !important; pointer-events: none !important;"></iframe><div id="ads"></div></body></html>


问:
Tap screen to trigger autofocus with getUserMedia
The API with getUserMedia is very useful to have a video stream inside the browser/inside a HTML5 page, see for example https://www.html5rocks.com/en/tutorials/getusermedia/intro/ or https://simpl.info/getusermedia/sources/.

From this API, how to trigger an autofocus of the (smartphone) camera when doing a tap in the video display?

This is indeed the usual behaviour in nearly all smartphone camera apps.

I haven't found anything about "focus" in the API documentation MediaDevices.getUserMedia()

答:
This is impossible right now but it may be possible in the near future. You should take a look at MediaStream Image Capture Working Draft. This spec describes advance options for .applyConstraints, initially introduced in Media Capture and Streams.

How it works according to spec? First, you need to get the capabilities by using .getCapabilities. If the browser can manage focus, then you can set focusMode: "auto" | "manual" and focusDistance: number for current constraints.

Focus mode describes the focus setting of the capture device (e.g. auto or manual).

Focus distance is a numeric camera setting that controls the focus distance of the lens. The setting usually represents distance in meters to the optimal focus distance.

Unfortunately, you can't control the focus at the moment, but you can check the code that may work in the future.

Chrome issue about support for focusDistance | Chrome Platform Status | MediaCapture Image Implementation Status.

CodeSandbox Demo

navigator.mediaDevices
  .getUserMedia({ video: true })
  .then(gotMedia)
  .catch(err => console.error("getUserMedia() failed: ", err));

function gotMedia(mediastream) {
  const video = document.querySelector("video");
  video.srcObject = mediastream;

  const track = mediastream.getVideoTracks()[0];
  const capabilities = track.getCapabilities();

  // Check whether focus distance is supported or not.
  if (!capabilities.focusDistance) {
    return;
  }

  // Map focus distance to a slider element.
  const input = document.querySelector('input[type="range"]');
  input.min = capabilities.focusDistance.min;
  input.max = capabilities.focusDistance.max;
  input.step = capabilities.focusDistance.step;
  input.value = track.getSettings().focusDistance;

  input.oninput = function(event) {
    track.applyConstraints({
      advanced: [{
        focusMode: "manual",
        focusDistance: event.target.value
      }]
    });
  };
  input.hidden = false;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><video autoplay></video>
<input type="range" hidden /></code>```

Body:
This is impossible right now but it may be possible in the near future. You should take a look at MediaStream Image Capture Working Draft. This spec describes advance options for .applyConstraints, initially introduced in Media Capture and Streams.

How it works according to spec? First, you need to get the capabilities by using .getCapabilities. If the browser can manage focus, then you can set focusMode: "auto" | "manual" and focusDistance: number for current constraints.

Focus mode describes the focus setting of the capture device (e.g. auto or manual).

Focus distance is a numeric camera setting that controls the focus distance of the lens. The setting usually represents distance in meters to the optimal focus distance.

Unfortunately, you can't control the focus at the moment, but you can check the code that may work in the future.

Chrome issue about support for focusDistance | Chrome Platform Status | MediaCapture Image Implementation Status.

CodeSandbox Demo

navigator.mediaDevices
  .getUserMedia({ video: true })
  .then(gotMedia)
  .catch(err => console.error("getUserMedia() failed: ", err));

function gotMedia(mediastream) {
  const video = document.querySelector("video");
  video.srcObject = mediastream;

  const track = mediastream.getVideoTracks()[0];
  const capabilities = track.getCapabilities();

  // Check whether focus distance is supported or not.
  if (!capabilities.focusDistance) {
    return;
  }

  // Map focus distance to a slider element.
  const input = document.querySelector('input[type="range"]');
  input.min = capabilities.focusDistance.min;
  input.max = capabilities.focusDistance.max;
  input.step = capabilities.focusDistance.step;
  input.value = track.getSettings().focusDistance;

  input.oninput = function(event) {
    track.applyConstraints({
      advanced: [{
        focusMode: "manual",
        focusDistance: event.target.value
      }]
    });
  };
  input.hidden = false;
}

<video autoplay></video>
<input type="range" hidden />


问:
ComboBox.SelectedText doesn't give me the SelectedText
I am building a String and the code looks like

```<code>String status = "The status of my combobox is " + comboBoxTest.SelectedText
</code>```

I am using WinForm in VS2010

The result looks like

"The status of my combobox is "

答:
All of the previous answers explain what the OP 'should' do.  I am explaining what the .SelectedText property is.

The .SelectedText property is not the text in the combobox.  It is the text that is highlighted.  It is the same as .SelectedText property for a textbox.

The following picture shows that the .SelectedText property would be equal to "ort".

Body:
I am building a String and the code looks like

String status = "The status of my combobox is " + comboBoxTest.SelectedText

I am using WinForm in VS2010

The result looks like

"The status of my combobox is "