<commit_before>'use strict';

var lazyReq = require('lazy-req')(require);
var inquirer = lazyReq('inquirer');
var through = lazyReq('through2');
var path = lazyReq('path');
var livereload = lazyReq('gulp-livereload');
var watch = lazyReq('gulp-watch');
var filelog = require('gulp-filelog');
var fs = require('fs-extra');

var PLUGIN_PATHS = {
  SCRIPTS: 'plugin/res/js/angularjs',
  SCRIPT_DEPENDENCIES: 'plugin/res/js/angularjs/metadata',
  TEXT: 'plugin/res/lang/feature'
};

module.exports = function (gulp, gutil) {
  var text, plugin, pluginUpload, pluginServer, lrListening;

  var scripts = require('../lib/scripts.js')(gulp, gutil);
  var sandboxApi = require('../lib/sandbox-api-hack.js')(gulp, gutil);
  var text = require('../lib/text.js')(gulp, gutil);
  var plugin = require('../lib/plugin-create.js')(gulp, gutil);

  function getPluginServer() {
    if (!pluginServer) {
      pluginServer = require('../lib/plugin-server.js')(gulp, gutil);
    }

    return pluginServer;
  }

  gulp.task('plugin-scripts', function () {
    return scripts.process(
      [
        scripts.JS_MAIN_PATTERN,
        scripts.TPL_MAIN_PATTERN,
        scripts.DEPENDENCIES
      ],
      PLUGIN_PATHS.SCRIPTS,
      undefined,
      false,
      true
    );
  });

  gulp.task('plugin-script-deps', ['plugin-scripts'], function () {
    return scripts.createDependencies(
      PLUGIN_PATHS.SCRIPTS,
      PLUGIN_PATHS.SCRIPT_DEPENDENCIES);
  });

  gulp.task('plugin-text', function () {
    var textPropPattern = gutil.env.ng.textProperties.map(function (dir) {
      return path().join(dir, text.FILES_PATTERN);
    });
    return text.process(textPropPattern, PLUGIN_PATHS.TEXT);
  });

  gulp.task('plugin-git-version', function (cb) {
    if (gutil.env.gitStatusVersion) {
      var gitVersion = require('../lib/git-version.js')(gulp, gutil);
      return gitVersion.create('plugin');
    } else {
      cb();
      return gutil.noop();
    }
  });

  gulp.task('plugin-ng', [
    'plugin-script-deps',
    'plugin-text'
  ]);

  gulp.task('plugin-res', gutil.env.ng ? ['plugin-ng'] : [], function () {
    return gulp.src(['res/**', '!res/**/README.md', '!res/**/*.example'])
      .pipe(gulp.dest('plugin/res'));
  });

  gulp.task('plugin-web', gutil.env.ng ? ['plugin-ng'] : [], function () {
    return gulp.src(['web/**', '!web/**/README.md', '!web/**/*.example'])
      .pipe(gulp.dest('plugin/web'));
  });

  /* plugin task */
  gulp.task('plugin-build', [
    'plugin-res',
    'plugin-web',
    'plugin-git-version'
  ]);

  gulp.task('plugin-verify', ['plugin-build'], function (cb) {
    if (gutil.env.verifyPlugin === false) {
      cb();
    } else {
      return plugin.verify();
    }
  });

  gulp.task('plugin-ready', ['plugin-verify'], function (cb) {
    gutil.log(gutil.colors.green('Done compiling plugin: ' +
      path().join(process.cwd(), '/plugin')));
    cb();
  });

  gulp.task('plugin-upload', ['plugin-ready'], function () {
    var stream = through().obj();
    var server = getPluginServer().getServer();
    var uploadCallBack = function() {
      if ((gutil.env['force'] || server.force()) && !gutil.env['prompt']) {
        if (!pluginUpload) {
          pluginUpload = require('../lib/plugin-upload.js')(gulp, gutil);
        }
        pluginUpload.upload(server, {
          debugMode: gutil.env['debug']
        }).pipe(stream);
      } else {
        inquirer().prompt({
          name: 'pluginUpload',
          message: 'Would you like to upload plugin to server?',
          type: 'confirm'
        }, function (answers) {
          if (answers.pluginUpload) {
            if (!pluginUpload) {
              pluginUpload = require('../lib/plugin-upload.js')(gulp, gutil);
            }
            pluginUpload.upload(server, {
              debugMode: gutil.env['debug']
            }).pipe(stream);
          } else {
            stream.end();
          }
        });
      }
      return stream;
    };

    if (!gutil.env['skip-version-check']) {
        var versioncheck = require('../lib/version-check.js')(gulp, gutil);
        versioncheck.validate(server.serverUrl(), server.pluginToken(), server, uploadCallBack);
    } else {
        uploadCallBack();
    }
    return;
  });

  var pluginTaskDependencies = [];

  if (gutil.env['skip-upload']) {
    pluginTaskDependencies.push('plugin-ready');
  } else {
    pluginTaskDependencies.push('plugin-upload');
  }
  gulp.task('plugin', pluginTaskDependencies);

  gulp.task('plugin-dev-clean', function () {
    return sandboxApi.deletePlugin();
  });

  gulp.task('plugin-dev-sync', ['plugin-dev-clean', 'plugin-ready'], function (cb) {
    return sandboxApi.syncPlugin();
  });

  gulp.task('plugin-dev-refresh', ['plugin-dev-sync'], function (cb) {
    return sandboxApi.refreshPlugin({ all: true });
  });

  function addWatch(pattern, callback, cb) {
    if (!lrListening) {
      lrListening = true;
      livereload().listen();
    }

    watch()(pattern, function (file) {
      callback(file, function () {
        gutil.log(gutil.colors.cyan('Staging file for upload: ', file.path));

        sandboxApi.syncPlugin().then(function () {
          var reloadQuery = sandboxApi.createReloadQuery(file.relative);
          return sandboxApi.refreshPlugin(reloadQuery);
        }).then(function () {
          livereload().reload(file);
        });
      });
    });
    cb();
  }

  gulp.task('watch-scripts', function (cb) {
    addWatch(
      [scripts.JS_MAIN_PATTERN, scripts.TPL_MAIN_PATTERN],
      function (file, done) {
        return scripts.process(
          [scripts.JS_MAIN_PATTERN, scripts.TPL_MAIN_PATTERN],
          PLUGIN_PATHS.SCRIPTS,
          [file.path],
          true,
          true
        ).on('end', done);
      },
      cb
    );
  });

  gulp.task('watch-script-deps', ['plugin-ready'], function (cb) {
    addWatch(
      './sdk.conf.json',
      function (file, done) {
        return scripts.createDependencies(
          PLUGIN_PATHS.SCRIPTS,
          PLUGIN_PATHS.SCRIPT_DEPENDENCIES,
          true
        ).on('end', done);
      },
      cb
    );
  });

  gulp.task('watch-text', function (cb) {
    var textPropPattern = gutil.env.ng.textProperties.map(function (dir) {
      return path().join(dir, text.FILES_PATTERN);
    });
    // TODO: currently goes through all files -
    // try optimizing this for processing updated file only
    addWatch(
      textPropPattern,
      function (file, done) {
        return text.process(textPropPattern, PLUGIN_PATHS.TEXT).on('end', done);
      },
      cb
    );
  });

  gulp.task('watch-res', function (cb) {
    addWatch(
      ['res/**'].concat(gutil.env.watchResIgnore || []),
      function (file, done) {
        fs.copy(file.path, file.path.replace(process.cwd(), 'plugin'), done);
      },
      cb
    );
  });

  gulp.task('watch-web', function (cb) {
    addWatch(
      'web/**',
      function (file, done) {
        fs.copy(file.path, file.path.replace(process.cwd(), 'plugin'), done);
      },
      cb
    );
  });

  gulp.task('watch-ng', gutil.env.ng ? [
    'watch-scripts',
    'watch-script-deps',
    'watch-text'
  ] : []);

  gulp.task('dev', [
    'plugin-dev-refresh',
    'plugin-ready',
    'watch-ng',
    'watch-res',
    'watch-web'
  ]);

  gulp.task('default', ['dev']);

};
<commit_msg>Removed gulp-filelog.<commit_after>'use strict';

var lazyReq = require('lazy-req')(require);
var inquirer = lazyReq('inquirer');
var through = lazyReq('through2');
var path = lazyReq('path');
var livereload = lazyReq('gulp-livereload');
var watch = lazyReq('gulp-watch');
var fs = require('fs-extra');

var PLUGIN_PATHS = {
  SCRIPTS: 'plugin/res/js/angularjs',
  SCRIPT_DEPENDENCIES: 'plugin/res/js/angularjs/metadata',
  TEXT: 'plugin/res/lang/feature'
};

