问:
npm ERR! code ELIFECYCLE when using bash script with npm
I am simply trying to use some bash to check some things then run the commands I want. But I'm getting stuck at the first hurdle:

hutber.sh

```<code>#!/bin/bash
echo 'hutber' ; exit 1;
</code>```

package.json

```<code>"hutber": "./hutber.sh"
</code>```

terminal

```<code>hutber@hutber-mint /var/www/mvt-framework $ npm run hutber

> mvt-framework@0.0.1 hutber /var/www/mvt-framework
> ./hutber.sh

hutber
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! mvt-framework@0.0.1 hutber: `./hutber.sh`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the mvt-framework@0.0.1 hutber script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/hutber/.npm/_logs/2017-12-05T15_52_44_355Z-debug.log
</code>```

error log

```<code>0 info it worked if it ends with ok
1 verbose cli [ '/home/hutber/.nvm/versions/node/v8.7.0/bin/node',
1 verbose cli   '/home/hutber/.nvm/versions/node/v8.7.0/bin/npm',
1 verbose cli   'run',
1 verbose cli   'hutber' ]
2 info using npm@5.4.2
3 info using node@v8.7.0
4 verbose run-script [ 'prehutber', 'hutber', 'posthutber' ]
5 info lifecycle mvt-framework@0.0.1~prehutber: mvt-framework@0.0.1
6 info lifecycle mvt-framework@0.0.1~hutber: mvt-framework@0.0.1
7 verbose lifecycle mvt-framework@0.0.1~hutber: unsafe-perm in lifecycle true
8 verbose lifecycle mvt-framework@0.0.1~hutber: PATH: /home/hutber/.nvm/versions/node/v8.7.0/lib/node_modules/npm/bin/node-gyp-bin:/var/www/mvt-framework/node_modules/.bin:/home/hutber/.nvm/versions/node/v8.7.0/bin:/home/hutber/bin:/home/hutber/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/hutber/Android/Sdk/tools:/home/hutber/Android/Sdk/platform-tools
9 verbose lifecycle mvt-framework@0.0.1~hutber: CWD: /var/www/mvt-framework
10 silly lifecycle mvt-framework@0.0.1~hutber: Args: [ '-c', './hutber.sh' ]
11 silly lifecycle mvt-framework@0.0.1~hutber: Returned: code: 1  signal: null
12 info lifecycle mvt-framework@0.0.1~hutber: Failed to exec hutber script
13 verbose stack Error: mvt-framework@0.0.1 hutber: `./hutber.sh`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (/home/hutber/.nvm/versions/node/v8.7.0/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:280:16)
13 verbose stack     at emitTwo (events.js:125:13)
13 verbose stack     at EventEmitter.emit (events.js:213:7)
13 verbose stack     at ChildProcess.<anonymous> (/home/hutber/.nvm/versions/node/v8.7.0/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at emitTwo (events.js:125:13)
13 verbose stack     at ChildProcess.emit (events.js:213:7)
13 verbose stack     at maybeClose (internal/child_process.js:927:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5)
14 verbose pkgid mvt-framework@0.0.1
15 verbose cwd /var/www/mvt-framework
16 verbose Linux 4.4.0-53-generic
17 verbose argv "/home/hutber/.nvm/versions/node/v8.7.0/bin/node" "/home/hutber/.nvm/versions/node/v8.7.0/bin/npm" "run" "hutber"
18 verbose node v8.7.0
19 verbose npm  v5.4.2
20 error code ELIFECYCLE
21 error errno 1
22 error mvt-framework@0.0.1 hutber: `./hutber.sh`
22 error Exit status 1
23 error Failed at the mvt-framework@0.0.1 hutber script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]
</code>```

答:
It works as expected.

You end your bash script with a code error 1, used for catching general errors, so npm throws an error.

error code ELIFECYCLE

  error errno 1

It would end without error, if you change for a code 0:

```<code>#!/bin/bash
echo 'hutber' ; exit 0;
</code>```

Body:
I am simply trying to use some bash to check some things then run the commands I want. But I'm getting stuck at the first hurdle:

hutber.sh

#!/bin/bash
echo 'hutber' ; exit 1;

package.json

"hutber": "./hutber.sh"

terminal

hutber@hutber-mint /var/www/mvt-framework $ npm run hutber

> mvt-framework@0.0.1 hutber /var/www/mvt-framework
> ./hutber.sh

hutber
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! mvt-framework@0.0.1 hutber: `./hutber.sh`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the mvt-framework@0.0.1 hutber script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/hutber/.npm/_logs/2017-12-05T15_52_44_355Z-debug.log

error log

0 info it worked if it ends with ok
1 verbose cli [ '/home/hutber/.nvm/versions/node/v8.7.0/bin/node',
1 verbose cli   '/home/hutber/.nvm/versions/node/v8.7.0/bin/npm',
1 verbose cli   'run',
1 verbose cli   'hutber' ]
2 info using npm@5.4.2
3 info using node@v8.7.0
4 verbose run-script [ 'prehutber', 'hutber', 'posthutber' ]
5 info lifecycle mvt-framework@0.0.1~prehutber: mvt-framework@0.0.1
6 info lifecycle mvt-framework@0.0.1~hutber: mvt-framework@0.0.1
7 verbose lifecycle mvt-framework@0.0.1~hutber: unsafe-perm in lifecycle true
8 verbose lifecycle mvt-framework@0.0.1~hutber: PATH: /home/hutber/.nvm/versions/node/v8.7.0/lib/node_modules/npm/bin/node-gyp-bin:/var/www/mvt-framework/node_modules/.bin:/home/hutber/.nvm/versions/node/v8.7.0/bin:/home/hutber/bin:/home/hutber/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/hutber/Android/Sdk/tools:/home/hutber/Android/Sdk/platform-tools
9 verbose lifecycle mvt-framework@0.0.1~hutber: CWD: /var/www/mvt-framework
10 silly lifecycle mvt-framework@0.0.1~hutber: Args: [ '-c', './hutber.sh' ]
11 silly lifecycle mvt-framework@0.0.1~hutber: Returned: code: 1  signal: null
12 info lifecycle mvt-framework@0.0.1~hutber: Failed to exec hutber script
13 verbose stack Error: mvt-framework@0.0.1 hutber: `./hutber.sh`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (/home/hutber/.nvm/versions/node/v8.7.0/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:280:16)
13 verbose stack     at emitTwo (events.js:125:13)
13 verbose stack     at EventEmitter.emit (events.js:213:7)
13 verbose stack     at ChildProcess.<anonymous> (/home/hutber/.nvm/versions/node/v8.7.0/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at emitTwo (events.js:125:13)
13 verbose stack     at ChildProcess.emit (events.js:213:7)
13 verbose stack     at maybeClose (internal/child_process.js:927:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5)
14 verbose pkgid mvt-framework@0.0.1
15 verbose cwd /var/www/mvt-framework
16 verbose Linux 4.4.0-53-generic
17 verbose argv "/home/hutber/.nvm/versions/node/v8.7.0/bin/node" "/home/hutber/.nvm/versions/node/v8.7.0/bin/npm" "run" "hutber"
18 verbose node v8.7.0
19 verbose npm  v5.4.2
20 error code ELIFECYCLE
21 error errno 1
22 error mvt-framework@0.0.1 hutber: `./hutber.sh`
22 error Exit status 1
23 error Failed at the mvt-framework@0.0.1 hutber script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]

Body:
It works as expected.

You end your bash script with a code error 1, used for catching general errors, so npm throws an error.

error code ELIFECYCLE

  error errno 1

It would end without error, if you change for a code 0:

#!/bin/bash
echo 'hutber' ; exit 0;


来源: stackexchange

问:
override the product quantity of existing already product in cart -Woocommerce
I have tried a lot to override the existing product quantity in the cart but nothing.

Actually I have this code:

```<code>add_action('woocommerce_add_to_cart', 'add_to_cart_qty', 10, 6 );
function add_to_cart_qty( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ){

    $real_product_id = $variation_id > 0 ? $variation_id : $product_id;

    $product = wc_get_product($real_product_id);
    $product_stock = $product->get_stock_quantity();

    // Zero or negative stock (remove the product)
    if( $product_stock <= 0 && $product->get_manage_stock() ){
        WC()->cart->remove_cart_item( $cart_item_key );
        return;
    }

    if( $quantity > $product_stock && $product->get_manage_stock() ){
        WC()->cart->set_quantity( $cart_item_key, $product_stock );
    }
}
</code>```

that sets the maximum available product quantity when product is added to cart.
But I will need also to act in cart page when customer change the item quantities…

I think we can handle this issue in two ways:

first either we remove the product on add to the cart of the same product which is already in cart

second way is update the quantity of existing product on add to the cart of the same product, and this should also work for variable products.

I have tried a lot of different snippet codes for this but no results.

Any help will be appreciated.

答:
Using this custom function hooked in woocommerce_after_cart_item_quantity_update action hook, will avoid customer to add more than the product stock quantity when updating cart item quantity:

```<code>add_action('woocommerce_after_cart_item_quantity_update', 'update_cart_items_quantities', 10, 4 );
function update_cart_items_quantities( $cart_item_key, $quantity, $old_quantity, $cart ){
    $cart_data = $cart->get_cart();
    $cart_item = $cart_data[$cart_item_key];
    $manage_stock = $cart_item['data']->get_manage_stock();
    $product_stock = $cart_item['data']->get_stock_quantity();

    // Zero or negative stock (remove the product)
    if( $product_stock <= 0 && $manage_stock ){
        unset( $cart->cart_contents[ $cart_item_key ] );
    }
    if( $quantity > $product_stock && $manage_stock ){
        $cart->cart_contents[ $cart_item_key ]['quantity'] = $product_stock;
    }
    return $product_stock;
}
</code>```

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

This code is tested and works even for product variations.

ContentLicense: CC BY-SA 3.0

Body:
I have tried a lot to override the existing product quantity in the cart but nothing.

Actually I have this code:

add_action('woocommerce_add_to_cart', 'add_to_cart_qty', 10, 6 );
function add_to_cart_qty( $cart_item_key, $product_id, $quantity, $variation_id, $variation, $cart_item_data ){

    $real_product_id = $variation_id > 0 ? $variation_id : $product_id;

    $product = wc_get_product($real_product_id);
    $product_stock = $product->get_stock_quantity();

    // Zero or negative stock (remove the product)
    if( $product_stock <= 0 && $product->get_manage_stock() ){
        WC()->cart->remove_cart_item( $cart_item_key );
        return;
    }

    if( $quantity > $product_stock && $product->get_manage_stock() ){
        WC()->cart->set_quantity( $cart_item_key, $product_stock );
    }
}

that sets the maximum available product quantity when product is added to cart.
But I will need also to act in cart page when customer change the item quantities…

I think we can handle this issue in two ways:

first either we remove the product on add to the cart of the same product which is already in cart

second way is update the quantity of existing product on add to the cart of the same product, and this should also work for variable products.

I have tried a lot of different snippet codes for this but no results.

Any help will be appreciated.

Body:
Using this custom function hooked in woocommerce_after_cart_item_quantity_update action hook, will avoid customer to add more than the product stock quantity when updating cart item quantity:

add_action('woocommerce_after_cart_item_quantity_update', 'update_cart_items_quantities', 10, 4 );
function update_cart_items_quantities( $cart_item_key, $quantity, $old_quantity, $cart ){
    $cart_data = $cart->get_cart();
    $cart_item = $cart_data[$cart_item_key];
    $manage_stock = $cart_item['data']->get_manage_stock();
    $product_stock = $cart_item['data']->get_stock_quantity();

    // Zero or negative stock (remove the product)
    if( $product_stock <= 0 && $manage_stock ){
        unset( $cart->cart_contents[ $cart_item_key ] );
    }
    if( $quantity > $product_stock && $manage_stock ){
        $cart->cart_contents[ $cart_item_key ]['quantity'] = $product_stock;
    }
    return $product_stock;
}

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

