<commit_before>/**

 /$$$$$$$              /$$               /$$                                            /$$$$$$
| $$__  $$            | $$              | $$                                           /$$__  $$
| $$  \ $$  /$$$$$$  /$$$$$$    /$$$$$$ | $$$$$$$   /$$$$$$   /$$$$$$$  /$$$$$$       | $$  \__/  /$$$$$$   /$$$$$$  /$$    /$$ /$$$$$$   /$$$$$$
| $$  | $$ |____  $$|_  $$_/   |____  $$| $$__  $$ |____  $$ /$$_____/ /$$__  $$      |  $$$$$$  /$$__  $$ /$$__  $$|  $$  /$$//$$__  $$ /$$__  $$
| $$  | $$  /$$$$$$$  | $$      /$$$$$$$| $$  \ $$  /$$$$$$$|  $$$$$$ | $$$$$$$$       \____  $$| $$$$$$$$| $$  \__/ \  $$/$$/| $$$$$$$$| $$  \__/
| $$  | $$ /$$__  $$  | $$ /$$ /$$__  $$| $$  | $$ /$$__  $$ \____  $$| $$_____/       /$$  \ $$| $$_____/| $$        \  $$$/ | $$_____/| $$
| $$$$$$$/|  $$$$$$$  |  $$$$/|  $$$$$$$| $$$$$$$/|  $$$$$$$ /$$$$$$$/|  $$$$$$$      |  $$$$$$/|  $$$$$$$| $$         \  $/  |  $$$$$$$| $$
|_______/  \_______/   \___/   \_______/|_______/  \_______/|_______/  \_______/       \______/  \_______/|__/          \_/    \_______/|__/

**/

var mongojs = require('mongojs')
    ,nano = require('nano')('http://localhost:5984')
    ,mongoose = require('mongoose')
    ,Registration = require('../models/registration')
    ,log4js     = require('log4js')
    ,logger     = log4js.getLogger('stout')

//                                 _______________________________
//________________________________/    Client Side Abstraction    \___________________________________

function DbModule(dbType)
{
// Implementation reference:

  this._impl = null

// Setup procedure:

  this._SetImplementation(this._EstablishImplementer(dbType))

  return this
}

DbModule.prototype = {

    _SetImplementation: function(implementer)
    {
        this._impl = null
        if(implementer)
            this._impl = implementer
    },

    // EstablishImplementer - function that creates
    // the Concrete Implementer and binds it to DbModule.
    // This is the very method to place your
    // browser/feature/object detection code.
    _EstablishImplementer: function(container)
    {
        if(container === 'mongojs_db')
            return new MongoJS_DB()
        else if(container === 'mongoose')
            return new Mongoose()
        else if(container === 'mongodb')
            return new MongoDB()
        else if(container === 'couchdb')
            return new CouchDB()

        return null
    },

  // Functions "exported" by the DbModule abstraction:
  //                                 __________________
  //________________________________/   Client API     \___________________________________
    initialize: function(db) {
        if(this._impl) {
            this._impl.initialize(db)
        }
    },
    connect: function(collection)
    {
        // Check if any implementor is bound and has the required method:
        if(this._impl) {
            this._impl.connect(collection)       // Forward request to implementer
            return true
        } else
            return false
    },
    close: function() {
        if(this._impl) {
            this._impl.close()
        }
    },
    getAll : function(model,callback)
    {
        // Check if any implementor is bound
        if(this._impl)
            this._impl.getAll(model,callback)     // Forward request to implementer
    },
    getById : function(collection,id,callback)
    {
        // Check if any implementor is bound
        if(this._impl)
            this._impl.getById(collection,id,callback)     // Forward request to implementer
    },
    getByNodeId : function(collection,id,callback)
    {
        // Check if any implementor is bound
        if(this._impl)
            this._impl.getByNodeId(collection,id,callback)     // Forward request to implementer
    },
    getByIds : function(collection,ids)
    {
        // Check if any implementor is bound
        if(this._impl)
            this._impl.getByIds(collection,ids)     // Forward request to implementer
    },
    getNodeByType: function(collection,type)
    {
        if(this._impl)
            this._impl.getNodeByType(collection,type)
    },
    save : function(collection,doc)
    {
        if(this._impl)
            this._impl.save(collection,doc)
    },
    saveWithCallback : function(model,doc,callback) {
        if(this._impl)
            this._impl.saveWithCallback(model,doc,callback)
    },
    update : function(collection,doc)
    {
        // Check if any implementor is bound
        if(this._impl)
            this._impl.update(doc)       // Forward request to implementer
    },
    create : function()
    {
        // Check if any implementor is bound
        if(this._impl) {
            return this._impl.create()     // Forward request to implementer
        }
        return null
    },
    getModel: function(modelName) {
        if(this._impl) {
            return this._impl.getModel(modelName)
        }
    },
    createModel: function(coll,obj) {
        if(this._impl) {
            return this._impl.createModel(coll, obj)
        }
        return null
    },
    remove : function(collection,id)
    {
        // Check if any implementor is bound and has the required method:
        if(this._impl)
            this._impl.remove(collection,id)     // Forward request to implementer
    }
}

//                             ___________________________
//____________________________/     Implementations       \__________________________

//                                  ________________________
//_________________________________/       Mongoose         \__________________________

function Mongoose()
{
    this._mongoose = null
}

Mongoose.prototype = {
    connect: function (collection) {
        if(this._mongoose)
            return this._mongoose

        var uri = 'mongodb://localhost/' + collection
        this._mongoose = mongoose.connect(uri, function (err, res) {
            if (err) {
                logger.debug('ERROR connecting to: ' + uri + '. ' + err)
                return null
            } else {
                logger.debug('Succeeded connected to: ' + uri)

                return this._mongoose
            }
        })
    },
    getAll: function (modelName, callback) {
        console.log("inside getAll : modelName = " + modelName)
        var model = this.getModel(modelName)
        if(model) {
            model.find({}, function (err, docs) {
                if (err) callback(err, null)
                callback(null, docs)
            })
        }
    },
    getById: function (modelName, Id, callback) {
        var model = this.getModel(modelName)
        if(model) {
            model.find({_id: Id}, function (err, obj) {
                logger.debug(JSON.stringify(obj))
                callback(null,obj)
            })
        }
        else {
            callback(err,null)
        }
    },
    getByNodeId: function (modelName, Id, callback) {
        var model = this.getModel(modelName)
        if(model) {
            model.find({"data.message.node.nodeId": Id}, function (err, obj) {
                logger.debug(JSON.stringify(obj))
                callback(null,obj)
            })
        }
        else {
            callback(err,null)
        }
    },
    getModel: function(modelName) {
        var model = this._mongoose.model(modelName)
        if(model)
            return model
        else
            throw err
    },
    createModel: function (collection, schema) {
        //create the schema
        logger.debug("createModel: coll = " + collection)
        logger.debug("createModel: schema = " + JSON.stringify(schema))
        var userSchema = this._mongoose.Schema(schema)
        logger.debug("createModel: userSchema = " + userSchema)
        var model = this._mongoose.model(collection, userSchema)
        logger.debug("createModel: res = " + model)
        return model
    },
    save: function (modelName,doc) {
        if (doc != undefined) {
           logger.debug("save: doc = " + JSON.stringify(doc))
            //doc is the incoming data, so we have to retrieve a model and instantiate an instance with the incoming json doc
            var model = this._mongoose.model(modelName)
            logger.debug("save: model = " + model)
            var reg = new model(doc)
            logger.debug("save: reg = " + JSON.stringify(reg))
            reg.save(function (err,item,numberAffected) {
                if (err)
                    logger.debug("err in the save: " + err.message)
                else {
                    logger.debug("save: numberAffected: " + numberAffected)
                    logger.debug("save: saved item: " + item)
                }
            })
        }
    },
    saveWithCallback: function (modelName,doc,callback) {
        logger.debug("saveWithCallback: model doc = " + doc)
        var model = this._mongoose.model(modelName)
        logger.debug("saveWithCallback: model = " + model)
        var reg = new model(doc)
        logger.debug("saveWithCallback: reg = " + JSON.stringify(reg) )
        if (doc != undefined) {
            doc.save(function (err,item,numberAffected) {
                if (err) {
                    logger.debug("saveWithCallback: err in the save: " + err.message)
                    callback(err, null)
                }
                else {
                    logger.debug("numberAffected: " + numberAffected)
                    logger.debug("saved item: " + item)
                    callback(null,{"results.numberAffected":numberAffected,"Saved": item})
                }
            })
        }
    },
    close: function() {
        this._mongoose.disconnect(function() {
            logger.debug("Disconnected...")
        })
    }
}
//                                  ___________________________
//_________________________________/       Native MongoDB      \__________________________

function MongoDB()
{
    this._mongodb  = null
}

MongoDB.prototype = {

    //Native MongoDB has the db connection object in its callback(giving the db connection at the app level) so we need to just pass
    //that to this initialize function. All the other interfaces allow the db to be connected from anywhere in the code hierarchy
    initialize: function(db) {
        this._mongodb = db
    },
    connect: function(collection) {
        var coll = this._mongodb.collection(collection)
    },
    getAll: function(model,callback) {
        var model = this._mongodb.collection(model)
        model.find().toArray(function(err,docs) {
            if(err)
                callback(err,null)
            callback(null,docs)
        })
    },
    getById: function(collection,Id,callback) {
        var coll = this._mongodb.collection(collection)
        coll.findOne({"data.message.node.nodeId":Id},function(err,document) {
            if(err)
                callback(err,null)
            logger.debug("Db: document = " + JSON.stringify(document))
            callback(null,document)
         })
     },
    save: function(collection,doc) {
        logger.debug("In Save Method")
        var coll = this._mongodb.collection(collection)
        coll.save(doc,function(err,document) {
            logger.debug("wrote this doc: " + JSON.stringify(document))
        })
    }
}
//                                  ___________________________
//_________________________________/          MongoJS_DB       \__________________________

function MongoJS_DB()
{
    this._mongojs_db  = null
}

