问:
How to Populate and Aggregate
i want to aggregate the ratings so i could get the total of feedbacks. But the thing is, it's referenced. Here's my schema

User

```<code>    username: String,
    fullname: String,
    email: {
        type: String,
        lowercase: true,
        unique: true
    },
  address: String,
  password: String,
  feedback: [{
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Feedback'
  }]
</code>```

Feedback

```<code>var FeedbackSchema = new mongoose.Schema({
    postname: String,
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    message: String,
    feedbacktype: String,
    thumbsup: Boolean,
    rating: {
        communication: Number,
        timeliness: Number,
        delivery: Number
    }
});
</code>```

So what i want to achieve is, i will find the User by id then populate the feedbacks field, then i will aggregate the ratings on the feedback field so i would get a total of number of ratings for communication, for delivery and for timeliness. (The ratings are 1-5 stars)

Do you know how to aggregate and populate? thank you

**update

So i've run the aggregation to the user schema, now im getting 0 results from all ratings

```<code>User.aggregate([
  { "$match": { "_id": ObjectId('593150f6ac4d9b0410d2aac0') } },
  { "$lookup": {
    "from": "feedbacks",
    "localField": "feedback",
    "foreignField": "_id",
    "as": "feedback"
  }},
  { "$project": {
    "username": 1,
    "fullname": 1,
    "email": 1,
    "password": 1,
    "rating": {
      "communication": { "$sum": "$feedback.rating.communication" },
      "timeliness": { "$sum": "$feedback.rating.timeliness" },
      "delivery": { "$sum": "$feedback.rating.delivery" }
    }
  }}
]).exec(function(err, a){
    console.log(a)
})
</code>```

result rating: { communication: 0, timeliness: 0, delivery: 0 } } ]

also tried it with other users, all of them 0 result rating

答:
Simple Listing to Follow

```<code>var async = require('async'),
    mongoose = require('mongoose'),
    Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/rating');

var userSchema = new Schema({
  username: String,
  feedback: [{ type: Schema.Types.ObjectId, ref: 'Feedback' }]
});

var feedbackSchema = new Schema({
  rating: {
    communication: Number,
    timeliness: Number,
    delivery: Number
  }
});

var User = mongoose.model('User', userSchema);
var Feedback = mongoose.model('Feedback', feedbackSchema);
async.series(
  [
    (callback) => {
      async.each([User,Feedback],(model,callback) => {
        model.remove({},callback);
      },callback);
    },

    (callback) => {
      async.waterfall(
        [
          (callback) => {
            async.map(
              [
                { "rating": {
                  "communication": 1, "timeliness": 2, "delivery": 3
                }},
                { "rating": {
                  "communication": 2, "timeliness": 3, "delivery": 4
                }}
              ],
              (item,callback) => {
                Feedback.create(item,callback)
              },
              callback
            );
          },
          (feedback, callback) => {
            User.create({ "username": "Bill", "feedback": feedback },callback);
          },
          (user, callback) => {
            User.aggregate([
              { "$match": { "_id": user._id } },
              { "$lookup": {
                "from": "feedbacks",
                "localField": "feedback",
                "foreignField": "_id",
                "as": "feedback"
              }},
              { "$project": {
                "username": 1,
                "rating": {
                  "communication": { "$sum": "$feedback.rating.communication" },
                  "timeliness": { "$sum": "$feedback.rating.timeliness" },
                  "delivery": { "$sum": "$feedback.rating.delivery" }
                }
              }}
            ],(err,results) => {
              console.log(JSON.stringify(results, undefined, 2));
              callback(err);
            });
          }
        ],
        callback
      )
    }
  ],
  (err) => {
    if (err) throw err;
    mongoose.disconnect();
  }
);
</code>```

This will create two collections as User

```<code>{
        "_id" : ObjectId("593548455198ab3c09cf736b"),
        "username" : "Bill",
        "feedback" : [
                ObjectId("593548455198ab3c09cf7369"),
                ObjectId("593548455198ab3c09cf736a")
        ],
        "__v" : 0
}
</code>```

And feedbacks:

```<code>{
        "_id" : ObjectId("593548455198ab3c09cf7369"),
        "rating" : {
                "communication" : 1,
                "timeliness" : 2,
                "delivery" : 3
        },
        "__v" : 0
}
{
        "_id" : ObjectId("593548455198ab3c09cf736a"),
        "rating" : {
                "communication" : 2,
                "timeliness" : 3,
                "delivery" : 4
        },
        "__v" : 0
}
</code>```

Program Output Shows the aggregation:

```<code>[
  {
    "_id": "5935494a159c633c1b34807b",
    "username": "Bill",
    "rating": {
      "communication": 3,
      "timeliness": 5,
      "delivery": 7
    }
  }
]
</code>```

Also package.json if the two dependencies are not clear enough:

```<code>{
  "name": "ratings",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "async": "^2.4.1",
    "mongoose": "^4.10.4"
  }
}
</code>```

Original Answer

Personally I would work this from the "Feedback" since you have the user already recorded there, and it is actually the way this scales better.

Instead of using population, we can instead use $lookup with a MongoDB server version of at least 3.2:

```<code>Feedback.aggregate([
  { "$match": { "user": userId } },
  { "$group": {
    "_id": "$user",
    "communication": { "$sum": "$rating.communication" },
    "timeliness": { "$sum": "$rating.timeliness" },
    "delivery": { "$sum": "$rating.delivery" }
  }},
  { "$lookup": {
    "from": "users",
    "localField": "_id",
    "foreignField": "_id",
    "as": "user"
  }},
  { "$unwind": "$user" }
])
</code>```

If you do not have a server version that supports $lookupthen you can still "manually join" the User details with something like this:

```<code>Feedback.aggregate([
  { "$match": { "user": userId } },
  { "$group": {
    "_id": "$user",
    "communication": { "$sum": "$rating.communication" },
    "timeliness": { "$sum": "$rating.timeliness" },
    "delivery": { "$sum": "$rating.delivery" }
  }}
],function(err, results) {
    result = results[0];
    User.findById(userId).lean().exec(function(err, user) {
      result.user = user;     // swap the _id for the Object

      // Then output result
    });
})
</code>```

Which is basically what .populate() does, but we are doing it manually and efficiently for the result returned.

You can work the other way around from the User model, but it's likely more efficient to simply work this way around.

```<code>User.aggregate([
  { "$match": { "_id": userid } },
  { "$lookup": {
    "from": "feedbacks",
    "localField": "feedback",
    "foreignField": "_id",
    "as": "feedback"
  }},
  { "$project": {
    "username": 1,
    "fullname": 1,
    "email": 1,
    "password": 1,
    "rating": {
      "communication": { "$sum": "$feedback.rating.communication" },
      "timeliness": { "$sum": "$feedback.rating.timeliness" },
      "delivery": { "$sum": "$feedback.rating.delivery" }
    }
  }}
])
</code>```

Title: How to Populate and Aggregate

Body:
i want to aggregate the ratings so i could get the total of feedbacks. But the thing is, it's referenced. Here's my schema

User

    username: String,
    fullname: String,
    email: {
        type: String,
        lowercase: true,
        unique: true
    },
  address: String,
  password: String,
  feedback: [{
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Feedback'
  }]

Feedback

var FeedbackSchema = new mongoose.Schema({
    postname: String,
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    message: String,
    feedbacktype: String,
    thumbsup: Boolean,
    rating: {
        communication: Number,
        timeliness: Number,
        delivery: Number
    }
});

So what i want to achieve is, i will find the User by id then populate the feedbacks field, then i will aggregate the ratings on the feedback field so i would get a total of number of ratings for communication, for delivery and for timeliness. (The ratings are 1-5 stars)

Do you know how to aggregate and populate? thank you

**update

So i've run the aggregation to the user schema, now im getting 0 results from all ratings

User.aggregate([
  { "$match": { "_id": ObjectId('593150f6ac4d9b0410d2aac0') } },
  { "$lookup": {
    "from": "feedbacks",
    "localField": "feedback",
    "foreignField": "_id",
    "as": "feedback"
  }},
  { "$project": {
    "username": 1,
    "fullname": 1,
    "email": 1,
    "password": 1,
    "rating": {
      "communication": { "$sum": "$feedback.rating.communication" },
      "timeliness": { "$sum": "$feedback.rating.timeliness" },
      "delivery": { "$sum": "$feedback.rating.delivery" }
    }
  }}
]).exec(function(err, a){
    console.log(a)
})

result rating: { communication: 0, timeliness: 0, delivery: 0 } } ]

also tried it with other users, all of them 0 result rating

Body:
Simple Listing to Follow

var async = require('async'),
    mongoose = require('mongoose'),
    Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/rating');

var userSchema = new Schema({
  username: String,
  feedback: [{ type: Schema.Types.ObjectId, ref: 'Feedback' }]
});

var feedbackSchema = new Schema({
  rating: {
    communication: Number,
    timeliness: Number,
    delivery: Number
  }
});

var User = mongoose.model('User', userSchema);
var Feedback = mongoose.model('Feedback', feedbackSchema);
async.series(
  [
    (callback) => {
      async.each([User,Feedback],(model,callback) => {
        model.remove({},callback);
      },callback);
    },

    (callback) => {
      async.waterfall(
        [
          (callback) => {
            async.map(
              [
                { "rating": {
                  "communication": 1, "timeliness": 2, "delivery": 3
                }},
                { "rating": {
                  "communication": 2, "timeliness": 3, "delivery": 4
                }}
              ],
              (item,callback) => {
                Feedback.create(item,callback)
              },
              callback
            );
          },
          (feedback, callback) => {
            User.create({ "username": "Bill", "feedback": feedback },callback);
          },
          (user, callback) => {
            User.aggregate([
              { "$match": { "_id": user._id } },
              { "$lookup": {
                "from": "feedbacks",
                "localField": "feedback",
                "foreignField": "_id",
                "as": "feedback"
              }},
              { "$project": {
                "username": 1,
                "rating": {
                  "communication": { "$sum": "$feedback.rating.communication" },
                  "timeliness": { "$sum": "$feedback.rating.timeliness" },
                  "delivery": { "$sum": "$feedback.rating.delivery" }
                }
              }}
            ],(err,results) => {
              console.log(JSON.stringify(results, undefined, 2));
              callback(err);
            });
          }
        ],
        callback
      )
    }
  ],
  (err) => {
    if (err) throw err;
    mongoose.disconnect();
  }
);

This will create two collections as User

{
        "_id" : ObjectId("593548455198ab3c09cf736b"),
        "username" : "Bill",
        "feedback" : [
                ObjectId("593548455198ab3c09cf7369"),
                ObjectId("593548455198ab3c09cf736a")
        ],
        "__v" : 0
}