This code is tested and works even for product variations.

ContentLicense: CC BY-SA 4.0


问:
Node promise error propagation between classes
Im currently in the process of making my code object oriented and have a problem with propagating promise errors between class instances.

Page.js:

```<code>exports.Page = class {
  constructor(link, limiter){
    this.link = link;
    //limiter is a instance of bottleneck, use it for rate limiting
    this.limiter = limiter;
  }

  setResults(){
    return new Request(this.link, this.limiter).makeRequest()
    .catch(err => {
      //i dont get here
      console.log(err);
    })
  }
}
</code>```

(is called and initiated from another class)

Request.js:

```<code>exports.Request = class {
  constructor(options, limiter){
    this.options = options;
    this.limiter = limiter;
  }

  makeRequest(){
    return this.limiter.schedule(this.request, this.options)
    .catch(err => {
      //i get here
      throw err;
    });
  }

  request(url){
    return rp("https://httpstat.us/500")
    .catch(err => {
      //i get here
      throw err;
    })
  }
}
</code>```

So my problem is, that the error wont be propagated back to the page.js but instead prints an unhandled rejection error in the console. I've tried running this without limiter.schedule but it doesnt make a difference. Would be great to get some pointers, cant figure it out.

答: Callbacks passed to Promises do not return values. Period. Full Stop. You pass a callback as the single argument of either a .then() or a .catch() which, when run, will never return a value or throw a catch-able Error because it has no context to return or error out to.

Body:
Im currently in the process of making my code object oriented and have a problem with propagating promise errors between class instances.

Page.js:

exports.Page = class {
  constructor(link, limiter){
    this.link = link;
    //limiter is a instance of bottleneck, use it for rate limiting
    this.limiter = limiter;
  }

  setResults(){
    return new Request(this.link, this.limiter).makeRequest()
    .catch(err => {
      //i dont get here
      console.log(err);
    })
  }
}

(is called and initiated from another class)

Request.js:

exports.Request = class {
  constructor(options, limiter){
    this.options = options;
    this.limiter = limiter;
  }

  makeRequest(){
    return this.limiter.schedule(this.request, this.options)
    .catch(err => {
      //i get here
      throw err;
    });
  }

  request(url){
    return rp("https://httpstat.us/500")
    .catch(err => {
      //i get here
      throw err;
    })
  }
}

So my problem is, that the error wont be propagated back to the page.js but instead prints an unhandled rejection error in the console. I've tried running this without limiter.schedule but it doesnt make a difference. Would be great to get some pointers, cant figure it out.


问:
textArea.setText() wrong output
I'm trying to print out a HashMap with keys and values into the TextArea field.
The map is printed when I try to print it out like this:

for(Map.Entry<Integer,String> entry : kodovi.entrySet()) {
                        System.out.println(entry.getKey()+" : "+entry.getValue());}

But when I try to print it out in a Text Area like this, it just prints out the last key and value.

```<code>for(Map.Entry<Integer,String> entry: kodovi.entrySet()){
    textArea.setText(entry.getKey()+" : "+entry.getValue());}
</code>```

How to fix this?

答:
Every time you call textArea.setText(...),
the last call replaces whatever content was previously there.

You could get the previous content and append to it,
but string concatenation is inefficient.

It will be better to build a string using a StringBuilder,
and then set the content from that:

```<code>StringBuilder sb = new StringBuilder();
for (Map.Entry<Integer, String> entry : kodovi.entrySet()) {
    sb.append(entry.getKey()).append(" : ").append(entry.getValue()).append("\n");
}

textArea.setText(sb.toString());
</code>```

Title: textArea.setText() wrong output

Body:
I'm trying to print out a HashMap with keys and values into the TextArea field.
The map is printed when I try to print it out like this:

for(Map.Entry<Integer,String> entry : kodovi.entrySet()) {
                        System.out.println(entry.getKey()+" : "+entry.getValue());}

But when I try to print it out in a Text Area like this, it just prints out the last key and value.

for(Map.Entry<Integer,String> entry: kodovi.entrySet()){
    textArea.setText(entry.getKey()+" : "+entry.getValue());}

How to fix this?

Body:
Every time you call textArea.setText(...),
the last call replaces whatever content was previously there.

You could get the previous content and append to it,
but string concatenation is inefficient.

It will be better to build a string using a StringBuilder,
and then set the content from that:

StringBuilder sb = new StringBuilder();
for (Map.Entry<Integer, String> entry : kodovi.entrySet()) {
    sb.append(entry.getKey()).append(" : ").append(entry.getValue()).append("\n");
}

textArea.setText(sb.toString());


问:
react big calendar - using it for api call
I am using react big calendar and I am using the start days and end days of the week for my api call
here's the function I am calling to get events

```<code>getEvents(calendarId,firstday,lastDay);
</code>```

this function creates the api url to hit using the calendar id and the dates for first day and last day.

so, if the calendar shows the week as 20th august - 27 august
then first day is 20-08-2017 and last day is 27-08-2017
and my api url becomes

```<code>calendar/events/?start="20-08-2017"&end="27-08-2017"
</code>```

for next week i.e 28-08-2017 to 3-08-2017
I want to get dates automatically from the calendar
 so I can use it in my api call?

the problem is that I am quite new to react-big-calendar and I dont know how to get the dates from there.
I'd really appreciate it if you could provide some suggestions or advice or even point me where to look.
I have been through the documentation but couldnt get what I want.

EDIT:
I am using onNavigate as shown below to call the function that makes the api call

```<code>onNavigate={() => {
 actions.calendar.getEvents(this.props.params.calendarId, firstday, lastday);

              }}
</code>```

答:
Try to change your callback to accept the current start date of your calendar:

```<code>onNavigate={(date) => ...}
</code>```

and calculate the requered date range for your API call e.g. using moment JS lib.

Body:
I am using react big calendar and I am using the start days and end days of the week for my api call
here's the function I am calling to get events

getEvents(calendarId,firstday,lastDay);

this function creates the api url to hit using the calendar id and the dates for first day and last day.

so, if the calendar shows the week as 20th august - 27 august
then first day is 20-08-2017 and last day is 27-08-2017
and my api url becomes

calendar/events/?start="20-08-2017"&end="27-08-2017"

for next week i.e 28-08-2017 to 3-08-2017
I want to get dates automatically from the calendar
 so I can use it in my api call?

the problem is that I am quite new to react-big-calendar and I dont know how to get the dates from there.
I'd really appreciate it if you could provide some suggestions or advice or even point me where to look.
I have been through the documentation but couldnt get what I want.

EDIT:
I am using onNavigate as shown below to call the function that makes the api call

onNavigate={() => {
 actions.calendar.getEvents(this.props.params.calendarId, firstday, lastday);

              }}

Body:
Try to change your callback to accept the current start date of your calendar:

onNavigate={(date) => ...}

and calculate the requered date range for your API call e.g. using moment JS lib.


问:
SQL Multiple Left Joins performance is bad
So, I have a rather simple query, which works, but very slow.

Is there a better way to optimize the query? Should I break out the LEFT JOINS on multiple columns? What about doing multiple runs and using Union ALL to join them together?

The tables have maybe 500,000 ROWS in them, and are indexed well.

Please help. Query takes forever to run

```<code>SELECT
ep.Id,
ep.DisplayName,
ep.EmailAddress,
COALESCE(
    gs.DisplayNameMember + ' (' + gd.DisplayName + ')',
    ea.DisplayName ,
    ep.TrusteeUserAccountName,
    ep.Trustee
) AS Trustee

FROM
dbo.ExchangePermissions ep WITH (NOLOCK)

LEFT JOIN dbo.GroupDetail gd WITH (NOLOCK) ON (ep.Trustee = gd.[Identity] OR ep.Trustee = gd.DisplayName OR ep.TrusteeUserAccountName = gd.SamAccountName)
LEFT JOIN dbo.GroupMemberShip gs WITH (NOLOCK) ON gd.name = gs.groupname
LEFT JOIN dbo.ExchangeAccount ea WITH (NOLOCK) ON (ep.Trustee = ea.[Identity] OR ep.Trustee = ea.DisplayName OR ep.TrusteeUserAccountName = ea.SamAccountName)

WHERE
ep.OTHERID= @MyParameter
</code>```

答:
The ORs in your LEFT JOINs are not helping performance at all. You should break them down into separate queries and UNION the results together. Working from Vykintas answer, we get the following:

```<code>SELECT
ep.Id,
ep.DisplayName,
ep.EmailAddress,
COALESCE(
    gs.DisplayNameMember + ' (' + gd.DisplayName + ')',
    ep.TrusteeUserAccountName,
    ep.Trustee
) AS Trustee
FROM
dbo.ExchangePermissions ep WITH (NOLOCK)
LEFT JOIN dbo.GroupDetail gd WITH (NOLOCK) ON ep.Trustee = gd.[Identity]
LEFT JOIN dbo.GroupMemberShip gs WITH (NOLOCK) ON gd.name = gs.groupname
WHERE
ep.OTHERID= @MyParameter

UNION

SELECT
ep.Id,
ep.DisplayName,
ep.EmailAddress,
COALESCE(
    gs.DisplayNameMember + ' (' + gd.DisplayName + ')',
    ep.TrusteeUserAccountName,
    ep.Trustee
) AS Trustee
FROM
dbo.ExchangePermissions ep WITH (NOLOCK)
LEFT JOIN dbo.GroupDetail gd WITH (NOLOCK) ON ep.Trustee = gd.DisplayName
LEFT JOIN dbo.GroupMemberShip gs WITH (NOLOCK) ON gd.name = gs.groupname
WHERE
ep.OTHERID= @MyParameter

UNION

SELECT
ep.Id,
ep.DisplayName,
ep.EmailAddress,
COALESCE(
    gs.DisplayNameMember + ' (' + gd.DisplayName + ')',
    ep.TrusteeUserAccountName,
    ep.Trustee
) AS Trustee
FROM
dbo.ExchangePermissions ep WITH (NOLOCK)
LEFT JOIN dbo.GroupDetail gd WITH (NOLOCK) ON ep.TrusteeUserAccountName = gd.SamAccountName
LEFT JOIN dbo.GroupMemberShip gs WITH (NOLOCK) ON gd.name = gs.groupname
WHERE
ep.OTHERID= @MyParameter
</code>```

Body:
So, I have a rather simple query, which works, but very slow.

Is there a better way to optimize the query? Should I break out the LEFT JOINS on multiple columns? What about doing multiple runs and using Union ALL to join them together?

The tables have maybe 500,000 ROWS in them, and are indexed well.

Please help. Query takes forever to run

SELECT
ep.Id,
ep.DisplayName,
ep.EmailAddress,
COALESCE(
    gs.DisplayNameMember + ' (' + gd.DisplayName + ')',
    ea.DisplayName ,
    ep.TrusteeUserAccountName,
    ep.Trustee
) AS Trustee

FROM
dbo.ExchangePermissions ep WITH (NOLOCK)