MongoJS_DB.prototype = {

    connect: function(collection) {
        this._mongojs_db = mongojs(collection)
        logger.debug("MongoDB.connect")
    },
    getAll: function(collection)
    {
        var coll = this._mongojs_db.collection(collection)

        coll.find().sort({name:1},function(err, docs) {
            // docs is an array of all the documents in mycollection
            for(var i=0;i<docs.length;i++)
                logger.debug("doc = " + docs[i]._id + " name = " + docs[i].name)
        })
        logger.debug("MongoJS_DB.getAll")
    },
    getById: function(collection,id)
    {
        logger.debug("MongoDB: getById method")
        var coll = this._mongojs_db.collection(collection)
        logger.debug("getById: id = " + id)
        logger.debug("coll = " + collection)
        coll.find({_id:this._mongojs_db.ObjectId(id)},function(err,docs) {
            logger.debug("docs.length = " +docs.length)
            for(var i=0;i<docs.length;i++)
                logger.debug("doc = " + docs[i]._id + " name = " +docs[i].name)
        })
        logger.debug("MongoJS_DB.getById")
    },
    getNodeByType: function(collection,type) {
        logger.debug("MongoDB: getNodeByType")
        var coll = this._mongojs_db.collection(collection)
        coll.find({type:type},function(err,docs) {
            logger.debug("docs.length = " +docs.length)
            for(var i=0;i<docs.length;i++)
                logger.debug("doc = " + docs[i]._id + " name = " +docs[i].name)
        })
        logger.debug("MongoJS_DB.getNodeByType")
    },
    getByIds: function(collection,ids)
    {
        //should return an array of json objects that match the ids
        logger.debug("MongoDB: getByIds method")
        var coll = this._mongojs_db.collection(collection)
        logger.debug("getByIds: ids = " + ids)
        logger.debug("coll = " + collection)

        coll.find({_id:this._mongojs_db.ObjectId(ids)},function(err,docs) {
            logger.debug("docs.length = " +docs.length)
            for(var i=0;i<docs.length;i++)
                logger.debug("doc = " + docs[i]._id + " name = " +docs[i].name)
        })
        logger.debug("MongoJS_DB.getByIds")
    },
    remove: function(collection,id) {
        logger.debug("MongoJS_DB.remove")
    },
    create: function(collection) {
        logger.debug("MongoJS_DB.create")
    },
    save: function(collection,doc) {
        var coll = this._mongojs_db.collection(collection)
        coll.save(doc,{"myname":"Leon Siewert"},function(err,document) {
            if(err)
                throw err
            logger.debug("Saved: doc = " + JSON.stringify(document))
        })
    }
}

//                                  ___________________________
//_________________________________/          CouchDB          \__________________________

function CouchDB()
{
    this._couchdb = null
}

CouchDB.prototype = {

    getAll: function(collection)
    {
        logger.debug("CouchDB.getAll")
    },
    getByIds: function(collection,ids)
    {
        logger.debug("CouchDB.getByIds")
    }
}

// This is the set of private objects:
//                             ___________________________
//____________________________/     Private Objects       \__________________________

var getSomething = function() {

}