And feedbacks:

{
        "_id" : ObjectId("593548455198ab3c09cf7369"),
        "rating" : {
                "communication" : 1,
                "timeliness" : 2,
                "delivery" : 3
        },
        "__v" : 0
}
{
        "_id" : ObjectId("593548455198ab3c09cf736a"),
        "rating" : {
                "communication" : 2,
                "timeliness" : 3,
                "delivery" : 4
        },
        "__v" : 0
}

Program Output Shows the aggregation:

[
  {
    "_id": "5935494a159c633c1b34807b",
    "username": "Bill",
    "rating": {
      "communication": 3,
      "timeliness": 5,
      "delivery": 7
    }
  }
]

Also package.json if the two dependencies are not clear enough:

{
  "name": "ratings",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "async": "^2.4.1",
    "mongoose": "^4.10.4"
  }
}

Original Answer

Personally I would work this from the "Feedback" since you have the user already recorded there, and it is actually the way this scales better.

Instead of using population, we can instead use $lookup with a MongoDB server version of at least 3.2:

Feedback.aggregate([
  { "$match": { "user": userId } },
  { "$group": {
    "_id": "$user",
    "communication": { "$sum": "$rating.communication" },
    "timeliness": { "$sum": "$rating.timeliness" },
    "delivery": { "$sum": "$rating.delivery" }
  }},
  { "$lookup": {
    "from": "users",
    "localField": "_id",
    "foreignField": "_id",
    "as": "user"
  }},
  { "$unwind": "$user" }
])

If you do not have a server version that supports $lookupthen you can still "manually join" the User details with something like this:

Feedback.aggregate([
  { "$match": { "user": userId } },
  { "$group": {
    "_id": "$user",
    "communication": { "$sum": "$rating.communication" },
    "timeliness": { "$sum": "$rating.timeliness" },
    "delivery": { "$sum": "$rating.delivery" }
  }}
],function(err, results) {
    result = results[0];
    User.findById(userId).lean().exec(function(err, user) {
      result.user = user;     // swap the _id for the Object

      // Then output result
    });
})

Which is basically what .populate() does, but we are doing it manually and efficiently for the result returned.

You can work the other way around from the User model, but it's likely more efficient to simply work this way around.

User.aggregate([
  { "$match": { "_id": userid } },
  { "$lookup": {
    "from": "feedbacks",
    "localField": "feedback",
    "foreignField": "_id",
    "as": "feedback"
  }},
  { "$project": {
    "username": 1,
    "fullname": 1,
    "email": 1,
    "password": 1,
    "rating": {
      "communication": { "$sum": "$feedback.rating.communication" },
      "timeliness": { "$sum": "$feedback.rating.timeliness" },
      "delivery": { "$sum": "$feedback.rating.delivery" }
    }
  }}
])


来源: stackexchange

问:
DataGridView not getting columns from DataTable when binding
I have a DataGridView that I am binding to a table. After I do the following code:

```<code>Dim filterTable As New DataTable
filterTable.Columns.Add("KeyName")
filterTable.Columns.Add("Path")

GridView.DataSource = filterTable

GridView.Columns.Count remains 0.
</code>```

Basically, the BindUnidentifiedKeys(UnidentifiedKeys As Dictionary(Of String, String), ByRef GridView As DataGridView) is called.

I call it like this:
UnidentifiedKeysManager.Instance.BindUnidentifiedKeys(UnidentifiedKeysManager.Instance.GetKeys, grdUnidentifiedKeys)

I pass it a dictionary and a DataGridView, by reference.

Yet when I set it's datasource to a datatable that has columns, the GridView's columns remain 0. I don't know why this is happening.

答:
I had to do this to ensure columns were always present on occasion..</p>

```<code>GridView.Columns.Clear();
GridView.DataSource = null;
GridView.AutoGenerateColumns = true;
GridView.DataSource = datasource
GridView.DataMember = "Table1";
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a DataGridView that I am binding to a table. After I do the following code:

Dim filterTable As New DataTable
filterTable.Columns.Add("KeyName")
filterTable.Columns.Add("Path")

GridView.DataSource = filterTable

GridView.Columns.Count remains 0.

Basically, the BindUnidentifiedKeys(UnidentifiedKeys As Dictionary(Of String, String), ByRef GridView As DataGridView) is called.

I call it like this:
UnidentifiedKeysManager.Instance.BindUnidentifiedKeys(UnidentifiedKeysManager.Instance.GetKeys, grdUnidentifiedKeys)

I pass it a dictionary and a DataGridView, by reference.

Yet when I set it's datasource to a datatable that has columns, the GridView's columns remain 0. I don't know why this is happening.

Body:
I had to do this to ensure columns were always present on occasion..

GridView.Columns.Clear();
GridView.DataSource = null;
GridView.AutoGenerateColumns = true;
GridView.DataSource = datasource
GridView.DataMember = "Table1";


问:
Fatal error: Out of memory (allocated 761004032) (tried to allocate 755370216 bytes) in D:\xampp\phpMyAdmin\libraries\zip_extension.lib.php on line 55
Am trying to import 120MB size database.zip file in xampp PHPMyAdmin.
I'm increse following in php.ini

memory_limit=1200M

upload_max_filesize=1200M

post_max_size=1100M

max_input_time=5000

But still i got error

Fatal error: Out of memory (allocated 761004032) (tried to allocate 755370216 bytes) in D:\xampp\phpMyAdmin\libraries\zip_extension.lib.php on line 55

How can i fix this ?

Note: Original database.sql file size is 750MB

答:
Try this:
Open cmd

Type cd c:\xampp\mysql\bin and press enter.

After that type this following code:

```<code>mysql -u root -p database_name < database.sql
</code>```

Note: Before this copy and paste your databse.sql file in C:\xampp\mysql\bin

Body:
Try this:
Open cmd

Type cd c:\xampp\mysql\bin and press enter.

After that type this following code:

mysql -u root -p database_name < database.sql

Note: Before this copy and paste your databse.sql file in C:\xampp\mysql\bin


问:
How to select
 inside

Assume I have html structure as

```<code>ul
  li //this one
    ul
      li
      li
      li
  li //this one
</code>```

I don't want to get all li's.
As I commented I just want to get first segment li's. How can I select them?

```<code>document.querySelectorAll("ul > li");
</code>```

returns all li's.

edit: actually this is just a snippet of the tree.

I can't modify the structure as adding class or id. I'm looking for an answer to get the list of first layer lis

答:
Try this it should do the trick :

```<code>$("ul > li").not("ul li ul li");
</code>```

Also this should work in your case :

```<code>$("ul").first().children("li");
</code>```

Title: How to select <li> inside <ul>

Body:
Assume I have html structure as

ul
  li //this one
    ul
      li
      li
      li
  li //this one

I don't want to get all li's.
As I commented I just want to get first segment li's. How can I select them?

document.querySelectorAll("ul > li");

returns all li's.

edit: actually this is just a snippet of the tree.

I can't modify the structure as adding class or id. I'm looking for an answer to get the list of first layer lis

Body:
Try this it should do the trick :

$("ul > li").not("ul li ul li");

Also this should work in your case :

$("ul").first().children("li");


问:
Are multiple operations for string formatting allowed in Python?
Could be a basic one:

I am just trying to do multiple operations on one of the key in a dictionary with encoding the first element of the key, splitting it further based on a character and also joining with another string as below:

```<code>images_list["RepoTag"] = image["RepoDigests"][0].encode("utf-8").split("@")[0] + ":none"
</code>```

Code snippet in which I am doing the above formatting:

```<code>from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
import requests

@require_http_methods(["GET"])
def images_info(request):
    response = requests.get("http://127.0.0.1:6000/images/json")
    table = []
    images_list = {}
    for image in response.json():
        try:
            images_list["RepoTag"] = image["RepoTags"][0].encode("utf-8")
        except TypeError:
            images_list["RepoTag"] = image["RepoDigests"][0].encode("utf-8").split("@")[0] + ":none"
        images_list["Id"] = image["Id"].encode("utf-8")[7:19]
        table.append(images_list)
        images_list = {}

    return JsonResponse(table,safe=False)
</code>```

Can someone tell me whether is it the right way to do these many operations in a single line? or in another way Does it follows the python standards ?

If not does python standards suggest any limited operations in a single line or so?

Reason for asking this is that the number of characters should not exceed 79 characters as per pep-8.

答:
There's nothing wrong with chaining a few string operations together. If you want to keep it within the 80-character line, just add some parentheses:

```<code>images_list["RepoTag"] = (
    image["RepoDigests"][0].encode("utf-8").split("@")[0] +
    ":none")
</code>```

or use str.format() to provide those same parentheses:

```<code>images_list["RepoTag"] = '{}:none'.format(
    image["RepoDigests"][0].encode("utf-8").split("@")[0])
