<commit_before>"use strict";

var _ = require('lodash');
var i8n = require('inflection');
var path = require('path');
var resolve =require('resolve');
var Schema = require('./schema');

module.exports = Registry;

function Registry(context) {
    if (!this instanceof Registry) return new Registry(context);

    this.context = context || this;
    this.schemas = [];
    this.definitions = {};
    this.models = {};
    this.plugins = [];
}

Registry.prototype.use = function (plugin, opts) {
    if (typeof plugin === "string") {
        try {
            plugin = require(resolve.sync(plugin, { basedir: path.resolve('./') }));
        } catch (e) {
            throw e;
        }
    }

    plugin = new plugin(this, opts || {});

    if (typeof plugin.define === "function") {
        for (var k in this.models) {
            plugin.define(this.models[k]);
        }
    }

    this.plugins.push(plugin);

    return this;
};

Registry.prototype.define = function (/*name, desc, setup*/) {
    var i, arg, type, name, desc, setup;
    for (i = 0; i < arguments.length; i++) {
        arg = arguments[i];
        type = typeof arg;
        if (!name && type === 'string') {
            name = arg;
        } else if (!desc && (type === 'object' || type === 'function')) {
            desc = arg;
        } else if (!setup && type === 'function') {
            setup = arg;
        } else {
            throw new Error('Unsupported argument ' + arg);
        }
    }

    desc = desc || {};
    if (typeof desc === 'function') {
        desc = desc(Schema);
    }

    if (desc.name) {
        name = desc.name;
    }

    var def;

    desc = standartize(desc);
    def = findDefinition(this.definitions, name);
    if (def) {
        name = def.name;
        desc = _.merge(_.cloneDeep(def), desc);
    } else {
        desc.name = name;
    }
    this.definitions[name] = desc;
    this.setup(desc, setup);
    return desc;
};

var DEF_KEYS = ['name', 'properties', 'fields', 'relations', 'settings'];
function standartize(desc) {
    var result = _.pick(desc, DEF_KEYS);
    result.settings = _.assign({}, result.settings, _.omit(desc, DEF_KEYS));
    return result;
}

Registry.prototype.setup = function (name, setup) {
    if (typeof setup !== 'function') return;
    var def = findDefinition(this.definitions, name);

    if (!def) throw new Error('Unknown model ' + name + ' for setup');

    def.setups = def.setups || [];
    if (Array.isArray(setup)) {
        def.setups = def.setups.concat(setup);
    } else {
        def.setups.push(setup);
    }
};

Registry.prototype.build = function (options) {
    if (!options) {
        options = {db: {driver: 'memory'}};
    } else if (typeof options === 'string') {
        options = {db: {driver: options}};
    } else if (options.driver) {
        options = {db: options};
    }

    var self = this;
    var schemas = this.schemas = [];
    this.models = {};

    _.forEach(options, function (conf, name) {
        if (!conf || !conf.driver) {
            console.log('No config found for ' + name + ' schema, using in-memory schema');
            conf = {driver: 'memory'};
        }
        var schema = createSchema(conf.driver, conf);
        self._build(schema, conf.models);
        schema.name = name;
        schemas[name] = schema;
        schemas.push(schema);
    });

    return schemas;
};

Registry.prototype._build = function (schema, names) {
    if (names == '*') names = null;
    if (typeof names === 'string') names = [names];
    if (names && !Array.isArray(names)) {
        throw new Error('`names` must be a string or string array');
    }

    var context = this.context;
    var plugins = this.plugins;
    var models = this.models;
    var defs = names ? _.pick(this.definitions, names) : this.definitions;

    schema.on('beforeDefine', function(name, properties, settings) {
        for (var i = 0; i < plugins.length; i++) {
            if (typeof plugins[i].beforeDefine === "function") {
                plugins[i].beforeDefine(name, properties, settings);
            }
        }
    });

    schema.on('define', function(model, name, properties, settings) {
        models[name] = model;
        if (schema.backyard) {
            schema.backyard.define(name, properties, settings);
        }
        for (var i = 0; i < plugins.length; i++) {
            if (typeof plugins[i].define === "function") {
                plugins[i].define(model, name, properties, settings);
            }
        }
    });

    _.forEach(defs, function (def, name) {
        schema.define(name, def.properties || def.fields, def.settings);
    });

    _.forEach(defs, function (def) {
        buildRelations(schema, def);
    });

    _.forEach(defs, function (def) {
        if (!def.setups) return;
        for(var i = 0; i < def.setups.length; i++) {
            def.setups[i](models[def.name], context);
        }
    });
};

function findDefinition(definitions, name) {
    if (typeof name === 'object') return name;
    var possibles = [name, name.toLowerCase(), name.toUpperCase(), i8n.underscore(name), i8n.camelize(name)],
        i;
    for (i = 0; i < possibles.length; i++) {
        if (definitions[possibles[i]]) return definitions[possibles[i]];
    }
}

function createSchema(name, settings) {
    var schema = new Schema(name, settings);
    if (settings && settings.backyard) {
        schema.backyard = new Schema(settings.backyard.driver, settings.backyard);
    }
    return schema;
}

function buildRelations(schema, def) {
    if (!def.relations) return;
    var model = schema.models[def.name];
    var relations = def.relations;
    for (var name in relations) {
        var rel = relations[name];
        var target = rel.model,
            targetName,
            targetModel;

        if (!target) {
            target = i8n.singularize(name);
        }
        targetName = findKey(schema.models, target);
        if (targetName) {
            targetModel = schema.models[targetName];
        }

        if (!targetModel) {
            throw new Error(util.format('Unknown target model `%s` to build relationship %s.%s -> %s -> %s',
                target, model.modelName, name, rel.type, target));
        }

        var options = _.omit(rel, ['type', 'target', 'model']);
        options.as = options.as || name;
        model[rel.type](targetModel, options);
    }
}

function findKey(object, target) {
    var targetName = target.toLowerCase();
    return _.findKey(object, function (value, name) {
        return name.toLowerCase() === targetName;
    });
}
<commit_msg>check options empty for registry.build used in database boot phase<commit_after>"use strict";

var _ = require('lodash');
var i8n = require('inflection');
var path = require('path');
var resolve =require('resolve');
var Schema = require('./schema');

module.exports = Registry;

function Registry(context) {
    if (!this instanceof Registry) return new Registry(context);

    this.context = context || this;
    this.schemas = [];
    this.definitions = {};
    this.models = {};
    this.plugins = [];
}

Registry.prototype.use = function (plugin, opts) {
    if (typeof plugin === "string") {
        try {
            plugin = require(resolve.sync(plugin, { basedir: path.resolve('./') }));
        } catch (e) {
            throw e;
        }
    }

    plugin = new plugin(this, opts || {});

    if (typeof plugin.define === "function") {
        for (var k in this.models) {
            plugin.define(this.models[k]);
        }
    }

    this.plugins.push(plugin);

    return this;
};

Registry.prototype.define = function (/*name, desc, setup*/) {
    var i, arg, type, name, desc, setup;
    for (i = 0; i < arguments.length; i++) {
        arg = arguments[i];
        type = typeof arg;
        if (!name && type === 'string') {
            name = arg;
        } else if (!desc && (type === 'object' || type === 'function')) {
            desc = arg;
        } else if (!setup && type === 'function') {
            setup = arg;
        } else {
            throw new Error('Unsupported argument ' + arg);
        }
    }

    desc = desc || {};
    if (typeof desc === 'function') {
        desc = desc(Schema);
    }

    if (desc.name) {
        name = desc.name;
    }

    var def;

    desc = standartize(desc);
    def = findDefinition(this.definitions, name);
    if (def) {
        name = def.name;
        desc = _.merge(_.cloneDeep(def), desc);
    } else {
        desc.name = name;
    }
    this.definitions[name] = desc;
    this.setup(desc, setup);
    return desc;
};

var DEF_KEYS = ['name', 'properties', 'fields', 'relations', 'settings'];
function standartize(desc) {
    var result = _.pick(desc, DEF_KEYS);
    result.settings = _.assign({}, result.settings, _.omit(desc, DEF_KEYS));
    return result;
}

Registry.prototype.setup = function (name, setup) {
    if (typeof setup !== 'function') return;
    var def = findDefinition(this.definitions, name);

    if (!def) throw new Error('Unknown model ' + name + ' for setup');

    def.setups = def.setups || [];
    if (Array.isArray(setup)) {
        def.setups = def.setups.concat(setup);
    } else {
        def.setups.push(setup);
    }
};

Registry.prototype.build = function (options) {
    if (!options) {
        options = {db: {driver: 'memory'}};
    } else if (typeof options === 'string') {
        options = {db: {driver: options}};
    } else if (options.driver) {
        options = {db: options};
    }

    if (!_.isEmpty(options)) throw new Error('No database config provided');

    var self = this;
    var schemas = this.schemas = [];
    this.models = {};

    _.forEach(options, function (conf, name) {
        if (!conf || !conf.driver) {
            console.log('No config found for ' + name + ' schema, using in-memory schema');
            conf = {driver: 'memory'};
        }
        var schema = createSchema(conf.driver, conf);
        self._build(schema, conf.models);
        schema.name = name;
        schemas[name] = schema;
        schemas.push(schema);
    });

    return schemas;
};