module.exports = DbModule<commit_msg>still invoking the mongoose model...just committing here to save the commented out portion of trying to xform jsonschema to mongoose (which isn't working yet)<commit_after>/**

 /$$$$$$$              /$$               /$$                                            /$$$$$$
| $$__  $$            | $$              | $$                                           /$$__  $$
| $$  \ $$  /$$$$$$  /$$$$$$    /$$$$$$ | $$$$$$$   /$$$$$$   /$$$$$$$  /$$$$$$       | $$  \__/  /$$$$$$   /$$$$$$  /$$    /$$ /$$$$$$   /$$$$$$
| $$  | $$ |____  $$|_  $$_/   |____  $$| $$__  $$ |____  $$ /$$_____/ /$$__  $$      |  $$$$$$  /$$__  $$ /$$__  $$|  $$  /$$//$$__  $$ /$$__  $$
| $$  | $$  /$$$$$$$  | $$      /$$$$$$$| $$  \ $$  /$$$$$$$|  $$$$$$ | $$$$$$$$       \____  $$| $$$$$$$$| $$  \__/ \  $$/$$/| $$$$$$$$| $$  \__/
| $$  | $$ /$$__  $$  | $$ /$$ /$$__  $$| $$  | $$ /$$__  $$ \____  $$| $$_____/       /$$  \ $$| $$_____/| $$        \  $$$/ | $$_____/| $$
| $$$$$$$/|  $$$$$$$  |  $$$$/|  $$$$$$$| $$$$$$$/|  $$$$$$$ /$$$$$$$/|  $$$$$$$      |  $$$$$$/|  $$$$$$$| $$         \  $/  |  $$$$$$$| $$
|_______/  \_______/   \___/   \_______/|_______/  \_______/|_______/  \_______/       \______/  \_______/|__/          \_/    \_______/|__/

**/

var mongojs         = require('mongojs')
    ,util           = require('util')
    ,jsonSchema     = require('json-schema-converter')
    ,nano           = require('nano')('http://localhost:5984')
    ,mongoose       = require('mongoose')
    //,Registration_schema   = require('../models/json_schema_reg.json')
    ,Registration_schema   = require('../models/Registration.js')
    ,logger         = require('log4js').getLogger('stout')

//                                 _______________________________
//________________________________/    Client Side Abstraction    \___________________________________

function DbModule(dbType)
{
// Implementation reference:

  this._impl = null

// Setup procedure:

  this._SetImplementation(this._EstablishImplementer(dbType))

  return this
}

DbModule.prototype = {

    _SetImplementation: function(implementer)
    {
        this._impl = null
        if(implementer)
            this._impl = implementer
    },

    // EstablishImplementer - function that creates
    // the Concrete Implementer and binds it to DbModule.
    // This is the very method to place your
    // browser/feature/object detection code.
    _EstablishImplementer: function(container)
    {
        if(container === 'mongojs_db')
            return new MongoJS_DB()
        else if(container === 'mongoose')
            return new Mongoose()
        else if(container === 'mongodb')
            return new MongoDB()
        else if(container === 'couchdb')
            return new CouchDB()

        return null
    },

  // Functions "exported" by the DbModule abstraction:
  //                                 __________________
  //________________________________/   Client API     \___________________________________
    initialize: function(db) {
        if(this._impl) {
            this._impl.initialize(db)
        }
    },
    connect: function(collection)
    {
        // Check if any implementor is bound and has the required method:
        if(this._impl) {
            this._impl.connect(collection)       // Forward request to implementer
            return true
        } else
            return false
    },
    close: function() {
        if(this._impl) {
            this._impl.close()
        }
    },
    getAll : function(model,callback)
    {
        // Check if any implementor is bound
        if(this._impl)
            this._impl.getAll(model,callback)     // Forward request to implementer
    },
    getById : function(collection,id,callback)
    {
        // Check if any implementor is bound
        if(this._impl)
            this._impl.getById(collection,id,callback)     // Forward request to implementer
    },
    getByNodeId : function(collection,id,callback)
    {
        // Check if any implementor is bound
        if(this._impl)
            this._impl.getByNodeId(collection,id,callback)     // Forward request to implementer
    },
    getByIds : function(collection,ids)
    {
        // Check if any implementor is bound
        if(this._impl)
            this._impl.getByIds(collection,ids)     // Forward request to implementer
    },
    getNodeByType: function(collection,type)
    {
        if(this._impl)
            this._impl.getNodeByType(collection,type)
    },
    save : function(collection,doc)
    {
        if(this._impl)
            this._impl.save(collection,doc)
    },
    saveWithCallback : function(model,doc,callback) {
        if(this._impl)
            this._impl.saveWithCallback(model,doc,callback)
    },
    update : function(collection,doc)
    {
        // Check if any implementor is bound
        if(this._impl)
            this._impl.update(doc)       // Forward request to implementer
    },
    create : function()
    {
        // Check if any implementor is bound
        if(this._impl) {
            return this._impl.create()     // Forward request to implementer
        }
        return null
    },
    getModel: function(modelName) {
        if(this._impl) {
            return this._impl.getModel(modelName)
        }
    },
    createModel: function(coll,obj) {
        if(this._impl) {
            return this._impl.createModel(coll, obj)
        }
        return null
    },
    remove : function(collection,id)
    {
        // Check if any implementor is bound and has the required method:
        if(this._impl)
            this._impl.remove(collection,id)     // Forward request to implementer
    }
}

//                             ___________________________
//____________________________/     Implementations       \__________________________

//                                  ________________________
//_________________________________/       Mongoose         \__________________________

function Mongoose()
{
    this._mongoose = null
}

Mongoose.prototype = {
    connect: function (collection) {
        if(this._mongoose)
            return this._mongoose

        var uri = 'mongodb://localhost/' + collection
        this._mongoose = mongoose.connect(uri, function (err, res) {
            if (err) {
                logger.debug('ERROR connecting to: ' + uri + '. ' + err)
                return null
            } else {
                logger.debug('Succeeded connected to: ' + uri)

                return this._mongoose
            }
        })
    },
    getAll: function (modelName, callback) {
        console.log("inside getAll : modelName = " + modelName)
        var model = this.getModel(modelName)
        if(model) {
            model.find({}, function (err, docs) {
                if (err) callback(err, null)
                callback(null, docs)
            })
        }
    },
    getById: function (modelName, Id, callback) {
        var model = this.getModel(modelName)
        if(model) {
            model.find({_id: Id}, function (err, obj) {
                logger.debug(JSON.stringify(obj))
                callback(null,obj)
            })
        }
        else {
            callback(err,null)
        }
    },
    getByNodeId: function (modelName, Id, callback) {
        var model = this.getModel(modelName)
        if(model) {
            model.find({"data.message.node.nodeId": Id}, function (err, obj) {
                logger.debug(JSON.stringify(obj))
                callback(null,obj)
            })
        }
        else {
            callback(err,null)
        }
    },
    getModel: function(modelName) {
        var model = this._mongoose.model(modelName)
        if(model)
            return model
        else
            throw err
    },
    createModel: function (collection, schema) {
        //create the schema
        logger.debug("createModel: coll = " + collection)
        logger.debug("createModel: schema = " + JSON.stringify(schema))
        var userSchema = this._mongoose.Schema(schema)
        logger.debug("createModel: userSchema = " + userSchema)
        var model = this._mongoose.model(collection, userSchema)
        logger.debug("createModel: res = " + model)
        return model
    },
    save: function (modelName,doc) {
        if (doc != undefined) {
           logger.debug("save: doc = " + JSON.stringify(doc))
            //doc is the incoming data, so we have to retrieve a model and instantiate an instance with the incoming json doc
            var model = this._mongoose.model(modelName)
//            if(!jsonSchema.is_valid(Registration_schema)) {
//                logger.debug("JSON SCHEMA REG NOT Valid: " + util.inspect(jsonSchema.validate(Registration_schema)))
//            }
            //var model = jsonSchema.to_mongoose_schema(Registration_schema)
            logger.debug("save: model = " + JSON.stringify(model))
            var saveDoc = new model(doc)
            logger.debug("save: saveDoc = " + saveDoc ) //JSON.stringify(saveDoc))
            saveDoc.save(function (err,item,numberAffected) {
                if (err)
                    logger.debug("err in the save: " + err.message)
                else {
                    logger.debug("save: numberAffected: " + numberAffected)
                    logger.debug("save: saved item: " + item)
                }
            })
        }
    },
    saveWithCallback: function (modelName,doc,callback) {
        logger.debug("saveWithCallback: model doc = " + doc)
        var model = this._mongoose.model(modelName)
        logger.debug("saveWithCallback: model = " + model)
        var reg = new model(doc)
        logger.debug("saveWithCallback: reg = " + JSON.stringify(reg) )
        if (doc != undefined) {
            doc.save(function (err,item,numberAffected) {
                if (err) {
                    logger.debug("saveWithCallback: err in the save: " + err.message)
                    callback(err, null)
                }
                else {
                    logger.debug("numberAffected: " + numberAffected)
                    logger.debug("saved item: " + item)
                    callback(null,{"results.numberAffected":numberAffected,"Saved": item})
                }
            })
        }
    },
    close: function() {
        this._mongoose.disconnect(function() {
            logger.debug("Disconnected...")
        })
    }
}
//                                  ___________________________
//_________________________________/       Native MongoDB      \__________________________

function MongoDB()
{
    this._mongodb  = null
}

MongoDB.prototype = {

    //Native MongoDB has the db connection object in its callback(giving the db connection at the app level) so we need to just pass
    //that to this initialize function. All the other interfaces allow the db to be connected from anywhere in the code hierarchy
    initialize: function(db) {
        this._mongodb = db
    },
    connect: function(collection) {
        var coll = this._mongodb.collection(collection)
    },
    getAll: function(model,callback) {
        var model = this._mongodb.collection(model)
        model.find().toArray(function(err,docs) {
            if(err)
                callback(err,null)
            callback(null,docs)
        })
    },
    getById: function(collection,Id,callback) {
        var coll = this._mongodb.collection(collection)
        coll.findOne({"data.message.node.nodeId":Id},function(err,document) {
            if(err)
                callback(err,null)
            logger.debug("Db: document = " + JSON.stringify(document))
            callback(null,document)
         })
     },
    save: function(collection,doc) {
        logger.debug("In Save Method")
        var coll = this._mongodb.collection(collection)
        coll.save(doc,function(err,document) {
            logger.debug("wrote this doc: " + JSON.stringify(document))
        })
    }
}
//                                  ___________________________
//_________________________________/          MongoJS_DB       \__________________________

function MongoJS_DB()
{
    this._mongojs_db  = null
}

MongoJS_DB.prototype = {

    connect: function(collection) {
        this._mongojs_db = mongojs(collection)
        logger.debug("MongoDB.connect")
    },
    getAll: function(collection)
    {
        var coll = this._mongojs_db.collection(collection)

        coll.find().sort({name:1},function(err, docs) {
            // docs is an array of all the documents in mycollection
            for(var i=0;i<docs.length;i++)
                logger.debug("doc = " + docs[i]._id + " name = " + docs[i].name)
        })
        logger.debug("MongoJS_DB.getAll")
    },
    getById: function(collection,id)
    {
        logger.debug("MongoDB: getById method")
        var coll = this._mongojs_db.collection(collection)
        logger.debug("getById: id = " + id)
        logger.debug("coll = " + collection)
        coll.find({_id:this._mongojs_db.ObjectId(id)},function(err,docs) {
            logger.debug("docs.length = " +docs.length)
            for(var i=0;i<docs.length;i++)
                logger.debug("doc = " + docs[i]._id + " name = " +docs[i].name)
        })
        logger.debug("MongoJS_DB.getById")
    },
    getNodeByType: function(collection,type) {
        logger.debug("MongoDB: getNodeByType")
        var coll = this._mongojs_db.collection(collection)
        coll.find({type:type},function(err,docs) {
            logger.debug("docs.length = " +docs.length)
            for(var i=0;i<docs.length;i++)
                logger.debug("doc = " + docs[i]._id + " name = " +docs[i].name)
        })
        logger.debug("MongoJS_DB.getNodeByType")
    },
    getByIds: function(collection,ids)
    {
        //should return an array of json objects that match the ids
        logger.debug("MongoDB: getByIds method")
        var coll = this._mongojs_db.collection(collection)
        logger.debug("getByIds: ids = " + ids)
        logger.debug("coll = " + collection)

        coll.find({_id:this._mongojs_db.ObjectId(ids)},function(err,docs) {
            logger.debug("docs.length = " +docs.length)
            for(var i=0;i<docs.length;i++)
                logger.debug("doc = " + docs[i]._id + " name = " +docs[i].name)
        })
        logger.debug("MongoJS_DB.getByIds")
    },
    remove: function(collection,id) {
        logger.debug("MongoJS_DB.remove")
    },
    create: function(collection) {
        logger.debug("MongoJS_DB.create")
    },
    save: function(collection,doc) {
        var coll = this._mongojs_db.collection(collection)
        coll.save(doc,{"myname":"Leon Siewert"},function(err,document) {
            if(err)
                throw err
            logger.debug("Saved: doc = " + JSON.stringify(document))
        })
    }
}

//                                  ___________________________
//_________________________________/          CouchDB          \__________________________

function CouchDB()
{
    this._couchdb = null
}

CouchDB.prototype = {

    getAll: function(collection)
    {
        logger.debug("CouchDB.getAll")
    },
    getByIds: function(collection,ids)
    {
        logger.debug("CouchDB.getByIds")
    }
}

// This is the set of private objects:
//                             ___________________________
//____________________________/     Private Objects       \__________________________

var getSomething = function() {

}

module.exports = DbModule<|endoftext|>


<commit_before>#!/usr/bin/env node
var _ = require('lodash');
var moment = require('moment');
var Promise = require('bluebird');
var debug = require('debug')('bin:importfreshsample');
var reportDuplicate = require('debug')('bin:importfreshsample:duplicate!');
var request = Promise.promisifyAll(require('request'));
var nconf = require('nconf');
var mongo = require('../lib/mongo');

nconf.argv().env().file({ file: "config/collector.json" });

if(!nconf.get('password'))
    return console.log("--password required");

const amount = nconf.get('amount') || 50;
const url = ( nconf.get('server') || 'http://localhost:8000' ) + '/api/v1/glue/' + nconf.get('password') +'/' + amount;

const htmlCleanFields = ['_id', 'savingTime', 'id', 'userId', 'impressionId', 'timelineId', 'html' ];

debug("Accessing to %s", url);
return request
    .getAsync(url)
    .then(function(res) {
        return res.body;
    })
    .then(JSON.parse)
    .then(function(content) {

        debug("Returning the timeline %s (%s %s) %s, impressions %d, htmls %d",
            content[2].id,
            content[2].startTime,
            moment.duration(moment(content[2].startTime) - moment()).humanize(),
            content[2].geoip,
            _.size(content[0]),
            _.size(content[1])
        );

        var timeline = content[2];
        timeline.startTime = new Date(content[2].startTime);

        var impressions = _.map(content[0], function(i) {
            i.impressionTime = new Date(i.impressionTime);
            return i;
        });

        var htmls = _.map(content[1], function(h) {
            var clean = _.pick(h, htmlCleanFields);
            clean.savingTime = new Date(clean.savingTime);
            return clean;
        });

        if(!_.size(htmls) || !_.size(impressions)) {
            debug("Found an empty timeline! (%s) nothing to save.", content[2].id);
            return [ null, [], [] ];
        }

        debug("Ready with a timeline with %d impressions and %d htmls",
            _.size(impressions), _.size(htmls));

        /* because one writing operation might fail for duplicated Id the operation are separated */

        return [ timeline, impressions, htmls ];
    })
    .tap(writeTimeline)
    .tap(writeImpressions)
    .then(writeHtmls)
    .map(function(done)  {
        if(_.get(done, 'id'))
            console.log(done.id);
    });

function writeTimeline(blob) {
    if(blob[0] && _.get(blob[0], 'id')) {
        return mongo
            .writeOne(nconf.get('schema').timelines, blob[0])
            .catch(duplicatedError);
    }
}

function writeImpressions(blob) {
    var counter = 0;
    return Promise.map(blob[1], function(impression) {
        return mongo
            .writeOne(nconf.get('schema').impressions, impression)
            .tap(function() { counter++; })
            .catch(duplicatedError);
    }, { concurrency: 1} )
    .tap(function() {
        if(_.size(blob[1])) {
            if(!counter)
                reportDuplicate("timeline already saved");
            else
                debug("Written %d impressions", counter);
        }
    });
}

function writeHtmls(blob) {
    return Promise.map(blob[2], function(html) {
        return mongo
            .writeOne(nconf.get('schema').htmls, html)
            .catch(duplicatedError);
    }, { concurrency: 1} );
}

function duplicatedError(error) {
    if(error.code !== 11000) {
        debug("unexpected error?\n%s", error.message);
        process.exit(0);
    }
}
<commit_msg>importer can help to build UT base<commit_after>#!/usr/bin/env node
var _ = require('lodash');
var moment = require('moment');
var Promise = require('bluebird');
var debug = require('debug')('bin:importfreshsample');
var reportDuplicate = require('debug')('bin:importfreshsample:duplicate!');
var request = Promise.promisifyAll(require('request'));
var nconf = require('nconf');
var mongo = require('../lib/mongo');

nconf.argv().env();
const cfgFile = nconf.get('config') ? nconf.get('config') : "config/content.json";
nconf.file({ file: cfgFile });

if(!nconf.get('password'))
    return console.log("--password required");

const amount = nconf.get('amount') || 50;
const url = ( nconf.get('server') || 'http://localhost:8000' ) + '/api/v1/glue/' + nconf.get('password') +'/' + amount;

const htmlCleanFields = ['_id', 'savingTime', 'id', 'userId', 'impressionId', 'timelineId', 'html' ];

debug("Accessing to %s", url);
return request
    .getAsync(url)
    .then(function(res) {
        return res.body;
    })
    .then(JSON.parse)
    .then(function(content) {

        debug("Returning the timeline %s (%s %s) %s, impressions %d, htmls %d",
            content[2].id,
            content[2].startTime,
            moment.duration(moment(content[2].startTime) - moment()).humanize(),
            content[2].geoip,
            _.size(content[0]),
            _.size(content[1])
        );

        var timeline = content[2];
        timeline.startTime = new Date(content[2].startTime);

        var impressions = _.map(content[0], function(i) {
            i.impressionTime = new Date(i.impressionTime);
            return i;
        });

        var htmls = _.map(content[1], function(h) {
            var clean = _.pick(h, htmlCleanFields);
            clean.savingTime = new Date(clean.savingTime);
            return clean;
        });

        if(!_.size(htmls) || !_.size(impressions)) {
            debug("Found an empty timeline! (%s) nothing to save.", content[2].id);
            return [ null, [], [] ];
        }

        debug("Ready with a timeline with %d impressions and %d htmls",
            _.size(impressions), _.size(htmls));

        /* because one writing operation might fail for duplicated Id the operation are separated */

        return [ timeline, impressions, htmls ];
    })
    .tap(writeTimeline)
    .tap(writeImpressions)
    .then(writeHtmls)
    .map(function(done)  {
        if(_.get(done, 'id'))
            console.log(done.id);
    });

function writeTimeline(blob) {
    if(blob[0] && _.get(blob[0], 'id')) {
        return mongo
            .writeOne(nconf.get('schema').timelines, blob[0])
            .catch(duplicatedError);
    }
}

function writeImpressions(blob) {
    var counter = 0;
    return Promise.map(blob[1], function(impression) {
        return mongo
            .writeOne(nconf.get('schema').impressions, impression)
            .tap(function() { counter++; })
            .catch(duplicatedError);
    }, { concurrency: 1} )
    .tap(function() {
        if(_.size(blob[1])) {
            if(!counter)
                reportDuplicate("timeline already saved");
            else
                debug("Written %d impressions", counter);
        }
    });
}

function writeHtmls(blob) {
    return Promise.map(blob[2], function(html) {
        return mongo
            .writeOne(nconf.get('schema').htmls, html)
            .catch(duplicatedError);
    }, { concurrency: 1} );
}

function duplicatedError(error) {
    if(error.code !== 11000) {
        debug("unexpected error?\n%s", error.message);
        process.exit(0);
    }
}
<|endoftext|>


<commit_before>let catalogBySort = {}

import Libra from './LibraAPI'

export const CHASE_API_ENDPOINT = 'https://uysa8o7cq6.execute-api.us-east-1.amazonaws.com/prod'
export const CHASE_THUMBS_CF_PATH = 'https://d2aed4ktvx51jm.cloudfront.net'
export const CHASE_THUMBS_S3_PATH = 'https://s3.amazonaws.com/syon-chase'

export function makeCatalog(listFromPocket) {
  // console.tron.info('ChaseDriver#makeCatalog -- listFromPocket', listFromPocket)
  let catalog = {}
  let rawItems = {}
  Object.keys(listFromPocket).forEach((key) => {
    const m = listFromPocket[key]
    rawItems[key] = m
    itemId = m.item_id
    catalog[key] = {
      key: itemId,
      itemId: itemId,
      sortId: m.sort_id,
    }
    catalogBySort[m.sort_id] = itemId
  })
  return { catalog, rawItems }
}

export async function saveCatalogItemsAsEntryToStorage(rawItems) {
  // console.tron.info('ChaseDriver#saveCatalogItemsAsEntryToStorage -- rawItems', rawItems)
  let entries = await _loadEntriesFromStorage()
  const promises = []
  Object.keys(rawItems).forEach(itemId => {
    const item = rawItems[itemId]
    const existEntry = entries[itemId]
    if (!existEntry) {
      promises.push(_convertItemToEntry(item))
    }
  })
  await Promise.all(promises).then(values => {
    // console.tron.info('ChaseDriver#Promise.all Done!', values)
    values.forEach(v => { entries[v.eid] = v })
    console.tron.info('ChaseDriver# -- NewEntries:', entries)
    global.storage.save({ key: 'entries', data: entries, expires: null })
  })
  return entries
}

export function callLambdaThumb(url, pocket_id, image_suggested) {
  return new Promise((resolve, reject) => {
    const qs = `url=${url}&pocket_id=${pocket_id}&suggested=${image_suggested}`
    fetch(`${CHASE_API_ENDPOINT}/thumb?${qs}`).then(response => {
      console.tron.info('ChaseDriver#callLambdaThumb', `${response.status} (${pocket_id})`)
      if (response.ok) {
        resolve()
      }
    }, err => {
      reject()
    })
  })
}

async function _loadEntriesFromStorage() {
  // console.tron.info('ChaseDriver#_loadEntriesFromStorage -- start')
  const entries = await global.storage.load({ key: 'entries' })
    .then(entries => {
      return entries
    }).catch(e => {
      return {}
    })
  // console.tron.info('ChaseDriver#_loadEntriesFromStorage -- done', entries)
  return entries
}

async function _convertItemToEntry(item) {
  const url = item.resolved_url ? item.resolved_url : item.given_url
  const isHTTPS = url.startsWith('https')
  const isHTTP  = url.startsWith('http:')
  let pageinfo = {}
  if (isHTTPS) {
    const libra = new Libra(url)
    pageinfo = await libra.getData().then(data => data).catch(e => {})
    // console.tron.info('ChaseDriver#Libra', pageinfo)
  }
  else if (isHTTP) {
    pageinfo = await fetch(`${CHASE_API_ENDPOINT}/info?url=${url}`, {
        method: 'GET',
      }).then((response) => {
        if (response.ok) {
          // console.tron.info('ChaseDriver#FetchDone!', url)
          return response.json()
        } else {
          return {}
        }
      }).catch(e => {
        return {}
      })
    // console.tron.info('ChaseDriver#[Lambda/info]', {url, pageinfo})
  }
  const entry = _mergeItemAndPageinfo(url, item, pageinfo)
  // console.tron.info('ChaseDriver# -- New Entry:', entry)
  return entry
}

function _mergeItemAndPageinfo(url, m, pi) {
  pi = pi || {}
  return {
    eid: m.item_id,
    url: url,
    image: _buildImagePath(m.item_id),
    image_suggested: (m.has_image === '1') ? m.image.src : '',
    siteName: pi.site_name,
    title: _choiceText(m.title, pi.title),
    description: pi.description,
    fqdn: `${url}/`.match(/\/\/(.*?)\//)[1],
    sortId: m.sort_id,
    tags: m.tags,
    date: _getDate(m.time_added),
  }
}

function _choiceText(pkt, ogp) {
  return ogp ? ogp : pkt
}

function _getDate(time10) {
  const dt = new Date(time10 * 1000)
  const y = dt.getFullYear()
  const m = dt.getMonth() + 1
  const d = dt.getDate()
  return `${y}.${m}.${d}`
}

function _buildImagePath(itemId) {
  const item10Id = `0000000000${itemId}`.substr(-10, 10)
  const itemId3 = item10Id.slice(0, 3)
  return `items/thumbs/${itemId3}/${item10Id}.jpg`
}
<commit_msg>:+1: consider entry update from Pocket service<commit_after>let catalogBySort = {}

import Libra from './LibraAPI'

export const CHASE_API_ENDPOINT = 'https://uysa8o7cq6.execute-api.us-east-1.amazonaws.com/prod'
export const CHASE_THUMBS_CF_PATH = 'https://d2aed4ktvx51jm.cloudfront.net'
export const CHASE_THUMBS_S3_PATH = 'https://s3.amazonaws.com/syon-chase'

export function makeCatalog(listFromPocket) {
  // console.tron.info('ChaseDriver#makeCatalog -- listFromPocket', listFromPocket)
  let catalog = {}
  let rawItems = {}
  Object.keys(listFromPocket).forEach((key) => {
    const m = listFromPocket[key]
    rawItems[key] = m
    itemId = m.item_id
    catalog[key] = {
      key: itemId,
      itemId: itemId,
      sortId: m.sort_id,
    }
    catalogBySort[m.sort_id] = itemId
  })
  return { catalog, rawItems }
}

export async function saveCatalogItemsAsEntryToStorage(rawItems) {
  // console.tron.info('ChaseDriver#saveCatalogItemsAsEntryToStorage -- rawItems', rawItems)
  let entries = await _loadEntriesFromStorage()
  const promises = []
  Object.keys(rawItems).forEach(itemId => {
    const item = rawItems[itemId]
    const existEntry = entries[itemId]
    promises.push(_convertItemToEntry(item, existEntry))
  })
  await Promise.all(promises).then(values => {
    // console.tron.info('ChaseDriver#Promise.all Done!', values)
    values.forEach(v => { entries[v.eid] = v })
    console.tron.info('ChaseDriver# -- NewEntries:', entries)
    global.storage.save({ key: 'entries', data: entries, expires: null })
  })
  return entries
}

export function callLambdaThumb(url, pocket_id, image_suggested) {
  return new Promise((resolve, reject) => {
    const qs = `url=${url}&pocket_id=${pocket_id}&suggested=${image_suggested}`
    fetch(`${CHASE_API_ENDPOINT}/thumb?${qs}`).then(response => {
      console.tron.info('ChaseDriver#callLambdaThumb', `${response.status} (${pocket_id})`)
      if (response.ok) {
        resolve()
      }
    }, err => {
      reject()
    })
  })
}

async function _loadEntriesFromStorage() {
  // console.tron.info('ChaseDriver#_loadEntriesFromStorage -- start')
  const entries = await global.storage.load({ key: 'entries' })
    .then(entries => {
      return entries
    }).catch(e => {
      return {}
    })
  // console.tron.info('ChaseDriver#_loadEntriesFromStorage -- done', entries)
  return entries
}

async function _convertItemToEntry(item, existEntry) {
  const url = item.resolved_url ? item.resolved_url : item.given_url
  const isHTTPS = url.startsWith('https')
  const isHTTP  = url.startsWith('http:')
  let pageinfo = {}
  if (!existEntry) {
    if (isHTTPS) {
      const libra = new Libra(url)
      pageinfo = await libra.getData().then(data => data).catch(e => {})
      // console.tron.info('ChaseDriver#Libra', pageinfo)
    }
    else if (isHTTP) {
      pageinfo = await fetch(`${CHASE_API_ENDPOINT}/info?url=${url}`, {
          method: 'GET',
        }).then((response) => {
          if (response.ok) {
            // console.tron.info('ChaseDriver#FetchDone!', url)
            return response.json()
          } else {
            return {}
          }
        }).catch(e => {
          return {}
        })
      // console.tron.info('ChaseDriver#[Lambda/info]', {url, pageinfo})
    }
  }
  const entry = _mergeItemAndPageinfo(existEntry, url, item, pageinfo)
  // console.tron.info('ChaseDriver# -- New Entry:', entry)
  return entry
}

function _mergeItemAndPageinfo(existEntry, url, m, pi) {
  pi = pi || {}
  if (existEntry) {
    existEntry['sortId'] = m.sort_id
    existEntry['tags'] = m.tags
    return existEntry
  } else {
    return {
      eid: m.item_id,
      url: url,
      image: _buildImagePath(m.item_id),
      image_suggested: (m.has_image === '1') ? m.image.src : '',
      siteName: pi.site_name,
      title: _choiceText(m.title, pi.title),
      description: pi.description,
      fqdn: `${url}/`.match(/\/\/(.*?)\//)[1],
      sortId: m.sort_id,
      tags: m.tags,
      date: _getDate(m.time_added),
    }
  }
}

function _choiceText(pkt, ogp) {
  return ogp ? ogp : pkt
}

function _getDate(time10) {
  const dt = new Date(time10 * 1000)
  const y = dt.getFullYear()
  const m = dt.getMonth() + 1
  const d = dt.getDate()
  return `${y}.${m}.${d}`
}

function _buildImagePath(itemId) {
  const item10Id = `0000000000${itemId}`.substr(-10, 10)
  const itemId3 = item10Id.slice(0, 3)
  return `items/thumbs/${itemId3}/${item10Id}.jpg`
}
<|endoftext|>


<commit_before><commit_msg>Add min and max to label settings<commit_after><|endoftext|>


<commit_before>var win = Titanium.UI.currentWindow;

var b1 = Titanium.UI.createButton({
	title:'I am a Button',
	height:40,
	width:200,
	top:10
});

var b2 = Titanium.UI.createButton({
	title:'I am a Button',
	image:'../images/chat.png',
	width:200,
	height:40,
	top:60
});

var b3 = Titanium.UI.createButton({
	color:'#fff',
	backgroundImage:'../images/BUTT_grn_off.png',
	backgroundSelectedImage:'../images/BUTT_grn_on.png',
	backgroundDisabledImage: '../images/BUTT_drk_off.png',
	top:110,
	width:301,
	height:57,
	font:{fontSize:20,fontWeight:'bold',fontFamily:'Helvetica Neue'},
	title:'Click Me'
});

var buttonLabel = Titanium.UI.createLabel({
	color:'#f00',
	highlightedColor:'#0f0',
	backgroundColor:'transparent',
	width:'100',
	height:'auto',
	right:5,
	text:'Custom Label'
});

b3.add(buttonLabel);

var state = 0;
b3.addEventListener('click', function()
{
	switch (state)
	{
		case 0:
			b3.enabled=false;
			b3.title = 'I am Disabled';
			state++;

			setTimeout(function()
			{
				b3.enabled=true;
				b3.title = 'I am Enabled';
			},1000);

			break;
		case 1:
			b3.font = {fontSize:25,fontFamily:'Marker Felt', fontWeight:'bold'};
			b3.title = 'I am red';
			b3.backgroundImage = '../images/BUTT_red_off.png';
			b3.backgroundSelectedImage = '../images/BUTT_red_on.png';
			b3.color = '#222';
			state++;
			break;
		case 2:
			b3.width = 200;
			b3.color = '#fff';
			b3.title = 'White text';
			state=0;
			break;
	}
});

var b4 = Titanium.UI.createButton({
	title:'Hide/Show Button Above',
	width:200,
	height:40,
	top:175
});

var visible = true;
b4.addEventListener('click', function()
{
	if (!visible)
	{
		b3.show();
		visible=true;
	}
	else
	{
		b3.hide();
		visible=false;
	}
});

var b5 = Titanium.UI.createButton({
	width:200,
	height:40,
	top:225
});
var b5Label = Ti.UI.createLabel({
	text:'Label',
	width:50,
	height:20,
	color:'#336699'
});
b5.add(b5Label);

var b5ImageView = Ti.UI.createImageView({
	image:'../images/camera.png',
	left:10,
	height:33,
	width:33
});
b5.add(b5ImageView);
b5.addEventListener('touchstart', function()
{
	b5Label.color = 'red';
});
b5.addEventListener('touchend', function()
{
	b5Label.color = '#336699';
});
win.add(b1);
win.add(b3);
win.add(b4);

// add iphone specific tests
if (Titanium.Platform.name == 'iPhone OS')
{
	win.add(b2);
	win.add(b5);
}

var bhleft = Titanium.UI.createButton({
	title : 'H-Left',
	width : 50,
	height: 40,
	top : 300,
	left : 60
});
bhleft.addEventListener('click', function() {
	b1.textAlign = Titanium.UI.TEXT_ALIGNMENT_LEFT;
});

var bhcenter = Titanium.UI.createButton({
	title : 'H-Center',
	width : 50,
	height: 40,
	top : 300,
	left : 120
});
bhcenter.addEventListener('click', function() {
	b1.textAlign = Titanium.UI.TEXT_ALIGNMENT_CENTER;
});

var bhright = Titanium.UI.createButton({
	title : 'H-Right',
	width : 50,
	height: 40,
	top : 300,
	left : 180
});
bhright.addEventListener('click', function() {
	b1.textAlign = Titanium.UI.TEXT_ALIGNMENT_RIGHT;
});

var bvtop = Titanium.UI.createButton({
	title : 'V-Top',
	width : 50,
	height: 40,
	top : 350,
	left : 60
});
bvtop.addEventListener('click', function() {
	b1.verticalAlign = Titanium.UI.TEXT_VERTICAL_ALIGNMENT_TOP;
});

var bvcenter = Titanium.UI.createButton({
	title : 'V-Center',
	width : 50,
	height: 40,
	top : 350,
	left : 120
});
bvcenter.addEventListener('click', function() {
	b1.verticalAlign = Titanium.UI.TEXT_VERTICAL_ALIGNMENT_CENTER;
});

var bvbottom = Titanium.UI.createButton({
	title : 'V-Bottom',
	width : 50,
	height: 40,
	top : 350,
	left : 180
});
bvbottom.addEventListener('click', function() {
	b1.verticalAlign = Titanium.UI.TEXT_VERTICAL_ALIGNMENT_BOTTOM;
});

win.add(bhleft);
win.add(bhcenter);
win.add(bhright);
win.add(bvtop);
win.add(bvcenter);
win.add(bvbottom);<commit_msg>cleaned up, removed ios only buttons<commit_after>var win = Titanium.UI.currentWindow;

var b1 = Titanium.UI.createButton({
	title:'I am a Button',
	height:40,
	width:200,
	top:10
});

var b3 = Titanium.UI.createButton({
	color:'#fff',
	backgroundImage:'../images/BUTT_grn_off.png',
	backgroundSelectedImage:'../images/BUTT_grn_on.png',
	backgroundDisabledImage: '../images/BUTT_drk_off.png',
	top:90,
	width:301,
	height:57,
	font:{fontSize:20,fontWeight:'bold',fontFamily:'Helvetica Neue'},
	title:'Click Me'
});

var buttonLabel = Titanium.UI.createLabel({
	color:'#f00',
	highlightedColor:'#0f0',
	backgroundColor:'transparent',
	width:'100',
	height:'auto',
	right:5,
	text:'Custom Label'
});

b3.add(buttonLabel);

var state = 0;
b3.addEventListener('click', function()
{
	switch (state)
	{
		case 0:
			b3.enabled=false;
			b3.title = 'I am Disabled';
			state++;

			setTimeout(function()
			{
				b3.enabled=true;
				b3.title = 'I am Enabled';
			},1000);

			break;
		case 1:
			b3.font = {fontSize:25,fontFamily:'Marker Felt', fontWeight:'bold'};
			b3.title = 'I am red';
			b3.backgroundImage = '../images/BUTT_red_off.png';
			b3.backgroundSelectedImage = '../images/BUTT_red_on.png';
			b3.color = '#222';
			state++;
			break;
		case 2:
			b3.width = 200;
			b3.color = '#fff';
			b3.title = 'White text';
			state=0;
			break;
	}
});

var b4 = Titanium.UI.createButton({
	title:'Hide/Show Button Above',
	width:250,
	height:40,
	top:175
});

var visible = true;
b4.addEventListener('click', function()
{
	if (!visible)
	{
		b3.show();
		visible=true;
	}
	else
	{
		b3.hide();
		visible=false;
	}
});

win.add(b1);
win.add(b3);
win.add(b4);

// add a series of alignment buttons
var buttonRows = [
	[
		{ title: 'H-Left', textAlign: Titanium.UI.TEXT_ALIGNMENT_LEFT },
		{ title: 'H-Center', textAlign: Titanium.UI.TEXT_ALIGNMENT_CENTER },
		{ title: 'H-Right', textAlign: Titanium.UI.TEXT_ALIGNMENT_RIGHT }
	],
	[
		{ title: 'V-Top', verticalAlign: Titanium.UI.TEXT_VERTICAL_ALIGNMENT_TOP },
		{ title: 'V-Center', verticalAlign: Titanium.UI.TEXT_VERTICAL_ALIGNMENT_CENTER },
		{ title: 'V-Bottom', verticalAlign: Titanium.UI.TEXT_VERTICAL_ALIGNMENT_BOTTOM }
	]
];

for (var i = 0; i < buttonRows.length; i++) {
	var row = buttonRows[i];
	for (var j = 0; j < row.length; j++) {
		var button = Titanium.UI.createButton({
			title: row[j].title,
			width: 100,
			height: 40,
			top: 300 + (50 * i),
			left: 100 * (j+1),
			textAlignProperty: row[j].textAlign,
			verticalAlignProperty: row[j].verticalAlign
		});
		button.addEventListener('click', function(e) {
			if (e.source.textAlignProperty) {
				b1.textAlign = e.source.textAlignProperty;
			} else if (e.source.verticalAlignProperty) {
				b1.verticalAlign = e.source.verticalAlignProperty;
			}
		});
		win.add(button);
	}
}

// for (var i = 0; i < buttons.length; i++) {
	// var b = Titanium.UI.createButton({
		// title: buttons[i].title,
		// width: 100,
		// height: 40,
		// top: 300 + (buttons[i].row ? buttons[i].row * 50),
		// left: 100 * (i+1),
		// textAlign: buttons[i].textAlign || Titanium.UI.TEXT_ALIGNMENT_CENTER,
		// verticalAlign: buttons[i].verticalAlign || Titanium.UI.TEXT_VERTICAL_ALIGNMENT_CENTER
	// });
	// b.addEventListener('click', function(e) {
		// if (e.source.textAlign) {
			// b1.textAlign = 	e.source.textAlign;
		// } else if (e.source.verticalAlign) {
			// b1.textAlign = 	e.source.verticalAlign;
		// }
	// });
	// win.add(b);
// }<|endoftext|>


<commit_before>/*
 * Logspace
 * Copyright (c) 2015 Indoqa Software Design und Beratung GmbH. All rights reserved.
 * This program and the accompanying materials are made available under the terms of
 * the Eclipse Public License Version 1.0, which accompanies this distribution and
 * is available at http://www.eclipse.org/legal/epl-v10.html.
 */

export const COLORS = [
  '#e51c23',
  '#5677fc',
  '#ffeb3b',
  '#259b24',
  '#673ab7',
  '#009688',
  '#e91e63',
  '#00bcd4'
]

export const SCALES = {
  "integer_property_response_code": {
    label: 'HTTP Status codes',
    min: 0,
    max: 500
  }
}

export const TYPES = [
  'bar',
  'line',
  'area'
]
<commit_msg>darker yellow<commit_after>/*
 * Logspace
 * Copyright (c) 2015 Indoqa Software Design und Beratung GmbH. All rights reserved.
 * This program and the accompanying materials are made available under the terms of
 * the Eclipse Public License Version 1.0, which accompanies this distribution and
 * is available at http://www.eclipse.org/legal/epl-v10.html.
 */

export const COLORS = [
  '#e51c23',
  '#5677fc',
  '#f4b400',
  '#259b24',
  '#673ab7',
  '#009688',
  '#e91e63',
  '#00bcd4'
]

export const SCALES = {
  "integer_property_response_code": {
    label: 'HTTP Status codes',
    min: 0,
    max: 500
  }
}

export const TYPES = [
  'bar',
  'line',
  'area'
]
<|endoftext|>


<commit_before>export const GAPS = {
    second: 1,
    minute: 60,
    hour: 3600,
    day: 86400,
    week: 604800,
    month: 2629740,
    year: 31556900
}<commit_msg>add missing license header<commit_after>/*
 * Logspace
 * Copyright (c) 2015 Indoqa Software Design und Beratung GmbH. All rights reserved.
 * This program and the accompanying materials are made available under the terms of
 * the Eclipse Public License Version 1.0, which accompanies this distribution and
 * is available at http://www.eclipse.org/legal/epl-v10.html.
 */

export const GAPS = {
    second: 1,
    minute: 60,
    hour: 3600,
    day: 86400,
    week: 604800,
    month: 2629740,
    year: 31556900
}<|endoftext|>


<commit_before>var infowindow = new google.maps.InfoWindow();
var map;
var routeBoxer;
var service;

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var mapOptions = {
    zoom: 4,
    center: new google.maps.LatLng(39, -98),
    mapTypeId: google.maps.MapTypeId.ROADMAP,
  };
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  service = new google.maps.places.PlacesService(map);

  routeBoxer = new RouteBoxer();

  directionService = new google.maps.DirectionsService();
  directionsRenderer = new google.maps.DirectionsRenderer({ map: map })

  directionsDisplay.setMap(map);
  directionsDisplay.setPanel(document.getElementById('directions-panel'));
}

function calcRoute() {
  var start = document.getElementById('start').value;
  var end = document.getElementById('end').value;

  var waypt1 = document.getElementById('waypoint1').value;
  var waypt2 = document.getElementById('waypoint2').value;
  var waypts = []
  if (waypt1) {
    waypts.push({
      location:waypt1,
      stopover:true});
  }
  if (waypt2) {
    waypts.push({
      location:waypt2,
      stopover:true});
  }

  var request = {
    origin: start,
    destination: end,
    waypoints: waypts,
    optimizeWaypoints: true,
    travelMode: google.maps.TravelMode.DRIVING
  };

  directionService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);

      // Build boxes around route
      var path = response.routes[0].overview_path;
      var boxes = routeBoxer.box(path, 1) // distance from route
      findPlaces(boxes,0)
    } else {
      alert("Directions query failed: " + status);
    }
  });
}