LEFT JOIN dbo.GroupDetail gd WITH (NOLOCK) ON (ep.Trustee = gd.[Identity] OR ep.Trustee = gd.DisplayName OR ep.TrusteeUserAccountName = gd.SamAccountName)
LEFT JOIN dbo.GroupMemberShip gs WITH (NOLOCK) ON gd.name = gs.groupname
LEFT JOIN dbo.ExchangeAccount ea WITH (NOLOCK) ON (ep.Trustee = ea.[Identity] OR ep.Trustee = ea.DisplayName OR ep.TrusteeUserAccountName = ea.SamAccountName)

WHERE
ep.OTHERID= @MyParameter

Body:
The ORs in your LEFT JOINs are not helping performance at all. You should break them down into separate queries and UNION the results together. Working from Vykintas answer, we get the following:

SELECT
ep.Id,
ep.DisplayName,
ep.EmailAddress,
COALESCE(
    gs.DisplayNameMember + ' (' + gd.DisplayName + ')',
    ep.TrusteeUserAccountName,
    ep.Trustee
) AS Trustee
FROM
dbo.ExchangePermissions ep WITH (NOLOCK)
LEFT JOIN dbo.GroupDetail gd WITH (NOLOCK) ON ep.Trustee = gd.[Identity]
LEFT JOIN dbo.GroupMemberShip gs WITH (NOLOCK) ON gd.name = gs.groupname
WHERE
ep.OTHERID= @MyParameter

UNION

SELECT
ep.Id,
ep.DisplayName,
ep.EmailAddress,
COALESCE(
    gs.DisplayNameMember + ' (' + gd.DisplayName + ')',
    ep.TrusteeUserAccountName,
    ep.Trustee
) AS Trustee
FROM
dbo.ExchangePermissions ep WITH (NOLOCK)
LEFT JOIN dbo.GroupDetail gd WITH (NOLOCK) ON ep.Trustee = gd.DisplayName
LEFT JOIN dbo.GroupMemberShip gs WITH (NOLOCK) ON gd.name = gs.groupname
WHERE
ep.OTHERID= @MyParameter

UNION

SELECT
ep.Id,
ep.DisplayName,
ep.EmailAddress,
COALESCE(
    gs.DisplayNameMember + ' (' + gd.DisplayName + ')',
    ep.TrusteeUserAccountName,
    ep.Trustee
) AS Trustee
FROM
dbo.ExchangePermissions ep WITH (NOLOCK)
LEFT JOIN dbo.GroupDetail gd WITH (NOLOCK) ON ep.TrusteeUserAccountName = gd.SamAccountName
LEFT JOIN dbo.GroupMemberShip gs WITH (NOLOCK) ON gd.name = gs.groupname
WHERE
ep.OTHERID= @MyParameter


问:
How to disable link time code generation in CMake
We are using CMake with the Visual Studio 2015 generator and I am trying to disable link time code generation for libraries and executables under the debug build configuration. It seems that when I modify the linker flags with

SET_TARGET_PROPERTIES(${_PROJNAME} PROPERTIES LINK_FLAGS_DEBUG "${LINK_FLAGS_DEBUG} /LTCG:OFF")

that CMake still generates solutions with /LTCG:INCREMENTAL in the linker additional options but also with /LTGC:OFF appended.  Does anyone know a way to turn LTCG off completely for all configurations so I can enable it just for those that we want it enabled for?

cmake version 3.10.0-rc2

答:
If something ends up under "Additional Options" in the generated VS projects, it means CMake didn't recognize the option given (and therefore didn't replace its own default).

See CMake's source cmVS141LinkFlagTable.h:

```<code>{ "LinkTimeCodeGeneration", "", "Default", "Default", 0 },
{ "LinkTimeCodeGeneration", "LTCG:incremental", "Use Fast Link Time Code Generation", "UseFastLinkTimeCodeGeneration", 0 },
{ "LinkTimeCodeGeneration", "LTCG", "Use Link Time Code Generation", "UseLinkTimeCodeGeneration", 0 },
{ "LinkTimeCodeGeneration", "LTCG:PGInstrument", "Profile Guided Optimization - Instrument", "PGInstrument", 0 },
{ "LinkTimeCodeGeneration", "LTCG:PGOptimize", "Profile Guided Optimization - Optimization", "PGOptimization", 0 },
{ "LinkTimeCodeGeneration", "LTCG:PGUpdate", "Profile Guided Optimization - Update", "PGUpdate", 0 },
</code>```

But if I look at CMake's VS 2015 defaults:

```<code>CMAKE_EXE_LINKER_FLAGS = /machine:X86
CMAKE_EXE_LINKER_FLAGS_DEBUG = /debug /INCREMENTAL
CMAKE_EXE_LINKER_FLAGS_RELEASE = /INCREMENTAL:NO
</code>```

There is no /LTCG:INCREMENTAL in the defaults. So I think what you are actually looking for/what would help you is:

```<code>set_property(
    TARGET ${_PROJNAME}
    APPEND_STRING
    PROPERTY
        LINK_FLAGS_DEBUG " /INCREMENTAL:NO"
)
</code>```

Body:
If something ends up under "Additional Options" in the generated VS projects, it means CMake didn't recognize the option given (and therefore didn't replace its own default).

See CMake's source cmVS141LinkFlagTable.h:

{ "LinkTimeCodeGeneration", "", "Default", "Default", 0 },
{ "LinkTimeCodeGeneration", "LTCG:incremental", "Use Fast Link Time Code Generation", "UseFastLinkTimeCodeGeneration", 0 },
{ "LinkTimeCodeGeneration", "LTCG", "Use Link Time Code Generation", "UseLinkTimeCodeGeneration", 0 },
{ "LinkTimeCodeGeneration", "LTCG:PGInstrument", "Profile Guided Optimization - Instrument", "PGInstrument", 0 },
{ "LinkTimeCodeGeneration", "LTCG:PGOptimize", "Profile Guided Optimization - Optimization", "PGOptimization", 0 },
{ "LinkTimeCodeGeneration", "LTCG:PGUpdate", "Profile Guided Optimization - Update", "PGUpdate", 0 },

But if I look at CMake's VS 2015 defaults:

CMAKE_EXE_LINKER_FLAGS = /machine:X86
CMAKE_EXE_LINKER_FLAGS_DEBUG = /debug /INCREMENTAL
CMAKE_EXE_LINKER_FLAGS_RELEASE = /INCREMENTAL:NO

There is no /LTCG:INCREMENTAL in the defaults. So I think what you are actually looking for/what would help you is:

set_property(
    TARGET ${_PROJNAME}
    APPEND_STRING
    PROPERTY
        LINK_FLAGS_DEBUG " /INCREMENTAL:NO"
)


问:
How do I consolidate my code to have one variable that changes for each input?
I'm building a program that will take the skillsets of different candidates for a given job, and check to see if they have the required skills. I have figured out how to make this work, but I don't know how to do it without writing "candidate1", "candidate2" etc. Is there a more efficient way to do this?:

```<code>list_of_qualities = ['Experience in Cold Calling', 'Experience in Door to
Door Sales', 'Experience in Account Management','Experience in Warm Leads','Experience in Presenting', 'Experience in Negotiation',\'Experience in Leadership', 'Experience in Closing']

cold_calling = list_of_qualities[0]
door_to_door = list_of_qualities[1]
account_management = list_of_qualities[2]
warm_leads = list_of_qualities[3]
presenting = list_of_qualities[4]
negotiation = list_of_qualities[5]
leadership = list_of_qualities[6]
closing = list_of_qualities[7]

required_qualities = [cold_calling, presenting, account_management, leadership, closing]
candidate1 = [cold_calling, presenting, account_management, leadership, closing, door_to_door]
candidate2 = [cold_calling, warm_leads, account_management, leadership]
candidate3 = [cold_calling, account_management]
matched_qualities1 = []
matched_qualities2 = []
matched_qualities3 = []
lacking_qualities1 = []
lacking_qualities2 = []
lacking_qualities3 = []

print("To view and apply for your job, candidates must have the following skillset:")
print(required_qualities)
print(" ")
print("The candidates have the following matching skills:")
</code>```

Candidate 1

```<code>for i in candidate1:
    if i in required_qualities:
        matched_qualities1.append(i)
print("Candidate 1:", matched_qualities1)

for i in required_qualities:
    if i not in candidate1:
        lacking_qualities1.append(i)
</code>```

Check if candidate 1 has all skills or not

```<code>if len(lacking_qualities1) == 0:
    print("             This candidate has all of the required skills")
else:
    print("    lacking:", lacking_qualities1)
</code>```

答:
There are several options. You can have a list of lists, or a dataframe. An array is also an option, but not really appropriate. Some other things to simplify your code:

You can do cold_calling,door_to_door,account_management,warm_leads,presenting,negotiation,
leadership,closing = list_of_qualities

Also, you can replace your for-loop with lacking_qualities1=[quality in required_qualities if not quality in candidate1]

If you create a list of candidates, you can do

```<code>lacking_qualities_list_of_list=[
       [quality in required_qualities if not quality in candidate]
       for candidate in list_of_candidates]
</code>```

Body:
I'm building a program that will take the skillsets of different candidates for a given job, and check to see if they have the required skills. I have figured out how to make this work, but I don't know how to do it without writing "candidate1", "candidate2" etc. Is there a more efficient way to do this?:

list_of_qualities = ['Experience in Cold Calling', 'Experience in Door to
Door Sales', 'Experience in Account Management','Experience in Warm Leads','Experience in Presenting', 'Experience in Negotiation',\'Experience in Leadership', 'Experience in Closing']

cold_calling = list_of_qualities[0]
door_to_door = list_of_qualities[1]
account_management = list_of_qualities[2]
warm_leads = list_of_qualities[3]
presenting = list_of_qualities[4]
negotiation = list_of_qualities[5]
leadership = list_of_qualities[6]
closing = list_of_qualities[7]

required_qualities = [cold_calling, presenting, account_management, leadership, closing]
candidate1 = [cold_calling, presenting, account_management, leadership, closing, door_to_door]
candidate2 = [cold_calling, warm_leads, account_management, leadership]
candidate3 = [cold_calling, account_management]
matched_qualities1 = []
matched_qualities2 = []
matched_qualities3 = []
lacking_qualities1 = []
lacking_qualities2 = []
lacking_qualities3 = []

print("To view and apply for your job, candidates must have the following skillset:")
print(required_qualities)
print(" ")
print("The candidates have the following matching skills:")

Candidate 1

for i in candidate1:
    if i in required_qualities:
        matched_qualities1.append(i)
print("Candidate 1:", matched_qualities1)

for i in required_qualities:
    if i not in candidate1:
        lacking_qualities1.append(i)

Check if candidate 1 has all skills or not

if len(lacking_qualities1) == 0:
    print("             This candidate has all of the required skills")
else:
    print("    lacking:", lacking_qualities1)

Body:
There are several options. You can have a list of lists, or a dataframe. An array is also an option, but not really appropriate. Some other things to simplify your code:

You can do cold_calling,door_to_door,account_management,warm_leads,presenting,negotiation,
leadership,closing = list_of_qualities

Also, you can replace your for-loop with lacking_qualities1=[quality in required_qualities if not quality in candidate1]

If you create a list of candidates, you can do

lacking_qualities_list_of_list=[
       [quality in required_qualities if not quality in candidate]
       for candidate in list_of_candidates]


问:
Image Matching using opencvsharp3
I'm novice in OpenCVSharp3 and I've been having a look at some examples for image matching using this library.

The key to my question is that I don't know what kind of modifications the code from this question needs to compare two images that are almost 100% identical, but one of them is rotated (unlimited rotation) and sometimes slightly displaced from the source (some pixels).

The method from such question basically compare if one image is inside the other, but my project only need to compare 5 images with the same size, where two of them are the same with slightly differences.