</code>```

You could, otherwise, trivially use a local variable:

```<code>first_digest = image["RepoDigests"][0].encode("utf-8")
images_list["RepoTag"] = '{}:none'.format(first_digest.split("@")[0])
</code>```

Body:
Could be a basic one:

I am just trying to do multiple operations on one of the key in a dictionary with encoding the first element of the key, splitting it further based on a character and also joining with another string as below:

images_list["RepoTag"] = image["RepoDigests"][0].encode("utf-8").split("@")[0] + ":none"

Code snippet in which I am doing the above formatting:

from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
import requests

@require_http_methods(["GET"])
def images_info(request):
    response = requests.get("http://127.0.0.1:6000/images/json")
    table = []
    images_list = {}
    for image in response.json():
        try:
            images_list["RepoTag"] = image["RepoTags"][0].encode("utf-8")
        except TypeError:
            images_list["RepoTag"] = image["RepoDigests"][0].encode("utf-8").split("@")[0] + ":none"
        images_list["Id"] = image["Id"].encode("utf-8")[7:19]
        table.append(images_list)
        images_list = {}

    return JsonResponse(table,safe=False)

Can someone tell me whether is it the right way to do these many operations in a single line? or in another way Does it follows the python standards ?

If not does python standards suggest any limited operations in a single line or so?

Reason for asking this is that the number of characters should not exceed 79 characters as per pep-8.

Body:
There's nothing wrong with chaining a few string operations together. If you want to keep it within the 80-character line, just add some parentheses:

images_list["RepoTag"] = (
    image["RepoDigests"][0].encode("utf-8").split("@")[0] +
    ":none")

or use str.format() to provide those same parentheses:

images_list["RepoTag"] = '{}:none'.format(
    image["RepoDigests"][0].encode("utf-8").split("@")[0])

You could, otherwise, trivially use a local variable:

first_digest = image["RepoDigests"][0].encode("utf-8")
images_list["RepoTag"] = '{}:none'.format(first_digest.split("@")[0])


问:
how to store the data in a file in j2me..?
please can anyone tell me how to store the RMS data to file and how to modify it?</p>

答:
You can use this code for write the data in a file.</p>

```<code>private void writeTextFile(String fName, String text) {
    DataOutputStream dos = null;
    FileConnection fconn = null;
    try {
        fconn = (FileConnection) Connector.open(fName, Connector.READ_WRITE);
        if (!fconn.exists())
            fconn.create();
        dos = fconn.openDataOutputStream();
        dos.write(text.getBytes());
    } catch (IOException e) {
        System.out.println(e.getMessage());
    } finally {
        try {
            if (dos != null)
            dos.close();
            if (fconn != null)
                fconn.close();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}
</code>```

Body:
You can use this code for write the data in a file.

private void writeTextFile(String fName, String text) {
    DataOutputStream dos = null;
    FileConnection fconn = null;
    try {
        fconn = (FileConnection) Connector.open(fName, Connector.READ_WRITE);
        if (!fconn.exists())
            fconn.create();
        dos = fconn.openDataOutputStream();
        dos.write(text.getBytes());
    } catch (IOException e) {
        System.out.println(e.getMessage());
    } finally {
        try {
            if (dos != null)
            dos.close();
            if (fconn != null)
                fconn.close();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }
}


问:
location href returns as undefined
I have this Ripple effect code:

```<code>(function (window, $) {

  $(function() {

    $('.ripple-white').on('click', function (event) {
      event.preventDefault();

      var $div = $('<div/>'),
          btnOffset = $(this).offset(),
            xPos = event.pageX - btnOffset.left,
            yPos = event.pageY - btnOffset.top;

      $div.addClass('ripple-effect');
      var $ripple = $(".ripple-effect");

      $ripple.css("height", $(this).height());
      $ripple.css("width", $(this).height());
      $div
        .css({
          top: yPos - ($ripple.height()/2),
          left: xPos - ($ripple.width()/2),
          background: $(this).data("ripple-color")
        })
        .appendTo($(this));

      window.setTimeout(function(){
        $div.remove();
        location.href = $(this).attr('href');
      }, 800);

    });

  });

})(window, jQuery);
</code>```

Which is dynamically used for Wordpress post listing:

```<code><?php $the_query = new WP_Query( 'posts_per_page=50' ); ?>
<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
<div class="flex-3col"><a class="ripple-white" href="<?php the_permalink() ?>"><h3 class="single-menu"><?php the_title(); ?></h3></a></div>
<?php endwhile; wp_reset_postdata(); ?>
</code>```

For some reason I'm getting the location.href as UNDEFINED. I've also tried:

```<code>$('a', this).attr("href");
</code>```

Any advice what I'm doing wrong here?

答:
You have to define this in variable self to clicked element, like this:

(function (window, $) {

  $(function() {

    $('.ripple-white').on('click', function (event) {
 var self = this;
      event.preventDefault();

      var $div = $('
'),
          btnOffset = $(this).offset(),
            xPos = event.pageX - btnOffset.left,
            yPos = event.pageY - btnOffset.top;

      $div.addClass('ripple-effect');
      var $ripple = $(".ripple-effect");

      $ripple.css("height", $(this).height());
      $ripple.css("width", $(this).height());
      $div
        .css({
          top: yPos - ($ripple.height()/2),
          left: xPos - ($ripple.width()/2),
          background: $(this).data("ripple-color")
        })
        .appendTo($(this));

      window.setTimeout(function(){
        $div.remove();
        //location.href = $(this).attr('href');
  $(".clicked_href").html( $(self).attr('href') );
      }, 800);

    });

  });

})(window, jQuery);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="flex-3col"><h3 class="single-menu">Link 1</h3></div>
<div class="flex-3col"><h3 class="single-menu">Link 2</h3></div>
<div class="flex-3col"><h3 class="single-menu">Link 3</h3></div>

<div>Href: <span class="clicked_href"></span></div></code>```

Title: location href returns as undefined

Body:
I have this Ripple effect code:

(function (window, $) {

  $(function() {

    $('.ripple-white').on('click', function (event) {
      event.preventDefault();

      var $div = $('
'),
          btnOffset = $(this).offset(),
            xPos = event.pageX - btnOffset.left,
            yPos = event.pageY - btnOffset.top;

      $div.addClass('ripple-effect');
      var $ripple = $(".ripple-effect");

      $ripple.css("height", $(this).height());
      $ripple.css("width", $(this).height());
      $div
        .css({
          top: yPos - ($ripple.height()/2),
          left: xPos - ($ripple.width()/2),
          background: $(this).data("ripple-color")
        })
        .appendTo($(this));

      window.setTimeout(function(){
        $div.remove();
        location.href = $(this).attr('href');
      }, 800);

    });

  });

})(window, jQuery);

Which is dynamically used for Wordpress post listing:

<?php $the_query = new WP_Query( 'posts_per_page=50' ); ?>
<?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>

<a class="ripple-white" href="<?php the_permalink() ?>">
<?php the_title(); ?>

<?php endwhile; wp_reset_postdata(); ?>

For some reason I'm getting the location.href as UNDEFINED. I've also tried:

$('a', this).attr("href");

Any advice what I'm doing wrong here?

Body:
You have to define this in variable self to clicked element, like this:

(function (window, $) {

  $(function() {

    $('.ripple-white').on('click', function (event) {
 var self = this;
      event.preventDefault();

      var $div = $('<div/>'),
          btnOffset = $(this).offset(),
            xPos = event.pageX - btnOffset.left,
            yPos = event.pageY - btnOffset.top;

      $div.addClass('ripple-effect');
      var $ripple = $(".ripple-effect");

      $ripple.css("height", $(this).height());
      $ripple.css("width", $(this).height());
      $div
        .css({
          top: yPos - ($ripple.height()/2),
          left: xPos - ($ripple.width()/2),
          background: $(this).data("ripple-color")
        })
        .appendTo($(this));

      window.setTimeout(function(){
        $div.remove();
        //location.href = $(this).attr('href');
  $(".clicked_href").html( $(self).attr('href') );
      }, 800);

    });

  });

})(window, jQuery);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div class="flex-3col"><a class="ripple-white" href="http://www11.com"><h3 class="single-menu">Link 1</h3></a></div>
<div class="flex-3col"><a class="ripple-white" href="http://www22.com"><h3 class="single-menu">Link 2</h3></a></div>
<div class="flex-3col"><a class="ripple-white" href="http://www33.com"><h3 class="single-menu">Link 3</h3></a></div>

<div>Href: <span class="clicked_href"></span></div>


问:
C# date part of dateTime extension property
I have extension method on DateTime class:

```<code>public static DateTime? SafeConvertToDateTime(this string value, bool dateOnly)
{
    DateTime parsedDateTime;
    if (DateTime.TryParse(value, out parsedDateTime))
    {
        return DateTime.SpecifyKind(parsedDateTime, DateTimeKind.Utc);
    } else {
        return new DateTime(1, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    }
}
</code>```

If "dateOnly=true" i should return Datetime with only Date property and all conversions later on client (to local or utc) should be skipped if there is DateTime with only Date.
But how can i know that this DateTime holds only Date(since time can be valid as 0)?
I could add extension property (dateOnly), but as I know, I can't add extension property in C#, only methods?
Can I use some existing property of Datetime to tell, there is only date which should be consider later in code?

答:
But how can i know that this DateTime holds only Date(since time can
  be valid as 0)?

There is no way to achieve this using the existing DateTime class - since you won't be able to distinguish a 'date' vs a 'datetime that happens to be at midnight'. They will look exactly the same.

The Date type may be of interest - but given DateTime and Date are different types you'll need to alter your code to handle both types. Noda's LocalDate may also be of interest.

If you decide to use the Date type, you could create a wrapper class that contains either a date or a datetime, and pass it around as needed:

```<code>public class DateWithOrWithoutTime
{
    public Date? DateWithoutTime { get; private set; }
    public DateTime? DateWithTime { get; private set; }

    public DateWithOrWithoutTime(Date dateToSet)
    {
        DateWithoutTime = dateToSet;
    }
    public DateWithOrWithoutTime(DateTime dateTimeToSet)
    {
        DateWithTime = dateTimeToSet;
    }

    public bool IsDate()
    {
        return DateWithoutTime != null;
    }

    public bool IsDateTime()
    {
        return DateWithTime != null;
    }
}
</code>```

Body:
I have extension method on DateTime class:

public static DateTime? SafeConvertToDateTime(this string value, bool dateOnly)
{
    DateTime parsedDateTime;
    if (DateTime.TryParse(value, out parsedDateTime))
    {
        return DateTime.SpecifyKind(parsedDateTime, DateTimeKind.Utc);
    } else {
        return new DateTime(1, 1, 1, 0, 0, 0, DateTimeKind.Utc);
    }
}

If "dateOnly=true" i should return Datetime with only Date property and all conversions later on client (to local or utc) should be skipped if there is DateTime with only Date.
But how can i know that this DateTime holds only Date(since time can be valid as 0)?
I could add extension property (dateOnly), but as I know, I can't add extension property in C#, only methods?
Can I use some existing property of Datetime to tell, there is only date which should be consider later in code?

Body:
But how can i know that this DateTime holds only Date(since time can
  be valid as 0)?

There is no way to achieve this using the existing DateTime class - since you won't be able to distinguish a 'date' vs a 'datetime that happens to be at midnight'. They will look exactly the same.

The Date type may be of interest - but given DateTime and Date are different types you'll need to alter your code to handle both types. Noda's LocalDate may also be of interest.

If you decide to use the Date type, you could create a wrapper class that contains either a date or a datetime, and pass it around as needed:

public class DateWithOrWithoutTime
{
    public Date? DateWithoutTime { get; private set; }
    public DateTime? DateWithTime { get; private set; }

    public DateWithOrWithoutTime(Date dateToSet)
    {
        DateWithoutTime = dateToSet;
    }
    public DateWithOrWithoutTime(DateTime dateTimeToSet)
    {
        DateWithTime = dateTimeToSet;
    }

    public bool IsDate()
    {
        return DateWithoutTime != null;
    }

    public bool IsDateTime()
    {
        return DateWithTime != null;
    }
}


问:
How to do subtraction between two fields in a Table using an SQL query
I want to display the subtraction of two values from two different columns to a third column using a SQL query.

This is the table structure:

```<code>------------------------------------
id | subject | Time1 | Time2| Time3
------------------------------------
1  | String1 | 50    |  78  |
2  | String2 | 60    |  99  |
3  |         |       |      |
</code>```

I want to subtract Time2 from Time1 if both Time1 and Time2 has data and store in Time3.

Output should be like as

```<code>------------------------------------
id | subject | Time1 | Time2| Time3
------------------------------------
1  | String1 | 50    |  78  |  28
2  | String2 | 60    |  99  |  39
3  |         |       |      |
</code>```

Thanks!

答:
This checks the existence of data in Time1 and Time2: if there is enough data, Time3 = Time2 - Time1; otherwise it's null

```<code>select id, subject, Time1, Time2,
   ifnull(Time1, null, ifnull(Time2, null, Time2 - Time1)) as Time3
from myTable
</code>```

Body:
I want to display the subtraction of two values from two different columns to a third column using a SQL query.

This is the table structure:

------------------------------------
id | subject | Time1 | Time2| Time3
------------------------------------
1  | String1 | 50    |  78  |
2  | String2 | 60    |  99  |
3  |         |       |      |

I want to subtract Time2 from Time1 if both Time1 and Time2 has data and store in Time3.

Output should be like as

------------------------------------
id | subject | Time1 | Time2| Time3
------------------------------------
1  | String1 | 50    |  78  |  28
2  | String2 | 60    |  99  |  39
3  |         |       |      |

Thanks!

Body:
This checks the existence of data in Time1 and Time2: if there is enough data, Time3 = Time2 - Time1; otherwise it's null

select id, subject, Time1, Time2,
   ifnull(Time1, null, ifnull(Time2, null, Time2 - Time1)) as Time3
from myTable


问:
How to map an array object with key from different array set in javascript
I'm building a small application in VueJS where I'm getting a response in following format:

```<code>"meeting_summaries":[
    {
        "interaction_id":22,
        "nature":"1",
        "client_name":"Test Company 4",
    },
    {
        "interaction_id":22,
        "nature":"2",
        "client_name":"Test Company 5",
    }
]
</code>```

And I'm having a data set of nature as:

```<code>const nature = [
    {value: 1, label: "Demo 1"},
    {value: 2, label: "Demo 2"},
    {value: 3, label: "Demo 3"}
]
</code>```

I want to map my meeting_summaries with this data set were in meeting_summaries -> nature points to nature -> value so that my final output can look something like this:

```<code>"meeting_summaries":[
    {
        "interaction_id":22,
        "nature":"1",
        'nature_name": "Demo 1",
        "client_name":"Test Company 4",
    },
    {
        "interaction_id":22,
        "nature":"2",
        'nature_name": "Demo 2",
        "client_name":"Test Company 5",
    }
]
</code>```

答:
I'm just take a "map" approach in my solution for better performance:

```<code>const meeting_summaries = [ { "interaction_id":22, "nature":"1", "client_name":"Test Company 4", }, { "interaction_id":22, "nature":"2", "client_name":"Test Company 5", } ];

    const nature = [ {value: 1, label: "Demo 1"}, {value: 2, label: "Demo 2"}, {value: 3, label: "Demo 3"} ];

    const natureMap = nature.reduce((accum,current)=>{
                accum[current.value] = current.label;
                return accum;
    }, { });

    const result = meeting_summaries.map(item => {
            item.nature_name = natureMap[item.nature];
            return item;
    });

    console.log(result)
</code>```

Sorry for indentation, coded from smartphone

Body:
I'm building a small application in VueJS where I'm getting a response in following format:

"meeting_summaries":[
    {
        "interaction_id":22,
        "nature":"1",
        "client_name":"Test Company 4",
    },
    {
        "interaction_id":22,
        "nature":"2",
        "client_name":"Test Company 5",
    }
]

And I'm having a data set of nature as:

const nature = [
    {value: 1, label: "Demo 1"},
    {value: 2, label: "Demo 2"},
    {value: 3, label: "Demo 3"}
]

I want to map my meeting_summaries with this data set were in meeting_summaries -> nature points to nature -> value so that my final output can look something like this:

"meeting_summaries":[
    {
        "interaction_id":22,
        "nature":"1",
        'nature_name": "Demo 1",
        "client_name":"Test Company 4",
    },
    {
        "interaction_id":22,
        "nature":"2",
        'nature_name": "Demo 2",
        "client_name":"Test Company 5",
    }
]

Body:
I'm just take a "map" approach in my solution for better performance:

const meeting_summaries = [ { "interaction_id":22, "nature":"1", "client_name":"Test Company 4", }, { "interaction_id":22, "nature":"2", "client_name":"Test Company 5", } ];

    const nature = [ {value: 1, label: "Demo 1"}, {value: 2, label: "Demo 2"}, {value: 3, label: "Demo 3"} ];

    const natureMap = nature.reduce((accum,current)=>{
                accum[current.value] = current.label;
                return accum;
    }, { });

    const result = meeting_summaries.map(item => {
            item.nature_name = natureMap[item.nature];
            return item;
    });

    console.log(result)

Sorry for indentation, coded from smartphone


问:
Only Allowing IPv4 and HTTPS in Firewall
I've got a Ubuntu Machine in the cloud, running a Web Server with Nginx and Node.js.
In the firewall settings (ufw), I've only allowed ipv4 through port 443 (ssl)  for inbound connections (And ssh of course).

Is preventing regular HTTP and/or ipv6 connection a problem? And why ?

Thanks !

答:
Is preventing regular HTTP and/or ipv6 connection a problem?

If all URL's pointing to your server are only https:// and all IP addresses setup in DNS for your system are only IPv4 and you don't need to have any other services on this machine accessible from outside (i.e. SSH, mail, ...) then you expect only IPv4 TCP traffic on port 443 and your restriction makes sense. But, if any of these limitations regarding URL, DNS and services are not true then you probably deny valid traffic which will be a problem.


问:
How to properly remove Timer instance
I am using Timer instance in my project.

I create and add an instance to RunLoop

```<code>timer = Timer(timeInterval: 0.1, repeats: true, block: { (timer) in
    print("Hello")
})

if let timer = timer {
    RunLoop.current.add(timer, forMode: .commonModes)
}
</code>```

Now I am thinking about how to properly stop and remove Timer:

Should I trust in ARC and don't care about it?

Maybe deinit implementation is need. If is it true, what should be inside

```<code>deinit {
    longPressTimer?.invalidate()
    longPressTimer = nil
}
</code>```

invalidate is nesseccery? = nil ?

I have read serval threads from Stack about it but answers are contradictory. Could someone tell me which way is properly and explain me why?

答:
If timer is repeating it won't invalidate as long as it's target is in memory.

The best solution for me was to use this class - which will observe target, and it target is deallocate it will invalidate itself.

```<code>final class WeakTimer {
    private weak var timer: Timer?
    private weak var target: AnyObject?
    private let action: (Timer) -> Void

    private init(timeInterval: TimeInterval,
                     target: AnyObject,
                     repeats: Bool,
                     userInfo: Any?,
                     action: @escaping (Timer) -> Void) {
        self.target = target
        self.action = action
        self.timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(fire(timer:)), userInfo: userInfo, repeats: repeats)
        RunLoop.main.add(self.timer!, forMode: .commonModes)
    }

    class func scheduledTimer(timeInterval: TimeInterval,
                              target: AnyObject,
                              userInfo: Any?,
                              repeats: Bool,
                              action: @escaping (Timer) -> Void) -> Timer {
        return WeakTimer(timeInterval: timeInterval,
                         target: target,
                         repeats: repeats,
                         userInfo: userInfo,
                         action: action).timer!
    }

    @objc fileprivate func fire(timer: Timer) {
        if target != nil {
            action(timer)
        } else {
            timer.invalidate()
        }
    }
}
</code>```

Title: How to properly remove Timer instance

Body:
I am using Timer instance in my project.

I create and add an instance to RunLoop

timer = Timer(timeInterval: 0.1, repeats: true, block: { (timer) in
    print("Hello")
})

if let timer = timer {
    RunLoop.current.add(timer, forMode: .commonModes)
}

Now I am thinking about how to properly stop and remove Timer:

Should I trust in ARC and don't care about it?

Maybe deinit implementation is need. If is it true, what should be inside

deinit {
    longPressTimer?.invalidate()
    longPressTimer = nil
}

invalidate is nesseccery? = nil ?

I have read serval threads from Stack about it but answers are contradictory. Could someone tell me which way is properly and explain me why?

Body:
If timer is repeating it won't invalidate as long as it's target is in memory.

The best solution for me was to use this class - which will observe target, and it target is deallocate it will invalidate itself.

final class WeakTimer {
    private weak var timer: Timer?
    private weak var target: AnyObject?
    private let action: (Timer) -> Void

    private init(timeInterval: TimeInterval,
                     target: AnyObject,
                     repeats: Bool,
                     userInfo: Any?,
                     action: @escaping (Timer) -> Void) {
        self.target = target
        self.action = action
        self.timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(fire(timer:)), userInfo: userInfo, repeats: repeats)
        RunLoop.main.add(self.timer!, forMode: .commonModes)
    }

    class func scheduledTimer(timeInterval: TimeInterval,
                              target: AnyObject,
                              userInfo: Any?,
                              repeats: Bool,
                              action: @escaping (Timer) -> Void) -> Timer {
        return WeakTimer(timeInterval: timeInterval,
                         target: target,
                         repeats: repeats,
                         userInfo: userInfo,
                         action: action).timer!
    }

    @objc fileprivate func fire(timer: Timer) {
        if target != nil {
            action(timer)
        } else {
            timer.invalidate()
        }
    }
}


问:
Difference between Constructor and ngOnInit
Angular provides life cycle hook ngOnInit by default.

Why should ngOnInit be used, if we already have a constructor?

答:
OK, first of all ngOnInit is part of Angular lifecycle, while constructor is part of ES6 JavaScript class, so the major difference starts from right here!...

Look at the below chart that I created which shows the lifecycle of Angular.

In Angular2+ we use constructor to do the DI(Dependency Injection) for us, while in Angular 1 it was happening through calling to String method and checking which dependency was injected.

As you see in the above diagram, ngOnInit is happening after the constructor is ready and ngOnChnages and get fired after the component is ready for us. All initialisation can happen in this stage, a simple sample is injecting a service and initials it on init.

OK, I also share a sample code for you to look, see how we get use of ngOnInit and constructor in the code below:

```<code>import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
 selector: 'my-app',
 template: `<h1>App is running!</h1>
  <my-app-main [data]=data></<my-app-main>`,
  styles: ['h1 { font-weight: normal; }']
})
class ExampleComponent implements OnInit {
  constructor(private router: Router) {} //Dependency injection in the constructor

  // ngOnInit, get called after Component initialised!
  ngOnInit() {
    console.log('Component initialised!');
  }
}
</code>```

Body:
OK, first of all ngOnInit is part of Angular lifecycle, while constructor is part of ES6 JavaScript class, so the major difference starts from right here!...

Look at the below chart that I created which shows the lifecycle of Angular.

In Angular2+ we use constructor to do the DI(Dependency Injection) for us, while in Angular 1 it was happening through calling to String method and checking which dependency was injected.

As you see in the above diagram, ngOnInit is happening after the constructor is ready and ngOnChnages and get fired after the component is ready for us. All initialisation can happen in this stage, a simple sample is injecting a service and initials it on init.

OK, I also share a sample code for you to look, see how we get use of ngOnInit and constructor in the code below:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
 selector: 'my-app',
 template: `<h1>App is running!</h1>
  <my-app-main [data]=data></<my-app-main>`,
  styles: ['h1 { font-weight: normal; }']
})
class ExampleComponent implements OnInit {
  constructor(private router: Router) {} //Dependency injection in the constructor

