答:
It's not hard to implement.</p>

```<code>async function hash(promiseObj) {
  // Deconstitute promiseObj to keys and promises
  const keys = [];
  const promises = [];
  Object.keys(promiseObj).forEach(k => {
    keys.push(k);
    promises.push(promiseObj[k]);
  });
  // Wait for all promises
  const resolutions = await Promise.all(promises);
  // Reconstitute a resolutions object
  const result = {};
  keys.forEach((key, index) => (result[key] = resolutions[index]));
  return result;
}

hash({
  foo: Promise.resolve(8),
  bar: Promise.resolve(16),
}).then(results => console.log(results));
</code>```

Title: RSVP hash using vanilla promises

Body:
It's not hard to implement.

async function hash(promiseObj) {
  // Deconstitute promiseObj to keys and promises
  const keys = [];
  const promises = [];
  Object.keys(promiseObj).forEach(k => {
    keys.push(k);
    promises.push(promiseObj[k]);
  });
  // Wait for all promises
  const resolutions = await Promise.all(promises);
  // Reconstitute a resolutions object
  const result = {};
  keys.forEach((key, index) => (result[key] = resolutions[index]));
  return result;
}

hash({
  foo: Promise.resolve(8),
  bar: Promise.resolve(16),
}).then(results => console.log(results));


来源: stackexchange

问:
Setting the labels of colorbar matplotlib
I have spent a couple hours trying to figure this out. I want the colorbar to display three values along the bar, [0, 3315/2, 3315]. However, I am just getting this result:

Code:

```<code>print(max(average_powers)) # 3314.455810547
sm = plt.cm.ScalarMappable(cmap=cmap)
sm.set_array([])
mn=int(np.floor(0)) 3
mx=int(np.ceil(max(average_powers)))
md=(mx-mn)/2
cb = plt.colorbar(sm)
cb.set_ticks([mn,md,mx])
cb.set_ticklabels([mn,md,mx],update_ticks=True)
cb.set_label('Magnitude of Average Power for turbine')
</code>```

Thanks in advance!

答:
Replace

```<code>cb.set_ticks([mn,md,mx])
</code>```

With

```<code>cb.set_ticks([0, 0.5, 1])
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have spent a couple hours trying to figure this out. I want the colorbar to display three values along the bar, [0, 3315/2, 3315]. However, I am just getting this result:

Code:

print(max(average_powers)) # 3314.455810547
sm = plt.cm.ScalarMappable(cmap=cmap)
sm.set_array([])
mn=int(np.floor(0)) 3
mx=int(np.ceil(max(average_powers)))
md=(mx-mn)/2
cb = plt.colorbar(sm)
cb.set_ticks([mn,md,mx])
cb.set_ticklabels([mn,md,mx],update_ticks=True)
cb.set_label('Magnitude of Average Power for turbine')

Thanks in advance!

Body:
Replace

cb.set_ticks([mn,md,mx])

With

cb.set_ticks([0, 0.5, 1])


问:
How to Center GridView Component
Hello I new to Flutter and I am having an issue on centering the components of my icons anyone can suggest the correct way to center the dashboard icons.I am still trying to fix it but if you could provide some pointers for me that would be great. I have tried putting it row to row but the issue still same also padding on the Widget that I created

```<code>Widget build(BuildContext context){
final _width = MediaQuery.of(context).size.width;
final _height = MediaQuery.of(context).size.height;

  return new Stack(children: <Widget>[
    new Container(color: Colors.blue,),
    new Scaffold(
      appBar: AppBar(
        title: Text("Welcome"),
        centerTitle: true,
      ),
      drawer: MenuComponent(),
      backgroundColor: Colors.transparent,
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Row(
              children: <Widget>[
                Expanded(
                    child: Align(
                      alignment: FractionalOffset.topCenter,
                      child: Padding(
                        padding: EdgeInsets.all(10.0),
                        child: SizedBox(
                          height: 50,
                          width: 130,
                          child:new Text('One', style: new TextStyle(fontWeight: FontWeight.bold, fontSize: _width/15, color: Colors.white),),
                        ),
                      ),
                    )
                ),
                new Divider(height: _height/30,color: Colors.white,),
              ],
            ),
           Expanded(
             child: Center(
               child:  GridView.count(
                 padding: const EdgeInsets.all(20.0),
                 crossAxisSpacing: 10.0,
                 mainAxisSpacing: 10.0,

                 crossAxisCount: 4,
                 children: <Widget>[
                   homePageRowCell(Icons.account_circle, "My Account",context,HomePage()),
                   homePageRowCell(Icons.dashboard, "Home page",context, HomePage()),
                   homePageRowCell(Icons.person_outline, "Profile",context, ProfilePage()),
                   homePageRowCell(Icons.settings, "Settings",context, Settings()),
                   homePageRowCell(Icons.exit_to_app, "Logout",context, LoginPage()),
                 ],
               ),
             )
           )
          ],
        ),
      ),
    )
  ],);
//    return Scaffold(
//      appBar: AppBar(
//        title: Text("Home Page"),
//        centerTitle: true,
//      ),
//      drawer: MenuComponent(),
//    );
  }
}

Widget homePageRowCell(var sIcon, String title, BuildContext context, var page) => new Container(
  child: GestureDetector(
      onTap: () {
        Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => page)
        );
      },
    child: new Row(
      children: <Widget>[
        Column(
            children: <Widget>[
              new Icon(sIcon,color: Colors.white,),
              new Text(title,style: new TextStyle(color: Colors.white, fontWeight: FontWeight.normal)),
            ],
          ),

      ],
    ),
  )
);
</code>```

答:
Please try below code and check output

```<code>   @override
  Widget build(BuildContext context) {
    final _width = MediaQuery.of(context).size.width;
    final _height = MediaQuery.of(context).size.height;

    return new Stack(
      children: <Widget>[
        new Container(
          color: Colors.blue,
        ),
        new Scaffold(
          appBar: AppBar(
            title: Text("Welcome"),
            centerTitle: true,
          ),
        drawer: MenuComponent(),
          backgroundColor: Colors.transparent,
          body: new Center(
            child: new Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Row(
                  children: <Widget>[
                    Expanded(
                        child: Align(
                      alignment: FractionalOffset.topCenter,
                      child: Padding(
                        padding: EdgeInsets.all(10.0),
                        child: SizedBox(
                          height: 50,
                          width: 130,
                          child: new Text(
                            'One',
                            style: new TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: _width / 15,
                                color: Colors.white),
                          ),
                        ),
                      ),
                    )),
                    new Divider(
                      height: _height / 30,
                      color: Colors.white,
                    ),
                  ],
                ),
                Expanded(
                    child: Center(
                  child: GridView.count(
                    crossAxisCount: 4,
                    crossAxisSpacing: 10.0,
                    mainAxisSpacing: 10.0,
                    children: <Widget>[
                      homePageRowCell(Icons.account_circle, "My Account",
                          context, HomePage()),
                      homePageRowCell(
                          Icons.dashboard, "Home page", context, HomePage()),
                      homePageRowCell(Icons.person_outline, "Profile", context,
                          ProfilePage()),
                      homePageRowCell(
                          Icons.settings, "Settings", context, Settings()),
                      homePageRowCell(
                          Icons.exit_to_app, "Logout", context, LoginPage()),
                    ],
                  ),
                ))
              ],
            ),
          ),
        )
      ],
    );
//    return Scaffold(
//      appBar: AppBar(
//        title: Text("Home Page"),
//        centerTitle: true,
//      ),
//      drawer: MenuComponent(),
//    );
  }

Widget homePageRowCell(
        var sIcon, String title, BuildContext context, var page) =>
    new Container(
        child: GestureDetector(
      onTap: () {
        Navigator.push(context, MaterialPageRoute(builder: (context) => page));
      },
      child: new Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Column(
            children: <Widget>[
              new Icon(
                sIcon,
                color: Colors.white,
              ),
              new Text(title,
                  style: new TextStyle(
                      color: Colors.white, fontWeight: FontWeight.normal)),
            ],
          ),
        ],
      ),
    ));
