问:
Populate Only When Conditions Are Met
I have a mongodb database and   I use mongoose with nodejs.

I need return data from the next query populating "tabela_tuss" only if I have the field "temtussvinculado=true".

Here is what I am doing:

```<code>ConvProced.find({'convenioId':new ObjectId(req.params.id)})
        .populate('convenioId')
        .populate({
             path:'procedId',
             populate:{
                 path:'tabela_tuss',
                 match: { 'procedId.temtussvinculado': true}
            }
        })
        .exec( (err,data) => {
           callback(err,data,res)
        })
</code>```

My problem is that my match with "procedId.temtussvinculado:true" has no effect and "tabela_tuss" is never populated.

What am I doing wrong?

Here is my schemas:

```<code>////
var conveniosSchema = new mongoose.Schema({
  nome: {type: String, unique:true},
  ativo: {type: Boolean}
 });
module.exports = mongoose.model('Convenio', conveniosSchema,'convenios' );
////

////
const agProcedimentosSchema = new mongoose.Schema({
  ativo:{type:Boolean},
  temtussvinculado:{type:Boolean},
  tabela_tuss:{type:mongoose.Schema.Types.ObjectId, ref:'Tuss_22'}
});
module.exports = mongoose.model('Ag_procedimento', agProcedimentosSchema,'ag_procedimentos' );
///

////
const tuss_22Schema = new mongoose.Schema({
  codigo: {type: String, unique:true},
  descricao:{type: String},
  tabela:{type: String}
});
module.exports = mongoose.model('Tuss_22', tuss_22Schema,'tuss_22' );
////

//../models/convenioprocedimento
var conveniosProcedsSchema = new mongoose.Schema({
   convenioId:{type:mongoose.Schema.Types.ObjectId, ref:'Convenio'},
   procedId:{type:mongoose.Schema.Types.ObjectId, ref:'Ag_procedimento'},
   valor_particular:{type:Number},
   valor_convenio:{type:Number},
  });

module.exports = mongoose.model('ConvenioProcedimento', conveniosProcedsSchema,'conveniosprocedimentos' );

//my query:

const ConvProced = require('../models/convenioprocedimento');
ConvProced.find({'convenioId':new ObjectId(req.params.id)})
    .populate('convenioId')
    .populate({
         path:'procedId',
         populate:{
             path:'tabela_tuss',
             match: { 'procedId.temtussvinculado': true}
        }
    })
    .exec( (err,data) => {
       callback(err,data,res)
    })
</code>```

答:
What you are actually asking here is to "Only populate where a condition within the data says to do so", which is something that is not actually a "directly" supported action of .populate() or usage of the "nested populate" syntax.

So if you want to impose "conditions" on which items are actually populated or not, then you must handle the populate calls "manually".

The basic premise in your case is that you would need to inspect the value which you need to get from the "initial" top level .populate() call, but then "only" call the "inner" populate when the given condtions actually allow it.

So your code should then probably look like this using "Promises" using Promise.all() where you basically "loop" or .map() each query result and test the proceedid.temtussvinculado to see if it is true/false, and where true we actually issue a Model.populate() call, otherwise just return the data in it's present state:

```<code>ConvProced.find({'convenioId':new ObjectId(req.params.id)})
  .populate('convenioId procedId')
  .exec()
  .then(data =>
    Promise.all(
      data.map( d =>
        ( d.proceedid.temtussvinculado )
        ? mongoose.model('Tuss_22').populate(d,{ path: 'proceedId.tabela_tuss' })
        : d
      )
    )
  )
)
// Populated conditionally
.then( data =>
  // Do something with data
)
.catch(err => console.error(err)); // or something else with error
</code>```

There are different options available other than 'Promises', but it is the no dependency option. Alternate cases such as async.map to do much the same thing, but is an additional dependency if you do not already have it:

```<code>ConvProced.find({'convenioId':new ObjectId(req.params.id)})
  .populate('convenioId procedId')
  .exec((err,data) => {
    if (err) throw err;
    async.map(data,(d,callback) =>
      ( d.proceedid.temtussvinculado )
        ? mongoose.model('Tuss_22').populate(d,{ path: 'proceedId.tabela_tuss' },callback)
        : callback(null,d)
      (err,data) => {
        if (err) throw err; // or something
        // Conditionally populated
      }
    )
  })
</code>```

Also demonstrated with a full working example, which is actually a little more complicated than what you need to do, since the "condition" is nested within another array in this example:

```<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 subInnerSchema = new Schema({
  label: String
});

const innerSchema = new Schema({
  name: String,
  populate: Boolean,
  subs: [{ type: Schema.Types.ObjectId, ref: 'Sub' }]
});

const outerSchema = new Schema({
  title: String,
  inners: [{ type: Schema.Types.ObjectId, ref: 'Inner' }]
});

const Sub = mongoose.model('Sub', subInnerSchema);
const Inner = mongoose.model('Inner', innerSchema);
const Outer = mongoose.model('Outer', outerSchema);

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

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

    // Insert some data
    (callback) =>
      async.waterfall(
        [
          (callback) =>
            Sub.create([1,2,3,4].map( label => ({ label })),callback),

          (subs,callback) =>
            Inner.create(
              [0,2].map(x => subs.slice(x,x+2))
              .map((el,i) => ({
                name: i+i,
                populate: i == 1,
                subs: el
              })),
              callback
            ),

          (inners,callback) =>
            Outer.create(
              inners.map((inner,i) => ({
                title: i+1,
                inners: [inner]
              })),
              callback
            ),

        ],
        callback
      ),

    // Conditional populate async.map version
    (callback) =>
      Outer.find().populate('inners').exec((err,outers) => {
        if (err) callback(err);

        async.map(
          outers,
          (outer,callback) =>
            async.map(
              outer.inners,
              (inner,callback) =>
                (inner.populate)
                  ? Inner.populate(inner,{ path: 'subs' },callback)
                  : callback(null,inner),

              (err,inners) => {
                if (err) callback(err);
                outer.inners = inners
                callback(null,outer);
              }
            ),

          (err,outers) => {
            if (err) callback(err);
            log(outers);
            callback();
          }
        );
      }),

    // Conditional populate Promise
    (callback) =>
      Outer.find().populate('inners').exec()
        .then(outers =>
          Promise.all(
            outers.map( outer =>
              new Promise((resolve,reject) => {
                Promise.all(
                  outer.inners.map( inner =>
                    (inner.populate)
                      ? Inner.populate(inner,{ path: 'subs' })
                      : inner
                  )
                ).then(inners => {
                  outer.inners = inners;
                  resolve(outer)
                })
                .catch(reject)
              })
            )
          )
        )
        .then(outers => {
          log(outers);
          callback();
        })
        .catch(err => callback(err))

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

Which produces the output showing the "conditional" selection, from using either approach of course:

```<code>Mongoose: subs.remove({}, {})
Mongoose: inners.remove({}, {})
Mongoose: outers.remove({}, {})
Mongoose: subs.insert({ label: '1', _id: ObjectId("5961830256bf9e2d0fcf13b3"), __v: 0 })
Mongoose: subs.insert({ label: '2', _id: ObjectId("5961830256bf9e2d0fcf13b4"), __v: 0 })
Mongoose: subs.insert({ label: '3', _id: ObjectId("5961830256bf9e2d0fcf13b5"), __v: 0 })
Mongoose: subs.insert({ label: '4', _id: ObjectId("5961830256bf9e2d0fcf13b6"), __v: 0 })
Mongoose: inners.insert({ name: '0', populate: false, _id: ObjectId("5961830256bf9e2d0fcf13b7"), subs: [ ObjectId("5961830256bf9e2d0fcf13b3"), ObjectId("5961830256bf9e2d0fcf13b4") ], __v: 0 })
Mongoose: inners.insert({ name: '2', populate: true, _id: ObjectId("5961830256bf9e2d0fcf13b8"), subs: [ ObjectId("5961830256bf9e2d0fcf13b5"), ObjectId("5961830256bf9e2d0fcf13b6") ], __v: 0 })
Mongoose: outers.insert({ title: '1', _id: ObjectId("5961830256bf9e2d0fcf13b9"), inners: [ ObjectId("5961830256bf9e2d0fcf13b7") ], __v: 0 })
Mongoose: outers.insert({ title: '2', _id: ObjectId("5961830256bf9e2d0fcf13ba"), inners: [ ObjectId("5961830256bf9e2d0fcf13b8") ], __v: 0 })
Mongoose: outers.find({}, { fields: {} })
Mongoose: inners.find({ _id: { '$in': [ ObjectId("5961830256bf9e2d0fcf13b7"), ObjectId("5961830256bf9e2d0fcf13b8") ] } }, { fields: {} })
Mongoose: subs.find({ _id: { '$in': [ ObjectId("5961830256bf9e2d0fcf13b5"), ObjectId("5961830256bf9e2d0fcf13b6") ] } }, { fields: {} })
[
  {
    "_id": "5961830256bf9e2d0fcf13b9",
    "title": "1",
    "__v": 0,
    "inners": [
      {
        "_id": "5961830256bf9e2d0fcf13b7",
        "name": "0",
        "populate": false,
        "__v": 0,
        "subs": [
          "5961830256bf9e2d0fcf13b3",
          "5961830256bf9e2d0fcf13b4"
        ]
      }
    ]
  },
  {
    "_id": "5961830256bf9e2d0fcf13ba",
    "title": "2",
    "__v": 0,
    "inners": [
      {
        "_id": "5961830256bf9e2d0fcf13b8",
        "name": "2",
        "populate": true,
        "__v": 0,
        "subs": [
          {
            "_id": "5961830256bf9e2d0fcf13b5",
            "label": "3",
            "__v": 0
          },
          {
            "_id": "5961830256bf9e2d0fcf13b6",
            "label": "4",
            "__v": 0
          }
        ]
      }
    ]
  }
]
Mongoose: outers.find({}, { fields: {} })
Mongoose: inners.find({ _id: { '$in': [ ObjectId("5961830256bf9e2d0fcf13b7"), ObjectId("5961830256bf9e2d0fcf13b8") ] } }, { fields: {} })
Mongoose: subs.find({ _id: { '$in': [ ObjectId("5961830256bf9e2d0fcf13b5"), ObjectId("5961830256bf9e2d0fcf13b6") ] } }, { fields: {} })
[
  {
    "_id": "5961830256bf9e2d0fcf13b9",
    "title": "1",
    "__v": 0,
    "inners": [
      {
        "_id": "5961830256bf9e2d0fcf13b7",
        "name": "0",
        "populate": false,
        "__v": 0,
        "subs": [
          "5961830256bf9e2d0fcf13b3",
          "5961830256bf9e2d0fcf13b4"
        ]
      }
    ]
  },
  {
    "_id": "5961830256bf9e2d0fcf13ba",
    "title": "2",
    "__v": 0,
    "inners": [
      {
        "_id": "5961830256bf9e2d0fcf13b8",
        "name": "2",
        "populate": true,
        "__v": 0,
        "subs": [
          {
            "_id": "5961830256bf9e2d0fcf13b5",
            "label": "3",
            "__v": 0
          },
          {
            "_id": "5961830256bf9e2d0fcf13b6",
            "label": "4",
            "__v": 0
          }
        ]
      }
    ]
  }
]
</code>```

So you can see there that in much the same way there is a "boolean" field which is being tested to determine whether to perform a .populate() or just return the plain data instead.

Title: Populate Only When Conditions Are Met

Body:
I have a mongodb database and   I use mongoose with nodejs.

I need return data from the next query populating "tabela_tuss" only if I have the field "temtussvinculado=true".

Here is what I am doing:

ConvProced.find({'convenioId':new ObjectId(req.params.id)})
        .populate('convenioId')
        .populate({
             path:'procedId',
             populate:{
                 path:'tabela_tuss',
                 match: { 'procedId.temtussvinculado': true}
            }
        })
        .exec( (err,data) => {
           callback(err,data,res)
        })

My problem is that my match with "procedId.temtussvinculado:true" has no effect and "tabela_tuss" is never populated.

What am I doing wrong?

Here is my schemas:

////
var conveniosSchema = new mongoose.Schema({
  nome: {type: String, unique:true},
  ativo: {type: Boolean}
 });
module.exports = mongoose.model('Convenio', conveniosSchema,'convenios' );
////

////
const agProcedimentosSchema = new mongoose.Schema({
  ativo:{type:Boolean},
  temtussvinculado:{type:Boolean},
  tabela_tuss:{type:mongoose.Schema.Types.ObjectId, ref:'Tuss_22'}
});
module.exports = mongoose.model('Ag_procedimento', agProcedimentosSchema,'ag_procedimentos' );
///

////
const tuss_22Schema = new mongoose.Schema({
  codigo: {type: String, unique:true},
  descricao:{type: String},
  tabela:{type: String}
});
module.exports = mongoose.model('Tuss_22', tuss_22Schema,'tuss_22' );
////

//../models/convenioprocedimento
var conveniosProcedsSchema = new mongoose.Schema({
   convenioId:{type:mongoose.Schema.Types.ObjectId, ref:'Convenio'},
   procedId:{type:mongoose.Schema.Types.ObjectId, ref:'Ag_procedimento'},
   valor_particular:{type:Number},
   valor_convenio:{type:Number},
  });

module.exports = mongoose.model('ConvenioProcedimento', conveniosProcedsSchema,'conveniosprocedimentos' );

//my query:

const ConvProced = require('../models/convenioprocedimento');
ConvProced.find({'convenioId':new ObjectId(req.params.id)})
    .populate('convenioId')
    .populate({
         path:'procedId',
         populate:{
             path:'tabela_tuss',
             match: { 'procedId.temtussvinculado': true}
        }
    })
    .exec( (err,data) => {
       callback(err,data,res)
    })

Body:
What you are actually asking here is to "Only populate where a condition within the data says to do so", which is something that is not actually a "directly" supported action of .populate() or usage of the "nested populate" syntax.

So if you want to impose "conditions" on which items are actually populated or not, then you must handle the populate calls "manually".

The basic premise in your case is that you would need to inspect the value which you need to get from the "initial" top level .populate() call, but then "only" call the "inner" populate when the given condtions actually allow it.

So your code should then probably look like this using "Promises" using Promise.all() where you basically "loop" or .map() each query result and test the proceedid.temtussvinculado to see if it is true/false, and where true we actually issue a Model.populate() call, otherwise just return the data in it's present state:

ConvProced.find({'convenioId':new ObjectId(req.params.id)})
  .populate('convenioId procedId')
  .exec()
  .then(data =>
    Promise.all(
      data.map( d =>
        ( d.proceedid.temtussvinculado )
        ? mongoose.model('Tuss_22').populate(d,{ path: 'proceedId.tabela_tuss' })
        : d
      )
    )
  )
)
// Populated conditionally
.then( data =>
  // Do something with data
)
.catch(err => console.error(err)); // or something else with error

There are different options available other than 'Promises', but it is the no dependency option. Alternate cases such as async.map to do much the same thing, but is an additional dependency if you do not already have it:

ConvProced.find({'convenioId':new ObjectId(req.params.id)})
  .populate('convenioId procedId')
  .exec((err,data) => {
    if (err) throw err;
    async.map(data,(d,callback) =>
      ( d.proceedid.temtussvinculado )
        ? mongoose.model('Tuss_22').populate(d,{ path: 'proceedId.tabela_tuss' },callback)
        : callback(null,d)
      (err,data) => {
        if (err) throw err; // or something
        // Conditionally populated
      }
    )
  })

Also demonstrated with a full working example, which is actually a little more complicated than what you need to do, since the "condition" is nested within another array in this example:

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

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

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

const subInnerSchema = new Schema({
  label: String
});

const innerSchema = new Schema({
  name: String,
  populate: Boolean,
  subs: [{ type: Schema.Types.ObjectId, ref: 'Sub' }]
});

const outerSchema = new Schema({
  title: String,
  inners: [{ type: Schema.Types.ObjectId, ref: 'Inner' }]
});

const Sub = mongoose.model('Sub', subInnerSchema);
const Inner = mongoose.model('Inner', innerSchema);
const Outer = mongoose.model('Outer', outerSchema);

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

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

    // Insert some data
    (callback) =>
      async.waterfall(
        [
          (callback) =>
            Sub.create([1,2,3,4].map( label => ({ label })),callback),

          (subs,callback) =>
            Inner.create(
              [0,2].map(x => subs.slice(x,x+2))
              .map((el,i) => ({
                name: i+i,
                populate: i == 1,
                subs: el
              })),
              callback
            ),

          (inners,callback) =>
            Outer.create(
              inners.map((inner,i) => ({
                title: i+1,
                inners: [inner]
              })),
              callback
            ),

        ],
        callback
      ),

    // Conditional populate async.map version
    (callback) =>
      Outer.find().populate('inners').exec((err,outers) => {
        if (err) callback(err);

        async.map(
          outers,
          (outer,callback) =>
            async.map(
              outer.inners,
              (inner,callback) =>
                (inner.populate)
                  ? Inner.populate(inner,{ path: 'subs' },callback)
                  : callback(null,inner),

              (err,inners) => {
                if (err) callback(err);
                outer.inners = inners
                callback(null,outer);
              }
            ),

          (err,outers) => {
            if (err) callback(err);
            log(outers);
            callback();
          }
        );
      }),

    // Conditional populate Promise
    (callback) =>
      Outer.find().populate('inners').exec()
        .then(outers =>
          Promise.all(
            outers.map( outer =>
              new Promise((resolve,reject) => {
                Promise.all(
                  outer.inners.map( inner =>
                    (inner.populate)
                      ? Inner.populate(inner,{ path: 'subs' })
                      : inner
                  )
                ).then(inners => {
                  outer.inners = inners;
                  resolve(outer)
                })
                .catch(reject)
              })
            )
          )
        )
        .then(outers => {
          log(outers);
          callback();
        })
        .catch(err => callback(err))

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

Which produces the output showing the "conditional" selection, from using either approach of course:

Mongoose: subs.remove({}, {})
Mongoose: inners.remove({}, {})
Mongoose: outers.remove({}, {})
Mongoose: subs.insert({ label: '1', _id: ObjectId("5961830256bf9e2d0fcf13b3"), __v: 0 })
Mongoose: subs.insert({ label: '2', _id: ObjectId("5961830256bf9e2d0fcf13b4"), __v: 0 })
Mongoose: subs.insert({ label: '3', _id: ObjectId("5961830256bf9e2d0fcf13b5"), __v: 0 })
Mongoose: subs.insert({ label: '4', _id: ObjectId("5961830256bf9e2d0fcf13b6"), __v: 0 })
Mongoose: inners.insert({ name: '0', populate: false, _id: ObjectId("5961830256bf9e2d0fcf13b7"), subs: [ ObjectId("5961830256bf9e2d0fcf13b3"), ObjectId("5961830256bf9e2d0fcf13b4") ], __v: 0 })
Mongoose: inners.insert({ name: '2', populate: true, _id: ObjectId("5961830256bf9e2d0fcf13b8"), subs: [ ObjectId("5961830256bf9e2d0fcf13b5"), ObjectId("5961830256bf9e2d0fcf13b6") ], __v: 0 })
Mongoose: outers.insert({ title: '1', _id: ObjectId("5961830256bf9e2d0fcf13b9"), inners: [ ObjectId("5961830256bf9e2d0fcf13b7") ], __v: 0 })
Mongoose: outers.insert({ title: '2', _id: ObjectId("5961830256bf9e2d0fcf13ba"), inners: [ ObjectId("5961830256bf9e2d0fcf13b8") ], __v: 0 })
Mongoose: outers.find({}, { fields: {} })
Mongoose: inners.find({ _id: { '$in': [ ObjectId("5961830256bf9e2d0fcf13b7"), ObjectId("5961830256bf9e2d0fcf13b8") ] } }, { fields: {} })
Mongoose: subs.find({ _id: { '$in': [ ObjectId("5961830256bf9e2d0fcf13b5"), ObjectId("5961830256bf9e2d0fcf13b6") ] } }, { fields: {} })
[
  {
    "_id": "5961830256bf9e2d0fcf13b9",
    "title": "1",
    "__v": 0,
    "inners": [
      {
        "_id": "5961830256bf9e2d0fcf13b7",
        "name": "0",
        "populate": false,
        "__v": 0,
        "subs": [
          "5961830256bf9e2d0fcf13b3",
          "5961830256bf9e2d0fcf13b4"
        ]
      }
    ]
  },
  {
    "_id": "5961830256bf9e2d0fcf13ba",
    "title": "2",
    "__v": 0,
    "inners": [
      {
        "_id": "5961830256bf9e2d0fcf13b8",
        "name": "2",
        "populate": true,
        "__v": 0,
        "subs": [
          {
            "_id": "5961830256bf9e2d0fcf13b5",
            "label": "3",
            "__v": 0
          },
          {
            "_id": "5961830256bf9e2d0fcf13b6",
            "label": "4",
            "__v": 0
          }
        ]
      }
    ]
  }
]
Mongoose: outers.find({}, { fields: {} })
Mongoose: inners.find({ _id: { '$in': [ ObjectId("5961830256bf9e2d0fcf13b7"), ObjectId("5961830256bf9e2d0fcf13b8") ] } }, { fields: {} })
Mongoose: subs.find({ _id: { '$in': [ ObjectId("5961830256bf9e2d0fcf13b5"), ObjectId("5961830256bf9e2d0fcf13b6") ] } }, { fields: {} })
[
  {
    "_id": "5961830256bf9e2d0fcf13b9",
    "title": "1",
    "__v": 0,
    "inners": [
      {
        "_id": "5961830256bf9e2d0fcf13b7",
        "name": "0",
        "populate": false,
        "__v": 0,
        "subs": [
          "5961830256bf9e2d0fcf13b3",
          "5961830256bf9e2d0fcf13b4"
        ]
      }
    ]
  },
  {
    "_id": "5961830256bf9e2d0fcf13ba",
    "title": "2",
    "__v": 0,
    "inners": [
      {
        "_id": "5961830256bf9e2d0fcf13b8",
        "name": "2",
        "populate": true,
        "__v": 0,
        "subs": [
          {
            "_id": "5961830256bf9e2d0fcf13b5",
            "label": "3",
            "__v": 0
          },
          {
            "_id": "5961830256bf9e2d0fcf13b6",
            "label": "4",
            "__v": 0
          }
        ]
      }
    ]
  }
]

So you can see there that in much the same way there is a "boolean" field which is being tested to determine whether to perform a .populate() or just return the plain data instead.


来源: stackexchange

问:
Get class of appended ajax jquery data
```<code><div id="loadhere></div>
</code>```

Ajax snippet

```<code>  $('#loadhere').append('<span id="1" class="trash">     </span>');