Registry.prototype._build = function (schema, names) {
    if (names == '*') names = null;
    if (typeof names === 'string') names = [names];
    if (names && !Array.isArray(names)) {
        throw new Error('`names` must be a string or string array');
    }

    var context = this.context;
    var plugins = this.plugins;
    var models = this.models;
    var defs = names ? _.pick(this.definitions, names) : this.definitions;

    schema.on('beforeDefine', function(name, properties, settings) {
        for (var i = 0; i < plugins.length; i++) {
            if (typeof plugins[i].beforeDefine === "function") {
                plugins[i].beforeDefine(name, properties, settings);
            }
        }
    });

    schema.on('define', function(model, name, properties, settings) {
        models[name] = model;
        if (schema.backyard) {
            schema.backyard.define(name, properties, settings);
        }
        for (var i = 0; i < plugins.length; i++) {
            if (typeof plugins[i].define === "function") {
                plugins[i].define(model, name, properties, settings);
            }
        }
    });

    _.forEach(defs, function (def, name) {
        schema.define(name, def.properties || def.fields, def.settings);
    });

    _.forEach(defs, function (def) {
        buildRelations(schema, def);
    });

    _.forEach(defs, function (def) {
        if (!def.setups) return;
        for(var i = 0; i < def.setups.length; i++) {
            def.setups[i](models[def.name], context);
        }
    });
};

function findDefinition(definitions, name) {
    if (typeof name === 'object') return name;
    var possibles = [name, name.toLowerCase(), name.toUpperCase(), i8n.underscore(name), i8n.camelize(name)],
        i;
    for (i = 0; i < possibles.length; i++) {
        if (definitions[possibles[i]]) return definitions[possibles[i]];
    }
}

function createSchema(name, settings) {
    var schema = new Schema(name, settings);
    if (settings && settings.backyard) {
        schema.backyard = new Schema(settings.backyard.driver, settings.backyard);
    }
    return schema;
}

function buildRelations(schema, def) {
    if (!def.relations) return;
    var model = schema.models[def.name];
    var relations = def.relations;
    for (var name in relations) {
        var rel = relations[name];
        var target = rel.model,
            targetName,
            targetModel;

        if (!target) {
            target = i8n.singularize(name);
        }
        targetName = findKey(schema.models, target);
        if (targetName) {
            targetModel = schema.models[targetName];
        }

        if (!targetModel) {
            throw new Error(util.format('Unknown target model `%s` to build relationship %s.%s -> %s -> %s',
                target, model.modelName, name, rel.type, target));
        }

        var options = _.omit(rel, ['type', 'target', 'model']);
        options.as = options.as || name;
        model[rel.type](targetModel, options);
    }
}

function findKey(object, target) {
    var targetName = target.toLowerCase();
    return _.findKey(object, function (value, name) {
        return name.toLowerCase() === targetName;
    });
}
<|endoftext|>


<commit_before>(function() {

  /*
  We'll have some collectibles:

  - Ones that give 50, 100, 500, 1000 points.

  - One to clone pappu that'll kill all
    forks, branches, pakias.

  - One for pappu's invincibility
  */

  mit.Collectible = function() {

    // x/y pos
    this.x;
    this.y;

    // width/height
    this.w;
    this.h;

    // Collectible Type - read above
    this.type;

    // Some collectible types may have subtypes
    // like coins of 50, 100, 500, 1000 and so on ...
    this.sub_type;

    this.getBounds = function() {
      var b = {};

      b.start_x = this.x;
      b.start_y = this.y;
      b.end_x   = this.x + this.w;
      b.end_y   = this.y + this.h;

      return b;
    };

    this.draw = function(ctx) {
      switch (this.type) {

        case 'coin':
          this.drawCoin(ctx);
          break;

        case 'clone':
          this.drawClone(ctx);
          break;

        case 'invincible':
          this.drawInvincible(ctx);
          break;

      }

      return;
    };

    this.drawCoin = function(ctx) {
      // Get coin color based on sub type
      var color = mit.CollectibleUtils.getCoinColor(this.sub_type);

      ctx.beginPath();

      ctx.fillStyle = color;

      ctx.arc(
        this.x,
        this.y,
        this.w/2,
        0,
        2*Math.PI,
        false
      );

      ctx.fill();
      ctx.closePath();
    };

    this.drawClone = function(ctx) {
      ctx.drawImage(
        mit.CollectibleUtils.clone_img,
        this.x,
        this.y
      );
    };

    this.drawInvincible = function(ctx) {
      ctx.drawImage(
        mit.CollectibleUtils.invincible_img,
        this.x,
        this.y
      );
    };
  };

  mit.CollectibleUtils = {

    collecs: [],

    count: 2,

    types: ['clone'],
    //types: ['clone'],

    sub_types: {
      coin: [50, 100, 500, 1000]
    },

    init: function() {
      this.clone_img = new Image();
      this.clone_img.src = 'img/berries.png';

      this.invincible_img = new Image();
      this.invincible_img.src = 'img/apple.png';
    },

    getCoinColor: function(sub_type) {

      switch (sub_type) {
        case 50:
          return 'yellow';

        case 100:
          return 'blue';

        case 500:
          return 'orange';

        case 1000:
          return 'purple';
      }

    },

    getRandomPos: function() {
      var pos = {};

      var last = this.collecs[this.collecs.length - 1];

      if (last) {
        pos.x = last.x + utils.randomNumber(1000, 1500);
      }
      else {
        pos.x = utils.randomNumber(2000, 3000);
        pos.x = utils.randomNumber(500, 1000);
      }

      pos.y = utils.randomNumber(100, mit.H-100);

      // Check Positioning with forks
      var forks = mit.ForkUtils.forks;

      if (forks.length) {
        forks.forEach(function(fork) {
          if (Math.abs(pos.x - fork.x) < 300)
            pos.x = fork.x + 300;
        });
      }

      // Check Positioning with branches
      var branches = mit.BranchUtils.branches;

      if (branches.length) {
        branches.forEach(function(branch) {
          if (Math.abs(pos.x - branch.x) < 300)
            pos.x = branch.x + 300;
        });
      }

      return pos;
    },

    create: function() {
      var count = this.count - this.collecs.length;
      var collec,
          sub_types,
          pos;

      for (var i = 0; i < count; i++) {
        collec = new mit.Collectible();

        pos = this.getRandomPos();

        collec.x = pos.x;
        collec.y = pos.y;

        collec.w = 30;
        collec.h = 30;

        // Type
        collec.type = this.types[utils.randomNumber(0, this.types.length-1)];

        // Choosing Sub types if any
        sub_types = this.sub_types[collec.type];
        if (sub_types)
          collec.sub_type = sub_types[utils.randomNumber(0, sub_types.length-1)];

        this.collecs.push(collec);
      }
    },

    draw: function(ctx) {

      var self = this;

      self.create();

      self.collecs.forEach(function(collec, i) {
        if (collec.x < 0) {
          // Moved off the left edge
          /*var pos = self.getRandomPos();

          collec.x = pos.x;
          collec.y = pos.y;*/
          self.collecs.splice(i,1);
        }

        collec.x -= mit.Backgrounds.ground_bg_move_speed;

        collec.draw(ctx);
      });

      return;
    },

    checkCollision: function() {
      // First collec
      var collec = this.collecs[0],
          // Get Pappu Bounds
          pappu_bounds = mit.Pappu.getBounds(),
          // Get Nearest Collectible Bounds
          collec_bounds = collec.getBounds();

      if (utils.intersect(pappu_bounds, collec_bounds)) {
        // Pappu haz collected!

        // Determine type and perform action accordingly
        switch (collec.type) {

          case 'coin':
            mit.score += collec.sub_type;
            break;

          case 'clone':
            mit.Pappu.createClones(3);
            break;

          case 'invincible':
            mit.Pappu.invincible = 1;
            setTimeout(mit.Pappu.undoInvincible, 5000);
            break;
        }

        // Nuke the collectible
        this.collecs.shift();
      }

      return;
    }

  };

  mit.CollectibleUtils.init();

}());<commit_msg>fixes<commit_after>(function() {

  /*
  We'll have some collectibles:

  - Ones that give 50, 100, 500, 1000 points.

  - One to clone pappu that'll kill all
    forks, branches, pakias.

  - One for pappu's invincibility
  */

  mit.Collectible = function() {

    // x/y pos
    this.x;
    this.y;

    // width/height
    this.w;
    this.h;

    // Collectible Type - read above
    this.type;

    // Some collectible types may have subtypes
    // like coins of 50, 100, 500, 1000 and so on ...
    this.sub_type;

    this.getBounds = function() {
      var b = {};

      b.start_x = this.x;
      b.start_y = this.y;
      b.end_x   = this.x + this.w;
      b.end_y   = this.y + this.h;

      return b;
    };

    this.draw = function(ctx) {
      switch (this.type) {

        case 'coin':
          this.drawCoin(ctx);
          break;

        case 'clone':
          this.drawClone(ctx);
          break;

        case 'invincible':
          this.drawInvincible(ctx);
          break;

      }

      return;
    };

    this.drawCoin = function(ctx) {
      // Get coin color based on sub type
      var color = mit.CollectibleUtils.getCoinColor(this.sub_type);

      ctx.beginPath();

      ctx.fillStyle = color;

      ctx.arc(
        this.x,
        this.y,
        this.w/2,
        0,
        2*Math.PI,
        false
      );

      ctx.fill();
      ctx.closePath();
    };

    this.drawClone = function(ctx) {
      ctx.drawImage(
        mit.CollectibleUtils.clone_img,
        this.x,
        this.y
      );
    };

    this.drawInvincible = function(ctx) {
      ctx.drawImage(
        mit.CollectibleUtils.invincible_img,
        this.x,
        this.y
      );
    };
  };

  mit.CollectibleUtils = {

    collecs: [],

    count: 2,

    types: ['coin', 'clone', 'invincible'],
    //types: ['clone'],

    sub_types: {
      coin: [50, 100, 500, 1000]
    },

    init: function() {
      this.clone_img = new Image();
      this.clone_img.src = 'img/berries.png';

      this.invincible_img = new Image();
      this.invincible_img.src = 'img/apple.png';
    },

    getCoinColor: function(sub_type) {

      switch (sub_type) {
        case 50:
          return 'yellow';

        case 100:
          return 'blue';

        case 500:
          return 'orange';

        case 1000:
          return 'purple';
      }

    },

    getRandomPos: function() {
      var pos = {};

      var last = this.collecs[this.collecs.length - 1];

      if (last) {
        pos.x = last.x + utils.randomNumber(1000, 1500);
      }
      else {
        pos.x = utils.randomNumber(2000, 3000);
        pos.x = utils.randomNumber(500, 1000);
      }

      pos.y = utils.randomNumber(100, mit.H-100);

      // Check Positioning with forks
      var forks = mit.ForkUtils.forks;

      if (forks.length) {
        forks.forEach(function(fork) {
          if (Math.abs(pos.x - fork.x) < 300)
            pos.x = fork.x + 300;
        });
      }

      // Check Positioning with branches
      var branches = mit.BranchUtils.branches;

      if (branches.length) {
        branches.forEach(function(branch) {
          if (Math.abs(pos.x - branch.x) < 300)
            pos.x = branch.x + 300;
        });
      }

      return pos;
    },

    create: function() {
      var count = this.count - this.collecs.length;
      var collec,
          sub_types,
          pos;

      for (var i = 0; i < count; i++) {
        collec = new mit.Collectible();

        pos = this.getRandomPos();

        collec.x = pos.x;
        collec.y = pos.y;

        collec.w = 30;
        collec.h = 30;

        // Type
        collec.type = this.types[utils.randomNumber(0, this.types.length-1)];

        // Choosing Sub types if any
        sub_types = this.sub_types[collec.type];
        if (sub_types)
          collec.sub_type = sub_types[utils.randomNumber(0, sub_types.length-1)];

        this.collecs.push(collec);
      }
    },

    draw: function(ctx) {

      var self = this;

      self.create();

      self.collecs.forEach(function(collec, i) {
        if (collec.x < 0) {
          // Moved off the left edge
          /*var pos = self.getRandomPos();

          collec.x = pos.x;
          collec.y = pos.y;*/
          self.collecs.splice(i,1);
        }

        collec.x -= mit.Backgrounds.ground_bg_move_speed;

        collec.draw(ctx);
      });

      return;
    },

    checkCollision: function() {
      // First collec
      var collec = this.collecs[0],
          // Get Pappu Bounds
          pappu_bounds = mit.Pappu.getBounds(),
          // Get Nearest Collectible Bounds
          collec_bounds = collec.getBounds();

      if (utils.intersect(pappu_bounds, collec_bounds)) {
        // Pappu haz collected!

        // Determine type and perform action accordingly
        switch (collec.type) {

          case 'coin':
            mit.score += collec.sub_type;
            break;

          case 'clone':
            mit.Pappu.createClones(3);
            break;

          case 'invincible':
            mit.Pappu.invincible = 1;
            setTimeout(mit.Pappu.undoInvincible, 5000);
            break;
        }

        // Nuke the collectible
        this.collecs.shift();
      }

      return;
    }

  };

  mit.CollectibleUtils.init();

}());<|endoftext|>