module.exports = function (gulp, gutil) {
  var text, plugin, pluginUpload, pluginServer, lrListening;

  var scripts = require('../lib/scripts.js')(gulp, gutil);
  var sandboxApi = require('../lib/sandbox-api-hack.js')(gulp, gutil);
  var text = require('../lib/text.js')(gulp, gutil);
  var plugin = require('../lib/plugin-create.js')(gulp, gutil);

  function getPluginServer() {
    if (!pluginServer) {
      pluginServer = require('../lib/plugin-server.js')(gulp, gutil);
    }

    return pluginServer;
  }

  gulp.task('plugin-scripts', function () {
    return scripts.process(
      [
        scripts.JS_MAIN_PATTERN,
        scripts.TPL_MAIN_PATTERN,
        scripts.DEPENDENCIES
      ],
      PLUGIN_PATHS.SCRIPTS,
      undefined,
      false,
      true
    );
  });

  gulp.task('plugin-script-deps', ['plugin-scripts'], function () {
    return scripts.createDependencies(
      PLUGIN_PATHS.SCRIPTS,
      PLUGIN_PATHS.SCRIPT_DEPENDENCIES);
  });

  gulp.task('plugin-text', function () {
    var textPropPattern = gutil.env.ng.textProperties.map(function (dir) {
      return path().join(dir, text.FILES_PATTERN);
    });
    return text.process(textPropPattern, PLUGIN_PATHS.TEXT);
  });

  gulp.task('plugin-git-version', function (cb) {
    if (gutil.env.gitStatusVersion) {
      var gitVersion = require('../lib/git-version.js')(gulp, gutil);
      return gitVersion.create('plugin');
    } else {
      cb();
      return gutil.noop();
    }
  });

  gulp.task('plugin-ng', [
    'plugin-script-deps',
    'plugin-text'
  ]);

  gulp.task('plugin-res', gutil.env.ng ? ['plugin-ng'] : [], function () {
    return gulp.src(['res/**', '!res/**/README.md', '!res/**/*.example'])
      .pipe(gulp.dest('plugin/res'));
  });

  gulp.task('plugin-web', gutil.env.ng ? ['plugin-ng'] : [], function () {
    return gulp.src(['web/**', '!web/**/README.md', '!web/**/*.example'])
      .pipe(gulp.dest('plugin/web'));
  });

  /* plugin task */
  gulp.task('plugin-build', [
    'plugin-res',
    'plugin-web',
    'plugin-git-version'
  ]);

  gulp.task('plugin-verify', ['plugin-build'], function (cb) {
    if (gutil.env.verifyPlugin === false) {
      cb();
    } else {
      return plugin.verify();
    }
  });

  gulp.task('plugin-ready', ['plugin-verify'], function (cb) {
    gutil.log(gutil.colors.green('Done compiling plugin: ' +
      path().join(process.cwd(), '/plugin')));
    cb();
  });

  gulp.task('plugin-upload', ['plugin-ready'], function () {
    var stream = through().obj();
    var server = getPluginServer().getServer();
    var uploadCallBack = function() {
      if ((gutil.env['force'] || server.force()) && !gutil.env['prompt']) {
        if (!pluginUpload) {
          pluginUpload = require('../lib/plugin-upload.js')(gulp, gutil);
        }
        pluginUpload.upload(server, {
          debugMode: gutil.env['debug']
        }).pipe(stream);
      } else {
        inquirer().prompt({
          name: 'pluginUpload',
          message: 'Would you like to upload plugin to server?',
          type: 'confirm'
        }, function (answers) {
          if (answers.pluginUpload) {
            if (!pluginUpload) {
              pluginUpload = require('../lib/plugin-upload.js')(gulp, gutil);
            }
            pluginUpload.upload(server, {
              debugMode: gutil.env['debug']
            }).pipe(stream);
          } else {
            stream.end();
          }
        });
      }
      return stream;
    };

    if (!gutil.env['skip-version-check']) {
        var versioncheck = require('../lib/version-check.js')(gulp, gutil);
        versioncheck.validate(server.serverUrl(), server.pluginToken(), server, uploadCallBack);
    } else {
        uploadCallBack();
    }
    return;
  });

  var pluginTaskDependencies = [];

  if (gutil.env['skip-upload']) {
    pluginTaskDependencies.push('plugin-ready');
  } else {
    pluginTaskDependencies.push('plugin-upload');
  }
  gulp.task('plugin', pluginTaskDependencies);

  gulp.task('plugin-dev-clean', function () {
    return sandboxApi.deletePlugin();
  });

  gulp.task('plugin-dev-sync', ['plugin-dev-clean', 'plugin-ready'], function (cb) {
    return sandboxApi.syncPlugin();
  });

  gulp.task('plugin-dev-refresh', ['plugin-dev-sync'], function (cb) {
    return sandboxApi.refreshPlugin({ all: true });
  });

  function addWatch(pattern, callback, cb) {
    if (!lrListening) {
      lrListening = true;
      livereload().listen();
    }

    watch()(pattern, function (file) {
      callback(file, function () {
        gutil.log(gutil.colors.cyan('Staging file for upload: ', file.path));

        sandboxApi.syncPlugin().then(function () {
          var reloadQuery = sandboxApi.createReloadQuery(file.relative);
          return sandboxApi.refreshPlugin(reloadQuery);
        }).then(function () {
          livereload().reload(file);
        });
      });
    });
    cb();
  }

  gulp.task('watch-scripts', function (cb) {
    addWatch(
      [scripts.JS_MAIN_PATTERN, scripts.TPL_MAIN_PATTERN],
      function (file, done) {
        return scripts.process(
          [scripts.JS_MAIN_PATTERN, scripts.TPL_MAIN_PATTERN],
          PLUGIN_PATHS.SCRIPTS,
          [file.path],
          true,
          true
        ).on('end', done);
      },
      cb
    );
  });

  gulp.task('watch-script-deps', ['plugin-ready'], function (cb) {
    addWatch(
      './sdk.conf.json',
      function (file, done) {
        return scripts.createDependencies(
          PLUGIN_PATHS.SCRIPTS,
          PLUGIN_PATHS.SCRIPT_DEPENDENCIES,
          true
        ).on('end', done);
      },
      cb
    );
  });

  gulp.task('watch-text', function (cb) {
    var textPropPattern = gutil.env.ng.textProperties.map(function (dir) {
      return path().join(dir, text.FILES_PATTERN);
    });
    // TODO: currently goes through all files -
    // try optimizing this for processing updated file only
    addWatch(
      textPropPattern,
      function (file, done) {
        return text.process(textPropPattern, PLUGIN_PATHS.TEXT).on('end', done);
      },
      cb
    );
  });

  gulp.task('watch-res', function (cb) {
    addWatch(
      ['res/**'].concat(gutil.env.watchResIgnore || []),
      function (file, done) {
        fs.copy(file.path, file.path.replace(process.cwd(), 'plugin'), done);
      },
      cb
    );
  });

  gulp.task('watch-web', function (cb) {
    addWatch(
      'web/**',
      function (file, done) {
        fs.copy(file.path, file.path.replace(process.cwd(), 'plugin'), done);
      },
      cb
    );
  });

  gulp.task('watch-ng', gutil.env.ng ? [
    'watch-scripts',
    'watch-script-deps',
    'watch-text'
  ] : []);

  gulp.task('dev', [
    'plugin-dev-refresh',
    'plugin-ready',
    'watch-ng',
    'watch-res',
    'watch-web'
  ]);

  gulp.task('default', ['dev']);

};
<|endoftext|>


<commit_before><<<<<<< HEAD
var socket = io.connect('http://localhost:3000');
=======

var socket = io.connect(location.host);
>>>>>>> works on deployed server

var controller = new Leap.Controller({enableGestures: true});
var choice = "";
controller.on('deviceFrame', function(frame) {
  for (var i = 0; i < frame.hands.length; i++) {
    var hand = frame.hands[i];

    if (hand.grabStrength > 0.6) {
      choice = "rock";
    } else if (hand.grabStrength < 0.3 && !hand.ringFinger.extended && !hand.pinky.extended) {
      choice = "scissors";
    } else if (hand.grabStrength < 0.4 && hand.thumb.extended && hand.indexFinger.extended
            && hand.middleFinger.extended && hand.ringFinger.extended && hand.pinky.extended) {
      choice = "paper";
    }
    document.getElementById('player-choice').innerHTML = choice;
  }
});

controller.connect();

socket.on('countdown', function(data) {
  setTimeout(function() { document.getElementById('count-box').innerHTML = 3 }, 1000);
  setTimeout(function() { document.getElementById('count-box').innerHTML = 2 }, 2000);
  setTimeout(function() { document.getElementById('count-box').innerHTML = 1 }, 3000);
  setTimeout(function() { document.getElementById('count-box').innerHTML = 'GO' }, 4000);
  setTimeout(collectData(), 4000);

  // for (var i = 1; i <= 4; i++) {
  //   setTimeout(function(i) {
  //     document.getElementById('count-box').innerHTML = 4 - i
  //   }, i * 1000)
  // }
  // setTimeout(collectData(), 5000);
});

function collectData() {
  socket.emit('submit', {move: 'rock'});
}

socket.on('result', function(data){
  console.log(data.result);
  socket.disconnect();
  console.log(socket);
});

function reconnect(){
  socket.socket.connect()
};

console.log('Index.js called');
<commit_msg>Fixed merge markers<commit_after>var socket = io.connect(location.host);

var controller = new Leap.Controller({enableGestures: true});
var choice = "";
controller.on('deviceFrame', function(frame) {
  for (var i = 0; i < frame.hands.length; i++) {
    var hand = frame.hands[i];

    if (hand.grabStrength > 0.6) {
      choice = "rock";
    } else if (hand.grabStrength < 0.3 && !hand.ringFinger.extended && !hand.pinky.extended) {
      choice = "scissors";
    } else if (hand.grabStrength < 0.4 && hand.thumb.extended && hand.indexFinger.extended
            && hand.middleFinger.extended && hand.ringFinger.extended && hand.pinky.extended) {
      choice = "paper";
    }
    document.getElementById('player-choice').innerHTML = choice;
  }
});

controller.connect();

socket.on('countdown', function(data) {
  setTimeout(function() { document.getElementById('count-box').innerHTML = 3 }, 1000);
  setTimeout(function() { document.getElementById('count-box').innerHTML = 2 }, 2000);
  setTimeout(function() { document.getElementById('count-box').innerHTML = 1 }, 3000);
  setTimeout(function() { document.getElementById('count-box').innerHTML = 'GO' }, 4000);
  setTimeout(collectData(), 4000);

  // for (var i = 1; i <= 4; i++) {
  //   setTimeout(function(i) {
  //     document.getElementById('count-box').innerHTML = 4 - i
  //   }, i * 1000)
  // }
  // setTimeout(collectData(), 5000);
});

function collectData() {
  socket.emit('submit', {move: 'rock'});
}

socket.on('result', function(data){
  console.log(data.result);
  socket.disconnect();
  console.log(socket);
});

function reconnect(){
  socket.socket.connect()
};

console.log('Index.js called');
<|endoftext|>


<commit_before>/*
 * Copyright 2015. Author: Jeffrey Hing. All Rights Reserved.
 *
 * MIT License
 *
 * cabinet directive
 */
'use strict';

//-------------------------------------
// Module exports
//-------------------------------------

module.exports = addToModule;

//-------------------------------------
// Module dependencies and variables
//-------------------------------------

var CabinetConfig = require('./CabinetConfig');

var drawerTriggerDirective =
    require('./drawerTriggerDirective/drawerTriggerDirective');

var drawerContentsDirective =
    require('./drawerContentsDirective/drawerContentsDirective');

var drawerClassDirective =
    require('./drawerClassDirective/drawerClassDirective');

var DrawerController = require('./DrawerController');

// Private model name.
var MODEL = '_model';

//-------------------------------------
// factory method
//-------------------------------------

/*
 * Adds the cabinet directive and its child directives to the angular module.
 *
 * @example
 *    cabinetDirective('app', options);
 *
 * @param {object} module The angular module
 * @param {object} options
 */
function addToModule(moduleName, options) {

    var module = angular.module(moduleName);

    var config = new CabinetConfig(options);
    var directiveNames = config.directiveNames;

    module.directive(directiveNames.cabinet, function() {
        return cabinetDirective(config);
    });

    module.directive(directiveNames.drawerTrigger, function() {
        return drawerTriggerDirective(directiveNames,
            config.getElementClass('drawerTrigger'));
    });

    module.directive(directiveNames.drawerContents, ['$parse', function($parse) {
        return drawerContentsDirective(directiveNames,
            config.getElementClass('drawerContents'), $parse);
    }]);

    module.directive(directiveNames.drawerClass, ['$parse', function($parse) {
        return drawerClassDirective(directiveNames, $parse);
    }]);
}

//-------------------------------------
// cabinet directive
//-------------------------------------

/*
 * The cabinetDirective identifies the element as a cabinet which contains
 * one or more drawer directives. It is responsible for determining which
 * drawers should be opened or closed based upon the drawer directive states
 * and the user specified policy options.
 *
 * @constructor
 *
 * @example
 *

 *        ...
 *
...

 *

 *
 * @param {CabinetConfig} config
 */
function cabinetDirective(config) {

    Controller.prototype = CabinetController.prototype;

    return {
        controller: ['$timeout', Controller],
        link: link,
        require: config.directiveNames.cabinet,
        restrict: 'A'
    };

    function Controller($timeout) {
        // Need to pass config to CabinetController.
        CabinetController.call(this, new CabinetConfig(config), $timeout);
    }

    function link(scope, element, attrs, controller) {

        // Add default class
        element.addClass(config.getElementClass('cabinet'));

        controller.linkCompleted(scope, attrs);
    }
}

//-------------------------------------
// cabinet controller
//-------------------------------------

/*
 * @constructor
 */
function CabinetController(config, timeout) {
    this[MODEL] = new CabinetModel(this, config, timeout);
}

var controllerProto = CabinetController.prototype;

/*
 * Link completed. Finish initialization.
 *
 * @param {object} element The cabinet element.
 */
controllerProto.linkCompleted = function(scope, attrs) {
    var m = this[MODEL];

    m.watchOptions(scope, attrs);
};

/*
 * Returns the drawer controller for the drawer with the specified
 * id. If id is undefined, it returns the most recently created
 * drawer controller.
 *
 * @param {string} [id] The id of the drawer
 * @return {object} The drawer controller.
 */
controllerProto.getDrawerController = function(id) {
    var m = this[MODEL],
        controller;

    var drawer = m.getDrawerById(id);
    if (drawer) {
        controller = drawer.controller;
    } else {
        if (id) {
            controller = this.createDrawerController(id);
        } else {
            controller = m.drawers[m.drawers.length - 1].controller;
        }
    }
    return controller;
};

/*
 * Creates a drawer controller with the specified id if it has not
 * been created before. If no id is specified, it will create
 * a new drawer controller.
 *
 * @param {string} [id] The id of the drawer
 * @return {object} The drawer controller.
 */
