问:
Check if certain fee exists in woocommerce order items
I have added extra fees to orders, one of which being optional (customer may choose it on checkout page using an AJAX radio button).

My goal is to echo a custom message in the customer's account, inside the details of only those orders where the optional fee was added.

So, basically, let's say I have 3 fees for a placed order (which are all stored in wp_woocommerce_order_items table as fee in the order_item_type column).

One of these 3 fees is called Optional Fee (the one needed for my goal).

How do I check if this Optional Fee exists in the order's items?

I have started with the following code, but it only gets me the name of the fee that was last stored and thus will not match with Optional Fee.

```<code>$order = wc_get_order( $order_id );

foreach ( $order->get_items('fee') as $item_id => $item ) {

    $fee_name = $item->get_name(); // This only gets me the name of the last fee stored in order items table.

    if ( $fee_name == 'Optional Fee' ) {

            echo 'Custom message';

        }
}
</code>```

I think I should somehow get the list of fees (is it an array?) and check if Optional Fee exists in that list, but I can't figure out how to do it and couldn't find a working solution so far.

答:
After 2 days of trial & error, I finally figured it out. I don't know if it's the best solution, but it works.

Basically, what I needed to do was to return a true statement if the Optional Fee was found when looping through the order's fee items.

If anybody ever needs something similar, here's the code:

```<code>$order = wc_get_order( $order_id );

$optional_fee_exists = false;

   $fee_counter = 0;

   foreach ( $order->get_fees() as $item_fee ) {

       $fee_counter++;

       $fee_name = $item_fee->get_name();

       if ( $fee_name == 'Optional Fee' ) {

           $optional_fee_exists = true;

       }
   }

if ( $optional_fee_exists ) {

   //do stuff;

}

</code>```

Body:
I have added extra fees to orders, one of which being optional (customer may choose it on checkout page using an AJAX radio button).

My goal is to echo a custom message in the customer's account, inside the details of only those orders where the optional fee was added.

So, basically, let's say I have 3 fees for a placed order (which are all stored in wp_woocommerce_order_items table as fee in the order_item_type column).

One of these 3 fees is called Optional Fee (the one needed for my goal).

How do I check if this Optional Fee exists in the order's items?

I have started with the following code, but it only gets me the name of the fee that was last stored and thus will not match with Optional Fee.

$order = wc_get_order( $order_id );

foreach ( $order->get_items('fee') as $item_id => $item ) {

    $fee_name = $item->get_name(); // This only gets me the name of the last fee stored in order items table.

    if ( $fee_name == 'Optional Fee' ) {

            echo 'Custom message';

        }
}

I think I should somehow get the list of fees (is it an array?) and check if Optional Fee exists in that list, but I can't figure out how to do it and couldn't find a working solution so far.

Body:
After 2 days of trial & error, I finally figured it out. I don't know if it's the best solution, but it works.

Basically, what I needed to do was to return a true statement if the Optional Fee was found when looping through the order's fee items.

If anybody ever needs something similar, here's the code:

$order = wc_get_order( $order_id );

$optional_fee_exists = false;

   $fee_counter = 0;

   foreach ( $order->get_fees() as $item_fee ) {

       $fee_counter++;

       $fee_name = $item_fee->get_name();

       if ( $fee_name == 'Optional Fee' ) {

           $optional_fee_exists = true;

       }
   }

if ( $optional_fee_exists ) {

   //do stuff;

}


来源: stackexchange

问:
What event should i use to check when an input box loses focus in jquery
I have a function that is executed when a textbox gains focus and another function when it loses focus. problem is i dont know where to attach the function for the lost focus event. For the focus i am using</p>

```<code> $(" :input[class='Txtbox']").focus(function(){
        $(this).val("");

    });
</code>```

答: Use the blur() event. See http://api.jquery.com/blur/

ContentLicense: CC BY-SA 3.0

Body:
I have a function that is executed when a textbox gains focus and another function when it loses focus. problem is i dont know where to attach the function for the lost focus event. For the focus i am using

 $(" :input[class='Txtbox']").focus(function(){
        $(this).val("");

    });


问:
How do I add data into html table using jquery?
I'm trying to add data from my firebase realtime database into a html table using jquery and javascript. I'm new to jquery, so I more or less have no idea what I'm doing.
I can retrieve the data but I can't add it to the table on the html page.
Is something wrong with this line?:

```<code>$("#table_body tbody").append("<tr><td>" + name.Name + "</td><td>" +
user.Email +  "</td></td></td></tr>");
</code>```

the table_body is just the table's id. The table remains empty.
pls help

答:
Is this code running on load? Is this code wrapper in:

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

The document must be loaded before jQuery code can run properly, the function above ensures jQuery inside of it runs after the DOM has loaded

Example:

```<code>$(document).ready(function() {
  let arr = [{n:'test', e:'ing'}, {n:'stuff', e:'ok'}];
  for(let i = 0; i < arr.length; i++) {
    $("#table_body tbody").append("<tr><td>" + arr[i].n + "</td><td>" + arr[i].e +  "</td></tr>");
  }
});
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to add data from my firebase realtime database into a html table using jquery and javascript. I'm new to jquery, so I more or less have no idea what I'm doing.
I can retrieve the data but I can't add it to the table on the html page.
Is something wrong with this line?:

$("#table_body tbody").append("
" + name.Name + "	" +
user.Email +  "
");

the table_body is just the table's id. The table remains empty.
pls help

Body:
Is this code running on load? Is this code wrapper in:

$(document).ready(function(){});

The document must be loaded before jQuery code can run properly, the function above ensures jQuery inside of it runs after the DOM has loaded

Example:

$(document).ready(function() {
  let arr = [{n:'test', e:'ing'}, {n:'stuff', e:'ok'}];
  for(let i = 0; i < arr.length; i++) {
    $("#table_body tbody").append("<tr><td>" + arr[i].n + "</td><td>" + arr[i].e +  "</td></tr>");
  }
});


问:
Adding percentage to number in SQL
I would like to add a percentage sign after a number in SQL.

This is the query I have

```<code>select cast(vetted as float)/cast(account_create as float)*100 from numbers
</code>```

I have tried using the format function to change the integer to a string and concatenate the percentage sign, but this doesn't seem to work

答:
You can use the following solution using CONCAT:

```<code>SELECT CONCAT(CAST(vetted AS FLOAT) / CAST(account_create AS FLOAT) * 100, '%')
FROM numbers
</code>```

Title: Adding percentage to number in SQL

Body:
I would like to add a percentage sign after a number in SQL.

This is the query I have

select cast(vetted as float)/cast(account_create as float)*100 from numbers

I have tried using the format function to change the integer to a string and concatenate the percentage sign, but this doesn't seem to work

Body:
You can use the following solution using CONCAT:

SELECT CONCAT(CAST(vetted AS FLOAT) / CAST(account_create AS FLOAT) * 100, '%')
FROM numbers


问:
JSON to XML with @ character in json key
I have the following json which I want to convert to XML.

```<code>{
   "@test": "value"
}
</code>```

How do I convert this to XML hadeling the @ correctly? Is this even possible?

答:
It is doable as per this.

```<code>String json = "{ \"@test\":\"value\" }";

ObjectMapper objectMapper = new ObjectMapper();
ObjectMapper xmlMapper = new XmlMapper();
JsonNode tree = objectMapper.readTree(json);
String jsonAsXml = xmlMapper.writer().withRootName("RootTagName").writeValueAsString(tree);
System.out.println(jsonAsXml);
</code>```

Pom file:

```<code><dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.7</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.9.7</version>
</dependency>
</code>```

Output:

```<code><RootTagName><@test>value</@test></RootTagName>
</code>```

The @ is being preserved in the xml tag name.

Body:
I have the following json which I want to convert to XML.

{
   "@test": "value"
}

How do I convert this to XML hadeling the @ correctly? Is this even possible?

Body:
It is doable as per this.

String json = "{ \"@test\":\"value\" }";

ObjectMapper objectMapper = new ObjectMapper();
ObjectMapper xmlMapper = new XmlMapper();
JsonNode tree = objectMapper.readTree(json);
String jsonAsXml = xmlMapper.writer().withRootName("RootTagName").writeValueAsString(tree);
System.out.println(jsonAsXml);

Pom file:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.7</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.9.7</version>
</dependency>

Output:

<RootTagName><@test>value</@test></RootTagName>

The @ is being preserved in the xml tag name.


问:
grep for a particular text with special character
I am trying to grep a particular text in a log file but I am not able to get the particular text that I am interested

```<code>echo "[27 May 2019 23:42:32,418] [Accept-Nsh-Proxy-Thread] [ERROR] [::] [Appserver] Too many open files (Accept failed)" >> sl3737474646464-config_console.log | tail -f sl3737474646464-config_console.log
</code>```

```<code>cat sl3737474646464-config_console.log | grep -i "\[Appserver\] Too many open files \(Accept failed\)"
</code>```

But not able to get the string

How to get that text that I echoed?

答:
grep takes the \( as the beginning of the capture group. Just drop the \ from ( and ).

```<code>$ echo "[27 May 2019 23:42:32,418] [Accept-Nsh-Proxy-Thread] [ERROR] [::] [Appserver] Too many open files (Accept failed)" | grep -i "\[Appserver\] Too many open files (Accept failed)"
[27 May 2019 23:42:32,418] [Accept-Nsh-Proxy-Thread] [ERROR] [::] [Appserver] Too many open files (Accept failed)
</code>```

Or use grep -F switch. It causes grep to parse the argument literally, so you can forget about escaping:

```<code>$ echo "[27 May 2019 23:42:32,418] [Accept-Nsh-Proxy-Thread] [ERROR] [::] [Appserver] Too many open files (Accept failed)" | grep -i -F "[Appserver] Too many open files (Accept failed)"
[27 May 2019 23:42:32,418] [Accept-Nsh-Proxy-Thread] [ERROR] [::] [Appserver] Too many open files (Accept failed)
</code>```

Body:
I am trying to grep a particular text in a log file but I am not able to get the particular text that I am interested

echo "[27 May 2019 23:42:32,418] [Accept-Nsh-Proxy-Thread] [ERROR] [::] [Appserver] Too many open files (Accept failed)" >> sl3737474646464-config_console.log | tail -f sl3737474646464-config_console.log

cat sl3737474646464-config_console.log | grep -i "\[Appserver\] Too many open files \(Accept failed\)"

But not able to get the string

How to get that text that I echoed?

Body:
grep takes the \( as the beginning of the capture group. Just drop the \ from ( and ).

$ echo "[27 May 2019 23:42:32,418] [Accept-Nsh-Proxy-Thread] [ERROR] [::] [Appserver] Too many open files (Accept failed)" | grep -i "\[Appserver\] Too many open files (Accept failed)"
[27 May 2019 23:42:32,418] [Accept-Nsh-Proxy-Thread] [ERROR] [::] [Appserver] Too many open files (Accept failed)

Or use grep -F switch. It causes grep to parse the argument literally, so you can forget about escaping:

$ echo "[27 May 2019 23:42:32,418] [Accept-Nsh-Proxy-Thread] [ERROR] [::] [Appserver] Too many open files (Accept failed)" | grep -i -F "[Appserver] Too many open files (Accept failed)"
[27 May 2019 23:42:32,418] [Accept-Nsh-Proxy-Thread] [ERROR] [::] [Appserver] Too many open files (Accept failed)


问:
concatenate columns based on blank columns
I am having three columns,- and / should be used as separator  result should come in new column(File Index-sub Index/Year),if sub index is blank then result should be (File Index/Year).</p>

```<code>  SELECT
[ File Index].[File Index]
, [ File Index].[Sub Index]
, [ File Index].[Financial Year]
, [ File Index].[File Index] & [Sub Index] & [Financial Year] AS [Composite Index]
  FROM [File Index];