</code>```

Title: How to Center GridView Component

Body:
Hello I new to Flutter and I am having an issue on centering the components of my icons anyone can suggest the correct way to center the dashboard icons.I am still trying to fix it but if you could provide some pointers for me that would be great. I have tried putting it row to row but the issue still same also padding on the Widget that I created

Widget build(BuildContext context){
final _width = MediaQuery.of(context).size.width;
final _height = MediaQuery.of(context).size.height;

  return new Stack(children: <Widget>[
    new Container(color: Colors.blue,),
    new Scaffold(
      appBar: AppBar(
        title: Text("Welcome"),
        centerTitle: true,
      ),
      drawer: MenuComponent(),
      backgroundColor: Colors.transparent,
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Row(
              children: <Widget>[
                Expanded(
                    child: Align(
                      alignment: FractionalOffset.topCenter,
                      child: Padding(
                        padding: EdgeInsets.all(10.0),
                        child: SizedBox(
                          height: 50,
                          width: 130,
                          child:new Text('One', style: new TextStyle(fontWeight: FontWeight.bold, fontSize: _width/15, color: Colors.white),),
                        ),
                      ),
                    )
                ),
                new Divider(height: _height/30,color: Colors.white,),
              ],
            ),
           Expanded(
             child: Center(
               child:  GridView.count(
                 padding: const EdgeInsets.all(20.0),
                 crossAxisSpacing: 10.0,
                 mainAxisSpacing: 10.0,

                 crossAxisCount: 4,
                 children: <Widget>[
                   homePageRowCell(Icons.account_circle, "My Account",context,HomePage()),
                   homePageRowCell(Icons.dashboard, "Home page",context, HomePage()),
                   homePageRowCell(Icons.person_outline, "Profile",context, ProfilePage()),
                   homePageRowCell(Icons.settings, "Settings",context, Settings()),
                   homePageRowCell(Icons.exit_to_app, "Logout",context, LoginPage()),
                 ],
               ),
             )
           )
          ],
        ),
      ),
    )
  ],);
//    return Scaffold(
//      appBar: AppBar(
//        title: Text("Home Page"),
//        centerTitle: true,
//      ),
//      drawer: MenuComponent(),
//    );
  }
}

Widget homePageRowCell(var sIcon, String title, BuildContext context, var page) => new Container(
  child: GestureDetector(
      onTap: () {
        Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => page)
        );
      },
    child: new Row(
      children: <Widget>[
        Column(
            children: <Widget>[
              new Icon(sIcon,color: Colors.white,),
              new Text(title,style: new TextStyle(color: Colors.white, fontWeight: FontWeight.normal)),
            ],
          ),

      ],
    ),
  )
);

Body:
Please try below code and check output

   @override
  Widget build(BuildContext context) {
    final _width = MediaQuery.of(context).size.width;
    final _height = MediaQuery.of(context).size.height;

    return new Stack(
      children: <Widget>[
        new Container(
          color: Colors.blue,
        ),
        new Scaffold(
          appBar: AppBar(
            title: Text("Welcome"),
            centerTitle: true,
          ),
        drawer: MenuComponent(),
          backgroundColor: Colors.transparent,
          body: new Center(
            child: new Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Row(
                  children: <Widget>[
                    Expanded(
                        child: Align(
                      alignment: FractionalOffset.topCenter,
                      child: Padding(
                        padding: EdgeInsets.all(10.0),
                        child: SizedBox(
                          height: 50,
                          width: 130,
                          child: new Text(
                            'One',
                            style: new TextStyle(
                                fontWeight: FontWeight.bold,
                                fontSize: _width / 15,
                                color: Colors.white),
                          ),
                        ),
                      ),
                    )),
                    new Divider(
                      height: _height / 30,
                      color: Colors.white,
                    ),
                  ],
                ),
                Expanded(
                    child: Center(
                  child: GridView.count(
                    crossAxisCount: 4,
                    crossAxisSpacing: 10.0,
                    mainAxisSpacing: 10.0,
                    children: <Widget>[
                      homePageRowCell(Icons.account_circle, "My Account",
                          context, HomePage()),
                      homePageRowCell(
                          Icons.dashboard, "Home page", context, HomePage()),
                      homePageRowCell(Icons.person_outline, "Profile", context,
                          ProfilePage()),
                      homePageRowCell(
                          Icons.settings, "Settings", context, Settings()),
                      homePageRowCell(
                          Icons.exit_to_app, "Logout", context, LoginPage()),
                    ],
                  ),
                ))
              ],
            ),
          ),
        )
      ],
    );
//    return Scaffold(
//      appBar: AppBar(
//        title: Text("Home Page"),
//        centerTitle: true,
//      ),
//      drawer: MenuComponent(),
//    );
  }

Widget homePageRowCell(
        var sIcon, String title, BuildContext context, var page) =>
    new Container(
        child: GestureDetector(
      onTap: () {
        Navigator.push(context, MaterialPageRoute(builder: (context) => page));
      },
      child: new Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Column(
            children: <Widget>[
              new Icon(
                sIcon,
                color: Colors.white,
              ),
              new Text(title,
                  style: new TextStyle(
                      color: Colors.white, fontWeight: FontWeight.normal)),
            ],
          ),
        ],
      ),
    ));


问:
How to group similar News
I'm trying to build a rss-news fetching server to collect all news of a few sites about a topic. Often these sites have similar news with nearly the same information. How would it be possible to group such news. For example display the first and then a summary of other links?

Does anybody have experince with this?

答:
Look for keywords (e.g., split the description into words and remove any of the 100 or so most common words) then clump them by cooccurance of these.  Often just looking at the longest word will give you a good quick approximation.

In other words, if you have a table with "topic groups" you can assign each item to a new or existing topic group as it comes in.  First, see if any of the existing topic groups share enough keywords with the new item; if one does, put it there.  If none does, create a new topic group with its keywords and add it as the first member of that topic group.

-- MarkusQ

ContentLicense: CC BY-SA 2.5

Title: How to group similar News

OwnerDisplayName: MarkusQ


问:
ie8 scroll using arrows in flash
i have a problem with a game in flash , this game using up and down arrows, for some reason, when i click the game , the web page scrolls too, how can i fix it ? , i use this cheat in javascript but didn't work:

```<code>document.onkeydown = function(e) {
       var k = (window.event) ? event.keyCode : e.keyCode;
       if(k >= 37 && k <= 40) {

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

Also ,this game is loading trought another flash that embeds an iframe loading the flash game.

Thanks.

Sebastian.

答: try changing the wmode attribute to a solid colour (i.e. the same colour as your page background). </p>

Title: ie8 scroll using arrows in flash

Body:
i have a problem with a game in flash , this game using up and down arrows, for some reason, when i click the game , the web page scrolls too, how can i fix it ? , i use this cheat in javascript but didn't work:

document.onkeydown = function(e) {
       var k = (window.event) ? event.keyCode : e.keyCode;
       if(k >= 37 && k <= 40) {

           return false;
       }
   }

Also ,this game is loading trought another flash that embeds an iframe loading the flash game.

Thanks.

Sebastian.

ContentLicense: CC BY-SA 3.0


问:
How to position an svg image X pixels in a div using css?
I have multiple div boxes, each of differing widths.

How do I position the svg image 10 pixels from the right of each div ?

I've tried using percentages but it didn't work.

Below is my code:

```<code>select {
    background-image: url(caret-down.svg);
    background-repeat: no-repeat;
    background-position: 92% 50%;
}
</code>```

So this centers the svg vertically and 92% to the left of the div.

答:
ok I fixed it while searching...</p>

```<code>select {
    background-image: url(caret-down.svg);
    background-repeat: no-repeat;
    background-position: right 10px center;
}
</code>```

Body:
I have multiple div boxes, each of differing widths.

How do I position the svg image 10 pixels from the right of each div ?

I've tried using percentages but it didn't work.

Below is my code:

select {
    background-image: url(caret-down.svg);
    background-repeat: no-repeat;
    background-position: 92% 50%;
}

So this centers the svg vertically and 92% to the left of the div.

Body:
ok I fixed it while searching...

select {
    background-image: url(caret-down.svg);
    background-repeat: no-repeat;
    background-position: right 10px center;
}


问:
Get courts in complexes with minimal price
I have sport complexes and many corts in complexes .
 So I wanna select complexes by min price of court of it .

```<code>Complex1   court1 -price 2500
           court2  - price 3000
Complex2   court1 -price 5000
           court2 -price 1500
Result: Complex2(1500),Complex1(2500)
</code>```

DB:

```<code>sport_complexes -
    sc_id -compex id
    sc_city_id
    sc_sport_type_id
one to many
courts-
    c_id
    c_complex_id  -complex id
    c_coverage_id
    c_name
    c_cost  -price
</code>```

I tried like this .

```<code>get all complexes to special sport type
$complexes = $sporttype->complexes;

ids of complexes
$complexesIDs=$complexes->pluck('sc_id');

wanna order
$array=\App\Models\Courts::whereIn('c_complex_id', $complexesIDs)->orderBy('c_cost')->get()->unique('c_complex_id ')
</code>```

答:
This seems pretty easy to solve, you may have this in your sporttype class (I even don't know if that is a class):

```<code>public function complexes(){
    return $this->hasMany('App\Complex');
}
</code>```

You can create a new function to get the complexes ordered by cost:

```<code>public function complexesOrdered(){
    return $this->hasMany('App\Complex')->orderBy('c_cost');
}
</code>```

Another solution is traiting your relation as a function, so you can "requery" it:

```<code>$complexes = $sporttype->complexes()->orderBy('c_cost');
</code>```

Cheers!

EDIT:

You have to make one more relationship to accomplish that:

In your Complex class:

```<code>public function courts(){
    return $this->hasMany('App\Court');
}
public function cheapCourt(){
    return $this->hasMany('App\Court')->orderBy('c_cost');
}
</code>```

In your controller:

```<code>complex->cheapCourt->first();
</code>```

Body:
I have sport complexes and many corts in complexes .
 So I wanna select complexes by min price of court of it .

Complex1   court1 -price 2500
           court2  - price 3000
Complex2   court1 -price 5000
           court2 -price 1500
Result: Complex2(1500),Complex1(2500)

DB:

sport_complexes -
    sc_id -compex id
    sc_city_id
    sc_sport_type_id
one to many
courts-
    c_id
    c_complex_id  -complex id
    c_coverage_id
    c_name
    c_cost  -price

I tried like this .

get all complexes to special sport type
$complexes = $sporttype->complexes;

ids of complexes
$complexesIDs=$complexes->pluck('sc_id');

wanna order
$array=\App\Models\Courts::whereIn('c_complex_id', $complexesIDs)->orderBy('c_cost')->get()->unique('c_complex_id ')

Body:
This seems pretty easy to solve, you may have this in your sporttype class (I even don't know if that is a class):

public function complexes(){
    return $this->hasMany('App\Complex');
}

You can create a new function to get the complexes ordered by cost:

public function complexesOrdered(){
    return $this->hasMany('App\Complex')->orderBy('c_cost');
}

Another solution is traiting your relation as a function, so you can "requery" it:

$complexes = $sporttype->complexes()->orderBy('c_cost');

Cheers!

EDIT:

You have to make one more relationship to accomplish that:

In your Complex class:

public function courts(){
    return $this->hasMany('App\Court');
}
public function cheapCourt(){
    return $this->hasMany('App\Court')->orderBy('c_cost');
}

In your controller:

complex->cheapCourt->first();


问:
log_loss from sklearn gives nan, while tensorflow.losses.log_loss works
I have a binary classification problem.
I am using the log_loss from tensorflow.losses.log_loss.

To check, I use sklearn.metrics.log_loss. Most of the times, the two functions give the same result (only difference in dtype). In some instance, the sklearn function returns NaN while tf.losses.log_loss returns a correct value.

data is here:
https://pastebin.com/BvDgDnVT

code:

```<code>import sklearn.metrics
import tensorflow as tf
y_true = [... see pastebin link]
y_pred = [... see pastebin link]
loss_sk = sklearn.metrics.log_loss(y_true, y_pred, labels=[0, 1]) # -> returns NaN
with tf.Session() as sess:
    loss_tf = tf.losses.log_loss(y_true, y_pred).eval(session=sess) # -> returns 0.0549
</code>```

There seems to be some log(0) happening, but why does tensorflow not have this problem?

答:
Another way of fixing the issue is to provide eps=1e-7 to log_loss, which is a more appropriate epsilon for float32 and is what tensorflow's using.
Scikit however uses 1e-15 as a default (expecting float64).

Body:
I have a binary classification problem.
I am using the log_loss from tensorflow.losses.log_loss.

To check, I use sklearn.metrics.log_loss. Most of the times, the two functions give the same result (only difference in dtype). In some instance, the sklearn function returns NaN while tf.losses.log_loss returns a correct value.

data is here:
https://pastebin.com/BvDgDnVT

code:

import sklearn.metrics
import tensorflow as tf
y_true = [... see pastebin link]
y_pred = [... see pastebin link]
loss_sk = sklearn.metrics.log_loss(y_true, y_pred, labels=[0, 1]) # -> returns NaN
with tf.Session() as sess:
    loss_tf = tf.losses.log_loss(y_true, y_pred).eval(session=sess) # -> returns 0.0549

There seems to be some log(0) happening, but why does tensorflow not have this problem?


问:
add multiple Payloads on Vuex
I would like to pass 2 data, amount and id to the store so i try to give 2 payloads on the Actions but it doesn't work. Both data are undefined

How to pass 2 payloads in the same event ? (you can find that where the console.logs are)

When i put one single payload (id or amount, i got the correct value, but not when i try to give 2 payloads.

Thanks in advance!

Here my component :

```<code>    <script>
import { mapActions } from 'vuex'
import BaseButton from './BaseButton.vue'

export default {

  name: 'MenuItem',
  components: {
    BaseButton
  },
  props: {
    image: {
      type: Object,
      required: true
    },
    inStock: {
      type: Boolean,
      required: true
    },
    name: {
      type: String,
      required: true
    },
    price: {
      type: Number,
      required: true
    },
    quantity: {
      type: Number,
      defaut: 1
    },
    id: {
      type: Number,
      defaut: 1
    }
  },
  data() {
    return {
      onSale: false
    }
  },
  computed: {
    generatedPrice() {
      if (this.onSale) {
        return (this.price * 0.9).toFixed(2)
      } else {
        return this.price
      }
    }
  },
  methods: {
    ...mapActions(['updateShoppingCart'])
  },
  beforeMount() {
    const today = new Date().getDate()

    if (today % 2 === 0) {
      this.onSale = true
    }
  }
}

</script>

<template>
  <div class="menu-item">
    <img class="menu-item__image" :src="image.source" :alt="image.alt" />
    <div>
      <h3>{{ name }}</h3>
      id : {{ id }}
      <p>Price: {{ generatedPrice }} <span v-if="onSale">(10% off!)</span></p>
      <p v-if="inStock">In Stock</p>
      <p v-else>Out of Stock</p>
      <div>
        <label for="add-item-quantity">Quantity: {{ quantity }}</label>
        <input v-model.number="quantity" id="add-item-quantity" type="number" />
        <BaseButton @click="updateShoppingCart(quantity, id)" class="test">
          Add to shopping cart
        </BaseButton>
      </div>
    </div>
  </div>
</template>
</code>```

here the store :

```<code>import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    restaurantName: 'Cafe with A Vue',
    shoppingCart: 0,
    selectedItemId: 0,
    croissiantNumber: 0,
    baguetteNumber: 0,
    eclairNumber: 0,
    simpleMenu: [
      {
        id: 1,
        name: 'Crossiant',
        image: {
          source: '/images/crossiant.jp',
          alt: 'A crossiant'
        },
        inStock: true,
        quantity: 1,
        price: 2.99
      },
      {
        id: 2,
        name: 'French Baguette',
        image: {
          source: '/images/french-baguette.jpe',
          alt: 'Four French Baguettes'
        },
        inStock: true,
        quantity: 1,
        price: 3.99
      },
      {
        id: 3,
        name: 'Éclair',
        image: {
          source: '/images/eclair.jp',
          alt: 'Chocolate Éclair'
        },
        inStock: false,
        quantity: 1,
        price: 4.99
      }
    ]
  },
  getters: {
    copyright: state => {
      const currentYear = new Date().getFullYear()

      return `Copyright ${state.restaurantName} ${currentYear}`
    }
  },
  mutations: {
    ADD_ITEMS_TO_TOTAL_SHOPPING_CART(state, {amount}) {
      state.shoppingCart += amount
    }
  },
  actions: {
    updateShoppingCart({ commit }, {amount, id}) {
      commit('ADD_ITEMS_TO_TOTAL_SHOPPING_CART', {amount, id})
      console.log(id)
      console.log(amount)
    }
  },
  modules: {}
})
</code>```

答:
Question 1

Your action expects an object with 2 properties:  amount and id.  But you are not passing an object, but rather two separate variables updateShoppingCart(quantity, id).

In your template, call it like this instead:

```<code>updateShoppingCart({ amount: quantity, id });  // Note the object brackets
</code>```

Or, rename quantity in your component to amount and you could call it like this:

```<code>updateShoppingCart({ amount, id });
</code>```

Question 2 (using destructuring)

mutation:

```<code>ADD_ITEMS_TO_TOTAL_SHOPPING_CART(state, { amount, id }) {
  state.shoppingCart += amount;
  console.log(id);
}
</code>```

action:

```<code>updateShoppingCart({ commit }, { amount, id }) {
  commit('ADD_ITEMS_TO_TOTAL_SHOPPING_CART', { amount, id })
  console.log(id)
  console.log(amount)
}
</code>```

Question 2b (alternative using payload):

mutation:

```<code>ADD_ITEMS_TO_TOTAL_SHOPPING_CART(state, payload) {
  state.shoppingCart += payload.amount;
  console.log(payload.id);
}
</code>```

action:

```<code>updateShoppingCart({ commit }, payload) {
  commit('ADD_ITEMS_TO_TOTAL_SHOPPING_CART', payload)
  console.log(payload.id)
  console.log(payload.amount)
}
</code>```

Title: add multiple Payloads on Vuex

Body:
I would like to pass 2 data, amount and id to the store so i try to give 2 payloads on the Actions but it doesn't work. Both data are undefined

How to pass 2 payloads in the same event ? (you can find that where the console.logs are)

When i put one single payload (id or amount, i got the correct value, but not when i try to give 2 payloads.

Thanks in advance!

Here my component :

<template>

{{ name }}

      id : {{ id }}

Price: {{ generatedPrice }} (10% off!)

In Stock

Out of Stock

        Quantity: {{ quantity }}
        <input v-model.number="quantity" id="add-item-quantity" type="number" />
        <BaseButton @click="updateShoppingCart(quantity, id)" class="test">
          Add to shopping cart
        </BaseButton>

</template>

here the store :

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    restaurantName: 'Cafe with A Vue',
    shoppingCart: 0,
    selectedItemId: 0,
    croissiantNumber: 0,
    baguetteNumber: 0,
    eclairNumber: 0,
    simpleMenu: [
      {
        id: 1,
        name: 'Crossiant',
        image: {
          source: '/images/crossiant.jp',
          alt: 'A crossiant'
        },
        inStock: true,
        quantity: 1,
        price: 2.99
      },
      {
        id: 2,
        name: 'French Baguette',
        image: {
          source: '/images/french-baguette.jpe',
          alt: 'Four French Baguettes'
        },
        inStock: true,
        quantity: 1,
        price: 3.99
      },
      {
        id: 3,
        name: 'Éclair',
        image: {
          source: '/images/eclair.jp',
          alt: 'Chocolate Éclair'
        },
        inStock: false,
        quantity: 1,
        price: 4.99
      }
    ]
  },
  getters: {
    copyright: state => {
      const currentYear = new Date().getFullYear()

      return `Copyright ${state.restaurantName} ${currentYear}`
    }
  },
  mutations: {
    ADD_ITEMS_TO_TOTAL_SHOPPING_CART(state, {amount}) {
      state.shoppingCart += amount
    }
  },
  actions: {
    updateShoppingCart({ commit }, {amount, id}) {
      commit('ADD_ITEMS_TO_TOTAL_SHOPPING_CART', {amount, id})
      console.log(id)
      console.log(amount)
    }
  },
  modules: {}
})

Body:
Question 1

Your action expects an object with 2 properties:  amount and id.  But you are not passing an object, but rather two separate variables updateShoppingCart(quantity, id).

In your template, call it like this instead:

updateShoppingCart({ amount: quantity, id });  // Note the object brackets

Or, rename quantity in your component to amount and you could call it like this:

updateShoppingCart({ amount, id });

Question 2 (using destructuring)

mutation:

ADD_ITEMS_TO_TOTAL_SHOPPING_CART(state, { amount, id }) {
  state.shoppingCart += amount;
  console.log(id);
}

action:

updateShoppingCart({ commit }, { amount, id }) {
  commit('ADD_ITEMS_TO_TOTAL_SHOPPING_CART', { amount, id })
  console.log(id)
  console.log(amount)
}

Question 2b (alternative using payload):

mutation:

ADD_ITEMS_TO_TOTAL_SHOPPING_CART(state, payload) {
  state.shoppingCart += payload.amount;
  console.log(payload.id);
}

action:

updateShoppingCart({ commit }, payload) {
  commit('ADD_ITEMS_TO_TOTAL_SHOPPING_CART', payload)
  console.log(payload.id)
  console.log(payload.amount)
}


问:
how can I change the header alignment of my cxGrid table view?
How can I change the header alignment of my cxGrid tableView? I try

```<code>MyGridColumn.HeaderAlignmentVert := TcxAlignmentVert.vaCenter;
</code>```

but this not work :(

答:
The code below shows how to create a cxGrid, add a TcxGridDBTableView, and set the
header alignments for the TableView's headers, all entirely in code.  I've done it all in code because there are so many properties in the Object Inspector for a cxGrid and its contents that it's hard to see at a glance (in the OI or the DFM) what the relevant properties are.

```<code>type
  TForm1 = class(TForm)
    CDS1: TClientDataSet;
    DS1: TDataSource;
    cxGrid1DBTableView1: TcxGridDBTableView;
    cxGrid1Level1: TcxGridLevel;
    cxGrid1: TcxGrid;
    procedure FormCreate(Sender: TObject);
  [...]
  public
    cxGrid : TcxGrid;
    cxLevel : TcxGridLevel;
    cxView : TcxGridDBTableView;
  end;
[...]
procedure TForm1.FormCreate(Sender: TObject);
var
  Field : TField;
begin
  // First, set up TClientDataSet

  Field := TIntegerField.Create(Self);
  Field.FieldKind := fkData;
  Field.FieldName := 'ID';
  Field.DataSet := CDS1;

  Field := TStringField.Create(Self);
  Field.FieldKind := fkData;
  Field.FieldName := 'Name';
  Field.Size := 40;
  Field.DataSet := CDS1;

  Field := TIntegerField.Create(Self);
  Field.FieldKind := fkData;
  Field.FieldName := 'Value';
  Field.DataSet := CDS1;

  CDS1.CreateDataSet;

  CDS1.IndexFieldNames := 'ID';

  CDS1.InsertRecord([1, 'One', 1]);
  CDS1.InsertRecord([1, 'Two', 2]);
  CDS1.InsertRecord([1, 'Three', 3]);

  CDS1.First;

  //  Next, create cxGrid, and add cxGridDBTableView
  cxGrid := TcxGrid.Create(Self);
  cxGrid.Parent := Self;
  cxGrid.Width := 400;

  cxLevel := cxGrid.Levels.Add;
  cxLevel.Name := 'Firstlevel';

  cxView := cxGrid.CreateView(TcxGridDBTableView) as TcxGridDBTableView;
  cxView.Name := 'ATableView';
  cxView.OptionsView.HeaderHeight := 100; // so we can easily see different vert alignments

  cxView.DataController.Options := cxView.DataController.Options + [dcoImmediatePost];
  cxView.DataController.KeyFieldNames := 'ID';

  cxLevel.GridView := cxView;

  cxView.DataController.DataSource := DS1;
  cxView.DataController.CreateAllItems;

  //  by this point the columns and their headers will have been created

  cxView.Columns[0].HeaderAlignmentVert := cxclasses.vaTop;
  cxView.Columns[1].HeaderAlignmentVert := cxclasses.vaCenter;
  cxView.Columns[2].HeaderAlignmentVert := cxclasses.vaBottom;
end;
</code>```

For me, the headers have the correct alignments, ie

```<code>ID
    Name
           Value
</code>```

Fwiw, before creating the above example, I tried setting the headers' vertical alignments on an existing project, and couldn't get it to work either, by which I
mean, the headers texts all obstinately stayed in the vertical center.  So I guess there must be some other setting in my existing project's grid which overrides the
alignment behaviour.

Update I noticed that if I comment out the line which sets the HeaderHeight, the vertical alignment setting appears to have no effect.  I think that the reason is simply that the difference in vertical position of the text caused by different alignments is too small to notice - it is only after I increase the HeaderHeight to 23 or more that there is a visible difference.

Body:
How can I change the header alignment of my cxGrid tableView? I try

MyGridColumn.HeaderAlignmentVert := TcxAlignmentVert.vaCenter;

but this not work :(

Body:
The code below shows how to create a cxGrid, add a TcxGridDBTableView, and set the
header alignments for the TableView's headers, all entirely in code.  I've done it all in code because there are so many properties in the Object Inspector for a cxGrid and its contents that it's hard to see at a glance (in the OI or the DFM) what the relevant properties are.

type
  TForm1 = class(TForm)
    CDS1: TClientDataSet;
    DS1: TDataSource;
    cxGrid1DBTableView1: TcxGridDBTableView;
    cxGrid1Level1: TcxGridLevel;
    cxGrid1: TcxGrid;
    procedure FormCreate(Sender: TObject);
  [...]
  public
    cxGrid : TcxGrid;
    cxLevel : TcxGridLevel;
    cxView : TcxGridDBTableView;
  end;
[...]
procedure TForm1.FormCreate(Sender: TObject);
var
  Field : TField;
begin
  // First, set up TClientDataSet

  Field := TIntegerField.Create(Self);
  Field.FieldKind := fkData;
  Field.FieldName := 'ID';
  Field.DataSet := CDS1;

  Field := TStringField.Create(Self);
  Field.FieldKind := fkData;
  Field.FieldName := 'Name';
  Field.Size := 40;
  Field.DataSet := CDS1;

  Field := TIntegerField.Create(Self);
  Field.FieldKind := fkData;
  Field.FieldName := 'Value';
  Field.DataSet := CDS1;

  CDS1.CreateDataSet;

  CDS1.IndexFieldNames := 'ID';

  CDS1.InsertRecord([1, 'One', 1]);
  CDS1.InsertRecord([1, 'Two', 2]);
  CDS1.InsertRecord([1, 'Three', 3]);

  CDS1.First;

  //  Next, create cxGrid, and add cxGridDBTableView
  cxGrid := TcxGrid.Create(Self);
  cxGrid.Parent := Self;
  cxGrid.Width := 400;

  cxLevel := cxGrid.Levels.Add;
  cxLevel.Name := 'Firstlevel';

  cxView := cxGrid.CreateView(TcxGridDBTableView) as TcxGridDBTableView;
  cxView.Name := 'ATableView';
  cxView.OptionsView.HeaderHeight := 100; // so we can easily see different vert alignments

  cxView.DataController.Options := cxView.DataController.Options + [dcoImmediatePost];
  cxView.DataController.KeyFieldNames := 'ID';

  cxLevel.GridView := cxView;

  cxView.DataController.DataSource := DS1;
  cxView.DataController.CreateAllItems;

  //  by this point the columns and their headers will have been created

  cxView.Columns[0].HeaderAlignmentVert := cxclasses.vaTop;
  cxView.Columns[1].HeaderAlignmentVert := cxclasses.vaCenter;
  cxView.Columns[2].HeaderAlignmentVert := cxclasses.vaBottom;
end;

For me, the headers have the correct alignments, ie

ID
    Name
           Value

Fwiw, before creating the above example, I tried setting the headers' vertical alignments on an existing project, and couldn't get it to work either, by which I
mean, the headers texts all obstinately stayed in the vertical center.  So I guess there must be some other setting in my existing project's grid which overrides the
alignment behaviour.

Update I noticed that if I comment out the line which sets the HeaderHeight, the vertical alignment setting appears to have no effect.  I think that the reason is simply that the difference in vertical position of the text caused by different alignments is too small to notice - it is only after I increase the HeaderHeight to 23 or more that there is a visible difference.


问:
Cannot deserialize the json file with list of events?
I have below C# class structure,

```<code>public class Event
{
    public string Id { get; set; }
    public Body Body { get; set; }
    public BodyProperty[] BodyProperties { get; set; }
    public string EventType { get; set; }
    public string CreatedTime { get; set; }
}

public class BodyProperty
{
    public string Key { get; set; }
    public string Value { get; set; }
}

public class Body
{
    public Body(string value, string type = "TextualBody", string format = "application/json")
    {
        Type = type;
        Value = value;
        Format = format;
    }

    public string Type { get; set; }
    public string Value { get; set; }
    public string Format { get; set; }
}
</code>```

and trying to read below JSON file,

```<code>{
    "Events": [
        {
            "Id": "d22fc23c-968f-4406-bebb-fca231694986",
            "Body": {
                "Type": "TextualBody",
                "Value": "test",
                "Format": "application/json"
            },
            "BodyProperties": null,
            "EventType": "Entity",
            "CreatedTime": "2020-02-20T13:57:14.1234165+05:30"
        },
        {
            "Id": "fgdgdg-968f-4406-bebb-646464",
            "Body": {
                "Type": "TextualBody",
                "Value": "test",
                "Format": "application/json"
            },
            "BodyProperties": null,
            "EventType": "Entity",
            "CreatedTime": "2020-02-21T13:57:14.1234165+05:30"
        }
    ]
}
</code>```

But this give below error while trying to read like this, I can't change JSON format, what can I change while reading?

```<code>using (StreamReader file = File.OpenText(@"C:\TEMP\json1.json"))
        using (JsonTextReader jsonreader = new JsonTextReader(file))
        {
            var serializer = new JsonSerializer();
            return serializer.Deserialize<List<Event>>(jsonreader);
        }
</code>```

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[uploadJSON.Event]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
  To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object.

答:
So you code should look like :

```<code>public class Body
{
    public string Type { get; set; }
    public string Value { get; set; }
    public string Format { get; set; }
}

public class Event
{
    public string Id { get; set; }
    public Body Body { get; set; }
    public object BodyProperties { get; set; }
    public string EventType { get; set; }
    public DateTime CreatedTime { get; set; }
}

public class ListOfEvents
{
    public List<Event> Events { get; set; }
}
</code>```

Finally

```<code>using (StreamReader file = File.OpenText(@"C:\TEMP\json1.json"))
        using (JsonTextReader jsonreader = new JsonTextReader(file))
        {
            var serializer = new JsonSerializer();
            return serializer.Deserialize<List<ListOfEvents>>(jsonreader);
        }
</code>```

Body:
I have below C# class structure,

public class Event
{
    public string Id { get; set; }
    public Body Body { get; set; }
    public BodyProperty[] BodyProperties { get; set; }
    public string EventType { get; set; }
    public string CreatedTime { get; set; }
}

public class BodyProperty
{
    public string Key { get; set; }
    public string Value { get; set; }
}

public class Body
{
    public Body(string value, string type = "TextualBody", string format = "application/json")
    {
        Type = type;
        Value = value;
        Format = format;
    }

    public string Type { get; set; }
    public string Value { get; set; }
    public string Format { get; set; }
}

and trying to read below JSON file,

{
    "Events": [
        {
            "Id": "d22fc23c-968f-4406-bebb-fca231694986",
            "Body": {
                "Type": "TextualBody",
                "Value": "test",
                "Format": "application/json"
            },
            "BodyProperties": null,
            "EventType": "Entity",
            "CreatedTime": "2020-02-20T13:57:14.1234165+05:30"
        },
        {
            "Id": "fgdgdg-968f-4406-bebb-646464",
            "Body": {
                "Type": "TextualBody",
                "Value": "test",
                "Format": "application/json"
            },
            "BodyProperties": null,
            "EventType": "Entity",
            "CreatedTime": "2020-02-21T13:57:14.1234165+05:30"
        }
    ]
}

But this give below error while trying to read like this, I can't change JSON format, what can I change while reading?

using (StreamReader file = File.OpenText(@"C:\TEMP\json1.json"))
        using (JsonTextReader jsonreader = new JsonTextReader(file))
        {
            var serializer = new JsonSerializer();
            return serializer.Deserialize<List<Event>>(jsonreader);
        }

Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[uploadJSON.Event]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
  To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object.

Body:
So you code should look like :

public class Body
{
    public string Type { get; set; }
    public string Value { get; set; }
    public string Format { get; set; }
}

public class Event
{
    public string Id { get; set; }
    public Body Body { get; set; }
    public object BodyProperties { get; set; }
    public string EventType { get; set; }
    public DateTime CreatedTime { get; set; }
}

public class ListOfEvents
{
    public List<Event> Events { get; set; }
}

Finally

using (StreamReader file = File.OpenText(@"C:\TEMP\json1.json"))
        using (JsonTextReader jsonreader = new JsonTextReader(file))
        {
            var serializer = new JsonSerializer();
            return serializer.Deserialize<List<ListOfEvents>>(jsonreader);
        }


问:
AssertionError in TestCafe: expected ' ' to deeply equal ' '
I'm writing test in TestCafe and I should check, that the field for typing is empty. I'm doing it using eql assertion

```<code>.expect(instanceQuery.resultField.value).eql('')
</code>```

But I'm getting an error: AssertionError: expected ' ' to deeply equal ' '

答:
When I copy/paste your error message in a console, I get empty space characters, and the eql assertion expects an empty string.

Sometimes it happens that when you copy stuff to/from the console you get different space characters. Make sure you type yourself the empty string.

You can try it out here: sandbox

Body:
I'm writing test in TestCafe and I should check, that the field for typing is empty. I'm doing it using eql assertion

.expect(instanceQuery.resultField.value).eql('')

But I'm getting an error: AssertionError: expected ' ' to deeply equal ' '


问:
Puppeteer page.select does not work for some elements
I'm trying to select "select option" value in https://www.gumtree.com/ But it doesn't change the select element's value

This is the html source for this component:

```<code>    <select name="attributes[vehicle_make]" id="vehicle_make" data-validation-group-channel="cars-vans-motorbikes-details-group" required="" aria-required="true" aria-invalid="false">
        <option value="">Please select...</option>
        <option value="abarth">Abarth</option>
        <option value="ac">AC</option>...
    </select>
</code>```

This is the code i'm using:

```<code>    const select_vehicle_type = await page.waitForSelector("#vehicle_make");
    var value = 'Audi'; // I tried both 'Audi' and 'audi' as value but both doesn't work
    await page.select('#vehicle_make', value);

</code>```

Can someone please point out what is the issue here?

答: Issue is I was trying to set the value to dropdown before the page setting initial value to the dropdown fetched from the server. I added timeout to wait and then used await page.select('#vehicle_make', value); and it worked as expected.

Body:
I'm trying to select "select option" value in https://www.gumtree.com/ But it doesn't change the select element's value

This is the html source for this component:

    <select name="attributes[vehicle_make]" id="vehicle_make" data-validation-group-channel="cars-vans-motorbikes-details-group" required="" aria-required="true" aria-invalid="false">
        <option value="">Please select...</option>
        <option value="abarth">Abarth</option>
        <option value="ac">AC</option>...
    </select>

This is the code i'm using:

    const select_vehicle_type = await page.waitForSelector("#vehicle_make");
    var value = 'Audi'; // I tried both 'Audi' and 'audi' as value but both doesn't work
    await page.select('#vehicle_make', value);

Can someone please point out what is the issue here?


问:
Javascript regex to check if a value begins with a number followed by anything else
How would i go about doing a regex to see if it begins with a number and any character can follow after. My current expression is

```<code>var validaddress = /^[0-9][A-Za-z0-9]+$/;
</code>```

But this isn't the right way. Im new to this, help anyone?

答:
If you need character(s) after the digit, try this:

```<code>var validaddress = /^[0-9].+$/;
</code>```

If characters after the digit are optional, use this:

```<code>var validaddress = /^[0-9].*$/;
</code>```

Body:
How would i go about doing a regex to see if it begins with a number and any character can follow after. My current expression is

var validaddress = /^[0-9][A-Za-z0-9]+$/;

But this isn't the right way. Im new to this, help anyone?

Body:
If you need character(s) after the digit, try this:

var validaddress = /^[0-9].+$/;

If characters after the digit are optional, use this:

var validaddress = /^[0-9].*$/;


问:
Failed to load ApplicationContext from Unit Test: FileNotFound
I am creating a Maven Spring project, which includes MVC, Data and Security.
My Spring applicationContext-*.xml files are located at \src\main\resources\spring\

My TestCase is placed at \src\test\java\my\package\controller\ and its code is:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
    "classpath:spring/applicationContext.xml",
    "classpath:spring/applicationContext-jpa.xml",
    "classpath:spring/applicationContext-security.xml" })
public class MyControllerTest extends TestCase {
    @Autowired
    private MyController myController;

    @Test
    public void myMethod_test() {
    }
}
</code>```

When I right click on the test class and run as JUnit, I get

```<code>java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:101)
at
[...]
 Caused by: org.springframework.beans.factory.BeanDefinitionStoreException:
 IOException parsing XML document from class path resource
 [applicationContext.xml]; nested exception is java.io.FileNotFoundException:
 class path resource [applicationContext.xml] cannot be opened because it does not exist
[...]
</code>```

If I try to remove applicationContext.xml from the locations, I still get exactly the same error. The complete stack trace is this:

```<code>java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:101)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:331)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:213)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:290)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:292)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:233)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:176)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [applicationContext.xml]; nested exception is java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:343)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:303)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:216)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:187)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:251)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadBeanDefinitions(AbstractGenericContextLoader.java:253)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:122)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:250)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:64)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91)
... 25 more
Caused by: java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:329)
... 37 more
</code>```

答:
If you are using intellij, then try restarting intellij cache

File-> Invalidate cache/restart

clean and build project

See if it works, it worked for me.

Body:
I am creating a Maven Spring project, which includes MVC, Data and Security.
My Spring applicationContext-*.xml files are located at \src\main\resources\spring\

My TestCase is placed at \src\test\java\my\package\controller\ and its code is:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
    "classpath:spring/applicationContext.xml",
    "classpath:spring/applicationContext-jpa.xml",
    "classpath:spring/applicationContext-security.xml" })
public class MyControllerTest extends TestCase {
    @Autowired
    private MyController myController;

    @Test
    public void myMethod_test() {
    }
}

When I right click on the test class and run as JUnit, I get

java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:101)
at
[...]
 Caused by: org.springframework.beans.factory.BeanDefinitionStoreException:
 IOException parsing XML document from class path resource
 [applicationContext.xml]; nested exception is java.io.FileNotFoundException:
 class path resource [applicationContext.xml] cannot be opened because it does not exist
[...]

If I try to remove applicationContext.xml from the locations, I still get exactly the same error. The complete stack trace is this:

java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99)
at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:101)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:331)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:213)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:290)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:292)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:233)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:176)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [applicationContext.xml]; nested exception is java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:343)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:303)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:216)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:187)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:251)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadBeanDefinitions(AbstractGenericContextLoader.java:253)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:122)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:250)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:64)
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91)
... 25 more
Caused by: java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:329)
... 37 more


问:
Phone Verification with the Twilio API using java
Implementing authentication in a project and using phone verification with the Twilio API but have run into an error that I later carried a simple test with code I have added below. Did a basic test with sample code I got from the official twilio documentation from their site and had this error which I haven't been able to figure out.

Here is the sample code.

```<code>import com.twilio.Twilio;
import com.twilio.rest.verify.v2.service.Verification;