$('.trash').click(function(){
   var x=$(this).attr('id');
 });
</code>```

My problem i was not able to get the data of appended jquery data

答:
maybe you need to pass the handler as an argument to the function?</p>

```<code>$('.trash').click(function(handler){
   var x=handler.attr('id');
 });
</code>```

ContentLicense: CC BY-SA 3.0

Title: Get class of appended ajax jquery data

Body:
Ajax snippet

  $('#loadhere').append('     ');

$('.trash').click(function(){
   var x=$(this).attr('id');
 });

My problem i was not able to get the data of appended jquery data

Body:
maybe you need to pass the handler as an argument to the function?

$('.trash').click(function(handler){
   var x=handler.attr('id');
 });


问:
I am new to Racket and need some help for this function
I want the answer to be #t here:

```<code>> (is-member? "foo" '(4 5 #f "foo" a))
#t
</code>```

But I'm getting the error:

```<code>> (is-member? "foo" '(4 5 #f "foo" a))
;string=?: contract violation
;  expected: string?
;  given: #f
;  argument position: 2nd
;  other arguments...:
;   "foo"
</code>```

My definitions of is-member? and is-member-string? are:

```<code>#lang racket

(define (is-member? num lst)
  (if (null? lst)
      #f
      (if (string? num)
          (is-member-string? num lst)
          (is-member-number? num lst))))

(define (is-member-string? num lst)
  (if (null? lst)
      #f
      (if (integer? (car lst))
          (is-member-string? num (rest lst))
          (if (string=? (car lst) num)
              #t
              (is-member-string? num (rest lst))))))

(define (is-member-number? num lst)
  ....)
</code>```

答:
Look at the error message and see how it helps you. It says the error is coming from string=?, and if you look in DrRacket it even highlights the specific call that went wrong. It's the (string=? (car lst) num) in the is-member-string? function.

Figure out what arguments were and why they're wrong. The error message says that the wrong argument was #f where it expected a string.

Where did the bad argument come from? Was it num or (car lst)? Looking at how num flows through the program, num should always be "foo", so it's probably the other one, (car lst).

How did this code execute with that bad argument? Why is (car lst) false here? Because it's walking down the list, and the list contains a false in it. That should be fine, as long as you design your function properly to handle all values.

To do that, you should put a type signature on your functions to show what types of arguments are allowed. For is-member-string? I'm assuming you meant:

```<code>;; is-member-string? : String [List-of Any] -> Boolean
(define (is-member-string? str lst)
   ....)
</code>```

(I've renamed num to str because it's not a number, it's a string.)

Next you need to make sure that the code works with the signature. You're designing this function by destructuring the list argument, but you need to keep the types of the values in mind:

```<code>;; is-member-string? : String [List-of Any] -> Boolean
(define (is-member-string? str lst)
  (if (null? lst)
      #f
      (.... (first lst) ; (first lst) is an Any
       .... (rest lst)))) ; (rest lst) is a [List-of Any]
</code>```

(I'm using first instead of car because first makes more sense.)

Can you see what's wrong now?

```<code>;; is-member-string? : String [List-of Any] -> Boolean
(define (is-member-string? str lst)
  (if (null? lst)
      #f
      (if (integer? (first lst))             ; (first lst) is an Any
          (is-member-string? str (rest lst))
          (if (string=? (first lst) str)     ; (first lst) is an Any, but not an integer
              #t
              (is-member-string? str (rest lst))))))
</code>```

(first lst) is an Any, but you're using (string=? (first lst) str). That shouldn't be allowed unless you're sure that (first lst) is a string.

There are two ways to do this. One way to fix this is to use (equal? (first lst) str) instead.

```<code>;; is-member-string? : String [List-of Any] -> Boolean
(define (is-member-string? str lst)
  (if (null? lst)
      #f
      (if (equal? (first lst) str)
          #t
          (is-member-string? str (rest lst)))))
</code>```

The second way is to check that it's a string before you use string=?. I assume that's what you were trying to do with your integer? check, but it isn't working. Instead you want to use (string? (first lst)) somehow. You only want to check string=? after that passes. One way to do that is with and.

```<code>;; is-member-string? : String [List-of Any] -> Boolean
(define (is-member-string? str lst)
  (if (null? lst)
      #f
      (if (and (string? (first lst)) (string=? (first lst) str))
          #t
          (is-member-string? str (rest lst)))))
</code>```

Body:
I want the answer to be #t here:

> (is-member? "foo" '(4 5 #f "foo" a))
#t

But I'm getting the error:

> (is-member? "foo" '(4 5 #f "foo" a))
;string=?: contract violation
;  expected: string?
;  given: #f
;  argument position: 2nd
;  other arguments...:
;   "foo"

My definitions of is-member? and is-member-string? are:

#lang racket

(define (is-member? num lst)
  (if (null? lst)
      #f
      (if (string? num)
          (is-member-string? num lst)
          (is-member-number? num lst))))

(define (is-member-string? num lst)
  (if (null? lst)
      #f
      (if (integer? (car lst))
          (is-member-string? num (rest lst))
          (if (string=? (car lst) num)
              #t
              (is-member-string? num (rest lst))))))

(define (is-member-number? num lst)
  ....)

Body:
Look at the error message and see how it helps you. It says the error is coming from string=?, and if you look in DrRacket it even highlights the specific call that went wrong. It's the (string=? (car lst) num) in the is-member-string? function.

Figure out what arguments were and why they're wrong. The error message says that the wrong argument was #f where it expected a string.

Where did the bad argument come from? Was it num or (car lst)? Looking at how num flows through the program, num should always be "foo", so it's probably the other one, (car lst).

How did this code execute with that bad argument? Why is (car lst) false here? Because it's walking down the list, and the list contains a false in it. That should be fine, as long as you design your function properly to handle all values.

To do that, you should put a type signature on your functions to show what types of arguments are allowed. For is-member-string? I'm assuming you meant:

;; is-member-string? : String [List-of Any] -> Boolean
(define (is-member-string? str lst)
   ....)

(I've renamed num to str because it's not a number, it's a string.)

Next you need to make sure that the code works with the signature. You're designing this function by destructuring the list argument, but you need to keep the types of the values in mind:

;; is-member-string? : String [List-of Any] -> Boolean
(define (is-member-string? str lst)
  (if (null? lst)
      #f
      (.... (first lst) ; (first lst) is an Any
       .... (rest lst)))) ; (rest lst) is a [List-of Any]

(I'm using first instead of car because first makes more sense.)

Can you see what's wrong now?

;; is-member-string? : String [List-of Any] -> Boolean
(define (is-member-string? str lst)
  (if (null? lst)
      #f
      (if (integer? (first lst))             ; (first lst) is an Any
          (is-member-string? str (rest lst))
          (if (string=? (first lst) str)     ; (first lst) is an Any, but not an integer
              #t
              (is-member-string? str (rest lst))))))

(first lst) is an Any, but you're using (string=? (first lst) str). That shouldn't be allowed unless you're sure that (first lst) is a string.

There are two ways to do this. One way to fix this is to use (equal? (first lst) str) instead.

;; is-member-string? : String [List-of Any] -> Boolean
(define (is-member-string? str lst)
  (if (null? lst)
      #f
      (if (equal? (first lst) str)
          #t
          (is-member-string? str (rest lst)))))

The second way is to check that it's a string before you use string=?. I assume that's what you were trying to do with your integer? check, but it isn't working. Instead you want to use (string? (first lst)) somehow. You only want to check string=? after that passes. One way to do that is with and.

;; is-member-string? : String [List-of Any] -> Boolean
(define (is-member-string? str lst)
  (if (null? lst)
      #f
      (if (and (string? (first lst)) (string=? (first lst) str))
          #t
          (is-member-string? str (rest lst)))))


问:
How to get a word from an EditText?
I want the user to input a String word by phrase,

"animal" is a null String and I want to get it when the user enters the words after it or before it, I want to get that single word at its current position.

i.e.:

when I enter in my EditText "cat is an animal" the word "cat" will be saved in the list of animals, or "dog is an animal" and the word "dog" is saved, then the TextView says 'change to "ok"'.

```<code>public class MainActivity extends AppCompatActivity {

ArrayList<String> animal_names = new ArrayList<>();
String animal = null;
TextView say;
EditText enter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    say = (TextView) findViewById(R.id.textView);
    enter = (EditText) findViewById(R.id.editText);

    try {
        InputStream input = getAssets().open("animals names.txt");
        InputStreamReader rd = new InputStreamReader(input);
        BufferedReader br = new BufferedReader(rd);
        String line;
        while ((line = br.readLine()) != null) {
            animal_names.add(line);
        }

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

}

public void click(View view) {
    String s = enter.getText().toString().trim();
    if (s.equals(animal+" is an animal")){
        say.setText("ok");
        animal_names.add(animal);
    }else if (s.equals("is " + animal + "an animal" )){
        if (animal_names.contains(animal)){
            say.setText("yes");
        }else {
            say.setText("no");
        }
    }
}
</code>```

答: use text watcher and when the users string equals animal,,,save those letters in a new string inside text watcher</p>

Title: How to get a word from an EditText?

Body:
I want the user to input a String word by phrase,

"animal" is a null String and I want to get it when the user enters the words after it or before it, I want to get that single word at its current position.

i.e.:

when I enter in my EditText "cat is an animal" the word "cat" will be saved in the list of animals, or "dog is an animal" and the word "dog" is saved, then the TextView says 'change to "ok"'.

public class MainActivity extends AppCompatActivity {

ArrayList<String> animal_names = new ArrayList<>();
String animal = null;
TextView say;
EditText enter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    say = (TextView) findViewById(R.id.textView);
    enter = (EditText) findViewById(R.id.editText);

    try {
        InputStream input = getAssets().open("animals names.txt");
        InputStreamReader rd = new InputStreamReader(input);
        BufferedReader br = new BufferedReader(rd);
        String line;
        while ((line = br.readLine()) != null) {
            animal_names.add(line);
        }

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

}

public void click(View view) {
    String s = enter.getText().toString().trim();
    if (s.equals(animal+" is an animal")){
        say.setText("ok");
        animal_names.add(animal);
    }else if (s.equals("is " + animal + "an animal" )){
        if (animal_names.contains(animal)){
            say.setText("yes");
        }else {
            say.setText("no");
        }
    }
}


问:
@Bean annotation on a static method
Can anyone explain me why a @Bean on a static method is returning 2 different instances ?

I can understand that @Bean on a method non static like the class A is returning the same instance because default scope is singleton.

And If I try to inject the class B with @Autowire in a Service it won't work, so it looks like it's not load by the Spring App Context. So using a class like D will be similar !?
I think not because for @PropertySource we need to use in addition (used for the placeholder):

```<code>@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}
</code>```

and if we remove @Bean from this, it won't work.

Is there other use case where it would be useful to use @Bean on a static method?

EXAMPLE:

when I run:

```<code>@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {Conf.class})
public class Test {
    @org.junit.Test
    public void test(){
    }
}
</code>```

for

```<code>@Configuration
@ComponentScan
public class Conf {

    @Bean
    public A aaa(){
        return new A();
    }

    @Bean
    public static B bbb(){
        return new B();
    }

    @Bean
    @Scope("prototype")
    public C ccc(){
        return new C();
    }

    public static D ddd(){
        return new D();
    }

    @PostConstruct
    public void post(){
        System.out.println(aaa());
        System.out.println(aaa());
        System.out.println(bbb());
        System.out.println(bbb());
        System.out.println(ccc());
        System.out.println(ccc());
        System.out.println(ddd());
        System.out.println(ddd());
    }

}
public class A {
}
public class B {
}
public class C {
}
public class D {
}
</code>```

I get:

```<code>uk.co.xxx.unit.A@6caf0677
uk.co.xxx.unit.A@6caf0677
uk.co.xxx.unit.B@413d1baf
uk.co.xxx.unit.B@16eb3ea3
uk.co.xxx.unit.C@353352b6
uk.co.xxx.unit.C@4681c175
uk.co.xxx.unit.D@57a78e3
uk.co.xxx.unit.D@402c4085
</code>```

答:
@Bean  annotated methods get proxied in order to provide the correct bean instance. Static methods do not get proxied. Hence in your case bbb() invocation each time gives a new instance of B.

PropertySourcesPlaceholderConfigurer class is a special kind of bean since it implements BeanFactoryPostProcessor. In the container lifecycle, a BeanFactoryPostProcessor object must be instantiated earlier than an object of @Configuration-annotated class. Also you don't need to call this static method.

See Bootstrapping section in the java doc : [http://docs.spring.io/spring/docs/4.2.x/javadoc-api/org/springframework/context/annotation/Bean.html][1]

Special consideration must be taken for @Bean methods that return
  Spring BeanFactoryPostProcessor (BFPP) types. Because BFPP objects
  must be instantiated very early in the container lifecycle, they can
  interfere with processing of annotations such as @Autowired, @Value,
  and @PostConstruct within @Configuration classes. To avoid these
  lifecycle issues, mark BFPP-returning @Bean methods as static

Title: @Bean annotation on a static method

Body:
Can anyone explain me why a @Bean on a static method is returning 2 different instances ?

I can understand that @Bean on a method non static like the class A is returning the same instance because default scope is singleton.

And If I try to inject the class B with @Autowire in a Service it won't work, so it looks like it's not load by the Spring App Context. So using a class like D will be similar !?
I think not because for @PropertySource we need to use in addition (used for the placeholder):

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}

and if we remove @Bean from this, it won't work.

Is there other use case where it would be useful to use @Bean on a static method?

EXAMPLE:

when I run:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {Conf.class})
public class Test {
    @org.junit.Test
    public void test(){
    }
}

for

@Configuration
@ComponentScan
public class Conf {

    @Bean
    public A aaa(){
        return new A();
    }

    @Bean
    public static B bbb(){
        return new B();
    }

    @Bean
    @Scope("prototype")
    public C ccc(){
        return new C();
    }

    public static D ddd(){
        return new D();
    }

    @PostConstruct
    public void post(){
        System.out.println(aaa());
        System.out.println(aaa());
        System.out.println(bbb());
        System.out.println(bbb());
        System.out.println(ccc());
        System.out.println(ccc());
        System.out.println(ddd());
        System.out.println(ddd());
    }

}
public class A {
}
public class B {
}
public class C {
}
public class D {
}

I get:

uk.co.xxx.unit.A@6caf0677
uk.co.xxx.unit.A@6caf0677
uk.co.xxx.unit.B@413d1baf
uk.co.xxx.unit.B@16eb3ea3
uk.co.xxx.unit.C@353352b6
uk.co.xxx.unit.C@4681c175
uk.co.xxx.unit.D@57a78e3
uk.co.xxx.unit.D@402c4085


问:
How can building a heap be O(n) time complexity?
Can someone help explain how can building a heap be O(n) complexity?

Inserting an item into a heap is O(log n), and the insert is repeated n/2 times (the remainder are leaves, and can't violate the heap property). So, this means the complexity should be O(n log n), I would think.

In other words, for each item we "heapify", it has the potential to have to filter down (i.e., sift down) once for each level for the heap so far (which is log n levels).

What am I missing?

答:
@bcorso has already demonstrated the proof of the complexity analysis. But for the sake of those still learning complexity analysis, I have this to add:

The basis of your original mistake is due to a misinterpretation of the meaning of the statement, "insertion into a heap takes O(log n) time". Insertion into a heap is indeed O(log n), but you have to recognise that n is the size of the heap during the insertion.

In the context of inserting n objects into a heap, the complexity of the ith insertion is O(log n_i) where n_i is the size of the heap as at insertion i. Only the last insertion has a complexity of O (log n).

ContentLicense: CC BY-SA 4.0


问:
Partially completed text boxes and tombstoning in Windows Phone 7
When I use TwoWay data binding to a view model on a page, then from what I have observed, the view model is only updated when the focus leaves the field (eg. a TextBox). This behaviour matches the description in Updating the Data Source.

If the application is tombstoned, then most examples I've seen just persist the view model in the page state, and reload them if it is activated again.

From what I can see, this means that if the user hadn't caused focus to be lost from the text box they were editing, the current value isn't copied to the view model, and so it isn't saved.

Is that what a user (and also Microsoft's Application Certification process) would expect from a WP7 application?

答:
Saving partially entered text across tombstoning isn't a requirement for marketplace acceptance testing.

However, you should persist the data if it makes sense in the context of the application and that is what would give the best user experience.

DO NOT base your application experience on the way the framework synchronises data to a view model. Do what's best for the user.

If it made sense for the application to save this information, as a user, I would want it to and I woudn't care for whatever technical reason you gave for not doing this.

ContentLicense: CC BY-SA 2.5


问:
eliminate 3 backslashes with stripslashes
Out of some reasons after updating several things, on our wordpress site in the custom fields are automatically addes 3 backslashes before every apostrophe.
Example: src="abc" will result in src=\\\"abc\\\"

I've got a function in functions.php where I hook into the website. Now I need to remove those backslashes. This is the orignal function:

```<code>add_action('woocommerce_before_single_product', 'headline_placeholder');
function headline_placeholder () {
global $wp_query;
$postid = $wp_query->post->ID;
echo get_post_meta($postid, 'productheadline', true);
wp_reset_query();
}
</code>```

This is what I tried to remove the backslashes, but its only removing 2 backslashes, not all 3.

```<code>function removeslashes($string)
{
    $string=implode("",explode("\\",$string));
    return stripslashes(trim($string));
}

add_action('woocommerce_before_single_product', 'headline_placeholder');
function headline_placeholder () {
global $wp_query;
$postid = $wp_query->post->ID;
$meta = get_post_meta($postid, 'productheadline', true);
echo removeslashes($meta);
wp_reset_query();
}
</code>```

Where is the mistake?

答:
Maybe you can use str_replace, something like this:

```<code>function removesalshes($text) {
    return str_replace ( "///" , "", $text);
}
</code>```

Hope it helps!

Body:
Out of some reasons after updating several things, on our wordpress site in the custom fields are automatically addes 3 backslashes before every apostrophe.
Example: src="abc" will result in src=\\\"abc\\\"

I've got a function in functions.php where I hook into the website. Now I need to remove those backslashes. This is the orignal function:

add_action('woocommerce_before_single_product', 'headline_placeholder');
function headline_placeholder () {
global $wp_query;
$postid = $wp_query->post->ID;
echo get_post_meta($postid, 'productheadline', true);
wp_reset_query();
}

This is what I tried to remove the backslashes, but its only removing 2 backslashes, not all 3.

function removeslashes($string)
{
    $string=implode("",explode("\\",$string));
    return stripslashes(trim($string));
}

add_action('woocommerce_before_single_product', 'headline_placeholder');
function headline_placeholder () {
global $wp_query;
$postid = $wp_query->post->ID;
$meta = get_post_meta($postid, 'productheadline', true);
echo removeslashes($meta);
wp_reset_query();
}

Where is the mistake?

Body:
Maybe you can use str_replace, something like this:

function removesalshes($text) {
    return str_replace ( "///" , "", $text);
}

Hope it helps!


问:
Problems with "gam" smoothing in ggplot2
I am trying to use GAM smoothing in ggplot2. According to this conversation and this code, ggplot2 loads mgcv package used for general additive models only if n >= 1000. Otherwise a user has to manually load the package. As far as I understand this example code from the conversation should do the smoothing using geom_smooth(method="gam", formula = y ~ s(x, bs = "cs")):

```<code>library(ggplot2)
dat.large <- data.frame(x=rnorm(10000), y=rnorm(10000))
ggplot(dat.large, aes(x=x, y=y)) + geom_smooth()
</code>```

But I get an error:

```<code>geom_smooth: method="auto" and size of largest group is >=1000, so using gam with formula: y ~ s(x, bs = "cs"). Use 'method = x' to change the smoothing method.
Error in s(x, bs = "cs") : object 'x' not found
</code>```

The same error happens if I try following:

```<code>ggplot(dat.large, aes(x=x, y=y)) + geom_point() + geom_smooth(method="gam", formula = y ~ s(x, bs = "cs"))
</code>```

But for example linear model would work:

```<code>ggplot(dat.large, aes(x=x, y=y)) + geom_smooth(method = "lm", formula = y ~ x)
</code>```

What am I doing wrong here?

My R and package versions should be up-to-date:

```<code>R version 3.0.3 (2014-03-06)
Platform: x86_64-apple-darwin10.8.0 (64-bit)

other attached packages: mgcv_1.7-29  ggplot2_0.9.3.1
</code>```

答:
My problem was caused by a corrupt version of mgcv. Reinstalling this package solved the issue:

```<code>install.packages("mgcv")
</code>```

Versions:

Linux Mint 18 / 18.1

R 3.4.0

I had the same problem on two different Linux machines.

Body:
I am trying to use GAM smoothing in ggplot2. According to this conversation and this code, ggplot2 loads mgcv package used for general additive models only if n >= 1000. Otherwise a user has to manually load the package. As far as I understand this example code from the conversation should do the smoothing using geom_smooth(method="gam", formula = y ~ s(x, bs = "cs")):

library(ggplot2)
dat.large <- data.frame(x=rnorm(10000), y=rnorm(10000))
ggplot(dat.large, aes(x=x, y=y)) + geom_smooth()

But I get an error:

geom_smooth: method="auto" and size of largest group is >=1000, so using gam with formula: y ~ s(x, bs = "cs"). Use 'method = x' to change the smoothing method.
Error in s(x, bs = "cs") : object 'x' not found

The same error happens if I try following:

ggplot(dat.large, aes(x=x, y=y)) + geom_point() + geom_smooth(method="gam", formula = y ~ s(x, bs = "cs"))

But for example linear model would work:

ggplot(dat.large, aes(x=x, y=y)) + geom_smooth(method = "lm", formula = y ~ x)

What am I doing wrong here?

My R and package versions should be up-to-date:

R version 3.0.3 (2014-03-06)
Platform: x86_64-apple-darwin10.8.0 (64-bit)

other attached packages: mgcv_1.7-29  ggplot2_0.9.3.1

Body:
My problem was caused by a corrupt version of mgcv. Reinstalling this package solved the issue:

install.packages("mgcv")

Versions:

Linux Mint 18 / 18.1

R 3.4.0

I had the same problem on two different Linux machines.


问:
Pushing MailGun webhook onto AWS SQS
I need to process MailGun webhooks. I did implement a solution directly on our web servers to process the webhooks, but MailGun generates so many calls from a large campaign that it effectively becomes a DOS attack.

One solution I've been looking at is using AWS API Gateway to a Lambda function to then push onto an SQS queue. We can then poll the queue at a rate we can manage. Unfortunately we can't get this to work as AWS API Gateway does not support multipart/form-data content types (which some of the webhooks are). This means that our SQS messages are not well formatted / structured. The best we can do is use the $util.escapeJavaScript($input.body) function in the mapping template to create an SQS message that contains the raw string of the webhook content (with escaped javascript chars) that is effectively unparsable i.e. we can't get data out of it.

I've had a go at using Zapier to process the webhook and push directly on the SQS queue. This can parse the various content types effectively and create a nicely structured message for us, but the cost of the service is not viable.

Has anybody managed this problem in another way? Are there solutions to API Gateway not parsing the content properly? I've deliberately stayed away from MailGuns event polling API as it involves significant delays before the polled data can be 'trusted' (according to MailGun).

Basically, is there another way of getting a nicely parsed message from content types multipart/form-data and application/x-www-form-urlencoded onto the queue?

Any ideas would be much appreciated!

To add, this link higlights issues with APS Gateway and multipart\form-data content:
API Gateway - Post multipart\form-data

答:
As you've mentioned you can base64 encode in api gateway and call base64decode in the lambda function to retrieve the original payload (There are standard libraries in every language).

Also, note you can that you can use multipart form data for non file bodies.
Get non file body from multipart/form-data using AWS API Gateway and Lambda

Title: Pushing MailGun webhook onto AWS SQS


问:
AbstractController::DoubleRenderError in CommentsController#create
I have a little problem, this code works:

```<code>def create
  @article = Article.find(params[:article_id])
  if verify_recaptcha
    @comment = @article.comments.create(comment_params)
    redirect_to article_path(@article)
  else
    redirect_to article_path(@article)
  end
end
</code>```

Why this code does not work?:

```<code>def create
  @article = Article.find(params[:article_id])
  if verify_recaptcha
    @comment = @article.comments.create(comment_params)
    redirect_to article_path(@article)
  else
    render(
      html: "<script>alert('Recaptcha error!')</script>".html_safe,
      layout: 'application'
    )
    redirect_to article_path(@article)
  end
end
</code>```

I get this error:

AbstractController::DoubleRenderError in CommentsController#create
  Render and/or redirect were called multiple times in this action.

Please note that you may only call render or redirect, and at most once per action.

Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like redirect_to(...) and return.

答:
Don't combine render with redirect_to. You're already rendering the application.html.erb file as layout, and the html is the script you assigned.

If you want to use render you have to know that this one doesn't run any code in the target action, so, if you want to "reassign" the @article variable you'll have to use redirect_to, and if you want to add some message to notify the user then you can add a flash message, which you can display then in your view:

```<code>...
else
  flash[:error] = 'Recaptcha error!'
  redirect_to @article
end
</code>```

Then in your view:

```<code><% if flash[:error] %>
  <div class="error">
    <%= flash[:error] %>
  </div>
<% end %>
</code>```

Body:
I have a little problem, this code works:

def create
  @article = Article.find(params[:article_id])
  if verify_recaptcha
    @comment = @article.comments.create(comment_params)
    redirect_to article_path(@article)
  else
    redirect_to article_path(@article)
  end
end

Why this code does not work?:

def create
  @article = Article.find(params[:article_id])
  if verify_recaptcha
    @comment = @article.comments.create(comment_params)
    redirect_to article_path(@article)
  else
    render(
      html: "".html_safe,
      layout: 'application'
    )
    redirect_to article_path(@article)
  end
end

I get this error:

AbstractController::DoubleRenderError in CommentsController#create
  Render and/or redirect were called multiple times in this action.

Please note that you may only call render or redirect, and at most once per action.

Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like redirect_to(...) and return.

Body:
Don't combine render with redirect_to. You're already rendering the application.html.erb file as layout, and the html is the script you assigned.

If you want to use render you have to know that this one doesn't run any code in the target action, so, if you want to "reassign" the @article variable you'll have to use redirect_to, and if you want to add some message to notify the user then you can add a flash message, which you can display then in your view:

...
else
  flash[:error] = 'Recaptcha error!'
  redirect_to @article
end

Then in your view:

<% if flash[:error] %>
  <div class="error">
    <%= flash[:error] %>
  </div>
<% end %>


问:
How do I create a nested dictionary under a key that is yet to exist?
I have an empty array.

I want to assign a value like this: array[key][subkey] = 'value'

This produces a KeyError as array[key] does not exist yet.

What do I do? I tried the following...

```<code>array['key'] = None
array['key']['subkey'] = 'value'
</code>```

TypeError: 'NoneType' object does not support item assignment

I tried:

```<code>array['key'] = []
array['key']['subkey'] = 'value'
</code>```

TypeError: list indices must be integers, not str

I tried:

```<code>array['key'] = ['subkey']
array['key']['subkey'] = 'value'
</code>```

TypeError: list indices must be integers, not str

So what do I do?

答:
Can the below codes be used as a different method?</p>

```<code>>>> array = {}
>>> array["key"] = {"subkey": "value"}
>>> array
{'key': {'subkey': 'value'}}
>>>
</code>```

Body:
I have an empty array.

I want to assign a value like this: array[key][subkey] = 'value'

This produces a KeyError as array[key] does not exist yet.

What do I do? I tried the following...

array['key'] = None
array['key']['subkey'] = 'value'

TypeError: 'NoneType' object does not support item assignment

I tried:

array['key'] = []
array['key']['subkey'] = 'value'

TypeError: list indices must be integers, not str

I tried:

array['key'] = ['subkey']
array['key']['subkey'] = 'value'

TypeError: list indices must be integers, not str

So what do I do?

Body:
Can the below codes be used as a different method?

>>> array = {}
>>> array["key"] = {"subkey": "value"}
>>> array
{'key': {'subkey': 'value'}}
>>>


问:
How to customize the APK file name for product flavors?
I am customizing the name of the APK file of my Android application within the build.gradle script as follows:

android {
    defaultConfig {
        project.ext.set("archivesBaseName", "MyApplication");
    }
}
```

<p>Now that I am using product flavors:</p>

<pre class="lang-groovy prettyprint-override"><code>android {
    productFlavors {
        green {
            applicationId "com.example.myapplication.green"
        }

        blue {
            applicationId "com.example.myapplication.blue"
        }
    }
}
</code>```

Is there a way to customize the name of each APK? I experimented with archiveBaseName and baseName without success. In the end I want to come up with the following files:

```<code>build/outputs/apk/Blue-debug-1.2.1.apk
build/outputs/apk/Blue-debug-unaligned.apk
build/outputs/apk/Blue-release-1.2.1.apk
build/outputs/apk/Blue-release-unaligned.apk
build/outputs/apk/Green-debug-1.2.1.apk
build/outputs/apk/Green-debug-unaligned.apk
build/outputs/apk/Green-release-1.2.1.apk
build/outputs/apk/Green-release-unaligned.apk
</code>```

答:
Here's my variant (heh) of Lakshman's answer above, not sure why I needed the "variants.outputs.each" but I did.</p>

```<code>defaultConfig {
    applicationId "my.company.com"
    minSdkVersion 16
    targetSdkVersion 25
    applicationVariants.all { variant ->
        if (variant.productFlavors[0].name.equals("VariantA")) {
            variant.outputs.each { output ->
                def apk = output.outputFile;
                output.outputFile = new File(apk.parentFile, "Blue.apk");
            }
        } else { // Only two variants
            variant.outputs.each { output ->
                def apk = output.outputFile;
                output.outputFile = new File(apk.parentFile, "Green.apk");
            }
        }
    }
}
</code>```

Body:
I am customizing the name of the APK file of my Android application within the build.gradle script as follows:

android {
    defaultConfig {
        project.ext.set("archivesBaseName", "MyApplication");
    }
}

Now that I am using product flavors:

android {
    productFlavors {
        green {
            applicationId "com.example.myapplication.green"
        }

        blue {
            applicationId "com.example.myapplication.blue"
        }
    }
}

Is there a way to customize the name of each APK? I experimented with archiveBaseName and baseName without success. In the end I want to come up with the following files:

build/outputs/apk/Blue-debug-1.2.1.apk
build/outputs/apk/Blue-debug-unaligned.apk
build/outputs/apk/Blue-release-1.2.1.apk
build/outputs/apk/Blue-release-unaligned.apk
build/outputs/apk/Green-debug-1.2.1.apk
build/outputs/apk/Green-debug-unaligned.apk
build/outputs/apk/Green-release-1.2.1.apk
build/outputs/apk/Green-release-unaligned.apk

Body:
Here's my variant (heh) of Lakshman's answer above, not sure why I needed the "variants.outputs.each" but I did.

defaultConfig {
    applicationId "my.company.com"
    minSdkVersion 16
    targetSdkVersion 25
    applicationVariants.all { variant ->
        if (variant.productFlavors[0].name.equals("VariantA")) {
            variant.outputs.each { output ->
                def apk = output.outputFile;
                output.outputFile = new File(apk.parentFile, "Blue.apk");
            }
        } else { // Only two variants
            variant.outputs.each { output ->
                def apk = output.outputFile;
                output.outputFile = new File(apk.parentFile, "Green.apk");
            }
        }
    }
}


问:
How to get current Location in GoogleMap using FusedLocationProviderClient
I want to get periodic (say every 2 minutes) current location updates for this I'm following official documentation, I wrote this code but its not giving current location updates every two minutes even specified in LocationRequest object that I'm passing in requestLocationUpdates(), here is code:</p>

```<code>public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
    GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{

private FusedLocationProviderClient FusedLocationClient;
private GoogleApiClient mGoogleApiClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

 SupportMapFragment map =
  getSupportFragmentManager().findFragmentById(R.id.map));

  map.getMapAsync(this);

  FusedLocationClient LocationServices.getFusedLocationProviderClient(this);
}