function findPlaces(boxes, searchIndex) {
  var request = {
    bounds: boxes[searchIndex],
    types: ["gas_station"]
  };

  service.radarSearch(request, function (results, status) {
    if (results) {
      for (var i = 0; i < results.length; i++) {
        createMarker(result[i]);
      }
    }
    searchIndex++;
    if (searchIndex < boxes.length)
      findPlaces(boxes, searchIndex);
  });
}

function createMarker(place) {
  var placeLoc = place.geometry.location;
  var marker = new google.maps.Marker({
    map: map,
    position: place.geometry.location
  });

  var request = {
    reference: place.reference
  };

  google.maps.event.addListener(marker,'click',function(){
    service.getDetails(request, function(place, status) {
      if (status == google.maps.places.PlacesServiceStatus.OK) {
        var contentStr = '
' + place.name + '

' + place.formatted_address;
        if (!!place.formatted_phone_number) contentStr += '
' + place.formatted_phone_number;
        if (!!place.website) contentStr += '
' + place.website + '';
        contentStr += '
' + place.types + '
';
        infowindow.setContent(contentStr);
        infowindow.open(map,marker);
      } else {
        var contentStr = "
No Result, status=" + status + "
";
        infowindow.setContent(contentStr);
        infowindow.open(map,marker);
      }
    });
  });
}