public class Login {
    public final static String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    public final static String AUTH_TOKEN = "auth_token";

    public static void main(String[] args) {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
        Verification verification = Verification.creator(
                "VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
                "+237677777777",
                "sms")
                .create();

        System.out.println(verification.getStatus());
    }
}

</code>```

Here is the error

```<code>/usr/lib/jvm/java-1.8.0-openjdk-amd64/bin/java -javaagent:/snap/intellij
Exception in thread "main" com.twilio.exception.ApiException: Cannot deserialize instance of `java.util.LinkedHashMap<java.lang.Object,java.lang.Object>` out of START_ARRAY token
 at [Source: (ByteArrayInputStream); line: 1, column: 100] (through reference chain: com.twilio.rest.verify.v2.service.Verification["send_code_attempts"])
    at com.twilio.rest.verify.v2.service.Verification.fromJson(Verification.java:167)
    at com.twilio.rest.verify.v2.service.VerificationCreator.create(VerificationCreator.java:201)
    at com.twilio.rest.verify.v2.service.VerificationCreator.create(VerificationCreator.java:23)
    at com.twilio.base.Creator.create(Creator.java:45)
    at Login.main(Login.java:14)
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.LinkedHashMap<java.lang.Object,java.lang.Object>` out of START_ARRAY token
 at [Source: (ByteArrayInputStream); line: 1, column: 100] (through reference chain: com.twilio.rest.verify.v2.service.Verification["send_code_attempts"])
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59)
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1442)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1216)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1126)
    at com.fasterxml.jackson.databind.deser.std.StdDeserializer._deserializeFromEmpty(StdDeserializer.java:639)
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:360)
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:29)
    at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:530)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeWithErrorWrapping(BeanDeserializer.java:528)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeUsingPropertyBased(BeanDeserializer.java:417)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1287)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:326)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:159)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4202)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3242)
    at com.twilio.rest.verify.v2.service.Verification.fromJson(Verification.java:165)
    ... 4 more

Process finished with exit code 1
</code>```

