问:
FindAndUpdate How to check if document was really updated
Imagine the following model:

```<code>var Office =
{
    id: 1,
    name: "My Office",
    branches:
    [
      {
        adddress: "Some street, that avenue",
        isPrincipal: true,
      },
      {
        adddress: "Another address",
        isPrincipal: false,
      },
    ]
}
</code>```

I'd like to remove a branch, but we can't let the user remove the principal branch from an office. So here's my function:

```<code>remove: function(body)
{
  return new Promise(function(resolve, reject)
  {
    return Office.findByIdAndUpdate(1, { $pull: {'branches': {_id: body.branch.id}}}, { new: true })
    .then(function(updatedOffice){
      resolve(updatedOffice)
    })
    .catch(function(error){
      reject(error);
    });

  })
}
</code>```

I have some doubts here:

As you can see I haven't included the another WHERE on the isPrincipal property, this is because I don't know how can I determine whether the office object got actually changed. Because the object will alway be retrieved but... How can I know this for sure?

Is FindByIdAndUpdate the best approach considering we can't let a user delete the principal branch, and if he's trying to do so, we have to show a warning.

答:
The only real reliable way to see if an update was applied for something like a $pull is to basically check the returned document and see if the data you intended to $pull is still in there or not.

That's for any of the "findAndUpdate" variety of actions, and there is a valid reason for that as well as it also being the case that a plain .update() will actually "reliably" tell you if the modification was in fact made.

To walk through the cases:

Check the Returned Content

This basically involves looking at the array in the returned document in order to see if what we asked to remove is actually there:

```<code>var pullId = "5961de06ea264532c684611a";

Office.findByIdAndUpdate(1,
  { "$pull": { "branches": { "_id": pullId } } },
  { "new": true }
).then(office => {
  // Check if the supplied value is still in the array
  console.log(
    "Still there?: %s",
    (office.branches.find( b => b._id.toHexString() === pullId))
      ? true : false
  );
}).catch(err => console.error(err))
</code>```

We use .toHexString() in order to compare the actual value from an ObjectId since JavaScript just does not do "equality" with "Objects". You would check on both "left" and "right" if supplying something that was already "cast" to an ObjectId value, but in this case we know the other input is a "string".

Just use .update(), "It's reliable"

The other case here to consider brings into question if you "really need" the returned modified data anyway. Because the .update() method, will reliably return a result telling you if anything was actually modified:

```<code>Office.update(
  { "_id": 1 },
  { "$pull": { "branches": { "_id": pullId } } },
).then(result => {
  log(result);
}).catch(err => console.error(err))
</code>```

Where result here will look like:

```<code>{
  "n": 1,
  "nModified": 1,        // <--- This always tells the truth, and cannot lie!
  "opTime": {
    "ts": "6440673063762657282",
    "t": 4
  },
  "electionId": "7fffffff0000000000000004",
  "ok": 1
}
</code>```

And in which the nModified is a "true" indicator of whether something "actually updated". Therefore if it's 1 then the $pull actually had an effect, but when 0 nothing was actually removed from the array and nothing was modified.

This is because the method actually uses the updated API, which does have reliable results indicating actual modifications. The same would apply to something like a $set which did not actually change the value because the the value supplied was equal to what already existed in the document.

findAndModify Lies!

The other case here you might think of when looking closely at the documentation is to actually inspect the "raw result" and see if the document was modified or not. There is actually an indicator in the specification for this.

The problem is ( as well as requiring more work with Promises ) that the result is not actually truthful:

```<code>var bogusId = "5961de06ea264532c684611a"; // We know this is not there!

Promise((resolve,reject) => {
  Office.findByIdAndUpdate(1,
    { "$pull": { "branches": { "_id": bogusId } } },
    { "new": true, "passRawResult" },
    (err,result,raw) => {        // We cannot pass multiple results to a Promise
      if (err) reject(err);
      resolve({ result, raw });   // So we wrap it!
    }
  )
})
.then(response => log(response.raw))
.catch(err => console.error(err));
</code>```

The problem here is that even when we "know" this should not modify, the response says otherwise:

```<code>{
  "lastErrorObject": {
    "updatedExisting": true,
    "n": 1                     // <--- LIES! IT'S ALL LIES!!!
  },
  "value": {
    "_id": 1,
    "name": "My Office",
    "branches": [
      {
        "address": "Third address",
        "isPrincipal": false,
        "_id": "5961de06ea264532c6846118"
      }
    ],
    "__v": 0
  },
  "ok": 1,
  "_kareemIgnore": true
}
</code>```

So even after all that work to get the "third" argument out of the callback response, we still did not get told the correct information about the update.

Concluding

So if you want to "reliably" do this with a single request ( and you cannot reliably do that with multiple requests since the document could change in between! ) then your two options are:

Check the returned document to see if the data you wanted to remove is still there.

Forget returning a document and trust that .update() always tells you the "truth" ;)

Which one of these you use depends on the application usage pattern, but those are the two different ways of returning an "reliable" result.

Bit of a Listing

So just to be sure, here's a listing that goes through all the examples and demonstrates what they actually return:

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

mongoose.Promise = global.Promise;
mongoose.set('debug',true);

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

const branchesSchema = new Schema({
  address: String,
  isPrincipal: Boolean
});

const officeSchema = new Schema({
  _id: Number,
  name: String,
  branches: [branchesSchema]
},{ _id: false });

const Office = mongoose.model('Office', officeSchema);

function log(data) {
  console.log(JSON.stringify(data,undefined,2))
}

const testId = "5961a56d3ffd3d5e19c61610";

async.series(
  [
    // Clean data
    (callback) =>
      async.each(mongoose.models,(model,callback) =>
        model.remove({},callback),callback),

    // Insert some data and pull
    (callback) =>
      async.waterfall(
        [
          // Create and demonstrate
          (callback) =>
            Office.create({
              _id: 1,
              name: "My Office",
              branches: [
                {
                  address: "Some street, that avenue",
                  isPrincipal: true
                },
                {
                  address: "Another address",
                  isPrincipal: false
                },
                {
                  address: "Third address",
                  isPrincipal: false
                }
              ]
            },callback),

          // Demo Alternates
          (office,callback) =>
            async.mapSeries(
              [true,false].map((t,i) => ({ t, branch: office.branches[i] })),
              (test,callback) =>
                (test.t)
                  ? Office.findByIdAndUpdate(office._id,
                      { "$pull": { "branches": { "_id": test.branch._id } } },
                      { "new": true , "passRawResult": true },
                      (err,result,raw) => {
                        if (err) callback(err);
                        log(result);
                        log(raw);
                        callback();
                      })
                  : Office.findByIdAndUpdate(office._id,
                      { "$pull": { "branches": { "_id": test.branch._id } } },
                      { "new": true } // false here
                    ).then(result => {
                      log(result);
                      console.log(
                        "Present %s",
                        (result.branches.find( b =>
                          b._id.toHexString() === test.branch._id.toHexString() ))
                          ? true : false
                      );
                      callback();
                    }).catch(err => callback(err)),
              callback
            )
        ],
        callback
      ),

    // Find and demonstate fails
    (callback) =>
      async.waterfall(
        [
          (callback) => Office.findOne({},callback),

          (office,callback) =>
            async.eachSeries([true,false],(item,callback) =>
              (item)
                ? Office.findByIdAndUpdate(office._id,
                    { "$pull": { "branches": { "_id": testId } } },
                    { "new": true, "passRawResult": true },
                    (err,result,raw) => {
                      if (err) callback(err);
                      log(result);
                      log(raw);
                      callback();
                    }
                  )
                : Office.findByIdAndUpdate(office._id,
                    { "$pull": { "branches": { "_id": testId } } },
                    { "new": true }
                  ).then(result => {
                    console.log(result);
                    console.log(
                      "Present %s",
                      (result.branches.find( b =>
                        b._id.toHexString() === office.branches[0]._id.toHexString()))
                        ? true : false
                    );
                    callback();
                  })
                  .catch(err => callback(err)),
              callback)

        ],
        callback
      ),

    // Demonstrate update() modified shows 0
    (callback) =>
      Office.update(
        {},
        { "$pull": { "branches": { "_id": testId } } }
      ).then(result => {
        log(result);
        callback();
      })
      .catch(err => callback(err)),

    // Demonstrate wrapped promise
    (callback) =>
      Office.findOne()
        .then(office => {
          return new Promise((resolve,reject) => {
            Office.findByIdAndUpdate(office._id,
              { "$pull": { "branches": { "_id": testId } } },
              { "new": true, "passRawResult": true },
              (err,result,raw) => {
                if (err) reject(err);
                resolve(raw)
              }
            );
          })
        })
        .then(office => {
          log(office);
          callback();
        })
        .catch(err => callback(err))

  ],
  (err) => {
    if (err) throw err;
    mongoose.disconnect();
  }
);
</code>```

And the output it produces:

```<code>Mongoose: offices.remove({}, {})
Mongoose: offices.insert({ _id: 1, name: 'My Office', branches: [ { address: 'Some street, that avenue', isPrincipal: true, _id: ObjectId("5961e5211a73e8331b44d74b") }, { address: 'Another address', isPrincipal: false, _id: ObjectId("5961e5211a73e8331b44d74a") }, { address: 'Third address', isPrincipal: false, _id: ObjectId("5961e5211a73e8331b44d749") } ], __v: 0 })
Mongoose: offices.findAndModify({ _id: 1 }, [], { '$pull': { branches: { _id: ObjectId("5961e5211a73e8331b44d74b") } } }, { new: true, passRawResult: true, upsert: false, remove: false, fields: {} })
{
  "_id": 1,
  "name": "My Office",
  "__v": 0,
  "branches": [
    {
      "address": "Another address",
      "isPrincipal": false,
      "_id": "5961e5211a73e8331b44d74a"
    },
    {
      "address": "Third address",
      "isPrincipal": false,
      "_id": "5961e5211a73e8331b44d749"
    }
  ]
}
{
  "lastErrorObject": {
    "updatedExisting": true,
    "n": 1
  },
  "value": {
    "_id": 1,
    "name": "My Office",
    "branches": [
      {
        "address": "Another address",
        "isPrincipal": false,
        "_id": "5961e5211a73e8331b44d74a"
      },
      {
        "address": "Third address",
        "isPrincipal": false,
        "_id": "5961e5211a73e8331b44d749"
      }
    ],
    "__v": 0
  },
  "ok": 1,
  "_kareemIgnore": true
}
Mongoose: offices.findAndModify({ _id: 1 }, [], { '$pull': { branches: { _id: ObjectId("5961e5211a73e8331b44d74a") } } }, { new: true, upsert: false, remove: false, fields: {} })
{
  "_id": 1,
  "name": "My Office",
  "__v": 0,
  "branches": [
    {
      "address": "Third address",
      "isPrincipal": false,
      "_id": "5961e5211a73e8331b44d749"
    }
  ]
}
Present false
Mongoose: offices.findOne({}, { fields: {} })
Mongoose: offices.findAndModify({ _id: 1 }, [], { '$pull': { branches: { _id: ObjectId("5961a56d3ffd3d5e19c61610") } } }, { new: true, passRawResult: true, upsert: false, remove: false, fields: {} })
{
  "_id": 1,
  "name": "My Office",
  "__v": 0,
  "branches": [
    {
      "address": "Third address",
      "isPrincipal": false,
      "_id": "5961e5211a73e8331b44d749"
    }
  ]
}
{
  "lastErrorObject": {
    "updatedExisting": true,
    "n": 1
  },
  "value": {
    "_id": 1,
    "name": "My Office",
    "branches": [
      {
        "address": "Third address",
        "isPrincipal": false,
        "_id": "5961e5211a73e8331b44d749"
      }
    ],
    "__v": 0
  },
  "ok": 1,
  "_kareemIgnore": true
}
Mongoose: offices.findAndModify({ _id: 1 }, [], { '$pull': { branches: { _id: ObjectId("5961a56d3ffd3d5e19c61610") } } }, { new: true, upsert: false, remove: false, fields: {} })
{ _id: 1,
  name: 'My Office',
  __v: 0,
  branches:
   [ { address: 'Third address',
       isPrincipal: false,
       _id: 5961e5211a73e8331b44d749 } ] }