</code>```

答:
Since you have both MySQL and MS Access listed, here are solutions for both.

For MySQL, you can use a CASE statement for this:

```<code>SELECT [File Index], [Sub Index], [Financial Year],
       CASE WHEN [Sub Index] IS NOT NULL
             THEN Concat([File Index], '-', [Sub Index], '/', [Financial Year])
             ELSE Concat([File Index], '/', [Financial Year])
       END as [Composite Index]
FROM [File Index];
</code>```

For MS Access, you will use Switch(...):

```<code>SELECT [File Index], [Sub Index], [Financial Year],
       Switch(Not IsNull([Sub Index]),
                 [File Index] & '-' & [Sub Index] & '/' & [Financial Year],
              IsNull([Sub Index]),
                 [File Index] & '/' & [Financial Year]
       ) as [Composite Index]
FROM [File Index];
</code>```

Body:
I am having three columns,- and / should be used as separator  result should come in new column(File Index-sub Index/Year),if sub index is blank then result should be (File Index/Year).

  SELECT
[ File Index].[File Index]
, [ File Index].[Sub Index]
, [ File Index].[Financial Year]
, [ File Index].[File Index] & [Sub Index] & [Financial Year] AS [Composite Index]
  FROM [File Index];

Body:
Since you have both MySQL and MS Access listed, here are solutions for both.

For MySQL, you can use a CASE statement for this:

SELECT [File Index], [Sub Index], [Financial Year],
       CASE WHEN [Sub Index] IS NOT NULL
             THEN Concat([File Index], '-', [Sub Index], '/', [Financial Year])
             ELSE Concat([File Index], '/', [Financial Year])
       END as [Composite Index]
FROM [File Index];

For MS Access, you will use Switch(...):

SELECT [File Index], [Sub Index], [Financial Year],
       Switch(Not IsNull([Sub Index]),
                 [File Index] & '-' & [Sub Index] & '/' & [Financial Year],
              IsNull([Sub Index]),
                 [File Index] & '/' & [Financial Year]
       ) as [Composite Index]
FROM [File Index];


问:
Ionic 4 read SMS plugin for OTP Verification
I am developing the ionic4 app, to auto verification or whenever I will get SMS my app has to read that message. for this I used 'Cordova plugin add Cordova-plugin-SMS' but it is not working. i declared 'declare var window: any; and declare var SMS: any;' nothing has worked. it showing "java.lang.ClassNotFoundException: com.rjfun.cordova.sms.SMSPlugin" in Android, in the web while developing it showing " TypeError: Cannot read property 'listSMS' of undefined". can any one help me to solve this issue </p>

答:
very nice question ... you need to use cordova plugin for that. Below are the

First you need to install Android Permission Ionic Native Plugin.
run these two commands first to install Android Permission Plugin.

```<code>ionic cordova plugin add cordova-plugin-android-permissions
npm install @ionic-native/android-permissions
</code>```

Add android-permissions to your app's Module.

```<code>import { AndroidPermissions} from '@ionic-native/android-permissions';

@NgModule({

  providers: [

    AndroidPermissions

  ]

})
export class AppModule { }
</code>```

Check permissions on page

```<code>import { AndroidPermissions } from '@ionic-native/android-permissions';

export class HomePage {
constructor(public androidPermissions: AndroidPermissions) { }

ionViewWillEnter()
{

this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.READ_SMS).then(
  success => console.log('Permission granted'),
err => this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.READ_SMS)
);

this.androidPermissions.requestPermissions([this.androidPermissions.PERMISSION.READ_SMS]);
}
}
</code>```

After allowing Read SMS permission now you need to install cordova-plugin-sms. Run this command for install it.

```<code>ionic cordova plugin add cordova-sms-plugin

npm install @ionic-native/sms
</code>```

and in your page while reading SMS -

place this in top before declare class

```<code>declare var SMS:any;
</code>```

place below inside class

```<code>ionViewDidEnter()
    {

    this.platform.ready().then((readySource) => {
    if(SMS) SMS.startWatch(()=>{
               console.log('watching started');
            }, Error=>{
           console.log('failed to start watching');
       });

      document.addEventListener('onSMSArrive', (e:any)=>{
           var sms = e.data;
           console.log(sms);

           });

        });
    }
</code>```

Body:
very nice question ... you need to use cordova plugin for that. Below are the

First you need to install Android Permission Ionic Native Plugin.
run these two commands first to install Android Permission Plugin.

ionic cordova plugin add cordova-plugin-android-permissions
npm install @ionic-native/android-permissions

Add android-permissions to your app's Module.

import { AndroidPermissions} from '@ionic-native/android-permissions';

@NgModule({

  providers: [

    AndroidPermissions

  ]

})
export class AppModule { }

Check permissions on page

import { AndroidPermissions } from '@ionic-native/android-permissions';

export class HomePage {
constructor(public androidPermissions: AndroidPermissions) { }

ionViewWillEnter()
{

this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.READ_SMS).then(
  success => console.log('Permission granted'),
err => this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.READ_SMS)
);

this.androidPermissions.requestPermissions([this.androidPermissions.PERMISSION.READ_SMS]);
}
}

After allowing Read SMS permission now you need to install cordova-plugin-sms. Run this command for install it.

ionic cordova plugin add cordova-sms-plugin

npm install @ionic-native/sms

and in your page while reading SMS -

place this in top before declare class

declare var SMS:any;

place below inside class

ionViewDidEnter()
    {

    this.platform.ready().then((readySource) => {
    if(SMS) SMS.startWatch(()=>{
               console.log('watching started');
            }, Error=>{
           console.log('failed to start watching');
       });

      document.addEventListener('onSMSArrive', (e:any)=>{
           var sms = e.data;
           console.log(sms);

           });

        });
    }


问:
how foldr works on this data tree?
I know how foldr works on Leaf, but I don't know how foldr work on Node. What is the parameter \x z' if we already have f and z as parameter. assume we have

```<code>tree = Node [Leaf 1, Leaf 2, Node [Leaf 1, Leaf 3]]
</code>```

how this code works

```<code>foldr (+) 0 tree
</code>```

```<code>data RoseTree a =  Leaf a | Node [RoseTree a]
instance Foldable RoseTree where
    foldr f z (Leaf x) = f x z
    foldr f z (Node ns) =
        foldr (\x z' -> foldr f z' x) z ns