  // ngOnInit, get called after Component initialised!
  ngOnInit() {
    console.log('Component initialised!');
  }
}

ContentLicense: CC BY-SA 4.0


问:
can't build android project it shows error
project gradle

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha3'
        classpath 'com.google.gms:google-services:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

App Gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.arun4fms.efix"
        minSdkVersion 17
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        packagingOptions {
            exclude 'META-INF/LICENSE'
            exclude 'META-INF/LICENSE-FIREBASE.txt'
            exclude 'META-INF/NOTICE'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.google.firebase:firebase-database:10.2.0'
    compile 'com.google.firebase:firebase-crash:10.2.0'
    compile 'com.google.firebase:firebase-auth:10.2.0'
    compile 'com.chabbal:slidingdotsplash:1.0.2'
    compile 'com.google.firebase:firebase-core:10.2.0'
    compile 'com.firebase:firebase-client-android:2.5.2'
    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.android.support:design:25.2.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'
</code>```

Error:A problem occurred configuring root project 'webapp'.

Could not resolve all dependencies for configuration ':classpath'.
  Could not find com.android.tools.build:gradle:3.0.0-alpha3.
       Searched in the following locations:
           file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.pom
           file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.jar
           https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.pom
           https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.jar
       Required by:
           project :

答: com.android.tools.build.gradle latest version is 2.5.0-alpha-preview-02, there is no 3.0.0-alpha3</p>

Body:
project gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.0-alpha3'
        classpath 'com.google.gms:google-services:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

App Gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.example.arun4fms.efix"
        minSdkVersion 17
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        packagingOptions {
            exclude 'META-INF/LICENSE'
            exclude 'META-INF/LICENSE-FIREBASE.txt'
            exclude 'META-INF/NOTICE'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.google.firebase:firebase-database:10.2.0'
    compile 'com.google.firebase:firebase-crash:10.2.0'
    compile 'com.google.firebase:firebase-auth:10.2.0'
    compile 'com.chabbal:slidingdotsplash:1.0.2'
    compile 'com.google.firebase:firebase-core:10.2.0'
    compile 'com.firebase:firebase-client-android:2.5.2'
    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.android.support:design:25.2.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'

Error:A problem occurred configuring root project 'webapp'.

Could not resolve all dependencies for configuration ':classpath'.
  Could not find com.android.tools.build:gradle:3.0.0-alpha3.
       Searched in the following locations:
           file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.pom
           file:/C:/Program Files/Android/Android Studio/gradle/m2repository/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.jar
           https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.pom
           https://jcenter.bintray.com/com/android/tools/build/gradle/3.0.0-alpha3/gradle-3.0.0-alpha3.jar
       Required by:
           project :


问:
PHP namespace syntax
I am new to PHP and would appreciate some help with namespaces.
I have a class and it's declared as:

```<code>namespace P3;
class CardstreamCodingStandard_Sniffs_Classes_ClassDeclarationSniff {
}
</code>```

Now i want to implement an interface called CodeSniffer_Sniff. So i amended the class declaration as:

```<code>namespace P3;
class CardstreamCodingStandard_Sniffs_Classes_ClassDeclarationSniff extends CodeSniffer_Sniff  {
}
</code>```

But when I run the code I get

```<code>Fatal error:  Interface 'P3\CodeSniffer_Sniff' not found in /root/qa/CardstreamCodingStandard/Sniffs/Classes/ClassDeclarationSniff.php
</code>```

Please can someone explain what is going on? and what the correct syntax should be?

Thanks

Ok some more details
I have inherited this code that implements a sniff for phpcs

My class is declared as

```<code>namespace CardstreamCodingStandard\Sniffs\Classes;
class CardstreamCodingStandard_Sniffs_Classes_ClassDeclarationSniff implements PHP_CodeSniffer_Sniff {
}
</code>```

when I run phpcs with this sniff then I get the error

```<code>PHP Fatal error:  Interface 'CardstreamCodingStandard\Sniffs\Classes\PHP_CodeSniffer_Sniff' not found in /root/qa/CardstreamCodingStandard/Sniffs/Classes/ClassDeclarationSniff.php on line 23
PHP Stack trace:
PHP   1. {main}() /usr/bin/phpcs:0
PHP   2. PHP_CodeSniffer_CLI->runphpcs() /usr/bin/phpcs:25
PHP   3. PHP_CodeSniffer_CLI->process() /usr/share/pear/PHP/CodeSniffer/CLI.php:113
PHP   4. PHP_CodeSniffer->initStandard() /usr/share/pear/PHP/CodeSniffer/CLI.php:956
PHP   5. PHP_CodeSniffer->registerSniffs() /usr/share/pear/PHP/CodeSniffer.php:594
PHP   6. include_once() /usr/share/pear/PHP/CodeSniffer.php:1409
</code>```

I hope this makes things clearer

答:
Some details on how to use namespaces can be found at the php manual.

In your case it seems you are using the same namespace.

To correctly use an interface, you have to implement it into your class.
The correct use would be the following:

```<code>Class Apple implements Fruit { ... }
</code>```

More on interfaces and how to use them can be found here.

You are using the extends keyword which is used for creating child classes of a parent class.

The php manual on parent and child classes (called inheritance) has been linked here

Title: PHP namespace syntax

Body:
I am new to PHP and would appreciate some help with namespaces.
I have a class and it's declared as:

namespace P3;
class CardstreamCodingStandard_Sniffs_Classes_ClassDeclarationSniff {
}

Now i want to implement an interface called CodeSniffer_Sniff. So i amended the class declaration as:

namespace P3;
class CardstreamCodingStandard_Sniffs_Classes_ClassDeclarationSniff extends CodeSniffer_Sniff  {
}

But when I run the code I get

Fatal error:  Interface 'P3\CodeSniffer_Sniff' not found in /root/qa/CardstreamCodingStandard/Sniffs/Classes/ClassDeclarationSniff.php

Please can someone explain what is going on? and what the correct syntax should be?

Thanks

Ok some more details
I have inherited this code that implements a sniff for phpcs

My class is declared as

namespace CardstreamCodingStandard\Sniffs\Classes;
class CardstreamCodingStandard_Sniffs_Classes_ClassDeclarationSniff implements PHP_CodeSniffer_Sniff {
}

when I run phpcs with this sniff then I get the error

PHP Fatal error:  Interface 'CardstreamCodingStandard\Sniffs\Classes\PHP_CodeSniffer_Sniff' not found in /root/qa/CardstreamCodingStandard/Sniffs/Classes/ClassDeclarationSniff.php on line 23
PHP Stack trace:
PHP   1. {main}() /usr/bin/phpcs:0
PHP   2. PHP_CodeSniffer_CLI->runphpcs() /usr/bin/phpcs:25
PHP   3. PHP_CodeSniffer_CLI->process() /usr/share/pear/PHP/CodeSniffer/CLI.php:113
PHP   4. PHP_CodeSniffer->initStandard() /usr/share/pear/PHP/CodeSniffer/CLI.php:956
PHP   5. PHP_CodeSniffer->registerSniffs() /usr/share/pear/PHP/CodeSniffer.php:594
PHP   6. include_once() /usr/share/pear/PHP/CodeSniffer.php:1409

I hope this makes things clearer

Body:
Some details on how to use namespaces can be found at the php manual.

In your case it seems you are using the same namespace.

To correctly use an interface, you have to implement it into your class.
The correct use would be the following:

Class Apple implements Fruit { ... }

More on interfaces and how to use them can be found here.

You are using the extends keyword which is used for creating child classes of a parent class.

The php manual on parent and child classes (called inheritance) has been linked here


问:
Connect Electron desktop app with hardware
if I develop app desktop with Electron (atom). This app can connect with hardware, example barcode readers? How to?
electron.atom.io</p>

答: Don't know about 'other' hardware but "most" barcode readers need nothing but drivers on the OS, you will see they 'type' the code in your 'input' element :)


问:
Method get a string
I am trying to make a get method in a class medicine to get the description.
As I know of that in C++, there is no data type "String" like in Java, therefore I need to make an array of char to save the description. I couldn't find a way to make a method with return type "array of chars", I use a pointer like the following.

```<code>class Medicine {
public:
    char description[100] = "testing";
    char *getDescription() {
        char *p_description;
        char *p_subDescription = (char*)malloc(100 * sizeof(char));
        strcpy(p_subDescription, description);
        p_description = p_subDescription;
        free(p_subDescription);
        return p_description;
    }
};
</code>```

I have a question: is there any other way I can do to make the code shorter? I feel like this is too much work just for a method to get a string.

Thank,

答:
If you want this to be static (class-specific), the easiest way I can think of is a static, public property:</p>

```<code>class Medicine {
public:
    static const std::string description;
};
const std::string Medicine::description = "testing";
</code>```

Title: Method get a string

Body:
I am trying to make a get method in a class medicine to get the description.
As I know of that in C++, there is no data type "String" like in Java, therefore I need to make an array of char to save the description. I couldn't find a way to make a method with return type "array of chars", I use a pointer like the following.

class Medicine {
public:
    char description[100] = "testing";
    char *getDescription() {
        char *p_description;
        char *p_subDescription = (char*)malloc(100 * sizeof(char));
        strcpy(p_subDescription, description);
        p_description = p_subDescription;
        free(p_subDescription);
        return p_description;
    }
};

I have a question: is there any other way I can do to make the code shorter? I feel like this is too much work just for a method to get a string.

Thank,

Body:
If you want this to be static (class-specific), the easiest way I can think of is a static, public property:

class Medicine {
public:
    static const std::string description;
};
const std::string Medicine::description = "testing";


问:
Natural Language Generation - how to go beyond templates
We've build a system that analyzes some data and outputs some results in plain English (i.e. no charts etc.). The current implementation relies on lots of templates and some randomization in order to give as much diversity to the text as possible.

We'd like to switch to something more advanced with the hope that the produced text is less repetitive and sounds less robotic. I've searched a lot on google but I cannot find something concrete to start from. Any ideas?

EDIT: The data fed to the NLG mechanism are in JSON format. Here is an example about web analytics data. The json file may contain for example a metric (e.g. visits), it's value in the last X days, whether the last value is expected or not and which dimensions (e.g. countries or marketing channels) affected its change.

The current implementation could give something like this:

Overall visits in the UK mainly from ABC email campaign reached 10K (+20% DoD) and were above the expected value by 10%. Users were mainly landing on XXX page while the increase was consistent across devices.

We're looking to finding a way to depend less on templates, sound even more natural and increase the vocabulary.

答:
What you are looking for is a hot research area and a pretty tough task. Currently there is no way to generate 100% meaningful diverse and natural sentences. one approach to generate sentences is using n-grams. using these method you can generate sentences that look more natural and diverse that may look good but probably meaningless and grammatically incorrect.
A more up to date approach is using Deep learning. anyway if you want to generate meaningful sentences, maybe your best way is using your current template based method.
You can find an introduction to basics of n-gram based NLG here:
Generating Random Text with Bigrams

this tool sounds to implement some of the most famous techniques for natural language generation: simplenlg


问:
Python: Regex help
```<code>str = "a\b\c\dsdf\matchthis\erwe.txt"
</code>```

The last folder name.

Match "matchthis"

答:
```<code>x = "a\b\c\d\match\something.txt"
match = x.split('\\')[-2]
</code>```

ContentLicense: CC BY-SA 2.5

Title: Python: Regex help

Body:
str = "a\b\c\dsdf\matchthis\erwe.txt"

The last folder name.

Match "matchthis"


问:
JSON Data to Table View is too slow
I am showing JSON data in TableView but the application is slow. It is waiting 5-10 seconds before display.
I am getting this error in Xcode output:

2017-06-05 12:49:47.505 Ekstraders[1167:137558] This application is
  modifying the autolayout engine from a background thread after the
  engine was accessed from the main thread. This can lead to engine
  corruption and weird crashes.

```<code> Stack:(
    0   CoreFoundation                      0x000000010ad78b0b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x0000000108020141 objc_exception_throw + 48
    2   CoreFoundation                      0x000000010ade1625 +[NSException raise:format:] + 197
    3   Foundation                          0x0000000107d1917b _AssertAutolayoutOnAllowedThreadsOnly + 105
    4   Foundation                          0x0000000107d18f0f -[NSISEngine _optimizeWithoutRebuilding] + 61
    5   Foundation                          0x0000000107b487e6 -[NSISEngine optimize] + 108
    6   Foundation                          0x0000000107d16ef4 -[NSISEngine performPendingChangeNotifications] + 84
    7   UIKit                               0x00000001085b5412 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1787
    8   QuartzCore                          0x000000010dce6904 -[CALayer layoutSublayers] + 146
    9   QuartzCore                          0x000000010dcda526 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 370
    10  QuartzCore                          0x000000010dcda3a0 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
    11  QuartzCore                          0x000000010dc69e92 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 294
    12  QuartzCore                          0x000000010dc96130 _ZN2CA11Transaction6commitEv + 468
    13  QuartzCore                          0x000000010dc9642c _ZN2CA11Transaction14release_threadEPv + 214
    14  libsystem_pthread.dylib             0x000000010c065413 _pthread_tsd_cleanup + 544
    15  libsystem_pthread.dylib             0x000000010c06514d _pthread_exit + 152
    16  libsystem_pthread.dylib             0x000000010c0636d1 pthread_attr_getschedpolicy + 0
    17  libsystem_pthread.dylib             0x000000010c0630f1 start_wqthread + 13
)
</code>```

ViewController.swift:

```<code>import UIKit

class FirstViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!

    var tbCount = 0

    var myMp3s = [Mp3]()

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.dataSource = self
        tableView.delegate = self

        let url = URL(string: "example.php")

         DispatchQueue.main.async() { //JSON to Mp3 object.

        URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
            guard let data = data, error == nil else { return }

            do {
                let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
                let posts = json["server_response"] as? [[String: Any]] ?? []

                for i in posts {

                    print(i["id"]!)

                    let mp3 = Mp3(id: i["id"] as! String, category: i["kategori"] as! String)

                    self.myMp3s.append(mp3)

                }

                self.tableView.reloadData()
                self.tableView.tableFooterView = UIView(frame: .zero)

                print("counte", self.myMp3s.count)

            } catch let error as NSError {
                print(error)
            }
        }).resume()

        }

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myMp3s.count

    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        var height:CGFloat = CGFloat()

        height = 100
        return height
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell  = UITableViewCell()
        cell.backgroundColor =  UIColor.darkGray

        //Design
        cell.textLabel?.text = self.myMp3s[indexPath.row].category

        cell.textLabel?.backgroundColor = .red
        cell.textLabel?.layer.borderWidth = 3
        cell.textLabel?.layer.borderColor = UIColor.lightGray.cgColor
        cell.textLabel?.heightAnchor.constraint(equalToConstant: 50).isActive = true
        cell.textLabel?.widthAnchor.constraint(equalToConstant: 200).isActive = true

        cell.textLabel?.layer.cornerRadius = 10
        cell.textLabel?.clipsToBounds = true
        cell.textLabel?.centerYAnchor.constraint(equalTo: cell.centerYAnchor).isActive = true
        cell.textLabel?.centerXAnchor.constraint(equalTo: cell.centerXAnchor).isActive = true

        cell.textLabel?.textAlignment = .center
        cell.textLabel?.textColor = .white
        cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 16.0)

        return cell

    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print(myMp3s[indexPath.row].category)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}