Is valid such algorithm?

EDIT:

Here is an example of 5 images to detect the same:

答:
It can be valid but:

if you want unlimited rotation, you have to compare your reference image with an infinite combination of rotated other image.

if your other image is displaced from the source you will have to generate all the possible displacement images.

If you combine this two technique, you will have a lot of combination.

So yes, it can be done in generating all possible different images for one image, and compare them with your reference image.

It's not very robust, what will append if you try it on images displaced with a superior amount of pixels? if a color adjustment had be done on a image? if one is in gray-scale?

I recommend you to use machine learning for this problem.
I would proceed like this:

make a dataset of images

for each images, make a data augmentation (make all rotation, displacement, noise that it is possible).

Use a CNN and train it to recognize each variation of an image as the same image.

You're done, you have an algorithm who do the job :)

Here an implementation of tensorflow for C#
https://github.com/migueldeicaza/TensorFlowSharp

For a simple implementation of MNIST CNN with python see here

Here A video that explain how CNN works (look at the feature detection and pooling operation, it can help you)

Title: Image Matching using opencvsharp3


问:
Using WSO2 for Authentication and Authorization for web based Enterprise Applications
We want to use WSO2 as IAM framwork for our Internal and external applications.

We have below 3 main requirements.

WSO2 should be able to Authenticate user using LDAP (Active
Directory for Internal Employees ) or other data source for external
users.

We want to configure API access level in WSO2 example : ROLE based Authorization (or Policy based ) where we can configure who can access which
web API with Http verb.

We should be able dynamically add/update/delete users , update Authorization policies/ roles  through WSO2 API.

Please let me know if this is out of box supported in community edition or we have to buy any licenses for the same.

Note: I have installed the server and playing around as well.

答:
Yes these requirements are possible with WSO2 IS (Product stack)

You can easily plug an existing LDAP user store to WSO2 IS. (https://docs.wso2.com/display/IS530/Configuring+a+Read-write+LDAP+User+Store)

I am not 100% clear about what you are asking here. But if you are talking about IS APIs (Which specified in point number 3) you can do them solely with IS by little customization or else you can use WSO2 ESB with entitlement mediator to add XACML policies.

There are SOAP admin services(Non standard but able to update authorization polices etc) and REST services. (Standard SCIM 2.0 for user operations)
https://docs.wso2.com/display/IS530/Calling+Admin+Services
https://docs.wso2.com/display/IS530/SCIM+1.1+APIs


问:
R- How to add parts of a column to another column in a dataframe?
I have a very specific problem. My dataframe looks like this:

My problem is the Date and Day columns. Currently its like this:

Year-month-1  - And then in the next column the day.

I want it look like a normal Date-Column, like Year-month-day. So I want to take the days out of the 2nd column and replace them with the 01 in the first column.

Any idea how to do that?

答:
We can use the dplyr rear and lubridate packages.

```<code>library(readr)
library(dplyr)
library(lubridate)

df <- df %>%
  mutate(Date = ymd(paste(year(Date), month(Date), parse_number(Day), sep = '-')))
</code>```

The parse_number(Day) function gets the numeric values from the Day column. The year(Date) get the year from Date and month(Date) get the month from Date.

Then the paste combines the year-month-day with a hyphen as the separator sep = '-'. ymd converts it to a date format. mutate(Date inserts the new values into the Date column.

Body:
We can use the dplyr rear and lubridate packages.

library(readr)
library(dplyr)
library(lubridate)

df <- df %>%
  mutate(Date = ymd(paste(year(Date), month(Date), parse_number(Day), sep = '-')))

The parse_number(Day) function gets the numeric values from the Day column. The year(Date) get the year from Date and month(Date) get the month from Date.

Then the paste combines the year-month-day with a hyphen as the separator sep = '-'. ymd converts it to a date format. mutate(Date inserts the new values into the Date column.


问:
why some types of data refer to the same memory location
Asked such a question. Why only the type only str and boolean with the same variables refer to one memory location:

```<code>a = 'something'
b = 'something'
if a is b: print('True') # True
</code>```

but we did not write anywhere a = b. hence the interpreter saw that the strings are equal to each other and made a reference to one memory cell.

Of course, if we assign a new value to either of these two variables, there will be no conflict, so now the variable will refer to another memory location

```<code>b = 'something more'
if a is b: print('True') # False
</code>```

with type boolean going on all the same

```<code>a = True
b = True
if a is b: print('True') # True
</code>```

I first thought that this happens with all mutable types. But no. There remained one unchangeable type - tuple. But it has a different behavior, that is, when we assign the same values to variables, we already refer to different memory cells. Why does this happen only with tuple of immutable types

```<code>a = (1,9,8)
b = (1,9,8)
if a is b: print('True') # False
</code>```

答:
Why do some types cache values? Because you shouldn't be able to notice the difference!

is is a very specialized operator. Nearly always you should use == instead, which will do exactly what you want.

The cases where you want to use is instead of == basically are when you're dealing with objects that have overloaded the behavior of == to not mean what you want it to mean, or where you're worried that you might be dealing with such objects.

If you're not sure whether you're dealing with such objects or not, you're probably not, which means that == is always right and you don't have to ever use is.

It can be a matter of "style points" to use is with known singleton objects, like None, but there's nothing wrong with using == there (again, in the absence of a pathological implementation of ==).

If you're dealing with potentially untrustworthy objects, then you should never do anything that may invoke a method that they control.... and that's a good place to use is. But almost nobody is doing that, and those who do should be aware of the zillion other ways a malicious object could cause problems.

If an object implements == incorrectly then you can get all kinds of weird problems. In the course of debugging those problems, of course you can and should use is! But that shouldn't be your normal way of comparing objects in code you write.

The one other case where you might want to use is rather than == is as a performance optimization, if the object you're dealing with implements == in a particularly expensive way. This is not going to be the case very often at all, and most of the time there are better ways to reduce the number of times you have to compare two objects (e.g. by comparing hash codes instead) which will ultimately have a much better effect on performance without bringing correctness into question.

If you use == wherever you semantically want an equality comparison, then you will never even notice when some types sneakily reuse instances on you.

Body:
Asked such a question. Why only the type only str and boolean with the same variables refer to one memory location:

a = 'something'
b = 'something'
if a is b: print('True') # True

but we did not write anywhere a = b. hence the interpreter saw that the strings are equal to each other and made a reference to one memory cell.

Of course, if we assign a new value to either of these two variables, there will be no conflict, so now the variable will refer to another memory location

b = 'something more'
if a is b: print('True') # False

with type boolean going on all the same

a = True
b = True
if a is b: print('True') # True

I first thought that this happens with all mutable types. But no. There remained one unchangeable type - tuple. But it has a different behavior, that is, when we assign the same values to variables, we already refer to different memory cells. Why does this happen only with tuple of immutable types

a = (1,9,8)
b = (1,9,8)
if a is b: print('True') # False


问:
Why height text box is less than button?
Why height text box is less than button?

My Code :

 #container {
  overflow: auto;
  line-height: 100%;
  border: 1px solid red;
}
.t,#but {
   float: left;
}
#but ,.txt {
   border: 1px solid #999;
   padding: 10px;
   font-size: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
 <div class="t">
 <input type="text" class="txt" name="">
 </div>
 <div id="but"><span>Search</span></div>
</div></code>```

答:
/You'll need to do something like this although there is likely to be some differences across systems./

.searchtext {
    border:1px solid #000;
    border-right:none;
    padding:4px;
    margin:0px;
    float:left;
    height:16px;
    overflow:hidden;
    line-height:16px;
}
.searchbutton {
    border:1px solid #000;
    background:#fd0;
    vertical-align:top;
    padding:4px;
    margin:0;
    float:left;
    height:26px;
    overflow:hidden;
    width:5em;
    text-align:center;
    line-height:16px;
}```

Body:
Why height text box is less than button?

My Code :

 #container {
  overflow: auto;
  line-height: 100%;
  border: 1px solid red;
}
.t,#but {
   float: left;
}
#but ,.txt {
   border: 1px solid #999;
   padding: 10px;
   font-size: 20px;
}

 <input type="text" class="txt" name="">

Search


问:
XSD - Ignoring any Content of XML Element
I'm yet searching for some time for a solution for a problem with some database exports looking as follows:

```<code><DATA>

<ROW>
    <ID>36342</ID>
    <TIMESTAMP1>2017-11-24 14:54:51</TIMESTAMP1>
    <TIMESTAMP2>2017-11-24 14:54:51</TIMESTAMP2>
    <NOTES>please try <variable_name> inside <function></NOTES>
</ROW>

<ROW>
    <ID>36341</ID>
    <TIMESTAMP1>2017-11-24 12:51:50</TIMESTAMP1>
    <TIMESTAMP2>2017-11-24 12:51:50</TIMESTAMP2>
    <NOTES>Otherwise <option> could also be</NOTES>
</ROW>
</DATA>
</code>```

The real data in use is in fact a Support Database, means there are multiple place holders in hundreds of thousands of Entrys (NOTES2), so of course I cannot change any content. Also the Notes can contain any number of place holders, including none.

Now the problem is about, how to be able to understand any Content of "NOTES" as plain text, ignoring all XML lookalikes like <function>, <variable_name> and <option>. (and of course many others)

What I've got yet:

```<code><xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
<xsd:element name="DATA" sql:is-constant="1" >
 <xsd:complexType>
   <xsd:sequence>
     <xsd:element name="ROW" sql:relation="document" maxOccurs="unbounded">
       <xsd:complexType>
         <xsd:sequence>
           <xsd:element name="ID"  type="xsd:string" />
           <xsd:element name="TIMESTAMP1" type="xsd:string" />
           <xsd:element name="TIMESTAMP2" type="xsd:string" />
                <xsd:element name="NOTES" type="string" >
                    <xsd:complexType>
                        <xsd:sequence>
                            <xsd:any processContents="skip" minOccurs="0"/>
                        </xsd:sequence>
                    </xsd:complexType>
                </xsd:element>
         </xsd:sequence>
       </xsd:complexType>
     </xsd:element>
   </xsd:sequence>
  </xsd:complexType>
 </xsd:element>
 </xsd:schema>
</code>```

I have to add that I am in fact not an expert in XML/XSD. I'm only able to understand what I read. What I do read is, any Tag found inside "NOTES" should be skipped on interpretion. But unfortunately the Parser says:

```<code> 'type' cannot be present with either 'simpleType' or 'complexType'
</code>```

So of course the error message tells me to delete the entity "type" of the Element "NOTES", but if I do so the error is:

```<code>Text is not allowed in the context of element 'NOTES' according to DTD/Schema.
</code>```

So how would I now get the full content of such an element?

Best regards
Marius

答:
XSD cannot be written to allow XML not to be well-formed.

You cannot define an XSD to allow

```<code><NOTES>please try <variable_name> inside <function></NOTES>
</code>```

because such data is not well-formed XML.  A < character cannot be used unescaped in XML without serving as the start of markup.
Nothing you can do in XSD can change this.

Options

Escape <:

```<code><NOTES>please try <variable_name> inside <function></NOTES>
</code>```

Use CDATA:

```<code><NOTES><![CDATA[please try <variable_name> inside <function>]]></NOTES>
</code>```

Or close the "elements":

```<code><NOTES>please try <variable_name/> inside <function/></NOTES>
</code>```

Body:
I'm yet searching for some time for a solution for a problem with some database exports looking as follows:

<DATA>

<ROW>
    <ID>36342</ID>
    <TIMESTAMP1>2017-11-24 14:54:51</TIMESTAMP1>
    <TIMESTAMP2>2017-11-24 14:54:51</TIMESTAMP2>
    <NOTES>please try <variable_name> inside <function></NOTES>
