问:
Align font awesome icon in Bootstrap 4 button
maybe I'm being too strict this time but well, I want to perfectly align (vertically) some font awesome icons in BS 4 buttons, this is the code I'm using:

new Vue({
    el: '#app',
    data: {
        items: [
            {
                id: 1,
                title: "Item 1",
                price: 50
            },
            {
                id: 2,
                title: "Item 2",
                price: 100
            },
            {
                id: 3,
                title: "Item 3",
                price: 50.5
            }
        ],
        cart: [],
        search: ''
    },
    methods: {
        total() {
            var t = 0;
            for(var i = 0; i < this.cart.length; i++) {
                var item = this.cart[i];
                t += item.price * item.qty;
            }

            return t;
        },
        addItem(index) {
            var item = this.items[index];
            var found = false;
            // if it's there, increment quantity:
            for(var i = 0; i < this.cart.length; i++) {
                let ic = this.cart[i];

                if(ic.id == item.id) {
                    ic.qty++;
                    found = true;
                    break;
                }
            }

            // if not, add it:
            if(!found) {
                this.cart.push({
                    title: item.title,
                    qty: 1,
                    id: item.id,
                    price: item.price
                });
            }
        },
        dec(item) {
            item.qty--;
            if(item.qty < 1) {
                item.qty = 1;

                // remove item from cart:
                for(var i = 0; i < this.cart.length; i++) {
                    if(this.cart[i].id == item.id) {
                        this.cart.splice(i, 1);
                        break;
                    }
                }
            }
        },
        inc(item) {
            // increment item on cart:
            item.qty++;
        },
        onSubmit() {
            console.log(this.search);
        }
    },
    filters: {
        currency(price) {
            return '$'.concat(price.toFixed(2));
        }
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    background-color: #393C3D;
    color: #FFF;
}</code>```

<!doctype html>

    <meta charset="utf-8">
    <title>Vue.js Poster Shop</title>
    <link rel="icon" href="public/favicon.ico" type="image/x-icon">

    <link href="https://fonts.googleapis.com/css?family=Luckiest+Guy" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Lato|Montserrat" rel="stylesheet">

    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

                        Vue.js Poster Store
                        <button class="btn btn-sm btn-danger" v-on:click="dec(item)">

                        </button>
                        <button class="btn btn-sm btn-success" v-on:click="inc(item)">

                        </button>

                    <form v-on:submit.prevent="onSubmit()">

                            <input type="text"   class="form-control" v-model="search" placeholder="Search for...">

                                <button class="btn btn-primary" type="submit">Go!</button>

                    </form>

Store

{{item.title}}

Here goes the description

                        <button class="btn btn-success" v-on:click="addItem(index)">Add to cart</button>

Cart

Total: {{total() | currency}}

{{item.title}}

Price: {{item.price | currency}} x {{item.qty}}

                        <button class="btn btn-sm btn-danger" v-on:click="dec(item)">

                        </button>
                        <button class="btn btn-sm btn-success" v-on:click="inc(item)">

                        </button>

                    No items in the cart

```

and this is the result:

enter image description here

and, as you can see, the icons are not perfectly aligned vertically:
enter image description here

and I just wanted to know if there's a easy way to fix this (maybe I have something wrong in my code?)

I tried this but I couldn't make it work (that's for divs though). Any ideas?

Thanks in advance.

答:
solution 1, create your own - + button using css (perfect button)

solution 2, adjust FA icon margin

here is solution 1.

new Vue({
    el: '#app',
    data: {
        items: [
            {
                id: 1,
                title: "Item 1",
                price: 50
            },
            {
                id: 2,
                title: "Item 2",
                price: 100
            },
            {
                id: 3,
                title: "Item 3",
                price: 50.5
            }
        ],
        cart: [],
        search: ''
    },
    methods: {
        total() {
            var t = 0;
            for(var i = 0; i < this.cart.length; i++) {
                var item = this.cart[i];
                t += item.price * item.qty;
            }

            return t;
        },
        addItem(index) {
            var item = this.items[index];
            var found = false;
            // if it's there, increment quantity:
            for(var i = 0; i < this.cart.length; i++) {
                let ic = this.cart[i];

                if(ic.id == item.id) {
                    ic.qty++;
                    found = true;
                    break;
                }
            }

            // if not, add it:
            if(!found) {
                this.cart.push({
                    title: item.title,
                    qty: 1,
                    id: item.id,
                    price: item.price
                });
            }
        },
        dec(item) {
            item.qty--;
            if(item.qty < 1) {
                item.qty = 1;

                // remove item from cart:
                for(var i = 0; i < this.cart.length; i++) {
                    if(this.cart[i].id == item.id) {
                        this.cart.splice(i, 1);
                        break;
                    }
                }
            }
        },
        inc(item) {
            // increment item on cart:
            item.qty++;
        },
        onSubmit() {
            console.log(this.search);
        }
    },
    filters: {
        currency(price) {
            return '$'.concat(price.toFixed(2));
        }
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    background-color: #393C3D;
    color: #FFF;
}

.vbtn {
  display: inline-block;
  font-size: 0px;
}

.btn-sm { height: 35px; }

/* btn plus */
.button_plus {
  position: absolute;
  width: 35px;
  height: 35px;
  background: #5cb85c;
  cursor: pointer;
  border-radius: 3px;
  /* Mittig */
  margin: -31px 0 0 45px;
}

.button_plus:after {
  content: '';
  position: absolute;
  transform: translate(-50%, -50%);
  height: 4px;
  width: 50%;
  background: white;
  top: 50%;
  left: 50%;
}

.button_plus:before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: white;
  height: 50%;
  width: 4px;
}

.button_plus:hover:before,
.button_plus:hover:after {
  background: #fff;
  transition: 0.2s;
}

.button_plus:hover {
  background-color: #449d44;
  transition: 0.2s;
}

/* btn minus */
.button_minus {
  position: absolute;
  width: 35px;
  height: 35px;
  background: #d9534f;
  cursor: pointer;
  border-radius: 3px;
  margin-top: -31px;
}

.button_minus:after {
  content: '';
  position: absolute;
  transform: translate(-50%, -50%);
  height: 4px;
  width: 50%;
  background: white;
  top: 50%;
  left: 50%;
}

.button_minus:before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: white;
  height: 50%;
}

.button_minus:hover:before,
.button_minus:hover:after {
  background: #fff;
  transition: 0.2s;
}

.button_minus:hover {
  background-color: #c9302c;
  transition: 0.2s;
}</code>```

<!doctype html>

    <meta charset="utf-8">
    <title>Vue.js Poster Shop</title>
    <link rel="icon" href="public/favicon.ico" type="image/x-icon">

    <link href="https://fonts.googleapis.com/css?family=Luckiest+Guy" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Lato|Montserrat" rel="stylesheet">

    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

                        Vue.js Poster Store

                    <form v-on:submit.prevent="onSubmit()">

                            <input type="text"   class="form-control" v-model="search" placeholder="Search for...">

                                <button class="btn btn-primary" type="submit">Go!</button>

                    </form>

Store

{{item.title}}

Here goes the description

                        <button class="btn btn-success" v-on:click="addItem(index)">Add to cart</button>

Cart

Total: {{total() | currency}}

{{item.title}}

Price: {{item.price | currency}} x {{item.qty}}

                        <button class="btn btn-sm btn-danger" v-on:click="dec(item)">

                        </button>
                        <button class="btn btn-sm btn-success" v-on:click="inc(item)">

                        </button>

                    No items in the cart

```
</div>
</div>
</p>

<p>here is solution 2:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>new Vue({
    el: '#app',
    data: {
        items: [
            {
                id: 1,
                title: "Item 1",
                price: 50
            },
            {
                id: 2,
                title: "Item 2",
                price: 100
            },
            {
                id: 3,
                title: "Item 3",
                price: 50.5
            }
        ],
        cart: [],
        search: ''
    },
    methods: {
        total() {
            var t = 0;
            for(var i = 0; i < this.cart.length; i++) {
                var item = this.cart[i];
                t += item.price * item.qty;
            }

            return t;
        },
        addItem(index) {
            var item = this.items[index];
            var found = false;
            // if it's there, increment quantity:
            for(var i = 0; i < this.cart.length; i++) {
                let ic = this.cart[i];

                if(ic.id == item.id) {
                    ic.qty++;
                    found = true;
                    break;
                }
            }

            // if not, add it:
            if(!found) {
                this.cart.push({
                    title: item.title,
                    qty: 1,
                    id: item.id,
                    price: item.price
                });
            }
        },
        dec(item) {
            item.qty--;
            if(item.qty < 1) {
                item.qty = 1;

                // remove item from cart:
                for(var i = 0; i < this.cart.length; i++) {
                    if(this.cart[i].id == item.id) {
                        this.cart.splice(i, 1);
                        break;
                    }
                }
            }
        },
        inc(item) {
            // increment item on cart:
            item.qty++;
        },
        onSubmit() {
            console.log(this.search);
        }
    },
    filters: {
        currency(price) {
            return '$'.concat(price.toFixed(2));
        }
    }
});</code>```

body {
    background-color: #393C3D;
    color: #FFF;
}

.fa-margin-top {
  margin-top: 4px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Vue.js Poster Shop</title>
    <link rel="icon" href="public/favicon.ico" type="image/x-icon">

    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css?family=Luckiest+Guy" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Lato|Montserrat" rel="stylesheet">

    <!-- CSS -->
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <style type="text/css">
        body {
            background-color: #393C3D;
            color: #FFF;
        }
    </style>
</head>
<body>
<div class="container-fluid" id="app">
    <div class="row">
        <div class="col-lg-4 col-xs-12">
            <div class="card card-inverse bg-inverse my-3">
                <div class="card-block">
                    <h1 class="card-title">
                        Vue.js Poster Store
                        <button class="btn btn-sm btn-danger" v-on:click="dec(item)">
                            <i class="fa fa-minus fa-margin-top"></i>
                        </button>
                        <button class="btn btn-sm btn-success" v-on:click="inc(item)">
                            <i class="fa fa-plus fa-margin-top"></i>
                        </button>
                    </h1>
                    <form v-on:submit.prevent="onSubmit()">
                        <div class="input-group">
                            <input type="text"   class="form-control" v-model="search" placeholder="Search for...">
                            <span class="input-group-btn">
                                <button class="btn btn-primary" type="submit">Go!</button>
                            </span>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-6 col-xs-12">
            <div class="row">
                <div class="col-lg-12">
                    <h3>Store</h3>
                </div>
            </div>
            <div v-for="(item, index) in items">
                <div class="card card-inverse bg-inverse my-3">
                    <div class="card-block">
                        <h3 class="card-title">{{item.title}}</h3>
                        <p class="card-text">Here goes the description</p>
                        <button class="btn btn-success" v-on:click="addItem(index)">Add to cart</button>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-5 col-lg-5-offset-1 col-xs-12">
            <div class="row">
                <div class="col-lg-4">
                    <h3>Cart</h3>
                </div>
                <div class="col-lg-8">
                    <h5 v-if="cart.length">Total: {{total() | currency}}</h5>
                </div>
            </div>
            <div v-for="item in cart">
                <div class="card card-inverse bg-inverse my-3">
                    <div class="card-block">
                        <h3 class="card-title">{{item.title}}</h3>

                        <p>Price: {{item.price | currency}} x {{item.qty}}</p>

                        <button class="btn btn-sm btn-danger" v-on:click="dec(item)">
                            <i class="fa fa-minus"></i>
                        </button>
                        <button class="btn btn-sm btn-success" v-on:click="inc(item)">
                            <i class="fa fa-plus"></i>
                        </button>
                    </div>
                </div>
            </div>
            <div>
                <div class="my-3" v-if="!cart.length">
                    No items in the cart
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Scripts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.js"></script>
<script type="text/javascript" src="public/script.js"></script>

</body>
</html></code>```

Body:
maybe I'm being too strict this time but well, I want to perfectly align (vertically) some font awesome icons in BS 4 buttons, this is the code I'm using:

new Vue({
    el: '#app',
    data: {
        items: [
            {
                id: 1,
                title: "Item 1",
                price: 50
            },
            {
                id: 2,
                title: "Item 2",
                price: 100
            },
            {
                id: 3,
                title: "Item 3",
                price: 50.5
            }
        ],
        cart: [],
        search: ''
    },
    methods: {
        total() {
            var t = 0;
            for(var i = 0; i < this.cart.length; i++) {
                var item = this.cart[i];
                t += item.price * item.qty;
            }

            return t;
        },
        addItem(index) {
            var item = this.items[index];
            var found = false;
            // if it's there, increment quantity:
            for(var i = 0; i < this.cart.length; i++) {
                let ic = this.cart[i];

                if(ic.id == item.id) {
                    ic.qty++;
                    found = true;
                    break;
                }
            }

            // if not, add it:
            if(!found) {
                this.cart.push({
                    title: item.title,
                    qty: 1,
                    id: item.id,
                    price: item.price
                });
            }
        },
        dec(item) {
            item.qty--;
            if(item.qty < 1) {
                item.qty = 1;

                // remove item from cart:
                for(var i = 0; i < this.cart.length; i++) {
                    if(this.cart[i].id == item.id) {
                        this.cart.splice(i, 1);
                        break;
                    }
                }
            }
        },
        inc(item) {
            // increment item on cart:
            item.qty++;
        },
        onSubmit() {
            console.log(this.search);
        }
    },
    filters: {
        currency(price) {
            return '$'.concat(price.toFixed(2));
        }
    }
});

body {
    background-color: #393C3D;
    color: #FFF;
}

<!doctype html>

    <meta charset="utf-8">
    <title>Vue.js Poster Shop</title>
    <link rel="icon" href="public/favicon.ico" type="image/x-icon">

    <link href="https://fonts.googleapis.com/css?family=Luckiest+Guy" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Lato|Montserrat" rel="stylesheet">

    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

                        Vue.js Poster Store
                        <button class="btn btn-sm btn-danger" v-on:click="dec(item)">

                        </button>
                        <button class="btn btn-sm btn-success" v-on:click="inc(item)">

                        </button>

                    <form v-on:submit.prevent="onSubmit()">

                            <input type="text"   class="form-control" v-model="search" placeholder="Search for...">

                                <button class="btn btn-primary" type="submit">Go!</button>

                    </form>

Store

{{item.title}}

Here goes the description

                        <button class="btn btn-success" v-on:click="addItem(index)">Add to cart</button>

Cart

Total: {{total() | currency}}

{{item.title}}

Price: {{item.price | currency}} x {{item.qty}}

                        <button class="btn btn-sm btn-danger" v-on:click="dec(item)">

                        </button>
                        <button class="btn btn-sm btn-success" v-on:click="inc(item)">

                        </button>

                    No items in the cart

and this is the result:

enter image description here

and, as you can see, the icons are not perfectly aligned vertically:
enter image description here

and I just wanted to know if there's a easy way to fix this (maybe I have something wrong in my code?)

I tried this but I couldn't make it work (that's for divs though). Any ideas?