</code>```

答:
We can discuss the implementation with your given sample data:

```<code>foldr (+) 0 (Node [Leaf 1, Leaf 2, Node [Leaf 1, Leaf 3]])
</code>```

We here thus have a Node, so we take the second clause so we replace this with:

```<code>foldr (\x z' -> foldr (+) z' x) 0 [Leaf 1, Leaf 2, Node [Leaf 1, Leaf 3]]
</code>```

The outer foldr thus works on the list, which means that, by the documentation:

```<code>foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...)
</code>```

So that means that the above foldr is replaced with:

```<code>foldr (+) (foldr (+) (foldr (+) 0 (Node [Leaf 1, Leaf 3])) (Leaf 2)) (Leaf 1)
</code>```

So the outer function is now foldr (+) (...) (Leaf 1), this is the first clause of our foldr definition, so that is equal to:

```<code>(+) 1 (foldr (+) (foldr (+) 0 (Node [Leaf 1, Leaf 3])) (Leaf 2))
</code>```

We then can evalate the foldr (+) (...) (Leaf 2) expression, which is handled in the same way:

```<code>(+) 1 ((+) 2 (foldr (+) 0 (Node [Leaf 1, Leaf 3])))
</code>```

or less verbose:

```<code>1 + 2 + foldr (+) 0 (Node [Leaf 1, Leaf 3])
</code>```

Then finally we again have a foldr (+) 0 that works on a Node, this thus again results in an evaluation as discussed above:

```<code>1 + 2 + foldr (+) (foldr (+) 0 (Leaf 3)) (Leaf 1)
</code>```

We thus can again evaluate the outer foldr (+) to:

```<code>1 + 2 + (+) 1 (foldr (+) 0 (Leaf 3))
</code>```

and the inner foldr (+) to:

```<code>1 + 2 + (+) 1 ((+) 3 0)
</code>```

or less verbose:

```<code>foldr (\x z' -> foldr (+) z' x) 0 [Leaf 1, Leaf 2, Node [Leaf 1, Leaf 3]]
</code>```0

which is equivalent to:

```<code>foldr (\x z' -> foldr (+) z' x) 0 [Leaf 1, Leaf 2, Node [Leaf 1, Leaf 3]]
</code>```1

which is the sum of the nodes in the Leafs.

It is important to note that the outer foldr (here denoted in italics), is not the same foldr function as the inner foldr (here denoted in boldface) in the implementation: the outer one works with a list as functor, whereas the inner one is the one we define in the instance Foldable RoseTree:

```<code>foldr (\x z' -> foldr (+) z' x) 0 [Leaf 1, Leaf 2, Node [Leaf 1, Leaf 3]]
</code>```2

In case we thus perform a foldr on a Tree with a function f and an initial value z, we will replace all leaves with f x z, (so for foldr (+) 0 that is (+) x 0, or x + 0).

The Nodes will result in folding the values together where the result of the fold of the tailing elements is used as initial value of the fold with the head element.

Title: how foldr works on this data tree?

Body:
I know how foldr works on Leaf, but I don't know how foldr work on Node. What is the parameter \x z' if we already have f and z as parameter. assume we have

tree = Node [Leaf 1, Leaf 2, Node [Leaf 1, Leaf 3]]

how this code works

foldr (+) 0 tree

data RoseTree a =  Leaf a | Node [RoseTree a]
instance Foldable RoseTree where
    foldr f z (Leaf x) = f x z
    foldr f z (Node ns) =
        foldr (\x z' -> foldr f z' x) z ns

Body:
We can discuss the implementation with your given sample data:

foldr (+) 0 (Node [Leaf 1, Leaf 2, Node [Leaf 1, Leaf 3]])

We here thus have a Node, so we take the second clause so we replace this with:

foldr (\x z' -> foldr (+) z' x) 0 [Leaf 1, Leaf 2, Node [Leaf 1, Leaf 3]]

The outer foldr thus works on the list, which means that, by the documentation:

foldr f z [x1, x2, ..., xn] == x1 `f` (x2 `f` ... (xn `f` z)...)

So that means that the above foldr is replaced with:

foldr (+) (foldr (+) (foldr (+) 0 (Node [Leaf 1, Leaf 3])) (Leaf 2)) (Leaf 1)

So the outer function is now foldr (+) (...) (Leaf 1), this is the first clause of our foldr definition, so that is equal to:

(+) 1 (foldr (+) (foldr (+) 0 (Node [Leaf 1, Leaf 3])) (Leaf 2))

We then can evalate the foldr (+) (...) (Leaf 2) expression, which is handled in the same way:

(+) 1 ((+) 2 (foldr (+) 0 (Node [Leaf 1, Leaf 3])))

or less verbose:

1 + 2 + foldr (+) 0 (Node [Leaf 1, Leaf 3])

Then finally we again have a foldr (+) 0 that works on a Node, this thus again results in an evaluation as discussed above:

1 + 2 + foldr (+) (foldr (+) 0 (Leaf 3)) (Leaf 1)

We thus can again evaluate the outer foldr (+) to:

1 + 2 + (+) 1 (foldr (+) 0 (Leaf 3))

and the inner foldr (+) to:

1 + 2 + (+) 1 ((+) 3 0)

or less verbose:

1 + 2 + 1 + 3 + 0

which is equivalent to:

7

which is the sum of the nodes in the Leafs.

It is important to note that the outer foldr (here denoted in italics), is not the same foldr function as the inner foldr (here denoted in boldface) in the implementation: the outer one works with a list as functor, whereas the inner one is the one we define in the instance Foldable RoseTree:

instance Foldable RoseTree where
    foldr f z (Leaf x) = f x z
    foldr f z (Node ns) = foldr (\x z' -> foldr f z' x) z ns

In case we thus perform a foldr on a Tree with a function f and an initial value z, we will replace all leaves with f x z, (so for foldr (+) 0 that is (+) x 0, or x + 0).

The Nodes will result in folding the values together where the result of the fold of the tailing elements is used as initial value of the fold with the head element.


答:
You can try following :  </p>

```<code>select CONCAT(cast(vetted as float)/cast(account_create as float)*100,'%') from numbers
</code>```

Title: Adding percentage to number in SQL

Body:
You can try following :

select CONCAT(cast(vetted as float)/cast(account_create as float)*100,'%') from numbers


问:
How to add pin in a specific area created using image map
I have an angular application in which I have created an image map using HTML usemap

code:

```<code>    <img src="../../assets/floor2.jpg" usemap="#floor2Map">
        <map name="floor2Map">
            <area shape="poly" coords="210,340,216,234,312,236,323,323,317,346" matTooltip="Info about the Device" >
            <div id='pin-1' class="box" >
            <div class="pin-text">
                <h4>My Device</h3>
             </div>
        </div>
        </map>

In CSS file

.box:hover > .pin-text {
    display: block;
  }

  .box {
    width:8%;
    height:8%;
    background-image:   url('http://www.clker.com/cliparts/W/0/g/a/W/E/map-pin-red.svg');
    background-position: top;
    background-repeat: no-repeat;
    background-size: contain;
    position: absolute;
  }

  .pin-text {
    position: absolute;
    top:50%;
    transform:translateY(-50%);
    left:75%;
    white-space:nowrap;
    display: none;
  }
</code>```

I want to add a pin on this particular area of image, and when I hover over it, then the tooltip should come. How to do that? Currently my svg icon is coming below the image.

svg for reference - http://www.clker.com/cliparts/W/0/g/a/W/E/map-pin-red.svg

答:
```<code>.box {
    top : 260px ;
    left : 210px;
    width:8%;
    height:8%;
    background-image:   url('http://www.clker.com/cliparts/W/0/g/a/W/E/map-pin-red.svg');
    background-position: top;
    background-repeat: no-repeat;
    background-size: contain;
    position: absolute;
  }
</code>```

Adding top and left positioning has solved the issue

Body:
I have an angular application in which I have created an image map using HTML usemap

code:

        <map name="floor2Map">
            <area shape="poly" coords="210,340,216,234,312,236,323,323,317,346" matTooltip="Info about the Device" >

My Device

        </map>

In CSS file

.box:hover > .pin-text {
    display: block;
  }

  .box {
    width:8%;
    height:8%;
    background-image:   url('http://www.clker.com/cliparts/W/0/g/a/W/E/map-pin-red.svg');
    background-position: top;
    background-repeat: no-repeat;
    background-size: contain;
    position: absolute;
  }

  .pin-text {
    position: absolute;
    top:50%;
    transform:translateY(-50%);
    left:75%;
    white-space:nowrap;
    display: none;
  }

I want to add a pin on this particular area of image, and when I hover over it, then the tooltip should come. How to do that? Currently my svg icon is coming below the image.

svg for reference - http://www.clker.com/cliparts/W/0/g/a/W/E/map-pin-red.svg

Body:
.box {
    top : 260px ;
    left : 210px;
    width:8%;
    height:8%;
    background-image:   url('http://www.clker.com/cliparts/W/0/g/a/W/E/map-pin-red.svg');
    background-position: top;
    background-repeat: no-repeat;
    background-size: contain;
    position: absolute;
  }

Adding top and left positioning has solved the issue


问:
How to dispose shared variable in VB.NET
How to dispose the shared variable in vb.net

i am using shared object of Asterisk.NET Manager Variable, i assigned it in form load
and i dispose it in main form closing, My problem is after closing the application, application.exe keeps live in task manager, if i not initializing the shared object in form load there is no problem,

My code in form open

```<code>  Public Shared WithEvents objManager As Asterisk.NET.Manager.ManagerConnection

  Public Shared Sub ConnectAsterisk()
    Try
        objManager = New Asterisk.NET.Manager.ManagerConnection(ELASTIX_IP_ADDRESS, ASTERISK_PORT, ASTERISK_USER_NAME, ASTERISK_PASSWORD)
        objManager.Login()
    Catch ex As Exception

    End Try
End Sub

 Private Sub frmMain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    AsteriskManager.objManager = Nothing
End Sub
</code>```

can any one please help to do that

Thanks,
Senthil

答:
If you dispose the resource in the Closing event, it will be disposed as soon as any form is closed. This may work for you but it’s conceptually wrong if your resource is Shared.

Either remove the Shared qualifier from the variable or implement the “static finalizer” idiom to remove dispose the resource at the end of the application lifetime:

```<code>' *In* frmMain.vb:

Private Shared Finalizer As New SharedFinalizer()

Private Class SharedFinalizer
    Protected Overrides Sub Finalize()
        MyBase.Finalize()
        objManager.Logoff()
    End Sub
End Class
</code>```

The SharedFinalizer.Finalize code will be run exactly once, at the end of the application domain lifetime.

Body:
How to dispose the shared variable in vb.net

i am using shared object of Asterisk.NET Manager Variable, i assigned it in form load
and i dispose it in main form closing, My problem is after closing the application, application.exe keeps live in task manager, if i not initializing the shared object in form load there is no problem,

My code in form open

  Public Shared WithEvents objManager As Asterisk.NET.Manager.ManagerConnection

  Public Shared Sub ConnectAsterisk()
    Try
        objManager = New Asterisk.NET.Manager.ManagerConnection(ELASTIX_IP_ADDRESS, ASTERISK_PORT, ASTERISK_USER_NAME, ASTERISK_PASSWORD)
        objManager.Login()
    Catch ex As Exception

    End Try
End Sub

 Private Sub frmMain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    AsteriskManager.objManager = Nothing
End Sub

can any one please help to do that

Thanks,
Senthil

Body:
If you dispose the resource in the Closing event, it will be disposed as soon as any form is closed. This may work for you but it’s conceptually wrong if your resource is Shared.

Either remove the Shared qualifier from the variable or implement the “static finalizer” idiom to remove dispose the resource at the end of the application lifetime:

' *In* frmMain.vb:

Private Shared Finalizer As New SharedFinalizer()

Private Class SharedFinalizer
    Protected Overrides Sub Finalize()
        MyBase.Finalize()
        objManager.Logoff()
    End Sub
End Class

The SharedFinalizer.Finalize code will be run exactly once, at the end of the application domain lifetime.


问:
How to fix empty insert in Database from reactjs frontend using php rest api?
Update! I manage to fix the problem with my input in the database, but now I have another problem. When I insert 1 element in my database, my submit methods create 2 rows, 1 empty and 1 with my values.

Post.php

```<code> public function addComment(){
    // Create query
    $query = 'INSERT INTO ' . $this->table2 . ' SET content = :content,
rating = :rating, doctor = :doctor';

    // Prepare statement
    $stmt = $this->conn->prepare($query);

    // Clean data
    $this->content = htmlspecialchars(strip_tags($this->content));
    $this->rating = htmlspecialchars(strip_tags($this->rating));
    $this->doctor = htmlspecialchars(strip_tags($this->doctor));

    // Bind data
    $stmt->bindParam(':content', $this->content);
    $stmt->bindParam(':rating', $this->rating);
    $stmt->bindParam(':doctor', $this->doctor);

    // Execute query
    if($stmt->execute()) {
        return true;
    }

    // Print error if something goes wrong
    printf("Error: %s.\n", $stmt->error);

    return false;

}
</code>```

Here I have the addComment function. All the variables are private $table2 = 'com';  public $content; public $rating;  public $doctor;

add_comment.php

```<code>   // Instantiate DB & connect
   $database = new Database();
   $db = $database->connect();

   // Instantiate blog post object
   $post = new Post($db);

   // Get raw posted data
   $data = json_decode(file_get_contents("php://input"));

   $post->content = $data->content;
   $post->rating = $data->rating;
   $post->doctor = $data->doctor;

   // Create post
   if($post->addComment()) {
    echo json_encode(
        array('message' => 'Post Created')
    );
   } else {
    echo json_encode(
        array('message' => 'Post Not Created')
    );
   }