<commit_before>var util = require('util')

var helper = require('../helper')

var BaseReporter = function (formatError, reportSlow, adapter) {
  this.adapters = [adapter || process.stdout.write.bind(process.stdout)]

  this.onRunStart = function () {
    this._browsers = []
  }

  this.onBrowserStart = function (browser) {
    this._browsers.push(browser)
  }

  this.renderBrowser = function (browser) {
    var results = browser.lastResult
    var totalExecuted = results.success + results.failed
    var msg = util.format('%s: Executed %d of %d', browser, totalExecuted, results.total)

    if (results.failed) {
      msg += util.format(this.X_FAILED, results.failed)
    }

    if (results.skipped) {
      msg += util.format(' (skipped %d)', results.skipped)
    }

    if (browser.isReady) {
      if (results.disconnected) {
        msg += this.FINISHED_DISCONNECTED
      } else if (results.error) {
        msg += this.FINISHED_ERROR
      } else if (!results.failed) {
        msg += this.FINISHED_SUCCESS
      }

      msg += util.format(' (%s / %s)', helper.formatTimeInterval(results.totalTime),
        helper.formatTimeInterval(results.netTime))
    }

    return msg
  }

  this.renderBrowser = this.renderBrowser.bind(this)

  this.write = function () {
    var msg = util.format.apply(null, Array.prototype.slice.call(arguments))

    this.adapters.forEach(function (adapter) {
      adapter(msg)
    })
  }

  this.writeCommonMsg = this.write

  this.onBrowserError = function (browser, error) {
    this.writeCommonMsg(util.format(this.ERROR, browser) + formatError(error, '  '))
  }

  this.onBrowserLog = function (browser, log, type) {
    if (!helper.isString(log)) {
      // TODO(vojta): change util to new syntax (config object)
      log = util.inspect(log, false, undefined, this.USE_COLORS)
    }

    if (this._browsers && this._browsers.length === 1) {
      this.writeCommonMsg(util.format(this.LOG_SINGLE_BROWSER, type.toUpperCase(), log))
    } else {
      this.writeCommonMsg(util.format(this.LOG_MULTI_BROWSER, browser, type.toUpperCase(), log))
    }
  }

  this.onSpecComplete = function (browser, result) {
    if (result.skipped) {
      this.specSkipped(browser, result)
    } else if (result.success) {
      this.specSuccess(browser, result)
    } else {
      this.specFailure(browser, result)
    }

    if (reportSlow && result.time > reportSlow) {
      var specName = result.suite.join(' ') + ' ' + result.description
      var time = helper.formatTimeInterval(result.time)

      this.writeCommonMsg(util.format(this.SPEC_SLOW, browser, time, specName))
    }
  }

  this.specSuccess = this.specSkipped = function () {}

  this.specFailure = function (browser, result) {
    var specName = result.suite.join(' ') + ' ' + result.description
    var msg = util.format(this.SPEC_FAILURE, browser, specName)

    result.log.forEach(function (log) {
      msg += formatError(log, '\t')
    })

    this.writeCommonMsg(msg)
  }

  this.onRunComplete = function (browsers, results) {
    if (browsers.length > 1 && !results.error && !results.disconnected) {
      if (!results.failed) {
        this.write(this.TOTAL_SUCCESS, results.success)
      } else {
        this.write(this.TOTAL_FAILED, results.failed, results.success)
      }
    }
  }

  this.USE_COLORS = false

  this.LOG_SINGLE_BROWSER = '%s: %s\n'
  this.LOG_MULTI_BROWSER = '%s %s: %s\n'

  this.SPEC_FAILURE = '%s %s FAILED' + '\n'
  this.SPEC_SLOW = '%s SLOW %s: %s\n'
  this.ERROR = '%s ERROR\n'

  this.FINISHED_ERROR = ' ERROR'
  this.FINISHED_SUCCESS = ' SUCCESS'
  this.FINISHED_DISCONNECTED = ' DISCONNECTED'

  this.X_FAILED = ' (%d FAILED)'

  this.TOTAL_SUCCESS = 'TOTAL: %d SUCCESS\n'
  this.TOTAL_FAILED = 'TOTAL: %d FAILED, %d SUCCESS\n'
}

BaseReporter.decoratorFactory = function (formatError, reportSlow) {
  return function (self) {
    BaseReporter.call(self, formatError, reportSlow)
  }
}

BaseReporter.decoratorFactory.$inject = ['formatError', 'config.reportSlowerThan']

// PUBLISH
module.exports = BaseReporter
<commit_msg>Fix ENOMEM bug when dealing with very large numbers of tests / large amount of output<commit_after>var util = require('util')

var helper = require('../helper')

var chunkedWrite = function(output, f) {
    function chunkString(str, len) {
      var size = Math.ceil(str.length / len);
      var ret = new Array(size);
      var offset;

      for (var i = 0; i < size; i++) {
        offset = i * len;
        ret[i] = str.substring(offset, offset + len);
      }

      return ret;
    }

    var chunks = chunkString(output, 1024);

    chunks.forEach(
      function(c) {
        if (f) {
          f(c);
        }
        else {
          process.stdout.write(c);
        }
      });
}