google.maps.event.addDomListener(window, 'load', initialize);
<commit_msg>Fix typo in callback function for radarSearch in findPlaces<commit_after>var infowindow = new google.maps.InfoWindow();
var map;
var routeBoxer;
var service;

function initialize() {
  directionsDisplay = new google.maps.DirectionsRenderer();
  var mapOptions = {
    zoom: 4,
    center: new google.maps.LatLng(39, -98),
    mapTypeId: google.maps.MapTypeId.ROADMAP,
  };
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
  service = new google.maps.places.PlacesService(map);

  routeBoxer = new RouteBoxer();

  directionService = new google.maps.DirectionsService();
  directionsRenderer = new google.maps.DirectionsRenderer({ map: map })

  directionsDisplay.setMap(map);
  directionsDisplay.setPanel(document.getElementById('directions-panel'));
}

function calcRoute() {
  var start = document.getElementById('start').value;
  var end = document.getElementById('end').value;

  var waypt1 = document.getElementById('waypoint1').value;
  var waypt2 = document.getElementById('waypoint2').value;
  var waypts = []
  if (waypt1) {
    waypts.push({
      location:waypt1,
      stopover:true});
  }
  if (waypt2) {
    waypts.push({
      location:waypt2,
      stopover:true});
  }

  var request = {
    origin: start,
    destination: end,
    waypoints: waypts,
    optimizeWaypoints: true,
    travelMode: google.maps.TravelMode.DRIVING
  };

  directionService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);

      // Build boxes around route
      var path = response.routes[0].overview_path;
      var boxes = routeBoxer.box(path, 1) // distance from route
      findPlaces(boxes,0)
    } else {
      alert("Directions query failed: " + status);
    }
  });
}