</code>```

App.js

```<code>class App extends Component {

  constructor(props) {
super(props);
this.state = {

        content: '',
        rating: '',
        doctor: '',

  error:null
    }
  }

  handleFormSubmit = e => {
e.preventDefault();
    axios({
  method: 'post',
  url: 'http://localhost/fak/api/post/add_comment.php',
  headers: { 'content-type': 'application/json' },
  data: this.state,
})
    .then(result => {
        console.log(result.data)

    })
    .catch(error => this.setState({ error: error.message }));
  };

  render() {
return (
    <div className="App">
      <p>Add comment:</p>
      <div>
          <form action="#" >
          <label>Message</label>
          <textarea id="content" name="content" placeholder="Write something.."
                    onChange={e => this.setState({ content: e.target.value     })}
                    value={this.state.message}
          ></textarea>

          <input type="text" id="rating" name="rating" placeholder="Rating"
                 value={this.state.rating}
                 onChange={e => this.setState({ rating: e.target.value })}
          />

              <label>Rating</label>
          <label>Doctor name:</label>
          <input type="text" id="doctor" name="doctor" placeholder="Doctor name"
                 value={this.state.doctor}
                 onChange={e => this.setState({ doctor: e.target.value })}
          />

          <input type="submit" onClick={e => this.handleFormSubmit(e)} value="Submit" />
        </form >
      </div>
    </div>
    );
  }
}

 export default App;
</code>```

答:
The data keys that you set in the frontend are completely different from what you expect at the backend.

You need something like:

```<code>this.state = {
  content: '',
  rating: '',
  doctor: '',
  error:null
}

// You need to adapt it everywhere you use `this.state`
</code>```

Body:
Update! I manage to fix the problem with my input in the database, but now I have another problem. When I insert 1 element in my database, my submit methods create 2 rows, 1 empty and 1 with my values.

Post.php

 public function addComment(){
    // Create query
    $query = 'INSERT INTO ' . $this->table2 . ' SET content = :content,
rating = :rating, doctor = :doctor';

    // Prepare statement
    $stmt = $this->conn->prepare($query);

    // Clean data
    $this->content = htmlspecialchars(strip_tags($this->content));
    $this->rating = htmlspecialchars(strip_tags($this->rating));
    $this->doctor = htmlspecialchars(strip_tags($this->doctor));

    // Bind data
    $stmt->bindParam(':content', $this->content);
    $stmt->bindParam(':rating', $this->rating);
    $stmt->bindParam(':doctor', $this->doctor);

    // Execute query
    if($stmt->execute()) {
        return true;
    }

    // Print error if something goes wrong
    printf("Error: %s.\n", $stmt->error);

    return false;

}

Here I have the addComment function. All the variables are private $table2 = 'com';  public $content; public $rating;  public $doctor;

add_comment.php

   // Instantiate DB & connect
   $database = new Database();
   $db = $database->connect();

   // Instantiate blog post object
   $post = new Post($db);

   // Get raw posted data
   $data = json_decode(file_get_contents("php://input"));

   $post->content = $data->content;
   $post->rating = $data->rating;
   $post->doctor = $data->doctor;

   // Create post
   if($post->addComment()) {
    echo json_encode(
        array('message' => 'Post Created')
    );
   } else {
    echo json_encode(
        array('message' => 'Post Not Created')
    );
   }

App.js

class App extends Component {

  constructor(props) {
super(props);
this.state = {

        content: '',
        rating: '',
        doctor: '',

  error:null
    }
  }

  handleFormSubmit = e => {
e.preventDefault();
    axios({
  method: 'post',
  url: 'http://localhost/fak/api/post/add_comment.php',
  headers: { 'content-type': 'application/json' },
  data: this.state,
})
    .then(result => {
        console.log(result.data)

    })
    .catch(error => this.setState({ error: error.message }));
  };

  render() {
return (

Add comment:

          <form action="#" >
          Message
          <textarea id="content" name="content" placeholder="Write something.."
                    onChange={e => this.setState({ content: e.target.value     })}
                    value={this.state.message}
          ></textarea>

          <input type="text" id="rating" name="rating" placeholder="Rating"
                 value={this.state.rating}
                 onChange={e => this.setState({ rating: e.target.value })}
          />

              Rating
          Doctor name:
          <input type="text" id="doctor" name="doctor" placeholder="Doctor name"
                 value={this.state.doctor}
                 onChange={e => this.setState({ doctor: e.target.value })}
          />

          <input type="submit" onClick={e => this.handleFormSubmit(e)} value="Submit" />
        </form >

    );
  }
}

 export default App;

Body:
The data keys that you set in the frontend are completely different from what you expect at the backend.

You need something like:

this.state = {
  content: '',
  rating: '',
  doctor: '',
  error:null
}

// You need to adapt it everywhere you use `this.state`


问:
NoSuchElementException when using FindElementByAccessibilityId
I'm new to Appium but quite experienced with Selenium.

The first action, clicking on the Element 'Nieuw' is giving no problem, a screen with four choices appears.

After that I'm trying to click on an Element with accessibility id 'Proefitmanager'. In Appium desktop this is giving no problem but in my Appium test I'm getting a NoSuchElement exception. I'm using the Id which is suggested by Appium desktop and my code is comparable with the code generated by the recorder of Appium Desktop although I'm using C# instead of Java.

```<code>IWebElement nieuw = (IWebElement)driver.FindElementByXPath("(//android.view.View[@content-desc='Nieuw'])[2]");
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.ElementToBeClickable(nieuw));
nieuw.Click();

IWebElement proefrit = (IWebElement)driver.FindElementByAccessibilityId("Proefrit");
wait.Until(ExpectedConditions.ElementToBeClickable(proefrit));
proefrit.Click();
</code>```

My idea is that the element has no focus at the moment of clicking because it is in another frame or so. I tried to use SwitchTo().Frame(0) and Frame(1) but this is given exceptions like:

```<code>Could not proxy command to remote server. Original error: 404 - undefined`
</code>```

See image from Appium desktop to have an Idea what the app looks like.

答:
Firstly you need to switch from Native View to Web View before clicking on "Proefit" element.

Here is the sample code in Java:

```<code>   Set<String> contextNames = driver.getContextHandles();
   for (String contextName : contextNames) {
     System.out.println(contextName); //prints out something like NATIVE_APP or WEBVIEW_1
    }
   driver.context(contextNames.toArray()[1]); // set context to WEBVIEW_1
</code>```

Then Perform the click operation on the proefit element.

Here is the sample code in Java:

```<code>WebElement proefrit=driver.findElementByAccessibilityId("Proefrit");
wait.Until(ExpectedConditions.ElementToBeClickable(proefrit));
proefrit.click();
</code>```

3.Then switch back to Native Context to continue with the test.

```<code>driver.context("NATIVE_APP");
</code>```

Body:
I'm new to Appium but quite experienced with Selenium.

The first action, clicking on the Element 'Nieuw' is giving no problem, a screen with four choices appears.

After that I'm trying to click on an Element with accessibility id 'Proefitmanager'. In Appium desktop this is giving no problem but in my Appium test I'm getting a NoSuchElement exception. I'm using the Id which is suggested by Appium desktop and my code is comparable with the code generated by the recorder of Appium Desktop although I'm using C# instead of Java.

IWebElement nieuw = (IWebElement)driver.FindElementByXPath("(//android.view.View[@content-desc='Nieuw'])[2]");
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(ExpectedConditions.ElementToBeClickable(nieuw));
nieuw.Click();

IWebElement proefrit = (IWebElement)driver.FindElementByAccessibilityId("Proefrit");
wait.Until(ExpectedConditions.ElementToBeClickable(proefrit));
proefrit.Click();

My idea is that the element has no focus at the moment of clicking because it is in another frame or so. I tried to use SwitchTo().Frame(0) and Frame(1) but this is given exceptions like:

Could not proxy command to remote server. Original error: 404 - undefined`

See image from Appium desktop to have an Idea what the app looks like.

Body:
Firstly you need to switch from Native View to Web View before clicking on "Proefit" element.

Here is the sample code in Java:

   Set<String> contextNames = driver.getContextHandles();
   for (String contextName : contextNames) {
     System.out.println(contextName); //prints out something like NATIVE_APP or WEBVIEW_1
    }
   driver.context(contextNames.toArray()[1]); // set context to WEBVIEW_1

Then Perform the click operation on the proefit element.

Here is the sample code in Java:

WebElement proefrit=driver.findElementByAccessibilityId("Proefrit");
wait.Until(ExpectedConditions.ElementToBeClickable(proefrit));
proefrit.click();

3.Then switch back to Native Context to continue with the test.

driver.context("NATIVE_APP");


问:
How to make checkboxes readonly using multipledropdown.js in Angular.js
I need to readonly all checkboxes using Angular.js multipledropdown.js. My code is below:

```<code><div class="col-md-6" ng-show="sub_sub_menu">
<div class="input-group bmargindiv1 col-md-12">
<span class="input-group-addon ndrftextwidth text-right oditek-form" style="width:180px">Sub Sub Menu:</span>
<div ng-dropdown-multiselect="" options="example17data" selected-model="example17model" checkboxes="true" extra-settings="example17settings" class="form-control oditek-form" disabled=true></div>
    </div>