Thanks in advance.

Body:
solution 1, create your own - + button using css (perfect button)

solution 2, adjust FA icon margin

here is solution 1.

new Vue({
    el: '#app',
    data: {
        items: [
            {
                id: 1,
                title: "Item 1",
                price: 50
            },
            {
                id: 2,
                title: "Item 2",
                price: 100
            },
            {
                id: 3,
                title: "Item 3",
                price: 50.5
            }
        ],
        cart: [],
        search: ''
    },
    methods: {
        total() {
            var t = 0;
            for(var i = 0; i < this.cart.length; i++) {
                var item = this.cart[i];
                t += item.price * item.qty;
            }

            return t;
        },
        addItem(index) {
            var item = this.items[index];
            var found = false;
            // if it's there, increment quantity:
            for(var i = 0; i < this.cart.length; i++) {
                let ic = this.cart[i];

                if(ic.id == item.id) {
                    ic.qty++;
                    found = true;
                    break;
                }
            }

            // if not, add it:
            if(!found) {
                this.cart.push({
                    title: item.title,
                    qty: 1,
                    id: item.id,
                    price: item.price
                });
            }
        },
        dec(item) {
            item.qty--;
            if(item.qty < 1) {
                item.qty = 1;

                // remove item from cart:
                for(var i = 0; i < this.cart.length; i++) {
                    if(this.cart[i].id == item.id) {
                        this.cart.splice(i, 1);
                        break;
                    }
                }
            }
        },
        inc(item) {
            // increment item on cart:
            item.qty++;
        },
        onSubmit() {
            console.log(this.search);
        }
    },
    filters: {
        currency(price) {
            return '$'.concat(price.toFixed(2));
        }
    }
});

body {
    background-color: #393C3D;
    color: #FFF;
}

.vbtn {
  display: inline-block;
  font-size: 0px;
}

.btn-sm { height: 35px; }

/* btn plus */
.button_plus {
  position: absolute;
  width: 35px;
  height: 35px;
  background: #5cb85c;
  cursor: pointer;
  border-radius: 3px;
  /* Mittig */
  margin: -31px 0 0 45px;
}

.button_plus:after {
  content: '';
  position: absolute;
  transform: translate(-50%, -50%);
  height: 4px;
  width: 50%;
  background: white;
  top: 50%;
  left: 50%;
}

.button_plus:before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: white;
  height: 50%;
  width: 4px;
}

.button_plus:hover:before,
.button_plus:hover:after {
  background: #fff;
  transition: 0.2s;
}

.button_plus:hover {
  background-color: #449d44;
  transition: 0.2s;
}

/* btn minus */
.button_minus {
  position: absolute;
  width: 35px;
  height: 35px;
  background: #d9534f;
  cursor: pointer;
  border-radius: 3px;
  margin-top: -31px;
}

.button_minus:after {
  content: '';
  position: absolute;
  transform: translate(-50%, -50%);
  height: 4px;
  width: 50%;
  background: white;
  top: 50%;
  left: 50%;
}

.button_minus:before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: white;
  height: 50%;
}

.button_minus:hover:before,
.button_minus:hover:after {
  background: #fff;
  transition: 0.2s;
}

.button_minus:hover {
  background-color: #c9302c;
  transition: 0.2s;
}

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Vue.js Poster Shop</title>
    <link rel="icon" href="public/favicon.ico" type="image/x-icon">

    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css?family=Luckiest+Guy" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Lato|Montserrat" rel="stylesheet">

    <!-- CSS -->
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <style type="text/css">
        body {
            background-color: #393C3D;
            color: #FFF;
        }
    </style>
</head>
<body>
<div class="container-fluid" id="app">
    <div class="row">
        <div class="col-lg-4 col-xs-12">
            <div class="card card-inverse bg-inverse my-3">
                <div class="card-block">
                    <h1 class="card-title">
                        Vue.js Poster Store
                        <span class="vbtn" style="display: inline-block;">
                          <div class="button_plus"></div>
                          <div class="button_minus"></div>
                        </span>
                    </h1>
                    <form v-on:submit.prevent="onSubmit()">
                        <div class="input-group">
                            <input type="text"   class="form-control" v-model="search" placeholder="Search for...">
                            <span class="input-group-btn">
                                <button class="btn btn-primary" type="submit">Go!</button>
                            </span>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-6 col-xs-12">
            <div class="row">
                <div class="col-lg-12">
                    <h3>Store</h3>
                </div>
            </div>
            <div v-for="(item, index) in items">
                <div class="card card-inverse bg-inverse my-3">
                    <div class="card-block">
                        <h3 class="card-title">{{item.title}}</h3>
                        <p class="card-text">Here goes the description</p>
                        <button class="btn btn-success" v-on:click="addItem(index)">Add to cart</button>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-5 col-lg-5-offset-1 col-xs-12">
            <div class="row">
                <div class="col-lg-4">
                    <h3>Cart</h3>
                </div>
                <div class="col-lg-8">
                    <h5 v-if="cart.length">Total: {{total() | currency}}</h5>
                </div>
            </div>
            <div v-for="item in cart">
                <div class="card card-inverse bg-inverse my-3">
                    <div class="card-block">
                        <h3 class="card-title">{{item.title}}</h3>

                        <p>Price: {{item.price | currency}} x {{item.qty}}</p>

                        <button class="btn btn-sm btn-danger" v-on:click="dec(item)">
                            <i class="fa fa-minus"></i>
                        </button>
                        <button class="btn btn-sm btn-success" v-on:click="inc(item)">
                            <i class="fa fa-plus"></i>
                        </button>
                    </div>
                </div>
            </div>
            <div>
                <div class="my-3" v-if="!cart.length">
                    No items in the cart
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Scripts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.js"></script>
<script type="text/javascript" src="public/script.js"></script>