Present true
Mongoose: offices.update({}, { '$pull': { branches: { _id: ObjectId("5961a56d3ffd3d5e19c61610") } } }, {})
{
  "n": 1,
  "nModified": 0,
  "opTime": {
    "ts": "6440680872013201413",
    "t": 4
  },
  "electionId": "7fffffff0000000000000004",
  "ok": 1
}
Mongoose: offices.findOne({}, { fields: {} })
Mongoose: offices.findAndModify({ _id: 1 }, [], { '$pull': { branches: { _id: ObjectId("5961a56d3ffd3d5e19c61610") } } }, { new: true, passRawResult: true, upsert: false, remove: false, fields: {} })
{
  "lastErrorObject": {
    "updatedExisting": true,
    "n": 1
  },
  "value": {
    "_id": 1,
    "name": "My Office",
    "branches": [
      {
        "address": "Third address",
        "isPrincipal": false,
        "_id": "5961e5211a73e8331b44d749"
      }
    ],
    "__v": 0
  },
  "ok": 1,
  "_kareemIgnore": true
}
</code>```

Body:
Imagine the following model:

var Office =
{
    id: 1,
    name: "My Office",
    branches:
    [
      {
        adddress: "Some street, that avenue",
        isPrincipal: true,
      },
      {
        adddress: "Another address",
        isPrincipal: false,
      },
    ]
}

I'd like to remove a branch, but we can't let the user remove the principal branch from an office. So here's my function:

remove: function(body)
{
  return new Promise(function(resolve, reject)
  {
    return Office.findByIdAndUpdate(1, { $pull: {'branches': {_id: body.branch.id}}}, { new: true })
    .then(function(updatedOffice){
      resolve(updatedOffice)
    })
    .catch(function(error){
      reject(error);
    });

  })
}

I have some doubts here:

As you can see I haven't included the another WHERE on the isPrincipal property, this is because I don't know how can I determine whether the office object got actually changed. Because the object will alway be retrieved but... How can I know this for sure?

Is FindByIdAndUpdate the best approach considering we can't let a user delete the principal branch, and if he's trying to do so, we have to show a warning.

Body:
The only real reliable way to see if an update was applied for something like a $pull is to basically check the returned document and see if the data you intended to $pull is still in there or not.

That's for any of the "findAndUpdate" variety of actions, and there is a valid reason for that as well as it also being the case that a plain .update() will actually "reliably" tell you if the modification was in fact made.

To walk through the cases:

Check the Returned Content

This basically involves looking at the array in the returned document in order to see if what we asked to remove is actually there:

var pullId = "5961de06ea264532c684611a";

Office.findByIdAndUpdate(1,
  { "$pull": { "branches": { "_id": pullId } } },
  { "new": true }
).then(office => {
  // Check if the supplied value is still in the array
  console.log(
    "Still there?: %s",
    (office.branches.find( b => b._id.toHexString() === pullId))
      ? true : false
  );
}).catch(err => console.error(err))

We use .toHexString() in order to compare the actual value from an ObjectId since JavaScript just does not do "equality" with "Objects". You would check on both "left" and "right" if supplying something that was already "cast" to an ObjectId value, but in this case we know the other input is a "string".

Just use .update(), "It's reliable"

The other case here to consider brings into question if you "really need" the returned modified data anyway. Because the .update() method, will reliably return a result telling you if anything was actually modified:

Office.update(
  { "_id": 1 },
  { "$pull": { "branches": { "_id": pullId } } },
).then(result => {
  log(result);
}).catch(err => console.error(err))

Where result here will look like:

{
  "n": 1,
  "nModified": 1,        // <--- This always tells the truth, and cannot lie!
  "opTime": {
    "ts": "6440673063762657282",
    "t": 4
  },
  "electionId": "7fffffff0000000000000004",
  "ok": 1
}

And in which the nModified is a "true" indicator of whether something "actually updated". Therefore if it's 1 then the $pull actually had an effect, but when 0 nothing was actually removed from the array and nothing was modified.

This is because the method actually uses the updated API, which does have reliable results indicating actual modifications. The same would apply to something like a $set which did not actually change the value because the the value supplied was equal to what already existed in the document.

findAndModify Lies!

The other case here you might think of when looking closely at the documentation is to actually inspect the "raw result" and see if the document was modified or not. There is actually an indicator in the specification for this.

The problem is ( as well as requiring more work with Promises ) that the result is not actually truthful:

var bogusId = "5961de06ea264532c684611a"; // We know this is not there!

Promise((resolve,reject) => {
  Office.findByIdAndUpdate(1,
    { "$pull": { "branches": { "_id": bogusId } } },
    { "new": true, "passRawResult" },
    (err,result,raw) => {        // We cannot pass multiple results to a Promise
      if (err) reject(err);
      resolve({ result, raw });   // So we wrap it!
    }
  )
})
.then(response => log(response.raw))
.catch(err => console.error(err));

The problem here is that even when we "know" this should not modify, the response says otherwise:

{
  "lastErrorObject": {
    "updatedExisting": true,
    "n": 1                     // <--- LIES! IT'S ALL LIES!!!
  },
  "value": {
    "_id": 1,
    "name": "My Office",
    "branches": [
      {
        "address": "Third address",
        "isPrincipal": false,
        "_id": "5961de06ea264532c6846118"
      }
    ],
    "__v": 0
  },
  "ok": 1,
  "_kareemIgnore": true
}

So even after all that work to get the "third" argument out of the callback response, we still did not get told the correct information about the update.

Concluding

So if you want to "reliably" do this with a single request ( and you cannot reliably do that with multiple requests since the document could change in between! ) then your two options are:

Check the returned document to see if the data you wanted to remove is still there.

Forget returning a document and trust that .update() always tells you the "truth" ;)

Which one of these you use depends on the application usage pattern, but those are the two different ways of returning an "reliable" result.

Bit of a Listing

So just to be sure, here's a listing that goes through all the examples and demonstrates what they actually return:

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

mongoose.Promise = global.Promise;
mongoose.set('debug',true);

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

const branchesSchema = new Schema({
  address: String,
  isPrincipal: Boolean
});

const officeSchema = new Schema({
  _id: Number,
  name: String,
  branches: [branchesSchema]
},{ _id: false });

const Office = mongoose.model('Office', officeSchema);

function log(data) {
  console.log(JSON.stringify(data,undefined,2))
}

const testId = "5961a56d3ffd3d5e19c61610";

async.series(
  [
    // Clean data
    (callback) =>
      async.each(mongoose.models,(model,callback) =>
        model.remove({},callback),callback),

    // Insert some data and pull
    (callback) =>
      async.waterfall(
        [
          // Create and demonstrate
          (callback) =>
            Office.create({
              _id: 1,
              name: "My Office",
              branches: [
                {
                  address: "Some street, that avenue",
                  isPrincipal: true
                },
                {
                  address: "Another address",
                  isPrincipal: false
                },
                {
                  address: "Third address",
                  isPrincipal: false
                }
              ]
            },callback),

          // Demo Alternates
          (office,callback) =>
            async.mapSeries(
              [true,false].map((t,i) => ({ t, branch: office.branches[i] })),
              (test,callback) =>
                (test.t)
                  ? Office.findByIdAndUpdate(office._id,
                      { "$pull": { "branches": { "_id": test.branch._id } } },
                      { "new": true , "passRawResult": true },
                      (err,result,raw) => {
                        if (err) callback(err);
                        log(result);
                        log(raw);
                        callback();
                      })
                  : Office.findByIdAndUpdate(office._id,
                      { "$pull": { "branches": { "_id": test.branch._id } } },
                      { "new": true } // false here
                    ).then(result => {
                      log(result);
                      console.log(
                        "Present %s",
                        (result.branches.find( b =>
                          b._id.toHexString() === test.branch._id.toHexString() ))
                          ? true : false
                      );
                      callback();
                    }).catch(err => callback(err)),
              callback
            )
        ],
        callback
      ),

    // Find and demonstate fails
    (callback) =>
      async.waterfall(
        [
          (callback) => Office.findOne({},callback),

          (office,callback) =>
            async.eachSeries([true,false],(item,callback) =>
              (item)
                ? Office.findByIdAndUpdate(office._id,
                    { "$pull": { "branches": { "_id": testId } } },
                    { "new": true, "passRawResult": true },
                    (err,result,raw) => {
                      if (err) callback(err);
                      log(result);
                      log(raw);
                      callback();
                    }
                  )
                : Office.findByIdAndUpdate(office._id,
                    { "$pull": { "branches": { "_id": testId } } },
                    { "new": true }
                  ).then(result => {
                    console.log(result);
                    console.log(
                      "Present %s",
                      (result.branches.find( b =>
                        b._id.toHexString() === office.branches[0]._id.toHexString()))
                        ? true : false
                    );
                    callback();
                  })
                  .catch(err => callback(err)),
              callback)

        ],
        callback
      ),

    // Demonstrate update() modified shows 0
    (callback) =>
      Office.update(
        {},
        { "$pull": { "branches": { "_id": testId } } }
      ).then(result => {
        log(result);
        callback();
      })
      .catch(err => callback(err)),

    // Demonstrate wrapped promise
    (callback) =>
      Office.findOne()
        .then(office => {
          return new Promise((resolve,reject) => {
            Office.findByIdAndUpdate(office._id,
              { "$pull": { "branches": { "_id": testId } } },
              { "new": true, "passRawResult": true },
              (err,result,raw) => {
                if (err) reject(err);
                resolve(raw)
              }
            );
          })
        })
        .then(office => {
          log(office);
          callback();
        })
        .catch(err => callback(err))

  ],
  (err) => {
    if (err) throw err;
    mongoose.disconnect();
  }
);

And the output it produces:

Mongoose: offices.remove({}, {})
Mongoose: offices.insert({ _id: 1, name: 'My Office', branches: [ { address: 'Some street, that avenue', isPrincipal: true, _id: ObjectId("5961e5211a73e8331b44d74b") }, { address: 'Another address', isPrincipal: false, _id: ObjectId("5961e5211a73e8331b44d74a") }, { address: 'Third address', isPrincipal: false, _id: ObjectId("5961e5211a73e8331b44d749") } ], __v: 0 })
Mongoose: offices.findAndModify({ _id: 1 }, [], { '$pull': { branches: { _id: ObjectId("5961e5211a73e8331b44d74b") } } }, { new: true, passRawResult: true, upsert: false, remove: false, fields: {} })
{
  "_id": 1,
  "name": "My Office",
  "__v": 0,
  "branches": [
    {
      "address": "Another address",
      "isPrincipal": false,
      "_id": "5961e5211a73e8331b44d74a"
    },
    {
      "address": "Third address",
      "isPrincipal": false,
      "_id": "5961e5211a73e8331b44d749"
    }
  ]
}
{
  "lastErrorObject": {
    "updatedExisting": true,
    "n": 1
  },
  "value": {
    "_id": 1,
    "name": "My Office",
    "branches": [
      {
        "address": "Another address",
        "isPrincipal": false,
        "_id": "5961e5211a73e8331b44d74a"
      },
      {
        "address": "Third address",
        "isPrincipal": false,
        "_id": "5961e5211a73e8331b44d749"
      }
    ],
    "__v": 0
  },
  "ok": 1,
  "_kareemIgnore": true
}
Mongoose: offices.findAndModify({ _id: 1 }, [], { '$pull': { branches: { _id: ObjectId("5961e5211a73e8331b44d74a") } } }, { new: true, upsert: false, remove: false, fields: {} })
{
  "_id": 1,
  "name": "My Office",
  "__v": 0,
  "branches": [
    {
      "address": "Third address",
      "isPrincipal": false,
      "_id": "5961e5211a73e8331b44d749"
    }
  ]
}
Present false
Mongoose: offices.findOne({}, { fields: {} })
Mongoose: offices.findAndModify({ _id: 1 }, [], { '$pull': { branches: { _id: ObjectId("5961a56d3ffd3d5e19c61610") } } }, { new: true, passRawResult: true, upsert: false, remove: false, fields: {} })
{
  "_id": 1,
  "name": "My Office",
  "__v": 0,
  "branches": [
    {
      "address": "Third address",
      "isPrincipal": false,
      "_id": "5961e5211a73e8331b44d749"
    }
  ]
}
{
  "lastErrorObject": {
    "updatedExisting": true,
    "n": 1
  },
  "value": {
    "_id": 1,
    "name": "My Office",
    "branches": [
      {
        "address": "Third address",
        "isPrincipal": false,
        "_id": "5961e5211a73e8331b44d749"
      }
    ],
    "__v": 0
  },
  "ok": 1,
  "_kareemIgnore": true
}
Mongoose: offices.findAndModify({ _id: 1 }, [], { '$pull': { branches: { _id: ObjectId("5961a56d3ffd3d5e19c61610") } } }, { new: true, upsert: false, remove: false, fields: {} })
{ _id: 1,
  name: 'My Office',
  __v: 0,
  branches:
   [ { address: 'Third address',
       isPrincipal: false,
       _id: 5961e5211a73e8331b44d749 } ] }
Present true
Mongoose: offices.update({}, { '$pull': { branches: { _id: ObjectId("5961a56d3ffd3d5e19c61610") } } }, {})
{
  "n": 1,
  "nModified": 0,
  "opTime": {
    "ts": "6440680872013201413",
    "t": 4
  },
  "electionId": "7fffffff0000000000000004",
  "ok": 1
}
Mongoose: offices.findOne({}, { fields: {} })
Mongoose: offices.findAndModify({ _id: 1 }, [], { '$pull': { branches: { _id: ObjectId("5961a56d3ffd3d5e19c61610") } } }, { new: true, passRawResult: true, upsert: false, remove: false, fields: {} })
{
  "lastErrorObject": {
    "updatedExisting": true,
    "n": 1
  },
  "value": {
    "_id": 1,
    "name": "My Office",
    "branches": [
      {
        "address": "Third address",
        "isPrincipal": false,
        "_id": "5961e5211a73e8331b44d749"
      }
    ],
    "__v": 0
  },
  "ok": 1,
  "_kareemIgnore": true
}


来源: stackexchange

问:
Why notification doesn't work?
I want to create a notification that works every 5 minute,for example. For this, I use BroadCastReceiver. Here is my code:

```<code>   public void notifyMe()
   Calendar calendar = Calendar.getInstance() ;

    calendar.set(Calendar.HOUR,0);

    calendar.set(Calendar.MINUTE,5);

    calendar.set(Calendar.SECOND,0);

    Log.d("tagger",calendar.getTime().toString());

    Intent intent = new Intent(this,MyBroadcastReceiver.class);

    PendingIntent sender = PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_CANCEL_CURRENT);

    AlarmManager am = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);

    am.setInexactRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),5*60*1000,sender);
   }