</code>```

I can show JSON data in tableview, no problem but the problem is that it is too slow. It is waiting before display.
How can I solve this problem? Where am I wrong?

答:
URLSession.shared.dataTask is executing the completion handler in a background thread. This leads to unexpected issues because operations affecting the UI must be done by the main thread.

Thus, you should wrap those parts with DispatchQueue.main.async {}:

```<code>DispatchQueue.main.async {
  self.tableView.reloadData()
  self.tableView.tableFooterView = UIView(frame: .zero)
}
</code>```

Title: JSON Data to Table View is too slow

Body:
I am showing JSON data in TableView but the application is slow. It is waiting 5-10 seconds before display.
I am getting this error in Xcode output:

2017-06-05 12:49:47.505 Ekstraders[1167:137558] This application is
  modifying the autolayout engine from a background thread after the
  engine was accessed from the main thread. This can lead to engine
  corruption and weird crashes.

 Stack:(
    0   CoreFoundation                      0x000000010ad78b0b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x0000000108020141 objc_exception_throw + 48
    2   CoreFoundation                      0x000000010ade1625 +[NSException raise:format:] + 197
    3   Foundation                          0x0000000107d1917b _AssertAutolayoutOnAllowedThreadsOnly + 105
    4   Foundation                          0x0000000107d18f0f -[NSISEngine _optimizeWithoutRebuilding] + 61
    5   Foundation                          0x0000000107b487e6 -[NSISEngine optimize] + 108
    6   Foundation                          0x0000000107d16ef4 -[NSISEngine performPendingChangeNotifications] + 84
    7   UIKit                               0x00000001085b5412 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 1787
    8   QuartzCore                          0x000000010dce6904 -[CALayer layoutSublayers] + 146
    9   QuartzCore                          0x000000010dcda526 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 370
    10  QuartzCore                          0x000000010dcda3a0 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 24
    11  QuartzCore                          0x000000010dc69e92 _ZN2CA7Context18commit_transactionEPNS_11TransactionE + 294
    12  QuartzCore                          0x000000010dc96130 _ZN2CA11Transaction6commitEv + 468
    13  QuartzCore                          0x000000010dc9642c _ZN2CA11Transaction14release_threadEPv + 214
    14  libsystem_pthread.dylib             0x000000010c065413 _pthread_tsd_cleanup + 544
    15  libsystem_pthread.dylib             0x000000010c06514d _pthread_exit + 152
    16  libsystem_pthread.dylib             0x000000010c0636d1 pthread_attr_getschedpolicy + 0
    17  libsystem_pthread.dylib             0x000000010c0630f1 start_wqthread + 13
)

ViewController.swift:

import UIKit

class FirstViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

    @IBOutlet weak var tableView: UITableView!

    var tbCount = 0

    var myMp3s = [Mp3]()

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.dataSource = self
        tableView.delegate = self

        let url = URL(string: "example.php")

         DispatchQueue.main.async() { //JSON to Mp3 object.

        URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
            guard let data = data, error == nil else { return }

            do {
                let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
                let posts = json["server_response"] as? [[String: Any]] ?? []

                for i in posts {

                    print(i["id"]!)

                    let mp3 = Mp3(id: i["id"] as! String, category: i["kategori"] as! String)

                    self.myMp3s.append(mp3)

                }

                self.tableView.reloadData()
                self.tableView.tableFooterView = UIView(frame: .zero)

                print("counte", self.myMp3s.count)

            } catch let error as NSError {
                print(error)
            }
        }).resume()

        }

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myMp3s.count

    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        var height:CGFloat = CGFloat()

        height = 100
        return height
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell  = UITableViewCell()
        cell.backgroundColor =  UIColor.darkGray

        //Design
        cell.textLabel?.text = self.myMp3s[indexPath.row].category

        cell.textLabel?.backgroundColor = .red
        cell.textLabel?.layer.borderWidth = 3
        cell.textLabel?.layer.borderColor = UIColor.lightGray.cgColor
        cell.textLabel?.heightAnchor.constraint(equalToConstant: 50).isActive = true
        cell.textLabel?.widthAnchor.constraint(equalToConstant: 200).isActive = true

        cell.textLabel?.layer.cornerRadius = 10
        cell.textLabel?.clipsToBounds = true
        cell.textLabel?.centerYAnchor.constraint(equalTo: cell.centerYAnchor).isActive = true
        cell.textLabel?.centerXAnchor.constraint(equalTo: cell.centerXAnchor).isActive = true

        cell.textLabel?.textAlignment = .center
        cell.textLabel?.textColor = .white
        cell.textLabel?.font = UIFont.boldSystemFont(ofSize: 16.0)

        return cell

    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print(myMp3s[indexPath.row].category)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

I can show JSON data in tableview, no problem but the problem is that it is too slow. It is waiting before display.
How can I solve this problem? Where am I wrong?

Body:
URLSession.shared.dataTask is executing the completion handler in a background thread. This leads to unexpected issues because operations affecting the UI must be done by the main thread.

Thus, you should wrap those parts with DispatchQueue.main.async {}:

DispatchQueue.main.async {
  self.tableView.reloadData()
  self.tableView.tableFooterView = UIView(frame: .zero)
}


问:
How to run node server and java server in same command line in package.json start
I need to run :

```<code>node server.js
</code>```

And :

```<code>java -Xmx4g -cp 'libraries/corenlp/*' edu.stanford.nlp.pipeline.StanfordCoreNLPServer -serverProperties StanfordCoreNLP-french.properties -port 9000 -timeout 15000
</code>```

I tried :

```<code>node server.js; java -Xmx4g -cp 'libraries/corenlp/*' edu.stanford.nlp.pipeline.StanfordCoreNLPServer -serverProperties StanfordCoreNLP-french.properties -port 9000 -timeout 15000
</code>```

Or

```<code>node server.js && java -Xmx4g -cp 'libraries/corenlp/*' edu.stanford.nlp.pipeline.StanfordCoreNLPServer -serverProperties StanfordCoreNLP-french.properties -port 9000 -timeout 15000
</code>```

But in both case the java server is not running when I ask it in the node applicaition. But if I run both commande in 2 differents console.
There is no problem.
Thank you

Edit: I try to do it in the npm start

答:
You need to run the processes in the background. Please append & at the end of the commands to run them in the background.

```<code>node server.js &