</div>

var url3='../service/admin/user/group.php';
        var method3='POST';
        var data3=$.param({'action':'getAllSubSubMenuData','sub_id':$scope.smenu.value,'id':$scope.mmenu.value});
        $scope.example17data=[];
        DataService.connectToServerSideScript(method3,url3,data3)
        .then(function(response) {
            //console.log('state',response);
            if (response.length >0) {
                angular.forEach(response,function(obj){
                    var cdata={'label':obj.menu,'id':obj.id};
                    $scope.example17data.push(cdata);
                })
                angular.forEach(response,function(obj){
                    var data1={'id':parseInt(obj.id)};
                    $scope.example17model.push(data1);
                })
                $scope.sub_menu=true;
                $scope.sub_sub_menu=true;
            }else{
                $scope.sub_menu=true;
                $scope.sub_sub_menu=false;
            }
        },function(error) {

        })
</code>```

Here I am using multiple dropdown checkbox list and all check boxes are checked by default. Here I need to readonly all checkboxes so that it can not be changed.

答:
To make them read only you will have to disable the options. To disable them you need to add disabled property to your object. Try the following please</p>

```<code>var cdata={'label':obj.menu,'id':obj.id,disabled: true};
</code>```

Body:
I need to readonly all checkboxes using Angular.js multipledropdown.js. My code is below:

Sub Sub Menu:

var url3='../service/admin/user/group.php';
        var method3='POST';
        var data3=$.param({'action':'getAllSubSubMenuData','sub_id':$scope.smenu.value,'id':$scope.mmenu.value});
        $scope.example17data=[];
        DataService.connectToServerSideScript(method3,url3,data3)
        .then(function(response) {
            //console.log('state',response);
            if (response.length >0) {
                angular.forEach(response,function(obj){
                    var cdata={'label':obj.menu,'id':obj.id};
                    $scope.example17data.push(cdata);
                })
                angular.forEach(response,function(obj){
                    var data1={'id':parseInt(obj.id)};
                    $scope.example17model.push(data1);
                })
                $scope.sub_menu=true;
                $scope.sub_sub_menu=true;
            }else{
                $scope.sub_menu=true;
                $scope.sub_sub_menu=false;
            }
        },function(error) {

        })

Here I am using multiple dropdown checkbox list and all check boxes are checked by default. Here I need to readonly all checkboxes so that it can not be changed.

Body:
To make them read only you will have to disable the options. To disable them you need to add disabled property to your object. Try the following please

var cdata={'label':obj.menu,'id':obj.id,disabled: true};


答:
Use blur event.

```<code>$(" :input[class='Txtbox']").blur(function(){
    //do something
});
</code>```

Title: What event should i use to check when an input box loses focus in jquery

Body:
I have a function that is executed when a textbox gains focus and another function when it loses focus. problem is i dont know where to attach the function for the lost focus event. For the focus i am using

 $(" :input[class='Txtbox']").focus(function(){
        $(this).val("");

    });

Body:
Use blur event.

$(" :input[class='Txtbox']").blur(function(){
    //do something
});


问:
Spark scala with dependencies in one single jar
I have a Scala Spark application for which I want to create jar with dependencies using maven.

I am using maven-assembly-plugin

```<code><plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
</code>```

but when I am running my app with Spark-submit command, I am still getting java.lang.NoClassDefFoundError. When I am running it with --jars option and provide path for dependencies jar, It is running fine. Please let me know if I am missing something. Thanks

答:
The configuration looks good.
Try to delete previous application jars and run ‘mvn package’ command to create a new one.

Body:
I have a Scala Spark application for which I want to create jar with dependencies using maven.

I am using maven-assembly-plugin

<plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <version>2.4</version>
                <configuration>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>single</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

but when I am running my app with Spark-submit command, I am still getting java.lang.NoClassDefFoundError. When I am running it with --jars option and provide path for dependencies jar, It is running fine. Please let me know if I am missing something. Thanks


问:
customizing bootstrap form-control on select option
I'm using bootstrap's form-control class to keep a consistent style between my form input and those that requires a select option. However using bootstrap's form-control on select elements gives it the ugly drop-down button in firefox.

What I'd like to achieve is this

However looking through the css part I have no way of identifying which part it is that I should override as there does not seem to be a css specifying the drop-down arrow's decoration.

This is how the current code looks like

```<code><div class="form-group row">
    <label for="industry" class="">Industry :</label>
    <select name="industry" class="form-control">
        <option value="" disabled selected>Select Industry</option>
        <option value="financial-service">Financial Services</option>
        <option value="healthcare-lifescience">Healthcare & Life Science</option>
        <option value="communications">Communications</option>
    </select>
</div>
</code>```

答:
Check My Pen for you. It is 100% working in chrome, firefox, edge and safari

check this codepen

select.customDropdown::-ms-expand {
    display: none;
}

select.customDropdown {
    outline : none;
    overflow : hidden;
    text-indent : 0.01px;
    text-overflow : '';

    background : url("https://img.icons8.com/material/24/000000/sort-down.png") no-repeat right #fff;

    -webkit-appearance: none;
       -moz-appearance: none;
        -ms-appearance: none;
         -o-appearance: none;
            appearance: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css">

<div class="jumbotron container">
  <div class="row">
  <div class="col-md-6 offset-md-3">
<div class="form-group row">
    <label for="industry" class="">Industry :</label>
    <select name="industry" class="form-control customDropdown">
        <option value="" disabled selected>Select Industry</option>
        <option value="financial-service">Financial Services</option>
        <option value="healthcare-lifescience">Healthcare & Life Science</option>
        <option value="communications">Communications</option>
    </select>
</div>
  </div>
  </div>
  </div>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.js"></script></code>```

Body:
I'm using bootstrap's form-control class to keep a consistent style between my form input and those that requires a select option. However using bootstrap's form-control on select elements gives it the ugly drop-down button in firefox.

What I'd like to achieve is this

However looking through the css part I have no way of identifying which part it is that I should override as there does not seem to be a css specifying the drop-down arrow's decoration.

This is how the current code looks like

    Industry :
    <select name="industry" class="form-control">
        <option value="" disabled selected>Select Industry</option>
        <option value="financial-service">Financial Services</option>
        <option value="healthcare-lifescience">Healthcare & Life Science</option>
        <option value="communications">Communications</option>
    </select>

Body:
Check My Pen for you. It is 100% working in chrome, firefox, edge and safari

check this codepen

select.customDropdown::-ms-expand {
    display: none;
}

select.customDropdown {
    outline : none;
    overflow : hidden;
    text-indent : 0.01px;
    text-overflow : '';

    background : url("https://img.icons8.com/material/24/000000/sort-down.png") no-repeat right #fff;

    -webkit-appearance: none;
       -moz-appearance: none;
        -ms-appearance: none;
         -o-appearance: none;
            appearance: none;
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css">

<div class="jumbotron container">
  <div class="row">
  <div class="col-md-6 offset-md-3">
<div class="form-group row">
    <label for="industry" class="">Industry :</label>
    <select name="industry" class="form-control customDropdown">
        <option value="" disabled selected>Select Industry</option>
        <option value="financial-service">Financial Services</option>
        <option value="healthcare-lifescience">Healthcare & Life Science</option>
        <option value="communications">Communications</option>
    </select>
</div>
  </div>
  </div>
  </div>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.js"></script>


问:
Cloudera CDH 5.13 - is it possible to run spark 2.x with Yarn mode?
Team,

Installed CDH 5.13 version on my local computer and doing upgrade from spark 1.6 to spark 2.0. is it possible to do run spark application using yarn mode. Please confirm .  or it will work as standalone mode.

答: YARN supports stand alone mode and cluster mode. I have used both of them and they work fine on Cloudera 5.11 + Spark2 setup.</p>


问:
Worksheet change event with multiple selections
I have a sheet that i keep a log of the changes that happen on it such as data entered into a cell or data deleted etc. This works great except for when multiple selections happen.

For example if i select B2 and D2 and F2 and deleted the contents of the cells the worksheet change event will only pick up the change for the first cell, B2. So i have no idea what happened to the other cells.

Is there a way i can get around this and either get it to log the worksheet change for the other cells or stop multiple selection deletes happening ?

Here is my code

```<code>Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As

Range)

Dim ws As Worksheet, iRow As Long, iCol As Long, Message As String, SheetId As String, iRowE As Long, iColE As Long, iRowB As Long, iColB As Long

Set ws = Sh
SheetId = Replace(ws.Name, " ", "")
SheetId = Left(SheetId, 2) & Right(SheetId, 2)

iRowB = Target.Row
iColB = Target.Column
iRowE = iRowB + Target.Rows.Count - 1
iColE = iColB + Target.Columns.Count - 1

Message = Format(Now(), "ddHHmmss") & Application.UserName & "-" & SheetId

For iRow = iRowB To iRowE
  For iCol = iColB To iColE
    Message = Message & "|" & Format(iRow, " 0") & Format(iCol, " 0") & "|" & CStr(ws.Cells(iRow, iCol).Text)
  Next iCol
Next iRow

If Not FileExists("L:\HC\" & ThisWorkbook.Name & Format(Now(), "YYYYMM") & ".Log") Then
  Call LogIt("L:\HC\" & ThisWorkbook.Name & Format(Now(), "YYYYMM") & ".Log", "ddHHmmssUSER-sheet|row col|value|row col|value")
End If

Call LogIt("L:\HC\" & ThisWorkbook.Name & Format(Now(), "YYYYMM") & ".Log", Message)

End Sub
</code>```

答:
Rather than looping through the rows and columns as such, you can loop through each cell that was changed.  "Target" is a range and can be specified as more than 1 cell if that's what was changed in the process.

```<code>Dim objCell As Range

For Each objCell in Target
    ' Do Something
Next
</code>```

I can see you've attempted to do something like that but using the cell approach should give you each individual address that has changed.

Be careful though, mass amount of changes may cause some serious
  performance issues for a single hit.

I hope that helps.

Body:
I have a sheet that i keep a log of the changes that happen on it such as data entered into a cell or data deleted etc. This works great except for when multiple selections happen.

For example if i select B2 and D2 and F2 and deleted the contents of the cells the worksheet change event will only pick up the change for the first cell, B2. So i have no idea what happened to the other cells.

Is there a way i can get around this and either get it to log the worksheet change for the other cells or stop multiple selection deletes happening ?

Here is my code

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As

Range)