controllerProto.createDrawerController = function(id) {
    var m = this[MODEL];

    var drawer = m.getDrawerById(id);
    if (!drawer) {
        drawer = {
            id: id,
            controller: new DrawerController(this, m.drawers.length, m.timeout),
            isOpen: false
        };
        m.drawers.push(drawer);
    }
    return drawer.controller;
};

/*
 * Handle request to open or close a drawer.
 *
 * @param {number} index The index of the drawer.
 * @param {boolean} isOpen True to open, false to close.
 */
controllerProto.openDrawer = function(index, isOpen) {
    var m = this[MODEL];

    // Leave one drawer always open.
    if (!isOpen && m.config.oneAlwaysOpen) {
        if (m.openDrawerCount() <= 1) {
            return;
        }
    }

    // If opening drawer and only one drawer can be open
    // at a time, close the other drawers.
    if (isOpen && !m.config.allowMultipleOpen) {
        angular.forEach(m.drawers, function(drawer, i) {
            if (i !== index) {
                drawer.isOpen = false;
                drawer.controller.open(drawer.isOpen);
            }
        });
    }

    var currentDrawer = m.drawers[index];
    currentDrawer.isOpen = isOpen;
    currentDrawer.controller.open(isOpen);
};

/*
 * Adds a listener which is notified when the configuration changes.
 *
 * @param {function} listener
 */
controllerProto.addConfigListener = function(listener) {
    var m = this[MODEL];
    m.configListeners.push(listener);
};

//-------------------------------------
// cabinet controller's private model
//-------------------------------------

/*
 * @constructor
 */
function CabinetModel(controller, config, timeout) {
    this.controller = controller;

    // Timeout service.
    this.timeout = timeout;

    // Current configuration.
    this.config = config;

    // Listeners to notify when options change.
    this.configListeners = [];

    // Registered drawers.
    this.drawers = [];
}

var modelProto = CabinetModel.prototype;

/*
 * Watch for option changes on the scope.
 */
modelProto.watchOptions = function(scope, attrs) {
    var self = this;
    var cabinetDirectiveName = self.config.directiveNames.cabinet;

    // If no options specified, apply the default options.
    if (!attrs[cabinetDirectiveName]) {
        processOptions(self.config, self.config);
        return;
    }

    // Watch if the options change.
    scope.$watchCollection(attrs[cabinetDirectiveName], processOptions);

    function processOptions(options, oldOptions) {

        if (!options) {
            return;
        }

        var isFirstWatch = options === oldOptions;

        var openStatesChanged = isFirstWatch ||
            (options.openStates !== oldOptions.openStates);

        var oneAlwaysOpenChanged = isFirstWatch ||
            (options.oneAlwaysOpen !== oldOptions.oneAlwaysOpen);

        // Ensure that these options are applied which may affect
        // how the next options are applied.
        self.config.copyOptions(options, true);

        // Open/close the specified drawers.
        if (openStatesChanged) {
            if (options.openStates) {
                self.openDrawersById(options.openStates, true);
            }
        }

        // Ensure at least one drawer is opened.
        if (oneAlwaysOpenChanged) {
            if (options.oneAlwaysOpen) {
                if (self.openDrawerCount() === 0) {
                    self.controller.openDrawer(0, true);
                }
            }
        }

        isFirstWatch = false;

        self.notifyConfigListeners();
    }
};

/*
 * Notify options listeners of the current options.
 */
modelProto.notifyConfigListeners = function() {
    for (var i = 0; i < this.configListeners.length; i++) {
        this.configListeners[i](this.config);
    }
};

/*
 * Set the open state of the drawers, where each drawer is identifed
 * by a key. If a key is a number, it is interpreted as the index of
 * the drawer. If a key is a string, it is interpreted as the element
 * class of the drawer.
 *
 * @param {object} openStates A mapping of drawer id to open state.
 */
modelProto.openDrawersById = function(openStates) {
    for (var i = 0; i < this.drawers.length; i++) {
        var drawer = this.drawers[i];
        if (drawer.id !== undefined) {
            var isOpen = openStates[drawer.id];
            if (isOpen !== undefined) {
                this.controller.openDrawer(i, isOpen);
            }
        }
    }
};

/*
 * Returns the drawer with the specified id.
 *
 * @param {string} id The id of the drawer
 * @return {object} The drawer or null if not found.
 */
modelProto.getDrawerById = function(id) {
    if (id) {
        for (var i = this.drawers.length - 1; i >= 0; i--) {
            if (this.drawers[i].id === id) {
                return this.drawers[i];
            }
        }
    }
    return null;
};

/*
 * Return the number of opened drawers.
 *
 * @return {number}
 */
modelProto.openDrawerCount = function() {
    var count = 0;

    for (var i = 0; i < this.drawers.length; i++) {
        if (this.drawers[i].isOpen) {
            count++;
        }
    }
    return count;
};
<commit_msg>Remove need to pass controller into model.<commit_after>/*
 * Copyright 2015. Author: Jeffrey Hing. All Rights Reserved.
 *
 * MIT License
 *
 * cabinet directive
 */
'use strict';

//-------------------------------------
// Module exports
//-------------------------------------

module.exports = addToModule;

//-------------------------------------
// Module dependencies and variables
//-------------------------------------

var CabinetConfig = require('./CabinetConfig');

var drawerTriggerDirective =
    require('./drawerTriggerDirective/drawerTriggerDirective');

var drawerContentsDirective =
    require('./drawerContentsDirective/drawerContentsDirective');

var drawerClassDirective =
    require('./drawerClassDirective/drawerClassDirective');

var DrawerController = require('./DrawerController');

// Private model name.
var MODEL = '_model';

//-------------------------------------
// factory method
//-------------------------------------

/*
 * Adds the cabinet directive and its child directives to the angular module.
 *
 * @example
 *    cabinetDirective('app', options);
 *
 * @param {object} module The angular module
 * @param {object} options
 */
function addToModule(moduleName, options) {

    var module = angular.module(moduleName);

    var config = new CabinetConfig(options);
    var directiveNames = config.directiveNames;

    module.directive(directiveNames.cabinet, function() {
        return cabinetDirective(config);
    });

    module.directive(directiveNames.drawerTrigger, function() {
        return drawerTriggerDirective(directiveNames,
            config.getElementClass('drawerTrigger'));
    });

    module.directive(directiveNames.drawerContents, ['$parse', function($parse) {
        return drawerContentsDirective(directiveNames,
            config.getElementClass('drawerContents'), $parse);
    }]);

    module.directive(directiveNames.drawerClass, ['$parse', function($parse) {
        return drawerClassDirective(directiveNames, $parse);
    }]);
}

//-------------------------------------
// cabinet directive
//-------------------------------------

/*
 * The cabinetDirective identifies the element as a cabinet which contains
 * one or more drawer directives. It is responsible for determining which
 * drawers should be opened or closed based upon the drawer directive states
 * and the user specified policy options.
 *
 * @constructor
 *
 * @example
 *

 *        ...
 *
...

 *

 *
 * @param {CabinetConfig} config
 */
function cabinetDirective(config) {

    Controller.prototype = CabinetController.prototype;

    return {
        controller: ['$timeout', Controller],
        link: link,
        require: config.directiveNames.cabinet,
        restrict: 'A'
    };

    function Controller($timeout) {
        // Need to pass config to CabinetController.
        CabinetController.call(this, new CabinetConfig(config), $timeout);
    }

    function link(scope, element, attrs, controller) {

        // Add default class
        element.addClass(config.getElementClass('cabinet'));

        controller.linkCompleted(scope, attrs);
    }
}

//-------------------------------------
// cabinet controller
//-------------------------------------

/*
 * @constructor
 */
function CabinetController(config, timeout) {
    this[MODEL] = new CabinetModel(config, timeout);
}

var controllerProto = CabinetController.prototype;

/*
 * Link completed. Finish initialization.
 *
 * @param {object} element The cabinet element.
 */
controllerProto.linkCompleted = function(scope, attrs) {
    var m = this[MODEL];

    m.watchOptions(scope, attrs);
};

/*
 * Returns the drawer controller for the drawer with the specified
 * id. If id is undefined, it returns the most recently created
 * drawer controller.
 *
 * @param {string} [id] The id of the drawer
 * @return {object} The drawer controller.
 */
controllerProto.getDrawerController = function(id) {
    var m = this[MODEL],
        controller;

    var drawer = m.getDrawerById(id);
    if (drawer) {
        controller = drawer.controller;
    } else {
        if (id) {
            controller = this.createDrawerController(id);
        } else {
            controller = m.drawers[m.drawers.length - 1].controller;
        }
    }
    return controller;
};

/*
 * Creates a drawer controller with the specified id if it has not
 * been created before. If no id is specified, it will create
 * a new drawer controller.
 *
 * @param {string} [id] The id of the drawer
 * @return {object} The drawer controller.
 */
controllerProto.createDrawerController = function(id) {
    var m = this[MODEL];

    var drawer = m.getDrawerById(id);
    if (!drawer) {
        drawer = {
            id: id,
            controller: new DrawerController(this, m.drawers.length, m.timeout),
            isOpen: false
        };
        m.drawers.push(drawer);
    }
    return drawer.controller;
};

/*
 * Handle request to open or close a drawer.
 *
 * @param {number} index The index of the drawer.
 * @param {boolean} isOpen True to open, false to close.
 */
controllerProto.openDrawer = function(index, isOpen) {
    var m = this[MODEL];
    m.openDrawer(index, isOpen);
};

/*
 * Adds a listener which is notified when the configuration changes.
 *
 * @param {function} listener
 */
controllerProto.addConfigListener = function(listener) {
    var m = this[MODEL];
    m.configListeners.push(listener);
};

//-------------------------------------
// cabinet controller's private model
//-------------------------------------

/*
 * @constructor
 */
function CabinetModel(config, timeout) {

    // Timeout service.
    this.timeout = timeout;

    // Current configuration.
    this.config = config;

    // Listeners to notify when options change.
    this.configListeners = [];

    // Registered drawers.
    this.drawers = [];
}

var modelProto = CabinetModel.prototype;

/*
 * Watch for option changes on the scope.
 */
modelProto.watchOptions = function(scope, attrs) {
    var self = this;
    var cabinetDirectiveName = self.config.directiveNames.cabinet;

    // If no options specified, apply the default options.
    if (!attrs[cabinetDirectiveName]) {
        processOptions(self.config, self.config);
        return;
    }

    // Watch if the options change.
    scope.$watchCollection(attrs[cabinetDirectiveName], processOptions);

    function processOptions(options, oldOptions) {

        if (!options) {
            return;
        }

        var isFirstWatch = options === oldOptions;

        var openStatesChanged = isFirstWatch ||
            (options.openStates !== oldOptions.openStates);

        var oneAlwaysOpenChanged = isFirstWatch ||
            (options.oneAlwaysOpen !== oldOptions.oneAlwaysOpen);

        // Ensure that these options are applied which may affect
        // how the next options are applied.
        self.config.copyOptions(options, true);

        // Open/close the specified drawers.
        if (openStatesChanged) {
            if (options.openStates) {
                self.openDrawersById(options.openStates, true);
            }
        }

        // Ensure at least one drawer is opened.
        if (oneAlwaysOpenChanged) {
            if (options.oneAlwaysOpen) {
                if (self.openDrawerCount() === 0) {
                    self.openDrawer(0, true);
                }
            }
        }

        isFirstWatch = false;

        self.notifyConfigListeners();
    }
};

/*
 * Notify options listeners of the current options.
 */
modelProto.notifyConfigListeners = function() {
    for (var i = 0; i < this.configListeners.length; i++) {
        this.configListeners[i](this.config);
    }
};

/*
 * Handle request to open or close a drawer.
 *
 * @param {number} index The index of the drawer.
 * @param {boolean} isOpen True to open, false to close.
 */