</body>
</html>

here is solution 2:

new Vue({
    el: '#app',
    data: {
        items: [
            {
                id: 1,
                title: "Item 1",
                price: 50
            },
            {
                id: 2,
                title: "Item 2",
                price: 100
            },
            {
                id: 3,
                title: "Item 3",
                price: 50.5
            }
        ],
        cart: [],
        search: ''
    },
    methods: {
        total() {
            var t = 0;
            for(var i = 0; i < this.cart.length; i++) {
                var item = this.cart[i];
                t += item.price * item.qty;
            }

            return t;
        },
        addItem(index) {
            var item = this.items[index];
            var found = false;
            // if it's there, increment quantity:
            for(var i = 0; i < this.cart.length; i++) {
                let ic = this.cart[i];

                if(ic.id == item.id) {
                    ic.qty++;
                    found = true;
                    break;
                }
            }

            // if not, add it:
            if(!found) {
                this.cart.push({
                    title: item.title,
                    qty: 1,
                    id: item.id,
                    price: item.price
                });
            }
        },
        dec(item) {
            item.qty--;
            if(item.qty < 1) {
                item.qty = 1;

                // remove item from cart:
                for(var i = 0; i < this.cart.length; i++) {
                    if(this.cart[i].id == item.id) {
                        this.cart.splice(i, 1);
                        break;
                    }
                }
            }
        },
        inc(item) {
            // increment item on cart:
            item.qty++;
        },
        onSubmit() {
            console.log(this.search);
        }
    },
    filters: {
        currency(price) {
            return '$'.concat(price.toFixed(2));
        }
    }
});

body {
    background-color: #393C3D;
    color: #FFF;
}

.fa-margin-top {
  margin-top: 4px;
}

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Vue.js Poster Shop</title>
    <link rel="icon" href="public/favicon.ico" type="image/x-icon">

    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css?family=Luckiest+Guy" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Lato|Montserrat" rel="stylesheet">

    <!-- CSS -->
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <style type="text/css">
        body {
            background-color: #393C3D;
            color: #FFF;
        }
    </style>
</head>
<body>
<div class="container-fluid" id="app">
    <div class="row">
        <div class="col-lg-4 col-xs-12">
            <div class="card card-inverse bg-inverse my-3">
                <div class="card-block">
                    <h1 class="card-title">
                        Vue.js Poster Store
                        <button class="btn btn-sm btn-danger" v-on:click="dec(item)">
                            <i class="fa fa-minus fa-margin-top"></i>
                        </button>
                        <button class="btn btn-sm btn-success" v-on:click="inc(item)">
                            <i class="fa fa-plus fa-margin-top"></i>
                        </button>
                    </h1>
                    <form v-on:submit.prevent="onSubmit()">
                        <div class="input-group">
                            <input type="text"   class="form-control" v-model="search" placeholder="Search for...">
                            <span class="input-group-btn">
                                <button class="btn btn-primary" type="submit">Go!</button>
                            </span>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-lg-6 col-xs-12">
            <div class="row">
                <div class="col-lg-12">
                    <h3>Store</h3>
                </div>
            </div>
            <div v-for="(item, index) in items">
                <div class="card card-inverse bg-inverse my-3">
                    <div class="card-block">
                        <h3 class="card-title">{{item.title}}</h3>
                        <p class="card-text">Here goes the description</p>
                        <button class="btn btn-success" v-on:click="addItem(index)">Add to cart</button>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-5 col-lg-5-offset-1 col-xs-12">
            <div class="row">
                <div class="col-lg-4">
                    <h3>Cart</h3>
                </div>
                <div class="col-lg-8">
                    <h5 v-if="cart.length">Total: {{total() | currency}}</h5>
                </div>
            </div>
            <div v-for="item in cart">
                <div class="card card-inverse bg-inverse my-3">
                    <div class="card-block">
                        <h3 class="card-title">{{item.title}}</h3>

                        <p>Price: {{item.price | currency}} x {{item.qty}}</p>

                        <button class="btn btn-sm btn-danger" v-on:click="dec(item)">
                            <i class="fa fa-minus"></i>
                        </button>
                        <button class="btn btn-sm btn-success" v-on:click="inc(item)">
                            <i class="fa fa-plus"></i>
                        </button>
                    </div>
                </div>
            </div>
            <div>
                <div class="my-3" v-if="!cart.length">
                    No items in the cart
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Scripts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.2.6/vue.js"></script>
<script type="text/javascript" src="public/script.js"></script>

</body>
</html>


来源: stackexchange

问:
How to get Chef api credentials?
I am trying to use following script:
https://github.com/evanlok/chef-node-cleaner

Here the following variables are required:

CHEF_API_ENDPOINT
CHEF_API_CLIENT
CHEF_API_KEY

I could not find what would be the value of these variables.
CHEF_API_ENDPOINT may be the chef server url and CHEF_API_KEY is validator key. Not sure about these.
Please suggest what would be the value of these variables or how to get the value of these variables.
Thanks in advance!

答: You can create a new client with knife client create. You'll probably have to customize the ACLs to make sure it has the right permissions though. If you're unfamiliar with Chef client and ACL management, I probably wouldn't use this script.

ContentLicense: CC BY-SA 3.0

Title: How to get Chef api credentials?


问:
bootstrap collapse was overlayed by the div below
So I just used the default bootstrap navbar and collapse code to test:

You can see the code I used from here:http://getbootstrap.com/components/#navbar

I didn't change anything.It's pretty much the same code as they used in the Default navbar example.

```<code><nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
    <span class="sr-only">Toggle navigation</span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
  </button>
  <a class="navbar-brand" href="#">Brand</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
  <ul class="nav navbar-nav">
    <li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>
    <li><a href="#">Link</a></li>
    <li class="dropdown">
      <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
      <ul class="dropdown-menu">
        <li><a href="#">Action</a></li>
        <li><a href="#">Another action</a></li>
        <li><a href="#">Something else here</a></li>
        <li role="separator" class="divider"></li>
        <li><a href="#">Separated link</a></li>
        <li role="separator" class="divider"></li>
        <li><a href="#">One more separated link</a></li>
      </ul>
    </li>
  </ul>
  <form class="navbar-form navbar-left">
    <div class="form-group">
      <input type="text" class="form-control" placeholder="Search">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
  </form>
  <ul class="nav navbar-nav navbar-right">
    <li><a href="#">Link</a></li>
    <li class="dropdown">
      <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
      <ul class="dropdown-menu">
        <li><a href="#">Action</a></li>
        <li><a href="#">Another action</a></li>
        <li><a href="#">Something else here</a></li>
        <li role="separator" class="divider"></li>
        <li><a href="#">Separated link</a></li>
      </ul>
    </li>
  </ul>
</div><!-- /.navbar-collapse -->
</code>```

But the collpase is not expanding correctly on my site.It's overlayed by the div next to it.Illustrated in the pic.To see the problem clearly,I set the collpase.in backgroud-color as red,you can see it's overlayed by its next div getting on top of it.

I got all the bootstrap css and js files linked.

You can see the full code here to reproduce the prolem:https://eval.in/765747

What might be causing this?

答:
It is working properly here. I think it's a z-index problem. consider adding a high z-index to your navbar maybe 100.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
    Toggle navigation

  </button>
  Brand

Link (current)

Link

      Dropdown

Action

Another action

Something else here

Separated link

One more separated link

  <form class="navbar-form navbar-left">

      <input type="text" class="form-control" placeholder="Search">

    <button type="submit" class="btn btn-default">Submit</button>
  </form>

Link

      Dropdown

Action

Another action

Something else here

Separated link

```

Body:
So I just used the default bootstrap navbar and collapse code to test:

You can see the code I used from here:http://getbootstrap.com/components/#navbar

I didn't change anything.It's pretty much the same code as they used in the Default navbar example.

  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
    Toggle navigation

  </button>
  Brand

Link (current)

Link

      Dropdown

Action

Another action

Something else here

Separated link

One more separated link

  <form class="navbar-form navbar-left">

      <input type="text" class="form-control" placeholder="Search">

    <button type="submit" class="btn btn-default">Submit</button>
  </form>

Link

      Dropdown

Action

Another action

Something else here

Separated link

But the collpase is not expanding correctly on my site.It's overlayed by the div next to it.Illustrated in the pic.To see the problem clearly,I set the collpase.in backgroud-color as red,you can see it's overlayed by its next div getting on top of it.

I got all the bootstrap css and js files linked.

You can see the full code here to reproduce the prolem:https://eval.in/765747

What might be causing this?

Body:
It is working properly here. I think it's a z-index problem. consider adding a high z-index to your navbar maybe 100.

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
  <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
    <span class="sr-only">Toggle navigation</span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
  </button>
  <a class="navbar-brand" href="#">Brand</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
  <ul class="nav navbar-nav">
    <li class="active"><a href="#">Link <span class="sr-only">(current)</span></a></li>
    <li><a href="#">Link</a></li>
    <li class="dropdown">
      <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
      <ul class="dropdown-menu">
        <li><a href="#">Action</a></li>
        <li><a href="#">Another action</a></li>
        <li><a href="#">Something else here</a></li>
        <li role="separator" class="divider"></li>
        <li><a href="#">Separated link</a></li>
        <li role="separator" class="divider"></li>
        <li><a href="#">One more separated link</a></li>
      </ul>
    </li>
  </ul>
  <form class="navbar-form navbar-left">
    <div class="form-group">
      <input type="text" class="form-control" placeholder="Search">
    </div>
    <button type="submit" class="btn btn-default">Submit</button>
  </form>
  <ul class="nav navbar-nav navbar-right">
    <li><a href="#">Link</a></li>
    <li class="dropdown">
      <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown <span class="caret"></span></a>
      <ul class="dropdown-menu">
        <li><a href="#">Action</a></li>
        <li><a href="#">Another action</a></li>
        <li><a href="#">Something else here</a></li>
        <li role="separator" class="divider"></li>
        <li><a href="#">Separated link</a></li>
      </ul>
    </li>
  </ul>
</div><!-- /.navbar-collapse -->


问:
regarding print out os.environ variables
There is a code segment in one Python program. It runs fine.

```<code>if 'TV_DIR_RUNS' in os.environ:
    os.environ['TV_DIR_RUNS'] = os.path.join(os.environ['TV_DIR_RUNS'],'Seg')