@Override
public void onConnected(Bundle bundle) {
    FusedLocationClient.getLastLocation()
            .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {

                    if (location != null) {
                        Log.i("MainActivity ", "" + location.getLongitude())
                    }
                }
            });
FusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
FusedLocationClient.requestLocationUpdates(requestLocation(),
new LocationCallback(){
        @Override
        public void onLocationResult(LocationResult locationResult) {
            for (Location location : locationResult.getLocations()) {
               Log.i("MainActivity ", "" + location.getLongitude());
               //not getting current location updates every 2 minutes
            }
        };

    },null);

}

@Override
public void onConnectionSuspended(int i) {}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {}
</code>```

答:
```<code>    private LocationRequest locationRequest;

    public class MapsActivity extends FragmentActivity implements LocationListener{

    locationRequest = new LocationRequest();
    locationRequest.setInterval(60 * 1000);
    locationRequest.setFastestInterval(15 * 1000);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

@Override
public void onLocationChanged(Location location) {

    latitude = location.getLatitude();
    longitude = location.getLongitude();

}
</code>```

Implement Location change listener and you will be able to override onlocation changed...

Body:
I want to get periodic (say every 2 minutes) current location updates for this I'm following official documentation, I wrote this code but its not giving current location updates every two minutes even specified in LocationRequest object that I'm passing in requestLocationUpdates(), here is code:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
    GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{

private FusedLocationProviderClient FusedLocationClient;
private GoogleApiClient mGoogleApiClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

 SupportMapFragment map =
  getSupportFragmentManager().findFragmentById(R.id.map));

  map.getMapAsync(this);

  FusedLocationClient LocationServices.getFusedLocationProviderClient(this);
}

@Override
public void onConnected(Bundle bundle) {
    FusedLocationClient.getLastLocation()
            .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {

                    if (location != null) {
                        Log.i("MainActivity ", "" + location.getLongitude())
                    }
                }
            });
FusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
FusedLocationClient.requestLocationUpdates(requestLocation(),
new LocationCallback(){
        @Override
        public void onLocationResult(LocationResult locationResult) {
            for (Location location : locationResult.getLocations()) {
               Log.i("MainActivity ", "" + location.getLongitude());
               //not getting current location updates every 2 minutes
            }
        };

    },null);

}

@Override
public void onConnectionSuspended(int i) {}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {}

Body:
    private LocationRequest locationRequest;

    public class MapsActivity extends FragmentActivity implements LocationListener{

    locationRequest = new LocationRequest();
    locationRequest.setInterval(60 * 1000);
    locationRequest.setFastestInterval(15 * 1000);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

@Override
public void onLocationChanged(Location location) {

    latitude = location.getLatitude();
    longitude = location.getLongitude();

}

Implement Location change listener and you will be able to override onlocation changed...


问:
page reload not triggering document ready
The following td is updated on 1st page load by the javascript to yeild the result below (i.e.it all works).
However when pagination links are called the document ready is not called & thus the date not re written.
Ive tried various things but dont seam to get it working. On page rewriting the attribute is updated server side.
There are no ajax calls, the pagination link is just a simple url reloading the same page but with the query path changed. I understand the reload behaviour is normal - i just cant workaround it.

Any Ideas please to invoke my initialise call on subsequent loads?

```<code><td class="date" data-time="1499543100110"></td>

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

function initialise() {
    $(".date").each(function(){
        var millisec = parseInt($(this).attr("data-time"));
        var ts = moment(new Date(millisec)).format("MMMM Do YYYY, h:mm:ss a");
        $(this).text(ts);
    });
}

<a href="?page=6&size=20&criteria=" data-ajax-load="#ajaxload">7</a>
</code>```

output

```<code><td class="date" data-time="1499543100110">July 8th 2017, 8:45:00 pm</td>
</code>```

update

As was suggested below there was more to the issue. The pagination link was being captured & the request was being issued by ajax, bypassing all the normal js hooks. I removed the capture below & every thing works as expected. The network url traffic looked like straight forward page-load but was in fact an ajax call.

```<code>$(document).on('click', 'a[data-ajax-load]', function(event) {
    var _url = $(event.target).attr('href');
    var _target = $(event.target).data('ajax-load');
    $(_target).load(_Url + ' ' + _target,
        function(response, status, xhr) {
            // display errors etc
        }
    );
    return false;
});
</code>```

The answers below are all probably correct, but did not need to explore them - thanks for guidance.

答:
You can try using 'onload' on your body tag as follows:

```<code><body onload="myFunction()">
  //Code
</body>
</code>```

What this does is that it waits for the tag, in this case the  tag, to fully load before executing the function (myFunction() in this case.)

Your edited code should look something like this or something similar:

```<code><body onload="initialise()">
  <td class="date" data-time="1499543100110"></td>

  function initialise() {
    $(".date").each(function(){
      var millisec = parseInt($(this).attr("data-time"));
      var ts = moment(new Date(millisec)).format("MMMM Do YYYY, h:mm:ss
    a");
      $(this).text(ts);
    });
  }

  <a href="?page=6&size=20&criteria=" data-ajax load="#ajaxload">7</a>
</body>
</code>```

Edit: After some online researching, I found this:

You can use the JavaScript body.onload() function as well to stimulate a similar effect as follows:

```<code>body.onload(initialise);
</code>```

I am not an expert in jQuery, but looking at your code, I assume that you can also do this though I'm not sure:

```<code>$(body).onload(function () {
  initialise();
});
</code>```

Body:
The following td is updated on 1st page load by the javascript to yeild the result below (i.e.it all works).
However when pagination links are called the document ready is not called & thus the date not re written.
Ive tried various things but dont seam to get it working. On page rewriting the attribute is updated server side.
There are no ajax calls, the pagination link is just a simple url reloading the same page but with the query path changed. I understand the reload behaviour is normal - i just cant workaround it.

Any Ideas please to invoke my initialise call on subsequent loads?

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

function initialise() {
    $(".date").each(function(){
        var millisec = parseInt($(this).attr("data-time"));
        var ts = moment(new Date(millisec)).format("MMMM Do YYYY, h:mm:ss a");
        $(this).text(ts);
    });
}

7

output

July 8th 2017, 8:45:00 pm

update

As was suggested below there was more to the issue. The pagination link was being captured & the request was being issued by ajax, bypassing all the normal js hooks. I removed the capture below & every thing works as expected. The network url traffic looked like straight forward page-load but was in fact an ajax call.

$(document).on('click', 'a[data-ajax-load]', function(event) {
    var _url = $(event.target).attr('href');
    var _target = $(event.target).data('ajax-load');
    $(_target).load(_Url + ' ' + _target,
        function(response, status, xhr) {
            // display errors etc
        }
    );
    return false;
});

The answers below are all probably correct, but did not need to explore them - thanks for guidance.

Body:
You can try using 'onload' on your body tag as follows:

<body onload="myFunction()">
  //Code
</body>

What this does is that it waits for the tag, in this case the <body> tag, to fully load before executing the function (myFunction() in this case.)

Your edited code should look something like this or something similar:

<body onload="initialise()">
  <td class="date" data-time="1499543100110"></td>

  function initialise() {
    $(".date").each(function(){
      var millisec = parseInt($(this).attr("data-time"));
      var ts = moment(new Date(millisec)).format("MMMM Do YYYY, h:mm:ss
    a");
      $(this).text(ts);
    });
  }

  <a href="?page=6&amp;size=20&amp;criteria=" data-ajax load="#ajaxload">7</a>
</body>

Edit: After some online researching, I found this:

You can use the JavaScript body.onload() function as well to stimulate a similar effect as follows:

body.onload(initialise);

I am not an expert in jQuery, but looking at your code, I assume that you can also do this though I'm not sure:

$(body).onload(function () {
  initialise();
});


问:
Gulp uglify unable to handle arrow functions
I'm trying to compress my project using gulp-uglify, however gulp seems to throw the error Unexpected token: punc () whenever it encounters an arrow function in the code. Is there anything I can do to fix this? Thank you.

gulp-crash-test.js

```<code>// Function with callback to simulate the real code
function test(callback) {
    if (typeof callback === "function") callback();
}

// Causes a crash
test(() => {
    console.log("Test ran successfully!");
});

// Doesn't cause a crash
test(function () {
    console.log("Test ran successfully!");
});
</code>```

gulpfile.js

```<code>var gulp = require("gulp");
var concat = require("gulp-concat");
var uglify = require("gulp-uglify");

gulp.task("scripts", function() {
    gulp.src([
        "./gulp-crash-test.js"
    ]).pipe(
        concat("gulp-crash-test.min.js")
    ).pipe(
        uglify().on('error', function(e){
            console.log(e);
        })
    ).pipe(
        gulp.dest("./")
    );
});

gulp.task("watch", function() {
    gulp.watch("./gulp-crash-test.js", ["scripts"]);
});

gulp.task("default", ["watch", "scripts"]);
</code>```

答:
I tried babeli it kinda sucked. build time took me 40s. And I am not looking to transpile the code into es5 anyway

I prefer using uglify-es follow the descriptions
https://www.npmjs.com/package/uglify-es
https://www.npmjs.com/package/gulp-uglify

My build times are now 10s. I have the patience to wait 10s.

This is my gulpfile

```<code>var gulp = require('gulp');
var uglifycss = require('gulp-uglifycss');
var htmlminifier = require('gulp-html-minifier');
var useref = require('gulp-useref');
var gulpif = require('gulp-if');
var clean = require('gulp-clean');
var uglifyes = require('uglify-es');
var composer = require('gulp-uglify/composer');
var minifyes = composer(uglifyes, console);

.pipe(gulpif('*.js', minifyes()))
</code>```

Body:
I'm trying to compress my project using gulp-uglify, however gulp seems to throw the error Unexpected token: punc () whenever it encounters an arrow function in the code. Is there anything I can do to fix this? Thank you.

gulp-crash-test.js

// Function with callback to simulate the real code
function test(callback) {
    if (typeof callback === "function") callback();
}

// Causes a crash
test(() => {
    console.log("Test ran successfully!");
});

// Doesn't cause a crash
test(function () {
    console.log("Test ran successfully!");
});

gulpfile.js

var gulp = require("gulp");
var concat = require("gulp-concat");
var uglify = require("gulp-uglify");

gulp.task("scripts", function() {
    gulp.src([
        "./gulp-crash-test.js"
    ]).pipe(
        concat("gulp-crash-test.min.js")
    ).pipe(
        uglify().on('error', function(e){
            console.log(e);
        })
    ).pipe(
        gulp.dest("./")
    );
});

gulp.task("watch", function() {
    gulp.watch("./gulp-crash-test.js", ["scripts"]);
});

gulp.task("default", ["watch", "scripts"]);

Body:
I tried babeli it kinda sucked. build time took me 40s. And I am not looking to transpile the code into es5 anyway

I prefer using uglify-es follow the descriptions
https://www.npmjs.com/package/uglify-es
https://www.npmjs.com/package/gulp-uglify

My build times are now 10s. I have the patience to wait 10s.

This is my gulpfile

var gulp = require('gulp');
var uglifycss = require('gulp-uglifycss');
var htmlminifier = require('gulp-html-minifier');
var useref = require('gulp-useref');
var gulpif = require('gulp-if');
var clean = require('gulp-clean');
var uglifyes = require('uglify-es');
var composer = require('gulp-uglify/composer');
var minifyes = composer(uglifyes, console);

.pipe(gulpif('*.js', minifyes()))


问:
Date in dygraph (using R and xts) shows one day earlier than data
This is my first stackoverflow question, so apologies in advance for any lapses in etiquette or presentation.

I am using the dygraphs() package in R (3.3.3 on a Mac running Mavericks, using RStudio) to graph a time series of box-office receipts from an 18th-century theater. The dates run from 1789-04-14 to 1791-03-07. I'm using the newest version of the xts package (0.10-0), but the problem was identical in the previous version. As an xts object the data looks like this:

```<code>head(receipts.xts)
              kr
1789-04-14 15454
1789-04-20  6985
1789-04-22  4545
1789-04-24  5342
1789-04-26  5791
1789-04-28 25139
</code>```

The dates imported for the index are of type date.
('kr' stands for 'kreuzer,' a subdivision of the monetary unit of account at the time.)

The code to create the dygraph is:

```<code>dygraph(receipts.xts,
        main = "Opera Receipts, Burgtheater, 1789-1791") %>%
  dySeries("kr", label = "Receipts (kr)") %>%
  dyLegend(show="always", hideOnMouseOut =FALSE) %>% dyRangeSelector()
</code>```

All dates in the legend show one day earlier than the corresponding date in the xts object. This is shown in the attached screenshot, where the first datapoint is 1789-04-14, but shows in the RStudio viewer in the legend as "Apr, 13, 1789" (I have not been able to find a way to get rid of the unwanted comma after the month abbreviation.)

Oddly, when I save this graph as html, the legend on the webpage shows the correct date!

I've tried a very wide variety of possible solutions, but nothing so far has worked. This looks like a bug, but it's not clear to me where the bug is (in the dygraphs package? in RStudio? in xts?). My question seems similar to this one:

Date bug in dygraph in dygraphs package (using JavaScript) in R

But that question seems never to have had a definitive answer. The only way I can get the proper dates to display in the legends in the RStudio viewer is to add one day to all the dates (using lubridate) that are used as the index of the xts object, but then the dates are incorrect in the html.

**** Edit on 7/10/17 in response to Dirk's reply ****

I'd already been aware of the potential of the "hidden" timezone problem with the dates, and had tried a number of other approaches to fix that, although not yet setting the timezone with Sys.setenv() as Dirk suggested. I just tried that, and it doesn't fix the problem either.  My steps this time were:

```<code>operas$Date <- as.character(operas$Date)
Sys.setenv(tz="UTC")
receipts.xts <- xts(operas$Receipts, as.Date(operas$Date))
colnames(receipts.xts) <- "kr"
</code>```

(In the originating dataframe the dates are already of date type, but I wanted to start from scratch in showing this problem.) The dygraphs code is then the same as in my original example.

The results are identical: dates in the legend are one day too early when examined in the RStudio viewer, but are correct in the exported html when viewed in a browser.

So it looks like the problem is probably somewhere else.

The use of lubridate's as_date() in my original example only reflected one of my more recent attempts at a fix. My original code had used as.Date(). But thanks for the pointer.

**** Some sample data ****

```<code>> dput(receipts.test)
structure(list(Date = c("1789-04-14", "1789-04-20", "1789-04-22",
"1789-04-24", "1789-04-26", "1789-04-28", "1789-04-30", "1789-05-02",
"1789-05-04", "1789-05-06"), Receipts = c(15454L, 6985L, 4545L,
5342L, 5791L, 25139L, 6897L, 4268L, 2400L, 4515L)), .Names = c("Date",
"Receipts"), row.names = c(NA, 10L), class = c("tbl_df", "tbl",
"data.frame"))
</code>```

答:
So let's do a little tutorial. Start with a date, convert to a POSIXct and then format:

```<code>R> format(as.POSIXct(as.Date("2017-07-08")))
[1] "2017-07-07 19:00:00"
R>
</code>```

See what happens? I am in Chicago, and the five hours subtracted from midnight are my offset to UTC.  One possible fix is to set the timezone to UTC:

```<code>R> Sys.setenv(TZ="UTC")
R> format(as.POSIXct(as.Date("2017-07-08")))
[1] "2017-07-08"
R>
</code>```

Now the same input data is correctly "printed" as the same date.

Lesson: Be wary of Date to POSIXct conversions.  All you needed here is the proper timezone (for the context of the formatting).

Lastly, you really do not need the lubridate package to adjust a date.  R itself does that just fine:

```<code>R> as.Date("2017-07-08")
[1] "2017-07-08"
R> as.Date("2017-07-08") + 1:3
[1] "2017-07-09" "2017-07-10" "2017-07-11"
R>
</code>```

Dates and times are challenging for programmers and users. R has great support. Take your time and learn it, one issue at a time.

Edit: Ok, after I got dragged into this again, here are code and a chart.

Code

```<code>d <- structure(list(Date = c("1789-04-14", "1789-04-20", "1789-04-22",
                             "1789-04-24", "1789-04-26", "1789-04-28",
                             "1789-04-30", "1789-05-02",
                             "1789-05-04", "1789-05-06"),
                   Receipts = c(15454L, 6985L, 4545L, 5342L, 5791L, 25139L,
                                6897L, 4268L, 2400L, 4515L)),
            .Names = c("Date", "Receipts"),
            row.names = c(NA, 10L),
            class = c("tbl_df", "tbl", "data.frame"))

library(xts)
x <- xts(d[,2, drop=FALSE], order.by=as.Date(d[,1]))

library(dygraphs)
dygraph(x)
</code>```

This is the structure as posted, quickly converted to an xts using Date as the index type.

And we're done. As the chart shows, the first observation is shown as April 14 just as it should.

Hope this helps.

Chart

Data

Body:
This is my first stackoverflow question, so apologies in advance for any lapses in etiquette or presentation.

I am using the dygraphs() package in R (3.3.3 on a Mac running Mavericks, using RStudio) to graph a time series of box-office receipts from an 18th-century theater. The dates run from 1789-04-14 to 1791-03-07. I'm using the newest version of the xts package (0.10-0), but the problem was identical in the previous version. As an xts object the data looks like this:

head(receipts.xts)
              kr
1789-04-14 15454
1789-04-20  6985
1789-04-22  4545
1789-04-24  5342
1789-04-26  5791
1789-04-28 25139

The dates imported for the index are of type date.
('kr' stands for 'kreuzer,' a subdivision of the monetary unit of account at the time.)

The code to create the dygraph is:

dygraph(receipts.xts,
        main = "Opera Receipts, Burgtheater, 1789-1791") %>%
  dySeries("kr", label = "Receipts (kr)") %>%
  dyLegend(show="always", hideOnMouseOut =FALSE) %>% dyRangeSelector()

All dates in the legend show one day earlier than the corresponding date in the xts object. This is shown in the attached screenshot, where the first datapoint is 1789-04-14, but shows in the RStudio viewer in the legend as "Apr, 13, 1789" (I have not been able to find a way to get rid of the unwanted comma after the month abbreviation.)

Oddly, when I save this graph as html, the legend on the webpage shows the correct date!

I've tried a very wide variety of possible solutions, but nothing so far has worked. This looks like a bug, but it's not clear to me where the bug is (in the dygraphs package? in RStudio? in xts?). My question seems similar to this one:

Date bug in dygraph in dygraphs package (using JavaScript) in R

But that question seems never to have had a definitive answer. The only way I can get the proper dates to display in the legends in the RStudio viewer is to add one day to all the dates (using lubridate) that are used as the index of the xts object, but then the dates are incorrect in the html.

**** Edit on 7/10/17 in response to Dirk's reply ****

I'd already been aware of the potential of the "hidden" timezone problem with the dates, and had tried a number of other approaches to fix that, although not yet setting the timezone with Sys.setenv() as Dirk suggested. I just tried that, and it doesn't fix the problem either.  My steps this time were:

operas$Date <- as.character(operas$Date)
Sys.setenv(tz="UTC")
receipts.xts <- xts(operas$Receipts, as.Date(operas$Date))
colnames(receipts.xts) <- "kr"

(In the originating dataframe the dates are already of date type, but I wanted to start from scratch in showing this problem.) The dygraphs code is then the same as in my original example.

The results are identical: dates in the legend are one day too early when examined in the RStudio viewer, but are correct in the exported html when viewed in a browser.

So it looks like the problem is probably somewhere else.

The use of lubridate's as_date() in my original example only reflected one of my more recent attempts at a fix. My original code had used as.Date(). But thanks for the pointer.

**** Some sample data ****

> dput(receipts.test)
structure(list(Date = c("1789-04-14", "1789-04-20", "1789-04-22",
"1789-04-24", "1789-04-26", "1789-04-28", "1789-04-30", "1789-05-02",
"1789-05-04", "1789-05-06"), Receipts = c(15454L, 6985L, 4545L,
5342L, 5791L, 25139L, 6897L, 4268L, 2400L, 4515L)), .Names = c("Date",
"Receipts"), row.names = c(NA, 10L), class = c("tbl_df", "tbl",
"data.frame"))

Body:
So let's do a little tutorial. Start with a date, convert to a POSIXct and then format:

R> format(as.POSIXct(as.Date("2017-07-08")))
[1] "2017-07-07 19:00:00"
R>

See what happens? I am in Chicago, and the five hours subtracted from midnight are my offset to UTC.  One possible fix is to set the timezone to UTC:

R> Sys.setenv(TZ="UTC")
R> format(as.POSIXct(as.Date("2017-07-08")))
[1] "2017-07-08"
R>

Now the same input data is correctly "printed" as the same date.

Lesson: Be wary of Date to POSIXct conversions.  All you needed here is the proper timezone (for the context of the formatting).

Lastly, you really do not need the lubridate package to adjust a date.  R itself does that just fine:

R> as.Date("2017-07-08")
[1] "2017-07-08"
R> as.Date("2017-07-08") + 1:3
[1] "2017-07-09" "2017-07-10" "2017-07-11"
R>

Dates and times are challenging for programmers and users. R has great support. Take your time and learn it, one issue at a time.

Edit: Ok, after I got dragged into this again, here are code and a chart.

Code

d <- structure(list(Date = c("1789-04-14", "1789-04-20", "1789-04-22",
                             "1789-04-24", "1789-04-26", "1789-04-28",
                             "1789-04-30", "1789-05-02",
                             "1789-05-04", "1789-05-06"),
                   Receipts = c(15454L, 6985L, 4545L, 5342L, 5791L, 25139L,
                                6897L, 4268L, 2400L, 4515L)),
            .Names = c("Date", "Receipts"),
            row.names = c(NA, 10L),
            class = c("tbl_df", "tbl", "data.frame"))

library(xts)
x <- xts(d[,2, drop=FALSE], order.by=as.Date(d[,1]))

library(dygraphs)
dygraph(x)

This is the structure as posted, quickly converted to an xts using Date as the index type.

And we're done. As the chart shows, the first observation is shown as April 14 just as it should.

Hope this helps.

Chart

Data


问:
How to use forEach to alter an array
What code is required to instruct forEach() to make a permanent change to an array?

For example in the following simple code I add the phrase, "this is my " to each item in the array. According to the console log the changes were made.  But when I run the console again on the main timeline the changes weren't permanently saved to the array.  I'm sure I'm missing something simple but I can't see it.

var myArray = [];

myArray.push("dog");
myArray.push("cat");
myArray.push("mouse");

console.log(myArray);

myArray.forEach(myFunction);

function myFunction(item) {
    item = "this is my " +item;
    console.log(item);
}

console.log(myArray);```

答:
forEach() does not mutate the array on which it is called (although
  callback, if invoked, may do so).

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Go with Map:

var myArray = [];

myArray.push("dog");
myArray.push("cat");
myArray.push("mouse");

const myArrayChanged = myArray.map(myFunction);

function myFunction(item) {
    return "this is my " + item;
}

console.log(myArray);
console.log(myArrayChanged);```
</div>
</div>
</p>

<p>But, properly answering your question about how to do it using <code>forEach</code>, here it goes:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var myArray = [];

myArray.push("dog");
myArray.push("cat");
myArray.push("mouse");

console.log(myArray);

myArray.forEach(myFunction);
function myFunction(item, i, arr) {
    return arr[i] = "this is my " + item;
}

console.log(myArray);</code>```

Title: How to use forEach to alter an array

Body:
forEach() does not mutate the array on which it is called (although
  callback, if invoked, may do so).

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Go with Map:

var myArray = [];

myArray.push("dog");
myArray.push("cat");
myArray.push("mouse");

const myArrayChanged = myArray.map(myFunction);

function myFunction(item) {
    return "this is my " + item;
}

console.log(myArray);
console.log(myArrayChanged);

But, properly answering your question about how to do it using forEach, here it goes:

var myArray = [];

myArray.push("dog");
myArray.push("cat");
myArray.push("mouse");

console.log(myArray);

myArray.forEach(myFunction);
function myFunction(item, i, arr) {
    return arr[i] = "this is my " + item;
}

console.log(myArray);


问:
AWS Code Star Express API Enable CORS and Integration Response
I am using AWS Code star and using Express Web service template. Code star create Lambda and create API Gateway API. The api works, it returns what I want. I am trying to enable to CORS, through API gateway,

API GateWay -> API -> resouce -> Actions -> Enable CORS.

It fails on setting CORS on options as integration response is not generated for proxy.  Here are the images.

I think I have to configure this through YAML to generate integration response on options and GET.

Here is my YAML

```<code>    AWSTemplateFormatVersion: 2010-09-09
Transform:
- AWS::Serverless-2016-10-31
- AWS::CodeStar

Parameters:
  ProjectId:
    Type: String
    Description: AWS CodeStar projectID used to associate new resources to team members

Resources:
  HelloWorld:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: nodejs4.3
      Role:
        Fn::ImportValue:
          !Join ['-', [!Ref 'ProjectId', !Ref 'AWS::Region', 'LambdaTrustRole']]
      Events:
        GetEvent:
          Type: Api
          Properties:
            Path: /
            Method: get
  GetById:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: nodejs4.3
      Role:
        Fn::ImportValue:
          !Join ['-', [!Ref 'ProjectId', !Ref 'AWS::Region', 'LambdaTrustRole']]
      Events:
        GetEvent:
          Type: Api
          Properties:
            Path: /api/getById
            Method: get
</code>```

Here is my Lambda Handler.

```<code>    'use strict';

const awsServerlessExpress = require('aws-serverless-express')
const app = require('./app')
const server = awsServerlessExpress.createServer(app)

exports.handler = (event, context) => awsServerlessExpress.proxy(server, event, context);
</code>```

I would appreciate if some one can help me how can i adjust the CloudFormation Template.

答:
You cannot add headers to a integration response for proxy integrations. You will need to add the CORS headers in the response from lambda as

```<code>{
    "isBase64Encoded": true|false,
    "statusCode": httpStatusCode,
    "headers": { "headerName": "headerValue", ... },
    "body": "..."
}
</code>```

http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html#api-gateway-simple-proxy-for-lambda-output-format

Body:
I am using AWS Code star and using Express Web service template. Code star create Lambda and create API Gateway API. The api works, it returns what I want. I am trying to enable to CORS, through API gateway,

API GateWay -> API -> resouce -> Actions -> Enable CORS.

It fails on setting CORS on options as integration response is not generated for proxy.  Here are the images.

I think I have to configure this through YAML to generate integration response on options and GET.

Here is my YAML

    AWSTemplateFormatVersion: 2010-09-09
Transform:
- AWS::Serverless-2016-10-31
- AWS::CodeStar

Parameters:
  ProjectId:
    Type: String
    Description: AWS CodeStar projectID used to associate new resources to team members

Resources:
  HelloWorld:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: nodejs4.3
      Role:
        Fn::ImportValue:
          !Join ['-', [!Ref 'ProjectId', !Ref 'AWS::Region', 'LambdaTrustRole']]
      Events:
        GetEvent:
          Type: Api
          Properties:
            Path: /
            Method: get
  GetById:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: nodejs4.3
      Role:
        Fn::ImportValue:
          !Join ['-', [!Ref 'ProjectId', !Ref 'AWS::Region', 'LambdaTrustRole']]
      Events:
        GetEvent:
          Type: Api
          Properties:
            Path: /api/getById
            Method: get

Here is my Lambda Handler.

    'use strict';

const awsServerlessExpress = require('aws-serverless-express')
const app = require('./app')
const server = awsServerlessExpress.createServer(app)

exports.handler = (event, context) => awsServerlessExpress.proxy(server, event, context);

I would appreciate if some one can help me how can i adjust the CloudFormation Template.

Body:
You cannot add headers to a integration response for proxy integrations. You will need to add the CORS headers in the response from lambda as

{
    "isBase64Encoded": true|false,
    "statusCode": httpStatusCode,
    "headers": { "headerName": "headerValue", ... },
    "body": "..."
}

http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-set-up-simple-proxy.html#api-gateway-simple-proxy-for-lambda-output-format


问:
Library Image with jsf does not appear
I put some images in my application but the images are not appearing,I'm using jsf

UPDATE

```<code> <h:panelGroup layout="block" styleClass="logo_pull_left">

                     <h:commandLink action="index.xhtml">
                   <h:graphicImage library="resources" name="winnerlogo.png"/>
                     </h:commandLink>

              </h:panelGroup>
</code>```

my page with the image that should appear

UPDATE
image3

答:
You should have a direcory named resources and inside it a directory named imagens.
Then your code will work.

Title: Library Image with jsf does not appear

Body:
I put some images in my application but the images are not appearing,I'm using jsf

UPDATE

 <h:panelGroup layout="block" styleClass="logo_pull_left">

                     <h:commandLink action="index.xhtml">
                   <h:graphicImage library="resources" name="winnerlogo.png"/>
                     </h:commandLink>

              </h:panelGroup>

my page with the image that should appear

UPDATE
image3