modelProto.openDrawer = function(index, isOpen) {

    // Leave one drawer always open.
    if (!isOpen && this.config.oneAlwaysOpen) {
        if (this.openDrawerCount() <= 1) {
            return;
        }
    }

    // If opening drawer and only one drawer can be open
    // at a time, close the other drawers.
    if (isOpen && !this.config.allowMultipleOpen) {
        angular.forEach(this.drawers, function(drawer, i) {
            if (i !== index) {
                drawer.isOpen = false;
                drawer.controller.open(drawer.isOpen);
            }
        });
    }

    var currentDrawer = this.drawers[index];
    currentDrawer.isOpen = isOpen;
    currentDrawer.controller.open(isOpen);
};

/*
 * Set the open state of the drawers, where each drawer is identifed
 * by a key. If a key is a number, it is interpreted as the index of
 * the drawer. If a key is a string, it is interpreted as the element
 * class of the drawer.
 *
 * @param {object} openStates A mapping of drawer id to open state.
 */
modelProto.openDrawersById = function(openStates) {
    for (var i = 0; i < this.drawers.length; i++) {
        var drawer = this.drawers[i];
        if (drawer.id !== undefined) {
            var isOpen = openStates[drawer.id];
            if (isOpen !== undefined) {
                this.openDrawer(i, isOpen);
            }
        }
    }
};

/*
 * Returns the drawer with the specified id.
 *
 * @param {string} id The id of the drawer
 * @return {object} The drawer or null if not found.
 */
modelProto.getDrawerById = function(id) {
    if (id) {
        for (var i = this.drawers.length - 1; i >= 0; i--) {
            if (this.drawers[i].id === id) {
                return this.drawers[i];
            }
        }
    }
    return null;
};

/*
 * Return the number of opened drawers.
 *
 * @return {number}
 */
modelProto.openDrawerCount = function() {
    var count = 0;

    for (var i = 0; i < this.drawers.length; i++) {
        if (this.drawers[i].isOpen) {
            count++;
        }
    }
    return count;
};
<|endoftext|>


<commit_before>'use strict'

var opbeat = require('opbeat').start({
  appId: process.env.WORKLOAD_OPBEAT_APP_ID,
  organizationId: process.env.WORKLOAD_OPBEAT_ORG_ID,
  secretToken: process.env.WORKLOAD_OPBEAT_SECRET_TOKEN,
  active: process.env.NODE_ENV === 'production'
})

var Workload = require('workload')
var conf = require('./server/config')
var url = conf.server.url + '/'
var api = url + 'api/'

module.exports = {
  max: 60,
  filters: [
    Workload.stdFilters.expand,
    Workload.stdFilters.workdays,
    fillOutOrder
  ],
  requests: [
    {weight: 10, url: url},
    {weight: 10, url: url + 'favicon.ico'},
    {weight: 1, url: url, method: 'OPTIONS'},
    {weight: 8, url: api + 'products'},
    {weight: 6, url: api + 'products/{1..3}'},
    {weight: 3, url: api + 'products/{1..3}/customers'},
    {weight: 3, url: api + 'types'},
    {weight: 3, url: api + 'types/{1..3}'},
    {weight: 5, url: api + 'customers'},
    {weight: 4, url: api + 'customers/{1..1000}'},
    {weight: 7, url: api + 'orders'},
    {weight: 1, url: api + 'orders', method: 'POST'},
    {weight: 6, url: api + 'orders/{1..500}'}
  ]
}

function fillOutOrder (req, next) {
  if (req.method === 'POST' && req.url === api + 'orders') {
    var order = {
      customer_id: randId(1000),
      lines: []
    }
    for (var n = 0; n < 5; n++) {
      order.lines.push({id: randId(3), amount: rand(3) + 1})
    }
    req.json = order
  }
  next(req)
}

function rand (max) {
  return Math.round(Math.random() * max)
}

function randId (max) {
  return rand(max - 1) + 1
}
<commit_msg>Add few more product id's in workload settings<commit_after>'use strict'

var opbeat = require('opbeat').start({
  appId: process.env.WORKLOAD_OPBEAT_APP_ID,
  organizationId: process.env.WORKLOAD_OPBEAT_ORG_ID,
  secretToken: process.env.WORKLOAD_OPBEAT_SECRET_TOKEN,
  active: process.env.NODE_ENV === 'production'
})

var Workload = require('workload')
var conf = require('./server/config')
var url = conf.server.url + '/'
var api = url + 'api/'

module.exports = {
  max: 60,
  filters: [
    Workload.stdFilters.expand,
    Workload.stdFilters.workdays,
    fillOutOrder
  ],
  requests: [
    {weight: 10, url: url},
    {weight: 10, url: url + 'favicon.ico'},
    {weight: 1, url: url, method: 'OPTIONS'},
    {weight: 8, url: api + 'products'},
    {weight: 6, url: api + 'products/{1..6}'},
    {weight: 3, url: api + 'products/{1..6}/customers'},
    {weight: 3, url: api + 'types'},
    {weight: 3, url: api + 'types/{1..3}'},
    {weight: 5, url: api + 'customers'},
    {weight: 4, url: api + 'customers/{1..1000}'},
    {weight: 7, url: api + 'orders'},
    {weight: 1, url: api + 'orders', method: 'POST'},
    {weight: 6, url: api + 'orders/{1..500}'}
  ]
}

function fillOutOrder (req, next) {
  if (req.method === 'POST' && req.url === api + 'orders') {
    var order = {
      customer_id: randId(1000),
      lines: []
    }
    for (var n = 0; n < 5; n++) {
      order.lines.push({id: randId(3), amount: rand(3) + 1})
    }
    req.json = order
  }
  next(req)
}

function rand (max) {
  return Math.round(Math.random() * max)
}

function randId (max) {
  return rand(max - 1) + 1
}
<|endoftext|>


<commit_before>define([
	'underscore',
	'backbone',
	'text!templates/dialog_option_editor.tpl',
	'vent'
], function(_, Backbone, Template, vent) {
	return Backbone.Marionette.ItemView.extend({

		template: _.template(Template),

		initialize: function(options) {
			this.scripts = options.scripts;

			this.plaques   = options.contents.plaques;
			this.items     = options.contents.items;
			this.web_pages = options.contents.web_pages;
			this.dialogs   = options.contents.dialogs;
			this.tabs      = options.contents.tabs;

			this.previous_attributes = _.clone(this.model.attributes)
		},

		templateHelpers: function() {
			return {
				is_new: this.model.isNew(),

				option_selected: function(boolean_statement) {
					return boolean_statement ? "selected" : "";
				},
				link_types: this.link_types,

				scripts: this.scripts,

				// game objects for option menu
				plaques:   this.plaques,
				items:     this.items,
				web_pages: this.web_pages,
				dialogs:   this.dialogs,
				tabs:      this.tabs,

				link_options_visible: this.model.get("link_type") !== "EXIT",

				link_scripts:   this.model.get("link_type") === "DIALOG_SCRIPT",
				link_plaques:   this.model.get("link_type") === "EXIT_TO_PLAQUE",
				link_items:     this.model.get("link_type") === "EXIT_TO_ITEM",
				link_web_pages: this.model.get("link_type") === "EXIT_WEB_PAGE",
				link_dialogs:   this.model.get("link_type") === "EXIT_DIALOG",
				link_tabs:      this.model.get("link_type") === "EXIT_TAB"
			}
		},

		ui: {
			link_type: ".link-type",
			link_id:   ".link-id",
			prompt:    ".prompt"
		},

		events: {
			"change @ui.link_type": "onChangeLinkType",
			"change @ui.link_id":   "onChangeLinkId",
			"change @ui.prompt":    "onChangePrompt",
			"click .save":          "onClickSave",
			"click .cancel":        "onClickCancel",
			"click .edit-requirements": "onClickEditRequirements",
		},

		link_types: {
			'DIALOG_SCRIPT':    "Say Line",
			'EXIT':             "End Conversation",
			'EXIT_TO_PLAQUE':   "Exit to Plaque",
			'EXIT_TO_ITEM':     "Exit to Item",
			'EXIT_TO_WEB_PAGE': "Exit to Web Page",
			'EXIT_TO_DIALOG':   "Exit to Conversation",
			'EXIT_TO_TAB':      "Exit to Tab"
		},

		onChangeLinkType: function() {
			var value = this.ui.link_type.find("option:selected").val();
			this.model.set("link_type", value);

			// 0 out link ID before re-rendering sub select
			this.model.set("link_id", "0");
			this.render();
		},

		onChangeLinkId: function() {
			var value = this.ui.link_id.find("option:selected").val();
			this.model.set("link_id", value);
		},

		onChangePrompt: function() {
			this.model.set("prompt", this.ui.prompt.val());
		},

		onClickSave: function() {
			this.model.save({}, {
				success: function() {
					vent.trigger("conversation:update");
					vent.trigger("application:info:hide");
				}
			});
		},

		onClickCancel: function() {
			this.model.set(this.previous_attributes);
			vent.trigger("application:info:hide");
		}
	});
});
<commit_msg>Requirements for options<commit_after>define([
	'underscore',
	'backbone',
	'text!templates/dialog_option_editor.tpl',
	'views/requirements',
	'models/requirement_package',
	'models/game',
	'collections/and_packages',
	'collections/atoms',
	'collections/items',
	'collections/tags',
	'collections/plaques',
	'collections/dialogs',
	'collections/web_pages',
	'collections/quests',
	'collections/web_hooks',
	'vent'
], function(_, Backbone, Template,
	RequirementsEditorView,
	RequirementPackage,
	Game,
	AndPackagesCollection,
	AtomsCollection,
	ItemsCollection,
	TagsCollection,
	PlaquesCollection,
	DialogsCollection,
	WebPagesCollection,
	QuestsCollection,
	WebHooksCollection,
	vent) {
	return Backbone.Marionette.ItemView.extend({

		template: _.template(Template),

		initialize: function(options) {
			this.scripts = options.scripts;

			this.plaques   = options.contents.plaques;
			this.items     = options.contents.items;
			this.web_pages = options.contents.web_pages;
			this.dialogs   = options.contents.dialogs;
			this.tabs      = options.contents.tabs;

			this.previous_attributes = _.clone(this.model.attributes)
		},

		templateHelpers: function() {
			return {
				is_new: this.model.isNew(),

				option_selected: function(boolean_statement) {
					return boolean_statement ? "selected" : "";
				},
				link_types: this.link_types,

				scripts: this.scripts,

				// game objects for option menu
				plaques:   this.plaques,
				items:     this.items,
				web_pages: this.web_pages,
				dialogs:   this.dialogs,
				tabs:      this.tabs,

				link_options_visible: this.model.get("link_type") !== "EXIT",

				link_scripts:   this.model.get("link_type") === "DIALOG_SCRIPT",
				link_plaques:   this.model.get("link_type") === "EXIT_TO_PLAQUE",
				link_items:     this.model.get("link_type") === "EXIT_TO_ITEM",
				link_web_pages: this.model.get("link_type") === "EXIT_WEB_PAGE",
				link_dialogs:   this.model.get("link_type") === "EXIT_DIALOG",
				link_tabs:      this.model.get("link_type") === "EXIT_TAB"
			}
		},

		ui: {
			link_type: ".link-type",
			link_id:   ".link-id",
			prompt:    ".prompt"
		},

		events: {
			"change @ui.link_type": "onChangeLinkType",
			"change @ui.link_id":   "onChangeLinkId",
			"change @ui.prompt":    "onChangePrompt",
			"click .save":          "onClickSave",
			"click .cancel":        "onClickCancel",
			"click .edit-requirements": "onClickEditRequirements",
		},

		link_types: {
			'DIALOG_SCRIPT':    "Say Line",
			'EXIT':             "End Conversation",
			'EXIT_TO_PLAQUE':   "Exit to Plaque",
			'EXIT_TO_ITEM':     "Exit to Item",
			'EXIT_TO_WEB_PAGE': "Exit to Web Page",
			'EXIT_TO_DIALOG':   "Exit to Conversation",
			'EXIT_TO_TAB':      "Exit to Tab"
		},

		onChangeLinkType: function() {
			var value = this.ui.link_type.find("option:selected").val();
			this.model.set("link_type", value);

			// 0 out link ID before re-rendering sub select
			this.model.set("link_id", "0");
			this.render();
		},

		onChangeLinkId: function() {
			var value = this.ui.link_id.find("option:selected").val();
			this.model.set("link_id", value);
		},

		onChangePrompt: function() {
			this.model.set("prompt", this.ui.prompt.val());
		},

		onClickSave: function() {
			this.model.save({}, {
				success: function() {
					vent.trigger("conversation:update");
					vent.trigger("application:info:hide");
				}
			});
		},

		onClickCancel: function() {
			this.model.set(this.previous_attributes);
			vent.trigger("application:info:hide");
		},

		onClickEditRequirements: function() {
			var view = this;

			var requirement_package = new RequirementPackage({requirement_root_package_id: view.model.get("requirement_root_package_id"), game_id: view.model.get("game_id")});

			var game = new Game({game_id: view.model.get("game_id")});

			var contents = {
				items:      new ItemsCollection    ([], {parent: game}),
				tags:       new TagsCollection     ([], {parent: game}),
				plaques:    new PlaquesCollection  ([], {parent: game}),
				dialogs:    new DialogsCollection  ([], {parent: game}),
				web_pages:  new WebPagesCollection ([], {parent: game}),
				quests:     new QuestsCollection   ([], {parent: game}),
				hooks:      new WebHooksCollection ([], {parent: game})
			};

			if(requirement_package.id === "0") { requirement_package.fetch = function() {}; }

			$.when(contents.items.fetch(), contents.tags.fetch(), contents.plaques.fetch(), contents.dialogs.fetch(), contents.web_pages.fetch(), contents.quests.fetch(), contents.hooks.fetch(), requirement_package.fetch()).done(function()
			{
				// Load associations into collections
				var and_packages = new AndPackagesCollection(requirement_package.get("and_packages"));
				requirement_package.set("and_packages", and_packages);

				and_packages.each(function(and_package) {
					var atoms = new AtomsCollection(and_package.get("atoms"));
					and_package.set("atoms", atoms);
				});

				// launch editor
				var requirements_editor = new RequirementsEditorView({model: requirement_package, collection: and_packages, contents: contents});

				requirements_editor.on("cancel", function()
				{
					vent.trigger("application:popup:hide");
				});

				requirements_editor.on("requirement_package:save", function(requirement_package)
				{
					view.model.set("requirement_root_package_id", requirement_package.id);
					vent.trigger("application:popup:hide");
				});

				vent.trigger("application:popup:show", requirements_editor, "Locks Editor");
			});
		}
	});
});
<|endoftext|>