Dim ws As Worksheet, iRow As Long, iCol As Long, Message As String, SheetId As String, iRowE As Long, iColE As Long, iRowB As Long, iColB As Long

Set ws = Sh
SheetId = Replace(ws.Name, " ", "")
SheetId = Left(SheetId, 2) & Right(SheetId, 2)

iRowB = Target.Row
iColB = Target.Column
iRowE = iRowB + Target.Rows.Count - 1
iColE = iColB + Target.Columns.Count - 1

Message = Format(Now(), "ddHHmmss") & Application.UserName & "-" & SheetId

For iRow = iRowB To iRowE
  For iCol = iColB To iColE
    Message = Message & "|" & Format(iRow, " 0") & Format(iCol, " 0") & "|" & CStr(ws.Cells(iRow, iCol).Text)
  Next iCol
Next iRow

If Not FileExists("L:\HC\" & ThisWorkbook.Name & Format(Now(), "YYYYMM") & ".Log") Then
  Call LogIt("L:\HC\" & ThisWorkbook.Name & Format(Now(), "YYYYMM") & ".Log", "ddHHmmssUSER-sheet|row col|value|row col|value")
End If

Call LogIt("L:\HC\" & ThisWorkbook.Name & Format(Now(), "YYYYMM") & ".Log", Message)

End Sub

Body:
Rather than looping through the rows and columns as such, you can loop through each cell that was changed.  "Target" is a range and can be specified as more than 1 cell if that's what was changed in the process.

Dim objCell As Range

For Each objCell in Target
    ' Do Something
Next

I can see you've attempted to do something like that but using the cell approach should give you each individual address that has changed.

Be careful though, mass amount of changes may cause some serious
  performance issues for a single hit.

I hope that helps.


问:
How to insert an "if" formula in my code?
I have a section on my website to display a live price estimates based on a value inputted. I just have have one final bit of formula to add but I'm unsure how to modify the code, I need to introduce a minimum for the variable part of the price (5% of the inputted value or 2, whichever is greater. For example:

If(curValFloat * 0.05 > 2, curValFloat * 0.05, 2) + 4

Here's the code that's in use now:

```<code>var elDeliveryPrice = document.getElementById('deliveryPrice');
var elOrderValue = document.getElementById('orderValue');
var formatter = new Intl.NumberFormat('gb-GB', { style: 'currency', currency: 'GBP' });

elOrderValue.addEventListener('keyup', _ => {
  let curVal = elOrderValue.value;

  let curValFloat = parseFloat(curVal);
  if (isNaN(curValFloat)) {
    elDeliveryPrice.innerHTML = '';
    return;
  }

  elDeliveryPrice.innerHTML = formatter.format((curValFloat * 0.05) + 4);
});
</code>```

答:
Posting this as an answer since stuff in comments gets lost sometimes.

You can use Math#max, which returns the maximum of numbers passed to it.

```<code>Math.max(curValFloat * 0.05, 2)
</code>```

Body:
I have a section on my website to display a live price estimates based on a value inputted. I just have have one final bit of formula to add but I'm unsure how to modify the code, I need to introduce a minimum for the variable part of the price (5% of the inputted value or 2, whichever is greater. For example:

If(curValFloat * 0.05 > 2, curValFloat * 0.05, 2) + 4

Here's the code that's in use now:

var elDeliveryPrice = document.getElementById('deliveryPrice');
var elOrderValue = document.getElementById('orderValue');
var formatter = new Intl.NumberFormat('gb-GB', { style: 'currency', currency: 'GBP' });

elOrderValue.addEventListener('keyup', _ => {
  let curVal = elOrderValue.value;

  let curValFloat = parseFloat(curVal);
  if (isNaN(curValFloat)) {
    elDeliveryPrice.innerHTML = '';
    return;
  }

  elDeliveryPrice.innerHTML = formatter.format((curValFloat * 0.05) + 4);
});

Body:
Posting this as an answer since stuff in comments gets lost sometimes.

You can use Math#max, which returns the maximum of numbers passed to it.

Math.max(curValFloat * 0.05, 2)


问:
information from a range using a loop best practice for combo box
I wanted to take information from a range and add it to a userform in a combobox.

The below code did that for me with success, but in the combo box I set a range of 40 rows, so it has my values and then after my last value it has an empty space of around 20 lines which I put there in case the user adds more cost centres.

How can the combobox select the exact rows and then recognise, if a new cost centre is added later?

"rules" is the worksheet I get information from, "Cost Centres" is the name of a range I built on that worksheet which has 40 rows.

What is best practice that more than 40 cost centres get added, that I'll never need to go back into the code to change the range?

```<code>Private Sub UserForm_Initialize()

    Worksheets("Rules").Activate

    Dim rangeCount As Integer
    Dim Range As Range
    Dim i As Integer

    Set Range = ActiveSheet.Range("A2")
    rangeCount = ActiveSheet.Range("CostCentres").Count
    i = 2

    Do While i <= rangeCount

         Me.CostCentreCMBox.AddItem Cells(i, "a").Text

         i = i + 1
    Loop

End Sub
</code>```

答:
Thankyou tiger,

that has worked a perfectly,

however I have come across one problem, the code you gave worked perfectly for my cost centre's,

I then on the same user form created a Vendor combobox, which again has worked great with same code just changing variables to right ones.
With in the combo box I have all the vendors I need so it works however the scrollbar in that combo box doesn't work.
 To scroll down the vendors, I have to use arrows keys, or click inside the actual scroll bar bit and move the bar down that way, instead of click and hold the actual bar and move down if you understand.

have you come across this before? is there any reason for it?

regards,
Ross

Body:
I wanted to take information from a range and add it to a userform in a combobox.

The below code did that for me with success, but in the combo box I set a range of 40 rows, so it has my values and then after my last value it has an empty space of around 20 lines which I put there in case the user adds more cost centres.

How can the combobox select the exact rows and then recognise, if a new cost centre is added later?

"rules" is the worksheet I get information from, "Cost Centres" is the name of a range I built on that worksheet which has 40 rows.

What is best practice that more than 40 cost centres get added, that I'll never need to go back into the code to change the range?

Private Sub UserForm_Initialize()

    Worksheets("Rules").Activate

    Dim rangeCount As Integer
    Dim Range As Range
    Dim i As Integer

    Set Range = ActiveSheet.Range("A2")
    rangeCount = ActiveSheet.Range("CostCentres").Count
    i = 2

    Do While i <= rangeCount

         Me.CostCentreCMBox.AddItem Cells(i, "a").Text

         i = i + 1
    Loop

End Sub


问:
OneDrive Api - With whom the item is shared?
In OneDrive Business account I have shared files and folders and I'm trying to get a list of emails/users with whom the items are shared.

Both

```<code>https://graph.microsoft.com/v1.0/me/drive/sharedWithMe
</code>```

and

```<code>https://graph.microsoft.com/v1.0/me/drive/root/children
</code>```

both produce a similar result. I get the list of files, but the property Permissions is never present. All I see is whether the items are shared, but not with whom.

Now, I'm aware of /drive/items/{fileId}/permissions, but this would mean checking the files one-by-one. My app deals with a lot of files and I would really appreciate a way to get hose permissions in bulk...

Is there such an option?

答: _api/web/onedriveshareditems?$top=100&$expand=SpItemUrl might just do the trick. This is the URL that is used by the web interface of OneDrive. Hope it helps

Body:
In OneDrive Business account I have shared files and folders and I'm trying to get a list of emails/users with whom the items are shared.

Both

https://graph.microsoft.com/v1.0/me/drive/sharedWithMe

and

https://graph.microsoft.com/v1.0/me/drive/root/children

both produce a similar result. I get the list of files, but the property Permissions is never present. All I see is whether the items are shared, but not with whom.

Now, I'm aware of /drive/items/{fileId}/permissions, but this would mean checking the files one-by-one. My app deals with a lot of files and I would really appreciate a way to get hose permissions in bulk...

Is there such an option?


问:
json_decode help
I have been trying to use some API's from various services, At the moment im trying to retrieve data about a video on vimeo,

I have successfully got the file and read the contents, however, i do not know how to access each part of the file that is returned as a .json.

Basically, how do i access the data in the json file using PHP

Thanks

答: Did you try the json_decode function?</p>

Title: json_decode help

Body: Did you try the json_decode function?


问:
CollectionView sections
I have a collectionview and I want it to be of n section where each section has a ten of cells, my problem is: Maybe n equals thirty five, in this case I want to show 3 section with ten of cells and the last section with just five. </p>

答:
If array count is 35 return count/10 if count%10 is 0 else return count/10+1 in numberOfSections method

In numberOfItemsInSection method multiply current section with 10 and subtract from count. return min value of 10 or subtracted value

In cellForItemAt method multiply section with 10 and add row to get the array index

```<code>class ViewController: UIViewController, UICollectionViewDataSource {
    var arr = Array(1...35)
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return (arr.count/10) + (arr.count%10 == 0 ? 0 : 1)
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return min(10,arr.count - (10*section))
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? Cell
        let currentStr = arr[(indexPath.section*10)+indexPath.item]
        cell?.label.text = "\(currentStr)"
        return cell!
    }
}
</code>```

Title: CollectionView sections

Body:
If array count is 35 return count/10 if count%10 is 0 else return count/10+1 in numberOfSections method

In numberOfItemsInSection method multiply current section with 10 and subtract from count. return min value of 10 or subtracted value

In cellForItemAt method multiply section with 10 and add row to get the array index

class ViewController: UIViewController, UICollectionViewDataSource {
    var arr = Array(1...35)
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return (arr.count/10) + (arr.count%10 == 0 ? 0 : 1)
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return min(10,arr.count - (10*section))
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? Cell
        let currentStr = arr[(indexPath.section*10)+indexPath.item]
        cell?.label.text = "\(currentStr)"
        return cell!
    }
}


问:
Launch Image not showing up in iOS application (using Images.xcassets)
I'm having some trouble getting my launch image to show up in my application.

I have created all the static image files in the Images.xcassets file in an asset set called "LaunchImage".

I noticed that my project also contains a LaunchScreen.xib file (which was automatically created by Xcode).

This .xib file appears when I run the application on my iPhone6 device. It doesn't appear in the simulator for iPhone4s (which makes sense, since xib launch screen is only for iOS 8 +).

I want to use the static images that I have created since they fall under the Apple Guidelines and go with my application. However, I haven't had any luck at getting it to show up.

I noticed under the project settings that there is a section called App Icons and Launch Images. I see how the .xib is connected by the Launch Screen File option I assume.

However, there is an option called Launch Image Sources. What does this do?

I found this: http://matthewpalmer.net/blog/2014/09/10/iphone-6-plus-launch-image-adaptive-mode/. However, it didn't explain anything about the Launch Image Source option.

There is a button next to the Launch Image Sources called "Use Asset Catalog". When I click it, it just says Migrate Launch Images to an asset catalog. Your existing launch images will be copied into a new image set. Choose an asset catalog to use: .

This is confusing to me because I've already created my asset catalog and I definitely don't want it to overwrite images.xcassets file. So, how do I link this to the Launch Images Asset Set that I already have created? Also what "existing launch images" is it referring to will be copied into a new image set?

Thank you!

UPDATE 1

So, I tried the migrate images option and chose to the new set option. This caused a new image set to be created which I deleted. However, the name left in the Launch Image Source was set to LaunchImage which somehow connected to the image set that contains my launch images. It did mess up my LaunchImage set -- the images were set to unassigned. I deleted them and dragged my files to the appropriate box in the LaunchImage asset set. However, when I run the application it still doesn't work. =( Launch Image doesn't show up.

I even removed the information that was in Launch Screen File (which my assumption was the setting that connects to the .xib file). Still, somehow the .xib file appears on my iPhone6 device. =(

Any ideas what's going on?

答:
After few hours of unclear answers:

1) go to setting app General section in xCode.

2) Scroll down to App Icons and Launch Images.

3) Clear Launch Screen File (just leave it blank)