java -Xmx4g -cp 'libraries/corenlp/*' edu.stanford.nlp.pipeline.StanfordCoreNLPServer -serverProperties StanfordCoreNLP-french.properties -port 9000 -timeout 15000 &
</code>```

To kill them, you need to search these processes using ps -ef | grep command.

Body:
I need to run :

node server.js

And :

java -Xmx4g -cp 'libraries/corenlp/*' edu.stanford.nlp.pipeline.StanfordCoreNLPServer -serverProperties StanfordCoreNLP-french.properties -port 9000 -timeout 15000

I tried :

node server.js; java -Xmx4g -cp 'libraries/corenlp/*' edu.stanford.nlp.pipeline.StanfordCoreNLPServer -serverProperties StanfordCoreNLP-french.properties -port 9000 -timeout 15000

Or

node server.js && java -Xmx4g -cp 'libraries/corenlp/*' edu.stanford.nlp.pipeline.StanfordCoreNLPServer -serverProperties StanfordCoreNLP-french.properties -port 9000 -timeout 15000

But in both case the java server is not running when I ask it in the node applicaition. But if I run both commande in 2 differents console.
There is no problem.
Thank you

Edit: I try to do it in the npm start

Body:
You need to run the processes in the background. Please append & at the end of the commands to run them in the background.

node server.js &

java -Xmx4g -cp 'libraries/corenlp/*' edu.stanford.nlp.pipeline.StanfordCoreNLPServer -serverProperties StanfordCoreNLP-french.properties -port 9000 -timeout 15000 &

To kill them, you need to search these processes using ps -ef | grep command.


问:
How to add existing folder structure to VS2015 ASP.NET Web Site Project?
I have a simple VS2015 solution including an ASP.NET Web App project.

I want to add files from an online example, including their folder structure.

In other VS Project Types, if I click the "Show All Files" menu icon, I can see existing files (not already in the Project) and then "Include in Project".

However, in the ASP.NET Web App project, the "Show All Files" menu icon doesn't show up.

So, how do I either get "Show All Files" to appear for such a project type, or how can I add existing files with their folder structure to an ASP.NET Web App project?

答:
As it turns out, there's no "Show All Files" option for an ASP.NET Web App Project.

To see the files I'd added to the file system, that hadn't yet shown up in Visual Studio 2015, all I had to do was:

Under the Solution, right-click the Project

click "Refresh Folder"

The folder that existed in the file system now also showed up in VS2015, as I needed


问:
How to append input type text value to a href laravel?
I had a link which will get the value of input(text) if not empty and append it to href value. Is there a way to accomplish it?. Heres my code. Thanks in advance.</p>

```<code><a id= "lnk_audio_devices" href="{{route('search.products', ['category' => 'audio_devices',
          @if(txt_product.value != '')
            'products' => txt_product.value
          @endif
           ])}}" >Audio Devices</a>