</ROW>

<ROW>
    <ID>36341</ID>
    <TIMESTAMP1>2017-11-24 12:51:50</TIMESTAMP1>
    <TIMESTAMP2>2017-11-24 12:51:50</TIMESTAMP2>
    <NOTES>Otherwise <option> could also be</NOTES>
</ROW>
</DATA>

The real data in use is in fact a Support Database, means there are multiple place holders in hundreds of thousands of Entrys (NOTES2), so of course I cannot change any content. Also the Notes can contain any number of place holders, including none.

Now the problem is about, how to be able to understand any Content of "NOTES" as plain text, ignoring all XML lookalikes like <function>, <variable_name> and <option>. (and of course many others)

What I've got yet:

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        xmlns:sql="urn:schemas-microsoft-com:mapping-schema">
<xsd:element name="DATA" sql:is-constant="1" >
 <xsd:complexType>
   <xsd:sequence>
     <xsd:element name="ROW" sql:relation="document" maxOccurs="unbounded">
       <xsd:complexType>
         <xsd:sequence>
           <xsd:element name="ID"  type="xsd:string" />
           <xsd:element name="TIMESTAMP1" type="xsd:string" />
           <xsd:element name="TIMESTAMP2" type="xsd:string" />
                <xsd:element name="NOTES" type="string" >
                    <xsd:complexType>
                        <xsd:sequence>
                            <xsd:any processContents="skip" minOccurs="0"/>
                        </xsd:sequence>
                    </xsd:complexType>
                </xsd:element>
         </xsd:sequence>
       </xsd:complexType>
     </xsd:element>
   </xsd:sequence>
  </xsd:complexType>
 </xsd:element>
 </xsd:schema>

I have to add that I am in fact not an expert in XML/XSD. I'm only able to understand what I read. What I do read is, any Tag found inside "NOTES" should be skipped on interpretion. But unfortunately the Parser says:

 'type' cannot be present with either 'simpleType' or 'complexType'

So of course the error message tells me to delete the entity "type" of the Element "NOTES", but if I do so the error is:

Text is not allowed in the context of element 'NOTES' according to DTD/Schema.

So how would I now get the full content of such an element?

Best regards
Marius

Body:
XSD cannot be written to allow XML not to be well-formed.

You cannot define an XSD to allow

<NOTES>please try <variable_name> inside <function></NOTES>

because such data is not well-formed XML.  A < character cannot be used unescaped in XML without serving as the start of markup.
Nothing you can do in XSD can change this.

Options

Escape <:

<NOTES>please try &lt;variable_name> inside &lt;function></NOTES>

Use CDATA:

<NOTES><![CDATA[please try <variable_name> inside <function>]]></NOTES>

Or close the "elements":

<NOTES>please try <variable_name/> inside <function/></NOTES>


问:
Laravel 5.5: Route not catching/missing single parameter
It appears the parameter is not passing, but after various edits no luck, and no way to strip it down anymore than this.

Error:

```<code>Missing required parameters for [Route: request.new-request]
[URI: housing-request/{unit}].
(View: /vhosts/web.local/resources/views/requests/unit-1.blade.php)
</code>```

Link/URL:

```<code><a href="{{ route('request.new-request', ['unit' => 'single']) }}">
http://web.local/housing-request/single
</code>```

Route:

```<code>Route::get('/housing-request/{unit}', 'RequestsController@showHousingUnit')->name('request.new-request');
</code>```

Controller:

```<code>  public function showHousingUnit($unit)
  {

      if($unit == "single"){

         return view('requests.unit-1');

      } else if($unit == "double") {

        return view('requests.unit-2');

     }

  }
</code>```

答: The error was on a route inside the view which was missing the parameter</p>

Body:
It appears the parameter is not passing, but after various edits no luck, and no way to strip it down anymore than this.

Error:

Missing required parameters for [Route: request.new-request]
[URI: housing-request/{unit}].
(View: /vhosts/web.local/resources/views/requests/unit-1.blade.php)

Link/URL:

 'single']) }}">
http://web.local/housing-request/single

Route:

Route::get('/housing-request/{unit}', 'RequestsController@showHousingUnit')->name('request.new-request');

Controller:

  public function showHousingUnit($unit)
  {

      if($unit == "single"){

         return view('requests.unit-1');

      } else if($unit == "double") {

        return view('requests.unit-2');

     }

  }


问:
zsh prompt adam2 - script output without newline, is not being displayed
I'm using adam2 prompt on iterm2 terminal on mac for last 5 years and only today it struck to me that the scripts which produce output without a trailing newline character, is not being displayed.

For example:

(1) This doesn't display any output: echo -n "foo"

```
.-(~)---------------------------(gazal@Admins-MBP)-
--> echo -n "foo"
.-(~)---------------------------(gazal@Admins-MBP)-
-->
```

(2) However, this works correctly: echo "foo"

```
.-(~)---------------------------(gazal@Admins-MBP)-
--> echo  "foo"
foo
.-(~)---------------------------(gazal@Admins-MBP)-
-->
```

To setup this, I simply did this

autoload -Uz promptinit

promptinit

prompt adam2

However, if I switch to adam1 or any other prompt, the issue as described in (1) does not happen.

答:
You have to add setopt prompt_sp after you initialized the prompt, like so:

```<code>autoload -U promptinit
promptinit
prompt adam2 8bit
setopt prompt_sp
</code>```

https://www.zsh.org/mla/users/2017/msg00607.html

Body:
I'm using adam2 prompt on iterm2 terminal on mac for last 5 years and only today it struck to me that the scripts which produce output without a trailing newline character, is not being displayed.

For example:

(1) This doesn't display any output: echo -n "foo"

.-(~)---------------------------(gazal@Admins-MBP)-
--> echo -n "foo"
.-(~)---------------------------(gazal@Admins-MBP)-
-->

(2) However, this works correctly: echo "foo"

.-(~)---------------------------(gazal@Admins-MBP)-
--> echo  "foo"
foo
.-(~)---------------------------(gazal@Admins-MBP)-
-->

To setup this, I simply did this

autoload -Uz promptinit

promptinit

prompt adam2

However, if I switch to adam1 or any other prompt, the issue as described in (1) does not happen.

Body:
You have to add setopt prompt_sp after you initialized the prompt, like so:

autoload -U promptinit
promptinit
prompt adam2 8bit
setopt prompt_sp

https://www.zsh.org/mla/users/2017/msg00607.html


问:
Order By not working with Top MS SQL Query
I'm creating a query that should fit with the DataTable I'm working on from MsSQL. This is my first time to work on MsSQL so I'm trying to figure out the equivalent MsSQL query from my MySQL.

I made a custom query that will handle the LIMIT function in MySQL to MsSQL(hopefully). I have the following query that I use in my datatable:

```<code>    SELECT * FROM (
        SELECT top 20 CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) AS week_name,
        AVG(DATEDIFF(day, CONVERT(date, [UnloadDate]), CONVERT(date, [DeliveryDate]))) as Average_Delivery_Days
        FROM [CARGODB].[dbo].[Cargo_Transactions]
        WHERE [DeliveryDate] IS NOT NULL AND [DeliveryDate] != 0
        AND [UnloadDate] IS NOT NULL AND [UnloadDate] != 0 AND [DeliveryDate] > [UnloadDate] AND [Deleted] = 0 and [StageID] = 'D'
        AND [RouteID] IS NOT NULL AND [RouteID] != '' AND CONVERT(date, [DeliveryDate]) BETWEEN '2016-01-01' AND GETDATE()
        AND CONVERT(date, [DeliveryDate]) >= DATEADD(week, -24, getdate())
        GROUP BY DATEPART(YEAR,[DeliveryDate]), DATEPART(WEEK,[DeliveryDate])
        ORDER BY CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) ASC
    ) as foo
    except
    SELECT * FROM (
        SELECT top 10 CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) AS week_name,
        AVG(DATEDIFF(day, CONVERT(date, [UnloadDate]), CONVERT(date, [DeliveryDate]))) as Average_Delivery_Days
        FROM [CARGODB].[dbo].[Cargo_Transactions]
        WHERE [DeliveryDate] IS NOT NULL AND [DeliveryDate] != 0
        AND [UnloadDate] IS NOT NULL AND [UnloadDate] != 0 AND [DeliveryDate] > [UnloadDate] AND [Deleted] = 0 and [StageID] = 'D'
        AND [RouteID] IS NOT NULL AND [RouteID] != '' AND CONVERT(date, [DeliveryDate]) BETWEEN '2016-01-01' AND GETDATE()
        AND CONVERT(date, [DeliveryDate]) >= DATEADD(week, -24, getdate())
        GROUP BY DATEPART(YEAR,[DeliveryDate]), DATEPART(WEEK,[DeliveryDate])
        ORDER BY CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) ASC
    ) as bar
</code>```

The result is:

```<code>week_name     | Average_Delivery_Days
==================================
2017 Week 36  | 15
2017 Week 39  | 11
2017 Week 41  | 13
2017 Week 42  | 10
2017 Week 38  | 12
2017 Week 40  | 12
2017 Week 35  | 14
2017 Week 43  | 6
2017 Week 37  | 12
2017 Week 44  | 9
</code>```

But I would like it to be sorted by week number ascending so it should display 36, 37, 38, 39, and so on.

What could be missing in my query?

I appreciate your help. Thanks!

答:
Your ORDER BY clause only affects the TOP selection; it doesn't order the result set.  Adding an ORDER BY to the end of the query should do the trick.

I do see one other issue, however, which is that you're going to be sorting a VARCHAR column with numbers in it.  VARCHAR is sorted alphabetically, so Week 2 will appear after Week 19.  So I would do this:

```<code>SELECT
/* Explicitly select these columns */
week_name
, Average_Delivery_Days

FROM (
    SELECT top 20
    /* Add separate columns for numerical year and week */
     iyear = YEAR(DeliveryDate)
    , iweek = DATEPART(WEEK,DeliveryDate)
    , CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) AS week_name,
    AVG(DATEDIFF(day, CONVERT(date, [UnloadDate]), CONVERT(date, [DeliveryDate]))) as Average_Delivery_Days
    FROM [CARGODB].[dbo].[Cargo_Transactions]
    WHERE [DeliveryDate] IS NOT NULL AND [DeliveryDate] != 0
    AND [UnloadDate] IS NOT NULL AND [UnloadDate] != 0 AND [DeliveryDate] > [UnloadDate] AND [Deleted] = 0 and [StageID] = 'D'
    AND [RouteID] IS NOT NULL AND [RouteID] != '' AND CONVERT(date, [DeliveryDate]) BETWEEN '2016-01-01' AND GETDATE()
    AND CONVERT(date, [DeliveryDate]) >= DATEADD(week, -24, getdate())
    GROUP BY DATEPART(YEAR,[DeliveryDate]), DATEPART(WEEK,[DeliveryDate])
    ORDER BY CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) ASC
) as foo
except
SELECT * FROM (
    SELECT top 10 CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) AS week_name,
    AVG(DATEDIFF(day, CONVERT(date, [UnloadDate]), CONVERT(date, [DeliveryDate]))) as Average_Delivery_Days
    FROM [CARGODB].[dbo].[Cargo_Transactions]
    WHERE [DeliveryDate] IS NOT NULL AND [DeliveryDate] != 0
    AND [UnloadDate] IS NOT NULL AND [UnloadDate] != 0 AND [DeliveryDate] > [UnloadDate] AND [Deleted] = 0 and [StageID] = 'D'
    AND [RouteID] IS NOT NULL AND [RouteID] != '' AND CONVERT(date, [DeliveryDate]) BETWEEN '2016-01-01' AND GETDATE()
    AND CONVERT(date, [DeliveryDate]) >= DATEADD(week, -24, getdate())
    GROUP BY DATEPART(YEAR,[DeliveryDate]), DATEPART(WEEK,[DeliveryDate])
    ORDER BY CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) ASC
) as bar
 /* sort by the numeric columns */
 ORDER BY foo.iyear, foo.iweek
</code>```