</code>```

Also for Receiver:

```<code>public class MyBroadcastReceiver extends BroadcastReceiver {

private static final int NOTIFY_ID = 101;

@Override
public void onReceive(Context context, Intent intent) {

    Log.d("BroadcastReceiver", "debut receive");

    Intent resultIntent  =  new Intent(context,DetailActivity.class) ;

    PendingIntent resultPendingIntent = PendingIntent.getActivity(context,
            0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Notification.Builder mBuilder = new Notification.Builder(context)
            .setContentTitle("title")
            .setContentText("some text");

    mBuilder.setAutoCancel(true);

    mBuilder.setContentIntent(resultPendingIntent);

    int id = 001 ;

    NotificationManager mNotifyManager = (NotificationManager)context.getSystemService(Application.NOTIFICATION_SERVICE);

    mNotifyManager.notify(id,mBuilder.build());
}
}
</code>```

Manifest:

```<code>   <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:name=".PrefsApplication"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".DetailActivity" />
    <activity android:name=".ActionsActivity"

        ></activity>

    <receiver android:name=".MyBroadcastReceiver">

    </receiver>
</application>
</code>```

What it doesn't work? I didn't forget to add receiver to the manifest. I need to use Service instead of Receiver?

答:
Update notifyMe() method as below to set repeating alarm:

```<code>public void notifyMe()

    // Current time
    Calendar calendar = Calendar.getInstance() ;
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.SECOND, 0);

    Log.d("tagger", calendar.getTime().toString());

    Intent intent = new Intent(this, MyBroadcastReceiver.class);
    PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    // Set alarm
    AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    am.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 5*60*1000, sender);

    // Or you can also use
    //am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 5*60*1000, sender);
}
</code>```

Update MyBroadcastReceiver as below:

```<code>public class MyBroadcastReceiver extends BroadcastReceiver {

    private static final int NOTIFY_ID = 101;

    @Override
    public void onReceive(Context context, Intent intent) {

        Log.d("BroadcastReceiver", "debut receive");

        // Intent to start activity
        Intent resultIntent  =  new Intent(context, DetailActivity.class) ;
        PendingIntent resultPendingIntent = PendingIntent.getActivity(context,
            0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Notification mNotification = new Notification.Builder(context)
            .setContentTitle("Title")
            .setContentText("Some text")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setAutoCancel(true)
            .setContentIntent(resultPendingIntent).build();

        NotificationManager mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotifyManager.notify(NOTIFY_ID, mNotification);
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Why notification doesn't work?

Body:
I want to create a notification that works every 5 minute,for example. For this, I use BroadCastReceiver. Here is my code:

   public void notifyMe()
   Calendar calendar = Calendar.getInstance() ;

    calendar.set(Calendar.HOUR,0);

    calendar.set(Calendar.MINUTE,5);

    calendar.set(Calendar.SECOND,0);

    Log.d("tagger",calendar.getTime().toString());

    Intent intent = new Intent(this,MyBroadcastReceiver.class);

    PendingIntent sender = PendingIntent.getBroadcast(this,0,intent,PendingIntent.FLAG_CANCEL_CURRENT);

    AlarmManager am = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);

    am.setInexactRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),5*60*1000,sender);
   }

Also for Receiver:

public class MyBroadcastReceiver extends BroadcastReceiver {

private static final int NOTIFY_ID = 101;

@Override
public void onReceive(Context context, Intent intent) {

    Log.d("BroadcastReceiver", "debut receive");

    Intent resultIntent  =  new Intent(context,DetailActivity.class) ;

    PendingIntent resultPendingIntent = PendingIntent.getActivity(context,
            0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Notification.Builder mBuilder = new Notification.Builder(context)
            .setContentTitle("title")
            .setContentText("some text");

    mBuilder.setAutoCancel(true);

    mBuilder.setContentIntent(resultPendingIntent);

    int id = 001 ;

    NotificationManager mNotifyManager = (NotificationManager)context.getSystemService(Application.NOTIFICATION_SERVICE);

    mNotifyManager.notify(id,mBuilder.build());
}
}

Manifest:

   <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:name=".PrefsApplication"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".DetailActivity" />
    <activity android:name=".ActionsActivity"

        ></activity>

    <receiver android:name=".MyBroadcastReceiver">

    </receiver>
</application>

What it doesn't work? I didn't forget to add receiver to the manifest. I need to use Service instead of Receiver?

Body:
Update notifyMe() method as below to set repeating alarm:

public void notifyMe()

    // Current time
    Calendar calendar = Calendar.getInstance() ;
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.SECOND, 0);

    Log.d("tagger", calendar.getTime().toString());

    Intent intent = new Intent(this, MyBroadcastReceiver.class);
    PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    // Set alarm
    AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    am.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 5*60*1000, sender);

    // Or you can also use
    //am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 5*60*1000, sender);
}

Update MyBroadcastReceiver as below:

public class MyBroadcastReceiver extends BroadcastReceiver {

    private static final int NOTIFY_ID = 101;