</code>```

答:
First of all, you might want to try a workaround with a form, that is the usual way things like these are done, leading to an url like this foobar.com/foo/bar?yourinput=whatyoutyped. Instead of the button being a link, it nom submits the form.

If you want to keep your laravel routing the same. You will need javascript to append the text value to the link when the button is clicked.

function navigate(link, inputid){
  var url = link.href + "/" + document.getElementById(inputid).value;
  //window.location.href = url; //navigates to the given url, disabled for demo
  alert(url);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>click me
<input type="text" id="myText"></code>```

Body:
I had a link which will get the value of input(text) if not empty and append it to href value. Is there a way to accomplish it?. Heres my code. Thanks in advance.

 'audio_devices',
          @if(txt_product.value != '')
            'products' => txt_product.value
          @endif
           ])}}" >Audio Devices

Body:
First of all, you might want to try a workaround with a form, that is the usual way things like these are done, leading to an url like this foobar.com/foo/bar?yourinput=whatyoutyped. Instead of the button being a link, it nom submits the form.

If you want to keep your laravel routing the same. You will need javascript to append the text value to the link when the button is clicked.

function navigate(link, inputid){
  var url = link.href + "/" + document.getElementById(inputid).value;
  //window.location.href = url; //navigates to the given url, disabled for demo
  alert(url);
}

<a href="" onClick="navigate(this,'myText')">click me</a>
<input type="text" id="myText">


答:
Try this</p>

```<code>SELECT *, `Time2`-`Time1` AS `Time3` FROM `tablename`
</code>```

Title: How to do subtraction between two fields in a Table using an SQL query

Body:
I want to display the subtraction of two values from two different columns to a third column using a SQL query.

This is the table structure:

------------------------------------
id | subject | Time1 | Time2| Time3
------------------------------------
1  | String1 | 50    |  78  |
2  | String2 | 60    |  99  |
3  |         |       |      |

I want to subtract Time2 from Time1 if both Time1 and Time2 has data and store in Time3.

Output should be like as

------------------------------------
id | subject | Time1 | Time2| Time3
------------------------------------
1  | String1 | 50    |  78  |  28
2  | String2 | 60    |  99  |  39
3  |         |       |      |

Thanks!

Body:
Try this

SELECT *, `Time2`-`Time1` AS `Time3` FROM `tablename`


问:
Enumeration is throwing concurrentModification Exception. why?
Enumeration is Fail-safe. Fail-safe iterators will work on the cloning of the original collection. then why it is throwing concurrentModificationException? please clarify.

Please find my code:

```<code>public static void main(String[] args) {

    Vector<String> v=new Vector<String>();
    v.add("Amit");
    v.add("Raj");
    v.add("Pathak");
    v.add("Sumit");
    v.add("Aron");
    v.add("Trek");

    Enumeration en=(Enumeration) Collections.enumeration(v);

    while(en.hasMoreElements())
    {
        String value=(String) en.nextElement();
        System.out.println(value);
        v.remove(value);//modifying the collection

    }

}
</code>```

Find the error message below

```<code>Exception in thread "main" java.util.ConcurrentModificationException
at java.util.Vector$Itr.checkForComodification(Unknown Source)
at java.util.Vector$Itr.next(Unknown Source)
at java.util.Collections$2.nextElement(Unknown Source)
at valar.org.src.EnumerationTest.main(EnumerationTest.java:24)
</code>```

答:
Enumeration is Fail-safe.

Correct. (Allowing for some language difficulties.)

Fail-safe iterators will work on the cloning of the original collection.

Correct. (Allowing for some language difficulties.)

then why it is throwing concurrentModificationException?

Because there is no cloning involved.

Where is the cloning?

Body:
Enumeration is Fail-safe. Fail-safe iterators will work on the cloning of the original collection. then why it is throwing concurrentModificationException? please clarify.

Please find my code:

public static void main(String[] args) {

    Vector<String> v=new Vector<String>();
    v.add("Amit");
    v.add("Raj");
    v.add("Pathak");
    v.add("Sumit");
    v.add("Aron");
    v.add("Trek");

    Enumeration en=(Enumeration) Collections.enumeration(v);

    while(en.hasMoreElements())
    {
        String value=(String) en.nextElement();
        System.out.println(value);
        v.remove(value);//modifying the collection

    }

}

Find the error message below

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.Vector$Itr.checkForComodification(Unknown Source)
at java.util.Vector$Itr.next(Unknown Source)
at java.util.Collections$2.nextElement(Unknown Source)
at valar.org.src.EnumerationTest.main(EnumerationTest.java:24)


问:
My android studio shows graphic on opening activity_main.xml
My android studio shows graphically editing instead of the written xml codes. The online curse that i am studying requires me to write the xml codes so please tell me how can i switch to text editing of the visual of my app.</p>

答: Save your XML file to layouts folder, then opening the xml file you can view two tabs at bottom. One is TEXT and other is DESIGN. Switch to TEXT button to edit xml file. Check below image:


问:
reading/writing data frame to google sheets using pygsheets
What is the correct program flow to write different sized data frame to the same worksheet but ensure only the most recent data values written are visible?

Here was my original sequence:

```<code>gc = pygsheets.authorize(outh_file=oauth_file)
sh = gc.open(sheet_name)
wks = sh.worksheet_by_title(wks_name)
wks.set_dataframe(df, (1, 1))
</code>```

Problem with above sequence is if 1st write was 3800 rows x 12 cols and 2nd write was 2400 rows x 12 cols the wks would still show data from the prior write for rows above 2400.

My 2nd solution (basically a hack just to get it to work for me):

```<code>gc = pygsheets.authorize(outh_file=oauth_file)
sh = gc.open(spreadsheet_name)
wks = sh.worksheet_by_title(sheet_name)
sh.del_worksheet(wks)
sh.add_worksheet(sheet_name, rows=len(df) + 1, cols=len(df.columns))
wks = sh.worksheet_by_title(sheet_name)
wks.set_dataframe(df, (1, 1))
</code>```

The above sequence basically does what I want but I do not like having to delete the wks (I lose all my manual formatting). I know there must be a correct way to accomplish but I do not know the pygsheets API very well.