<commit_before>/* jshint -W097 */// jshint strict:false
/*jslint node: true */
var expect = require('chai').expect;
var setup  = require(__dirname + '/lib/setup');
var fs     = require('fs');

var objects = null;
var states  = null;
var onStateChanged = null;
var onObjectChanged = null;
var sendToID = 1;

var adapterShortName = setup.adapterName.substring(setup.adapterName.indexOf('.')+1);
var adapterShortNameLog = adapterShortName + ' Config Recurring Fullday';

function checkConnectionOfAdapter(cb, counter) {
    counter = counter || 0;
    console.log('Try check #' + counter);
    if (counter > 30) {
        if (cb) cb('Cannot check connection');
        return;
    }

    states.getState('system.adapter.' + adapterShortName + '.0.alive', function (err, state) {
        if (err) console.error(err);
        if (state && state.val) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkConnectionOfAdapter(cb, counter + 1);
            }, 1000);
        }
    });
}

function checkValueOfState(id, value, cb, counter) {
    counter = counter || 0;
    if (counter > 20) {
        if (cb) cb('Cannot check value Of State ' + id);
        return;
    }

    states.getState(id, function (err, state) {
        if (err) console.error(err);
        if (value === null && !state) {
            if (cb) cb();
        } else
        if (state && (value === undefined || state.val === value)) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkValueOfState(id, value, cb, counter + 1);
            }, 500);
        }
    });
}

function sendTo(target, command, message, callback) {
    onStateChanged = function (id, state) {
        if (id === 'messagebox.system.adapter.test.0') {
            callback(state.message);
        }
    };

    states.pushMessage('system.adapter.' + target, {
        command:    command,
        message:    message,
        from:       'system.adapter.test.0',
        callback: {
            message: message,
            id:      sendToID++,
            ack:     false,
            time:    (new Date()).getTime()
        }
    });
}

function setupIcsFiles() {
    if (!fs.existsSync(__dirname + '/data/recurring_fullday.ics')) {
        var d1 = new Date();
        var m1 = (d1.getMonth() + 1);
        if (m1 < 10) m1 = '0' + m1;
        var day1 = d1.getDate();
        if (day1 < 10) day1 = '0' + day1;

        var d2 = new Date();
        d2.setDate(d2.getDate() + 1);
        var m2 = (d2.getMonth() + 1);
        if (m2 < 10) m2 = '0' + m2;
        var day2 = d2.getDate();
        if (day2 < 10) day2 = '0' + day2;

        var data = 'BEGIN:VCALENDAR\n';
        data += 'PRODID:-//Google Inc//Google Calendar 70.9054//EN\n';
        data += 'VERSION:2.0\n';
        data += 'CALSCALE:GREGORIAN\n';
        data += 'METHOD:PUBLISH\n';
        data += 'X-WR-CALNAME:Schichtplan\n';
        data += 'X-WR-TIMEZONE:Europe/Berlin\n';
        data += 'X-WR-CALDESC:Zur Heizungssteuerung\n';
        data += 'BEGIN:VTIMEZONE\n';
        data += 'TZID:Europe/Berlin\n';
        data += 'X-LIC-LOCATION:Europe/Berlin\n';
        data += 'BEGIN:DAYLIGHT\n';
        data += 'TZOFFSETFROM:+0100\n';
        data += 'TZOFFSETTO:+0200\n';
        data += 'TZNAME:CEST\n';
        data += 'DTSTART:19700329T020000\n';
        data += 'RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU\n';
        data += 'END:DAYLIGHT\n';
        data += 'BEGIN:STANDARD\n';
        data += 'TZOFFSETFROM:+0200\n';
        data += 'TZOFFSETTO:+0100\n';
        data += 'TZNAME:CET\n';
        data += 'DTSTART:19701025T030000\n';
        data += 'RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU\n';
        data += 'END:STANDARD\n';
        data += 'END:VTIMEZONE\n';

		data += 'BEGIN:VEVENT\n';
		data += 'DTSTART;VALUE=DATE:' + d1.getFullYear() + m1 + day1 + '\n';
		data += 'DTEND;VALUE=DATE:' + d2.getFullYear() + m2 + day2 + '\n';
		data += 'RRULE:FREQ=WEEKLY;BYDAY=SU,SA\n';
		data += 'DTSTAMP:20181010T062520Z\n';
		data += 'UID:2C340B07-5893-4234-B0E5-A5EE82858F01\n';
		data += 'CREATED:20181008T073122Z\n';
		data += 'DESCRIPTION:WE\n';
		data += 'LAST-MODIFIED:20181008T073122Z\n';
		data += 'LOCATION:\n';
		data += 'SEQUENCE:0\n';
		data += 'STATUS:CONFIRMED\n';
		data += 'SUMMARY:WE\n';
		data += 'TRANSP:TRANSPARENT\n';
		data += 'END:VEVENT\n';

        data += 'END:VCALENDAR';
        fs.writeFileSync(__dirname + '/data/recurring_fullday.ics', data);
    }
}

function parseDate(input) {
	  var parts = input.split('.');
	  var date = new Date(new Date().getFullYear(), parts[1]-1, parts[0]);
	  var today = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()).getTime();

	  if(date.getTime() < today) {
		  date = new Date(new Date().getFullYear() + 1, parts[1] - 1, parts[0]);
	  }

	  return date;
}

describe('Test ' + adapterShortNameLog + ' adapter', function() {
    before('Test ' + adapterShortNameLog + ' adapter: Start js-controller', function (_done) {
        this.timeout(600000); // because of first install from npm

        setupIcsFiles();

        setup.setupController(function () {
            var config = setup.getAdapterConfig();
            // enable adapter
            config.common.enabled  = true;
            config.common.loglevel = 'silly';

            config.native.fulltime = "";
            config.native.forceFullday = false;
            config.native.replaceDates = false;
            config.native.hideYear = true;
            config.native.daysPreview = 8;
            config.native.calendars[0] = {
                "name": "calendar1-recurring",
                "url": __dirname + '/data/recurring_fullday.ics',
                "user": "username",
                "pass": "password",
                "sslignore": "ignore",
                "color": "red"
            };

            config.native.events[0] = {
                "name": "Vacation",
                "enabled": true,
                "display": false
            };
            config.native.events[1] = {
                "name": "MyEvent",
                "enabled": true,
                "display": true
            };
            config.native.events[2] = {
                "name": "TestEvent",
                "enabled": true,
                "display": true
            };
            config.native.events[3] = {
                "name": "InDayEvent",
                "enabled": true,
                "display": false
            };

            setup.setAdapterConfig(config.common, config.native);

            setup.startController(true, function(id, obj) {}, function (id, state) {
                    if (onStateChanged) onStateChanged(id, state);
                },
                function (_objects, _states) {
                    objects = _objects;
                    states  = _states;
                    _done();
                });
        });
    });

    it('Test ' + adapterShortNameLog + ' adapter: Check if adapter started', function (done) {
        this.timeout(60000);
        checkConnectionOfAdapter(function (res) {
            if (res) console.log(res);
            expect(res).not.to.be.equal('Cannot check connection');
            objects.setObject('system.adapter.test.0', {
                    common: {

                    },
                    type: 'instance'
                },
                function () {
                    states.subscribeMessage('system.adapter.test.0');
                    done();
                });
        });
    });

    it('Test ' + adapterShortNameLog + ': check count of events', function (done) {
        this.timeout(5000);
        setTimeout(function () {
            states.getState('ical.0.data.count', function (err, state) {
                expect(err).to.be.not.ok;
                expect(state.val).to.be.equal(0);
                done();
            });
        }, 3000);
    });

    it('Test ' + adapterShortNameLog + ': event Vacation', function (done) {
        this.timeout(5000);
        setTimeout(function () {
            states.getState('ical.0.events.Vacation', function (err, state) {
                expect(err).to.be.not.ok;
                expect(state.val).to.be.false;
                done();
            });
        }, 3000);
    });

    it('Test ' + adapterShortNameLog + ': event MyEvent', function (done) {
        this.timeout(5000);
        setTimeout(function () {
            states.getState('ical.0.events.MyEvent', function (err, state) {
                expect(err).to.be.not.ok;
                expect(state.val).to.be.false;
                done();
            });
        }, 3000);
    });

    it('Test ' + adapterShortNameLog + ': event TestEvent', function (done) {
        this.timeout(5000);
        setTimeout(function () {
            states.getState('ical.0.events.TestEvent', function (err, state) {
                expect(err).to.be.not.ok;
                expect(state.val).to.be.false;
                done();
            });
        }, 3000);
    });

    it('Test ' + adapterShortNameLog + ': event InDayEvent', function (done) {
        this.timeout(5000);
        setTimeout(function () {
            states.getState('ical.0.events.InDayEvent', function (err, state) {
                expect(err).to.be.not.ok;
                expect(state.val).to.be.false;
                done();
            });
        }, 3000);
    });

    it('Test ' + adapterShortNameLog + ': data.table', function (done) {
        this.timeout(2000);
        setTimeout(function () {
            states.getState('ical.0.data.table', function (err, state) {
                expect(err).to.be.not.ok;
                expect(state.val[0].date.indexOf('. 00:00')).to.be.equal(5);
                expect(state.val[0].event).to.be.equal('WE');
                expect(state.val[0]._section).to.be.equal('WE');
                expect(state.val[0]._allDay).to.be.true;

                expect(state.val[1].date.indexOf('. 00:00')).to.be.equal(5);
                expect(state.val[1].event).to.be.equal('WE');
                expect(state.val[1]._section).to.be.equal('WE');
                expect(state.val[1]._allDay).to.be.true;

                expect([
                	parseDate(state.val[0].date).getDay(),
                	parseDate(state.val[1].date).getDay()
                ]).to.be.an('array').that.includes(0, 6);

                done();
            });
        }, 1000);
    });

    after('Test ' + adapterShortNameLog + ' adapter: Stop js-controller', function (done) {
        this.timeout(10000);

        setup.stopController(function (normalTerminated) {
            console.log('Adapter normal terminated: ' + normalTerminated);
            done();
        });
    });
});
<commit_msg>fix test running on weekend<commit_after>/* jshint -W097 */// jshint strict:false
/*jslint node: true */
var expect = require('chai').expect;
var setup  = require(__dirname + '/lib/setup');
var fs     = require('fs');