    @Override
    public void onReceive(Context context, Intent intent) {

        Log.d("BroadcastReceiver", "debut receive");

        // Intent to start activity
        Intent resultIntent  =  new Intent(context, DetailActivity.class) ;
        PendingIntent resultPendingIntent = PendingIntent.getActivity(context,
            0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        Notification mNotification = new Notification.Builder(context)
            .setContentTitle("Title")
            .setContentText("Some text")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setAutoCancel(true)
            .setContentIntent(resultPendingIntent).build();

        NotificationManager mNotifyManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotifyManager.notify(NOTIFY_ID, mNotification);
    }
}


问:
Bootstrap pagination in .ejs template
I have a node project with some simple admin interfaces.  One page shows a list of users, it's paginated with a bootstrap paginator and when there's several thousand users the pagination looks like

Here's the code:

```<code><nav>
<div class="text-center">
    <ul class="pagination pagination-sm">
        <li
                <% if(page <= 0) { %>
                class="disabled"
                <% } %>
        ><a href="?page=<%= page <= 0 ? 0 : page - 1 %>">«</a></li>
        <% for(var i = 0; i < pages; i++) { %>
        <li
                <% if(page == i) { %>
                class="active"
                <% } %>
        ><a href="?page=<%= i %>"><%= i + 1 %></a></li>
        <% } %>
        <li <% if(page > pages - 1) { %>class="disabled"
                <% } %>
        ><a href="?page=<%= page > pages - 1 ? parseInt(pages) : 1 + parseInt(page) %>">»</a></li>
    </ul>
</div>
</code>```

I'm not an html person.  Here are my questions:

1: How does the href ?page=n work?  What's the ? do?  I assume there's logic somewhere that directs the browser to show the new page but I'm not sure where.

2: Is there a good way to add an ellipsis or some other truncated pagination?  I suppose I can show ten pages and bookend it with the single page advancers and bookend that with something to show the next/previous ten pages.  I'm not entirely sure how to make that happen.  Understanding how the href works would help.

Thanks!

答:
Paginate library takes most of the heavy burden of actually implementing pagination off you. You simply need to calculate three variables: Number of totals items, items per page, and current page number.

```<code>var totalItems, itemsPerPage, pageNum;
// calculate the data for above variables and pass them in below method

var pagination = paginate.page(totalItems, itemsPerPage, pageNum);
var paginationHtml = pagination.render({ baseUrl: '/' }); //the link to pass to href, page number will be added as query paramtere to it e.g. /?page=6
</code>```

paginationHtml now contains the bootstrap's pagination HTML. Simply pass it as parameter to ejs template and render it:

```<code><%- paginationHtml %>
</code>```

This one liner will give you the following:

You can change the styling by modifying bootstrap classes for pagination (as done in the example screenshots).

Title: Bootstrap pagination in .ejs template

Body:
I have a node project with some simple admin interfaces.  One page shows a list of users, it's paginated with a bootstrap paginator and when there's several thousand users the pagination looks like

Here's the code:

        <li
                <% if(page <= 0) { %>
                class="disabled"
                <% } %>
        ><a href="?page=<%= page <= 0 ? 0 : page - 1 %>">«

        <% for(var i = 0; i < pages; i++) { %>
        <li
                <% if(page == i) { %>
                class="active"
                <% } %>
        ><a href="?page=<%= i %>"><%= i + 1 %>

        <% } %>
        <li <% if(page > pages - 1) { %>class="disabled"
                <% } %>
        ><a href="?page=<%= page > pages - 1 ? parseInt(pages) : 1 + parseInt(page) %>">»

I'm not an html person.  Here are my questions:

1: How does the href ?page=n work?  What's the ? do?  I assume there's logic somewhere that directs the browser to show the new page but I'm not sure where.

2: Is there a good way to add an ellipsis or some other truncated pagination?  I suppose I can show ten pages and bookend it with the single page advancers and bookend that with something to show the next/previous ten pages.  I'm not entirely sure how to make that happen.  Understanding how the href works would help.

Thanks!

Body:
Paginate library takes most of the heavy burden of actually implementing pagination off you. You simply need to calculate three variables: Number of totals items, items per page, and current page number.

var totalItems, itemsPerPage, pageNum;
// calculate the data for above variables and pass them in below method

var pagination = paginate.page(totalItems, itemsPerPage, pageNum);
var paginationHtml = pagination.render({ baseUrl: '/' }); //the link to pass to href, page number will be added as query paramtere to it e.g. /?page=6

paginationHtml now contains the bootstrap's pagination HTML. Simply pass it as parameter to ejs template and render it:

<%- paginationHtml %>

This one liner will give you the following:

You can change the styling by modifying bootstrap classes for pagination (as done in the example screenshots).


问:
Exiting an infinite process in python subprocess
i have the following code

```<code>c = open("text.txt", 'a')

output = subprocess.Popen('ping -t 127.0.0.1', stdout=subprocess.PIPE).communicate()[0]

c.write(str(output))
</code>```

But as the ping is infinite , the code stucks at line two till i close the cmd

how can i close the infinite subprocess

i use python 2

答:
```<code>process = subprocess.Popen('ping -t 127.0.0.1', stdout=subprocess.PIPE)
time.sleep(10)
process.kill()
output=process.stdout.read()
</code>```

with this code , subprocess runs and data will be given stdout,

we don't need to use communicate

when ever you want to stop the process,

use process.kill()

and get data using stdout.read()

Body:
i have the following code

c = open("text.txt", 'a')

output = subprocess.Popen('ping -t 127.0.0.1', stdout=subprocess.PIPE).communicate()[0]

c.write(str(output))

But as the ping is infinite , the code stucks at line two till i close the cmd

how can i close the infinite subprocess

i use python 2

Body:
process = subprocess.Popen('ping -t 127.0.0.1', stdout=subprocess.PIPE)
time.sleep(10)
process.kill()
output=process.stdout.read()

with this code , subprocess runs and data will be given stdout,

we don't need to use communicate

when ever you want to stop the process,

use process.kill()

and get data using stdout.read()


问:
Single.just exception
I'm stuck to understand why RxJava does not capture my exception and it just crashes. The exception occurs while getting the object to emit.

Here is how my code looks like:

```<code>TestService testService = new TestService();
Single.just(testService.testGetUser())
      .subscribeOn(Schedulers.newThread())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribeWith(new DisposableSingleObserver<User>() {
        @Override
        public void onSuccess(@NonNull User user) {
          Log.d(TAG, "onSuccess(): Launching Home Activity");
          Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
          startActivity(intent);
        }

        @Override
        public void onError(@NonNull Throwable e) {
          Log.d(TAG, "onError()");
        }
      });
</code>```

My TestService class looks like:

```<code>public class TestService {
public User logInUser(LogInData logInData) throws RuntimeException {
        Log.d(TAG, "logInUser(): Logging user in");
        User user = this.guideMeAroundData.logInUser(logInData);
        return user;
      }
}
</code>```

In my logInUser() method I'm throwing an exception if the user is not valid. This causes my whole Android app to crash.

It looks like this is not the correct way to do it. Could anybody please tell how should I handle an scenario where an exception is thrown while getting the object(s) to be emitted?

答:
This is a very common (and baffling) misunderstanding of Java syntax and operations. The code

```<code>Single.just(testService.testGetUser())
</code>```

is equivalent to

```<code>User tmp1 = testService.testGetUser();
Single.just(tmp1)
</code>```

where testGetUser executes before RxJava even gets involved thus any exception it throws happens before that.

You are probably looking for the

```<code>Single.fromCallable(() -> testService.testGetUser())
</code>```

or simply define the Retrofit API as Single<User> logInUser(LogInData data).

Title: Single.just exception

Body:
I'm stuck to understand why RxJava does not capture my exception and it just crashes. The exception occurs while getting the object to emit.

Here is how my code looks like:

TestService testService = new TestService();
Single.just(testService.testGetUser())
      .subscribeOn(Schedulers.newThread())
      .observeOn(AndroidSchedulers.mainThread())
      .subscribeWith(new DisposableSingleObserver<User>() {
        @Override
        public void onSuccess(@NonNull User user) {
          Log.d(TAG, "onSuccess(): Launching Home Activity");
          Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
          startActivity(intent);
        }

        @Override
        public void onError(@NonNull Throwable e) {
          Log.d(TAG, "onError()");
        }
      });

My TestService class looks like:

public class TestService {
public User logInUser(LogInData logInData) throws RuntimeException {
        Log.d(TAG, "logInUser(): Logging user in");
        User user = this.guideMeAroundData.logInUser(logInData);
        return user;
      }
}

In my logInUser() method I'm throwing an exception if the user is not valid. This causes my whole Android app to crash.

It looks like this is not the correct way to do it. Could anybody please tell how should I handle an scenario where an exception is thrown while getting the object(s) to be emitted?

Body:
This is a very common (and baffling) misunderstanding of Java syntax and operations. The code

Single.just(testService.testGetUser())

is equivalent to

User tmp1 = testService.testGetUser();
Single.just(tmp1)

where testGetUser executes before RxJava even gets involved thus any exception it throws happens before that.

You are probably looking for the

Single.fromCallable(() -> testService.testGetUser())

or simply define the Retrofit API as Single<User> logInUser(LogInData data).


问:
Many call of function in Recursion
I was implementing maxPathSum function using recursion and I didn't know what happens when using two calls in the function .i know then that is called
binary recursion and know how to think about it from this reply on that question
Understanding double recursion

but when I write the code it didn't give me the right answer
[Note that]  the only direction needed is right and down

```<code>#include <iostream>
#include<algorithm>
using namespace std;
const int MAX=3;
int grid[MAX][MAX]={
                    {5,1,2},
                    {6,4,8},
                    {1,8,9}
};

bool valid(int r, int c);//check not get out grid
int maxPathSum(int r,int c);

int main()
{
    int sum=0;
    for(int i=0;i<MAX;i++)
    sum += maxPathSum(i,i);
    cout<<"the sum of the  longest path is: "<<sum;
}

int maxPathSum(int r,int c){
    if(!valid(r,c))
        return 1;

     //Reach the last element in the last right down
    if(r == MAX-1 && c == MAX-1)
        return grid[r][c];

    int path1=maxPathSum(r,c+1);//Right
    int path2=maxPathSum(r+1,c);//down

    return grid[r][c]+max(path1,path2);
}

 bool valid(int r, int c){
    if(r > MAX-1)
        return false;
    if(c > MAX-1)
        return false;

    return true;
}
</code>```

when I call the function without loop in main sometimes it give me the right answer

like that with low matrix length

```<code>const int MAX=2;
int grid[MAX][MAX]={
                    {5,2},
                    {1,8}
};
maxPathSum(0,0);
</code>```

答:
You are making a double sum.

```<code>return grid[r][c]+max(path1,path2)
</code>```

This piece of code already sums elements on the path.

```<code>for(int i=0;i<MAX;i++)
sum += maxPathSum(i,i);
</code>```

maxPathSum will return the sum of all elements on the path between (i,i) and (2,2). Then sum will contain the sum of all of those sums on on the diagonal elements. I don't think you want that.

Calling maxPathSum(0,0) in main should give the answer.

Now lets say you call maxPathSum(1,2). This function will then call maxPathSum(2,2) and maxPathSum(1,3). The first will return e22 and the latter 1. If e22=0 the result will be incorrect.

I am answering the question for the problem of finding the maximum path between (0,0) and (max-1,max-1). If the problem is not defined like that, you should specify it clearly.

Title: Many call of function in Recursion

Body:
I was implementing maxPathSum function using recursion and I didn't know what happens when using two calls in the function .i know then that is called
binary recursion and know how to think about it from this reply on that question
Understanding double recursion

but when I write the code it didn't give me the right answer
[Note that]  the only direction needed is right and down

#include <iostream>
#include<algorithm>
using namespace std;
const int MAX=3;
int grid[MAX][MAX]={
                    {5,1,2},
                    {6,4,8},
                    {1,8,9}
};

bool valid(int r, int c);//check not get out grid
int maxPathSum(int r,int c);

int main()
{
    int sum=0;
    for(int i=0;i<MAX;i++)
    sum += maxPathSum(i,i);
    cout<<"the sum of the  longest path is: "<<sum;
}

int maxPathSum(int r,int c){
    if(!valid(r,c))
        return 1;

     //Reach the last element in the last right down
    if(r == MAX-1 && c == MAX-1)
        return grid[r][c];

    int path1=maxPathSum(r,c+1);//Right
    int path2=maxPathSum(r+1,c);//down

    return grid[r][c]+max(path1,path2);
}