Will a more advanced pygsheet users please advise proper program flow and methods to use?

TIA,
--Rj

答:
fit=True will basically resize the sheet to fit you data frame. so if you wanna keep the sheet at same size, you can clear the sheet before next write. it wold be easier than your second solution. Also if you just wanna clear the range you had written earlier, you can pass a range to clear function.

```<code>wks.set_dataframe(df, (1, 1))
wks.clear()
wks.set_dataframe(df, (1, 1))
</code>```

Body:
What is the correct program flow to write different sized data frame to the same worksheet but ensure only the most recent data values written are visible?

Here was my original sequence:

gc = pygsheets.authorize(outh_file=oauth_file)
sh = gc.open(sheet_name)
wks = sh.worksheet_by_title(wks_name)
wks.set_dataframe(df, (1, 1))

Problem with above sequence is if 1st write was 3800 rows x 12 cols and 2nd write was 2400 rows x 12 cols the wks would still show data from the prior write for rows above 2400.

My 2nd solution (basically a hack just to get it to work for me):

gc = pygsheets.authorize(outh_file=oauth_file)
sh = gc.open(spreadsheet_name)
wks = sh.worksheet_by_title(sheet_name)
sh.del_worksheet(wks)
sh.add_worksheet(sheet_name, rows=len(df) + 1, cols=len(df.columns))
wks = sh.worksheet_by_title(sheet_name)
wks.set_dataframe(df, (1, 1))

The above sequence basically does what I want but I do not like having to delete the wks (I lose all my manual formatting). I know there must be a correct way to accomplish but I do not know the pygsheets API very well.

Will a more advanced pygsheet users please advise proper program flow and methods to use?

TIA,
--Rj

Body:
fit=True will basically resize the sheet to fit you data frame. so if you wanna keep the sheet at same size, you can clear the sheet before next write. it wold be easier than your second solution. Also if you just wanna clear the range you had written earlier, you can pass a range to clear function.

wks.set_dataframe(df, (1, 1))
wks.clear()
wks.set_dataframe(df, (1, 1))


问:
Lumen @ foreach Invalid argument
When I use this code:

```<code> $body=$request->all();
        $contacts = json_decode($request->get('contacts'), true);
        $user_contacts = array_flatten($this->_model->scan_contacts($this->_user->user_id, $contacts));
        $nonsync_contacts = array();
        foreach ($contacts as $contact) {

            if (!in_array($contact["mobile"], $user_contacts)) {
                $nonsync_contacts[] = $contact;
            }
        }
</code>```

I get this error message:

```<code>ErrorException in Arr.php line 493:
Invalid argument supplied for foreach()
</code>```

How do I avoid this error?

答:
```<code>$body=$request->all();
$contacts = json_decode($request->get('contacts'), true);
$user_contacts = array_flatten($this->_model->scan_contacts($this->_user->user_id, $contacts));
$nonsync_contacts = array();
if(is_array($contacts)) {
    foreach ($contacts as $contact) {

        if (!in_array($contact["mobile"], $user_contacts)) {
            $nonsync_contacts[] = $contact;
        }
    }
}
</code>```

Check is a $contacts array and after that loop it(because it can be null or something else)

Title: Lumen @ foreach Invalid argument

Body:
When I use this code:

 $body=$request->all();
        $contacts = json_decode($request->get('contacts'), true);
        $user_contacts = array_flatten($this->_model->scan_contacts($this->_user->user_id, $contacts));
        $nonsync_contacts = array();
        foreach ($contacts as $contact) {

            if (!in_array($contact["mobile"], $user_contacts)) {
                $nonsync_contacts[] = $contact;
            }
        }

I get this error message:

ErrorException in Arr.php line 493:
Invalid argument supplied for foreach()

How do I avoid this error?

Body:
$body=$request->all();
$contacts = json_decode($request->get('contacts'), true);
$user_contacts = array_flatten($this->_model->scan_contacts($this->_user->user_id, $contacts));
$nonsync_contacts = array();
if(is_array($contacts)) {
    foreach ($contacts as $contact) {

        if (!in_array($contact["mobile"], $user_contacts)) {
            $nonsync_contacts[] = $contact;
        }
    }
}

Check is a $contacts array and after that loop it(because it can be null or something else)


问:
Cropping UIImagePickerController with overlay
I am trying to create an square overlay for a UIImagePickerController.

I have created a NIB with a top and bottom view which overlays the UIImagePickerController which works fine.

When the photo is taken, it seems that the ratio of the photo from height to width is 1.33333. However the ratio of the frame from height to width (on iphone 4s) is 1.5.

How can I get the exact frame of what the UIImagePickerController is taking a photo of? It can't be covering the whole screen, unless it is being stretched when added to the parent view.

I need the correct frame so I can crop the image that UIImagePickerController creates. I don't want to have the user crop the image manually.

Thanks

答:
If you want to create a square overlay, use this:

```<code>UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.allowsEditing = YES;
</code>```

And to show a captured image in full screen, use this:

```<code>picker.allowsEditing = NO;
CGSize screenSize = [[UIScreen mainScreen] bounds].size;
float cameraAspectRatio = 4.0 / 3.0;
float imageWidth = floorf(screenSize.width * cameraAspectRatio);
float scale = ceilf((screenSize.height / imageWidth) * 10.0) / 10.0;

imagePicker.cameraViewTransform = CGAffineTransformMakeScale(scale, scale)
</code>```

Body:
If you want to create a square overlay, use this:

UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.sourceType = UIImagePickerControllerSourceTypeCamera;
picker.allowsEditing = YES;

And to show a captured image in full screen, use this:

picker.allowsEditing = NO;
CGSize screenSize = [[UIScreen mainScreen] bounds].size;
float cameraAspectRatio = 4.0 / 3.0;
float imageWidth = floorf(screenSize.width * cameraAspectRatio);
float scale = ceilf((screenSize.height / imageWidth) * 10.0) / 10.0;

imagePicker.cameraViewTransform = CGAffineTransformMakeScale(scale, scale)


问:
Click event and namespaced click event - which fires first and will stopPropagation() cancel one of them?
Example: foundation dropdown has namespaced event click.fndtn.dropdown.
Their code binds to it, but not to pure click.

What happens when I bind to click event of same element?

Which event fires first?

If I call event.stopPropagation() in click handler will that cancel click.fndtn.dropdown handler?

If I call event.stopPropagation() in click.fndtn.dropdown handler will that cancel click handler?

答:
1. Which even fires first?

jQuery ensures that they're fired in the order in which they were attached (which is also standard now, as of a few years ago).

2. If I call event.stopPropagation() in click handler will that cancel click.fndtn.dropdown handler?

No, but stopImmediatePropagation will if your handler was registered first.

3. If I call event.stopPropagation() in click.fndtn.dropdown handler will that cancel click handler?

No, but stopImmediatePropagation will if that handler was registered first.

Example:

$("#ns-first-stop-prop").on("click.ns", function(e) {
  console.log("click.ns -- calling stopPropagation");
  e.stopPropagation();
});
$("#ns-first-stop-prop").on("click", function(e) {
  console.log("click -- calling stopPropagation");
  e.stopPropagation();
});

$("#plain-first-stop-prop").on("click", function(e) {
  console.log("click -- calling stopPropagation");
  e.stopPropagation();
});
$("#plain-first-stop-prop").on("click.ns", function(e) {
  console.log("click.ns -- calling stopPropagation");
  e.stopPropagation();
});

$("#ns-first-stop-immed").on("click.ns", function(e) {
  console.log("click.ns -- calling stopImmediatePropagation");
  e.stopImmediatePropagation();
});
$("#ns-first-stop-immed").on("click", function(e) {
  console.log("click -- calling stopImmediatePropagation");
  e.stopImmediatePropagation();
});

$("#plain-first-stop-immed").on("click", function(e) {
  console.log("click -- calling stopImmediatePropagation");
  e.stopImmediatePropagation();
});
$("#plain-first-stop-immed").on("click.ns", function(e) {
  console.log("click.ns -- calling stopImmediatePropagation");
  e.stopImmediatePropagation();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div><input type="button" id="ns-first-stop-prop" value="Namespaced First - calls stopPropagation"></div>
<div><input type="button" id="plain-first-stop-prop" value="Non-Namespaced First - calls stopPropagation"></div>
<div><input type="button" id="ns-first-stop-immed" value="Namespaced First - calls stopImmediatePropagation"></div>
<div><input type="button" id="plain-first-stop-immed" value="Non-Namespaced First - calls stopImmediatePropagation"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
1. Which even fires first?

jQuery ensures that they're fired in the order in which they were attached (which is also standard now, as of a few years ago).

2. If I call event.stopPropagation() in click handler will that cancel click.fndtn.dropdown handler?

No, but stopImmediatePropagation will if your handler was registered first.

3. If I call event.stopPropagation() in click.fndtn.dropdown handler will that cancel click handler?

No, but stopImmediatePropagation will if that handler was registered first.

Example:

$("#ns-first-stop-prop").on("click.ns", function(e) {
  console.log("click.ns -- calling stopPropagation");
  e.stopPropagation();
});
$("#ns-first-stop-prop").on("click", function(e) {
  console.log("click -- calling stopPropagation");
  e.stopPropagation();
});

$("#plain-first-stop-prop").on("click", function(e) {
  console.log("click -- calling stopPropagation");
  e.stopPropagation();
});
$("#plain-first-stop-prop").on("click.ns", function(e) {
  console.log("click.ns -- calling stopPropagation");
  e.stopPropagation();
});

$("#ns-first-stop-immed").on("click.ns", function(e) {
  console.log("click.ns -- calling stopImmediatePropagation");
  e.stopImmediatePropagation();
});
$("#ns-first-stop-immed").on("click", function(e) {
  console.log("click -- calling stopImmediatePropagation");
  e.stopImmediatePropagation();
});

$("#plain-first-stop-immed").on("click", function(e) {
  console.log("click -- calling stopImmediatePropagation");
  e.stopImmediatePropagation();
});
$("#plain-first-stop-immed").on("click.ns", function(e) {
  console.log("click.ns -- calling stopImmediatePropagation");
  e.stopImmediatePropagation();
});

<div><input type="button" id="ns-first-stop-prop" value="Namespaced First - calls stopPropagation"></div>
<div><input type="button" id="plain-first-stop-prop" value="Non-Namespaced First - calls stopPropagation"></div>
<div><input type="button" id="ns-first-stop-immed" value="Namespaced First - calls stopImmediatePropagation"></div>
<div><input type="button" id="plain-first-stop-immed" value="Non-Namespaced First - calls stopImmediatePropagation"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>