4) Set Launch Images Source to LaunchImage (remember to create them in Assets.xcassets)

Now app will use images You set in LaunchImage.


问:
Is there a way to connect and view the files in a self Hosted Agent of Azure pipelines
I am pretty new to Azure Devops. Is there a way to connect and view the logs and the folders created in the self hosted agent of Azure devops pipeline.</p>

答:
Agree with Sajeetharan,I will show you the specific place to view the logs and folders in the page through the following image.

After the build pipeline finished, you can click into a build record. There is a Logs option in this record. You can click on the specific job to view the log, or you can click the Download all logs button to download the complete log to local view.
You can click on the file container which under Build artifacts published in the Summary to view folders.
In addition,using api:

GET https://dev.azure.com/{organization}/{project}/_apis/build/builds/{buildId}/logs?api-version=5.0 to get logs is also a good method.

Could you mark Sajeetharan's answer if it can be helpful to you.


问:
Add button on top of AVPlayerLayer - iOS Swift
I'm trying to add a play button on top of my AVPlayerLayer but it's not showing up.

I have a UIView called playerView as an IBOutlet.

Here's how I create the player and a corresponding playerLayer, and put it in the playerView:

```<code>    player = AVPlayer()
    superLayer = self.playerView.layer
    playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame = self.playerView.bounds
    playerLayer.cornerRadius = 5.0
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
    superLayer.addSublayer(playerLayer)

    self.view.bringSubview(toFront: playVideoButton)
</code>```

The problem is that the playVideoButton doesn't show up on top of the the playerLayer (the button is added in the storyboard). I tried hiding the playerLayer and the button still doesn't show up underneath, so it seems the button's not even in the view hierarchy.

答:
Maybe this can help </p>

```<code>let player = AVPlayer(url: videoURL!)
let playerLayer = AVPlayerLayer(player: player)

let btn = UIButton()
btn.frame = CGRect(x: 23, y: 34, width: 25, height: 30)

playerLayer.addSublayer(btn.layer)
self.view.layer.addSublayer(playerLayer)
</code>```

Body:
I'm trying to add a play button on top of my AVPlayerLayer but it's not showing up.

I have a UIView called playerView as an IBOutlet.

Here's how I create the player and a corresponding playerLayer, and put it in the playerView:

    player = AVPlayer()
    superLayer = self.playerView.layer
    playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame = self.playerView.bounds
    playerLayer.cornerRadius = 5.0
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
    superLayer.addSublayer(playerLayer)

    self.view.bringSubview(toFront: playVideoButton)

The problem is that the playVideoButton doesn't show up on top of the the playerLayer (the button is added in the storyboard). I tried hiding the playerLayer and the button still doesn't show up underneath, so it seems the button's not even in the view hierarchy.

Body:
Maybe this can help

let player = AVPlayer(url: videoURL!)
let playerLayer = AVPlayerLayer(player: player)

let btn = UIButton()
btn.frame = CGRect(x: 23, y: 34, width: 25, height: 30)

playerLayer.addSublayer(btn.layer)
self.view.layer.addSublayer(playerLayer)


问:
Rxjs execute concatMap only once
I have two Observables, getUser and getUserAvatar.
Both of them emits two values - cached immediately using BehaviorSubject, and real after network request.

Now code works this way:

1) Send request to get user and immediately emit cached user

2)After cached user emited, code goes inside concatMap, and execute getUserAvatar first time

3)getUserAvatar send request to server and immediately emit cached userAvatar

4)Everything is completed and cached user with cached avatar returned

5) After some time, real user returned and getUser emits value again

6) At this step, I want to prevent call concatMap second time, because server request already in progress, I want just go to return 'USER LOADED.

```<code>sendGetRequest('/user/').pipe(
        concatMap(() => {
            // HERE, after user data loaded, I have url for his avatar
            return sendGetRequest('/avatar/').pipe();
        }),
        map(() => {
            return 'USER LOADED';
        })
    )
</code>```

Code for Server request

```<code>sendGetRequest(url: string, ignoreCache?: boolean): any {

    let responseSubj = new Subject();

    const cachedData = this.cache.getItemForUrl(url);
    const cacheAllowed = cachedData && !ignoreCache;
    if (cacheAllowed) {
        responseSubj = new BehaviorSubject(cachedData);
    }

    const getFromServer = this.http.get(environment.API_SERVER_URL + url, this.addAuth()).pipe(
        filter((res: any) => {

            if (cacheAllowed && JSON.stringify(cachedData) === JSON.stringify(res)) {
                responseSubj.complete();
                return false;
            }

            this.cache.setItemForUrl(url, res).then(() => {
                responseSubj.complete();
            });
            return true;
        }),
        catchError((error, caught) => {
            console.log('ERROR FROM GET REQUEST', error);
            return throwError(error);
        })
    );

    return merge(responseSubj, getFromServer);
}
</code>```

答:
You should use exhaustMap instead of concatMap.

exhaustMap ignore other values until that observable completes.

For example,

```<code>fromEvent(this.saveButton.nativeElement, 'click')
.pipe(
    exhaustMap(() => this.saveCourse(this.form.value))
)
.subscribe();
</code>```

If we now click save let's say 5 times in a row, we can see, the clicks that we made while a save request was still ongoing where ignored, as expected!

Example is from angularuniveristy blog.

Detailed explanation of exhaustMap

Title: Rxjs execute concatMap only once

Body:
I have two Observables, getUser and getUserAvatar.
Both of them emits two values - cached immediately using BehaviorSubject, and real after network request.

Now code works this way:

1) Send request to get user and immediately emit cached user

2)After cached user emited, code goes inside concatMap, and execute getUserAvatar first time

3)getUserAvatar send request to server and immediately emit cached userAvatar

4)Everything is completed and cached user with cached avatar returned

5) After some time, real user returned and getUser emits value again

6) At this step, I want to prevent call concatMap second time, because server request already in progress, I want just go to return 'USER LOADED.

sendGetRequest('/user/').pipe(
        concatMap(() => {
            // HERE, after user data loaded, I have url for his avatar
            return sendGetRequest('/avatar/').pipe();
        }),
        map(() => {
            return 'USER LOADED';
        })
    )

Code for Server request

sendGetRequest(url: string, ignoreCache?: boolean): any {

    let responseSubj = new Subject();

    const cachedData = this.cache.getItemForUrl(url);
    const cacheAllowed = cachedData && !ignoreCache;
    if (cacheAllowed) {
        responseSubj = new BehaviorSubject(cachedData);
    }

    const getFromServer = this.http.get(environment.API_SERVER_URL + url, this.addAuth()).pipe(
        filter((res: any) => {

            if (cacheAllowed && JSON.stringify(cachedData) === JSON.stringify(res)) {
                responseSubj.complete();
                return false;
            }

            this.cache.setItemForUrl(url, res).then(() => {
                responseSubj.complete();
            });
            return true;
        }),
        catchError((error, caught) => {
            console.log('ERROR FROM GET REQUEST', error);
            return throwError(error);
        })
    );

    return merge(responseSubj, getFromServer);
}

Body:
You should use exhaustMap instead of concatMap.

exhaustMap ignore other values until that observable completes.

For example,

fromEvent(this.saveButton.nativeElement, 'click')
.pipe(
    exhaustMap(() => this.saveCourse(this.form.value))
)
.subscribe();

If we now click save let's say 5 times in a row, we can see, the clicks that we made while a save request was still ongoing where ignored, as expected!

Example is from angularuniveristy blog.

Detailed explanation of exhaustMap