</code>```

I was trying to take a look at os.environ['TV_DIR_RUNS'], by adding a print function.

```<code>if 'TV_DIR_RUNS' in os.environ:
    os.environ['TV_DIR_RUNS'] =    os.path.join(os.environ['TV_DIR_RUNS'],'KittiSeg')
print(os.environ['TV_DIR_RUNS'])
</code>```

Then running the program generates the following error message

```<code>File "train.py", line 107, in main
print(os.environ['TV_DIR_RUNS'])
File "/devl/lib/python3.4/os.py", line 635, in __getitem__
raise KeyError(key) from None
KeyError: 'TV_DIR_RUNS'
</code>```

This really confuses me, because it seems to me that os.environ['TV_DIR_RUNS'] =    os.path.join(os.environ['TV_DIR_RUNS'],'KittiSeg') can be executed successfully, why it cannot be printed out?

答:
I think you'll find that 'TV_DIR_RUNS' is not in os.environ. Change your line to print(os.environ.get('TV_DIR_RUNS'))

The line os.environ['TV_DIR_RUNS'] = ... is inside the block of the if statement, checking if 'TV_DIR_RUNS' is in os.environ.

Body:
There is a code segment in one Python program. It runs fine.

if 'TV_DIR_RUNS' in os.environ:
    os.environ['TV_DIR_RUNS'] = os.path.join(os.environ['TV_DIR_RUNS'],'Seg')

I was trying to take a look at os.environ['TV_DIR_RUNS'], by adding a print function.

if 'TV_DIR_RUNS' in os.environ:
    os.environ['TV_DIR_RUNS'] =    os.path.join(os.environ['TV_DIR_RUNS'],'KittiSeg')
print(os.environ['TV_DIR_RUNS'])

Then running the program generates the following error message

File "train.py", line 107, in main
print(os.environ['TV_DIR_RUNS'])
File "/devl/lib/python3.4/os.py", line 635, in __getitem__
raise KeyError(key) from None
KeyError: 'TV_DIR_RUNS'

This really confuses me, because it seems to me that os.environ['TV_DIR_RUNS'] =    os.path.join(os.environ['TV_DIR_RUNS'],'KittiSeg') can be executed successfully, why it cannot be printed out?


问:
Double versus float
I have a constant for pi in my code:

const float PI = acos(-1);

Would it be better to declare it as a double?  An answer to another question on this site said floating point operations aren't exactly precise, and I'd like the constant to be accurate.

答:
I'd like the constant to be accurate.

There is nothing like accurate floating point values. They cannot be stored with perfect precision, because of their representation in memory. This is only possible with integers. double give you double the precision a float offers (who would have guessed). double should fit your needs in almost every case.

I would recommend using M_PI from <cmath>, which should be available in all POSIX compliant implementations of the standard.

ContentLicense: CC BY-SA 2.5

Title: Double versus float


问:
Angular Modal window
I've got my modal window in Angular JS. Could some body answer me how to add blur effect to body when I open this modal window.

```<code>vm.OpenLogin = function () {
            var data = loginWizardService.getData().then(function (response) {
                $("#loginWizard").append($compile(response.data)($scope));

                $rootScope.modalInstance = $uibModal.open({
                    templateUrl: templUrl,
                    controller: OpenLoginWizardCtrl,
                    backdrop: 'static',
                    keyboard: false
                });
            });
        };
</code>```

答:
Maybe someone knows a more correct solution to this problem. But I found a solution for myself.

```<code>(function () {
    'use strict';

    angular
        .module('app.modal.window.open.service', [])
        .factory('$modalWindowService', $modalWindowService);

    $modalWindowService.inject = ["$http", "$uibModal", "$compile"];

    function $modalWindowService($http, $uibModal, $compile) {

        var modalInstance;

        return {
            openModal: function (urn, id, templateId, controller) {
                $http({
                    method: 'GET',
                    url: urn
                }).success(function (data, $scope) {
                    $("#" + id).append($compile(data)($scope));
                    modalInstance = $uibModal.open({
                        templateUrl: templateId,
                        controller: controller,
                        backdrop: 'static',
                        keyboard: false
                    });
                    return;
                }).error(function () {
                    alert("error");
                    return null;
                });
                document.getElementById('main').classList.add("blur");
            },
            closeModal: function (templateId, controller) {
                if (modalInstance !== undefined) {
                    modalInstance.close({
                        templateUrl: templateId,
                        controller: controller
                    });
                }
                document.getElementById('main').classList.remove("blur");
            }
        }
     }
})();
</code>```

enjoy it :)

Title: Angular Modal window

Body:
I've got my modal window in Angular JS. Could some body answer me how to add blur effect to body when I open this modal window.

vm.OpenLogin = function () {
            var data = loginWizardService.getData().then(function (response) {
                $("#loginWizard").append($compile(response.data)($scope));

                $rootScope.modalInstance = $uibModal.open({
                    templateUrl: templUrl,
                    controller: OpenLoginWizardCtrl,
                    backdrop: 'static',
                    keyboard: false
                });
            });
        };

Body:
Maybe someone knows a more correct solution to this problem. But I found a solution for myself.

(function () {
    'use strict';

    angular
        .module('app.modal.window.open.service', [])
        .factory('$modalWindowService', $modalWindowService);

    $modalWindowService.inject = ["$http", "$uibModal", "$compile"];

    function $modalWindowService($http, $uibModal, $compile) {

        var modalInstance;

        return {
            openModal: function (urn, id, templateId, controller) {
                $http({
                    method: 'GET',
                    url: urn
                }).success(function (data, $scope) {
                    $("#" + id).append($compile(data)($scope));
                    modalInstance = $uibModal.open({
                        templateUrl: templateId,
                        controller: controller,
                        backdrop: 'static',
                        keyboard: false
                    });
                    return;
                }).error(function () {
                    alert("error");
                    return null;
                });
                document.getElementById('main').classList.add("blur");
            },
            closeModal: function (templateId, controller) {
                if (modalInstance !== undefined) {
                    modalInstance.close({
                        templateUrl: templateId,
                        controller: controller
                    });
                }
                document.getElementById('main').classList.remove("blur");
            }
        }
     }
})();

enjoy it :)


问:
Can a slack bot message another bot?
I have a bot, and I can interact with it.  And there's another bot, and I would like my bot to chat with that bot, when they are in the same channel.  Is that even possible?

I tried to include a mention like <@IDBOT|name>: text, and even though it appears to me that the mention was successful, the other bot doesn't respond.  If I post this mention it will work.

Is there a limitation here?

答:
Yes, bots can talk to each other in a channel.

It depends on how you control the listening bot. I'm using a fork of the official Python Slackbot code (https://github.com/bscan/python-slackbot) and in it, I check for <@U1234567> where U1234567 is the user_id of the bot. When you mention @mybot, Slack replaces @mybot with <@U1234567> in the message. However, when posting as a bot, Slack doesn't replace a callout with the user_id. Instead, a bot can directly put <@U1234567> in the message (and post using as_user=True). Slack will display <@U1234567> as @mybot in the channel and the bot will be able to detect it if looking for that exact message string.

Source: played around until bots talked to each other.

Title: Can a slack bot message another bot?


问:
spark rdd how to flat Key - Array(value) pair
I have a park paired rdd (key, Array(value1, value2, value3.....)).
what scala statement should I wrote?
How could I flat this rdd and creating a new rdd : (key, value1), (key, value2), (key, value3)....</p>

答:
```<code>rdd.flatMap{case (k,v) => v.map(vx => (k,vx))}
</code>```


问:
How to divide different divs on the same line along the width of a device in different resolutions?
I have a list of projects consists of multiples lines.Each line consists of 3 divs:

The first contain a logo.

The second contains the title, state and the date of the project.

The third contains some more infos.

I want to put the 3 divs on the same line and take in consideration the width of different resolutions of device into the display of the page.
index.html:

As a result I got the logo in a line and the two other divs in another line.How can I fix that?

#list_project {
  position: relative;
  top: 120px;
  z-index: 1;
}

.project_logo {
  display: block;
  height: 60px;
}

.project_title {
  font-size: 18px;
  font-family: "Arial";
  color: #000000;
  font-weight: bold;
  line-height: 1.2;
}

.project_status {
  font-size: 18px;
  font-family: "Arial Round MT Bold";
  color: #8e8e8e;
  line-height: 1.2;
}

.project_date {
  font-size: 18px;
  font-family: "Arial";
  color: #8e8e8e;
  line-height: 1.2;
}

.project_info_1 {
  border-radius: 10px;
  background-color: #e6e1e1;
  height: 63px;
}

.project_cost {
  font-size: 16px;
  font-family: "Arial";
  color: #000000;
  font-weight: bold;
  line-height: 1.2;
}

.project_cost_1 {
  font-size: 16px;
  font-family: "Arial";
  color: #8e8e8e;
  font-weight: bold;
  line-height: 1.2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="list_project">
  <div class="container-fluid">
    <div class="row">
      <div class="col col-sm-4 col-md-4 col-lg-4 col-xl-4">
        <img class="project_logo" src="./logos/logo.png" />
      </div>
      <div class="col col-sm-4 col-md-4 col-lg-4 col-xl-4">
        <table>
          <tbody>
            <tr>
              <td class="project_title"> Project 1 </td>
            </tr>
            <tr>
              <td class="project_status">Active</td>
            </tr>
            <tr>
              <td class="project_date">03/2017-05/2018</td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="col col-sm-4 col-md-4 col-lg-4 col-xl-4">
        <table class="project_info_1">
          <tbody>
            <tr>
              <td class="project_cost" name="project_cost">Cost:</td>
              <td class="project_cost_1" name="project_cost_1">140.000k$.</td>
            </tr>
            <tr>
              <td class="project_cost" name="project_delay">Delay:</td>
              <td class="project_cost_1" name="project_delay_1">350 days.</td>
            </tr>
            <tr>
              <td class="project_cost" name="project_load">Load:</td>
              <td class="project_cost_1" name="project_load_1">125 days.</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div></code>```