 bool valid(int r, int c){
    if(r > MAX-1)
        return false;
    if(c > MAX-1)
        return false;

    return true;
}

when I call the function without loop in main sometimes it give me the right answer

like that with low matrix length

const int MAX=2;
int grid[MAX][MAX]={
                    {5,2},
                    {1,8}
};
maxPathSum(0,0);

Body:
You are making a double sum.

return grid[r][c]+max(path1,path2)

This piece of code already sums elements on the path.

for(int i=0;i<MAX;i++)
sum += maxPathSum(i,i);

maxPathSum will return the sum of all elements on the path between (i,i) and (2,2). Then sum will contain the sum of all of those sums on on the diagonal elements. I don't think you want that.

Calling maxPathSum(0,0) in main should give the answer.

Now lets say you call maxPathSum(1,2). This function will then call maxPathSum(2,2) and maxPathSum(1,3). The first will return e22 and the latter 1. If e22=0 the result will be incorrect.

I am answering the question for the problem of finding the maximum path between (0,0) and (max-1,max-1). If the problem is not defined like that, you should specify it clearly.


问:
float property ignores margin
I am learning semantic-ui framework and currently I'm using segments. My code looks like this:

```<code><!DOCTYPE html>
<html>
<head>
<script
    src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

<link rel="stylesheet"
    href="https://cdn.jsdelivr.net/semantic-ui/2.2.10/semantic.min.css">
<script
    src="https://cdn.jsdelivr.net/semantic-ui/2.2.10/semantic.min.js"></script>
    <link rel="icon" href="favicon.ico" type="image/x-icon" />
<title>Assignments</title>
<style>
    .raised.segment{
        margin: 1.5%;
        width: 30%;
        display: inline-block;
        float: left;
    }
    h3 {
        display: inline-block;
        text-align: center;
    }
</style>
</head>
<body>

 <div class="ui raised segment">
<h2 class="ui header">
  Section 6
</h2>
 <div class="ui middle aligned selection list">
  <div class="item">
    <img class="ui avatar image" src="/images/avatar/small/helen.jpg">
    <div class="content">
      <h3 class="ui header"> Vasil Pkhakadze </h3>
    </div>
  </div>
  <div class="item">
    <img class="ui avatar image" src="/images/avatar/small/christian.jpg">
    <div class="content">
      <div class="header">George Cercvadze</div>
    </div>
  </div>
   <div class="item">
    <img class="ui avatar image" src="/images/avatar/small/christian.jpg">
    <div class="content">
      <div class="header">George Cercvadze</div>
    </div>
  </div>
   <div class="item">
    <img class="ui avatar image" src="/images/avatar/small/christian.jpg">
    <div class="content">
      <div class="header">George Cercvadze</div>
    </div>
  </div>
</div>
 </div>

  <div class="ui raised segment">
<h2 class="ui header">
  Section 6
</h2>
 <div class="ui middle aligned selection list">
  <div class="item">
    <img class="ui avatar image" src="/images/avatar/small/helen.jpg">
    <div class="content">
      <h3 class="ui header"> Vasil Pkhakadze </h3>
    </div>
  </div>
  <div class="item">
    <img class="ui avatar image" src="/images/avatar/small/christian.jpg">
    <div class="content">
      <div class="header">George Cercvadze</div>
    </div>
  </div>
   <div class="item">
    <img class="ui avatar image" src="/images/avatar/small/christian.jpg">
    <div class="content">
      <div class="header">George Cercvadze</div>
    </div>
  </div>
   <div class="item">
    <img class="ui avatar image" src="/images/avatar/small/christian.jpg">
    <div class="content">
      <div class="header">George Cercvadze</div>
    </div>
  </div>
</div>
 </div>

  <div class="ui raised segment">
<h2 class="ui header">
  Section 6
</h2>
 <div class="ui middle aligned selection list">
  <div class="item">
    <img class="ui avatar image" src="/images/avatar/small/helen.jpg">
    <div class="content">
      <h3 class="ui header"> Vasil Pkhakadze </h3>
    </div>
  </div>
  <div class="item">
    <img class="ui avatar image" src="/images/avatar/small/christian.jpg">
    <div class="content">
      <div class="header">George Cercvadze</div>
    </div>
  </div>
   <div class="item">
    <img class="ui avatar image" src="/images/avatar/small/christian.jpg">
    <div class="content">
      <div class="header">George Cercvadze</div>
    </div>
  </div>
   <div class="item">
    <img class="ui avatar image" src="/images/avatar/small/christian.jpg">
    <div class="content">
      <div class="header">George Cercvadze</div>
    </div>
  </div>
</div>
 </div>

  <div class="ui raised segment">
<h2 class="ui header">
  Section 6
</h2>
 <div class="ui middle aligned selection list">
  <div class="item">
    <img class="ui avatar image" src="/images/avatar/small/helen.jpg">
    <div class="content">
      <h3 class="ui header"> Vasil Pkhakadze </h3>
    </div>
  </div>
  <div class="item">
    <img class="ui avatar image" src="/images/avatar/small/christian.jpg">
    <div class="content">
      <div class="header">George Cercvadze</div>
    </div>
  </div>
   <div class="item">
    <img class="ui avatar image" src="/images/avatar/small/christian.jpg">
    <div class="content">
      <div class="header">George Cercvadze</div>
    </div>
  </div>
   <div class="item">
    <img class="ui avatar image" src="/images/avatar/small/christian.jpg">
    <div class="content">
      <div class="header">George Cercvadze</div>
    </div>
  </div>
</div>
 </div>
</body>
</html>
</code>```

Everything is fine except the first segment. float:left property ignores its margin and so the first segment is touching the borders. Other segments are fine. Any suggestions ?

答:
Class with .ui.segment:first-child{margin-top: 0;} in semantic.min.css

have margin-top:0; thus making it to touch borders, override it with custom css

add important tag to this rule

CSS

```<code>.raised.segment{
        margin: 1.5% !important;
        width: 30%;
        display: inline-block;
        float: left;
    }
</code>```

everything should work fine

Link For reference

hope this helps..

Title: float property ignores margin

Body:
I am learning semantic-ui framework and currently I'm using segments. My code looks like this:

<!DOCTYPE html>

<link rel="stylesheet"
    href="https://cdn.jsdelivr.net/semantic-ui/2.2.10/semantic.min.css">

    <link rel="icon" href="favicon.ico" type="image/x-icon" />
<title>Assignments</title>

  Section 6

 Vasil Pkhakadze

George Cercvadze

George Cercvadze

George Cercvadze

  Section 6

 Vasil Pkhakadze

George Cercvadze

George Cercvadze

George Cercvadze

  Section 6

 Vasil Pkhakadze

George Cercvadze

George Cercvadze

George Cercvadze

  Section 6