Please any help will be much appreciated, im new to Twilio.

答:
Halo found a walk around this bug. In the meanwhile, while Twilio handles that you can use this way to get the verification code if you are facing same issue :)

I used the java Process class and the curl to post

Here is the code.

```<code>void method(String var) throws IOException {

  String command ="curl -X POST https://verify.twilio.com/v2/Services/" + SERVICE_ID + "/Verifications --data-urlencode To=" + phoneNumber +
                        " --data-urlencode Channel=sms -u " + ACCOUNT_SID + ":" + AUTH_TOKEN;

  Process process = Runtime.getRuntime().exec(command);
  process.getInputStream();
// some code
}
</code>```

Body:
Implementing authentication in a project and using phone verification with the Twilio API but have run into an error that I later carried a simple test with code I have added below. Did a basic test with sample code I got from the official twilio documentation from their site and had this error which I haven't been able to figure out.

Here is the sample code.

import com.twilio.Twilio;
import com.twilio.rest.verify.v2.service.Verification;

public class Login {
    public final static String ACCOUNT_SID = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
    public final static String AUTH_TOKEN = "auth_token";

    public static void main(String[] args) {
        Twilio.init(ACCOUNT_SID, AUTH_TOKEN);
        Verification verification = Verification.creator(
                "VAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
                "+237677777777",
                "sms")
                .create();

        System.out.println(verification.getStatus());
    }
}