答: 'Class' is misspelled. You have used 'clas' instead of "class"</p>

Body:
I have a list of projects consists of multiples lines.Each line consists of 3 divs:

The first contain a logo.

The second contains the title, state and the date of the project.

The third contains some more infos.

I want to put the 3 divs on the same line and take in consideration the width of different resolutions of device into the display of the page.
index.html:

As a result I got the logo in a line and the two other divs in another line.How can I fix that?

#list_project {
  position: relative;
  top: 120px;
  z-index: 1;
}

.project_logo {
  display: block;
  height: 60px;
}

.project_title {
  font-size: 18px;
  font-family: "Arial";
  color: #000000;
  font-weight: bold;
  line-height: 1.2;
}

.project_status {
  font-size: 18px;
  font-family: "Arial Round MT Bold";
  color: #8e8e8e;
  line-height: 1.2;
}

.project_date {
  font-size: 18px;
  font-family: "Arial";
  color: #8e8e8e;
  line-height: 1.2;
}

.project_info_1 {
  border-radius: 10px;
  background-color: #e6e1e1;
  height: 63px;
}

.project_cost {
  font-size: 16px;
  font-family: "Arial";
  color: #000000;
  font-weight: bold;
  line-height: 1.2;
}

.project_cost_1 {
  font-size: 16px;
  font-family: "Arial";
  color: #8e8e8e;
  font-weight: bold;
  line-height: 1.2;
}

               Project 1

              Active

              03/2017-05/2018

              Cost:
              140.000k$.

              Delay:
              350 days.

              Load:
              125 days.


问:
How to inject property values into Spring Boot beans
In my spring boot application, i'am trying to inject variable's value from the config file application.properties to my java class and i'm getting a null value.

here is the configuration of my application.properties file:

```<code>  myapp.username=user@user.com
  myapp.password=user
</code>```

here is where i call the configuration entries:

```<code>@Component
public class MyClass{

        @Value("${myapp.username}")
        public String username;

        @Value("${myapp.password}")
        public String password;

        public static void main(String[] args)  {

             System.out.println(password);
        }

  }
</code>```

I hope there someone how did deal with the same problem, thanks.

答:
you can use this example  add bean to your config like this :

```<code>@Configuration
@ComponentScan(basePackages = "youpackagebase")
@PropertySource(value = { "classpath:application.properties" })
public class AppConfig {

    /*
     * PropertySourcesPlaceHolderConfigurer Bean only required for @Value("{}") annotations.
     * Remove this bean if you are not using @Value annotations for injecting properties.
     */
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
</code>```

}

and in your  bean  :

```<code>@Component
public class NetClient {

@Value("${bigwater.api_config.url.login}")
public String url_login;
</code>```

Best Regards

Body:
In my spring boot application, i'am trying to inject variable's value from the config file application.properties to my java class and i'm getting a null value.

here is the configuration of my application.properties file:

  myapp.username=user@user.com
  myapp.password=user

here is where i call the configuration entries:

@Component
public class MyClass{

        @Value("${myapp.username}")
        public String username;

        @Value("${myapp.password}")
        public String password;

        public static void main(String[] args)  {

             System.out.println(password);
        }

  }

I hope there someone how did deal with the same problem, thanks.

Body:
you can use this example  add bean to your config like this :

@Configuration
@ComponentScan(basePackages = "youpackagebase")
@PropertySource(value = { "classpath:application.properties" })
public class AppConfig {

    /*
     * PropertySourcesPlaceHolderConfigurer Bean only required for @Value("{}") annotations.
     * Remove this bean if you are not using @Value annotations for injecting properties.
     */
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}

and in your  bean  :

@Component
public class NetClient {

@Value("${bigwater.api_config.url.login}")
public String url_login;

Best Regards


问:
User-defined function returns non-formattable dates Excel VBA
I created a UDF in Excel VBA that returns an multi-dimensional array of dates and doubles. The problem is that I cannot format the dates that are returned.

Here is a simplified example:

```<code>Function test(dates as Range)
    Dim results
    Dim i As Integer
    ReDim results(1 To dates.Cells.Count)
    For i = 1 To dates.Cells.Count
        results(i) = dates.Cells(i).Value
    Next
    test = Application.WorksheetFunction.Transpose(results)
End Function
</code>```

The transpose at the end is just for convenience to have an column output (I press Ctrl+Shift+enter). I you use this simplified example, you will not be able to format the output and it will not be considered as dates stricto sensu.

Any ideas?

答:
Change the results array to doubles:

```<code>Function test(dates As Range)
    Dim results() As Double
    Dim i As Integer
    ReDim results(1 To dates.Cells.Count)
    For i = 1 To dates.Cells.Count
        results(i) = dates.Cells(i).Value
    Next
    test = Application.WorksheetFunction.Transpose(results)
End Function
</code>```

Or change the dates.Cells(i).Value to dates.Cells(i).Value2 which will return the double not the date string:

```<code>Function test(dates As Range)
    Dim results
    Dim i As Integer
    ReDim results(1 To dates.Cells.Count)
    For i = 1 To dates.Cells.Count
        results(i) = dates.Cells(i).Value2
    Next
    test = Application.WorksheetFunction.Transpose(results)
End Function
</code>```

Then format the cells as you desire.

Body:
I created a UDF in Excel VBA that returns an multi-dimensional array of dates and doubles. The problem is that I cannot format the dates that are returned.

Here is a simplified example:

Function test(dates as Range)
    Dim results
    Dim i As Integer
    ReDim results(1 To dates.Cells.Count)
    For i = 1 To dates.Cells.Count
        results(i) = dates.Cells(i).Value
    Next
    test = Application.WorksheetFunction.Transpose(results)
End Function

The transpose at the end is just for convenience to have an column output (I press Ctrl+Shift+enter). I you use this simplified example, you will not be able to format the output and it will not be considered as dates stricto sensu.

Any ideas?

Body:
Change the results array to doubles:

Function test(dates As Range)
    Dim results() As Double
    Dim i As Integer
    ReDim results(1 To dates.Cells.Count)
    For i = 1 To dates.Cells.Count
        results(i) = dates.Cells(i).Value
    Next
    test = Application.WorksheetFunction.Transpose(results)
End Function

Or change the dates.Cells(i).Value to dates.Cells(i).Value2 which will return the double not the date string:

Function test(dates As Range)
    Dim results
    Dim i As Integer
    ReDim results(1 To dates.Cells.Count)
    For i = 1 To dates.Cells.Count
        results(i) = dates.Cells(i).Value2
    Next
    test = Application.WorksheetFunction.Transpose(results)
End Function

Then format the cells as you desire.


问:
Onclick an element, sliding toggle of div
I am trying to do an accordian style opening/closing of div using jquery. But for some reason the next() in jquery doesn't seem to be working. I want when a title is clicked, all other div should be closed except the clicked one.

Html code --

```<code><div class="office-row">
  <h3 class="office-title">Title</h3>
</div>
<div class="office">sadasd</div>
<div class="office-row">
  <h3 class="office-title">Title</h3>
</div>
<div class="office">sadasd</div>
<div class="office-row">
  <h3 class="office-title">Title</h3>
</div>
</code>```

Demo -- https://jsfiddle.net/v3hc19np/1/

Any help is highly appreciated.

答:
we can loop the elements and display them none using jquery and then use toggle function here is the working code for you query</p>

```<code> $('.office-title').click(function() {
    $(".office").each(function(index,obj){
        $(obj).hide();
    });
    $(e.target).parent().next().slideToggle();
    return false;
  });
</code>```

Body:
I am trying to do an accordian style opening/closing of div using jquery. But for some reason the next() in jquery doesn't seem to be working. I want when a title is clicked, all other div should be closed except the clicked one.

Html code --

Title

sadasd

Title

sadasd

Title

Demo -- https://jsfiddle.net/v3hc19np/1/

Any help is highly appreciated.

Body:
we can loop the elements and display them none using jquery and then use toggle function here is the working code for you query