问:
Run ROR as a windows service?
I need to run my Ruby on rails application as a windows service in production environment . What is the ideal and reliable way to achieve this requirement?</p>

答:
If a windows server is a must - I'd still go with Docker container for the app, because:

rails will run in a linux environment, you'll have less compatibility issues

you'll have Docker take care of process starting and monitoring, resource limiting

if you later choose to use other server - you can use the exact same container

Downside is a bit higher initial setup routine, but in the long run this should payoff.

Title: Run ROR as a windows service?


问:
Forwarding to external resource using an Ingress controller
I have been using the GCLB Ingress Controller to forward outside traffic to my in-cluster services, and this has been working great so far.

But, is there a way that based on a route/path match, traffic could be forwarded to outside of cluster resource. From the documentation, I can't seem to find anything and I don't think it can be achieved using GCLB Ingress Controller; but I haven't yet tried the NGINX Ingress Controller.

Is this a behavior that can be achieved using any of these 2 controllers? I would prefer using the native gcloud one, the GCLB but the other one works too.

答: Hope this can help you kubernates external service</p>


问:
Is it possible to do a If Else or a Switch Statement Firestore Rules
Is it possible to do a Switch Statement or an if else in firestore rules?

I have tried to search for it with no luck of finding an answer.

What i tried was

```<code>function getTier() {
  return get(/users/$(request.auth.uid)).data.userTier;
}

function canAddProduct() {
  if getTier() == 'UserTier.FREE'
    // Do additional code
    return doSomethingBasedOnFreeTier();
  else if getTier() == 'UserTier.SILVER'
    // Do additional code
    return doSomethingBasedOnSilverTier()
  else if getTier() == 'UserTier.GOLD'
    // Do additional code
    return doSomethingBasedOnGoldTier()
  else if getTier() == 'UserTier.COMPANY'
    // Do additional code
    return doSomethingBasedOnCompanyTier()
}
</code>```

Any help would be greatly appreciated.

答:
Firestore Rules are meant to define the rules for accessing the particular collections in your Project.
They are primarily used to check access for the user. They are not meant for anything other than checking logic. So they don't support switch statements, if..else conditions and conditional expressions.

You can use OR condition to check if the user can add the product according to the UserTier he/she belongs to.

```<code>function canAddProduct() {
    return ( getTier() == 'UserTier.FREE' || getTier() == 'UserTier.SILVER'
             || getTier() == 'UserTier.GOLD' || getTier() == 'UserTier.COMPANY' );
}
</code>```

This is the simplest way of checking access.

However for your particular case try this. I'm assuming that you have further checks on the user according to the tier they belong to.
Here I'm checking if the user's trial period is expired only if he is belonging to the FREE Tier.

```<code>function getUser() {
//Get the user
    return get(/users/$(request.auth.uid)).data;
}

function canAddProduct() {
    return ( getTier() == 'UserTier.FREE' && checkFreeTierAccess(getUser()) ||
             getTier() == 'UserTier.SILVER' && checkSilverTierAccess(getUser()) ||
             getTier() == 'UserTier.GOLD' && checkGoldTierAccess(getUser()) ||
             getTier() == 'UserTier.COMPANY' && checkCompanyTierAccess(getUser())
           );
 }

function checkFreeTierAccess(user) {
//do the checks
    return user.isTrailPeriodExpired;
}
</code>```

Hope this solves your problem.

Body:
Is it possible to do a Switch Statement or an if else in firestore rules?

I have tried to search for it with no luck of finding an answer.

What i tried was

function getTier() {
  return get(/users/$(request.auth.uid)).data.userTier;
}

function canAddProduct() {
  if getTier() == 'UserTier.FREE'
    // Do additional code
    return doSomethingBasedOnFreeTier();
  else if getTier() == 'UserTier.SILVER'
    // Do additional code
    return doSomethingBasedOnSilverTier()
  else if getTier() == 'UserTier.GOLD'
    // Do additional code
    return doSomethingBasedOnGoldTier()
  else if getTier() == 'UserTier.COMPANY'
    // Do additional code
    return doSomethingBasedOnCompanyTier()
}

Any help would be greatly appreciated.

Body:
Firestore Rules are meant to define the rules for accessing the particular collections in your Project.
They are primarily used to check access for the user. They are not meant for anything other than checking logic. So they don't support switch statements, if..else conditions and conditional expressions.

You can use OR condition to check if the user can add the product according to the UserTier he/she belongs to.

function canAddProduct() {
    return ( getTier() == 'UserTier.FREE' || getTier() == 'UserTier.SILVER'
             || getTier() == 'UserTier.GOLD' || getTier() == 'UserTier.COMPANY' );
}

This is the simplest way of checking access.

However for your particular case try this. I'm assuming that you have further checks on the user according to the tier they belong to.
Here I'm checking if the user's trial period is expired only if he is belonging to the FREE Tier.

function getUser() {
//Get the user
    return get(/users/$(request.auth.uid)).data;
}

function canAddProduct() {
    return ( getTier() == 'UserTier.FREE' && checkFreeTierAccess(getUser()) ||
             getTier() == 'UserTier.SILVER' && checkSilverTierAccess(getUser()) ||
             getTier() == 'UserTier.GOLD' && checkGoldTierAccess(getUser()) ||
             getTier() == 'UserTier.COMPANY' && checkCompanyTierAccess(getUser())
           );
 }

function checkFreeTierAccess(user) {
//do the checks
    return user.isTrailPeriodExpired;
}

Hope this solves your problem.


问:
Git. How to roll back changes in certain file in a chain of commits?
I have a repo with three files in it - 1.txt, 2.txt and 3.txt. I created a branch 'new_branch' and made commits (let's call them A, B and C), every of these commits contains changes in several files from my repo. Then I understood, that 1.txt was updated mistakenly. Is it possible to remove changes, made in 1.txt, from commits A, B and C but keep changes in 2.txt and 3.txt?

UPD. I want also to remove changes, made it 1.txt, from commit history. As result 'git log -p' should show, that only 2.txt and 3.txt were modified in commits A, B and C.

Many thanks.

答:
Here's another not so neat way [Solution provided by Tim best suits the situation though]-

Assuming your top 3 commits are A,B,C, You can do git reset --soft HEAD~3. All your committed changes will come in your staging area. You can unstage 1.txt and commit rest of the files.

This will lead to change in history with commits A, B and C to be replaced by a new commit D that will have all changes in A, B and C except for the file 1.txt.


问:
DataTrigger, Binding to nested properties via TemplatedParent
According to msdn, it should be perfectly legal, and possible, to bind something to a nested property:

```<code><Binding Path="propertyName.propertyName2" .../>
<Binding Path="propertyName.propertyName2.propertyName3" .../>
</code>```

In my case, it's not so, though...

I have a custom control, MyControl, with a dependency property ViewModel:

```<code>    public static DependencyProperty ViewModelProperty = DependencyProperty.Register(
        "ViewModel", typeof(IViewModel), typeof(MyControl));

    public IViewModel ViewModel
    {
        get { return (IViewModel)GetValue(ViewModelProperty); }
        set { SetValue(ViewModelProperty, value); }
    }
</code>```

and in the control template, I try to bind to properties in that viewmodel:

```<code> <Style TargetType="{x:Type my:MyControl}">
   <Setter Property="Template">
     <Setter.Value>
       <ControlTemplate TargetType="{x:Type my:MyControl}">
         <Grid>
           <TextBox Text="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=ViewModel.Text}"/>
           <Button x:Name="MyButton" Content="Visible by trigger" Visibility="Collapsed" />
         </Grid>
       <ControlTemplate.Triggers>
         <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=ViewModel.ButtonVisible}" Value="True">
           <Setter TargetName="MyButton" Property="Visibility" Value="Visible" />
         </DataTrigger>
      .../>
</code>```

In the viewmodel itself, I have a preoperty Text as follow:

```<code>    public string Text
    {
        get { return m_text; }
        set
        {
            m_text = value;
            OnPropertyChanged("Text");
        }
    }

    public bool ButtonVisible
    {
      get { return m_buttonVisible; }
      set
     {
       m_buttonVisible = value;
       OnPropertyChanged("ButtonVisible"); }
     }
</code>```

I get no bind errors, but things doesn't happend...

Any clues?

Edit
It looks like the bindings work half way. When the text is changed in the editbox, my Text property is set, but if the Text-property is set in code, the ui won't update.

Edit 2

Looks like my first attempt at simplifying the case before posting was a little to successful... As @Erno points out, the code that I posted seems to work OK.

I have looked at the original code some more, and added a trigger to the scenario. The original code uses triggers to show parts of the ui at given conditions. These are also binded to nested properties. I now think that these triggers fail to trigger. I have updated the code. If it still doesn't show whats wrong, I can post a sample application some where.

答:
There is a comma missing:

```<code><TextBox Text="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=ViewModel.Text}"/>
</code>```

EDIT

Add Mode=TwoWay to the binding:

```<code><TextBox Text="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=ViewModel.Text, Mode=TwoWay}"/>
</code>```

EDIT2

Got it! I could reproduce and fix it.

Replace the TemplatedParent with Self in the binding.
Read this explanation

Body:
According to msdn, it should be perfectly legal, and possible, to bind something to a nested property:

<Binding Path="propertyName.propertyName2" .../>
<Binding Path="propertyName.propertyName2.propertyName3" .../>

In my case, it's not so, though...

I have a custom control, MyControl, with a dependency property ViewModel:

    public static DependencyProperty ViewModelProperty = DependencyProperty.Register(
        "ViewModel", typeof(IViewModel), typeof(MyControl));

    public IViewModel ViewModel
    {
        get { return (IViewModel)GetValue(ViewModelProperty); }
        set { SetValue(ViewModelProperty, value); }
    }

and in the control template, I try to bind to properties in that viewmodel:

Body:
There is a comma missing:

<TextBox Text="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=ViewModel.Text}"/>

EDIT

Add Mode=TwoWay to the binding:

<TextBox Text="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Path=ViewModel.Text, Mode=TwoWay}"/>

EDIT2

Got it! I could reproduce and fix it.

Replace the TemplatedParent with Self in the binding.
Read this explanation