Body:
I'm creating a query that should fit with the DataTable I'm working on from MsSQL. This is my first time to work on MsSQL so I'm trying to figure out the equivalent MsSQL query from my MySQL.

I made a custom query that will handle the LIMIT function in MySQL to MsSQL(hopefully). I have the following query that I use in my datatable:

    SELECT * FROM (
        SELECT top 20 CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) AS week_name,
        AVG(DATEDIFF(day, CONVERT(date, [UnloadDate]), CONVERT(date, [DeliveryDate]))) as Average_Delivery_Days
        FROM [CARGODB].[dbo].[Cargo_Transactions]
        WHERE [DeliveryDate] IS NOT NULL AND [DeliveryDate] != 0
        AND [UnloadDate] IS NOT NULL AND [UnloadDate] != 0 AND [DeliveryDate] > [UnloadDate] AND [Deleted] = 0 and [StageID] = 'D'
        AND [RouteID] IS NOT NULL AND [RouteID] != '' AND CONVERT(date, [DeliveryDate]) BETWEEN '2016-01-01' AND GETDATE()
        AND CONVERT(date, [DeliveryDate]) >= DATEADD(week, -24, getdate())
        GROUP BY DATEPART(YEAR,[DeliveryDate]), DATEPART(WEEK,[DeliveryDate])
        ORDER BY CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) ASC
    ) as foo
    except
    SELECT * FROM (
        SELECT top 10 CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) AS week_name,
        AVG(DATEDIFF(day, CONVERT(date, [UnloadDate]), CONVERT(date, [DeliveryDate]))) as Average_Delivery_Days
        FROM [CARGODB].[dbo].[Cargo_Transactions]
        WHERE [DeliveryDate] IS NOT NULL AND [DeliveryDate] != 0
        AND [UnloadDate] IS NOT NULL AND [UnloadDate] != 0 AND [DeliveryDate] > [UnloadDate] AND [Deleted] = 0 and [StageID] = 'D'
        AND [RouteID] IS NOT NULL AND [RouteID] != '' AND CONVERT(date, [DeliveryDate]) BETWEEN '2016-01-01' AND GETDATE()
        AND CONVERT(date, [DeliveryDate]) >= DATEADD(week, -24, getdate())
        GROUP BY DATEPART(YEAR,[DeliveryDate]), DATEPART(WEEK,[DeliveryDate])
        ORDER BY CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) ASC
    ) as bar

The result is:

week_name     | Average_Delivery_Days
==================================
2017 Week 36  | 15
2017 Week 39  | 11
2017 Week 41  | 13
2017 Week 42  | 10
2017 Week 38  | 12
2017 Week 40  | 12
2017 Week 35  | 14
2017 Week 43  | 6
2017 Week 37  | 12
2017 Week 44  | 9

But I would like it to be sorted by week number ascending so it should display 36, 37, 38, 39, and so on.

What could be missing in my query?

I appreciate your help. Thanks!

Body:
Your ORDER BY clause only affects the TOP selection; it doesn't order the result set.  Adding an ORDER BY to the end of the query should do the trick.

I do see one other issue, however, which is that you're going to be sorting a VARCHAR column with numbers in it.  VARCHAR is sorted alphabetically, so Week 2 will appear after Week 19.  So I would do this:

SELECT
/* Explicitly select these columns */
week_name
, Average_Delivery_Days

FROM (
    SELECT top 20
    /* Add separate columns for numerical year and week */
     iyear = YEAR(DeliveryDate)
    , iweek = DATEPART(WEEK,DeliveryDate)
    , CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) AS week_name,
    AVG(DATEDIFF(day, CONVERT(date, [UnloadDate]), CONVERT(date, [DeliveryDate]))) as Average_Delivery_Days
    FROM [CARGODB].[dbo].[Cargo_Transactions]
    WHERE [DeliveryDate] IS NOT NULL AND [DeliveryDate] != 0
    AND [UnloadDate] IS NOT NULL AND [UnloadDate] != 0 AND [DeliveryDate] > [UnloadDate] AND [Deleted] = 0 and [StageID] = 'D'
    AND [RouteID] IS NOT NULL AND [RouteID] != '' AND CONVERT(date, [DeliveryDate]) BETWEEN '2016-01-01' AND GETDATE()
    AND CONVERT(date, [DeliveryDate]) >= DATEADD(week, -24, getdate())
    GROUP BY DATEPART(YEAR,[DeliveryDate]), DATEPART(WEEK,[DeliveryDate])
    ORDER BY CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) ASC
) as foo
except
SELECT * FROM (
    SELECT top 10 CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) AS week_name,
    AVG(DATEDIFF(day, CONVERT(date, [UnloadDate]), CONVERT(date, [DeliveryDate]))) as Average_Delivery_Days
    FROM [CARGODB].[dbo].[Cargo_Transactions]
    WHERE [DeliveryDate] IS NOT NULL AND [DeliveryDate] != 0
    AND [UnloadDate] IS NOT NULL AND [UnloadDate] != 0 AND [DeliveryDate] > [UnloadDate] AND [Deleted] = 0 and [StageID] = 'D'
    AND [RouteID] IS NOT NULL AND [RouteID] != '' AND CONVERT(date, [DeliveryDate]) BETWEEN '2016-01-01' AND GETDATE()
    AND CONVERT(date, [DeliveryDate]) >= DATEADD(week, -24, getdate())
    GROUP BY DATEPART(YEAR,[DeliveryDate]), DATEPART(WEEK,[DeliveryDate])
    ORDER BY CAST(DATEPART(YEAR,[DeliveryDate]) as varchar) + ' Week ' + CAST(DATEPART(WEEK,[DeliveryDate]) AS varchar) ASC
) as bar
 /* sort by the numeric columns */
 ORDER BY foo.iyear, foo.iweek


问:
How to keep Spark cluster alive between spark2-submits?
I need to process input data files as and when they arrive by doing a spark2-submit to process the input files through pyspark script. What I have observed is that for every spark2--submit, spark does a lot of initialization before doing the latest input file's data processing. This results in delay. How can I keep the Spark cluster alive between spark2-submits?

Separate but related question: Apart from spark2-submit, what other mechanisms can be used to submit payloads to spark?

Thanks in advance for your insights.

答:
Cluster

Unless you use Spark in local mode (there is really no cluster there) cluster is preserved between different applications.

SparkContext and SparkSession

Are local objects. There cannot live longer than the application. If initialization time is unacceptable you can adjust your application to use application serve like Livy.


问:
CLR Table-valued function with array argument
I have a SQL CLR function like this one:

```<code>public partial class UserDefinedFunctions {
    [Microsoft.SqlServer.Server.SqlFunction(TableDefinition = "number int", FillRowMethodName = "FillRow")]
    public static IEnumerable MyClrFunction(object obj) {
        // read obj array input and then
        var result = new ArrayList();
        result.Add((SqlInt32)1);
        result.Add((SqlInt32)2);
        result.Add((SqlInt32)3);
        return result;
    }

    public static void FillRow(object obj, out SqlInt32 number) {
        number = (SqlInt32)obj;
    }

}
</code>```

I would like to use it this way:

```<code>DECLARE @x arrayOfInt

INSERT INTO @x VALUES (10)
INSERT INTO @x VALUES (20)
INSERT INTO @x VALUES (30)

SELECT * FROM dbo.MyClrFunction(@x)
</code>```

arrayOfInt is:

```<code>CREATE TYPE [dbo].[arrayOfInt] AS TABLE(
[item] [int] NOT NULL,
PRIMARY KEY CLUSTERED
    (
    [item] ASC
    ) WITH (IGNORE_DUP_KEY = OFF)
)
</code>```

Problem I have is that arrayOfInt is incompatible with sql_variant. Is possible to write CLR Table-valued function which has an array (table) argument?

答:
SQLCLR does not support Table-Valued Parameters (TVPs):

CREATE PROCEDURE

[ type_schema_name. ] data_type

  ...

  Guidelines for CLR procedures:

Table-valued or cursor data types cannot be used as parameters.

CREATE FUNCTION

[ type_schema_name. ] parameter_data_type

  ... For CLR functions, all data types, including CLR user-defined types, are allowed except text, ntext, image, user-defined table types and timestamp data types.

However, you do have several options:

If the array is a simple list of numbers and/or strings you can always send in a delimited list of values (via SqlString / NVARCHAR(MAX)) and use String.Split() to unpack it.

If the array is more complex (i.e. multiple fields), then you can wrap the data in XML and pass that in as SqlXml.

Or, if you have a complex array then you can create a CLR UDT to be whatever     structure you like and pass that into the Function. This requires a bit more effort, though.

Also, keep in mind that Table-Valued Parameters are just that, tables (table variables), and not in-memory data structures such as Arrays and Collections. The main benefit and use-case of TVPs are in reducing complexity and increasing performance when sending data to SQL Server from an application. If you are already inside SQL Server such that you are creating a table variable and then wanting to pass it to a CLR stored procedure (or maybe function), then all you need to do is look at the problem in a slightly different way and you can accomplish the same basic thing:

Use a temporary table instead of a table variable

Pass the temporary table name to the CLR stored procedure

Use the in-process connection (i.e. connection string = "Context Connection = true;") because it can access local temporary objects

You can use the temporary table in any SQL that you execute by using the table name that was passed in

You can get the data from that table into the .NET context by doing a simple SELECT * on the table name that was passed in, and then read each row via SqlCommand.ExecuteReader() and SqlDataReader.Read()

ContentLicense: CC BY-SA 2.5

Body:
I have a SQL CLR function like this one:

public partial class UserDefinedFunctions {
    [Microsoft.SqlServer.Server.SqlFunction(TableDefinition = "number int", FillRowMethodName = "FillRow")]
    public static IEnumerable MyClrFunction(object obj) {
        // read obj array input and then
        var result = new ArrayList();
        result.Add((SqlInt32)1);
        result.Add((SqlInt32)2);
        result.Add((SqlInt32)3);
        return result;
    }

    public static void FillRow(object obj, out SqlInt32 number) {
        number = (SqlInt32)obj;
    }

}

I would like to use it this way:

DECLARE @x arrayOfInt

INSERT INTO @x VALUES (10)
INSERT INTO @x VALUES (20)
INSERT INTO @x VALUES (30)

SELECT * FROM dbo.MyClrFunction(@x)

arrayOfInt is:

CREATE TYPE [dbo].[arrayOfInt] AS TABLE(
[item] [int] NOT NULL,
PRIMARY KEY CLUSTERED
    (
    [item] ASC
    ) WITH (IGNORE_DUP_KEY = OFF)
)

Problem I have is that arrayOfInt is incompatible with sql_variant. Is possible to write CLR Table-valued function which has an array (table) argument?


问:
Highlight a slice of pie chart in highcharts on click of a div
How do I Highlight a slice of pie chart in highcharts on click of a div? More like copying the highlighting functionality of legends but from a differrent div.