Here is the error

/usr/lib/jvm/java-1.8.0-openjdk-amd64/bin/java -javaagent:/snap/intellij
Exception in thread "main" com.twilio.exception.ApiException: Cannot deserialize instance of `java.util.LinkedHashMap<java.lang.Object,java.lang.Object>` out of START_ARRAY token
 at [Source: (ByteArrayInputStream); line: 1, column: 100] (through reference chain: com.twilio.rest.verify.v2.service.Verification["send_code_attempts"])
    at com.twilio.rest.verify.v2.service.Verification.fromJson(Verification.java:167)
    at com.twilio.rest.verify.v2.service.VerificationCreator.create(VerificationCreator.java:201)
    at com.twilio.rest.verify.v2.service.VerificationCreator.create(VerificationCreator.java:23)
    at com.twilio.base.Creator.create(Creator.java:45)
    at Login.main(Login.java:14)
Caused by: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.LinkedHashMap<java.lang.Object,java.lang.Object>` out of START_ARRAY token
 at [Source: (ByteArrayInputStream); line: 1, column: 100] (through reference chain: com.twilio.rest.verify.v2.service.Verification["send_code_attempts"])
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59)
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1442)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1216)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1126)
    at com.fasterxml.jackson.databind.deser.std.StdDeserializer._deserializeFromEmpty(StdDeserializer.java:639)
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:360)
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:29)
    at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:530)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeWithErrorWrapping(BeanDeserializer.java:528)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeUsingPropertyBased(BeanDeserializer.java:417)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1287)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:326)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:159)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4202)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3242)
    at com.twilio.rest.verify.v2.service.Verification.fromJson(Verification.java:165)
    ... 4 more

Process finished with exit code 1

Please any help will be much appreciated, im new to Twilio.

Body:
Halo found a walk around this bug. In the meanwhile, while Twilio handles that you can use this way to get the verification code if you are facing same issue :)

I used the java Process class and the curl to post

Here is the code.

void method(String var) throws IOException {

  String command ="curl -X POST https://verify.twilio.com/v2/Services/" + SERVICE_ID + "/Verifications --data-urlencode To=" + phoneNumber +
                        " --data-urlencode Channel=sms -u " + ACCOUNT_SID + ":" + AUTH_TOKEN;

  Process process = Runtime.getRuntime().exec(command);
  process.getInputStream();
// some code
}


问:
Sitecore Caching for SSL + non-SSL sublayout
I have a little issue with a sublayout outputting data which should differ between SSL and non-SSL requests.

To replicate if you create a sublayout and in code behind render out the URL. If you then add this sublayout to a page through the sitecore interface, eg: presentation>details etc and set caching on and set all caching variable to on. Do you publish etc so the page is now viewable (also behaves the same if your doing it directly calling the the control by sublayout control in code).

If you execute this page in non-ssl mode (http://URL) you will get a URL such as; http://URL...
Then if you execute this page in ssl mode (https://URL) your output will still be http://URL...

So does anyone know of a way to get this so we an cache both instances.

Regards,
Chris

答:
You can use the existing VaryByParm functionality to create a VaryByUrl behaviour by programatically setting the cache key for the sublayout with the complete request url, including the scheme. I believe this would be the same process as described in Mark Ursino's response here: Customizing sublayout caching in Sitecore

As a side note, if in a multilanguage site with language prefixes be aware that using Sitecore.Context.RawUrl will give you the request url with language prefixes stripped out by the actions of the StripLanguage preProcessRequest pipeline step.

Paul


问:
How to use project dependencies with ts-node
I am currently debugging a project that uses ts-node to run locally. Do I have to install ts-node globally for this?

I did install it globally, but now i am seeing typescript errors that stems from diverging typescript versions. I fixed it by setting it to the same version.

Is there a way to use my project dependencies in my CLI to run the project? Or do I HAVE to install things globally?

答:
Since npm@5.2.0, npm ships with the npx package, which lets you run commands from the node_modules/.bin directory in your current project. For example: npx ts-node -v.

If for whatever reason you have an older version of npm, you can install this package globally with npm install -g npx.

You can use npx <package-name> also for packages that aren't installed yet in your project (see its options).

Alternatively, you can put the following into your package.json:

```<code>"scripts": {
    "start": "ts-node code/start.ts",
}
</code>```

Commands in the scripts field also use the local version of a package.

Body:
Since npm@5.2.0, npm ships with the npx package, which lets you run commands from the node_modules/.bin directory in your current project. For example: npx ts-node -v.

If for whatever reason you have an older version of npm, you can install this package globally with npm install -g npx.

You can use npx <package-name> also for packages that aren't installed yet in your project (see its options).

Alternatively, you can put the following into your package.json:

"scripts": {
    "start": "ts-node code/start.ts",
}

Commands in the scripts field also use the local version of a package.


问:
RealmChangeListener not working for the first install. Why?
I'm trying to set ChangeListener for RealmResults<Model> inside a fragment. It does not work only for the first time (Fresh install), after that it works even if the app is killed.

```<code>onCreateView(...){
        mModelResults = mRealm.where(Model::class.java).findAllAsync()
        mModelResults.addChangeListener(RealmChangeListener {

        })
}