function findPlaces(boxes, searchIndex) {
  var request = {
    bounds: boxes[searchIndex],
    types: ["gas_station"]
  };

  service.radarSearch(request, function (results, status) {
    if (results) {
      for (var i = 0; i < results.length; i++) {
        createMarker(results[i]);
      }
    }
    searchIndex++;
    if (searchIndex < boxes.length)
      findPlaces(boxes, searchIndex);
  });
}

function createMarker(place) {
  var placeLoc = place.geometry.location;
  var marker = new google.maps.Marker({
    map: map,
    position: place.geometry.location
  });

  var request = {
    reference: place.reference
  };

  google.maps.event.addListener(marker,'click',function(){
    service.getDetails(request, function(place, status) {
      if (status == google.maps.places.PlacesServiceStatus.OK) {
        var contentStr = '
' + place.name + '

' + place.formatted_address;
        if (!!place.formatted_phone_number) contentStr += '
' + place.formatted_phone_number;
        if (!!place.website) contentStr += '
' + place.website + '';
        contentStr += '
' + place.types + '
';
        infowindow.setContent(contentStr);
        infowindow.open(map,marker);
      } else {
        var contentStr = "
No Result, status=" + status + "
";
        infowindow.setContent(contentStr);
        infowindow.open(map,marker);
      }
    });
  });
}

google.maps.event.addDomListener(window, 'load', initialize);
<|endoftext|>


<commit_before>"use strict";
const NS_PER_SEC = 1e9;

var http = require("http");
var EventEmitter = require("events").EventEmitter;
var differ = require("deep-diff");

class SharedObjectClient extends EventEmitter {
    constructor(endpoint, transports) {
        super();
        if (!transports.rpc || !transports.source)
            throw new Error("Shared object " + endpoint.name + " needs both Source and RPC transports to be configured");

        this.endpoint = endpoint;
        this.initTransport = transports.rpc;
        this.updateTransport = transports.source;
        this.subscribed = false;

        this._flushData();
    }

    subscribe() {
        this.updateTransport.subscribe("_SO_" + this.endpoint.name);
        this.subscribed = true;
        this._init();
    }

    unsubscribe() {
        this.updateTransport.unsubscribe("_SO_" + this.endpoint.name);
        this.subscribed = false;
    }

    _processMessage(data) {
        if (data.endpoint == "_SO_" + this.endpoint.name) {

            this.emit('raw', {
                v: data.message.v,
                diffs: data.message.diffs
            });

            var idx = data.message.v - (this._v + 1);
            if (this.ready && idx < 0) {
                console.error("(" + this.endpoint.name + ") Bad version! Reinit!");
                return this._init();
            }
            this.procBuffer[idx] = data.message.diffs;
            this.timeBuffer[idx] = data.message.now;
            this.emit('timing', (new Date() - data.message.now) * 1000000);
            this.outstandingDiffs++;
            process.nextTick(this._tryApply.bind(this));
        }
    }

    _tryApply() {
        var totalDiffs = [];

        while (!!this.procBuffer[0]) {
            // Diffs are already reversed by Server!
            var diffs = this.procBuffer.shift();
            this.outstandingDiffs--;
            totalDiffs = diffs.concat(totalDiffs);

            for (let diff of diffs) {
                differ.applyChange(this.data, true, diff);
            }

            this.timeSum += new Date() - this.timeBuffer.shift();
            this.timeCount++;
            if (this.timeCount == 200) {
                console.log("(" + this.endpoint.name + ") Average time: " + (this.timeSum / 200) + " ms");
                this.timeSum = 0;
                this.timeCount = 0;
            }

            this._v++;
        }

        if (totalDiffs.length > 0) {
            this.emit('update', totalDiffs);
        } else if (this.ready && this.outstandingDiffs > 10) {
            console.error("(" + this.endpoint.name + ") Too many outstanding diffs, missed a version. Reinit.");
            this._init();
        }
    }

    _flushData() {
        this.data = {};
        this._v = 0;
        this.procBuffer = [];
        this.timeBuffer = [];

        this.timeSum = 0;
        this.timeCount = 0;

        this.outstandingDiffs = 0;

        this.ready = false;
    }

    _init() {

        this.data = {};
        this._v = 0;
        this.procBuffer = [];
        this.timeBuffer = [];

        this.timeSum = 0;
        this.timeCount = 0;

        this.outstandingDiffs = 0;

        this.ready = false;

        var postData = JSON.stringify({
            endpoint: "_SO_" + this.endpoint.name,
            input: "init"
        });
        var options = {
            hostname: this.initTransport.hostname,
            port: this.initTransport.port,
            path: '/',
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Content-Length': Buffer.byteLength(postData)
            }
        };

        var self = this;
        var req = http.request(options, (reply) => {
            var body = "";
            reply.on('data', function (data) {
                body += data;
            });
            reply.on('end', function () {
                var answer = JSON.parse(body);
                self.data = answer.res.data;
                self._v = answer.res.v;
                console.log("(" + self.endpoint.name + ") Init installed version", self._v);
                self.procBuffer.splice(0, self._v);
                self.timeBuffer.splice(0, self._v);
                self.outstandingDiffs = 0;
                for (let i of self.procBuffer) {
                    if (!!i)
                        self.outstandingDiffs++;
                }
                self.ready = true;
                self._tryApply();
                self.emit('init', self._v);
            });
        });

        var self = this;
        req.on('error', (e) => {
            console.error(`problem with request: ${e.message}`);
            setTimeout(self._init.bind(self), 1000); // Retry after a second
        });
        req.write(postData);
        req.end();
    }
}

module.exports = SharedObjectClient;<commit_msg>Expose full raw stream<commit_after>"use strict";
const NS_PER_SEC = 1e9;

var http = require("http");
var EventEmitter = require("events").EventEmitter;
var differ = require("deep-diff");