var objects = null;
var states  = null;
var onStateChanged = null;
var onObjectChanged = null;
var sendToID = 1;

var adapterShortName = setup.adapterName.substring(setup.adapterName.indexOf('.')+1);
var adapterShortNameLog = adapterShortName + ' Config Recurring Fullday';

function checkConnectionOfAdapter(cb, counter) {
    counter = counter || 0;
    console.log('Try check #' + counter);
    if (counter > 30) {
        if (cb) cb('Cannot check connection');
        return;
    }

    states.getState('system.adapter.' + adapterShortName + '.0.alive', function (err, state) {
        if (err) console.error(err);
        if (state && state.val) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkConnectionOfAdapter(cb, counter + 1);
            }, 1000);
        }
    });
}

function checkValueOfState(id, value, cb, counter) {
    counter = counter || 0;
    if (counter > 20) {
        if (cb) cb('Cannot check value Of State ' + id);
        return;
    }

    states.getState(id, function (err, state) {
        if (err) console.error(err);
        if (value === null && !state) {
            if (cb) cb();
        } else
        if (state && (value === undefined || state.val === value)) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkValueOfState(id, value, cb, counter + 1);
            }, 500);
        }
    });
}

function sendTo(target, command, message, callback) {
    onStateChanged = function (id, state) {
        if (id === 'messagebox.system.adapter.test.0') {
            callback(state.message);
        }
    };

    states.pushMessage('system.adapter.' + target, {
        command:    command,
        message:    message,
        from:       'system.adapter.test.0',
        callback: {
            message: message,
            id:      sendToID++,
            ack:     false,
            time:    (new Date()).getTime()
        }
    });
}

function setupIcsFiles() {
    if (!fs.existsSync(__dirname + '/data/recurring_fullday.ics')) {
        var d1 = new Date();
        var m1 = (d1.getMonth() + 1);
        if (m1 < 10) m1 = '0' + m1;
        var day1 = d1.getDate();
        if (day1 < 10) day1 = '0' + day1;

        var d2 = new Date();
        d2.setDate(d2.getDate() + 1);
        var m2 = (d2.getMonth() + 1);
        if (m2 < 10) m2 = '0' + m2;
        var day2 = d2.getDate();
        if (day2 < 10) day2 = '0' + day2;

        var data = 'BEGIN:VCALENDAR\n';
        data += 'PRODID:-//Google Inc//Google Calendar 70.9054//EN\n';
        data += 'VERSION:2.0\n';
        data += 'CALSCALE:GREGORIAN\n';
        data += 'METHOD:PUBLISH\n';
        data += 'X-WR-CALNAME:Schichtplan\n';
        data += 'X-WR-TIMEZONE:Europe/Berlin\n';
        data += 'X-WR-CALDESC:Zur Heizungssteuerung\n';
        data += 'BEGIN:VTIMEZONE\n';
        data += 'TZID:Europe/Berlin\n';
        data += 'X-LIC-LOCATION:Europe/Berlin\n';
        data += 'BEGIN:DAYLIGHT\n';
        data += 'TZOFFSETFROM:+0100\n';
        data += 'TZOFFSETTO:+0200\n';
        data += 'TZNAME:CEST\n';
        data += 'DTSTART:19700329T020000\n';
        data += 'RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=-1SU\n';
        data += 'END:DAYLIGHT\n';
        data += 'BEGIN:STANDARD\n';
        data += 'TZOFFSETFROM:+0200\n';
        data += 'TZOFFSETTO:+0100\n';
        data += 'TZNAME:CET\n';
        data += 'DTSTART:19701025T030000\n';
        data += 'RRULE:FREQ=YEARLY;BYMONTH=10;BYDAY=-1SU\n';
        data += 'END:STANDARD\n';
        data += 'END:VTIMEZONE\n';

		data += 'BEGIN:VEVENT\n';
		data += 'DTSTART;VALUE=DATE:' + d1.getFullYear() + m1 + day1 + '\n';
		data += 'DTEND;VALUE=DATE:' + d2.getFullYear() + m2 + day2 + '\n';
		data += 'RRULE:FREQ=WEEKLY;BYDAY=SU,SA\n';
		data += 'DTSTAMP:20181010T062520Z\n';
		data += 'UID:2C340B07-5893-4234-B0E5-A5EE82858F01\n';
		data += 'CREATED:20181008T073122Z\n';
		data += 'DESCRIPTION:WE\n';
		data += 'LAST-MODIFIED:20181008T073122Z\n';
		data += 'LOCATION:\n';
		data += 'SEQUENCE:0\n';
		data += 'STATUS:CONFIRMED\n';
		data += 'SUMMARY:WE\n';
		data += 'TRANSP:TRANSPARENT\n';
		data += 'END:VEVENT\n';

        data += 'END:VCALENDAR';
        fs.writeFileSync(__dirname + '/data/recurring_fullday.ics', data);
    }
}

function parseDate(input) {
	  var parts = input.split('.');
	  var date = new Date(new Date().getFullYear(), parts[1]-1, parts[0]);
	  var today = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()).getTime();

	  if(date.getTime() < today) {
		  date = new Date(new Date().getFullYear() + 1, parts[1] - 1, parts[0]);
	  }

	  return date;
}

describe('Test ' + adapterShortNameLog + ' adapter', function() {
    before('Test ' + adapterShortNameLog + ' adapter: Start js-controller', function (_done) {
        this.timeout(600000); // because of first install from npm

        setupIcsFiles();

        setup.setupController(function () {
            var config = setup.getAdapterConfig();
            // enable adapter
            config.common.enabled  = true;
            config.common.loglevel = 'silly';

            config.native.fulltime = "";
            config.native.forceFullday = false;
            config.native.replaceDates = false;
            config.native.hideYear = true;
            config.native.daysPreview = 8;
            config.native.calendars[0] = {
                "name": "calendar1-recurring",
                "url": __dirname + '/data/recurring_fullday.ics',
                "user": "username",
                "pass": "password",
                "sslignore": "ignore",
                "color": "red"
            };

            config.native.events[0] = {
                "name": "Vacation",
                "enabled": true,
                "display": false
            };
            config.native.events[1] = {
                "name": "MyEvent",
                "enabled": true,
                "display": true
            };
            config.native.events[2] = {
                "name": "TestEvent",
                "enabled": true,
                "display": true
            };
            config.native.events[3] = {
                "name": "InDayEvent",
                "enabled": true,
                "display": false
            };

            setup.setAdapterConfig(config.common, config.native);

            setup.startController(true, function(id, obj) {}, function (id, state) {
                    if (onStateChanged) onStateChanged(id, state);
                },
                function (_objects, _states) {
                    objects = _objects;
                    states  = _states;
                    _done();
                });
        });
    });

    it('Test ' + adapterShortNameLog + ' adapter: Check if adapter started', function (done) {
        this.timeout(60000);
        checkConnectionOfAdapter(function (res) {
            if (res) console.log(res);
            expect(res).not.to.be.equal('Cannot check connection');
            objects.setObject('system.adapter.test.0', {
                    common: {

                    },
                    type: 'instance'
                },
                function () {
                    states.subscribeMessage('system.adapter.test.0');
                    done();
                });
        });
    });

    it('Test ' + adapterShortNameLog + ': check count of events', function (done) {
        this.timeout(5000);
        setTimeout(function () {
            states.getState('ical.0.data.count', function (err, state) {
            	var d1 = new Date();
            	var weekend = d1.getDay() == 0 || d1.getDay() == 6;
                expect(err).to.be.not.ok;
                expect(state.val).to.be.equal(weekend ? 1 : 0);
                done();
            });
        }, 3000);
    });

    it('Test ' + adapterShortNameLog + ': event Vacation', function (done) {
        this.timeout(5000);
        setTimeout(function () {
            states.getState('ical.0.events.Vacation', function (err, state) {
                expect(err).to.be.not.ok;
                expect(state.val).to.be.false;
                done();
            });
        }, 3000);
    });

    it('Test ' + adapterShortNameLog + ': event MyEvent', function (done) {
        this.timeout(5000);
        setTimeout(function () {
            states.getState('ical.0.events.MyEvent', function (err, state) {
                expect(err).to.be.not.ok;
                expect(state.val).to.be.false;
                done();
            });
        }, 3000);
    });

    it('Test ' + adapterShortNameLog + ': event TestEvent', function (done) {
        this.timeout(5000);
        setTimeout(function () {
            states.getState('ical.0.events.TestEvent', function (err, state) {
                expect(err).to.be.not.ok;
                expect(state.val).to.be.false;
                done();
            });
        }, 3000);
    });

    it('Test ' + adapterShortNameLog + ': event InDayEvent', function (done) {
        this.timeout(5000);
        setTimeout(function () {
            states.getState('ical.0.events.InDayEvent', function (err, state) {
                expect(err).to.be.not.ok;
                expect(state.val).to.be.false;
                done();
            });
        }, 3000);
    });

    it('Test ' + adapterShortNameLog + ': data.table', function (done) {
        this.timeout(2000);
        setTimeout(function () {
            states.getState('ical.0.data.table', function (err, state) {
                expect(err).to.be.not.ok;
                expect(state.val[0].date.indexOf('. 00:00')).to.be.equal(5);
                expect(state.val[0].event).to.be.equal('WE');
                expect(state.val[0]._section).to.be.equal('WE');
                expect(state.val[0]._allDay).to.be.true;

                expect(state.val[1].date.indexOf('. 00:00')).to.be.equal(5);
                expect(state.val[1].event).to.be.equal('WE');
                expect(state.val[1]._section).to.be.equal('WE');
                expect(state.val[1]._allDay).to.be.true;

                expect([
                	parseDate(state.val[0].date).getDay(),
                	parseDate(state.val[1].date).getDay()
                ]).to.be.an('array').that.includes(0, 6);

                done();
            });
        }, 1000);
    });

    after('Test ' + adapterShortNameLog + ' adapter: Stop js-controller', function (done) {
        this.timeout(10000);

        setup.stopController(function (normalTerminated) {
            console.log('Adapter normal terminated: ' + normalTerminated);
            done();
        });
    });
});
<|endoftext|>


<commit_before>var assert = require('nodeunit').assert;
var colors = require('colors');

var HexaAssertionError = function(message) {
	var err = new Error(message);

	err.name = 'HexaAssertionError';
	this.name = err.name;

	this.stack = err.stack;

	this.toString = function() {
		return this.name + ': ' + this.message;
	};
};

HexaAssertionError.prototype = Error.prototype;
HexaAssertionError.prototype.name = 'HexaAssertionError';