 $('.office-title').click(function() {
    $(".office").each(function(index,obj){
        $(obj).hide();
    });
    $(e.target).parent().next().slideToggle();
    return false;
  });


问:
Get last 3 words from the string?
How do you get last 3 words from the string?

I managed to get working doing like this:

```<code>$statusMessage = explode(" ", str_replace(' '," ",$retStatus->plaintext));
$SliceDate = array_slice($statusMessage, -3, 3);
$date = implode(" ", $SliceDate);
echo $date;
</code>```

Is there a shorter way? Maybe there is a PHP function that I did not know..

答:
preg_match("/(?:\w+\s*){1,3}$/", $input_line, $output_array);

this catches 1 to 3 words and if the row is only 3 long, other regex one was close

Title: Get last 3 words from the string?

Body:
How do you get last 3 words from the string?

I managed to get working doing like this:

$statusMessage = explode(" ", str_replace(' '," ",$retStatus->plaintext));
$SliceDate = array_slice($statusMessage, -3, 3);
$date = implode(" ", $SliceDate);
echo $date;

Is there a shorter way? Maybe there is a PHP function that I did not know..


问:
ERROR - Additional information: Format of the initialization string does not conform to specification starting at index 0
Using Microsoft Visual Studio Community - deploying through Azure.

I have been stuck on this problem for 5 days. While trying to save user answers to a quiz, I KEEP getting this error. I have looked through so many other solutions to people asking the same thing and have not found any of them fixes my solution. This is the full error:

An exception of type 'System.ArgumentException' occurred in System.Data.dll but was not handled in user code
  Additional information: Format of the initialization string does not conform to specification starting at index 0.

I have looked and relooked at my connection string and code itself and have not found anything wrong.

Here is my code :

```<code>@using WebMatrix.Data;
@{
    Layout = "~/Views/Shared/_Layout.cshtml";

var Q1 = "";
var Q2 = "";
var Q3 = "";
var Q4 = "";
var Q5 = "";
var Q6 = "";
var Q7 = "";
var Q8 = "";
var Q9 = "";
var Q10 = "";
var weeknum = "";

if (IsPost)
{
    Q1 = Request.Form["Question1"];
    Q2 = Request.Form["Question2"];
    Q3 = Request.Form["Question3"];
    Q4 = Request.Form["Question4"];
    Q5 = Request.Form["Question5"];
    Q6 = Request.Form["Question6"];
    Q7 = Request.Form["Question7"];
    Q8 = Request.Form["Question8"];
    Q9 = Request.Form["Question9"];
    Q10 = Request.Form["Question10"];
    weeknum = "1";

    var db = Database.OpenConnectionString("PayForPlay", "System.Data.SqlClient");
    var insertCommand = "INSERT INTO  PayForPlay.WeeklyPredictions (WeekNumber, Question1, Question2, Question3, Question4, Question5, Question6, Question7, Question8, Question9, Question10) Values(@0, @1, @2, @3, @4, @5, @6, @7, @8, @9, @10) ";

    db.Execute(insertCommand, weeknum, Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10);
    Response.Redirect("~/Home/Submitted");
</code>```

Here is my connection string:

```<code><connectionStrings>
    <add name=“PayForPlay"
    providerName="System.Data.SqlClient"
    connectionString="Data Source=tcp:memberships2016.database.windows.net,1433;Initial Catalog=PayForPlay;Integrated Security=False;User Id=annah@memberships2016;Password=Annie207!;Encrypt=True;TrustServerCertificate=False;MultipleActiveResultSets=True" />
    <!--<add name="PayForPlay" connectionString="Data Source=memberships2016.database.windows.net;Initial Catalog=PayForPlay;Integrated Security=False;User ID=annah;Password=*********;Connect Timeout=15;Encrypt=True;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False " /> -->
</connectionStrings>
</code>```

The part of my connection string that is commented is another connection string I tried (following azure format) and it didn't work.

答:
WebMatrix.Data.OpenConnectionString, as far as I understands, wants a full connectionstring, not the key name of a connectionstring stored in the config file.

The OpenConnectionString method differs from the Open method, which
  uses the name of a connection string that is stored in the Web.config
  file. You might use the OpenConnectionString method when a connection
  string is programmatically generated or is provided by the user.

And this explains why that method cannot understand your 'PayForPlay' as a connectionstring. It expects to see a "Data Source=memberships2016....."

On the contrary, reading the documentation of the suggested Open method you can see:

The Open(String) method can connect to a database in two ways. The
  Open(String) method first searches the Web application's App_Data
  folder for a database file that matches the name that is passed
  (without the file-name extension) to the method. If no matching
  database file is found, the method searches the application's
  Web.config file for a connection string that matches name.

So, it seems that your problem should be solved using the Open method with

```<code>var db = Database.Open("PayForPlay");
</code>```

Body:
Using Microsoft Visual Studio Community - deploying through Azure.

I have been stuck on this problem for 5 days. While trying to save user answers to a quiz, I KEEP getting this error. I have looked through so many other solutions to people asking the same thing and have not found any of them fixes my solution. This is the full error:

An exception of type 'System.ArgumentException' occurred in System.Data.dll but was not handled in user code
  Additional information: Format of the initialization string does not conform to specification starting at index 0.

I have looked and relooked at my connection string and code itself and have not found anything wrong.

Here is my code :

@using WebMatrix.Data;
@{
    Layout = "~/Views/Shared/_Layout.cshtml";

var Q1 = "";
var Q2 = "";
var Q3 = "";
var Q4 = "";
var Q5 = "";
var Q6 = "";
var Q7 = "";
var Q8 = "";
var Q9 = "";
var Q10 = "";
var weeknum = "";

if (IsPost)
{
    Q1 = Request.Form["Question1"];
    Q2 = Request.Form["Question2"];
    Q3 = Request.Form["Question3"];
    Q4 = Request.Form["Question4"];
    Q5 = Request.Form["Question5"];
    Q6 = Request.Form["Question6"];
    Q7 = Request.Form["Question7"];
    Q8 = Request.Form["Question8"];
    Q9 = Request.Form["Question9"];
    Q10 = Request.Form["Question10"];
    weeknum = "1";

    var db = Database.OpenConnectionString("PayForPlay", "System.Data.SqlClient");
    var insertCommand = "INSERT INTO  PayForPlay.WeeklyPredictions (WeekNumber, Question1, Question2, Question3, Question4, Question5, Question6, Question7, Question8, Question9, Question10) Values(@0, @1, @2, @3, @4, @5, @6, @7, @8, @9, @10) ";

    db.Execute(insertCommand, weeknum, Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10);
    Response.Redirect("~/Home/Submitted");

Here is my connection string:

<connectionStrings>
    <add name=“PayForPlay"
    providerName="System.Data.SqlClient"
    connectionString="Data Source=tcp:memberships2016.database.windows.net,1433;Initial Catalog=PayForPlay;Integrated Security=False;User Id=annah@memberships2016;Password=Annie207!;Encrypt=True;TrustServerCertificate=False;MultipleActiveResultSets=True" />

</connectionStrings>

The part of my connection string that is commented is another connection string I tried (following azure format) and it didn't work.

Body:
WebMatrix.Data.OpenConnectionString, as far as I understands, wants a full connectionstring, not the key name of a connectionstring stored in the config file.

The OpenConnectionString method differs from the Open method, which
  uses the name of a connection string that is stored in the Web.config
  file. You might use the OpenConnectionString method when a connection
  string is programmatically generated or is provided by the user.

And this explains why that method cannot understand your 'PayForPlay' as a connectionstring. It expects to see a "Data Source=memberships2016....."

On the contrary, reading the documentation of the suggested Open method you can see:

The Open(String) method can connect to a database in two ways. The
  Open(String) method first searches the Web application's App_Data
  folder for a database file that matches the name that is passed
  (without the file-name extension) to the method. If no matching
  database file is found, the method searches the application's
  Web.config file for a connection string that matches name.

So, it seems that your problem should be solved using the Open method with

var db = Database.Open("PayForPlay");


问:
Not able to run xsjs file, error: site can't be reached
I am using office network to learn SAP HANA, to connect to HANA system I have to first connect to VPN then only the HANA system gets online. I configured a simple project XS application but when I try to run it, it shows the below error :

hana01’s server DNS address could not be found.

The URL which gets generated is https://hana01:4300/SampleXSapp/main.xsjs

I have no idea from where it is picking up "hana01:4300"

The online tutorial had port 8000 for running it

If I disconnect from VPN, then my HANA system goes down and the icon changes to gray from green.

I am attaching files and screenshot in case, you may check it what is wrong with any piece of code. Also please tell me if I had to make some changes in the Network to resolve this particular error.

My file main.xsjs:

```<code>$.response.contentType = "text/html";
var output;
output = "Hello World! This is a demo of simple SAP HANA Extended Services Application. Stay tuned to learn more.";
$.response.setBody(output);
</code>```

My .xsaccess file:

```<code>{
     "exposed" : true,
     "authentication" :  [{ "method": "Basic" }]
}
</code>```

.xsapp file has no content.

My HANA System:

I made same program in HANA Cloud platform there I can run my system,

Please advice on how to get this resolved, thanks in advance.

答:
In HANA Studio, if you right click on the connection name (H01), then hit "Properties", you will see the address used for the XS engine under "XS Properties".
This is the address used when you hit the run button in HANA Studio from what I understood.
I recommend you to change it with the IP address (172.30.170.00), as you might not have "HANA01" mapped properly in your host file.

The port 4300 is the default one used for HTTPS when your instance id is 00, which is your case. And HTTP is 8000.

But this is for HANA XS Classic as XS Advanced uses different ports.

You can always adapt the URL address generated while running you xsjs file from HANA Studio and the get the proper one to fix the "XS Properties".

Hope this helps

ContentLicense: CC BY-SA 4.0

Body:
I am using office network to learn SAP HANA, to connect to HANA system I have to first connect to VPN then only the HANA system gets online. I configured a simple project XS application but when I try to run it, it shows the below error :

hana01’s server DNS address could not be found.

The URL which gets generated is https://hana01:4300/SampleXSapp/main.xsjs

I have no idea from where it is picking up "hana01:4300"

The online tutorial had port 8000 for running it

If I disconnect from VPN, then my HANA system goes down and the icon changes to gray from green.

I am attaching files and screenshot in case, you may check it what is wrong with any piece of code. Also please tell me if I had to make some changes in the Network to resolve this particular error.

My file main.xsjs:

$.response.contentType = "text/html";
var output;
output = "Hello World! This is a demo of simple SAP HANA Extended Services Application. Stay tuned to learn more.";
$.response.setBody(output);

My .xsaccess file:

{
     "exposed" : true,
     "authentication" :  [{ "method": "Basic" }]
}

.xsapp file has no content.

My HANA System:

I made same program in HANA Cloud platform there I can run my system,

Please advice on how to get this resolved, thanks in advance.


问:
my django server running at 127.0.0.1:8000/blog how to change become 127.0.0.1:8000
My Django server is running on 127.0.0.1:8000/blog. How can I change this to become 127.0.0.1:8000.

url.py

```<code>from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
]
</code>```

答: Where is your "/blog" url defined? Change it to "/". Should be in your app/urls.py file.</p>

Body:
My Django server is running on 127.0.0.1:8000/blog. How can I change this to become 127.0.0.1:8000.

url.py

from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
]


问:
Where to draw the line - is it possible to love LINQ too much?
I recently found LINQ and love it.  I find lots of occasions where use of it is so much more expressive than the longhand version but a colleague passed a comment about me abusing this technology which now has me second guessing myself.  It is my perspective that if a technology works efficiently and the code is elegant then why not use it?  Is that wrong?  I could spend extra time writing out processes "longhand" and while the resulting code may be a few ms faster, it's 2-3 times more code and therefore 2-3 times more chance that there may be bugs.

Is my view wrong?  Should I be writing my code out longhand rather than using LINQ?  Isn't this what LINQ was designed for?

Edit: I was speaking about LINQ to objects, I don't use LINQ to XML so much and I have used LINQ to SQL but I'm not so enamoured with those flavours as LINQ to objects.

答: LINQ can be like art. Keep using it to make the code beautiful.</p>

LastEditorDisplayName: BobTheBuilder

OwnerDisplayName: Jimmy Bergmark - JTB World


答:
From standard:

There are three ﬂoating point types:
  float, double, and long double. The
  type double provides at least as much
  precision as float, and the type long
  double provides at least as much
  precision as double.

Of the three (notice that this goes hand in hand with the 3 versions of acos) you should choose long double if what you are aiming for is precision (but you should also know that after some degree, further precision may be redundant in some cases).

So you should use this to get the most precise result from acos

```<code>long double result = acos(-1L);
</code>```

(Note: There might be some platform specific types or some user defined types which provide more precision)

Title: Double versus float

Body:
I have a constant for pi in my code:

const float PI = acos(-1);

Would it be better to declare it as a double?  An answer to another question on this site said floating point operations aren't exactly precise, and I'd like the constant to be accurate.

Body:
From standard:

There are three ﬂoating point types:
  float, double, and long double. The
  type double provides at least as much
  precision as float, and the type long
  double provides at least as much
  precision as double.

Of the three (notice that this goes hand in hand with the 3 versions of acos) you should choose long double if what you are aiming for is precision (but you should also know that after some degree, further precision may be redundant in some cases).

So you should use this to get the most precise result from acos

long double result = acos(-1L);

(Note: There might be some platform specific types or some user defined types which provide more precision)


问:
Merging two XML files on a key field
Let's say I have the following two XML files with the following structure:

```<code><supervisors>
     <supervisor id="1">
         <firstName>John</firstName>
         <lastName>Smith</lastName>
         <department>IT</department>
     </supervisor>
     <supervisor id="2">
         <firstName>Jack</firstName>
         <lastName>Jones</lastName>
         <department>HR</department>
     </supervisor>
     <supervisor id="3">
         <firstName>Allan</firstName>
         <lastName>Johnson</lastName>
         <department>Sales</department>
     </supervisor>
     <supervisor id="4">
         <firstName>Chris</firstName>
         <lastName>Reyes</lastName>
         <department>Shipping</department>
     </supervisor>
</supervisors>

<employees>
     <employee supervisorID="1" employeeID="2">
         <firstName>Mike</firstName>
         <lastName>Albert</lastName>
         <phone>1111111111</phone>
     </employee>
     <employee supervisorID="1" employeeID="3">
         <firstName>Alicia</firstName>
         <lastName>James</lastName>
         <phone>1112222222</phone>
     </employee>
     <employee supervisorID="3" employeeID="4">
         <firstName>Anne</firstName>
         <lastName>Thomas</lastName>
         <phone>1112223333</phone>
     </employee>
</employees>
</code>```

I want to wind up with a dataset that looks like this JSON (it can be an actual dataset, but for this I am showing JSON because it is easier to represent):

```<code>[
     {empFName: "Mike", empLName: "Albert", supFName: "John", supLName: "Smith", dept: "IT"},
     {empFName: "Alicia", empLName: "James", supFName: "John", supLName: "Smith", dept: "IT"},
     {empFName: "Anne", empLName: "Thomas", supFName: "Allan", supLName: "Johnson", dept: "Sales"}
 ]
</code>```

How do I combine the XML data to properly return the way the JSON above is returned?

答:
Using LINQ to XML makes this easy, and XML literals make it beautiful (if you are in to that sort of thing) - LINQPad example:

Dim supervisors =
<supervisors>
     <supervisor id="1">
         <firstName>John</firstName>
         <lastName>Smith</lastName>
         <department>IT</department>
     </supervisor>
     <supervisor id="2">
         <firstName>Jack</firstName>
         <lastName>Jones</lastName>
         <department>HR</department>
     </supervisor>
     <supervisor id="3">
         <firstName>Allan</firstName>
         <lastName>Johnson</lastName>
         <department>Sales</department>
     </supervisor>
     <supervisor id="4">
         <firstName>Chris</firstName>
         <lastName>Reyes</lastName>
         <department>Shipping</department>
     </supervisor>
</supervisors>

Dim employees =
<employees>
     <employee supervisorID="1" employeeID="2">
         <firstName>Mike</firstName>
         <lastName>Albert</lastName>
         <phone>1111111111</phone>
     </employee>
     <employee supervisorID="1" employeeID="3">
         <firstName>Alicia</firstName>
         <lastName>James</lastName>
         <phone>1112222222</phone>
     </employee>
     <employee supervisorID="3" employeeID="4">
         <firstName>Anne</firstName>
         <lastName>Thomas</lastName>
         <phone>1112223333</phone>
     </employee>
</employees>

Dim joined = (
    From e In employees.<employee>
    Join s In supervisors.<supervisor> On e.@supervisorID Equals s.@id
    Select New With {
        .empFName = e.<firstName>.Value,
        .empLName = e.<lastName>.Value,
        .supFName = s.<firstName>.Value,
        .supLName = s.<lastName>.Value,
        .dept = s.<department>.Value
    }
)

joined.Dump()
```

<p>This results in:</p>

<p><img src="https://i.stack.imgur.com/Q7keq.png" alt="LINQPad output"></p>

<p>Json.NET can convert that to JSON.</p>

```Dim json = JsonConvert.SerializeObject(joined)
json.Dump()
```

```[
    {"empFName":"Mike","empLName":"Albert","supFName":"John","supLName":"Smith","dept":"IT"},
    {"empFName":"Alicia","empLName":"James","supFName":"John","supLName":"Smith","dept":"IT"},
    {"empFName":"Anne","empLName":"Thomas","supFName":"Allan","supLName":"Johnson","dept":"Sales"}
]
```

Title: Merging two XML files on a key field

Body:
Let's say I have the following two XML files with the following structure:

<supervisors>
     <supervisor id="1">
         <firstName>John</firstName>
         <lastName>Smith</lastName>
         <department>IT</department>
     </supervisor>
     <supervisor id="2">
         <firstName>Jack</firstName>
         <lastName>Jones</lastName>
         <department>HR</department>
     </supervisor>
     <supervisor id="3">
         <firstName>Allan</firstName>
         <lastName>Johnson</lastName>
         <department>Sales</department>
     </supervisor>
     <supervisor id="4">
         <firstName>Chris</firstName>
         <lastName>Reyes</lastName>
         <department>Shipping</department>
     </supervisor>
</supervisors>

<employees>
     <employee supervisorID="1" employeeID="2">
         <firstName>Mike</firstName>
         <lastName>Albert</lastName>
         <phone>1111111111</phone>
     </employee>
     <employee supervisorID="1" employeeID="3">
         <firstName>Alicia</firstName>
         <lastName>James</lastName>
         <phone>1112222222</phone>
     </employee>
     <employee supervisorID="3" employeeID="4">
         <firstName>Anne</firstName>
         <lastName>Thomas</lastName>
         <phone>1112223333</phone>
     </employee>
</employees>

I want to wind up with a dataset that looks like this JSON (it can be an actual dataset, but for this I am showing JSON because it is easier to represent):

[
     {empFName: "Mike", empLName: "Albert", supFName: "John", supLName: "Smith", dept: "IT"},
     {empFName: "Alicia", empLName: "James", supFName: "John", supLName: "Smith", dept: "IT"},
     {empFName: "Anne", empLName: "Thomas", supFName: "Allan", supLName: "Johnson", dept: "Sales"}
 ]

How do I combine the XML data to properly return the way the JSON above is returned?

Body:
Using LINQ to XML makes this easy, and XML literals make it beautiful (if you are in to that sort of thing) - LINQPad example:

Dim supervisors =
<supervisors>
     <supervisor id="1">
         <firstName>John</firstName>
         <lastName>Smith</lastName>
         <department>IT</department>
     </supervisor>
     <supervisor id="2">
         <firstName>Jack</firstName>
         <lastName>Jones</lastName>
         <department>HR</department>
     </supervisor>
     <supervisor id="3">
         <firstName>Allan</firstName>
         <lastName>Johnson</lastName>
         <department>Sales</department>
     </supervisor>
     <supervisor id="4">
         <firstName>Chris</firstName>
         <lastName>Reyes</lastName>
         <department>Shipping</department>
     </supervisor>
</supervisors>

Dim employees =
<employees>
     <employee supervisorID="1" employeeID="2">
         <firstName>Mike</firstName>
         <lastName>Albert</lastName>
         <phone>1111111111</phone>
     </employee>
     <employee supervisorID="1" employeeID="3">
         <firstName>Alicia</firstName>
         <lastName>James</lastName>
         <phone>1112222222</phone>
     </employee>
     <employee supervisorID="3" employeeID="4">
         <firstName>Anne</firstName>
         <lastName>Thomas</lastName>
         <phone>1112223333</phone>
     </employee>
</employees>

Dim joined = (
    From e In employees.<employee>
    Join s In supervisors.<supervisor> On e.@supervisorID Equals s.@id
    Select New With {
        .empFName = e.<firstName>.Value,
        .empLName = e.<lastName>.Value,
        .supFName = s.<firstName>.Value,
        .supLName = s.<lastName>.Value,
        .dept = s.<department>.Value
    }
)

joined.Dump()

This results in:

Json.NET can convert that to JSON.

Dim json = JsonConvert.SerializeObject(joined)
json.Dump()

[
    {"empFName":"Mike","empLName":"Albert","supFName":"John","supLName":"Smith","dept":"IT"},
    {"empFName":"Alicia","empLName":"James","supFName":"John","supLName":"Smith","dept":"IT"},
    {"empFName":"Anne","empLName":"Thomas","supFName":"Allan","supLName":"Johnson","dept":"Sales"}
]


问:
Passing and Returning structs C
So I have had this problem where I keep getting error codes only in my main that (1) The struct has already been defined when I keep my struct in a header file and (2) I am using incompatible pointer types.

```<code>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "functDefs.h"
#include "writeToFile.c"
#include "readFile.c"
#include "inputContactInfo.c"
#include "contactInfoStruct.h"

int main(void) {

    int i = 0;
    char *ynAns;
    struct contactId *contactInfo;
    contactInfo = malloc(sizeof(struct contactId));

    do {
            if(ynAns != NULL) {
                    free(ynAns);
            }
            ynAns = malloc(sizeof(char) * 5);
            printf("\nDo you wish to enter a new contact (Yes or No)?: ");
            fgets(ynAns, 5, stdin);
            ynAns[(strlen(ynAns) - 1)] = '\0';
            if (strcmp(ynAns, "Yes") == 0) {
                    printf("\n");
                    contactInfo = realloc(contactInfo, sizeof(struct contactId) * (i + 1));
                    contactInfo[i] = inputContactInfo();
                    i++;
            }

    } while(strcmp(ynAns, "No") != 0);

    writeToFile(contactInfo, i);

    readFile(i);

    free(contactInfo);
    return 0;
}
</code>```

Then here are my function definitions:

```<code>void writeToFile(struct contactId *contInfo, int numContacts);
struct contactId *inputContactInfo();
void readFile(int numContacts);
</code>```

And this is the struct header file:

```<code>struct contactId {
    char firstName[20];
    char lastName[20];
    char companyName[50];
    char phoneNumber[15];
    char email[50];
};
</code>```

I get errors like:

```<code>IOlist.c: In function ‘main’:
IOlist.c:28:40: error: incompatible types when assigning to     type ‘struct contactId’ from type ‘struct contactId *’
                     contactInfo[i] = inputContactInfo();
                                    ^
IOlist.c:34:21: warning: passing argument 1 of ‘writeToFile’  from incompatible pointer type
     writeToFile(contactInfo, i);
                 ^
In file included from IOlist.c:5:0:
writeToFile.c:7:6: note: expected ‘struct contactId *’ but  argument is of type ‘struct contactId *’
void writeToFile(struct contactId *contInfo, int numContacts)   {
     ^
</code>```

And these errors as well:

```<code>In file included from IOlist.c:5:0:
writeToFile.c:7:6: error: conflicting types for ‘writeToFile’
void writeToFile(struct contactId *contInfo, int numContacts)  {
     ^
In file included from IOlist.c:4:0:
functDefs.h:1:6: note: previous declaration of ‘writeToFile’  was here
void writeToFile(struct contactId *contInfo, int numContacts);
     ^
In file included from readFile.c:4:0,
             from IOlist.c:6:
contactStruct.h:1:8: error: redefinition of ‘struct contact’
struct contact {
       ^
In file included from writeToFile.c:4:0,
             from IOlist.c:5:
contactStruct.h:1:8: note: originally defined here
 struct contact {
        ^
</code>```

答: Your function inputContactInfo() returns a pointer to struct. But the place where it tries to returnn pointer is a struct. You need declare  struct contactId **contactInfo, allocate memory for each element, and then you can correctly assign your pointer to contactInfo[i].</p>

Title: Passing and Returning structs C

Body:
So I have had this problem where I keep getting error codes only in my main that (1) The struct has already been defined when I keep my struct in a header file and (2) I am using incompatible pointer types.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "functDefs.h"
#include "writeToFile.c"
#include "readFile.c"
#include "inputContactInfo.c"
#include "contactInfoStruct.h"

int main(void) {

    int i = 0;
    char *ynAns;
    struct contactId *contactInfo;
    contactInfo = malloc(sizeof(struct contactId));

    do {
            if(ynAns != NULL) {
                    free(ynAns);
            }
            ynAns = malloc(sizeof(char) * 5);
            printf("\nDo you wish to enter a new contact (Yes or No)?: ");
            fgets(ynAns, 5, stdin);
            ynAns[(strlen(ynAns) - 1)] = '\0';
            if (strcmp(ynAns, "Yes") == 0) {
                    printf("\n");
                    contactInfo = realloc(contactInfo, sizeof(struct contactId) * (i + 1));
                    contactInfo[i] = inputContactInfo();
                    i++;
            }

    } while(strcmp(ynAns, "No") != 0);

    writeToFile(contactInfo, i);

    readFile(i);

    free(contactInfo);
    return 0;
}

Then here are my function definitions:

void writeToFile(struct contactId *contInfo, int numContacts);
struct contactId *inputContactInfo();
void readFile(int numContacts);

And this is the struct header file:

struct contactId {
    char firstName[20];
    char lastName[20];
    char companyName[50];
    char phoneNumber[15];
    char email[50];
};

I get errors like:

IOlist.c: In function ‘main’:
IOlist.c:28:40: error: incompatible types when assigning to     type ‘struct contactId’ from type ‘struct contactId *’
                     contactInfo[i] = inputContactInfo();
                                    ^
IOlist.c:34:21: warning: passing argument 1 of ‘writeToFile’  from incompatible pointer type
     writeToFile(contactInfo, i);
                 ^
In file included from IOlist.c:5:0:
writeToFile.c:7:6: note: expected ‘struct contactId *’ but  argument is of type ‘struct contactId *’
void writeToFile(struct contactId *contInfo, int numContacts)   {
     ^

And these errors as well:

In file included from IOlist.c:5:0:
writeToFile.c:7:6: error: conflicting types for ‘writeToFile’
void writeToFile(struct contactId *contInfo, int numContacts)  {
     ^
In file included from IOlist.c:4:0:
functDefs.h:1:6: note: previous declaration of ‘writeToFile’  was here
void writeToFile(struct contactId *contInfo, int numContacts);
     ^
In file included from readFile.c:4:0,
             from IOlist.c:6:
contactStruct.h:1:8: error: redefinition of ‘struct contact’
struct contact {
       ^
In file included from writeToFile.c:4:0,
             from IOlist.c:5:
contactStruct.h:1:8: note: originally defined here
 struct contact {
        ^


问:
Still getting error empty array
I'm still getting an error in tableView and I can't figure out why:

```<code>@objc class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var productsToDisplay: [SKProduct]!

override func viewWillAppear(_ animated: Bool) {
    // an assync call to load products to the productsToDisplay
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "PurchaseItemTableViewCell", for: indexPath) as? PurchaseItemTableViewCell else {
        fatalError("Coulnd't parse table cell!")
    }

    // here the app always show an error without any specification
    if(!(self.productsToDisplay != nil && self.productsToDisplay!.count > 0))     {
        return cell
    }

    cell.nameLabel.text = "my text"

   return cell

}

}
</code>```

What I'm doing wrong? Or how to fix the error / not load content of the table until data are loaded?

Thank you very much

答:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell should not be called by the system until your async loading call completes.

You have to implement func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int and let it return the number of elements in productsToDisplay. Then the systen will call cellForRowAt indexPath only if you have at least one row to display.

Remember to call reloadData on the tableView when your async request is completed.

Title: Still getting error empty array

Body:
I'm still getting an error in tableView and I can't figure out why:

@objc class MyViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var productsToDisplay: [SKProduct]!

override func viewWillAppear(_ animated: Bool) {
    // an assync call to load products to the productsToDisplay
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = tableView.dequeueReusableCell(withIdentifier: "PurchaseItemTableViewCell", for: indexPath) as? PurchaseItemTableViewCell else {
        fatalError("Coulnd't parse table cell!")
    }

    // here the app always show an error without any specification
    if(!(self.productsToDisplay != nil && self.productsToDisplay!.count > 0))     {
        return cell
    }

    cell.nameLabel.text = "my text"

   return cell

}

}

What I'm doing wrong? Or how to fix the error / not load content of the table until data are loaded?

Thank you very much


问:
Boolean use for decision making
Basically I want to do a method that is used to make decision, which when the HitshipPercentage is less than 50 and the shots is not equal to zero, it will use the method public space fire(). I am not sure how to use the boolean  in the correct way.

```<code>public Space fire()
{
 System.out.println("Hi");
}

     public boolean hitRateAnalysis()
 {

     if (HitShipPercentage < 50 && Shots!=0)

      return true;

     else{
     return false;
     }
 }
</code>```

答:
Your fire() is wrong and will cause a compilation error, you have to return an instance of Space. Either change the return type of the method to void or return an instance of the Space class.

This will call the fire method correctly:

```<code>public boolean hitRateAnalysis() {
   if (HitShipPercentage < 50 && Shots != 0){
      fire();
      return true;
    }
   return false;
 }
</code>```

Title: Boolean use for decision making

Body:
Basically I want to do a method that is used to make decision, which when the HitshipPercentage is less than 50 and the shots is not equal to zero, it will use the method public space fire(). I am not sure how to use the boolean  in the correct way.

public Space fire()
{
 System.out.println("Hi");
}

     public boolean hitRateAnalysis()
 {

     if (HitShipPercentage < 50 && Shots!=0)

      return true;

     else{
     return false;
     }
 }

Body:
Your fire() is wrong and will cause a compilation error, you have to return an instance of Space. Either change the return type of the method to void or return an instance of the Space class.

This will call the fire method correctly:

public boolean hitRateAnalysis() {
   if (HitShipPercentage < 50 && Shots != 0){
      fire();
      return true;
    }
   return false;
 }