 Vasil Pkhakadze

George Cercvadze

George Cercvadze

George Cercvadze

Everything is fine except the first segment. float:left property ignores its margin and so the first segment is touching the borders. Other segments are fine. Any suggestions ?

Body:
Class with .ui.segment:first-child{margin-top: 0;} in semantic.min.css

have margin-top:0; thus making it to touch borders, override it with custom css

add important tag to this rule

CSS

.raised.segment{
        margin: 1.5% !important;
        width: 30%;
        display: inline-block;
        float: left;
    }

everything should work fine

Link For reference

hope this helps..


问:
TypeError: Python thinks that I passed a function 2 arguments but I only passed it 1
I work on something in Seattle Repy which is a restricted subset of Python. Anyway, I wanted to implement my own Queue that derives from a list:

```<code>class Queue(list):
    job_count = 0

    def __init__(self):
        list.__init__(self)

    def appendleft(item):
        item.creation_time = getruntime()
        item.current_count = self.job_count
        self.insert(0, item)

    def pop():
        item = self.pop()
        item.pop_time = getruntime()
        return item
</code>```

Now I call this in my main server, where I use my own Job class to pass Jobs to the Queue:

```<code>mycontext['queue'] = Queue()
# ...
job = Job(str(ip), message)
mycontext['queue'].appendleft(job)
</code>```

The last line raises the following exception:

Exception (with type 'exceptions.TypeError'): appendleft() takes exactly 1 argument (2 given)

I'm relatively new to Python, so could anyone explain to me why it would think that I gave appendleft() two arguments when there obviously was only one?

答:
Python automatically passes SELF (ie the current object) as the first argument, so you'd need to change the function definition for appendleft to:

```<code>def appendleft(self, item):
</code>```

This is also true for other function definitions within a class.  They all require SELF as the first parameter in the function definition, so:

```<code>def pop():
</code>```

would need to be:

```<code>def pop(self):
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I work on something in Seattle Repy which is a restricted subset of Python. Anyway, I wanted to implement my own Queue that derives from a list:

class Queue(list):
    job_count = 0

    def __init__(self):
        list.__init__(self)

    def appendleft(item):
        item.creation_time = getruntime()
        item.current_count = self.job_count
        self.insert(0, item)

    def pop():
        item = self.pop()
        item.pop_time = getruntime()
        return item

Now I call this in my main server, where I use my own Job class to pass Jobs to the Queue:

mycontext['queue'] = Queue()
# ...
job = Job(str(ip), message)
mycontext['queue'].appendleft(job)

The last line raises the following exception:

Exception (with type 'exceptions.TypeError'): appendleft() takes exactly 1 argument (2 given)

I'm relatively new to Python, so could anyone explain to me why it would think that I gave appendleft() two arguments when there obviously was only one?

Body:
Python automatically passes SELF (ie the current object) as the first argument, so you'd need to change the function definition for appendleft to:

def appendleft(self, item):

This is also true for other function definitions within a class.  They all require SELF as the first parameter in the function definition, so:

def pop():

would need to be:

def pop(self):


问:
Setting value of class variable from String Request Volley in Android
I have a function named isUserExist.This func checks whether user exist on database with this email address.

In stringrequest i set the isUserExist variable "true".End of the func,func returns isUserExist.

Problem is it always returns false even if i set it true in the string request.it sets it true in the if statement.

In the class declaration of it like:

```<code>boolean isUserExist;
</code>```

And the function is:

```<code>private boolean isUserExist()
{

    StringRequest strReq = new StringRequest(Request.Method.POST,
            AppConfig.URL_USER_EXIST, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {

            try {
                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");
                if (error) {
                    // setting isUserExist = true
                    isUserExist = true;
                    //Log.w("debug1",String.valueOf(isUserExist);)
                    //returns true;

                } else {

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {

        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting params to register url
            Map<String, String> params = new HashMap<String, String>();
            params.put("email", mail);

            return params;
        }

    };
    AppController.getInstance().addToRequestQueue(strReq);
    //Log.w("debug2",String.valueOf(isuserExist));
    //returns false
    return isUserExist;
}
</code>```

What did i try so far :

I have searched and find these ideas.
1)to make it static
2)Declaring boolean result[] = new boolean[1]; and end of the function return result[0] which i have assaign it true in String Request.
3)Declaring isUserExist as Local variable.boolean isUserExist = false; in the beggining of the func.
4)In the firs decleration assaign it like :boolean isUserExist = false instead of boolean isUserExist;

But none of them works.

答: Problem was working with threads.Volley thread sets the isUserExist true after function returns.</p>

Body:
I have a function named isUserExist.This func checks whether user exist on database with this email address.

In stringrequest i set the isUserExist variable "true".End of the func,func returns isUserExist.

Problem is it always returns false even if i set it true in the string request.it sets it true in the if statement.

In the class declaration of it like:

boolean isUserExist;

And the function is:

private boolean isUserExist()
{

    StringRequest strReq = new StringRequest(Request.Method.POST,
            AppConfig.URL_USER_EXIST, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {

            try {
                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");
                if (error) {
                    // setting isUserExist = true
                    isUserExist = true;
                    //Log.w("debug1",String.valueOf(isUserExist);)
                    //returns true;

                } else {

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {

        }
    }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting params to register url
            Map<String, String> params = new HashMap<String, String>();
            params.put("email", mail);

            return params;
        }

    };
    AppController.getInstance().addToRequestQueue(strReq);
    //Log.w("debug2",String.valueOf(isuserExist));
    //returns false
    return isUserExist;
}

What did i try so far :

I have searched and find these ideas.
1)to make it static
2)Declaring boolean result[] = new boolean[1]; and end of the function return result[0] which i have assaign it true in String Request.
3)Declaring isUserExist as Local variable.boolean isUserExist = false; in the beggining of the func.
4)In the firs decleration assaign it like :boolean isUserExist = false instead of boolean isUserExist;

But none of them works.


问:
QT QPushButton Press Event
i want to do a very time-consuming operation when press a QT button but failed, can anybody help me explain this? thanks!
the code is:

```<code>bool eventFilter(QObject *target, QEvent *event)
{
    if (target == ui.zoominBtn){
         if (event->type() == QEvent::MouseButtonPress){
             phcs[curPhcId].zoom(0.1);
             renderRaytracingImage();
         }
    }
    return QMainWindow::eventFilter(target, event);
}
</code>```

now i move the time consuming-part to a QThread:

```<code>if (target == ui.zoominBtn){
    if (event->type() == QEvent::MouseButtonPress){
        //phcs[curPhcId].zoom(0.1);
        TracerayThread *traceThread = new TracerayThread(&scene,&(phcs[curPhcId]),this);
        connect(traceThread, SIGNAL(resultReady()), this, SLOT(render()));
        connect(traceThread, SIGNAL(finished()), traceThread, SLOT(deleteLater()));
        traceThread->start();
    }
}
</code>```

i need to pass two pointer to the new thread,can i do this?

答:
You can use QPushButton click signal.

```<code>connect(YourButtonName,  &QPushButton::clicked, this, &MainWindow::YourSlotName);
</code>```

No need to use eventFilter. if you want to use it don't forget installEventFilter

Title: QT QPushButton Press Event

Body:
i want to do a very time-consuming operation when press a QT button but failed, can anybody help me explain this? thanks!
the code is:

bool eventFilter(QObject *target, QEvent *event)
{
    if (target == ui.zoominBtn){
         if (event->type() == QEvent::MouseButtonPress){
             phcs[curPhcId].zoom(0.1);
             renderRaytracingImage();
         }
    }
    return QMainWindow::eventFilter(target, event);
}

now i move the time consuming-part to a QThread:

if (target == ui.zoominBtn){
    if (event->type() == QEvent::MouseButtonPress){
        //phcs[curPhcId].zoom(0.1);
        TracerayThread *traceThread = new TracerayThread(&scene,&(phcs[curPhcId]),this);
        connect(traceThread, SIGNAL(resultReady()), this, SLOT(render()));
        connect(traceThread, SIGNAL(finished()), traceThread, SLOT(deleteLater()));
        traceThread->start();
    }
}

i need to pass two pointer to the new thread,can i do this?

Body:
You can use QPushButton click signal.

connect(YourButtonName,  &QPushButton::clicked, this, &MainWindow::YourSlotName);

No need to use eventFilter. if you want to use it don't forget installEventFilter


问:
Gitlab run docker inside docker
I'm using gitlab 9.3.3-ce.0 and gitlab runner with docker executor. I want to build images inside this docker-executor. How to do it?

I'm trying to connect to outer docker using this section inside /etc/gitlab-runner/config.toml:

```<code>[runners.docker]
    tls_verify = false
    image = "java:8"
    privileged = true
    disable_cache = false
    volumes = ["/var/images", "/var/lib/docker:/var/lib/docker",
               "/var/run/docker.sock:/var/run/docker.sock",
               "/usr/bin/docker:/usr/bin/docker"]
    shm_size = 0
</code>```

But when I try to execute inside docker docker info I get:

```<code>/usr/bin/docker: No such file or directory
</code>```

But it should exist:

```<code>$ which docker
/usr/bin/docker
</code>```

答: Turns out that default installation of docker via apt-get is not visible inside docker itself, so separate standalone docker is installed and used.</p>

Title: Gitlab run docker inside docker

Body:
I'm using gitlab 9.3.3-ce.0 and gitlab runner with docker executor. I want to build images inside this docker-executor. How to do it?

I'm trying to connect to outer docker using this section inside /etc/gitlab-runner/config.toml:

[runners.docker]
    tls_verify = false
    image = "java:8"
    privileged = true
    disable_cache = false
    volumes = ["/var/images", "/var/lib/docker:/var/lib/docker",
               "/var/run/docker.sock:/var/run/docker.sock",
               "/usr/bin/docker:/usr/bin/docker"]
    shm_size = 0

But when I try to execute inside docker docker info I get:

/usr/bin/docker: No such file or directory

But it should exist:

$ which docker
/usr/bin/docker


问:
Log user input and time to text file using PHP
I've been trying to create a HTML form to collect user data and log it into a text file. What do I put inside "store.php" such that a log of the date/time and what was inside the text box is written to a text file inside a dir called "log"?

In addition, how do I use JS (or jQuery) to hide the entire form once the user has clicked done to prevent them from submitting the form again, but still allow them to see the rest of the page?

The existing HTML for the form is:

```<code>  <form method="post" action="store.php">
   <input placeholder="Name" id="Name" type="text"/><br>
   <input type="submit" value="Done"/>
  </form>
</code>```

答:
Depending on what happens in store.php you must use PHP's filesystem functions (like fread(), file_get_contents(), file_put_contents(), etc.), open/create a file, write your data into it, close and save it.

http://php.net/manual/en/ref.filesystem.php

For the JQuery part, look at form events. Simple example:

```<code>$('#myForm').on('submit', function() {
   $(this).hide();
}
</code>```

Or post more code and we can give you a better solution.

edit:
here is a function I pulled from some old project:

```<code>function write_log( $error,$logtype="error" ) {
// get date and time for the log entry
$t = time();
$date = date('d/n/Y H:i:s', $t);

// prepare log string
$log = "#{$date} : {$error}<br>\n";

// decide what type of log to write to
$type = $logtype;
switch($logtype) {
    case("error"):
        $type = "errors";
        break;
    case("user"):
        $type = "users";
        break;
    case("db"):
        $type = "db";
        break;
}
$log = trim( $log );
$filename = LOG_PATH."/{$type}_log.txt";
file_put_contents($filename, $log, FILE_APPEND | LOCK_EX );
}// end of function
</code>```

It's the same. First parameter takes log content, second optional parameter takes log type (or defaults to 'error')

Hope that helps.

Body:
I've been trying to create a HTML form to collect user data and log it into a text file. What do I put inside "store.php" such that a log of the date/time and what was inside the text box is written to a text file inside a dir called "log"?

In addition, how do I use JS (or jQuery) to hide the entire form once the user has clicked done to prevent them from submitting the form again, but still allow them to see the rest of the page?

The existing HTML for the form is:

  <form method="post" action="store.php">
   <input placeholder="Name" id="Name" type="text"/>

   <input type="submit" value="Done"/>
  </form>

Body:
Depending on what happens in store.php you must use PHP's filesystem functions (like fread(), file_get_contents(), file_put_contents(), etc.), open/create a file, write your data into it, close and save it.

http://php.net/manual/en/ref.filesystem.php

For the JQuery part, look at form events. Simple example:

$('#myForm').on('submit', function() {
   $(this).hide();
}

Or post more code and we can give you a better solution.

edit:
here is a function I pulled from some old project:

function write_log( $error,$logtype="error" ) {
// get date and time for the log entry
$t = time();
$date = date('d/n/Y H:i:s', $t);

// prepare log string
$log = "#{$date} : {$error}<br>\n";

// decide what type of log to write to
$type = $logtype;
switch($logtype) {
    case("error"):
        $type = "errors";
        break;
    case("user"):
        $type = "users";
        break;
    case("db"):
        $type = "db";
        break;
}
$log = trim( $log );
$filename = LOG_PATH."/{$type}_log.txt";
file_put_contents($filename, $log, FILE_APPEND | LOCK_EX );
}// end of function

It's the same. First parameter takes log content, second optional parameter takes log type (or defaults to 'error')

Hope that helps.


问:
Texture from Assets folder to Texture2D and the save?
I have a Texture in the Assets folder with (Texture Type = Advanced, Read/Write Enabled = true, Max Size = 512, Format = RGB 24 bit). Now I want to read this texture and then copy the pixels into another texture2d and save that.

```<code>private Texture2D sourceImg;

...

Texture2D tex = new Texture2D(512, 512, TextureFormat.RGB24, false);
tex.SetPixels(sourceImg.GetPixels(0,0,512,512));
tex.Apply();
byte[] png = tex.EncodeToPNG();
File.WriteAllBytes(Application.persistentDataPath + "/Screenshot.png", png);
</code>```

I don't know, why this simple code is not working?

When I add the new tex to a quad with:

```<code>quad.renderer.material.mainTexture = tex;
</code>```

It works.

答:
Thanks! Works for me. Suggest change this:
File.WriteAllBytes(Application.persistentDataPath + "/Screenshot.png", png);
by a custom output folder, like this:
File.WriteAllBytes("C:/OutputFolder" + "/Screenshot.png", png);</p>

Body:
I have a Texture in the Assets folder with (Texture Type = Advanced, Read/Write Enabled = true, Max Size = 512, Format = RGB 24 bit). Now I want to read this texture and then copy the pixels into another texture2d and save that.

private Texture2D sourceImg;

...

Texture2D tex = new Texture2D(512, 512, TextureFormat.RGB24, false);
tex.SetPixels(sourceImg.GetPixels(0,0,512,512));
tex.Apply();
byte[] png = tex.EncodeToPNG();
File.WriteAllBytes(Application.persistentDataPath + "/Screenshot.png", png);

I don't know, why this simple code is not working?

When I add the new tex to a quad with:

quad.renderer.material.mainTexture = tex;

It works.


问:
Can variables adjacent to a bit-field get corrupted?
I am facing a problem very similar to that described by the Linux Kernel community - Betrayed by a Bit-Field

The essence of the problem is that GCC issues 64-bit read accesses to even access 1-bit bitfields. This causes the unexpected side effect of reading in adjacent fields that can be modified elsewhere in the program. When the modified bitfield value is written back, the adjacent variable's old value is also written back, thereby losing any modification done to it by other threads.

My problem is slightly different. I have a class/struct like this-

```<code>class Group {

    uint8 adjVariable;
    volatile bool  flag1: 1;
    volatile bool  flag2: 1;
    // so on...
    volatile bool  flag10: 1;
};
</code>```

The way these variables are accessed is -

```<code>Group::fun() {
    Group_Scoped_lock();
    // adjVariable was 12 here.
    if ( adjVariable > 0 ) {
        adjVariable = 0; // <------- EXPLICIT ZERO ASSIGNMENT
    }
    // some code that doesn't affect adjVariable
    bool1 = false;
    bool2 = false;
    bool3 = false;
    assert( adjVariable == 0 ); // <---- This assert is tripping stating that adjVariable is 12!!
}
</code>```

Before we suspected "bugs" with GCC, I verified if adjVariable was being accessed without Group_lock() elsewhere. To the best of my ability, I couldnt see any place in code where this was happening.

Now, since compiler issues 64 bit reads for bitfields AND they are volatile, what if it issued a read to adjVariable as part of this read AND the explicit ZERO assignment of adjVariable was still in cache and hence we read the older value of 12 for adjVariable? And this newly read value overwrites the explicitly set value? And hence we are tripping the assert? If so, how do I validate this?

In the article, they are discussing losing out updates to adjacent variables done in other threads but in my problem, I'm suspecting we are losing on updates to adjVariable done in the same thread because of reads from memory. Is this possible?

We are using an ancient g++ compiler which is only C++98 compliant on an equally older Fedora release 12 virtual machine. Also, we ran into this issue ONLY once a code base which was running for 6 months

答:
If adjVariable is not accessed from any other concurrent thread, then it's pretty much guaranteed to be 0 at the point of the assert.

While all the bools are a single memory location and indeed can produce some weird behavior between themselves, adjVariable is a separate memory location and the compiler has to make sure that all the loads and stores to it appear to happen in well-defined order conforming to the source code.

If the compiler issues 64-bit writes for bit fields, then it has to protect adjacent memory locations by aligning bit fields to 8 bytes (e.g. there should be 7-byte padding between adjVariable and flag1). I don't see how 64-bit reads can mess with correctness here though.

While the notion of memory location only works for C++11 and later, the logic still applies to C++98: the only way for adjVariable not to be zero in the assert should be for another thread to write to adjVariable.

Body:
I am facing a problem very similar to that described by the Linux Kernel community - Betrayed by a Bit-Field

The essence of the problem is that GCC issues 64-bit read accesses to even access 1-bit bitfields. This causes the unexpected side effect of reading in adjacent fields that can be modified elsewhere in the program. When the modified bitfield value is written back, the adjacent variable's old value is also written back, thereby losing any modification done to it by other threads.

My problem is slightly different. I have a class/struct like this-

class Group {

    uint8 adjVariable;
    volatile bool  flag1: 1;
    volatile bool  flag2: 1;
    // so on...
    volatile bool  flag10: 1;
};

The way these variables are accessed is -

Group::fun() {
    Group_Scoped_lock();
    // adjVariable was 12 here.
    if ( adjVariable > 0 ) {
        adjVariable = 0; // <------- EXPLICIT ZERO ASSIGNMENT
    }
    // some code that doesn't affect adjVariable
    bool1 = false;
    bool2 = false;
    bool3 = false;
    assert( adjVariable == 0 ); // <---- This assert is tripping stating that adjVariable is 12!!
}

Before we suspected "bugs" with GCC, I verified if adjVariable was being accessed without Group_lock() elsewhere. To the best of my ability, I couldnt see any place in code where this was happening.

Now, since compiler issues 64 bit reads for bitfields AND they are volatile, what if it issued a read to adjVariable as part of this read AND the explicit ZERO assignment of adjVariable was still in cache and hence we read the older value of 12 for adjVariable? And this newly read value overwrites the explicitly set value? And hence we are tripping the assert? If so, how do I validate this?

In the article, they are discussing losing out updates to adjacent variables done in other threads but in my problem, I'm suspecting we are losing on updates to adjVariable done in the same thread because of reads from memory. Is this possible?

We are using an ancient g++ compiler which is only C++98 compliant on an equally older Fedora release 12 virtual machine. Also, we ran into this issue ONLY once a code base which was running for 6 months


问:
URL Rewrite in .htaccess?
i want to use URL rewriting in this link and will apply to all website but it's not work why?
and what can i do if i want to using URL rewriting??

the link http://www.example.com/showpage/php?page_id = 98
and i want to be http://www.example.com/showpage/98

i test it in local but not work and test it online in my domain not work. if any tools must run in my domain

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^showpage/$ showpage.php?page_id=$1
</IfModule>
</code>```

答:
$1 is not defined by a pattern. Try this:</p>

```<code>RewriteRule ^showpage/(.*)$ showpage.php?page_id=$1
</code>```

Title: URL Rewrite in .htaccess?

Body:
i want to use URL rewriting in this link and will apply to all website but it's not work why?
and what can i do if i want to using URL rewriting??

the link http://www.example.com/showpage/php?page_id = 98
and i want to be http://www.example.com/showpage/98

i test it in local but not work and test it online in my domain not work. if any tools must run in my domain

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^showpage/$ showpage.php?page_id=$1
</IfModule>

Body:
$1 is not defined by a pattern. Try this:

RewriteRule ^showpage/(.*)$ showpage.php?page_id=$1


问:
Can I deploy a Spring Boot application on godaddy
Can I deploy a Spring-Boot application on godaddy
using Web hosting and cPanel?
Thanks.</p>

答:
No. If you're using Web hosting (shared) plans according to Godaddy details.

I Suggest the answer from Amir Al.

For more information:

Web hosting (Shared) usually limits the Web technology you can use.
However, they're cheap and easy to set up a Wordpress, Drupal, Joomla etc.
So, if you use spring-boot, search Java web hosting

Virtual Private Server (VPS) and Dedicated Server will unlock the web hosting limitation because you have to do it by yourself.
However, if you're not familiar with Linux (Ex. CentOS / Ubuntu) command line. you can try Window VPS. If it looks so expensive, move to the cloud. I suggest a free trials or ~5USD package with Digital Ocean, Google Cloud, Amazon lightsail, and so on

Platform as a Service (PaaS) such as heroku. If Linux command line seems to be hard work for you. This choice gives you a shortcut to deploy your target application. However you have to learn about Git and their tools.

So, if you want to deploy spring-boot use:

Java web hosting

Cloud PaaS

VPS


问:
Reshape a data for Sklearn
I have a list of colors:

```<code>initialColors = [u'black' u'black' u'black' u'white' u'white' u'white' u'powderblue'
 u'whitesmoke' u'black' u'cornflowerblue' u'powderblue' u'powderblue'
 u'goldenrod' u'white' u'lavender' u'white' u'powderblue' u'powderblue'
 u'powderblue' u'powderblue' u'powderblue' u'powderblue' u'powderblue'
 u'powderblue' u'white' u'white' u'powderblue' u'white' u'white']
</code>```

And I have a labels for these colors like this:

```<code>labels_train = [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1]
</code>```

0 means that a color is chosen by female, 1 means male. And I am going to predict a gender using another one array of colors.

So, for my initial colors I turn the name into numerical feature vectors like this:

```<code>from sklearn import preprocessing
le = preprocessing.LabelEncoder()
le.fit(initialColors)
features_train = le.transform(initialColors)
</code>```

After that my features_train looks like:

```<code>[0 0 0 5 5 5 4 6 0 1 4 4 2 5 3 5 4 4 4 4 4 4 4 4 5 5 4 5 5]
</code>```

And finally, I do:

```<code>from sklearn.naive_bayes import GaussianNB
clf = GaussianNB()
clf.fit(features_train, labels_train)
</code>```

But I've got an error:

```<code>/Library/Python/2.7/site-packages/sklearn/utils/validation.py:395: DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and will raise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.
  DeprecationWarning)
Traceback (most recent call last):
  File "app.py", line 36, in <module>
    clf.fit(features_train, labels_train)
  File "/Library/Python/2.7/site-packages/sklearn/naive_bayes.py", line 182, in fit
    X, y = check_X_y(X, y)
  File "/Library/Python/2.7/site-packages/sklearn/utils/validation.py", line 531, in check_X_y
    check_consistent_length(X, y)
  File "/Library/Python/2.7/site-packages/sklearn/utils/validation.py", line 181, in check_consistent_length
    " samples: %r" % [int(l) for l in lengths])
ValueError: Found input variables with inconsistent numbers of samples: [1, 70]
</code>```

I did:

```<code>features_train = features_train.reshape(-1, 1)
labels_train = labels_train.reshape(-1, 1)
clf.fit(features_train, labels_train)
</code>```

I've got an error:

```<code>/Library/Python/2.7/site-packages/sklearn/utils/validation.py:526: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().
  y = column_or_1d(y, warn=True)
</code>```

I also tried:

```<code>features_train = features_train.reshape(1, -1)
labels_train = labels_train.reshape(1, -1)
</code>```

But anyway:

```<code>Traceback (most recent call last):
  File "app.py", line 36, in <module>
    clf.fit(features_train, labels_train)
  File "/Library/Python/2.7/site-packages/sklearn/naive_bayes.py", line 182, in fit
    X, y = check_X_y(X, y)
  File "/Library/Python/2.7/site-packages/sklearn/utils/validation.py", line 526, in check_X_y
    y = column_or_1d(y, warn=True)
  File "/Library/Python/2.7/site-packages/sklearn/utils/validation.py", line 562, in column_or_1d
    raise ValueError("bad input shape {0}".format(shape))
ValueError: bad input shape (1, 29)
</code>```

My problem is that I don't understand what is the best way to reshape a data in my case. Can you please a help me to choose a way to reshape my data?

答:
Quick answer:

Do features_train = features_train.reshape(-1, 1);

Do NOT do labels_train = labels_train.reshape(-1, 1). Leave labels_train as it is.

Some details:

It seems you are confused about the why 2D data array input is required for estimators. Your training vectors X has a shape (n_samples, n_features). So features_train.reshape(-1, 1) is correct for your case here, since you have only 1 feature and want to let numpy to infer how many samples are there. This indeed solves your first error.

Your target values y has a shape (n_samples,), which expects a 1D array. When you do labels_train = labels_train.reshape(-1, 1), you convert it to a 2D column-vector. That's why you got the second warning. Note that it's a warning, meaning fit() figured it out and did the correct conversion, i.e. your program continues to run and should be correct.

When you do:

```<code>features_train = features_train.reshape(1, -1)
labels_train = labels_train.reshape(1, -1)
</code>```

First, it is a wrong conversion for features_train for your case here because X.reshape(1, -1) means you have 1 sample and want to let numpy to infer how many features are there. It is not what you want but fit() doesn't know and will process it accordingly, giving you the wrong result.

That being said, your last error does not come from features_train = features_train.reshape(1, -1). It is from labels_train = labels_train.reshape(1, -1). Your labels_train has now a shape (1, 29) which is neither a row nor a column-vector. Though we might know it should be interpreted as a 1D array of target values, fit() is not that smart yet and don't know what to do with it.

Title: Reshape a data for Sklearn

Body:
I have a list of colors:

initialColors = [u'black' u'black' u'black' u'white' u'white' u'white' u'powderblue'
 u'whitesmoke' u'black' u'cornflowerblue' u'powderblue' u'powderblue'
 u'goldenrod' u'white' u'lavender' u'white' u'powderblue' u'powderblue'
 u'powderblue' u'powderblue' u'powderblue' u'powderblue' u'powderblue'
 u'powderblue' u'white' u'white' u'powderblue' u'white' u'white']

And I have a labels for these colors like this:

labels_train = [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1]

0 means that a color is chosen by female, 1 means male. And I am going to predict a gender using another one array of colors.

So, for my initial colors I turn the name into numerical feature vectors like this:

from sklearn import preprocessing
le = preprocessing.LabelEncoder()
le.fit(initialColors)
features_train = le.transform(initialColors)

After that my features_train looks like:

[0 0 0 5 5 5 4 6 0 1 4 4 2 5 3 5 4 4 4 4 4 4 4 4 5 5 4 5 5]

And finally, I do:

from sklearn.naive_bayes import GaussianNB
clf = GaussianNB()
clf.fit(features_train, labels_train)

But I've got an error:

/Library/Python/2.7/site-packages/sklearn/utils/validation.py:395: DeprecationWarning: Passing 1d arrays as data is deprecated in 0.17 and will raise ValueError in 0.19. Reshape your data either using X.reshape(-1, 1) if your data has a single feature or X.reshape(1, -1) if it contains a single sample.
  DeprecationWarning)
Traceback (most recent call last):
  File "app.py", line 36, in <module>
    clf.fit(features_train, labels_train)
  File "/Library/Python/2.7/site-packages/sklearn/naive_bayes.py", line 182, in fit
    X, y = check_X_y(X, y)
  File "/Library/Python/2.7/site-packages/sklearn/utils/validation.py", line 531, in check_X_y
    check_consistent_length(X, y)
  File "/Library/Python/2.7/site-packages/sklearn/utils/validation.py", line 181, in check_consistent_length
    " samples: %r" % [int(l) for l in lengths])
ValueError: Found input variables with inconsistent numbers of samples: [1, 70]

I did:

features_train = features_train.reshape(-1, 1)
labels_train = labels_train.reshape(-1, 1)
clf.fit(features_train, labels_train)

I've got an error:

/Library/Python/2.7/site-packages/sklearn/utils/validation.py:526: DataConversionWarning: A column-vector y was passed when a 1d array was expected. Please change the shape of y to (n_samples, ), for example using ravel().
  y = column_or_1d(y, warn=True)

I also tried:

features_train = features_train.reshape(1, -1)
labels_train = labels_train.reshape(1, -1)

But anyway:

Traceback (most recent call last):
  File "app.py", line 36, in <module>
    clf.fit(features_train, labels_train)
  File "/Library/Python/2.7/site-packages/sklearn/naive_bayes.py", line 182, in fit
    X, y = check_X_y(X, y)
  File "/Library/Python/2.7/site-packages/sklearn/utils/validation.py", line 526, in check_X_y
    y = column_or_1d(y, warn=True)
  File "/Library/Python/2.7/site-packages/sklearn/utils/validation.py", line 562, in column_or_1d
    raise ValueError("bad input shape {0}".format(shape))
ValueError: bad input shape (1, 29)

My problem is that I don't understand what is the best way to reshape a data in my case. Can you please a help me to choose a way to reshape my data?

Body:
Quick answer:

Do features_train = features_train.reshape(-1, 1);

Do NOT do labels_train = labels_train.reshape(-1, 1). Leave labels_train as it is.

Some details:

It seems you are confused about the why 2D data array input is required for estimators. Your training vectors X has a shape (n_samples, n_features). So features_train.reshape(-1, 1) is correct for your case here, since you have only 1 feature and want to let numpy to infer how many samples are there. This indeed solves your first error.

Your target values y has a shape (n_samples,), which expects a 1D array. When you do labels_train = labels_train.reshape(-1, 1), you convert it to a 2D column-vector. That's why you got the second warning. Note that it's a warning, meaning fit() figured it out and did the correct conversion, i.e. your program continues to run and should be correct.

When you do:

features_train = features_train.reshape(1, -1)
labels_train = labels_train.reshape(1, -1)

First, it is a wrong conversion for features_train for your case here because X.reshape(1, -1) means you have 1 sample and want to let numpy to infer how many features are there. It is not what you want but fit() doesn't know and will process it accordingly, giving you the wrong result.

That being said, your last error does not come from features_train = features_train.reshape(1, -1). It is from labels_train = labels_train.reshape(1, -1). Your labels_train has now a shape (1, 29) which is neither a row nor a column-vector. Though we might know it should be interpreted as a 1D array of target values, fit() is not that smart yet and don't know what to do with it.


问:
How to change StackView content after the view has loaded?
i have created a new instance of UIstackView in a file called Stages

```<code>    class Stages: UIStackView {

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init(coder: NSCoder) {
        super.init(coder: coder)
        }

func SetUpStageOne() {
add some views inside a stackview

func SetUpStageTwo() {
add some new views inside a stackview
}
</code>```

I am stuck trying to figure out how i can get the StackView to appear at Run-time like this

```<code>        class Stages: UIStackView {

        override init(frame: CGRect) {
            super.init(frame: frame)

           if score == 0 {
           SetUpStageOne()
    }
           if score == 1 {
           SetUpStageTwo()
        }

        required init(coder: NSCoder) {
            super.init(coder: coder)
           if score == 0 {
           SetUpStageOne()
    }
           if score == 1 {
           SetUpStageTwo()
        }

   }

    func SetUpStageOne() {
    add some views inside a stackview

    func SetUpStageTwo() {
    add some new views inside a stackview
    }
</code>```

i can get the first StackView to appear, when the score == 0
but thoughout the game, i want to update the stackview so that the second stackview appear when the score == 1, but that dosnt happen.

答: Try using self.setNeedsLayout() at the end of each setupstage method. This will adjust the layout of a view's subviews. self.setNeedsDisplay() will not work as it resets the view if you have overridden the draw(_ rect) function.</p>

Body:
i have created a new instance of UIstackView in a file called Stages

    class Stages: UIStackView {

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init(coder: NSCoder) {
        super.init(coder: coder)
        }

func SetUpStageOne() {
add some views inside a stackview

func SetUpStageTwo() {
add some new views inside a stackview
}

I am stuck trying to figure out how i can get the StackView to appear at Run-time like this

        class Stages: UIStackView {

        override init(frame: CGRect) {
            super.init(frame: frame)

           if score == 0 {
           SetUpStageOne()
    }
           if score == 1 {
           SetUpStageTwo()
        }

        required init(coder: NSCoder) {
            super.init(coder: coder)
           if score == 0 {
           SetUpStageOne()
    }
           if score == 1 {
           SetUpStageTwo()
        }

   }

    func SetUpStageOne() {
    add some views inside a stackview

    func SetUpStageTwo() {
    add some new views inside a stackview
    }

i can get the first StackView to appear, when the score == 0
but thoughout the game, i want to update the stackview so that the second stackview appear when the score == 1, but that dosnt happen.


问:
How to query all data in a table that contains a foreign key from other table that contains multiple foreign key?
Here are my tables:

TABLE

What I want to happen here is to formulate a query that retrieves all data from tblCurrentTransaction.

My query:

```<code>SELECT room_name, duration_name, price, final_price, check_in, check_out
FROM tblCurrentTransaction,
     tblRoomRates,
     tblRooms,
     tblDuration
WHERE tblRoomRates.room_id = tblRooms.id
  AND tblRoomRates.duration_id = tblDuration.id
</code>```

Output:

What happen is that it prints everything that is in the other tables.

 What I wanted it to do is to just print the data in tblCurrentTransaction

答:
I've done it:</p>

```<code>SELECT room_name, duration_name, price, final_price, check_in, check_out
FROM tblCurrentTransaction,
     tblRoomRates,
     tblRooms,
     tblDuration
WHERE tblRoomRates.room_id = tblRooms.id
  AND tblRoomRates.duration_id = tblDuration.id
  AND tblCurrentTransaction.room_rate_id = tblRoomRates.id;
</code>```

Body:
Here are my tables:

TABLE

What I want to happen here is to formulate a query that retrieves all data from tblCurrentTransaction.

My query:

SELECT room_name, duration_name, price, final_price, check_in, check_out
FROM tblCurrentTransaction,
     tblRoomRates,
     tblRooms,
     tblDuration
WHERE tblRoomRates.room_id = tblRooms.id
  AND tblRoomRates.duration_id = tblDuration.id

Output:

What happen is that it prints everything that is in the other tables.

 What I wanted it to do is to just print the data in tblCurrentTransaction

Body:
I've done it:

SELECT room_name, duration_name, price, final_price, check_in, check_out
FROM tblCurrentTransaction,
     tblRoomRates,
     tblRooms,
     tblDuration
WHERE tblRoomRates.room_id = tblRooms.id
  AND tblRoomRates.duration_id = tblDuration.id
  AND tblCurrentTransaction.room_rate_id = tblRoomRates.id;