var equals = function(expected, actual) {
	try {
		assert.deepEqual(expected, actual);
	} catch (e) {
		var line = 0;
		var	lines = [];
		var cursor = 0;
		var out = '';

		while (cursor < expected.length || cursor < actual.length) {
			for (var a = 0; a < 16; a++) {
				if (cursor < expected.length && cursor < actual.length) {
					if (expected[cursor] != actual[cursor] && lines.indexOf(line) == -1) {
						lines.push(line);
					}
				}
				cursor += 1;
			}
			line += 1;
		}

		var exp = '';
		var act = '';
		for (line in lines) {
			exp = '\tExpected: ' + ('000' + line).slice(-5) + ': ';
			act = '\tActual  : ' + ('000' + line).slice(-5) + ': ';
			for (var b = 0; b < 16; b++) {
				cursor = (line * 16) + b;

				if (cursor < expected.length && cursor < actual.length) {
					if (expected[cursor] !== actual[cursor]) {
						exp += ('0' + expected[cursor]).toString(16).substr(-2).toUpperCase().green;
						act += ('0' + actual[cursor]).toString(16).substr(-2).toUpperCase().red;
					} else {
						exp += ('0' + expected[cursor]).toString(16).substr(-2).toUpperCase();
						act += ('0' + actual[cursor]).toString(16).substr(-2).toUpperCase();
					}
				}

				if (((b+1) % 2) === 0) {
                    exp += ' ';
                    act += ' ';
                }

			}
			out += '\n' + exp + '- ' + (line + 1);
			out += '\n' + act + '- ' + (line + 1);
		}
        throw new HexaAssertionError(out);
	}
	return true;
};

exports.equals = equals;
<commit_msg>improved hex-assert rate on codeclimate<commit_after>var assert = require('nodeunit').assert;
require('colors');

var HexaAssertionError = function(message) {
	var err = new Error(message);

	err.name = 'HexaAssertionError';
	this.name = err.name;

	this.stack = err.stack;

	this.toString = function() {
		return this.name + ': ' + this.message;
	};
};

HexaAssertionError.prototype = Error.prototype;
HexaAssertionError.prototype.name = 'HexaAssertionError';

var equals = function(expected, actual) {
	try {
		assert.deepEqual(expected, actual);
	} catch (e) {
		var line = 0;
		var	lines = [];
		var cursor = 0;
		var out = '';

		while (cursor < expected.length || cursor < actual.length) {
			for (var a = 0; a < 16; a++) {
				if (cursor < expected.length && cursor < actual.length) {
					if (expected[cursor] !== actual[cursor] && lines.indexOf(line) === -1) {
						lines.push(line);
					}
				}
				cursor += 1;
			}
			line += 1;
		}

		var exp = '';
		var act = '';
		for (line in lines) {
			exp = '\tExpected: ' + ('000' + line).slice(-5) + ': ';
			act = '\tActual  : ' + ('000' + line).slice(-5) + ': ';
			for (var b = 0; b < 16; b++) {
				cursor = (line * 16) + b;

				if (cursor < expected.length && cursor < actual.length) {
					if (expected[cursor] !== actual[cursor]) {
						exp += ('0' + expected[cursor]).toString(16).substr(-2).toUpperCase().green;
						act += ('0' + actual[cursor]).toString(16).substr(-2).toUpperCase().red;
					} else {
						exp += ('0' + expected[cursor]).toString(16).substr(-2).toUpperCase();
						act += ('0' + actual[cursor]).toString(16).substr(-2).toUpperCase();
					}
				}

				if (((b+1) % 2) === 0) {
                    exp += ' ';
                    act += ' ';
                }

			}
			out += '\n' + exp + '- ' + (line + 1);
			out += '\n' + act + '- ' + (line + 1);
		}
        throw new HexaAssertionError(out);
	}
	return true;
};

exports.equals = equals;
<|endoftext|>


<commit_before>'use strict';

var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');

var browserSync = require('browser-sync');
var browserSyncSpa = require('browser-sync-spa');

var util = require('util');

var proxyMiddleware = require('http-proxy-middleware');

function browserSyncInit(baseDir, browser) {
  browser = browser === undefined ? 'default' : browser;

  var routes = null;
  if(baseDir === conf.paths.src || (util.isArray(baseDir) && baseDir.indexOf(conf.paths.src) !== -1)) {
    routes = {
      '/bower_components': 'bower_components'
    };
  }

  var server = {
    baseDir: baseDir,
    routes: routes
  };

  /*
   * You can add a proxy to your backend by uncommenting the line below.
   * You just have to configure a context which will we redirected and the target url.
   * Example: $http.get('/users') requests will be automatically proxified.
   *
   * For more details and option, https://github.com/chimurai/http-proxy-middleware/blob/v0.9.0/README.md
   */
  // server.middleware = proxyMiddleware('/users', {target: 'http://jsonplaceholder.typicode.com', changeOrigin: true});

  browserSync.instance = browserSync.init({
    startPath: '/',
    server: server,
    browser: browser
  });
}

browserSync.use(browserSyncSpa({
  selector: '[ng-app]'// Only needed for angular apps
}));

gulp.task('serve', ['watch'], function () {
  browserSyncInit([path.join(conf.paths.tmp, '/serve'), conf.paths.src]);
});

gulp.task('serve:dist', ['build'], function () {
  browserSyncInit(conf.paths.dist);
});

gulp.task('serve:e2e', ['inject'], function () {
  browserSyncInit([conf.paths.tmp + '/serve', conf.paths.src], []);
});

gulp.task('serve:e2e-dist', ['build'], function () {
  browserSyncInit(conf.paths.dist, []);
});
<commit_msg>don't show browsersync notifications<commit_after>'use strict';

var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');

var browserSync = require('browser-sync');
var browserSyncSpa = require('browser-sync-spa');

var util = require('util');

var proxyMiddleware = require('http-proxy-middleware');

function browserSyncInit(baseDir, browser) {
  browser = browser === undefined ? 'default' : browser;

  var routes = null;
  if(baseDir === conf.paths.src || (util.isArray(baseDir) && baseDir.indexOf(conf.paths.src) !== -1)) {
    routes = {
      '/bower_components': 'bower_components'
    };
  }

  var server = {
    baseDir: baseDir,
    routes: routes
  };

  /*
   * You can add a proxy to your backend by uncommenting the line below.
   * You just have to configure a context which will we redirected and the target url.
   * Example: $http.get('/users') requests will be automatically proxified.
   *
   * For more details and option, https://github.com/chimurai/http-proxy-middleware/blob/v0.9.0/README.md
   */
  // server.middleware = proxyMiddleware('/users', {target: 'http://jsonplaceholder.typicode.com', changeOrigin: true});

  browserSync.instance = browserSync.init({
    startPath: '/',
    server: server,
    browser: browser,
    notify: false
  });
}

browserSync.use(browserSyncSpa({
  selector: '[ng-app]'// Only needed for angular apps
}));

gulp.task('serve', ['watch'], function () {
  browserSyncInit([path.join(conf.paths.tmp, '/serve'), conf.paths.src]);
});

gulp.task('serve:dist', ['build'], function () {
  browserSyncInit(conf.paths.dist);
});

gulp.task('serve:e2e', ['inject'], function () {
  browserSyncInit([conf.paths.tmp + '/serve', conf.paths.src], []);
});

gulp.task('serve:e2e-dist', ['build'], function () {
  browserSyncInit(conf.paths.dist, []);
});
<|endoftext|>


<commit_before>$(document).ready(function(){
  $('.progress').progress();

  $('#specialty_dropdown').dropdown();
});

var marks = $.extend(true, {}, classes);;

function save(){
  var specialty = $('#specialty_value').val();
  var profile = $('#profile_value').val();
  var term = $('#term').text();

  marks[specialty][profile][term][0] = Number($('#class-1-value').val() || "0");
  marks[specialty][profile][term][1] = Number($('#class-2-value').val() || "0");
  marks[specialty][profile][term][2] = Number($('#class-3-value').val() || "0");
  marks[specialty][profile][term][3] = Number($('#class-4-value').val() || "0");
  marks[specialty][profile][term][4] = Number($('#class-5-value').val() || "0");

  updateProgress();
}

function updateProgress(){
  var value = 0;
  for(var key in marks){
    for(var keey in marks[key]){
      for(var i = 1; i < 8; i++){
        for(var j = 0;j < marks[key][keey][i].length; j++){
          if(typeof marks[key][keey][i][j] != 'number') continue;

          switch (j) {
            case 0:
              value += (marks[key][keey][i][j] - 2) * 2;
              break;
            case 1:
              value += (marks[key][keey][i][j] - 2) * 2;
              break;
            case 2:
              value += marks[key][keey][i][j] - 2;
              break;
            case 3:
              value += marks[key][keey][i][j] - 2;
              break;
            case 4:
              value += (marks[key][keey][i][j] - 2) / 2;
              break;
          }
        }
      }
    }
  }

  $('.progress').progress({ value : value });

  if(value >= 66){
    unlock(6, false);
    unlock(5, false);
    unlock(4, false);
    unlock(3, false);
    unlock(2, false);
    unlock(1, false);
  } else if(value >= 58){
    unlock(6, true);
    unlock(5, false);
    unlock(4, false);
    unlock(3, false);
    unlock(2, false);
    unlock(1, false);
  } else if(value >= 46){
    unlock(6, true);
    unlock(5, true);
    unlock(4, false);
    unlock(3, false);
    unlock(2, false);
    unlock(1, false);
  } else if(value >= 32){
    unlock(6, true);
    unlock(5, true);
    unlock(4, true);
    unlock(3, false);
    unlock(2, false);
    unlock(1, false);
  } else if(value >= 16){
    unlock(6, true);
    unlock(5, true);
    unlock(4, true);
    unlock(3, true);
    unlock(2, false);
    unlock(1, false);
  } else {
    unlock(6, true);
    unlock(5, true);
    unlock(4, true);
    unlock(3, true);
    unlock(2, true);
    unlock(1, true);
  }
}

function unlock(term, lock){
  $('#term-'+term+'-lock').removeClass('lock');
  $('#term-'+term+'-lock').removeClass('unlock');

  if(lock){
    $('#term-'+term+'-lock').addClass('lock');
  } else {
    $('#term-'+term+'-lock').addClass('unlock');
  }
}

function openModal(term){
  var Term = classes[$('#specialty_value').val()][$('#profile_value').val()][term];
  var TermMarks = marks[$('#specialty_value').val()][$('#profile_value').val()][term];

  $('#term').text(term);

  $('#class-1').text(Term[0]);
  $('#class-2').text(Term[1]);
  $('#class-3').text(Term[2]);
  $('#class-4').text(Term[3]);
  $('#class-5').text(Term[4]);

  $('#class-1-dropdown').dropdown();
  $('#class-2-dropdown').dropdown();
  $('#class-3-dropdown').dropdown();
  $('#class-4-dropdown').dropdown();
  $('#class-5-dropdown').dropdown();

  for(var i = 0; i < TermMarks.length; i++){
    if(typeof TermMarks[i] != 'number'){
      $('#class-'+(i+1)+'-dropdown').dropdown('clear');
      continue;
    }

    $('#class-'+(i+1)+'-dropdown [data-value="'+TermMarks[i]+'"]').click();
  }

  $('#score').modal('show');
}

function selectSpecialty(name){
  var specialty = classes[name];
  var profiles = Object.keys(specialty);

  for(var i = 0; i < profiles.length; i++){
    var model = '
'+profiles[i]+'
';

    $('#profile_select').append(model);
  }

  $('#profile_dropdown').dropdown();
}

function selectProfile(name){
  $('#achievements').show();
}
<commit_msg>Added save function<commit_after>$(document).ready(function(){
  $('.progress').progress();

  $('#specialty_dropdown').dropdown();

  loadSelected();
});

var marks = $.extend(true, {}, classes);

function saveSelected(){
  localStorage.setItem('specialty',$('#specialty_value').val());
  localStorage.setItem('profile',$('#profile_value').val());
}

function loadSelected(){
  if(!localStorage.getItem("profile")) return;

  $('[onclick="selectSpecialty('+localStorage.getItem("specialty")+')"]').click();

  $('[onclick="selectProfile(\''+localStorage.getItem("profile")+'\')"]').click();
}