Am I missing something ?

</code>```

答:
It worked when I changed few things.

(1) Initialized model class in realm database with some data for the first time/install.

(2) Changed findAllAsync() to findAll.

Body:
I'm trying to set ChangeListener for RealmResults<Model> inside a fragment. It does not work only for the first time (Fresh install), after that it works even if the app is killed.

onCreateView(...){
        mModelResults = mRealm.where(Model::class.java).findAllAsync()
        mModelResults.addChangeListener(RealmChangeListener {

        })
}

Am I missing something ?


问:
How to transform template to template pre C++11
Triggered by this question I wrote a template that allows to transform a template into a template with different parameters:

```<code>template< template <int A,char B,bool> typename T>
struct Add_true {
    template <int A,char B> using type = T<A,B,true>;
};
</code>```

Background: The aim was to pass a template<int A, char B, bool C> class A2{}; as template template parameter to a template<template<int A, char B> typename T> class A1 {};. I learned about templates with C++11. It was quite a shift in thinking about code once I got used to writing types/functions that take types and "return" types instead of writing functions that take values and return values. It never occurred to me that it is also surprisingly simple to write templates that given a template "return" a different template. The thing is I have not the slightest clue how to write the above or similar without alias templates that are only available since C++11. What was possible always afaik is the following. Given

```<code>template <int A,char B, bool C> struct Foo{};
</code>```

I can "bind" a bool parameter to Foo via:

```<code>template <int A,char B>
struct Add_true_to_Foo {
     typedef Foo<A,B> type;
};
</code>```

But now Add_true_to_Foo::type is not a template and I have not the slightest clue without C++11 how to write a Add_true that would not only work for Foo but also for

```<code>template <int A,char B, bool C> struct Bar{};
</code>```

Maybe I am missing something obvious. My quesiton is

Is it possible to write an equivalent to the above Add_true before C++11?

答:
There are no strict equivalents of the C++11 template using,
but you can add extra template class instead to mimic behavior and with different syntax:

```<code>template <template <int, char, bool> class C>
struct Add_true {
    template <int A, char B>
    struct apply
    {
        typedef T<A, B, true> type;
    }
};
</code>```

With usage:

```<code>template <int A,char B, bool C> struct Foo{};