var BaseReporter = function (formatError, reportSlow, adapter) {
  this.adapters = [adapter || chunkedWrite];

  this.onRunStart = function () {
    this._browsers = []
  }

  this.onBrowserStart = function (browser) {
    this._browsers.push(browser)
  }

  this.renderBrowser = function (browser) {
    var results = browser.lastResult
    var totalExecuted = results.success + results.failed
    var msg = util.format('%s: Executed %d of %d', browser, totalExecuted, results.total)

    if (results.failed) {
      msg += util.format(this.X_FAILED, results.failed)
    }

    if (results.skipped) {
      msg += util.format(' (skipped %d)', results.skipped)
    }

    if (browser.isReady) {
      if (results.disconnected) {
        msg += this.FINISHED_DISCONNECTED
      } else if (results.error) {
        msg += this.FINISHED_ERROR
      } else if (!results.failed) {
        msg += this.FINISHED_SUCCESS
      }

      msg += util.format(' (%s / %s)', helper.formatTimeInterval(results.totalTime),
        helper.formatTimeInterval(results.netTime))
    }

    return msg
  }

  this.renderBrowser = this.renderBrowser.bind(this)

  this.write = function () {
    var msg = util.format.apply(null, Array.prototype.slice.call(arguments))

    this.adapters.forEach(function (adapter) {
      chunkedWrite(msg, adapter);
    })
  }

  this.writeCommonMsg = this.write

  this.onBrowserError = function (browser, error) {
    this.writeCommonMsg(util.format(this.ERROR, browser) + formatError(error, '  '))
  }

  this.onBrowserLog = function (browser, log, type) {
    if (!helper.isString(log)) {
      // TODO(vojta): change util to new syntax (config object)
      log = util.inspect(log, false, undefined, this.USE_COLORS)
    }

    if (this._browsers && this._browsers.length === 1) {
      this.writeCommonMsg(util.format(this.LOG_SINGLE_BROWSER, type.toUpperCase(), log))
    } else {
      this.writeCommonMsg(util.format(this.LOG_MULTI_BROWSER, browser, type.toUpperCase(), log))
    }
  }

  this.onSpecComplete = function (browser, result) {
    if (result.skipped) {
      this.specSkipped(browser, result)
    } else if (result.success) {
      this.specSuccess(browser, result)
    } else {
      this.specFailure(browser, result)
    }

    if (reportSlow && result.time > reportSlow) {
      var specName = result.suite.join(' ') + ' ' + result.description
      var time = helper.formatTimeInterval(result.time)

      this.writeCommonMsg(util.format(this.SPEC_SLOW, browser, time, specName))
    }
  }

  this.specSuccess = this.specSkipped = function () {}

  this.specFailure = function (browser, result) {
    var specName = result.suite.join(' ') + ' ' + result.description
    var msg = util.format(this.SPEC_FAILURE, browser, specName)

    result.log.forEach(function (log) {
      msg += formatError(log, '\t')
    })

    this.writeCommonMsg(msg)
  }

  this.onRunComplete = function (browsers, results) {
    if (browsers.length > 1 && !results.error && !results.disconnected) {
      if (!results.failed) {
        this.write(this.TOTAL_SUCCESS, results.success)
      } else {
        this.write(this.TOTAL_FAILED, results.failed, results.success)
      }
    }
  }

  this.USE_COLORS = false

  this.LOG_SINGLE_BROWSER = '%s: %s\n'
  this.LOG_MULTI_BROWSER = '%s %s: %s\n'

  this.SPEC_FAILURE = '%s %s FAILED' + '\n'
  this.SPEC_SLOW = '%s SLOW %s: %s\n'
  this.ERROR = '%s ERROR\n'

  this.FINISHED_ERROR = ' ERROR'
  this.FINISHED_SUCCESS = ' SUCCESS'
  this.FINISHED_DISCONNECTED = ' DISCONNECTED'

  this.X_FAILED = ' (%d FAILED)'

  this.TOTAL_SUCCESS = 'TOTAL: %d SUCCESS\n'
  this.TOTAL_FAILED = 'TOTAL: %d FAILED, %d SUCCESS\n'
}

BaseReporter.decoratorFactory = function (formatError, reportSlow) {
  return function (self) {
    BaseReporter.call(self, formatError, reportSlow)
  }
}

BaseReporter.decoratorFactory.$inject = ['formatError', 'config.reportSlowerThan']

// PUBLISH
module.exports = BaseReporter
<|endoftext|>


<commit_before>'use strict';

var chalk = require('chalk');
var basename = require('path').basename;

module.exports = function specReporter(argv, cli){
  return function(err, context){
    if(err)
      cli.error(chalk.red('FAILED: ' + prettyName(context.spec.path)))
      , argv.verbose && cli.error(err.message)
      , argv.verbose && cli.error(context.output);
    else
      cli.praise(chalk.green('PASSED: ' + prettyName(context.spec.path)));
  };
};

function prettyName(path){
  return basename(path, '.spun').replace(/[^a-z0-9]/g, ' ');
}
<commit_msg>closes #11: Display browser in reporting.<commit_after>'use strict';

var chalk = require('chalk');
var basename = require('path').basename;

module.exports = function specReporter(argv, cli){
  return function(err, context){
    var browser = context.browser;
    if(err)
      cli.error(chalk.red(prefixed(browser) + prettyName(context.spec.path)))
      , argv.verbose && cli.error(err.message)
      , argv.verbose && cli.error(context.output);
    else
      cli.praise(chalk.green(prefixed(browser) + prettyName(context.spec.path)));
  };
};

function prefixed(prefix){
  return prefix + '          :  '.substring(prefix.length);
}

function prettyName(path){
  return basename(path, '.spun').replace(/[^a-z0-9]/g, ' ');
}
<|endoftext|>


<commit_before>/*!
 * Start Bootstrap - Createive v4.0.0-alpha (http://startbootstrap.com/template-overviews/creative)
 * Copyright 2013-2018 Start Bootstrap
 * Licensed under MIT (https://github.com/BlackrockDigital/startbootstrap-creative/blob/master/LICENSE)
 */