function save(){
  var specialty = $('#specialty_value').val();
  var profile = $('#profile_value').val();
  var term = $('#term').text();

  marks[specialty][profile][term][0] = Number($('#class-1-value').val() || "0");
  marks[specialty][profile][term][1] = Number($('#class-2-value').val() || "0");
  marks[specialty][profile][term][2] = Number($('#class-3-value').val() || "0");
  marks[specialty][profile][term][3] = Number($('#class-4-value').val() || "0");
  marks[specialty][profile][term][4] = Number($('#class-5-value').val() || "0");

  updateProgress();
}

function updateProgress(){
  var value = 0;
  for(var key in marks){
    for(var keey in marks[key]){
      for(var i = 1; i < 8; i++){
        for(var j = 0;j < marks[key][keey][i].length; j++){
          if(typeof marks[key][keey][i][j] != 'number') continue;

          switch (j) {
            case 0:
              value += (marks[key][keey][i][j] - 2) * 2;
              break;
            case 1:
              value += (marks[key][keey][i][j] - 2) * 2;
              break;
            case 2:
              value += marks[key][keey][i][j] - 2;
              break;
            case 3:
              value += marks[key][keey][i][j] - 2;
              break;
            case 4:
              value += (marks[key][keey][i][j] - 2) / 2;
              break;
          }
        }
      }
    }
  }

  $('.progress').progress({ value : value });

  if(value >= 66){
    unlock(6, false);
    unlock(5, false);
    unlock(4, false);
    unlock(3, false);
    unlock(2, false);
    unlock(1, false);
  } else if(value >= 58){
    unlock(6, true);
    unlock(5, false);
    unlock(4, false);
    unlock(3, false);
    unlock(2, false);
    unlock(1, false);
  } else if(value >= 46){
    unlock(6, true);
    unlock(5, true);
    unlock(4, false);
    unlock(3, false);
    unlock(2, false);
    unlock(1, false);
  } else if(value >= 32){
    unlock(6, true);
    unlock(5, true);
    unlock(4, true);
    unlock(3, false);
    unlock(2, false);
    unlock(1, false);
  } else if(value >= 16){
    unlock(6, true);
    unlock(5, true);
    unlock(4, true);
    unlock(3, true);
    unlock(2, false);
    unlock(1, false);
  } else {
    unlock(6, true);
    unlock(5, true);
    unlock(4, true);
    unlock(3, true);
    unlock(2, true);
    unlock(1, true);
  }
}

function unlock(term, lock){
  $('#term-'+term+'-lock').removeClass('lock');
  $('#term-'+term+'-lock').removeClass('unlock');

  if(lock){
    $('#term-'+term+'-lock').addClass('lock');
  } else {
    $('#term-'+term+'-lock').addClass('unlock');
  }
}

function openModal(term){
  var Term = classes[$('#specialty_value').val()][$('#profile_value').val()][term];
  var TermMarks = marks[$('#specialty_value').val()][$('#profile_value').val()][term];

  $('#term').text(term);

  $('#class-1').text(Term[0]);
  $('#class-2').text(Term[1]);
  $('#class-3').text(Term[2]);
  $('#class-4').text(Term[3]);
  $('#class-5').text(Term[4]);

  $('#class-1-dropdown').dropdown();
  $('#class-2-dropdown').dropdown();
  $('#class-3-dropdown').dropdown();
  $('#class-4-dropdown').dropdown();
  $('#class-5-dropdown').dropdown();

  for(var i = 0; i < TermMarks.length; i++){
    if(typeof TermMarks[i] != 'number'){
      $('#class-'+(i+1)+'-dropdown').dropdown('clear');
      continue;
    }

    $('#class-'+(i+1)+'-dropdown [data-value="'+TermMarks[i]+'"]').click();
  }

  $('#score').modal('show');
}

function selectSpecialty(name){
  var specialty = classes[name];
  var profiles = Object.keys(specialty);

  for(var i = 0; i < profiles.length; i++){
    var model = '
'+profiles[i]+'
';

    $('#profile_select').append(model);
  }

  $('#profile_dropdown').dropdown();
}

function selectProfile(name){
  $('#achievements').show();

  saveSelected();
}
<|endoftext|>


<commit_before>/*global dom */
/**
 * Get an element's parent in the composed tree
 * @param   DOMNode   Element
 * @return  DOMNode   Parent element
 */
dom.getComposedParent = function getComposedParent (element)  {
  if (element.assignedSlot) {
    // NOTE: If the display of a slot element isn't 'contents',
    // the slot shouldn't be ignored. Chrome does not support this (yet) so,
    // we'll skip this part for now.
    return getComposedParent(element.assignedSlot); // content of a shadow DOM slot
  } else if (element.parentNode) {
    var parentNode = element.parentNode;
    if (parentNode.nodeType === 1) {
      return parentNode; // Regular node
    } else if (parentNode.host) {
      return parentNode.host; // Shadow root
    }
  }
  return null; // Root node
};
<commit_msg>fix: getComposedParent should not return slot nodes (#438)<commit_after>/*global dom */
/**
 * Get an element's parent in the composed tree
 * @param   DOMNode   Element
 * @return  DOMNode   Parent element
 */
dom.getComposedParent = function getComposedParent (element)  {
  if (element.assignedSlot) {
    // NOTE: If the display of a slot element isn't 'contents',
    // the slot shouldn't be ignored. Chrome does not support this (yet) so,
    // we'll skip this part for now.
    return getComposedParent(element.assignedSlot); // parent of a shadow DOM slot
  } else if (element.parentNode) {
    var parentNode = element.parentNode;
    if (parentNode.nodeType === 1) {
      return parentNode; // Regular node
    } else if (parentNode.host) {
      return parentNode.host; // Shadow root
    }
  }
  return null; // Root node
};
<|endoftext|>


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

module.exports = function(field, search) {
  var value = [];
  search.forEach(function(chunk) {
    if (util.isRegExp(search)) value.push(search);
    else value.push(new RegExp(search, 'i'));
  });
  return value.length == 0 ? undefined : { $in: value };
}
<commit_msg>string handler update<commit_after>var util = require('util');

module.exports = function(field, search) {
  var value = [];
  search.forEach(function(chunk) {
    if (util.isRegExp(search)) value.push(chunk);
    else value.push(new RegExp(chunk, 'i'));
  });
  return value.length == 0 ? undefined : { $in: value };
}
<|endoftext|>


<commit_before>/*
 * grunt-version-file
 * https://github.com/cfogelberg/grunt-version-file
 *
 * Copyright (c) 2014 Christo Fogelberg
 * Licensed under the MIT license.
 */
// Allow indirectly-executed (should-executed) function literals to pass jshint IIFE warning:
/*jshint -W068 */
// Allow expressions (...should.be.a.Foo;)
/*jshint -W030 */

 "use strict";

describe("GeneratorManager", function() {
  var GeneratorManager = require("../../lib/generator_manager");

  it("requires an options.generator_dir constructor argument", function() {
    (function() {
      var config_without_generator_dir = { generator_list: ["foo", "bar"] };
      var gm = new GeneratorManager(config_without_generator_dir);
    }).should.throw();
  });

  it("throws an error when options.generator_dir is not a string", function() {
    (function() {
      var config_without_generator_dir_string = { generator_list: ["foo", "bar"], generator_dir: 1 };
      var gm = new GeneratorManager(config_without_generator_dir_string);
    }).should.throw();
  });

  it.skip("throws an error when options.generator_dir does not exist", function() {
  });

  it("requires an options.generator_list constructor argument", function() {
  it("requires an options.generator_dir constructor argument", function() {
    (function() {
      var config_without_generator_list = { generator_dir: "foo" };
      var gm = new GeneratorManager(config_without_generator_list);
    }).should.throw();
  });
  });

  it("throws an error when options.generator_list is not an array", function() {
    (function() {
      var config_without_generator_list_array = { generator_dir: "foo", generator_list: "foo" };
      var gm = new GeneratorManager(config_without_generator_list_array);
    }).should.throw();
  });

  it.skip("builds a generator for each entry in options.generator_dir", function() {
  });

  it.skip("throws an error when a gen. list member is not in generator_dir", function() {
  });

  it("throws an error when any unexpected options fields are defined", function() {
    (function() {
      var config_with_extra_entry = { generator_dir: "foo", generator_list: ["bar", "baz"], extra: 1234 };
      var gm = new GeneratorManager(config_with_extra_entry);
    }).should.throw();
  });

  it.skip("allows iteration over all generators", function() {
  });
});
<commit_msg>GeneratorManager test impl<commit_after>/*
 * grunt-version-file
 * https://github.com/cfogelberg/grunt-version-file
 *
 * Copyright (c) 2014 Christo Fogelberg
 * Licensed under the MIT license.
 */
// Allow indirectly-executed (should-executed) function literals to pass jshint IIFE warning:
/*jshint -W068 */
// Allow expressions (...should.be.a.Foo;)
/*jshint -W030 */

"use strict";

describe("GeneratorManager", function() {
  var GeneratorManager = require("../../lib/generator_manager");

  var GENERATOR_DIR_VALID = "generators";
  var GENERATOR_LIST_VALID = ["datestring", "npm_version"];

  var CONFIG_VALID = {
    generator_dir: GENERATOR_DIR_VALID,
    generator_list: GENERATOR_LIST_VALID
  };

  it("requires an options.generator_dir constructor argument", function() {
    (function() {
      var gm = new GeneratorManager({
        generator_list: GENERATOR_LIST_VALID
      });
    }).should.throw();
  });

  it("throws an error when options.generator_dir is not a string", function() {
    (function() {
      var gm = new GeneratorManager({
        generator_list: GENERATOR_LIST_VALID,
        generator_dir: 1
      });
    }).should.throw();
  });

  it("throws an error when options.generator_dir does not exist", function() {
    (function() {
      var gm = new GeneratorManager({
        generator_list: GENERATOR_LIST_VALID,
        generator_dir: "does-not-exist"
      });
    }).should.throw();
  });

  it("requires an options.generator_list constructor argument", function() {
    (function() {
      var gm = new GeneratorManager({
        generator_dir: GENERATOR_DIR_VALID
      });
    }).should.throw();
  });

  it("throws an error when options.generator_list is not an array", function() {
    (function() {
      var gm = new GeneratorManager({
        generator_dir: GENERATOR_DIR_VALID,
        generator_list: "datestring"
      });
    }).should.throw();
  });

  it("throws an error when options.generator_list contains duplicates", function() {
    (function() {
      var gm = new GeneratorManager({
        generator_dir: GENERATOR_DIR_VALID,
        generator_list: GENERATOR_LIST_VALID.concat(GENERATOR_LIST_VALID)
      });
    }).should.throw();
  });

  it("throws an error when options.generator_list is empty", function() {
    (function() {
      var gm = new GeneratorManager({
        generator_dir: GENERATOR_DIR_VALID,
        generator_list: []
      });
    }).should.throw();
  });

  it("returns the correct generator_map", function() {
    var gm = new GeneratorManager(CONFIG_VALID);
    var map = gm.generator_map();
    var expected_length = GENERATOR_LIST_VALID.length;
    Object.keys(map).length.should.equal.expected_length;
    for(var i in GENERATOR_LIST_VALID) {
      var gen = GENERATOR_LIST_VALID[i];
      map[gen].should.not.equal.undefined;
    }
  });

  it("throws an error when a gen. list member is not in generator_dir", function() {
    (function() {
      var gm = new GeneratorManager({
        generator_dir: GENERATOR_DIR_VALID,
        generator_list: ["not_valid_generator"]
      });
    }).should.throw();
  });

  it("throws an error when any unexpected options fields are defined", function() {
    (function() {
      var gm = new GeneratorManager({
        generator_dir: GENERATOR_DIR_VALID,
        generator_list: GENERATOR_LIST_VALID,
        extra: 1234
      });
    }).should.throw();
  });

  it.skip("allows iteration over all generators", function() {
    var gm = new GeneratorManager(CONFIG_VALID);
  });
});
<|endoftext|>