class SharedObjectClient extends EventEmitter {
    constructor(endpoint, transports) {
        super();
        if (!transports.rpc || !transports.source)
            throw new Error("Shared object " + endpoint.name + " needs both Source and RPC transports to be configured");

        this.endpoint = endpoint;
        this.initTransport = transports.rpc;
        this.updateTransport = transports.source;
        this.subscribed = false;

        this._flushData();
    }

    subscribe() {
        this.updateTransport.subscribe("_SO_" + this.endpoint.name);
        this.subscribed = true;
        this._init();
    }

    unsubscribe() {
        this.updateTransport.unsubscribe("_SO_" + this.endpoint.name);
        this.subscribed = false;
    }

    _processMessage(data) {
        if (data.endpoint == "_SO_" + this.endpoint.name) {

            this.emit('raw', {
                v: data.message.v,
                diffs: data.message.diffs
            });

            var idx = data.message.v - (this._v + 1);
            if (this.ready && idx < 0) {
                console.error("(" + this.endpoint.name + ") Bad version! Reinit!");
                return this._init();
            }
            this.procBuffer[idx] = data.message.diffs;
            this.timeBuffer[idx] = data.message.now;
            this.emit('timing', (new Date() - data.message.now) * 1000000);
            this.outstandingDiffs++;
            process.nextTick(this._tryApply.bind(this));
        }
    }

    _tryApply() {
        var totalDiffs = [];

        while (!!this.procBuffer[0]) {
            // Diffs are already reversed by Server!
            var diffs = this.procBuffer.shift();
            this.outstandingDiffs--;
            totalDiffs = diffs.concat(totalDiffs);

            for (let diff of diffs) {
                differ.applyChange(this.data, true, diff);
            }

            this.timeSum += new Date() - this.timeBuffer.shift();
            this.timeCount++;
            if (this.timeCount == 200) {
                console.log("(" + this.endpoint.name + ") Average time: " + (this.timeSum / 200) + " ms");
                this.timeSum = 0;
                this.timeCount = 0;
            }

            this._v++;
        }

        if (totalDiffs.length > 0) {
            this.emit('update', totalDiffs);
        } else if (this.ready && this.outstandingDiffs > 10) {
            console.error("(" + this.endpoint.name + ") Too many outstanding diffs, missed a version. Reinit.");
            this._init();
        }
    }

    _flushData() {
        this.data = {};
        this._v = 0;
        this.procBuffer = [];
        this.timeBuffer = [];

        this.timeSum = 0;
        this.timeCount = 0;

        this.outstandingDiffs = 0;

        this.ready = false;
    }

    _init() {

        this.data = {};
        this._v = 0;
        this.procBuffer = [];
        this.timeBuffer = [];

        this.timeSum = 0;
        this.timeCount = 0;

        this.outstandingDiffs = 0;

        this.ready = false;

        var postData = JSON.stringify({
            endpoint: "_SO_" + this.endpoint.name,
            input: "init"
        });
        var options = {
            hostname: this.initTransport.hostname,
            port: this.initTransport.port,
            path: '/',
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Content-Length': Buffer.byteLength(postData)
            }
        };

        var self = this;
        var req = http.request(options, (reply) => {
            var body = "";
            reply.on('data', function (data) {
                body += data;
            });
            reply.on('end', function () {
                var answer = JSON.parse(body);
                self.data = answer.res.data;
                self._v = answer.res.v;
                console.log("(" + self.endpoint.name + ") Init installed version", self._v);
                self.procBuffer.splice(0, self._v);
                self.timeBuffer.splice(0, self._v);
                self.outstandingDiffs = 0;
                for (let i of self.procBuffer) {
                    if (!!i)
                        self.outstandingDiffs++;
                }
                self.ready = true;
                self._tryApply();
                self.emit('init', {v: answer.res.v, data: answer.res.data});
            });
        });

        var self = this;
        req.on('error', (e) => {
            console.error(`problem with request: ${e.message}`);
            setTimeout(self._init.bind(self), 1000); // Retry after a second
        });
        req.write(postData);
        req.end();
    }
}

module.exports = SharedObjectClient;<|endoftext|>


<commit_before>// Redirect between plain HTTP and encrypted HTTPS according to
// `general_ssl_mode` global setting.
//
// http_only: Force HTTP everywhere.
// https_only: Force HTTPS everywhere.
// https_for_registered: Force HTTPS for users, and HTTP for guests.

'use strict';

var COOKIE_MAXAGE_LIKE_FOREVER = 0xFFFFFFFF;
var COOKIE_EXPIRES_IN_THE_PAST = new Date('Thu, 01 Jan 1970 00:00:00 GMT');

module.exports = function (N) {

  // Ensure HTTPS if "ssl" cookie is set *before* session load because
  // session id is stored as secure cookie - it's sent only encrypted.
  N.wire.before('server_chain:*', { priority: -82 }, function force_members_https(env, callback) {
    if ('1' !== env.extras.getCookie('ssl')) {
      // No cookie. Continue.
      callback();
      return;
    }

    if (env.request.isEncrypted) {
      // Already encrypted. Continue.
      callback();
      return;
    }

    var redirectUrl = env.helpers.url_to(env.method, env.params, { protocol: 'https' });

    if (!redirectUrl) {
      // Can't build URL - usually RPC-only method.
      callback({
        code: N.io.BAD_REQUEST
      , message: 'Encrypted connection is required'
      });
      return;
    }

    callback({
      code: N.io.REDIRECT
    , head: { Location: redirectUrl }
    });
  });

  // Helper to read "general_ssl_mode" setting used by next hooks.
  function isEncryptionRequired(env, callback) {
    N.settings.get('general_ssl_mode', {}, function (err, policy) {
      if (err) {
        callback(err);
        return;
      }

      switch (policy) {
      case 'https_off':
        callback(null, false);
        return;

      case 'https_always':
        callback(null, true);
        return;

      case 'https_members':
        if ('users.auth' === env.method.slice(0, 'users.auth'.length)) {
          // force true even for guests at login/register page
          callback(null, true);
        } else {
          callback(null, Boolean(env.session && env.session.user_id));
        }
        return;

      default:
        // Case for broken settings store.
        callback('Value of setting "general_ssl_mode" is unknown: ' +
                 JSON.stringify(policy));
        return;
      }
    });
  }

  // Main guest/user http/https redirector. Just after session load.
  N.wire.before('server_chain:*', { priority: -75 }, function switch_http_and_https(env, callback) {
    isEncryptionRequired(env, function (err, shouldBeEncrypted) {
      if (err) {
        callback(err);
        return;
      }

      if (env.request.isEncrypted === shouldBeEncrypted) {
        // Redirection is not needed. Continue.
        callback();
        return;
      }

      var redirectUrl = env.helpers.url_to(env.method, env.params, {
        protocol: shouldBeEncrypted ? 'https' : 'http'
      });

      if (!redirectUrl) {
        // Can't build URL - usually RPC-only method.
        callback({
          code: N.io.BAD_REQUEST
        , message: 'Encrypted connection is required'
        });
        return;
      }

      callback({
        code: N.io.REDIRECT
      , head: { Location: redirectUrl }
      });
    });
  });

  // Set cookie to keep secure connection for logged in users.
  N.wire.after('server_chain:*', { priority: 80, ensure: true }, function set_ssl_redirect_cookie(env, callback) {
    isEncryptionRequired(env, function (err, shouldBeEncrypted) {
      if (err) {
        callback(err);
        return;
      }

      if (env.session && env.session.user_id && shouldBeEncrypted) {
        // Add cookie for a HUGE amount of time.
        env.extras.setCookie('ssl', '1', { maxAge: COOKIE_MAXAGE_LIKE_FOREVER, path: '/' });
      } else {
        // Delete cookie by setting 'expires' to a past date.
        env.extras.setCookie('ssl', '0', { expires: COOKIE_EXPIRES_IN_THE_PAST, path: '/' });
      }
      callback();
    });
  });

  // Modify 'secure' flag of session id cookie.
  N.wire.after('server_chain:*', { priority: 85, ensure: true }, function set_sid_cookie_mode(env, callback) {
    if (!env.extras.setCookie.storage['sid']) {
      // No session id cookie.
      callback();
      return;
    }

    isEncryptionRequired(env, function (err, shouldBeEncrypted) {
      if (err) {
        callback(err);
        return;
      }

      env.extras.setCookie.storage['sid'].options.secure = shouldBeEncrypted;
      callback();
    });
  });
};
<commit_msg>Use `env.extras.updateCookie` helper.<commit_after>// Redirect between plain HTTP and encrypted HTTPS according to
// `general_ssl_mode` global setting.
//
// http_only: Force HTTP everywhere.
// https_only: Force HTTPS everywhere.
// https_for_registered: Force HTTPS for users, and HTTP for guests.

'use strict';

var COOKIE_MAXAGE_LIKE_FOREVER = 0xFFFFFFFF;
var COOKIE_EXPIRES_IN_THE_PAST = new Date('Thu, 01 Jan 1970 00:00:00 GMT');

module.exports = function (N) {

  // Ensure HTTPS if "ssl" cookie is set *before* session load because
  // session id is stored as secure cookie - it's sent only encrypted.
  N.wire.before('server_chain:*', { priority: -82 }, function force_members_https(env, callback) {
    if ('1' !== env.extras.getCookie('ssl')) {
      // No cookie. Continue.
      callback();
      return;
    }

    if (env.request.isEncrypted) {
      // Already encrypted. Continue.
      callback();
      return;
    }

    var redirectUrl = env.helpers.url_to(env.method, env.params, { protocol: 'https' });

    if (!redirectUrl) {
      // Can't build URL - usually RPC-only method.
      callback({
        code: N.io.BAD_REQUEST
      , message: 'Encrypted connection is required'
      });
      return;
    }

    callback({
      code: N.io.REDIRECT
    , head: { Location: redirectUrl }
    });
  });

  // Helper to read "general_ssl_mode" setting used by next hooks.
  function isEncryptionRequired(env, callback) {
    N.settings.get('general_ssl_mode', {}, function (err, policy) {
      if (err) {
        callback(err);
        return;
      }

      switch (policy) {
      case 'https_off':
        callback(null, false);
        return;

      case 'https_always':
        callback(null, true);
        return;

      case 'https_members':
        if ('users.auth' === env.method.slice(0, 'users.auth'.length)) {
          // force true even for guests at login/register page
          callback(null, true);
        } else {
          callback(null, Boolean(env.session && env.session.user_id));
        }
        return;

      default:
        // Case for broken settings store.
        callback('Value of setting "general_ssl_mode" is unknown: ' +
                 JSON.stringify(policy));
        return;
      }
    });
  }

  // Main guest/user http/https redirector. Just after session load.
  N.wire.before('server_chain:*', { priority: -75 }, function switch_http_and_https(env, callback) {
    isEncryptionRequired(env, function (err, shouldBeEncrypted) {
      if (err) {
        callback(err);
        return;
      }

      if (env.request.isEncrypted === shouldBeEncrypted) {
        // Redirection is not needed. Continue.
        callback();
        return;
      }

      var redirectUrl = env.helpers.url_to(env.method, env.params, {
        protocol: shouldBeEncrypted ? 'https' : 'http'
      });

      if (!redirectUrl) {
        // Can't build URL - usually RPC-only method.
        callback({
          code: N.io.BAD_REQUEST
        , message: 'Encrypted connection is required'
        });
        return;
      }

      callback({
        code: N.io.REDIRECT
      , head: { Location: redirectUrl }
      });
    });
  });

  // Set cookie to keep secure connection for logged in users.
  N.wire.after('server_chain:*', { priority: 80, ensure: true }, function set_ssl_redirect_cookie(env, callback) {
    isEncryptionRequired(env, function (err, shouldBeEncrypted) {
      if (err) {
        callback(err);
        return;
      }

      if (env.session && env.session.user_id && shouldBeEncrypted) {
        // Add cookie for a HUGE amount of time.
        env.extras.setCookie('ssl', '1', { maxAge: COOKIE_MAXAGE_LIKE_FOREVER, path: '/' });
      } else {
        // Delete cookie by setting 'expires' to a past date.
        env.extras.setCookie('ssl', '0', { expires: COOKIE_EXPIRES_IN_THE_PAST, path: '/' });
      }
      callback();
    });
  });

  // Modify 'secure' flag of session id cookie.
  N.wire.after('server_chain:*', { priority: 85, ensure: true }, function set_sid_cookie_mode(env, callback) {
    isEncryptionRequired(env, function (err, shouldBeEncrypted) {
      if (err) {
        callback(err);
        return;
      }

      env.extras.updateCookie('sid', { secure: shouldBeEncrypted });
      callback();
    });
  });
};
<|endoftext|>