typedef Add_true<Foo>::apply<42, '*'>::type my_type; // Foo<42, '*', true>
</code>```

Body:
Triggered by this question I wrote a template that allows to transform a template into a template with different parameters:

template< template <int A,char B,bool> typename T>
struct Add_true {
    template <int A,char B> using type = T;
};

Background: The aim was to pass a template<int A, char B, bool C> class A2{}; as template template parameter to a template<template<int A, char B> typename T> class A1 {};. I learned about templates with C++11. It was quite a shift in thinking about code once I got used to writing types/functions that take types and "return" types instead of writing functions that take values and return values. It never occurred to me that it is also surprisingly simple to write templates that given a template "return" a different template. The thing is I have not the slightest clue how to write the above or similar without alias templates that are only available since C++11. What was possible always afaik is the following. Given

template <int A,char B, bool C> struct Foo{};

I can "bind" a bool parameter to Foo via:

template <int A,char B>
struct Add_true_to_Foo {
     typedef Foo type;
};

But now Add_true_to_Foo::type is not a template and I have not the slightest clue without C++11 how to write a Add_true that would not only work for Foo but also for

template <int A,char B, bool C> struct Bar{};

Maybe I am missing something obvious. My quesiton is

Is it possible to write an equivalent to the above Add_true before C++11?

Body:
There are no strict equivalents of the C++11 template using,
but you can add extra template class instead to mimic behavior and with different syntax:

template <template <int, char, bool> class C>
struct Add_true {
    template <int A, char B>
    struct apply
    {
        typedef T<A, B, true> type;
    }
};

With usage:

template <int A,char B, bool C> struct Foo{};

typedef Add_true<Foo>::apply<42, '*'>::type my_type; // Foo<42, '*', true>


问:
Sequelize : Get Subquery/Raw Query as model for include
I have gone through the Sequelize doc, but can't find anything helpful

What I want to do is to add raw query or custom model in include, is it possible ?

```<code>model.Post.findAll({
            include: [{
                    model: model.User,
                    attributes: ['fullname', 'profilepic'],
                },
                {
                    model: model.PostComments,
                },
                {
                    model: "Raw Query"
                }
            ]
        }
</code>```

What I want to achieve is like :

```<code>Select post_id, count(*) as total_likes from post_likes group by post_id
</code>```

I can't achieve this by using simply include, so what I want to do is create a table/model from above query and then use it inside include.

If I use group by withing include it gives group by from top level, and I want to apply group by just for the post_like table.

Please let me know, if it found confusing or not clear.

答:
I was looking to do the same, use a raw query dynamically formed inside the include but there's no possible way to use include without a model https://sequelize.org/master/class/lib/model.js~Model.html#static-method-findAll .

For the purposes of my MySQL I turned my inner join (include) into a where in. I was doing the inner join to avoid the exception This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery . I get this exception because I have a subquery with LIMIT applied.

If it helps anyone:

```<code>let rows = await j_model.findAll({
        attributes: [...j_columns, `${association}.meta_key_id`],
        include: [
            {
                model: um_model,
                as: association,
                attributes: ['um_id'],
                on: {'j_id' : {$col: 'j.j_id'} }
        ],
        where: {'j_id': {$in: sequelize.literal(`(SELECT * FROM (${massive_inner_raw_query}) as tmp)`)}},
        logging: console.log
    });
</code>```

The actual magic is in this line:

```<code>where: {'j_id': {$in: sequelize.literal(`(SELECT * FROM (${massive_inner_raw_query}) as tmp)`)}}
</code>```

The SELECT * FROM removes that exception and lets me do a where in instead of the wanted INNER JOIN. Maybe you can apply a similar deal to your problem.

Body:
I have gone through the Sequelize doc, but can't find anything helpful

What I want to do is to add raw query or custom model in include, is it possible ?

model.Post.findAll({
            include: [{
                    model: model.User,
                    attributes: ['fullname', 'profilepic'],
                },
                {
                    model: model.PostComments,
                },
                {
                    model: "Raw Query"
                }
            ]
        }

What I want to achieve is like :

Select post_id, count(*) as total_likes from post_likes group by post_id

I can't achieve this by using simply include, so what I want to do is create a table/model from above query and then use it inside include.

If I use group by withing include it gives group by from top level, and I want to apply group by just for the post_like table.

Please let me know, if it found confusing or not clear.

Body:
I was looking to do the same, use a raw query dynamically formed inside the include but there's no possible way to use include without a model https://sequelize.org/master/class/lib/model.js~Model.html#static-method-findAll .

For the purposes of my MySQL I turned my inner join (include) into a where in. I was doing the inner join to avoid the exception This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery . I get this exception because I have a subquery with LIMIT applied.

If it helps anyone:

let rows = await j_model.findAll({
        attributes: [...j_columns, `${association}.meta_key_id`],
        include: [
            {
                model: um_model,
                as: association,
                attributes: ['um_id'],
                on: {'j_id' : {$col: 'j.j_id'} }
        ],
        where: {'j_id': {$in: sequelize.literal(`(SELECT * FROM (${massive_inner_raw_query}) as tmp)`)}},
        logging: console.log
    });

The actual magic is in this line:

where: {'j_id': {$in: sequelize.literal(`(SELECT * FROM (${massive_inner_raw_query}) as tmp)`)}}

The SELECT * FROM removes that exception and lets me do a where in instead of the wanted INNER JOIN. Maybe you can apply a similar deal to your problem.


答:
I suppose this should work</p>

```<code>/^\d+.+$/
</code>```

Title: Javascript regex to check if a value begins with a number followed by anything else

Body:
I suppose this should work

/^\d+.+$/


问:
Find a record in json Object if the record has specific key in python
I have a JSON object which has 100000 records. I want a select a record which has specific value to the one of the key

Eg:

```<code>[{
    "name": "bindu",
    "age": "24",
    "qualification": "b.tech"
},
{
    "name": "naveen",
    "age": "23",
    "qualification": "b.tech"
},
{
    "name": "parvathi",
    "age": "23",
    "qualification": "m.tech"
},
{
    "name": "bindu s",
    "status": "married"
},
{
    "name": "naveen k",
    "status": "unmarried"

}]
</code>```

now I want to combine the records which are having the name with 'bindu' and 'bindu s. We can achieve this by iterating on the JSON object but since the size is more it is taking more time. Is there any way to make this easy.

I want the output like

```<code>[{
    "name": "bindu",
    "age": "24",
    "qualification": "b.tech",
    "status": "married"
},
{
    "name": "naveen",
    "age": "23",
    "qualification": "b.tech",
    "status": "unmarried"

},
{
    "name": "parvathi",
    "age": "23",
    "qualification": "m.tech"
    "status": ""
},
</code>```

答:
This will rename and merge your objects by first name.</p>

```<code>jq 'map(.name |= split(" ")[0]) | group_by(.name) | map(add)'
</code>```

Body:
I have a JSON object which has 100000 records. I want a select a record which has specific value to the one of the key

Eg:

[{
    "name": "bindu",
    "age": "24",
    "qualification": "b.tech"
},
{
    "name": "naveen",
    "age": "23",
    "qualification": "b.tech"
},
{
    "name": "parvathi",
    "age": "23",
    "qualification": "m.tech"
},
{
    "name": "bindu s",
    "status": "married"
},
{
    "name": "naveen k",
    "status": "unmarried"

}]

now I want to combine the records which are having the name with 'bindu' and 'bindu s. We can achieve this by iterating on the JSON object but since the size is more it is taking more time. Is there any way to make this easy.

I want the output like

[{
    "name": "bindu",
    "age": "24",
    "qualification": "b.tech",
    "status": "married"
},
{
    "name": "naveen",
    "age": "23",
    "qualification": "b.tech",
    "status": "unmarried"

},
{
    "name": "parvathi",
    "age": "23",
    "qualification": "m.tech"
    "status": ""
},

Body:
This will rename and merge your objects by first name.

jq 'map(.name |= split(" ")[0]) | group_by(.name) | map(add)'


问:
Integrity Error when trying to upload to MySQL DB in python
I have this code which currently lets me update a school's data in mySQL database, if the id already exists. However, what I am also trying to achieve, is that if the ID doesn't exist in the DB, it inserts those values. Here is the code I've got so far:

```<code>from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@localhost/dbName'
db = SQLAlchemy(app)

class Example(db.Model):
    __tablename__ = 'schools'
    _id = db.Column('_id', db.Unicode, primary_key=True)
    establishmentNumber = db.Column('establishmentNumber', db.Unicode)

    def __init__(self, id, establishmentNumber):
        self.id = id
        self.establishmentNumber = establishmentNumber

update_this = Example.query.filter_by(_id=school._id.iloc[0]).first()

update_this.establishmentNumber = 'bob'
db.session.commit()

examples = Example.query.all()
examples

for ex in examples:
    print (ex.establishmentNumber)
</code>```

This will update correctly, however, when I try to add a completely new school to the db, with this code:

```<code>new_ex = Example('5c12345scl', 'fifth')
db.session.add(new_ex)
db.session.commit()
</code>```

I get this error:

```<code>IntegrityError: (MySQLdb._exceptions.IntegrityError) (1364, "Field '_id' doesn't have a default value")
[SQL: INSERT INTO schools (`establishmentNumber`) VALUES (%s)]
[parameters: ('fifth',)]
(Background on this error at: http://sqlalche.me/e/gkpj)
</code>```

Does anyone know how to get rid of this error?

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
UPDATE
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

The above is working now. I am now trying to combine the add and update functions so that it checks if the id exists in the table. If not, it inserts a new row. If it does, then it just updates the values. Below is my code so far, thanks to @James Summers:

```<code>class Example(db.Model):
    __tablename__ = 'schools'
    _id = db.Column('_id', db.Unicode, primary_key=True)
    establishmentNumber = db.Column('establishmentNumber', db.Unicode)
    laCode = db.Column('laCode', db.Unicode)
    urn = db.Column('urn', db.Unicode)
    name = db.Column('name', db.Unicode)
    phaseOfEducation = db.Column('phaseOfEducation', db.Unicode)
    wondeID = db.Column('wondeID', db.Unicode)

    def __init__(self, _id, establishmentNumber, laCode, urn, name, phaseOfEducation, wondeID):
        self._id = _id
        self.establishmentNumber = establishmentNumber
        self.laCode = laCode
        self.urn = urn
        self.name = name
        self.phaseOfEducation = phaseOfEducation
        self.wondeID = wondeID

        def add_or_update(self, _id, establishmentNumber, laCode, urn, name, phaseOfEducation, wondeID):
            update_this = Example.query.filter_by(_id=school._id.iloc[0]).first()

            if not update_this:
                new_ex = Example(school._id.iloc[0], school.establishmentNumber.iloc[0], school.laCode.iloc[0], school.urn.iloc[0], school.name.iloc[0], school.phaseOfEducation.iloc[0], school.wondeID.iloc[0])
                db.session.add(new_ex)
                db.session.commit()

            else:
                update_this.establishmentNumber = 'hello'
                db.session.commit()

            return new_ex
</code>```

It is not producing any errors, but it's not adding or updating either. Can anyone see what I've done wrong?

答:
The error is perhaps with your constructor.

You have a class member that is:
_id = db.Column('_id', db.Unicode, primary_key=True)

but in your constructor you're setting self.id = id

A fix for this problem would be to either update your model for the code to look like this:

class Example(db.Model):
    __tablename__ = 'schools'
    _id = db.Column('_id', db.Unicode, primary_key=True)
    establishmentNumber = db.Column('establishmentNumber', db.Unicode)

    def __init__(self, id, establishmentNumber):
        self._id = id
        self.establishmentNumber = establishmentNumber
```

<p>or what someone in the comments suggested to do by adding a default value to your column. However, I would not suggest adding a default value to your primary key. </p>

<p>Another possible solution for this problem is to create an <code>add_or_update</code> method to your class, which is the better solution for the long run. You do it by adding a class method which gets a result by id, if it doesn't exist, your code will create one or update the existing retrieved result. This is how you would implement the following code:</p>

<pre class="lang-py prettyprint-override"><code>class Example(db.Model):
    __tablename__ = 'schools'

    _id = db.Column('_id', db.Unicode, primary_key=True)
    establishmentNumber = db.Column('establishmentNumber', db.Unicode)

    def __init__(self, id, establishmentNumber):
        self._id = id
        self.establishmentNumber = establishmentNumber

    @classmethod
    def add_or_update(cls, example_id, establishmentNumber):
        entity = cls.query.filter_by(id=example_id).first()

        if not entity:
          entity = cls(example_id, establishmentNumber)

        entity.establishmentNumber = establishmentNumber

        db.session.add(entity)
        db.session.commit()

        return entity
</code>```

Good luck and cheers!

Body:
I have this code which currently lets me update a school's data in mySQL database, if the id already exists. However, what I am also trying to achieve, is that if the ID doesn't exist in the DB, it inserts those values. Here is the code I've got so far:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@localhost/dbName'
db = SQLAlchemy(app)

class Example(db.Model):
    __tablename__ = 'schools'
    _id = db.Column('_id', db.Unicode, primary_key=True)
    establishmentNumber = db.Column('establishmentNumber', db.Unicode)

    def __init__(self, id, establishmentNumber):
        self.id = id
        self.establishmentNumber = establishmentNumber

update_this = Example.query.filter_by(_id=school._id.iloc[0]).first()

update_this.establishmentNumber = 'bob'
db.session.commit()

examples = Example.query.all()
examples

for ex in examples:
    print (ex.establishmentNumber)

This will update correctly, however, when I try to add a completely new school to the db, with this code:

new_ex = Example('5c12345scl', 'fifth')
db.session.add(new_ex)
db.session.commit()

I get this error:

IntegrityError: (MySQLdb._exceptions.IntegrityError) (1364, "Field '_id' doesn't have a default value")
[SQL: INSERT INTO schools (`establishmentNumber`) VALUES (%s)]
[parameters: ('fifth',)]
(Background on this error at: http://sqlalche.me/e/gkpj)

Does anyone know how to get rid of this error?

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
UPDATE
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''

The above is working now. I am now trying to combine the add and update functions so that it checks if the id exists in the table. If not, it inserts a new row. If it does, then it just updates the values. Below is my code so far, thanks to @James Summers:

class Example(db.Model):
    __tablename__ = 'schools'
    _id = db.Column('_id', db.Unicode, primary_key=True)
    establishmentNumber = db.Column('establishmentNumber', db.Unicode)
    laCode = db.Column('laCode', db.Unicode)
    urn = db.Column('urn', db.Unicode)
    name = db.Column('name', db.Unicode)
    phaseOfEducation = db.Column('phaseOfEducation', db.Unicode)
    wondeID = db.Column('wondeID', db.Unicode)

    def __init__(self, _id, establishmentNumber, laCode, urn, name, phaseOfEducation, wondeID):
        self._id = _id
        self.establishmentNumber = establishmentNumber
        self.laCode = laCode
        self.urn = urn
        self.name = name
        self.phaseOfEducation = phaseOfEducation
        self.wondeID = wondeID

        def add_or_update(self, _id, establishmentNumber, laCode, urn, name, phaseOfEducation, wondeID):
            update_this = Example.query.filter_by(_id=school._id.iloc[0]).first()

            if not update_this:
                new_ex = Example(school._id.iloc[0], school.establishmentNumber.iloc[0], school.laCode.iloc[0], school.urn.iloc[0], school.name.iloc[0], school.phaseOfEducation.iloc[0], school.wondeID.iloc[0])
                db.session.add(new_ex)
                db.session.commit()

            else:
                update_this.establishmentNumber = 'hello'
                db.session.commit()

            return new_ex

It is not producing any errors, but it's not adding or updating either. Can anyone see what I've done wrong?

Body:
The error is perhaps with your constructor.

You have a class member that is:
_id = db.Column('_id', db.Unicode, primary_key=True)

but in your constructor you're setting self.id = id

A fix for this problem would be to either update your model for the code to look like this:

class Example(db.Model):
    __tablename__ = 'schools'
    _id = db.Column('_id', db.Unicode, primary_key=True)
    establishmentNumber = db.Column('establishmentNumber', db.Unicode)

    def __init__(self, id, establishmentNumber):
        self._id = id
        self.establishmentNumber = establishmentNumber

or what someone in the comments suggested to do by adding a default value to your column. However, I would not suggest adding a default value to your primary key.

Another possible solution for this problem is to create an add_or_update method to your class, which is the better solution for the long run. You do it by adding a class method which gets a result by id, if it doesn't exist, your code will create one or update the existing retrieved result. This is how you would implement the following code:

class Example(db.Model):
    __tablename__ = 'schools'

    _id = db.Column('_id', db.Unicode, primary_key=True)
    establishmentNumber = db.Column('establishmentNumber', db.Unicode)

    def __init__(self, id, establishmentNumber):
        self._id = id
        self.establishmentNumber = establishmentNumber

    @classmethod
    def add_or_update(cls, example_id, establishmentNumber):
        entity = cls.query.filter_by(id=example_id).first()

        if not entity:
          entity = cls(example_id, establishmentNumber)

        entity.establishmentNumber = establishmentNumber

        db.session.add(entity)
        db.session.commit()

        return entity

Good luck and cheers!


问:
Lightgallery: Fit Image to Browser Window
I use the Lightgallery Plugin for my image gallery. It works perfectly but there is something which is not perfect. I want to fit the images into the browser window.

It works when the resolution of the image is higher than the resolution of the browser window. But when it is smaller it doesn´t fit.

Here is the plugin:
http://sachinchoolur.github.io/lightGallery/

Does anybody have an idea or script to solve the problem?

Thanks,
Jannis

答:
This helped for me in Lightgallery v1.2.6:</p>

```<code>.lg-outer .lg-img-wrap {
    max-width:100vw;
    max-height: 100vh;
}
</code>```

Body:
This helped for me in Lightgallery v1.2.6:

.lg-outer .lg-img-wrap {
    max-width:100vw;
    max-height: 100vh;
}