```<code>Highcharts.chart('container', {
chart: {
    plotBackgroundColor: null,
    plotBorderWidth: null,
    plotShadow: false,
    type: 'pie'
},
title: {
    text: 'Browser market shares January, 2015 to May, 2015'
},
tooltip: {
    pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
    pie: {
        allowPointSelect: true,
        cursor: 'pointer',
        dataLabels: {
            enabled: false
        },
        showInLegend: true
    }
},
series: [{
    name: 'Brands',
    colorByPoint: true,
    data: [{
        name: 'Microsoft Internet Explorer',
        y: 56.33
    }, {
        name: 'Chrome',
        y: 24.03,
        sliced: true,
        selected: true
    }, {
        name: 'Firefox',
        y: 10.38
    }, {
        name: 'Safari',
        y: 4.77
    }, {
        name: 'Opera',
        y: 0.91
    }, {
        name: 'Proprietary or Undetectable',
        y: 0.2
    }]
}]
</code>```

});

For example in the highchart above I want a different div to do what legends do here. Here is the link to jsfiddle http://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/pie-legend/

答:
To do this make the chart a variable and interact with it like a typical javascript Object:

// Build the chart
$(function() {
  var chart = Highcharts.chart('container', {
      chart: {
          plotBackgroundColor: null,
          plotBorderWidth: null,
          plotShadow: false,
          type: 'pie'
      },
      title: {
          text: 'Browser market shares January, 2015 to May, 2015'
      },
      tooltip: {
          pointFormat: '{series.name}: {point.percentage:.1f}%'
      },
      plotOptions: {
          pie: {
              allowPointSelect: true,
              cursor: 'pointer',
              dataLabels: {
                  enabled: false
              },
              showInLegend: true
          }
      },
      series: [{
          name: 'Brands',
          colorByPoint: true,
          data: [{
              name: 'Microsoft Internet Explorer',
              y: 56.33
          }, {
              name: 'Chrome',
              y: 24.03,
              sliced: true,
              selected: true
          }, {
              name: 'Firefox',
              y: 10.38
          }, {
              name: 'Safari',
              y: 4.77
          }, {
              name: 'Opera',
              y: 0.91
          }, {
              name: 'Proprietary or Undetectable',
              y: 0.2
          }]
      }]
  });

  $('#button').click(function() {
      var point = chart.series[0].data[3]; //Or any other point
      point.select();
      chart.tooltip.refresh(point);
    });
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

<div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>
<div id="button" style="background-color:grey; width:100px;color:white;">Select Safari</div></code>```

edit: words

Body:
How do I Highlight a slice of pie chart in highcharts on click of a div? More like copying the highlighting functionality of legends but from a differrent div.

Highcharts.chart('container', {
chart: {
    plotBackgroundColor: null,
    plotBorderWidth: null,
    plotShadow: false,
    type: 'pie'
},
title: {
    text: 'Browser market shares January, 2015 to May, 2015'
},
tooltip: {
    pointFormat: '{series.name}: {point.percentage:.1f}%'
},
plotOptions: {
    pie: {
        allowPointSelect: true,
        cursor: 'pointer',
        dataLabels: {
            enabled: false
        },
        showInLegend: true
    }
},
series: [{
    name: 'Brands',
    colorByPoint: true,
    data: [{
        name: 'Microsoft Internet Explorer',
        y: 56.33
    }, {
        name: 'Chrome',
        y: 24.03,
        sliced: true,
        selected: true
    }, {
        name: 'Firefox',
        y: 10.38
    }, {
        name: 'Safari',
        y: 4.77
    }, {
        name: 'Opera',
        y: 0.91
    }, {
        name: 'Proprietary or Undetectable',
        y: 0.2
    }]
}]

});

For example in the highchart above I want a different div to do what legends do here. Here is the link to jsfiddle http://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/pie-legend/

Body:
To do this make the chart a variable and interact with it like a typical javascript Object:

// Build the chart
$(function() {
  var chart = Highcharts.chart('container', {
      chart: {
          plotBackgroundColor: null,
          plotBorderWidth: null,
          plotShadow: false,
          type: 'pie'
      },
      title: {
          text: 'Browser market shares January, 2015 to May, 2015'
      },
      tooltip: {
          pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
      },
      plotOptions: {
          pie: {
              allowPointSelect: true,
              cursor: 'pointer',
              dataLabels: {
                  enabled: false
              },
              showInLegend: true
          }
      },
      series: [{
          name: 'Brands',
          colorByPoint: true,
          data: [{
              name: 'Microsoft Internet Explorer',
              y: 56.33
          }, {
              name: 'Chrome',
              y: 24.03,
              sliced: true,
              selected: true
          }, {
              name: 'Firefox',
              y: 10.38
          }, {
              name: 'Safari',
              y: 4.77
          }, {
              name: 'Opera',
              y: 0.91
          }, {
              name: 'Proprietary or Undetectable',
              y: 0.2
          }]
      }]
  });

  $('#button').click(function() {
      var point = chart.series[0].data[3]; //Or any other point
      point.select();
      chart.tooltip.refresh(point);
    });
})

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

<div id="container" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>
<div id="button" style="background-color:grey; width:100px;color:white;">Select Safari</div>

edit: words


问:
Unexpected (wrong) template deduction using armadillo library
I am writing a c++ template function, aimed at computing a function of a matrix, where the matrix type is a template parameter. When using it with the armadillo library, I get an unexpected failure in compilation.
I am using armadillo 8.300 and gcc 7.2.0.
In the following a test program which illustrates the issue.

```<code>#include <armadillo>

arma::Mat<double> sq(const arma::Mat<double>& M)
{
  arma::Mat<double> res(M);
  res = res * M;
  return res;
}

template <class MatrixClass>
MatrixClass sqgen(const MatrixClass& M)
{
  MatrixClass res(M);
  res = res * M;
  return res;
}

int main()
{
  arma::Mat<double> id(3, 3, arma::fill::eye);
  arma::Mat<double> m(3, 3, arma::fill::ones);

  arma::Mat<double> m2(sq(m));
  arma::Mat<double> m_id2(sq(id - m));

  arma::Mat<double> m2gen(sqgen(m));
  arma::Mat<double> m_id2gen(sqgen(id - m)); // Error here
  return 0;
}
</code>```

For illustration I defined two functions sq and sqgen which essentially do the same job. sq is the explicit instantiation of sqgen when the template parameter MatrixClass is arma::Mat<double>. The compilation with

```<code>g++ -std=c++14 -Wall -pedantic -O3 -o test test.cpp -lstdc++ -larmadillo
</code>```

fails giving the error:

```<code>test.cpp: In instantiation of ‘MatrixClass sq(const MatrixClass&) [with MatrixClass = arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>]’:
test.cpp:24:36:   required from here
test.cpp:14:7: error: no match for ‘operator=’ (operand types are ‘arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>’ and ‘arma::enable_if2<true, const arma::Glue<arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::glue_times> >::result {aka const arma::Glue<arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::glue_times>}’)
   res = res * M;
   ~~~~^~~~~~~~~
In file included from /usr/include/armadillo:204:0,
                 from test.cpp:1:
/usr/include/armadillo_bits/eGlue_bones.hpp:22:7: note: candidate: arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>& arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>::operator=(const arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>&) <deleted>
 class eGlue : public Base<typename T1::elem_type, eGlue<T1, T2, eglue_type> >
       ^~~~~
/usr/include/armadillo_bits/eGlue_bones.hpp:22:7: note:   no known conversion for argument 1 from ‘arma::enable_if2<true, const arma::Glue<arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::glue_times> >::result {aka const arma::Glue<arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::glue_times>}’ to ‘const arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>&’
</code>```

The problem lies in the last call of sqgen. There is no problem in calling sqgen(m), however the call sqgen(id - m) causes the error.  Notice that, instead, using the call sq(id - m) is perfectly legal. Since the function sqgen should be, in the code above, exactly equal to sq, I presume that the compiler does not deduce correctly the template parameter MatrixClass in sqgen(id - m).
In fact, upon substituting

```<code>arma::Mat<double> m_id2gen(sqgen(id - m));
</code>```

with

```<code>arma::Mat<double> m_id2gen(sqgen(arma::Mat<double>(id - m)));
</code>```

the code compiles correctly.

答:
The compiler is working fine. Armadillo does heavy optimization of expressions involving matrices, such as reordering multiplications, delaying evaluation, and more. This is all done via template metaprogramming. The Armadillo matrix classes provide copy-assignment operators (e.g., mat::operator=()), which take other matrices and copy their data. There is, however, no overload of the operator=() which takes one of these expression templates. Hence the error about operand types are 'eGlue<...>...' and such.

The quick fix to this is to add .eval() to the end of any expression, which forces evaluation of said expression. So you'd do:

```<code>res = (res * M).eval();
return res;
</code>```

Or just:

```<code>return (res * M).eval(); // I'm actually not sure if the eval() is necessary here.
</code>```

Another option is to try doing in-place multiplication, which should also work fine. As in:

```<code>res *= M;
return res;
</code>```

Body:
I am writing a c++ template function, aimed at computing a function of a matrix, where the matrix type is a template parameter. When using it with the armadillo library, I get an unexpected failure in compilation.
I am using armadillo 8.300 and gcc 7.2.0.
In the following a test program which illustrates the issue.

#include <armadillo>

arma::Mat<double> sq(const arma::Mat<double>& M)
{
  arma::Mat<double> res(M);
  res = res * M;
  return res;
}

template <class MatrixClass>
MatrixClass sqgen(const MatrixClass& M)
{
  MatrixClass res(M);
  res = res * M;
  return res;
}

int main()
{
  arma::Mat<double> id(3, 3, arma::fill::eye);
  arma::Mat<double> m(3, 3, arma::fill::ones);

  arma::Mat<double> m2(sq(m));
  arma::Mat<double> m_id2(sq(id - m));

  arma::Mat<double> m2gen(sqgen(m));
  arma::Mat<double> m_id2gen(sqgen(id - m)); // Error here
  return 0;
}

For illustration I defined two functions sq and sqgen which essentially do the same job. sq is the explicit instantiation of sqgen when the template parameter MatrixClass is arma::Mat<double>. The compilation with

g++ -std=c++14 -Wall -pedantic -O3 -o test test.cpp -lstdc++ -larmadillo

fails giving the error:

test.cpp: In instantiation of ‘MatrixClass sq(const MatrixClass&) [with MatrixClass = arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>]’:
test.cpp:24:36:   required from here
test.cpp:14:7: error: no match for ‘operator=’ (operand types are ‘arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>’ and ‘arma::enable_if2<true, const arma::Glue<arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::glue_times> >::result {aka const arma::Glue<arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::glue_times>}’)
   res = res * M;
   ~~~~^~~~~~~~~
In file included from /usr/include/armadillo:204:0,
                 from test.cpp:1:
/usr/include/armadillo_bits/eGlue_bones.hpp:22:7: note: candidate: arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>& arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>::operator=(const arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>&) <deleted>
 class eGlue : public Base<typename T1::elem_type, eGlue<T1, T2, eglue_type> >
       ^~~~~
/usr/include/armadillo_bits/eGlue_bones.hpp:22:7: note:   no known conversion for argument 1 from ‘arma::enable_if2<true, const arma::Glue<arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::glue_times> >::result {aka const arma::Glue<arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>, arma::glue_times>}’ to ‘const arma::eGlue<arma::Mat<double>, arma::Mat<double>, arma::eglue_minus>&’

The problem lies in the last call of sqgen. There is no problem in calling sqgen(m), however the call sqgen(id - m) causes the error.  Notice that, instead, using the call sq(id - m) is perfectly legal. Since the function sqgen should be, in the code above, exactly equal to sq, I presume that the compiler does not deduce correctly the template parameter MatrixClass in sqgen(id - m).
In fact, upon substituting

arma::Mat<double> m_id2gen(sqgen(id - m));

with

arma::Mat<double> m_id2gen(sqgen(arma::Mat<double>(id - m)));

the code compiles correctly.

Body:
The compiler is working fine. Armadillo does heavy optimization of expressions involving matrices, such as reordering multiplications, delaying evaluation, and more. This is all done via template metaprogramming. The Armadillo matrix classes provide copy-assignment operators (e.g., mat::operator=()), which take other matrices and copy their data. There is, however, no overload of the operator=() which takes one of these expression templates. Hence the error about operand types are 'eGlue<...>...' and such.

The quick fix to this is to add .eval() to the end of any expression, which forces evaluation of said expression. So you'd do:

res = (res * M).eval();
return res;

Or just:

return (res * M).eval(); // I'm actually not sure if the eval() is necessary here.

Another option is to try doing in-place multiplication, which should also work fine. As in:

res *= M;
return res;


问:
Go array initialization
```<code>func identityMat4() [16]float {
    return {
        1, 0, 0, 0,
        0, 1, 0, 0,
        0, 0, 1, 0,
        0, 0, 0, 1 }
}
</code>```

I hope you get the idea of what I'm trying to do from the example. How do I do this in Go?

答:
How to use an array initializer to initialize a  test table block:</p>

```<code>tables := []struct {
    input []string
    result string
} {
    {[]string{"one ", " two", " three "}, "onetwothree"},
    {[]string{" three", "four ", " five "}, "threefourfive"},
}

for _, table := range tables {
    result := StrTrimConcat(table.input...)

    if result != table.result {
        t.Errorf("Result was incorrect. Expected: %v. Got: %v. Input: %v.", table.result, result, table.input)
    }
}
</code>```

Title: Go array initialization

Body:
func identityMat4() [16]float {
    return {
        1, 0, 0, 0,
        0, 1, 0, 0,
        0, 0, 1, 0,
        0, 0, 0, 1 }
}

I hope you get the idea of what I'm trying to do from the example. How do I do this in Go?

Body:
How to use an array initializer to initialize a  test table block:

tables := []struct {
    input []string
    result string
} {
    {[]string{"one ", " two", " three "}, "onetwothree"},
    {[]string{" three", "four ", " five "}, "threefourfive"},
}

for _, table := range tables {
    result := StrTrimConcat(table.input...)

    if result != table.result {
        t.Errorf("Result was incorrect. Expected: %v. Got: %v. Input: %v.", table.result, result, table.input)
    }
}


问:
Pika/RabbitMq Socket closed on large message sent through SSL
I am receiving an error ‘Socket closed when connection was open’ when sending a large message on an SSL connection to RabbitMq using Pika.

The connection is a SelectConnection with TLSv1_2 protocol configuration

It fails for messages bigger than 130kB.  Smaller messages go through fine.  Without SSL, the same code works for much larger messages, even tens of megabytes are passed around flawlessly.

Environment:

pika 0.10.0

rabbitmq 3.6.9, erlang 19.2

sender, receiver, and rabbitmq server on the same physical machine

linux or macos

Any suggestion on what is happening and how to fix it?

thanks a lot

答:
Had exactly the same issue - fixed it by using monkey patching from gevent </p>

```<code>from gevent import monkey
monkey.patch_all()
</code>```

Body:
Had exactly the same issue - fixed it by using monkey patching from gevent

from gevent import monkey
monkey.patch_all()


问:
Handling async situations in an .NET MVC application
I wanted to get some basic .NET MVC understanding so I started working on a very simple application that is somewhat similar to Yelp.  It consists of a User object and Business object.  A user can add businesses to their "watch list" and when someone creates a review for that business the application would look through a table of "user id-business id" relations and email the users that are watching that business for new reviews (so that they can respond to them).

In my ReviewsController, I have a Create action that creates a review.  Before that action returns, I would like to run a method that checks if there are any watches for the business the review was just created for.

This is where I get stuck because I'm not sure what would be a good way of doing this in MVC setting(?).

What I do know is that the user who is creating the review does not need to wait for the application to look through the "user-business" relation table.

Would it be a good idea to create this lookup functionality as an async method? I also looked into events but seems like events are not ideal in MVC setting. Are there any well-established patters in MVC world for situations like these?

答:
@Jonathan Tyson pointed out this article which shows some great options for background taks.

I am thinking of going with QueueBackgroundWorkItem as it seems to be a good fit for my scenario. It is already build in with .Net 4.5.2 and it does everything I am looking for.

Beware of the 90 second limit on it (might not be a great solution for everyone).  In my case it is more than enough time.


问:
Bootstrap layout splitting
Please help i need bootstrap layout design. I need layout design like the attachment image format. I need one page splitted to two column (header and content with scroll bar) and another column splitted by two rows with responsive. I tried all but not working. Please help

答:
Start here ... https://v4-alpha.getbootstrap.com/getting-started/download/

In general, building a layout begins with a container element. The container defines a 12 column grid system. Read more about this here ... https://v4-alpha.getbootstrap.com/layout/grid/

Each column is given a class with the naming convention, col-{breakpoint}-{# of columns}

Here is a example of a three column layout. The first and last .col will span 3 column units, while the middle will span 6.

```<code><div class="container">
  <div class="row">
    <div class="col-3">
      FIRST COLUMN
    </div>
    <div class="col-6">
      SECOND COLUMN
    </div>
    <div class="col-3">
      THIRD COLUMN
    </div>
  </div>
</div>
</code>```

Have fun coding!

Title: Bootstrap layout splitting

Body:
Start here ... https://v4-alpha.getbootstrap.com/getting-started/download/

In general, building a layout begins with a container element. The container defines a 12 column grid system. Read more about this here ... https://v4-alpha.getbootstrap.com/layout/grid/

Each column is given a class with the naming convention, col-{breakpoint}-{# of columns}

Here is a example of a three column layout. The first and last .col will span 3 column units, while the middle will span 6.

<div class="container">
  <div class="row">
    <div class="col-3">
      FIRST COLUMN
    </div>
    <div class="col-6">
      SECOND COLUMN
    </div>
    <div class="col-3">
      THIRD COLUMN
    </div>
  </div>
</div>

Have fun coding!


问:
Firebase Data Structure Best Practice For User Interaction
I am building a review app and wanted to figure out best practices in structuring a Firebase database to store reviews, likes and comments from users on titles and each other's posts. I am using Xcode and Swift.

Do I make a separate REVIEWS node that stores all reviews and has a USER ID child for the user ID of the writer of the review and a TITLE ID node for the ID of the Title being reviewed?

Do I nest reviews associated with the titles or users within the title and user nodes?

When it's time to display say all a user's reviews, do I then query the database using the user's ID?

For displaying all the reviews of a title do I query using the title's ID?

Thanks

答:
This is very difficult to give one answer because there are 100 different structures that would work. Here's a cross-linked, double referenced structure to illustrate that point

```<code>movies
   movie_0
     title: "Monty Python and the Holy Grail"
     reviewed_by
       uid_1: tre
     reviews
       review_0: true

reviews
   review_0
     movie_id: "movie_0"
     uid: "uid_1"
     review: "Best movie evah"

users
  uid_0
     name: "Tim"
     reviewed_movies:
       movie_0: true
     reviews
       review_0: true
</code>```

With that crazyness, you can:

```<code>query movies for which users reviewed it or which reviews
query reviews for certain users, certain movies and that the actual review was
query users for names, which movies that user reviewed and what the reviews were
</code>```

So the question is; what do you need to query for?

Lets take your #3

When it's time to display say all a user's reviews, do I then query
  the database using the user's ID?

The the structure I presented, if you want to get all of a users reviews, you don't have to query at all! You directly observe that users node

```<code>let ref = fbRef.child("users").child("uid_0").child("reviews")
ref.observe...
</code>```

then you can iterate over the results to obtain the review references

Likewise, you could query the reviews node for all reviews where uid is the uid of the the user in question.

I realize this isn't a specific answer but it does provide guides

EDIT

One of the comments was a specific question so let me address it this way.

Suppose the only goal is to see all of the reviews for a specific movie. The structure could be greatly simplified:

```<code>movies
   movie_0
     title: "Monty Python and the Holy Grail"
reviews
   review_0
     movie_id: "movie_0"
     uid: "uid_1"
     review: "Best movie evah"
users
  uid_1
     name: "Tim"
</code>```

Then suppose we know the movie and the movie id of movie_0. To get the reviews and the user, something like this will work

```<code>let reviewsRef = self.ref.child("reviews")
let query = reviewsRef.queryOrdered(byChild: "movie_id").queryEqual(toValue: "movie_0")
query.observeSingleEvent(of: .value) { snapshot in
    for child in snapshot.children {
        let snap = child as! DataSnapshot
        let dict = snap.value as! [String: Any]
        let uid = dict["uid"] as! String
        let review = dict["review"] as! String

        let userRef = self.ref.child("users").child(uid)
        userRef.observeSingleEvent(of: .value, with: { userSnapshot in
            let userDict = userSnapshot.value as! [String: Any]
            let userName = userDict["name"] as! String
            print("\(userName) said \(review)")
        })
    }
}
</code>```

Body:
This is very difficult to give one answer because there are 100 different structures that would work. Here's a cross-linked, double referenced structure to illustrate that point

movies
   movie_0
     title: "Monty Python and the Holy Grail"
     reviewed_by
       uid_1: tre
     reviews
       review_0: true

reviews
   review_0
     movie_id: "movie_0"
     uid: "uid_1"
     review: "Best movie evah"

users
  uid_0
     name: "Tim"
     reviewed_movies:
       movie_0: true
     reviews
       review_0: true

With that crazyness, you can:

query movies for which users reviewed it or which reviews
query reviews for certain users, certain movies and that the actual review was
query users for names, which movies that user reviewed and what the reviews were

So the question is; what do you need to query for?

Lets take your #3

When it's time to display say all a user's reviews, do I then query
  the database using the user's ID?

The the structure I presented, if you want to get all of a users reviews, you don't have to query at all! You directly observe that users node

let ref = fbRef.child("users").child("uid_0").child("reviews")
ref.observe...

then you can iterate over the results to obtain the review references

Likewise, you could query the reviews node for all reviews where uid is the uid of the the user in question.

I realize this isn't a specific answer but it does provide guides

EDIT

One of the comments was a specific question so let me address it this way.

Suppose the only goal is to see all of the reviews for a specific movie. The structure could be greatly simplified:

movies
   movie_0
     title: "Monty Python and the Holy Grail"
reviews
   review_0
     movie_id: "movie_0"
     uid: "uid_1"
     review: "Best movie evah"
users
  uid_1
     name: "Tim"

Then suppose we know the movie and the movie id of movie_0. To get the reviews and the user, something like this will work

let reviewsRef = self.ref.child("reviews")
let query = reviewsRef.queryOrdered(byChild: "movie_id").queryEqual(toValue: "movie_0")
query.observeSingleEvent(of: .value) { snapshot in
    for child in snapshot.children {
        let snap = child as! DataSnapshot
        let dict = snap.value as! [String: Any]
        let uid = dict["uid"] as! String
        let review = dict["review"] as! String

        let userRef = self.ref.child("users").child(uid)
        userRef.observeSingleEvent(of: .value, with: { userSnapshot in
            let userDict = userSnapshot.value as! [String: Any]
            let userName = userDict["name"] as! String
            print("\(userName) said \(review)")
        })
    }
}