<commit_before>/*
 * network.js: Openstack Security Group object.
 *
 * (C) 2015 Rackspace
 *      Shaunak Kashyap
 * MIT LICENSE
 */

var util = require('util'),
    base = require('../../core/network/securityGroup'),
    _ = require('lodash');

var SecurityGroup = exports.SecurityGroup = function SecurityGroup(client, details) {
  base.SecurityGroup.call(this, client, details);
};

util.inherits(SecurityGroup, base.SecurityGroup);

SecurityGroup.prototype._setProperties = function (details) {

  this.id = details.id || this.id;
  this.name = details.name || this.name;
  this.description = details.description || '';
  this.tenantId = details.tenant_id || this.tenantId;
  this.securityGroupRules = details.security_group_rules || this.securityGroupRules;
};

SecurityGroup.prototype.toJSON = function () {
  return _.pick(this, ['id', 'name', 'description', 'securityGroupRules', 'tenantId']);
};
<commit_msg>[openstack][network] camelize key name of security group list<commit_after>/*
 * network.js: Openstack Security Group object.
 *
 * (C) 2015 Rackspace
 *      Shaunak Kashyap
 * MIT LICENSE
 */

var util = require('util'),
    base = require('../../core/network/securityGroup'),
    _ = require('lodash');

var SecurityGroup = exports.SecurityGroup = function SecurityGroup(client, details) {
  base.SecurityGroup.call(this, client, details);
};

var SecurityGroupRule = require('./securityGroupRule').SecurityGroupRule;

util.inherits(SecurityGroup, base.SecurityGroup);

SecurityGroup.prototype._setProperties = function (details) {
  var self = this;

  this.id = details.id || this.id;
  this.name = details.name || this.name;
  this.description = details.description || '';
  this.tenantId = details.tenant_id || this.tenantId;
  this.securityGroupRules = details.security_group_rules.map(function (securityGroupRule) {
    return new SecurityGroupRule(self.client, securityGroupRule);
  });
};

SecurityGroup.prototype.toJSON = function () {
  return _.pick(this, ['id', 'name', 'description', 'securityGroupRules', 'tenantId']);
};
<|endoftext|>


<commit_before>"use strict";

var assert = require('assert');

var Game = function(goal) {

    var scoreBulls = function(guess, goal) {
	var bulls = 0;
	for (var i=0;i<guess.length;++i) {
	    if (guess[i] === goal[i])
		bulls++;
	}
	return bulls;
    };

    var scoreCows = function(guess, goal) {
	var cows = 0;
	for (var i=0;i<goal.length;++i) {
	    var desiredChar = goal[i];
	    for (var j=0;j<goal.length;++j) {
		if (j === i) continue;

		if (guess[j] === desiredChar) {
		    cows++;
		}
	    }
	}
	return cows;
    };

    this.score = function(guess) {
	assert(goal.length === guess.length, 'Lengths must be equivalent');

        return {
	    cows: scoreCows(guess,goal),
	    bulls: scoreBulls(guess,goal)
	};
    };

    var finishingScore = function(score) {
	return score.bulls === 4;
    };

    this.play = function(strategy) {
	var turns = 0;

	do {
	    turns++;
	    var guess = strategy.guess();
	    var score = this.score(guess);
	    strategy.update(score);
	} while (!finishingScore(score));

	return turns;
    };

    return this;
};

var asString = function(num) {
    var s = '0000' + num;
    return s.substr(s.length - 4);
};

var fromTo = function(start,end) {
    var arr = [];
    for (var i=start;i<=end;++i) {
	arr.push(i);
    }
    return arr;
};

var Player = function() {

    this.possibilities = fromTo(0,9999);

    this.guess = function() {
	return asString(1234);
    };

    return this;
};

var Naive = function() {

    this.currentGuess = 0;

    this.guess = function() {
	return asString(this.currentGuess);
    };

    this.update = function(guess, score) {
	this.currentGuess++;
    };

    return this;
};

var createGame = function(goal) {
    return new Game(goal);
};

describe("cows and bulls", function() {

    describe('playing naive', function() {
	it('should solve it within 9999 turns', function() {
	    var game = createGame('5555');
	    var turns = game.play(new Naive());

	    assert.equal(5556, turns);
	});
    });

    describe('intelligently playing', function() {

	var containsDuplicates = function(str) {
	    for (var i=0;i<str.length;++i) {
		var found = false;
		for (var j=0;j<str.length;++j) {
		    if (i === j) continue;

		    if (str[i] === str[j])
			return true;
		}
	    }
	    return false;
	};

	it('should have four unique numbers in initial guess', function() {
	    var player = new Player();

	    var initialGuess = player.guess();
	    assert(!containsDuplicates(initialGuess), 'no duplicates');
	});

	it('initial pool of answers is 10000', function() {
	    var player = new Player();

	    assert.equal(10000, player.possibilities.length);
	});
    });

    describe('scoring', function() {
	it('should match the example', function() {
	    var game = createGame('8045');
	    var result = game.score('0865');

	    assert.equal(2, result.cows);
	    assert.equal(1, result.bulls);
	});

	it('no matches scores no cows or bulls', function() {
            var game = createGame('1234');

            var r = game.score('5678');
            assert.equal(0,r.cows);
	    assert.equal(0,r.bulls);
	});

	it('all correct is all bulls', function() {
	    var game = createGame('1234');

	    var r = game.score('1234');
	    assert.equal(4, r.bulls);
	    assert.equal(0, r.cows);
	});

	it('all in wrong order is all cows', function() {
	    var game = createGame('1234');

	    var r = game.score('4321');
	    assert.equal(4, r.cows);
	    assert.equal(0, r.bulls);
	});
    });
});
<commit_msg>refactor<commit_after>"use strict";

var assert = require('assert');

var Game = function(goal) {

    var scoreBulls = function(guess, goal) {
	var bulls = 0;
	for (var i=0;i<guess.length;++i) {
	    if (guess[i] === goal[i])
		bulls++;
	}
	return bulls;
    };

    var scoreCows = function(guess, goal) {
	var cows = 0;
	for (var i=0;i<goal.length;++i) {
	    var desiredChar = goal[i];
	    for (var j=0;j<goal.length;++j) {
		if (j === i) continue;

		if (guess[j] === desiredChar) {
		    cows++;
		}
	    }
	}
	return cows;
    };

    this.score = function(guess) {
	assert(goal.length === guess.length, 'Lengths must be equivalent');

        return {
	    cows: scoreCows(guess,goal),
	    bulls: scoreBulls(guess,goal)
	};
    };

    var finishingScore = function(score) {
	return score.bulls === 4;
    };

    this.play = function(strategy) {
	var turns = 0;

	do {
	    turns++;
	    var guess = strategy.guess();
	    var score = this.score(guess);
	    strategy.update(score);
	} while (!finishingScore(score));

	return turns;
    };

    return this;
};

var asString = function(num) {
    var s = '0000' + num;
    return s.substr(s.length - 4);
};

var fromTo = function(start,end) {
    var arr = [];
    for (var i=start;i<=end;++i) {
	arr.push(i);
    }
    return arr;
};

var Player = function() {

    this.possibilities = fromTo(0,9999);

    this.guess = function() {
	return asString(1234);
    };

    return this;
};

var Naive = function() {

    this.currentGuess = 0;

    this.guess = function() {
	return asString(this.currentGuess);
    };

    this.update = function(guess, score) {
	this.currentGuess++;
    };

    return this;
};

var createGame = function(goal) {
    return new Game(goal);
};

var containsDuplicates = function(str) {
    for (var i=0;i<str.length;++i) {
	var found = false;
	for (var j=0;j<str.length;++j) {
	    if (i === j) continue;

	    if (str[i] === str[j])
		return true;
	}
    }
    return false;
};

describe("cows and bulls", function() {

    describe('playing naive', function() {
	it('should solve it within 9999 turns', function() {
	    var game = createGame('5555');
	    var turns = game.play(new Naive());

	    assert.equal(5556, turns);
	});
    });

    describe('intelligently playing', function() {

	it('should have four unique numbers in initial guess', function() {
	    var player = new Player();

	    var initialGuess = player.guess();
	    assert(!containsDuplicates(initialGuess), 'no duplicates');
	});

	it('initial pool of answers is 10000', function() {
	    var player = new Player();

	    assert.equal(10000, player.possibilities.length);
	});
    });

    describe('scoring', function() {
	it('should match the example', function() {
	    var game = createGame('8045');
	    var result = game.score('0865');

	    assert.equal(2, result.cows);
	    assert.equal(1, result.bulls);
	});

	it('no matches scores no cows or bulls', function() {
            var game = createGame('1234');

            var r = game.score('5678');
            assert.equal(0,r.cows);
	    assert.equal(0,r.bulls);
	});

	it('all correct is all bulls', function() {
	    var game = createGame('1234');

	    var r = game.score('1234');
	    assert.equal(4, r.bulls);
	    assert.equal(0, r.cows);
	});

	it('all in wrong order is all cows', function() {
	    var game = createGame('1234');

	    var r = game.score('4321');
	    assert.equal(4, r.cows);
	    assert.equal(0, r.bulls);
	});
    });
});
<|endoftext|>