!function(e){"use strict";e('a[href*="#"]:not([href="#"])').click(function(){if(location.pathname.replace(/^\//,"")==this.pathname.replace(/^\//,"")&&location.hostname==this.hostname){var a=e(this.hash);if((a=a.length?a:e("[name="+this.hash.slice(1)+"]")).length)return e("html, body").animate({scrollTop:a.offset().top-48},1e3,"easeInOutExpo"),!1}}),e("body").scrollspy({target:"#mainNav",offset:48}),e(".navbar-collapse>ul>li>a").click(function(){e(".navbar-collapse").collapse("hide")}),e(window).scroll(function(){100<e("#mainNav").offset().top?e("#mainNav").addClass("navbar-shrink"):e("#mainNav").removeClass("navbar-shrink")}),window.sr=ScrollReveal(),sr.reveal(".sr-icons",{duration:600,scale:.3,distance:"0px"},200),sr.reveal(".sr-button",{duration:1e3,delay:200}),sr.reveal(".sr-contact",{duration:600,scale:.3,distance:"0px"},300),e(".popup-gallery").magnificPopup({delegate:"a",type:"image",tLoading:"Loading image #%curr%...",mainClass:"mfp-img-mobile",gallery:{enabled:!0,navigateByImgClick:!0,preload:[0,1]},image:{tError:'The image #%curr% could not be loaded.'}})}(jQuery);<commit_msg>Fixed minified css<commit_after>/*!
 * Start Bootstrap - Createive v4.0.0-alpha (http://startbootstrap.com/template-overviews/creative)
 * Copyright 2013-2018 Start Bootstrap
 * Licensed under MIT (https://github.com/BlackrockDigital/startbootstrap-creative/blob/master/LICENSE)
 */
!function(e){"use strict";e('a[href*="#"]:not([href="#"])').click(function(){if(location.pathname.replace(/^\//,"")==this.pathname.replace(/^\//,"")&&location.hostname==this.hostname){var a=e(this.hash);if((a=a.length?a:e("[name="+this.hash.slice(1)+"]")).length)return e("html, body").animate({scrollTop:a.offset().top-48},1e3,"easeInOutExpo"),!1}}),e("body").scrollspy({target:"#mainNav",offset:48}),e(".navbar-collapse>ul>li>a").click(function(){e(".navbar-collapse").collapse("hide")}),e(window).scroll(function(){100<e("#mainNav").offset().top?e("#mainNav").addClass("navbar-shrink"):e("#mainNav").removeClass("navbar-shrink")}),window.sr=ScrollReveal(),sr.reveal(".sr-icons",{duration:600,scale:.3,distance:"0px"},200),sr.reveal(".sr-button",{duration:1e3,delay:200}),sr.reveal(".sr-contact",{duration:600,scale:.3,distance:"0px"},300)}(jQuery);<|endoftext|>


<commit_before>var request = require('request'),
    _ = require('underscore'),
    passError = require('../util/passError');

require('bufferjs');

module.exports = function () {
    return function http(assetConfig, fromUrl, cb) {
        var url = assetConfig.url;
        assetConfig.rawSrcProxy = function (cb) {
            var matchUrl = url.match(/^([^#]*)((?:#.*)?)$/),
                urlWithoutFragmentIdentifier = matchUrl[1],
                fragmentIdentifier = matchUrl[2],
                requestOptions = http.requestOptions || {},
                numRetries = requestOptions.numRetries || 0;

            (function doRequest() {
                // Hack: Allows you to control the request options by setting the 'requestOptions' of the returned function to
                // an object.
                var req = request(_.defaults({
                    uri: urlWithoutFragmentIdentifier,
                    onResponse: true
                }, requestOptions), function (err, response) {
                    if (err) {
                        if (typeof numRetries === 'number' && numRetries > 0) {
                            numRetries -= 1;
                            return doRequest();
                        } else {
                            return cb(err);
                        }
                    }
                    if (response.statusCode >= 400) {
                        cb(new Error("Got " + response.statusCode + " from remote server: " + url));
                    } else {
                        var metadata = {
                                url: req.uri.href + fragmentIdentifier // Might be different from the originally requested url if redirects were followed
                            },
                            buffers = [];
                        if ('content-type' in response.headers) {
                            var matchContentType = response.headers['content-type'].match(/^\s*([\w\-\+\.]+\/[\w\-\+\.]+)\s*(?:;\s*charset=([\'\"]|)\s*([\w\-]+)\s*\2\s*)?$/i);
                            if (matchContentType) {
                                metadata.contentType = matchContentType[1].toLowerCase();
                                if (matchContentType[3]) {
                                    metadata.encoding = matchContentType[3].toLowerCase();
                                }
                            } else {
                                console.warn("resolvers.http: Couldn't parse Content-Type " + response.headers['content-type'] + " while fetching " + url);
                            }
                        }
                        if ('etag' in response.headers) {
                            metadata.etag = response.headers.etag;
                        }
                        if ('cache-control' in response.headers) {
                            metadata.cacheControl = response.headers['cache-control'];
                        }
                        ['date', 'last-modified'].forEach(function (headerName) {
                            if (headerName in response.headers) {
                                metadata[headerName.replace(/-([a-z])/, function ($0, ch) {
                                    return ch.toUpperCase();
                                })] = new Date(response.headers[headerName]);
                            }
                        });
                        response.on('data', function (buffer) {
                            buffers.push(buffer);
                        }).on('end', function () {
                            cb(null, Buffer.concat(buffers), metadata);
                        }).on('error', cb);
                    }
                });
            }());
        };
        assetConfig.isResolved = true;
        process.nextTick(function () {
            cb(null, assetConfig);
        });
    };
};
<commit_msg>resolvers.http: More liberal parsing of the Content-Type header.<commit_after>var request = require('request'),
    _ = require('underscore'),
    passError = require('../util/passError');

require('bufferjs');

module.exports = function () {
    return function http(assetConfig, fromUrl, cb) {
        var url = assetConfig.url;
        assetConfig.rawSrcProxy = function (cb) {
            var matchUrl = url.match(/^([^#]*)((?:#.*)?)$/),
                urlWithoutFragmentIdentifier = matchUrl[1],
                fragmentIdentifier = matchUrl[2],
                requestOptions = http.requestOptions || {},
                numRetries = requestOptions.numRetries || 0;

            (function doRequest() {
                // Hack: Allows you to control the request options by setting the 'requestOptions' of the returned function to
                // an object.
                var req = request(_.defaults({
                    uri: urlWithoutFragmentIdentifier,
                    onResponse: true
                }, requestOptions), function (err, response) {
                    if (err) {
                        if (typeof numRetries === 'number' && numRetries > 0) {
                            numRetries -= 1;
                            return doRequest();
                        } else {
                            return cb(err);
                        }
                    }
                    if (response.statusCode >= 400) {
                        cb(new Error("Got " + response.statusCode + " from remote server: " + url));
                    } else {
                        var metadata = {
                                url: req.uri.href + fragmentIdentifier // Might be different from the originally requested url if redirects were followed
                            },
                            buffers = [];
                        if ('content-type' in response.headers) {
                            var matchContentType = response.headers['content-type'].match(/^\s*([\w\-\+\.]+\/[\w\-\+\.]+).*(?:;\s*charset\s*=\s*([\'\"]|)\s*([\w\-]+)\s*\2\s*)?/i);
                            if (matchContentType) {
                                metadata.contentType = matchContentType[1].toLowerCase();
                                if (matchContentType[3]) {
                                    metadata.encoding = matchContentType[3].toLowerCase();
                                }
                            } else {
                                console.warn("resolvers.http: Couldn't parse Content-Type " + response.headers['content-type'] + " while fetching " + url);
                            }
                        }
                        if ('etag' in response.headers) {
                            metadata.etag = response.headers.etag;
                        }
                        if ('cache-control' in response.headers) {
                            metadata.cacheControl = response.headers['cache-control'];
                        }
                        ['date', 'last-modified'].forEach(function (headerName) {
                            if (headerName in response.headers) {
                                metadata[headerName.replace(/-([a-z])/, function ($0, ch) {
                                    return ch.toUpperCase();
                                })] = new Date(response.headers[headerName]);
                            }
                        });
                        response.on('data', function (buffer) {
                            buffers.push(buffer);
                        }).on('end', function () {
                            cb(null, Buffer.concat(buffers), metadata);
                        }).on('error', cb);
                    }
                });
            }());
        };
        assetConfig.isResolved = true;
        process.nextTick(function () {
            cb(null, assetConfig);
        });
    };
};
<|endoftext|>


<commit_before>class DCFLazyLoad {
  constructor(itemList, observerConfig, classNames) {
    this.itemList = itemList;
    this.observerConfig = observerConfig;
    this.classNames = classNames;
  }

  pxTOvw(value) {
    const zeroIndex = 0;
    const oneHundred = 100;
    const docElement = document.documentElement,
      docBody = document.getElementsByTagName('body')[zeroIndex],
      windowWidth = window.innerWidth || docElement.clientWidth || docBody.clientWidth;

    const result = oneHundred * value / windowWidth;
    return `${result }vw`;
  }

  /**
   * Apply the image: preloaded image is loaded but not applied to actual image element
   * @param {string} image: the image element that we are targetting
   */
  applyImage(image) {
    const src = image.dataset.src;
    const srcset = image.dataset.srcset || null;
    let sizes = null;

    if (!src) {
      return;
    }

    // Process parent picture lazy load if image is child of a picture
    if (image.parentNode.nodeName === 'PICTURE') {
      this.applyPicture(image.parentNode);
      sizes = image.dataset.sizes || this.pxTOvw(image.parentNode.parentElement.clientWidth);
    } else {
      sizes = image.dataset.sizes || this.pxTOvw(image.parentElement.clientWidth);
    }

    // Prevent this from being lazy loaded a second time.
    image.classList.add('dcf-lazy-loaded');
    image.classList.remove('dcf-lazy-load');

    if (src) {
      image.src = src;
      image.removeAttribute('data-src');
    }
    if (srcset) {
      image.srcset = srcset;
      image.removeAttribute('data-srcset');
    }
    if (sizes) {
      image.sizes = sizes;
      image.removeAttribute('data-sizes');
    }
    if (this.classNames.length) {
      this.classNames.forEach((className) => image.classList.add(className));
    }
  }

  /**
   * @param {string}  src     The src of image.
   * @param {string}  srcset  Defaults to null if not provided.
   * @param {integer} sizes   Defaults to null if not provided.
   *
   * @returns {Promise}
   */
  fetchImage(src, srcset = null, sizes = null) {
    return new Promise((resolve, reject) => {
      const image = new Image();
      if (src) {
        image.src = src;
      }
      if (srcset) {
        image.srcset = srcset;
      }
      if (sizes) {
        image.sizes = sizes;
      }

      image.onload = resolve;
      image.onerror = reject;
    }).catch(() => {
      // do nothing
    });
  }

  /**
   * Preloads the image
   * @param {object} image   An image object.
   *
   * @returns {(object|void)} Returns a promise for fetchImage or void.
   */
  preloadImage(image) {
    const src = image.dataset.src;
    const srcset = image.dataset.srcset;
    const sizes = image.dataset.sizes || null;

    let fetchImagePromise = null;
    if (src) {
      try {
        fetchImagePromise = this.fetchImage(src, srcset, sizes);
      } catch (error) {
        // do nothing
      }
    }
    return fetchImagePromise;
  }

  /**
   * Apply the picture
   * @param {string} picture: the picture element that we are targeting
   */
  applyPicture(picture) {
    // update picture source tags
    let pictureSources = picture.getElementsByTagName('SOURCE');
    Array.from(pictureSources).forEach((pictureSource) => {
      const srcset = pictureSource.dataset.srcset || null;
      const sizes = pictureSource.dataset.sizes || this.pxTOvw(picture.parentElement.clientWidth);

      if (!srcset) {
        // skip this pictureSource
        return;
      }

      pictureSource.srcset = srcset;
      pictureSource.removeAttribute('data-srcset');

      if (sizes) {
        pictureSource.sizes = sizes;
        pictureSource.removeAttribute('data-sizes');
      }
    });
  }

  /**
   * Load all of the items immediately
   * @param {NodeListOf<Element>} items     List of node elements.
   * @param {boolean}             preload   Whether to preload or not.
   */
  loadItemsImmediately(items, preload = true) {
    items.forEach((item) => {
      switch (item.nodeName) {
      case 'IMG':
        if (preload === true) {
          this.preloadImage(item);
        }
        this.applyImage(item);
        break;

      default:
        // do nothing skip to next item;
        return;
      }
    });
  }

  /**
   * Disconnect the observer
   */
  disconnect() {
    if (!this.observer) {
      return;
    }

    this.observer.disconnect();
  }

  initialize() {
    // onIntersection callback function
    let onIntersection = (entries, observer) => {
      const zero = 0;
      const zeroIndex = 0;
      const oneIndex = 1;
      // Disconnect if we've already loaded all of the images
      if (this.itemsCount === zero) {
        this.observer.disconnect();
      }

      // Loop through the entries
      entries.forEach((entry) => {
        switch (entry.target.nodeName) {
        case 'IMG':
          if (entry.intersectionRatio > observer.thresholds[zeroIndex] &&
              entry.intersectionRatio < observer.thresholds[oneIndex]) {
            this.preloadImage(entry.target);
          } else if (entry.intersectionRatio > observer.thresholds[oneIndex]) {
            this.itemsCount--;
            this.applyImage(entry.target);
            this.observer.unobserve(entry.target);
          }
          break;

        default:
          // do nothing skip to next item;
          return;
        }
      });
    };

    if (!this.itemList) {
      return;
    }

    this.itemsCount = this.itemList.length;

    if ('loading' in HTMLImageElement.prototype) {
      // Native lazy loading IS supported, so set src-data to src
      this.loadItemsImmediately(this.itemList, false);
    } else {
      // Native lazy loading NOT supported, so handle via javascript
      // If browser doesn't support intersection observer, load the items immediately
      if (!('IntersectionObserver' in window)) {
        this.loadItemsImmediately(this.itemList);
      } else {
        // It is supported, load the items
        this.observer = new IntersectionObserver(onIntersection, this.observerConfig);

        this.itemList.forEach((item) => {
          if (item.classList.contains('dcf-lazy-loaded')) {
            // skip item
            return;
          }

          this.observer.observe(item);
        });
      }
    }
  }
}
<commit_msg>Support lazy loading of video (#393)<commit_after>class DCFLazyLoad {
  constructor(itemList, observerConfig, classNames) {
    this.itemList = itemList;
    this.observerConfig = observerConfig;
    this.classNames = classNames;
  }

  pxTOvw(value) {
    const zeroIndex = 0;
    const oneHundred = 100;
    const docElement = document.documentElement,
      docBody = document.getElementsByTagName('body')[zeroIndex],
      windowWidth = window.innerWidth || docElement.clientWidth || docBody.clientWidth;

    const result = oneHundred * value / windowWidth;
    return `${result }vw`;
  }

  /**
   * Apply the image: preloaded image is loaded but not applied to actual image element
   * @param {string} image: the image element that we are targetting
   */
  applyImage(image) {
    const src = image.dataset.src;
    const srcset = image.dataset.srcset || null;
    let sizes = null;

    if (!src) {
      return;
    }

    // Process parent picture lazy load if image is child of a picture
    if (image.parentNode.nodeName === 'PICTURE') {
      this.applyPicture(image.parentNode);
      sizes = image.dataset.sizes || this.pxTOvw(image.parentNode.parentElement.clientWidth);
    } else {
      sizes = image.dataset.sizes || this.pxTOvw(image.parentElement.clientWidth);
    }

    // Prevent this from being lazy loaded a second time.
    image.classList.add('dcf-lazy-loaded');
    image.classList.remove('dcf-lazy-load');

    if (src) {
      image.src = src;
      image.removeAttribute('data-src');
    }
    if (srcset) {
      image.srcset = srcset;
      image.removeAttribute('data-srcset');
    }
    if (sizes) {
      image.sizes = sizes;
      image.removeAttribute('data-sizes');
    }
    if (this.classNames.length) {
      this.classNames.forEach((className) => image.classList.add(className));
    }
  }

  /**
   * @param {string}  src     The src of image.
   * @param {string}  srcset  Defaults to null if not provided.
   * @param {integer} sizes   Defaults to null if not provided.
   *
   * @returns {Promise}
   */
  fetchImage(src, srcset = null, sizes = null) {
    return new Promise((resolve, reject) => {
      const image = new Image();
      if (src) {
        image.src = src;
      }
      if (srcset) {
        image.srcset = srcset;
      }
      if (sizes) {
        image.sizes = sizes;
      }

      image.onload = resolve;
      image.onerror = reject;
    }).catch(() => {
      // do nothing
    });
  }

  /**
   * Preloads the image
   * @param {object} image   An image object.
   *
   * @returns {(object|void)} Returns a promise for fetchImage or void.
   */
  preloadImage(image) {
    const src = image.dataset.src;
    const srcset = image.dataset.srcset;
    const sizes = image.dataset.sizes || null;

    let fetchImagePromise = null;
    if (src) {
      try {
        fetchImagePromise = this.fetchImage(src, srcset, sizes);
      } catch (error) {
        // do nothing
      }
    }
    return fetchImagePromise;
  }

  /**
   * Apply the picture
   * @param {string} picture: the picture element that we are targeting
   */
  applyPicture(picture) {
    // update picture source tags
    let pictureSources = picture.getElementsByTagName('SOURCE');
    Array.from(pictureSources).forEach((pictureSource) => {
      const srcset = pictureSource.dataset.srcset || null;
      const sizes = pictureSource.dataset.sizes || this.pxTOvw(picture.parentElement.clientWidth);

      if (!srcset) {
        // skip this pictureSource
        return;
      }

      pictureSource.srcset = srcset;
      pictureSource.removeAttribute('data-srcset');

      if (sizes) {
        pictureSource.sizes = sizes;
        pictureSource.removeAttribute('data-sizes');
      }
    });
  }

  applyVideo(video) {
    let videoSources = video.getElementsByTagName('SOURCE');
    const poster = video.dataset.poster || null;

    Array.from(videoSources).forEach((videoSource) => {
      const src = videoSource.dataset.src || null;

      if (!src) {
        // skip this videoSource
        return;
      }

      videoSource.src = src;
      videoSource.removeAttribute('data-src');
    });

    if (poster) {
      video.poster = poster;
      video.removeAttribute('data-poster');
    }

    // Prevent this from being lazy loaded a second time.
    video.classList.add('dcf-lazy-loaded');
    video.classList.remove('dcf-lazy-load');

    if (this.classNames.length) {
      this.classNames.forEach((className) => video.classList.add(className));
    }

    video.load();
  }

  /**
   * Load all of the items immediately
   * @param {NodeListOf<Element>} items     List of node elements.
   * @param {boolean}             preload   Whether to preload or not.
   */
  loadItemsImmediately(items, preload = true) {
    items.forEach((item) => {
      switch (item.nodeName) {
      case 'IMG':
        if (preload === true) {
          this.preloadImage(item);
        }
        this.applyImage(item);
        break;

      case 'VIDEO':
        this.applyVideo(item);
        break;

      default:
        // do nothing skip to next item;
        return;
      }
    });
  }

  /**
   * Disconnect the observer
   */
  disconnect() {
    if (!this.observer) {
      return;
    }

    this.observer.disconnect();
  }

  initialize() {
    // onIntersection callback function
    let onIntersection = (entries, observer) => {
      const zero = 0;
      const zeroIndex = 0;
      const oneIndex = 1;
      // Disconnect if we've already loaded all of the images
      if (this.itemsCount === zero) {
        this.observer.disconnect();
      }

      // Loop through the entries
      entries.forEach((entry) => {
        switch (entry.target.nodeName) {
        case 'IMG':
          if (entry.intersectionRatio > observer.thresholds[zeroIndex] &&
            entry.intersectionRatio < observer.thresholds[oneIndex]) {
            this.preloadImage(entry.target);
          } else if (entry.intersectionRatio > observer.thresholds[oneIndex]) {
            this.itemsCount--;
            this.applyImage(entry.target);
            this.observer.unobserve(entry.target);
          }
          break;

        case 'VIDEO':
          if (entry.intersectionRatio > observer.thresholds[oneIndex]) {
            this.itemsCount--;
            this.applyVideo(entry.target);
            this.observer.unobserve(entry.target);
          }
          break;

        default:
          // do nothing skip to next item;
          return;
        }
      });
    };

    if (!this.itemList) {
      return;
    }

    this.itemsCount = this.itemList.length;

    if (!('IntersectionObserver' in window)) {
      this.loadItemsImmediately(this.itemList, 'loading' in HTMLImageElement.prototype);
    } else {
      // It is supported, load the items
      this.observer = new IntersectionObserver(onIntersection, this.observerConfig);

      this.itemList.forEach((item) => {
        if (item.classList.contains('dcf-lazy-loaded')) {
          // skip item
          return;
        }

        // Native image lazy loading IS supported, so set src-data to src
        if ('loading' in HTMLImageElement.prototype && item.nodeName === 'IMG') {
          this.itemsCount--;
          this.applyImage(item);
          return;
        }

        this.observer.observe(item);
      });
    }
  }
}
<|endoftext|>


<commit_before>(function($) {
     window['Devtools'] = { //window represents the browser window
        //by putting it in window, it's essentially greating a global variable

        // development settings.
        //VERSION: 0.1,

        defaults: {
            logging: false,  // false to turn off logging
            production: false
        },

	get_rid : function(name) {

        var rids = {
            "rulesets": {"prod": "b507199x6.prod",
                          "dev": "b507199x6.dev"
            },
            "bootstrap":{"prod": "b507199x1.prod",
                          "dev": "b507199x1.dev"
            },
            "cloud_os":{"prod": "a169x625.prod",
                          "dev": "a169x625.prod"
            }
        };

	    return this.defaults.production ? rids[name].prod : rids[name].dev;
	},

    rid_eci: null, //fleet_eci
    rid_summary: {}, //vehicle_summary
    rid_list: [], //vehicles

    log: function() {
        if (this.defaults.logging && console && console.log) {
            [].unshift.call(arguments, "Devtools:"); // arguments is Array-like, it's not an Array
            console.log.apply(console, arguments);
        }
    },

    getProfile: function(channel, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
            Devtools.log("Retrieving profile for user");

        return CloudOS.skyCloud("a169x676", "get_all_me", {}, function(res) { //fix this up. what rule is this calling?
            CloudOS.clean(res);
            if(typeof cb !== "undefined"){
                cb(res);
            }
        },
        {"eci": channel});
    },

    bootstrapped: function(cb,options){
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("bootstrapped ??");
        return CloudOS.skyCloud(Devtools.get_rid("bootstrap"), "testingReturns", {}, function(json) {
            Devtools.log("Displaying testingReturns", json);
            cb(json);
        }, {"eci":eci});
    },

    getRulesets: function(cb, options) //almost like getProfile in fuse-api.js
    {

        cb = cb || function(){};
        options = options || {};
        //var rid = "rulesets";
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Showing the rulesets");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showRulesets", {}, function(json) {
            Devtools.log("Displaying rulesets", json);
            cb(json);
        }, {"eci":eci});
    },

    status: function(cb, options){
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Showing the channels");
        //return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "rulesetList", {}, function(json) {
        return CloudOS.skyCloud(Devtools.get_rid("cloud_os"), "rulesetList", {}, function(json) {
            Devtools.log("Displaying installed rulesets", json);
            cb(json);
        }, {"eci":eci});
    },
// ---------- account ----------
    // this is called in _layouts/code.html when the account is created
    initAccount: function(attrs, cb, options)
        {
        cb = cb || function(){};
        options = options || {};
        attrs = attrs || {};
            Devtools.log("Initializing account for user with attributes ", attrs);

            return CloudOS.raiseEvent("devtools", "bootstrap", {}, {}, function(response)
            {
        // note that because the channel is create asynchronously, processing callback does
        // NOT mean the channel exists.
        //        Devtools.log("account initialized");
        if(response.length < 1) {
            throw "Account initialization failed";
        }
        cb(response);
            });
        },

    about: function(cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var json = {rids: rid,url: url}; //not sure what this does
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Getting info about pico ");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "aboutPico", {}, function(json) {
            Devtools.log("This pico: ", json);
            cb(json);
        }, {"eci":eci});
    },

//---------the functions for updating rulesets

    updateUrl: function(rid, url, cb, options) //basing this off of updateCarvoyantVehicle
    {
        cb = cb || function(){};
        options = options || {};
        var json = {rids: rid,url: url}; //not sure what this does
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Updating the URL");
        return CloudOS.raiseEvent("devtools", "update_url", json, {}, function(json) {
            Devtools.log("Directive from updating URL", json);
            cb(json);
        }, {"eci":eci});
    },

    flushRID: function(rid, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var json = {rid: rid};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Flushing RID " + rid);
        return CloudOS.raiseEvent("devtools", "flush_rid", json, {}, function(json) {
            Devtools.log("Directive from Flushing Rid", json);
            cb(json);
        }, {"eci":eci});
    },

    deleteRID: function(rid, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var json = {rid: rid};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Deleting RID " + rid);
        return CloudOS.raiseEvent("devtools", "delete_rid", json, {}, function(json) {
            Devtools.log("Directive from Deleting Rid", json);
            cb(json);
        }, {"eci":eci});
    },

    showInstalledRulesets: function(cb, options) // PJW
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Showing the rulesets");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showInstalledRulesets", {}, function(json) {
            Devtools.log("Displaying installed rulesets", json);
            cb(json);
        }, {"eci":eci});
    },

    installRulesets: function(ridlist, cb, options) // PJW
    {
        cb = cb || function(){};
        options = options || {};
	var json = {rids: ridlist};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Installing rulesets");
        return CloudOS.raiseEvent("devtools", "install_rulesets", json, {}, function(json) {
            Devtools.log("Directive from installing rulesets", json);
            cb(json);
        }, {"eci":eci});
    },

    uninstallRulesets: function(ridlist, cb, options) // PJW
    {
        cb = cb || function(){};
        options = options || {};
	var json = {rids: ridlist};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Uninstalling rulesets");
        return CloudOS.raiseEvent("devtools", "uninstall_rulesets", json, {}, function(json) {
            Devtools.log("Directive from uninstalling rulesets", json);
            cb(json);
        }, {"eci":eci});
    },
    RegisterRuleset: function(url,cb,options)
    {
        cb = cb || function(){};
        options = options || {};
    var json = {rulesetURL: url}; // json for attribute thats passed to the ruleset as eventattribute
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Registering rulesets");
        return CloudOS.raiseEvent("devtools", "register_ruleset", json, {}, function(json) {
            Devtools.log("Directive from register ruleset", json);
            cb(json);
        }, {"eci":eci});
    },

    //--------------------------------Channels mannagement----------------------
    showInstalledChannels: function(cb, options) // copied PJW
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Showing the channels");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showInstalledChannels", {}, function(json) {
            Devtools.log("Displaying installed channels", json);
            cb(json);
        }, {"eci":eci});
    },
    installChannel: function(channel_name, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
    var parameters = {channelName:channel_name};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Installing channels");
       return CloudOS.raiseEvent("devtools", "create_channel", parameters,{}, function(json) {
           Devtools.log("Directive from create channel", json);
           cb(json);
       }, {"eci":eci});
    },
    uninstallChannel: function(ECI, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
    var json = {channelID:ECI};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Destroy channels");
        return CloudOS.raiseEvent("devtools", "channel_destroy", json,{}, function(json) {
           Devtools.log("Directive from create channel", json);
           cb(json);
        }, {"eci":eci});

    },
    //---------------------------------Authorize Client mannagement----------------
    authorizeClient: function(app_Data, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("authorizing clientlient ");
       return CloudOS.raiseEvent("devtools", "authorize_client", app_Data,{}, function(json) {
           Devtools.log("Directive from AuthorizeClient", json);
           cb(json);
       }, {"eci":eci});
    },
	showAthorizedClients: function(cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Showing the showing clients");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showClients", {}, function(json) {
            Devtools.log("Displaying athorize clients", json);
            cb(json);
        }, {"eci":eci});
    },
    removeClient: function(app_ECI, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var json = {"appECI":app_ECI};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("remove client");
        console.log("attributes",json);
        return CloudOS.raiseEvent("devtools", "remove_client", json,{}, function(json) {
           Devtools.log("Directive from remove client", json);
           cb(json);
        }, {"eci":eci});
    },
    updateClient: function(app_ECI, app_Data, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        app_Data["appECI"]=app_ECI;
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Updating client");
        return CloudOS.raiseEvent("devtools", "update_client", app_Data, {}, function(json) {
            Devtools.log("Directive from updating Client", json);
            cb(json);
        }, {"eci":eci});
    },

    showScheduledEvents: function(cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("show scheduled events");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showScheduleEvents", {}, function(json) {
            Devtools.log("Displaying scheduled events", json);
            cb(json);
        }, {"eci":eci});
    },
    scheduleEvent: function(Data, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("scheduling event");
       return CloudOS.raiseEvent("devtools", "event_scheduled", Data,{}, function(json) {
           Devtools.log("Directive from ScheduleEvent", json);
           cb(json);
       }, {"eci":eci});
    },
    //-------------------Subscriptions--------------------
    showSubscriptions: function(cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("show Subscriptions");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showSubscriptions", {}, function(json) {
            Devtools.log("Displaying showSubscriptions", json);
            cb(json);
        }, {"eci":eci});
    },
    showIncoming: function(cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("show Incoming");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showIncoming", {}, function(json) {
            Devtools.log("Displaying showIncoming", json);
            cb(json);
        }, {"eci":eci});
    },
    showOutGoing: function(cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("show OutGoing");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showOutGoing", {}, function(json) {
            Devtools.log("Displaying showOutGoing", json);
            cb(json);
        }, {"eci":eci});
    },
    ApproveSubscription: function(event_channel, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("approve subscription");
       return CloudOS.raiseEvent("devtools", "incoming_request_approved", event_channel,{}, function(json) {
           Devtools.log("Directive from ApproveSubscription", json);
           cb(json);
       }, {"eci":eci});
    },
    AddSubscription: function(data, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("approve subscription");
       return CloudOS.raiseEvent("devtools", "subscribe", data,{}, function(json) {
           Devtools.log("Directive from AddSubscription", json);
           cb(json);
       }, {"eci":eci});
    },

   //TESTING CODE WRITTEN IN NANO MANAGER
   scheduleEvent: function(data, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var parameters = {channelName:channel_name};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Installing channels");
       return CloudOS.raiseEvent("nano_manager", "scheduled_event", data,{}, function(json) {
           Devtools.log("Creating a scheduled event", json);
           cb(json);
       }, {"eci":eci});
    }
//
}; //closes the "window" inside the function DON'T DELETE

//----------------------------------

    function isEmpty(obj) {

        // null and undefined are "empty"
        if (obj === null) return true;

        // Assume if it has a length property with a non-zero value
        // that that property is correct.
        if (obj.length > 0)    return false;
        if (obj.length === 0)  return true;

        // Otherwise, does it have any properties of its own?
        // Note that this doesn't handle
        // toString and valueOf enumeration bugs in IE < 9
        for (var key in obj) {
                if (hasOwnProperty.call(obj, key)) return false;
        }

        return true;

        }

})(jQuery);
<commit_msg>Revert "testing again"<commit_after>(function($) {
     window['Devtools'] = { //window represents the browser window
        //by putting it in window, it's essentially greating a global variable

        // development settings.
        //VERSION: 0.1,

        defaults: {
            logging: false,  // false to turn off logging
            production: false
        },

	get_rid : function(name) {

        var rids = {
            "rulesets": {"prod": "b507199x0.prod",
                          "dev": "b507199x0.dev"
            },
            "bootstrap":{"prod": "b507199x1.prod",
                          "dev": "b507199x1.dev"
            },
            "cloud_os":{"prod": "a169x625.prod",
                          "dev": "a169x625.prod"
            }
        };

	    return this.defaults.production ? rids[name].prod : rids[name].dev;
	},

    rid_eci: null, //fleet_eci
    rid_summary: {}, //vehicle_summary
    rid_list: [], //vehicles

    log: function() {
        if (this.defaults.logging && console && console.log) {
            [].unshift.call(arguments, "Devtools:"); // arguments is Array-like, it's not an Array
            console.log.apply(console, arguments);
        }
    },

    getProfile: function(channel, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
            Devtools.log("Retrieving profile for user");

        return CloudOS.skyCloud("a169x676", "get_all_me", {}, function(res) { //fix this up. what rule is this calling?
            CloudOS.clean(res);
            if(typeof cb !== "undefined"){
                cb(res);
            }
        },
        {"eci": channel});
    },

    bootstrapped: function(cb,options){
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("bootstrapped ??");
        return CloudOS.skyCloud(Devtools.get_rid("bootstrap"), "testingReturns", {}, function(json) {
            Devtools.log("Displaying testingReturns", json);
            cb(json);
        }, {"eci":eci});
    },

    getRulesets: function(cb, options) //almost like getProfile in fuse-api.js
    {

        cb = cb || function(){};
        options = options || {};
        //var rid = "rulesets";
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Showing the rulesets");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showRulesets", {}, function(json) {
            Devtools.log("Displaying rulesets", json);
            cb(json);
        }, {"eci":eci});
    },

    status: function(cb, options){
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Showing the channels");
        //return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "rulesetList", {}, function(json) {
        return CloudOS.skyCloud(Devtools.get_rid("cloud_os"), "rulesetList", {}, function(json) {
            Devtools.log("Displaying installed rulesets", json);
            cb(json);
        }, {"eci":eci});
    },
// ---------- account ----------
    // this is called in _layouts/code.html when the account is created
    initAccount: function(attrs, cb, options)
        {
        cb = cb || function(){};
        options = options || {};
        attrs = attrs || {};
            Devtools.log("Initializing account for user with attributes ", attrs);

            return CloudOS.raiseEvent("devtools", "bootstrap", {}, {}, function(response)
            {
        // note that because the channel is create asynchronously, processing callback does
        // NOT mean the channel exists.
        //        Devtools.log("account initialized");
        if(response.length < 1) {
            throw "Account initialization failed";
        }
        cb(response);
            });
        },

    about: function(cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var json = {rids: rid,url: url}; //not sure what this does
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Getting info about pico ");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "aboutPico", {}, function(json) {
            Devtools.log("This pico: ", json);
            cb(json);
        }, {"eci":eci});
    },

//---------the functions for updating rulesets

    updateUrl: function(rid, url, cb, options) //basing this off of updateCarvoyantVehicle
    {
        cb = cb || function(){};
        options = options || {};
        var json = {rids: rid,url: url}; //not sure what this does
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Updating the URL");
        return CloudOS.raiseEvent("devtools", "update_url", json, {}, function(json) {
            Devtools.log("Directive from updating URL", json);
            cb(json);
        }, {"eci":eci});
    },

    flushRID: function(rid, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var json = {rid: rid};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Flushing RID " + rid);
        return CloudOS.raiseEvent("devtools", "flush_rid", json, {}, function(json) {
            Devtools.log("Directive from Flushing Rid", json);
            cb(json);
        }, {"eci":eci});
    },

    deleteRID: function(rid, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var json = {rid: rid};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Deleting RID " + rid);
        return CloudOS.raiseEvent("devtools", "delete_rid", json, {}, function(json) {
            Devtools.log("Directive from Deleting Rid", json);
            cb(json);
        }, {"eci":eci});
    },

    showInstalledRulesets: function(cb, options) // PJW
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Showing the rulesets");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showInstalledRulesets", {}, function(json) {
            Devtools.log("Displaying installed rulesets", json);
            cb(json);
        }, {"eci":eci});
    },

    installRulesets: function(ridlist, cb, options) // PJW
    {
        cb = cb || function(){};
        options = options || {};
	var json = {rids: ridlist};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Installing rulesets");
        return CloudOS.raiseEvent("devtools", "install_rulesets", json, {}, function(json) {
            Devtools.log("Directive from installing rulesets", json);
            cb(json);
        }, {"eci":eci});
    },

    uninstallRulesets: function(ridlist, cb, options) // PJW
    {
        cb = cb || function(){};
        options = options || {};
	var json = {rids: ridlist};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Uninstalling rulesets");
        return CloudOS.raiseEvent("devtools", "uninstall_rulesets", json, {}, function(json) {
            Devtools.log("Directive from uninstalling rulesets", json);
            cb(json);
        }, {"eci":eci});
    },
    RegisterRuleset: function(url,cb,options)
    {
        cb = cb || function(){};
        options = options || {};
    var json = {rulesetURL: url}; // json for attribute thats passed to the ruleset as eventattribute
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Registering rulesets");
        return CloudOS.raiseEvent("devtools", "register_ruleset", json, {}, function(json) {
            Devtools.log("Directive from register ruleset", json);
            cb(json);
        }, {"eci":eci});
    },

    //--------------------------------Channels mannagement----------------------
    showInstalledChannels: function(cb, options) // copied PJW
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Showing the channels");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showInstalledChannels", {}, function(json) {
            Devtools.log("Displaying installed channels", json);
            cb(json);
        }, {"eci":eci});
    },
    installChannel: function(channel_name, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
    var parameters = {channelName:channel_name};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Installing channels");
       return CloudOS.raiseEvent("devtools", "create_channel", parameters,{}, function(json) {
           Devtools.log("Directive from create channel", json);
           cb(json);
       }, {"eci":eci});
    },
    uninstallChannel: function(ECI, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
    var json = {channelID:ECI};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Destroy channels");
        return CloudOS.raiseEvent("devtools", "channel_destroy", json,{}, function(json) {
           Devtools.log("Directive from create channel", json);
           cb(json);
        }, {"eci":eci});

    },
    //---------------------------------Authorize Client mannagement----------------
    authorizeClient: function(app_Data, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("authorizing clientlient ");
       return CloudOS.raiseEvent("devtools", "authorize_client", app_Data,{}, function(json) {
           Devtools.log("Directive from AuthorizeClient", json);
           cb(json);
       }, {"eci":eci});
    },
	showAthorizedClients: function(cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Showing the showing clients");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showClients", {}, function(json) {
            Devtools.log("Displaying athorize clients", json);
            cb(json);
        }, {"eci":eci});
    },
    removeClient: function(app_ECI, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var json = {"appECI":app_ECI};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("remove client");
        console.log("attributes",json);
        return CloudOS.raiseEvent("devtools", "remove_client", json,{}, function(json) {
           Devtools.log("Directive from remove client", json);
           cb(json);
        }, {"eci":eci});
    },
    updateClient: function(app_ECI, app_Data, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        app_Data["appECI"]=app_ECI;
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Updating client");
        return CloudOS.raiseEvent("devtools", "update_client", app_Data, {}, function(json) {
            Devtools.log("Directive from updating Client", json);
            cb(json);
        }, {"eci":eci});
    },

    showScheduledEvents: function(cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("show scheduled events");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showScheduleEvents", {}, function(json) {
            Devtools.log("Displaying scheduled events", json);
            cb(json);
        }, {"eci":eci});
    },
    scheduleEvent: function(Data, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("scheduling event");
       return CloudOS.raiseEvent("devtools", "event_scheduled", Data,{}, function(json) {
           Devtools.log("Directive from ScheduleEvent", json);
           cb(json);
       }, {"eci":eci});
    },
    //-------------------Subscriptions--------------------
    showSubscriptions: function(cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("show Subscriptions");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showSubscriptions", {}, function(json) {
            Devtools.log("Displaying showSubscriptions", json);
            cb(json);
        }, {"eci":eci});
    },
    showIncoming: function(cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("show Incoming");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showIncoming", {}, function(json) {
            Devtools.log("Displaying showIncoming", json);
            cb(json);
        }, {"eci":eci});
    },
    showOutGoing: function(cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("show OutGoing");
        return CloudOS.skyCloud(Devtools.get_rid("rulesets"), "showOutGoing", {}, function(json) {
            Devtools.log("Displaying showOutGoing", json);
            cb(json);
        }, {"eci":eci});
    },
    ApproveSubscription: function(event_channel, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("approve subscription");
       return CloudOS.raiseEvent("devtools", "incoming_request_approved", event_channel,{}, function(json) {
           Devtools.log("Directive from ApproveSubscription", json);
           cb(json);
       }, {"eci":eci});
    },
    AddSubscription: function(data, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("approve subscription");
       return CloudOS.raiseEvent("devtools", "subscribe", data,{}, function(json) {
           Devtools.log("Directive from AddSubscription", json);
           cb(json);
       }, {"eci":eci});
    },

   //TESTING CODE WRITTEN IN NANO MANAGER
   scheduleEvent: function(data, cb, options)
    {
        cb = cb || function(){};
        options = options || {};
        var parameters = {channelName:channel_name};
        var eci = options.eci || CloudOS.defaultECI;
        Devtools.log("Installing channels");
       return CloudOS.raiseEvent("nano_manager", "scheduled_event", data,{}, function(json) {
           Devtools.log("Creating a scheduled event", json);
           cb(json);
       }, {"eci":eci});
    }
//
}; //closes the "window" inside the function DON'T DELETE

//----------------------------------

    function isEmpty(obj) {

        // null and undefined are "empty"
        if (obj === null) return true;

        // Assume if it has a length property with a non-zero value
        // that that property is correct.
        if (obj.length > 0)    return false;
        if (obj.length === 0)  return true;

        // Otherwise, does it have any properties of its own?
        // Note that this doesn't handle
        // toString and valueOf enumeration bugs in IE < 9
        for (var key in obj) {
                if (hasOwnProperty.call(obj, key)) return false;
        }

        return true;

        }

})(jQuery);
<|endoftext|>