<commit_before>'use strict';

var gulp = require('gulp'),
  jshint = require('gulp-jshint'),
  prettify = require('gulp-jsbeautifier'),
  mocha = require('gulp-mocha'),
  istanbul = require('gulp-istanbul'),
  changed = require('gulp-changed'),
  cache = require('gulp-cached'),
  browserify = require('gulp-browserify'),
  less = require('gulp-less'),
  config = require('./src/shared/config.js'),
  concat = require('gulp-concat');

var isWatching = false;

var paths = {
  scripts: [
    'gulpfile.js',
    'src/app.js',
    'src/server.js',
    'tests/*.js',
    'src/**/*.js'
  ],
  tests: [
    'tests/utils.test.js',
    'tests/controlValidation.test.js',
    'tests/initApi.test.js',
    'tests/userApi.test.js',
    'tests/projectApi.test.js',
    'tests/deviceApi.test.js',
    'tests/profileApi.test.js'
  ],
  browserifySrc: [
    'src/client/authModule.js',
    'src/client/dashboardModule.js'
  ],
  browserifyDest: 'public/js/',
  lessSrc: [
    'public/less/kube.less',
    'public/less/auth.less',
    'public/less/dashboard.less'
  ]
};

gulp.task('less', function () {
  return gulp.src(paths.lessSrc, { base: './' })
    .pipe(less())
    .pipe(gulp.dest('./public/css'));
});

gulp.task('browserify', function() {
    var debug = config.code_generation.browserify.debug;
    return gulp.src(paths.browserifySrc)
        .pipe(browserify({
          insertGlobals : true,
          debug : debug
        }))
        .pipe(concat('bundle.js'))
        .pipe(gulp.dest(paths.browserifyDest));
});

gulp.task('jshint', function () {
  return gulp.src(paths.scripts, {
      base: './'
    })
    .pipe(cache('syntax-check'))
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter('jshint-stylish'))
    .pipe(jshint.reporter('fail'));
});

gulp.task('prettify', function () {
  return gulp.src(paths.scripts, {
      base: './'
    })
    .pipe(cache('format-js'))
    .pipe(prettify({
      config: '.jsbeautifyrc',
      mode: 'VERIFY_AND_WRITE'
    }))
    .pipe(gulp.dest('./'));
});

gulp.task('test', function () {
  return gulp.src(paths.tests, {
      read: false
    })
    .pipe(mocha({
      reporter: 'spec',
      bail: true,
      colors: true,
      timeout: 30000
    }));

});

gulp.task('watch', function () {
  isWatching = true;
  gulp.watch(paths.scripts, ['jshint']);
});

gulp.task('default', ['jshint', 'prettify', 'browserify', ]);

// Hack to stop gulp from hanging after mocha test
// Follow:
// https://github.com/gulpjs/gulp/issues/167
// https://github.com/sindresorhus/gulp-mocha/issues/1
// https://github.com/sindresorhus/gulp-mocha/issues/54
gulp.on('stop', function () {
  if (!isWatching) {
    process.nextTick(function () {
      process.exit(0);
    });
  }
});
<commit_msg>Gulp now has the same functionality as grunt used to.<commit_after>'use strict';

var gulp = require('gulp'),
  jshint = require('gulp-jshint'),
  prettify = require('gulp-jsbeautifier'),
  mocha = require('gulp-mocha'),
  istanbul = require('gulp-istanbul'),
  changed = require('gulp-changed'),
  cache = require('gulp-cached'),
  browserify = require('gulp-browserify'),
  less = require('gulp-less'),
  config = require('./src/shared/config.js'),
  concat = require('gulp-concat');

var isWatching = false;

var paths = {
  scripts: [
    'gulpfile.js',
    'src/app.js',
    'src/server.js',
    'tests/*.js',
    'src/**/*.js'
  ],
  tests: [
    'tests/utils.test.js',
    'tests/controlValidation.test.js',
    'tests/initApi.test.js',
    'tests/userApi.test.js',
    'tests/projectApi.test.js',
    'tests/deviceApi.test.js',
    'tests/profileApi.test.js'
  ],
  browserifySrc: [
    'src/client/authModule.js',
    'src/client/dashboardModule.js'
  ],
  browserifyDest: 'public/js/',
  lessDir: 'public/less/**/*.less',
  lessSrc: [
    'public/less/kube.less',
    'public/less/auth.less',
    'public/less/dashboard.less'
  ]
};

gulp.task('less', function () {
  return gulp.src(paths.lessSrc, { base: './' })
    .pipe(cache('less'))
    .pipe(less())
    .pipe(gulp.dest('./public/css'));
});

gulp.task('browserify', function() {
    var debug = config.code_generation.browserify.debug;
    return gulp.src(paths.browserifySrc)
        .pipe(cache('browserify'))
        .pipe(browserify({
          insertGlobals : true,
          debug : debug
        }))
        .pipe(concat('bundle.js'))
        .pipe(gulp.dest(paths.browserifyDest));
});

gulp.task('jshint', function () {
  return gulp.src(paths.scripts, {
      base: './'
    })
    .pipe(cache('syntax-check'))
    .pipe(jshint('.jshintrc'))
    .pipe(jshint.reporter('jshint-stylish'))
    .pipe(jshint.reporter('fail'));
});

gulp.task('prettify', function () {
  return gulp.src(paths.scripts, {
      base: './'
    })
    .pipe(prettify({
      config: '.jsbeautifyrc',
      mode: 'VERIFY_AND_WRITE'
    }))
    .pipe(gulp.dest('./'));
});

gulp.task('test', function () {
  return gulp.src(paths.tests, {
      read: false
    })
    .pipe(mocha({
      reporter: 'spec',
      bail: true,
      colors: true,
      timeout: 30000
    }));

});

gulp.task('watch', function () {
  isWatching = true;
  gulp.watch(paths.scripts, ['jshint', 'browserify']);
  gulp.watch(paths.lessDir, ['less']);
});

gulp.task('compile', ['jshint', 'browserify', 'less' ]);

gulp.task('default', ['jshint', 'prettify', 'browserify', 'less', 'test' ]);

// Hack to stop gulp from hanging after mocha test
// Follow:
// https://github.com/gulpjs/gulp/issues/167
// https://github.com/sindresorhus/gulp-mocha/issues/1
// https://github.com/sindresorhus/gulp-mocha/issues/54
gulp.on('stop', function () {
  if (!isWatching) {
    process.nextTick(function () {
      process.exit(0);
    });
  }
});
<|endoftext|>


<commit_before>// PLUGIN: Mustache

(function (Popcorn) {

  /**
   * Mustache Popcorn Plug-in
   *
   * Adds the ability to render JSON using templates via the Mustache templating library.
   *
   * @param {Object} options
   *
   * Required parameters: start, end, template, data, and target.
   * Optional parameter: static.
   *
   *   start: the time in seconds when the mustache template should be rendered
   *          in the target div.
   *
   *   end: the time in seconds when the rendered mustache template should be
   *        removed from the target div.
   *
   *   target: a String -- the target div's id.
   *
   *   template: the mustache template for the plugin to use when rendering.  This can be
   *             a String containing the template, or a Function that returns the template's
   *             String.
   *
   *   data: the data to be rendered using the mustache template.  This can be a JSON String,
   *         a JavaScript Object literal, or a Function returning a String or Literal.
   *
   *   dynamic: an optional argument indicating that the template and json data are dynamic
   *            and need to be loaded dynamically on every use.  Defaults to True.
   *
   * Example:
     var p = Popcorn('#video')

        // Example using template and JSON strings.
        .mustache({
          start: 5, // seconds
          end:  15,  // seconds
          target: 'mustache',
          template: '
{{header}}
'                         +
                    '{{#bug}}'                                    +
                    '{{/bug}}'                                    +
                    ''                                            +
                    '{{#items}}'                                  +
                    '  {{#first}}'                                +
                    '
{{name}}
'      +
                    '  {{/first}}'                                +
                    '  {{#link}}'                                 +
                    '
{{name}}
' +
                    '  {{/link}}'                                 +
                    '{{/items}}'                                  +
                    ''                                            +
                    '{{#empty}}'                                  +
                    '
The list is empty.
'                 +
                    '{{/empty}}'                                  ,

          data:     '{'                                                        +
                    '  "header": "Colors", '                                   +
                    '  "items": [ '                                            +
                    '      {"name": "red", "first": true, "url": "#Red"}, '    +
                    '      {"name": "green", "link": true, "url": "#Green"}, ' +
                    '      {"name": "blue", "link": true, "url": "#Blue"} '    +
                    '  ],'                                                     +
                    '  'empty': false'                                         +
                    '}',
          dynamic: false // The json is not going to change, load it early.
        } )

        // Example showing Functions instead of Strings.
        .mustache({
          start: 20,  // seconds
          end:   25,  // seconds
          target: 'mustache',
          template: function(instance, options) {
                      var template = // load your template file here...
                      return template;
                    },
          data:     function(instance, options) {
                      var json = // load your json here...
                      return json;
                    }
        } );
  *
  */

  Popcorn.plugin( 'mustache' , function( options ) {

    var getData, data, getTemplate, template, loaded = false;

    Popcorn.getScript('https://github.com/janl/mustache.js/raw/master/mustache.js', function() {
      loaded = true;
    });

    var shouldReload = !!options.dynamic,
        typeOfTemplate = typeof options.template,
        typeOfData = typeof options.data;

    if ( typeOfTemplate === 'function' ) {
      if ( !shouldReload ) {
        template = options.template( options );
      } else {
        getTemplate = options.template;
      }
    } else if ( typeOfTemplate === 'string' ) {
      template = options.template;
    } else {
      throw 'Mustache Plugin Error: options.template must be a String or a Function.';
    }

    if ( typeOfData === 'function' ) {
      if ( !shouldReload ) {
        data = options.data(options);
      } else {
        getData = options.data;
      }
    } else if ( typeOfData === 'string' ) {
      data = JSON.parse( options.data );
    } else if ( typeOfData === 'object' ) {
      data = options.data;
    } else {
      throw 'Mustache Plugin Error: options.data must be a String, Object, or Function.';
    }

    return {
      start: function( event, options ) {

        var interval = window.setInterval( function() {

          if( loaded ) {

            window.clearInterval( interval );

            // if dynamic, freshen json data on every call to start, just in case.
            if ( getData ) {
              data = getData( options );
            }

            if ( getTemplate ) {
              template = getTemplate( options );
            }

            var html = Mustache.to_html( template,
                                         data
                                       ).replace( /^\s*/mg, '' );
            document.getElementById( options.target ).innerHTML = html;
          }
        }, 10 );
      },

      end: function( event, options ) {
        document.getElementById( options.target ).innerHTML = '';
      },
      _teardown: function( options ) {
        getData = data = getTemplate = template = null;
      }
    };
  },
  {
    about: {
      name: 'Popcorn Mustache Plugin',
      version: '0.1',
      author: 'David Humphrey (@humphd)',
      website: 'http://vocamus.net/dave'
    },
    options: {
      start: {elem:'input', type:'text', label:'In'},
      end: {elem:'input', type:'text', label:'Out'},
      target: 'mustache-container',
      template: {elem:'input', type:'text', label:'Template'},
      data: {elem:'input', type:'text', label:'Data'},
      /* TODO: how to show a checkbox/boolean? */
      dynamic: {elem:'input', type:'text', label:'Dynamic'}
    }
  });
})( Popcorn );
<commit_msg>[#469] Fixed error throwing to use Popcorn.error and also switched to using setTimeout instead of setInterval as per requested<commit_after>// PLUGIN: Mustache

(function (Popcorn) {

  /**
   * Mustache Popcorn Plug-in
   *
   * Adds the ability to render JSON using templates via the Mustache templating library.
   *
   * @param {Object} options
   *
   * Required parameters: start, end, template, data, and target.
   * Optional parameter: static.
   *
   *   start: the time in seconds when the mustache template should be rendered
   *          in the target div.
   *
   *   end: the time in seconds when the rendered mustache template should be
   *        removed from the target div.
   *
   *   target: a String -- the target div's id.
   *
   *   template: the mustache template for the plugin to use when rendering.  This can be
   *             a String containing the template, or a Function that returns the template's
   *             String.
   *
   *   data: the data to be rendered using the mustache template.  This can be a JSON String,
   *         a JavaScript Object literal, or a Function returning a String or Literal.
   *
   *   dynamic: an optional argument indicating that the template and json data are dynamic
   *            and need to be loaded dynamically on every use.  Defaults to True.
   *
   * Example:
     var p = Popcorn('#video')

        // Example using template and JSON strings.
        .mustache({
          start: 5, // seconds
          end:  15,  // seconds
          target: 'mustache',
          template: '
{{header}}
'                         +
                    '{{#bug}}'                                    +
                    '{{/bug}}'                                    +
                    ''                                            +
                    '{{#items}}'                                  +
                    '  {{#first}}'                                +
                    '
{{name}}
'      +
                    '  {{/first}}'                                +
                    '  {{#link}}'                                 +
                    '
{{name}}
' +
                    '  {{/link}}'                                 +
                    '{{/items}}'                                  +
                    ''                                            +
                    '{{#empty}}'                                  +
                    '
The list is empty.
'                 +
                    '{{/empty}}'                                  ,

          data:     '{'                                                        +
                    '  "header": "Colors", '                                   +
                    '  "items": [ '                                            +
                    '      {"name": "red", "first": true, "url": "#Red"}, '    +
                    '      {"name": "green", "link": true, "url": "#Green"}, ' +
                    '      {"name": "blue", "link": true, "url": "#Blue"} '    +
                    '  ],'                                                     +
                    '  'empty': false'                                         +
                    '}',
          dynamic: false // The json is not going to change, load it early.
        } )

        // Example showing Functions instead of Strings.
        .mustache({
          start: 20,  // seconds
          end:   25,  // seconds
          target: 'mustache',
          template: function(instance, options) {
                      var template = // load your template file here...
                      return template;
                    },
          data:     function(instance, options) {
                      var json = // load your json here...
                      return json;
                    }
        } );
  *
  */

  Popcorn.plugin( 'mustache' , function( options ) {

    var getData, data, getTemplate, template, loaded = false;

    Popcorn.getScript('https://github.com/janl/mustache.js/raw/master/mustache.js', function() {
      loaded = true;
    });

    var shouldReload = !!options.dynamic,
        typeOfTemplate = typeof options.template,
        typeOfData = typeof options.data;

    if ( typeOfTemplate === 'function' ) {
      if ( !shouldReload ) {
        template = options.template( options );
      } else {
        getTemplate = options.template;
      }
    } else if ( typeOfTemplate === 'string' ) {
      template = options.template;
    } else {
      Popcorn.error( 'Mustache Plugin Error: options.template must be a String or a Function.' );
    }

    if ( typeOfData === 'function' ) {
      if ( !shouldReload ) {
        data = options.data(options);
      } else {
        getData = options.data;
      }
    } else if ( typeOfData === 'string' ) {
      data = JSON.parse( options.data );
    } else if ( typeOfData === 'object' ) {
      data = options.data;
    } else {
      Popcorn.error( 'Mustache Plugin Error: options.data must be a String, Object, or Function.' );
    }

    return {
      start: function( event, options ) {

        var interval = function() {

          if( !loaded ) {
            setTimeout( function() {
              interval();
            }, 10 );
          } else {

            // if dynamic, freshen json data on every call to start, just in case.
            if ( getData ) {
              data = getData( options );
            }

            if ( getTemplate ) {
              template = getTemplate( options );
            }

            var html = Mustache.to_html( template,
                                         data
                                       ).replace( /^\s*/mg, '' );
            document.getElementById( options.target ).innerHTML = html;
          }
        }

        interval();

      },

      end: function( event, options ) {
        document.getElementById( options.target ).innerHTML = '';
      },
      _teardown: function( options ) {
        getData = data = getTemplate = template = null;
      }
    };
  },
  {
    about: {
      name: 'Popcorn Mustache Plugin',
      version: '0.1',
      author: 'David Humphrey (@humphd)',
      website: 'http://vocamus.net/dave'
    },
    options: {
      start: {elem:'input', type:'text', label:'In'},
      end: {elem:'input', type:'text', label:'Out'},
      target: 'mustache-container',
      template: {elem:'input', type:'text', label:'Template'},
      data: {elem:'input', type:'text', label:'Data'},
      /* TODO: how to show a checkbox/boolean? */
      dynamic: {elem:'input', type:'text', label:'Dynamic'}
    }
  });
})( Popcorn );
<|endoftext|>


<commit_before>var gulp = require('gulp');
var path = require('path');
var babel = require('gulp-babel');
var gutil = require("gulp-util");
var webpack = require("webpack");
var webpackConfigBase = require('./webpack.config-base.js');
var del = require('del');
var objectAssign = require('object-assign')
// var eslint = require('gulp-eslint');

// CONSTANTS =======================================================================
var LIB_ENTRY = './src/lib/index.js';
var LIB_OUTPUT_PATH = path.join(__dirname, 'lib');
var LIB_NAME = 'MaterialDesignReact';
var LIB_TARGET = 'umd';

var EXAMPLES_ENTRY = './src/examples/main.js';
var EXAMPLES_OUTPUT_PATH = path.join(__dirname, 'examples');

// TASKS ======================================================================
gulp.task('default', ['build-package', 'build-modules', 'build-examples']);

gulp.task('clean', function(cb) {
  del(['./examples', './lib'], cb);
});

gulp.task('build-modules', function () {
    return gulp.src('src/lib/**/!(index).js?')
        // .pipe(eslint())
        // .pipe(eslint.failOnError())
        .pipe(babel({stage: 0}))
        .pipe(gulp.dest('lib/'));
});

gulp.task("build-package", function(cb) {
    var config = objectAssign({}, webpackConfigBase, {
      entry: {
        index: LIB_ENTRY
      },
      output: {
        path: LIB_OUTPUT_PATH,
        filename: '[name].js',
        sourceMapFilename: path.join(__dirname, 'debug/[file].map'),
        library: LIB_NAME,
        libraryTarget: LIB_TARGET,
        pathinfo: true
      },
      externals: [
        {react: 'React'}
      ]
    });

    webpack(config, function(err, stats) {
        if(err) throw new gutil.PluginError("webpack", err);
        gutil.log("[webpack]", stats.toString({
            // output options
        }));
        cb();
    });
});

gulp.task('move-examples-index', function() {
  return gulp.src('src/examples/index.html')
    .pipe(gulp.dest('examples/'));
});

gulp.task("build-examples", ['move-examples-index'], function(cb) {
    config = objectAssign({}, webpackConfigBase, {
      entry: {
        bundle: EXAMPLES_ENTRY
      },
      output: {
        path: EXAMPLES_OUTPUT_PATH,
        filename: '[name].js',
        pathinfo: true
      }
    });

    webpack(config, function(err, stats) {
        if(err) throw new gutil.PluginError("webpack", err);
        gutil.log("[webpack]", stats.toString({
            // output options
        }));
        cb();
    });
});
<commit_msg>Fix debug path<commit_after>var gulp = require('gulp');
var path = require('path');
var babel = require('gulp-babel');
var gutil = require("gulp-util");
var webpack = require("webpack");
var webpackConfigBase = require('./webpack.config-base.js');
var del = require('del');
var objectAssign = require('object-assign')
// var eslint = require('gulp-eslint');

// CONSTANTS =======================================================================
var LIB_ENTRY = './src/lib/index.js';
var LIB_OUTPUT_PATH = path.join(__dirname, 'lib');
var LIB_NAME = 'MaterialDesignReact';
var LIB_TARGET = 'umd';

var EXAMPLES_ENTRY = './src/examples/main.js';
var EXAMPLES_OUTPUT_PATH = path.join(__dirname, 'examples');

// TASKS ======================================================================
gulp.task('default', ['build-package', 'build-modules', 'build-examples']);

gulp.task('clean', function(cb) {
  del(['./examples', './lib'], cb);
});

gulp.task('build-modules', function () {
    return gulp.src('src/lib/**/!(index).js?')
        // .pipe(eslint())
        // .pipe(eslint.failOnError())
        .pipe(babel({stage: 0}))
        .pipe(gulp.dest('lib/'));
});

gulp.task("build-package", function(cb) {
    var config = objectAssign({}, webpackConfigBase, {
      entry: {
        index: LIB_ENTRY
      },
      output: {
        path: LIB_OUTPUT_PATH,
        filename: '[name].js',
        sourceMapFilename: 'debug/[file].map',
        library: LIB_NAME,
        libraryTarget: LIB_TARGET,
        pathinfo: true
      },
      externals: [
        {react: 'React'}
      ]
    });

    webpack(config, function(err, stats) {
        if(err) throw new gutil.PluginError("webpack", err);
        gutil.log("[webpack]", stats.toString({
            // output options
        }));
        cb();
    });
});

gulp.task('move-examples-index', function() {
  return gulp.src('src/examples/index.html')
    .pipe(gulp.dest('examples/'));
});

gulp.task("build-examples", ['move-examples-index'], function(cb) {
    config = objectAssign({}, webpackConfigBase, {
      entry: {
        bundle: EXAMPLES_ENTRY
      },
      output: {
        path: EXAMPLES_OUTPUT_PATH,
        filename: '[name].js',
        sourceMapFilename: 'debug/[file].map',
        pathinfo: true,
      }
    });

    webpack(config, function(err, stats) {
        if(err) throw new gutil.PluginError("webpack", err);
        gutil.log("[webpack]", stats.toString({
            // output options
        }));
        cb();
    });
});
<|endoftext|>


<commit_before>import Immutable from 'immutable'
import sinon from 'sinon'
import { range, sample, random, isArray } from 'lodash'
import EventEmitter from 'eventemitter3'

import { eventsStreamFromBus } from '../src/utils'

const AGGREGATES_NUM = 200
const AGGREGATE_TYPES = Immutable.fromJS(range(3, 30).map(n => `Type${n}`))
const EVENT_TYPES = Immutable.fromJS(range(20, 40).map(n => `Type${n}`))
const MIN_EVENTS_PER_AGGREGATE = 1
const MAX_EVENTS_PER_AGGREGATE = 20
const SNAPSHOT_THRESHOLD = 7

function InMemorySimulation (data) {
  let {aggregates, events, snapshots} = data
  let store = FixtureStore()
  let backend = FixtureBackend({aggregates, events, snapshots, store})

  return {
    aggregates,
    events,
    snapshots,
    backend: Object.keys(backend)
              .reduce((spied, handler) => {
                spied[handler] = sinon.spy(backend[handler])
                return spied
              }, {}),
    store,
    call: FixtureGRPCCall(),
    callback: sinon.spy()
  }
}

function FixtureBackend ({aggregates, events, snapshots, store}) {
  function dispatchEvents (results, events) {
    events.forEach((evt, idx) => setTimeout(() => {
      results.emit('event', evt.toJS())
    }, idx + 1))
    setTimeout(function () {
      results.emit('end')
    }, events.size + 5)
  }
  function dispatchSnapshot (results, snapshot) {
    setTimeout(() => {
      results.emit('snapshot', snapshot.toJS())
    }, 1)
    setTimeout(function () {
      results.emit('end')
    }, 2)
  }

  return {
    getEvents ({fromEventId, limit}) {
      let results = new EventEmitter()
      let filteredEvents = events.filter(evt => evt.get('id') > fromEventId)
      filteredEvents = limit ? filteredEvents.slice(0, limit) : filteredEvents

      dispatchEvents(results, filteredEvents)

      return results
    },
    getEventsByAggregate ({aggregateIdentity, fromVersion, limit}) {
      let results = new EventEmitter()
      let { id, type } = aggregateIdentity
      let filteredEvents = events.filter(evt =>
        evt.get('sequenceNumber') > fromVersion &&
        evt.get('aggregateId') === id &&
        evt.get('aggregateType') === type
      )
      filteredEvents = limit ? filteredEvents.slice(0, limit) : filteredEvents

      dispatchEvents(results, filteredEvents)

      return results
    },
    getEventsByAggregateTypes ({aggregateTypes, fromEventId, limit}) {
      let results = new EventEmitter()
      let filteredEvents = events.filter(evt =>
        evt.get('id') > fromEventId &&
        ~aggregateTypes.indexOf(evt.get('aggregateType'))
      )
      filteredEvents = limit ? filteredEvents.slice(0, limit) : filteredEvents

      dispatchEvents(results, filteredEvents)

      return results
    },
    getEventsByTypes ({eventTypes, fromEventId, limit}) {
      let results = new EventEmitter()
      let filteredEvents = events.filter(evt =>
        evt.get('id') > fromEventId &&
        ~eventTypes.indexOf(evt.get('type'))
      )
      filteredEvents = limit ? filteredEvents.slice(0, limit) : filteredEvents

      dispatchEvents(results, filteredEvents)

      return results
    },
    getLastSnapshotOfAggregate ({aggregateIdentity}) {
      let results = new EventEmitter()
      let { id, type } = aggregateIdentity
      let snapshot = snapshots.filter(snapshot =>
        snapshot.get('aggregateId') === id &&
        snapshot.get('aggregateType') === type
      ).takeLast(1).get(0)

      dispatchSnapshot(results, snapshot)

      return results
    },
    storeEvents () {}
  }
}

function FixtureStore () {
  let messageBus = new EventEmitter()
  return {
    eventsStream: eventsStreamFromBus(messageBus),
    publishEvents: sinon.spy((events) => {
      events = isArray(events) ? events : [events]
      events.forEach((evt, idx) => setTimeout(() => {
        messageBus.emit('StoredEvents', JSON.stringify([evt]))
      }, idx * 5))
    })
  }
}

function FixtureGRPCCall () {
  let call = new EventEmitter()
  sinon.spy(call, 'on')
  sinon.spy(call, 'emit')
  sinon.spy(call, 'removeAllListeners')
  call.write = sinon.spy()
  call.end = sinon.spy()

  return call
}

function getSimulationData () {
  let aggregateTypes = AGGREGATE_TYPES.toArray()
  let eventTypes = EVENT_TYPES.toArray()
  let now = Date.now()
  let firstTime = now - (180 * 1000) // 3 min
  let aggregates = Immutable.fromJS(range(AGGREGATES_NUM).map(n => ({
    id: `aid${n}`,
    type: sample(aggregateTypes),
    version: random(MIN_EVENTS_PER_AGGREGATE, MAX_EVENTS_PER_AGGREGATE) // First version of aggregate should be 1
  })))
  let aggregateStreams = Immutable.fromJS(aggregates.map(
    (aggregate) => {
      return Immutable.fromJS(range(aggregate.get('version')).map(n => ({
        type: sample(eventTypes),
        aggregateId: aggregate.get('id'),
        aggregateType: aggregate.get('type'),
        sequenceNumber: n + 1, // First event of an aggregate should be 1
        data: '',
        metadata: ''
      })))
    }
  ))

  let events = Immutable.fromJS(
    range(aggregateStreams.flatten(true).size)
      .map(() => {
        let streamIdx = random(aggregateStreams.size - 1)
        let stream = aggregateStreams.get(streamIdx)
        let evt = stream.get(0)
        aggregateStreams = aggregateStreams.set(streamIdx, stream.shift())
        if (!aggregateStreams.get(streamIdx).size) {
          aggregateStreams = aggregateStreams.delete(streamIdx)
        }
        return evt
      })
  )

  let instants = events
                  .map(() => random(firstTime, now))
                  .sortBy(ms => ms)
                  .map(ms => new Date(firstTime + ms))
                  .map(d => d.toISOString())

  events = events.map(
    (evt, idx) => evt.set('id', idx + 1).set('storedOn', instants.get(idx))
  )

  let snapshots = aggregates
                    .filter(aggregate => aggregate.get('version') > SNAPSHOT_THRESHOLD)
                    .map(aggregate => {
                      let snapshotsN = Math.floor(aggregate.get('version') / SNAPSHOT_THRESHOLD)
                      return Immutable.fromJS(range(snapshotsN).map(n => ({
                        aggregateId: aggregate.get('id'),
                        aggregateType: aggregate.get('type'),
                        version: (n + 1) * SNAPSHOT_THRESHOLD,
                        data: ''
                      })))
                    }).flatten(true)

  return {
    aggregates,
    events,
    snapshots
  }
}

export default InMemorySimulation
export {
  getSimulationData,
  AGGREGATES_NUM,
  AGGREGATE_TYPES,
  EVENT_TYPES,
  MIN_EVENTS_PER_AGGREGATE,
  MAX_EVENTS_PER_AGGREGATE,
  SNAPSHOT_THRESHOLD
}
<commit_msg>fix times<commit_after>import Immutable from 'immutable'
import sinon from 'sinon'
import { range, sample, random, isArray } from 'lodash'
import EventEmitter from 'eventemitter3'

import { eventsStreamFromBus } from '../src/utils'

const AGGREGATES_NUM = 200
const AGGREGATE_TYPES = Immutable.fromJS(range(3, 30).map(n => `Type${n}`))
const EVENT_TYPES = Immutable.fromJS(range(20, 40).map(n => `Type${n}`))
const MIN_EVENTS_PER_AGGREGATE = 1
const MAX_EVENTS_PER_AGGREGATE = 20
const SNAPSHOT_THRESHOLD = 7

function InMemorySimulation (data) {
  let {aggregates, events, snapshots} = data
  let store = FixtureStore()
  let backend = FixtureBackend({aggregates, events, snapshots, store})

  return {
    aggregates,
    events,
    snapshots,
    backend: Object.keys(backend)
              .reduce((spied, handler) => {
                spied[handler] = sinon.spy(backend[handler])
                return spied
              }, {}),
    store,
    call: FixtureGRPCCall(),
    callback: sinon.spy()
  }
}

function FixtureBackend ({aggregates, events, snapshots, store}) {
  function dispatchEvents (results, events) {
    events.forEach((evt, idx) => setTimeout(() => {
      results.emit('event', evt.toJS())
    }, idx + 5))
    setTimeout(function () {
      results.emit('end')
    }, events.size + 5)
  }
  function dispatchSnapshot (results, snapshot) {
    setTimeout(() => {
      results.emit('snapshot', snapshot.toJS())
    }, 5)
    setTimeout(function () {
      results.emit('end')
    }, 10)
  }

  return {
    getEvents ({fromEventId, limit}) {
      let results = new EventEmitter()
      let filteredEvents = events.filter(evt => evt.get('id') > fromEventId)
      filteredEvents = limit ? filteredEvents.slice(0, limit) : filteredEvents

      dispatchEvents(results, filteredEvents)

      return results
    },
    getEventsByAggregate ({aggregateIdentity, fromVersion, limit}) {
      let results = new EventEmitter()
      let { id, type } = aggregateIdentity
      let filteredEvents = events.filter(evt =>
        evt.get('sequenceNumber') > fromVersion &&
        evt.get('aggregateId') === id &&
        evt.get('aggregateType') === type
      )
      filteredEvents = limit ? filteredEvents.slice(0, limit) : filteredEvents

      dispatchEvents(results, filteredEvents)

      return results
    },
    getEventsByAggregateTypes ({aggregateTypes, fromEventId, limit}) {
      let results = new EventEmitter()
      let filteredEvents = events.filter(evt =>
        evt.get('id') > fromEventId &&
        ~aggregateTypes.indexOf(evt.get('aggregateType'))
      )
      filteredEvents = limit ? filteredEvents.slice(0, limit) : filteredEvents

      dispatchEvents(results, filteredEvents)

      return results
    },
    getEventsByTypes ({eventTypes, fromEventId, limit}) {
      let results = new EventEmitter()
      let filteredEvents = events.filter(evt =>
        evt.get('id') > fromEventId &&
        ~eventTypes.indexOf(evt.get('type'))
      )
      filteredEvents = limit ? filteredEvents.slice(0, limit) : filteredEvents

      dispatchEvents(results, filteredEvents)

      return results
    },
    getLastSnapshotOfAggregate ({aggregateIdentity}) {
      let results = new EventEmitter()
      let { id, type } = aggregateIdentity
      let snapshot = snapshots.filter(snapshot =>
        snapshot.get('aggregateId') === id &&
        snapshot.get('aggregateType') === type
      ).takeLast(1).get(0)

      dispatchSnapshot(results, snapshot)

      return results
    },
    storeEvents () {}
  }
}

function FixtureStore () {
  let messageBus = new EventEmitter()
  return {
    eventsStream: eventsStreamFromBus(messageBus),
    publishEvents: sinon.spy((events) => {
      events = isArray(events) ? events : [events]
      events.forEach((evt, idx) => setTimeout(() => {
        messageBus.emit('StoredEvents', JSON.stringify([evt]))
      }, idx * 5))
    })
  }
}

function FixtureGRPCCall () {
  let call = new EventEmitter()
  sinon.spy(call, 'on')
  sinon.spy(call, 'emit')
  sinon.spy(call, 'removeAllListeners')
  call.write = sinon.spy()
  call.end = sinon.spy()

  return call
}

function getSimulationData () {
  let aggregateTypes = AGGREGATE_TYPES.toArray()
  let eventTypes = EVENT_TYPES.toArray()
  let now = Date.now()
  let firstTime = now - (180 * 1000) // 3 min
  let aggregates = Immutable.fromJS(range(AGGREGATES_NUM).map(n => ({
    id: `aid${n}`,
    type: sample(aggregateTypes),
    version: random(MIN_EVENTS_PER_AGGREGATE, MAX_EVENTS_PER_AGGREGATE) // First version of aggregate should be 1
  })))
  let aggregateStreams = Immutable.fromJS(aggregates.map(
    (aggregate) => {
      return Immutable.fromJS(range(aggregate.get('version')).map(n => ({
        type: sample(eventTypes),
        aggregateId: aggregate.get('id'),
        aggregateType: aggregate.get('type'),
        sequenceNumber: n + 1, // First event of an aggregate should be 1
        data: '',
        metadata: ''
      })))
    }
  ))

  let events = Immutable.fromJS(
    range(aggregateStreams.flatten(true).size)
      .map(() => {
        let streamIdx = random(aggregateStreams.size - 1)
        let stream = aggregateStreams.get(streamIdx)
        let evt = stream.get(0)
        aggregateStreams = aggregateStreams.set(streamIdx, stream.shift())
        if (!aggregateStreams.get(streamIdx).size) {
          aggregateStreams = aggregateStreams.delete(streamIdx)
        }
        return evt
      })
  )

  let instants = events
                  .map(() => random(firstTime, now))
                  .sortBy(ms => ms)
                  .map(ms => new Date(firstTime + ms))
                  .map(d => d.toISOString())

  events = events.map(
    (evt, idx) => evt.set('id', idx + 1).set('storedOn', instants.get(idx))
  )

  let snapshots = aggregates
                    .filter(aggregate => aggregate.get('version') > SNAPSHOT_THRESHOLD)
                    .map(aggregate => {
                      let snapshotsN = Math.floor(aggregate.get('version') / SNAPSHOT_THRESHOLD)
                      return Immutable.fromJS(range(snapshotsN).map(n => ({
                        aggregateId: aggregate.get('id'),
                        aggregateType: aggregate.get('type'),
                        version: (n + 1) * SNAPSHOT_THRESHOLD,
                        data: ''
                      })))
                    }).flatten(true)

  return {
    aggregates,
    events,
    snapshots
  }
}

export default InMemorySimulation
export {
  getSimulationData,
  AGGREGATES_NUM,
  AGGREGATE_TYPES,
  EVENT_TYPES,
  MIN_EVENTS_PER_AGGREGATE,
  MAX_EVENTS_PER_AGGREGATE,
  SNAPSHOT_THRESHOLD
}
<|endoftext|>


<commit_before>var map;
var n0q;
var jsonlayer;
var sbwlayer;
var selectControl;
var ts = null;
var aqlive = 0;
var showlogo = 1;
var selectedCameraFeature;

function selectMapFeature(){
	selectControl.unselectAll();
	jsonlayer.features.forEach(function(feat){
		if (feat.data.cid == cameraID){
			selectControl.select(feat);
		}
	});
}
function liveShot()
{
	if (aqlive) return;
	aqlive = true;
	ts = new Date();
	document.camera.src = "live.php?id="+ cameraID +"&"+ ts.getTime();
	aqlive = false;
}
function setCameraFromForm(cid){
	setCamera(cid);
	var feature = jsonlayer.getSource().getFeatureById(cid);
	if (feature){
    	if (feature != selectedCameraFeature){
    		if (selectedCameraFeature){
    			selectedCameraFeature.setStyle(feature.getStyle());
    		}
    	}
    	cameraStyle2.getImage().setRotation(parseInt(feature.get('angle')) / 180. * 3.14);
    	feature.setStyle(cameraStyle2);
    	selectedCameraFeature = feature;
    	setCamera(feature.get('cid'));
	}
}
function updateHREF(){
	window.location.href = '#'+cameraID;
}
function refreshCamera()
{
    ts = new Date();
    imgurl = "/data/camera/640x480/"+ cameraID +".jpg?"+ ts.getTime();
    document.camera.src = imgurl;
}
function refreshRADAR(){
    if (n0q){
        n0q.setSource(n0q.getSource());
    }
}
function refreshJSON(){
	    jsonlayer.setSource(jsonlayer.getSource());
	    sbwlayer.setSource(sbwlayer.getSource());
}
function setCamera(cid){
	//console.log("setCamera() called");
	document.getElementById("c"+cid).checked = true;
	cameraID = cid;
	updateHREF();
	refreshCamera();
}
function cb_siteOver(feature){
	if (cameraID != feature.data.cid){
		setCamera( feature.data.cid );
	}
};
var sbwLookup = {
		 "TO": 'red',
		 "MA": 'purple',
		 "FF": 'green',
		 "EW": 'green',
		 "FA": 'green',
		 "FL": 'green',
		 "SV": 'yellow'
		};

var sbwStyle = [new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: '#FFF',
      width: 4.5
    })
  }), new ol.style.Style({
	    stroke: new ol.style.Stroke({
	        color: '#319FD3',
	        width: 3
	      })
	    })
  ];

var cameraStyle = new ol.style.Style({
	image: new ol.style.Icon({
		src: '/images/yellow_arrow.png'
	})
});
var cameraStyle2 = new ol.style.Style({
	image: new ol.style.Icon({
		src: '/images/red_arrow.png',
		scale: 1.2
	})
});
/*
var styleMap = new OpenLayers.StyleMap({
    'default': {
 	   externalGraphic: "/images/yellow_arrow.png",
        graphicHeight: 20,
        rotation: "\${angle}",
        strokeOpacity: 1
    },
    'select': {
       graphicHeight: 30
    }
});
*/

function switchRADAR(){
	for (var i=0; i < document.radar.nexrad.length; i++)
	{
		if (document.radar.nexrad[i].checked)
		{
			v = document.radar.nexrad[i].value;
			n0q.setSource(new ol.source.XYZ({
				url: '/cache/tile.py/1.0.0/'+v+'/{z}/{x}/{y}.png'
			}));
		}
	}
}

$().ready(function(){

	sbwlayer = new ol.layer.Vector({
		title: 'Storm Based Warnings',
		source: new ol.source.Vector({
			url: "/geojson/sbw.geojson",
			format: new ol.format.GeoJSON()
		}),
		style: function(feature, resolution){
			sbwStyle[1].getStroke().setColor(sbwLookup[feature.get('phenomena')]);
			return sbwStyle;
		}
	});
	jsonlayer = new ol.layer.Vector({
		title: 'Webcams',
		source: new ol.source.Vector({
			url: "/geojson/webcam.php?network=TV",
			format: new ol.format.GeoJSON()
		}),
		style: function(feature, resolution){
			// OL rotation is in radians!
			cameraStyle.getImage().setRotation(parseInt(feature.get('angle')) / 180. * 3.14);
			return [cameraStyle];
		}
	});
	n0q = new ol.layer.Tile({
		title: 'NEXRAD Base Reflectivity',
		source: new ol.source.XYZ({
			url: '/cache/tile.py/1.0.0/nexrad-n0q-900913/{z}/{x}/{y}.png'
		})
	});
	map = new ol.Map({
		target: 'map',
		layers: [new ol.layer.Tile({
            title: 'OpenStreetMap',
            visible: true,
            source: new ol.source.OSM()
            }),
            n0q,
            sbwlayer, jsonlayer
		],
		view: new ol.View({
			projection: 'EPSG:3857',
			center: ol.proj.transform([-93.5, 42.1], 'EPSG:4326', 'EPSG:3857'),
			zoom: 7
		})
	});
    var layerSwitcher = new ol.control.LayerSwitcher();
    map.addControl(layerSwitcher);

    map.on('click', function(evt){
    	var feature = map.forEachFeatureAtPixel(evt.pixel,
    			function(feature, layer){
    				return feature;
    			}
    	);
    	if (feature){
    		if (feature.get('cid')){
    	    	if (feature != selectedCameraFeature){
    	    		if (selectedCameraFeature){
    	    			selectedCameraFeature.setStyle(feature.getStyle());
    	    		}
    	    	}
    	    	cameraStyle2.getImage().setRotation(parseInt(feature.get('angle')) / 180. * 3.14);
    	    	feature.setStyle(cameraStyle2);
    	    	selectedCameraFeature = feature;
    	    	setCamera(feature.get('cid'));
    		}
    	}
    });

	var tokens = window.location.href.split('#');
	if (tokens.length == 2){
		setCamera(tokens[1]);

	}

    window.setInterval(refreshRADAR, 150000);
    window.setInterval(refreshCamera, 60000);
    window.setInterval(refreshJSON, 65000);
});

<commit_msg>fix layer refreshing for webcam viewer<commit_after>var map;
var n0q;
var jsonlayer;
var sbwlayer;
var selectControl;
var ts = null;
var aqlive = 0;
var showlogo = 1;
var selectedCameraFeature;

function selectMapFeature(){
	selectControl.unselectAll();
	jsonlayer.features.forEach(function(feat){
		if (feat.data.cid == cameraID){
			selectControl.select(feat);
		}
	});
}
function liveShot()
{
	if (aqlive) return;
	aqlive = true;
	ts = new Date();
	document.camera.src = "live.php?id="+ cameraID +"&"+ ts.getTime();
	aqlive = false;
}
function setCameraFromForm(cid){
	setCamera(cid);
	var feature = jsonlayer.getSource().getFeatureById(cid);
	if (feature){
    	if (feature != selectedCameraFeature){
    		if (selectedCameraFeature){
    			selectedCameraFeature.setStyle(feature.getStyle());
    		}
    	}
    	cameraStyle2.getImage().setRotation(parseInt(feature.get('angle')) / 180. * 3.14);
    	feature.setStyle(cameraStyle2);
    	selectedCameraFeature = feature;
    	setCamera(feature.get('cid'));
	}
}
function updateHREF(){
	window.location.href = '#'+cameraID;
}
function refreshCamera()
{
    ts = new Date();
    imgurl = "/data/camera/640x480/"+ cameraID +".jpg?"+ ts.getTime();
    document.camera.src = imgurl;
}
function refreshRADAR(){
    if (n0q){
        n0q.setSource(n0q.getSource());
    }
}
function refreshJSON(){
	    jsonlayer.setSource(new ol.source.Vector({
			url: "/geojson/webcam.php?network=TV",
		format: new ol.format.GeoJSON()
	}));
	    sbwlayer.setSource(new ol.source.Vector({
			url: "/geojson/sbw.geojson",
		format: new ol.format.GeoJSON()
	}));
}
function setCamera(cid){
	//console.log("setCamera() called");
	document.getElementById("c"+cid).checked = true;
	cameraID = cid;
	updateHREF();
	refreshCamera();
}
function cb_siteOver(feature){
	if (cameraID != feature.data.cid){
		setCamera( feature.data.cid );
	}
};
var sbwLookup = {
		 "TO": 'red',
		 "MA": 'purple',
		 "FF": 'green',
		 "EW": 'green',
		 "FA": 'green',
		 "FL": 'green',
		 "SV": 'yellow'
		};

var sbwStyle = [new ol.style.Style({
    stroke: new ol.style.Stroke({
      color: '#FFF',
      width: 4.5
    })
  }), new ol.style.Style({
	    stroke: new ol.style.Stroke({
	        color: '#319FD3',
	        width: 3
	      })
	    })
  ];

var cameraStyle = new ol.style.Style({
	image: new ol.style.Icon({
		src: '/images/yellow_arrow.png'
	})
});
var cameraStyle2 = new ol.style.Style({
	image: new ol.style.Icon({
		src: '/images/red_arrow.png',
		scale: 1.2
	})
});
/*
var styleMap = new OpenLayers.StyleMap({
    'default': {
 	   externalGraphic: "/images/yellow_arrow.png",
        graphicHeight: 20,
        rotation: "\${angle}",
        strokeOpacity: 1
    },
    'select': {
       graphicHeight: 30
    }
});
*/

function switchRADAR(){
	for (var i=0; i < document.radar.nexrad.length; i++)
	{
		if (document.radar.nexrad[i].checked)
		{
			v = document.radar.nexrad[i].value;
			n0q.setSource(new ol.source.XYZ({
				url: '/cache/tile.py/1.0.0/'+v+'/{z}/{x}/{y}.png'
			}));
		}
	}
}

$().ready(function(){

	sbwlayer = new ol.layer.Vector({
		title: 'Storm Based Warnings',
		source: new ol.source.Vector({
			url: "/geojson/sbw.geojson",
			format: new ol.format.GeoJSON()
		}),
		style: function(feature, resolution){
			sbwStyle[1].getStroke().setColor(sbwLookup[feature.get('phenomena')]);
			return sbwStyle;
		}
	});
	jsonlayer = new ol.layer.Vector({
		title: 'Webcams',
		source: new ol.source.Vector({
			url: "/geojson/webcam.php?network=TV",
			format: new ol.format.GeoJSON()
		}),
		style: function(feature, resolution){
			// OL rotation is in radians!
			cameraStyle.getImage().setRotation(parseInt(feature.get('angle')) / 180. * 3.14);
			return [cameraStyle];
		}
	});
	n0q = new ol.layer.Tile({
		title: 'NEXRAD Base Reflectivity',
		source: new ol.source.XYZ({
			url: '/cache/tile.py/1.0.0/nexrad-n0q-900913/{z}/{x}/{y}.png'
		})
	});
	map = new ol.Map({
		target: 'map',
		layers: [new ol.layer.Tile({
            title: 'OpenStreetMap',
            visible: true,
            source: new ol.source.OSM()
            }),
            n0q,
            sbwlayer, jsonlayer
		],
		view: new ol.View({
			projection: 'EPSG:3857',
			center: ol.proj.transform([-93.5, 42.1], 'EPSG:4326', 'EPSG:3857'),
			zoom: 6
		})
	});
    var layerSwitcher = new ol.control.LayerSwitcher();
    map.addControl(layerSwitcher);

    map.on('click', function(evt){
    	var feature = map.forEachFeatureAtPixel(evt.pixel,
    			function(feature, layer){
    				return feature;
    			}
    	);
    	if (feature){
    		if (feature.get('cid')){
    	    	if (feature != selectedCameraFeature){
    	    		if (selectedCameraFeature){
    	    			selectedCameraFeature.setStyle(feature.getStyle());
    	    		}
    	    	}
    	    	cameraStyle2.getImage().setRotation(parseInt(feature.get('angle')) / 180. * 3.14);
    	    	feature.setStyle(cameraStyle2);
    	    	selectedCameraFeature = feature;
    	    	setCamera(feature.get('cid'));
    		}
    	}
    });

	var tokens = window.location.href.split('#');
	if (tokens.length == 2){
		setCamera(tokens[1]);

	}

    window.setInterval(refreshRADAR, 150000);
    window.setInterval(refreshCamera, 60000);
    window.setInterval(refreshJSON, 65000);
});

<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var _ = require('lodash'),
	defaultAssets = require('./config/assets/default'),
	testAssets = require('./config/assets/test'),
	gulp = require('gulp'),
	gulpLoadPlugins = require('gulp-load-plugins'),
	runSequence = require('run-sequence'),
	plugins = gulpLoadPlugins();

var minimist = require('minimist');

var args = minimist(process.argv.slice(2), {
	string: 'file'
});

// Set NODE_ENV to 'test'
gulp.task('env:test', function() {
	process.env.NODE_ENV = 'test';
});

// Set NODE_ENV to 'development'
gulp.task('env:dev', function() {
	process.env.NODE_ENV = 'development';
});

// Set NODE_ENV to 'production'
gulp.task('env:prod', function() {
	process.env.NODE_ENV = 'production';
});

// Nodemon task
gulp.task('nodemon', function() {
	return plugins.nodemon({
		script: 'server.js',
		nodeArgs: ['--debug'],
		ext: 'js,html',
		watch: _.union(defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.config)
	});
});

// Watch Files For Changes
gulp.task('watch', function() {
	// Start livereload
	plugins.livereload.listen();

	// Add watch rules
	gulp.watch(defaultAssets.server.views).on('change', plugins.livereload.changed);
	gulp.watch(defaultAssets.server.allJS, ['jshint']).on('change', plugins.livereload.changed);
	gulp.watch(defaultAssets.client.views).on('change', plugins.livereload.changed);
	gulp.watch(defaultAssets.client.js, ['jshint']).on('change', plugins.livereload.changed);
	gulp.watch(defaultAssets.client.css, ['csslint']).on('change', plugins.livereload.changed);
	gulp.watch(defaultAssets.client.sass, ['sass', 'csslint']).on('change', plugins.livereload.changed);
	gulp.watch(defaultAssets.client.less, ['less', 'csslint']).on('change', plugins.livereload.changed);
});

// CSS linting task
gulp.task('csslint', function(done) {
	return gulp.src(defaultAssets.client.css)
		.pipe(plugins.csslint('.csslintrc'))
		.pipe(plugins.csslint.reporter())
		.pipe(plugins.csslint.reporter(function(file) {
			if (!file.csslint.errorCount) {
				done();
			}
		}));
});

// JS linting task
gulp.task('jshint', function() {
	return gulp.src(_.union(defaultAssets.server.allJS, defaultAssets.client.js, testAssets.tests.server, testAssets.tests.client, testAssets.tests.e2e))
		.pipe(plugins.jshint())
		.pipe(plugins.jshint.reporter('default'))
		.pipe(plugins.jshint.reporter('fail'));
});

// JS minifying task
gulp.task('uglify', function() {
	return gulp.src(defaultAssets.client.js)
		.pipe(plugins.ngAnnotate())
		.pipe(plugins.uglify({
			mangle: false
		}))
		.pipe(plugins.concat('application.min.js'))
		.pipe(gulp.dest('public/dist'));
});

// CSS minifying task
gulp.task('cssmin', function() {
	return gulp.src(defaultAssets.client.css)
		.pipe(plugins.cssmin())
		.pipe(plugins.concat('application.min.css'))
		.pipe(gulp.dest('public/dist'));
});

// Sass task
gulp.task('sass', function() {
	return gulp.src(defaultAssets.client.sass)
		.pipe(plugins.sass())
		.pipe(plugins.rename(function(path) {
			path.dirname = path.dirname.replace('/scss', '/css');
		}))
		.pipe(gulp.dest('./modules/'));
});

// Less task
gulp.task('less', function() {
	return gulp.src(defaultAssets.client.less)
		.pipe(plugins.less())
		.pipe(plugins.rename(function(path) {
			path.dirname = path.dirname.replace('/less', '/css');
		}))
		.pipe(gulp.dest('./modules/'));
});

// Connect to MongoDB using the mongoose module
gulp.task('mongoose', function(done) {
	var mongoose = require('./config/lib/mongoose.js');

	mongoose.connect(function(db) {
		done();
	});
});

// Mocha tests task
gulp.task('mocha', ['env:test', 'mongoose'], function() {
	var testFiles;
	if (args.file) testFiles = args.file;
	else testFiles = testAssets.tests.server;

	return gulp.src(testFiles)
		.pipe(plugins.mocha({
			reporter: 'spec'
		})).once('end', function() {
			process.exit();
		});
});

// Karma test runner task
gulp.task('karma', ['env:test'], function(done) {
	return gulp.src([])
		.pipe(plugins.karma({
			configFile: 'karma.conf.js',
			action: 'run',
			singleRun: true
		}))
		.on('error', function(err) {
			// Make sure failed tests cause gulp to exit non-zero
			throw err;
		});
});

// Selenium standalone WebDriver update task
gulp.task('webdriver-update', plugins.protractor.webdriver_update);

// Protractor test runner task
gulp.task('protractor', function() {
	gulp.src([])
		.pipe(plugins.protractor.protractor({
			configFile: "protractor.conf.js"
		}))
		.on('error', function(e) {
			throw e
		})
});

// Lint CSS and JavaScript files.
gulp.task('lint', function(done) {
	runSequence('less', 'sass', ['csslint', 'jshint'], done);
});

// Lint project files and minify them into two production files.
gulp.task('build', function(done) {
	runSequence('env:dev', 'lint', ['uglify', 'cssmin'], done);
});

// Run the project tests
gulp.task('test', function(done) {
	runSequence('karma', 'mocha', done);
});

// Run the project in development mode
gulp.task('default', function(done) {
	runSequence('env:dev', 'lint', ['nodemon', 'watch'], done);
});

// Run the project in debug mode
gulp.task('debug', function(done) {
	runSequence('env:dev', 'lint', ['nodemon', 'watch'], done);
});

// Run the project in production mode
gulp.task('prod', function(done) {
	runSequence('build', 'lint', ['nodemon', 'watch'], done);
});<commit_msg>better naming<commit_after>'use strict';

/**
 * Module dependencies.
 */
var _ = require('lodash'),
	defaultAssets = require('./config/assets/default'),
	testAssets = require('./config/assets/test'),
	gulp = require('gulp'),
	gulpLoadPlugins = require('gulp-load-plugins'),
	runSequence = require('run-sequence'),
	plugins = gulpLoadPlugins();

var minimist = require('minimist');

var args = minimist(process.argv.slice(2), {
	string: 'testFiles'
});

// Set NODE_ENV to 'test'
gulp.task('env:test', function() {
	process.env.NODE_ENV = 'test';
});

// Set NODE_ENV to 'development'
gulp.task('env:dev', function() {
	process.env.NODE_ENV = 'development';
});

// Set NODE_ENV to 'production'
gulp.task('env:prod', function() {
	process.env.NODE_ENV = 'production';
});

// Nodemon task
gulp.task('nodemon', function() {
	return plugins.nodemon({
		script: 'server.js',
		nodeArgs: ['--debug'],
		ext: 'js,html',
		watch: _.union(defaultAssets.server.views, defaultAssets.server.allJS, defaultAssets.server.config)
	});
});

// Watch Files For Changes
gulp.task('watch', function() {
	// Start livereload
	plugins.livereload.listen();

	// Add watch rules
	gulp.watch(defaultAssets.server.views).on('change', plugins.livereload.changed);
	gulp.watch(defaultAssets.server.allJS, ['jshint']).on('change', plugins.livereload.changed);
	gulp.watch(defaultAssets.client.views).on('change', plugins.livereload.changed);
	gulp.watch(defaultAssets.client.js, ['jshint']).on('change', plugins.livereload.changed);
	gulp.watch(defaultAssets.client.css, ['csslint']).on('change', plugins.livereload.changed);
	gulp.watch(defaultAssets.client.sass, ['sass', 'csslint']).on('change', plugins.livereload.changed);
	gulp.watch(defaultAssets.client.less, ['less', 'csslint']).on('change', plugins.livereload.changed);
});

// CSS linting task
gulp.task('csslint', function(done) {
	return gulp.src(defaultAssets.client.css)
		.pipe(plugins.csslint('.csslintrc'))
		.pipe(plugins.csslint.reporter())
		.pipe(plugins.csslint.reporter(function(file) {
			if (!file.csslint.errorCount) {
				done();
			}
		}));
});

// JS linting task
gulp.task('jshint', function() {
	return gulp.src(_.union(defaultAssets.server.allJS, defaultAssets.client.js, testAssets.tests.server, testAssets.tests.client, testAssets.tests.e2e))
		.pipe(plugins.jshint())
		.pipe(plugins.jshint.reporter('default'))
		.pipe(plugins.jshint.reporter('fail'));
});

// JS minifying task
gulp.task('uglify', function() {
	return gulp.src(defaultAssets.client.js)
		.pipe(plugins.ngAnnotate())
		.pipe(plugins.uglify({
			mangle: false
		}))
		.pipe(plugins.concat('application.min.js'))
		.pipe(gulp.dest('public/dist'));
});

// CSS minifying task
gulp.task('cssmin', function() {
	return gulp.src(defaultAssets.client.css)
		.pipe(plugins.cssmin())
		.pipe(plugins.concat('application.min.css'))
		.pipe(gulp.dest('public/dist'));
});

// Sass task
gulp.task('sass', function() {
	return gulp.src(defaultAssets.client.sass)
		.pipe(plugins.sass())
		.pipe(plugins.rename(function(path) {
			path.dirname = path.dirname.replace('/scss', '/css');
		}))
		.pipe(gulp.dest('./modules/'));
});

// Less task
gulp.task('less', function() {
	return gulp.src(defaultAssets.client.less)
		.pipe(plugins.less())
		.pipe(plugins.rename(function(path) {
			path.dirname = path.dirname.replace('/less', '/css');
		}))
		.pipe(gulp.dest('./modules/'));
});

// Connect to MongoDB using the mongoose module
gulp.task('mongoose', function(done) {
	var mongoose = require('./config/lib/mongoose.js');

	mongoose.connect(function(db) {
		done();
	});
});

// Mocha tests task
gulp.task('mocha', ['env:test', 'mongoose'], function() {
	var testFiles;
	if (args.testFiles) testFiles = args.testFiles;
	else testFiles = testAssets.tests.server;

	return gulp.src(testFiles)
		.pipe(plugins.mocha({
			reporter: 'spec'
		})).once('end', function() {
			process.exit();
		});
});

// Karma test runner task
gulp.task('karma', ['env:test'], function(done) {
	return gulp.src([])
		.pipe(plugins.karma({
			configFile: 'karma.conf.js',
			action: 'run',
			singleRun: true
		}))
		.on('error', function(err) {
			// Make sure failed tests cause gulp to exit non-zero
			throw err;
		});
});

// Selenium standalone WebDriver update task
gulp.task('webdriver-update', plugins.protractor.webdriver_update);

// Protractor test runner task
gulp.task('protractor', function() {
	gulp.src([])
		.pipe(plugins.protractor.protractor({
			configFile: "protractor.conf.js"
		}))
		.on('error', function(e) {
			throw e
		})
});

// Lint CSS and JavaScript files.
gulp.task('lint', function(done) {
	runSequence('less', 'sass', ['csslint', 'jshint'], done);
});

// Lint project files and minify them into two production files.
gulp.task('build', function(done) {
	runSequence('env:dev', 'lint', ['uglify', 'cssmin'], done);
});

// Run the project tests
gulp.task('test', function(done) {
	runSequence('karma', 'mocha', done);
});

// Run the project in development mode
gulp.task('default', function(done) {
	runSequence('env:dev', 'lint', ['nodemon', 'watch'], done);
});

// Run the project in debug mode
gulp.task('debug', function(done) {
	runSequence('env:dev', 'lint', ['nodemon', 'watch'], done);
});

// Run the project in production mode
gulp.task('prod', function(done) {
	runSequence('build', 'lint', ['nodemon', 'watch'], done);
});<|endoftext|>


<commit_before>var _ = require('lodash');
var log = require('gulp-util').log;
var path = require('path');
var gulp = require('gulp');
var jade = require('gulp-jade');
var sass = require('gulp-ruby-sass');
var bower = require('bower');
var Dgeni = require('dgeni');
var cssmin = require('gulp-cssmin');
var jshint = require('gulp-jshint');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var wrapper = require('gulp-wrapper');
var nunjucks = require('./nunjucks-build');
var pleeease = require('gulp-pleeease');
var ngAnnotate = require('gulp-ng-annotate');
var livereload = require('gulp-livereload');
var ngTemplates = require('gulp-ng-templates');

var paths = {
	templates: [
		'src/**/*.jade'
	],
	scripts: [
		'src/**/*.js',
		'!src/**/*_test.js'
	],
	stylesheets: ['stylesheets/**/*.scss'],
	docs: {
		scripts: ['docs/app/src/**/*.js'],
		assets: ['docs/app/assets/**/*.*'],
		templates: ['docs/app/src/**/*.html']
	}
};

gulp.task('docs-assets', function () {
	gulp.src(paths.docs.assets)
	.pipe(gulp.dest('build/docs'));
});

gulp.task('docs-scripts', function () {
	gulp.src(paths.docs.scripts)
	.pipe(ngAnnotate())
	.pipe(uglify())
	.pipe(concat('app.js'))
	.pipe(wrapper({
		header: `(function (window, angular, undefined) {`,
		footer: `}(window, angular, undefined));`
	}))
	.pipe(gulp.dest('build/docs/js'));
});

gulp.task('docs-mobie-build', function () {
	gulp.src([
		'build/mobie.js',
		'build/mobie.css',
		'build/mobie.tpl.js'
	])
	.pipe(gulp.dest('build/docs/lib'));
});

gulp.task('docs-deps', [
	'build',
	'docs-scripts',
	'docs-templates',
	'docs-assets',
	'docs-mobie-build'
], function (done) {
	var bowerTask = bower.commands.install([], {}, {
		directory: 'build/docs/lib'
	});

	bowerTask.on('log', function (result) {
		log('bower:', result.id, result.data.endpoint.name);
	});

	bowerTask.on('error', function (error) {
		log(error);
	});

	bowerTask.on('end', function () {
		done();
	});
});

gulp.task('docs-build', ['docs-deps'], function () {
	var dgeni = new Dgeni([require('./docs/config')])
	return dgeni.generate();
});

gulp.task('docs-livereload', function () {
	livereload.listen();
	gulp.watch([
		'build/docs/{js,css,partials}/*.{js,css,html}',
		'build/docs/lib/mobie.*'
	]).on('change', livereload.changed);
});

gulp.task('docs-stylesheets', function () {
	sass('./docs/app/scss/app.scss')
	.pipe(cssmin())
	.pipe(gulp.dest('build/docs/css'));
});

gulp.task('docs-watch', ['docs-livereload'], function () {
	gulp.watch('docs/app/scss/**/*.scss', ['docs-stylesheets']);
	gulp.watch('docs/app/src/**/*.js', ['docs-scripts']);
	gulp.watch('docs/app/src/**/*.{html,jade}', ['docs-templates']);
	gulp.watch('docs/config/**/*.{js,html}', ['docs-build']);

	gulp.watch(paths.scripts, ['scripts']);
	gulp.watch(paths.templates, ['templates']);
	gulp.watch(paths.stylesheets, ['stylesheets']);

	gulp.watch('build/mobie.*', ['docs-mobie-build']);
});

var express = require('express');
gulp.task('docs-serve', ['docs-watch'], function () {
	var app = express();
	app.use(express.static('build/docs'));
	app.get('/', function (req, res) {
		res.render('index.html');
	});
	app.listen(8080, function () {
		console.log('Documentation server is running at 0.0.0.0:8080');
	});
});

gulp.task('docs-templates', function () {
	gulp.src(['docs/app/src/**/*.mobile.jade'])
	.pipe(jade())
	.pipe(gulp.dest('build/docs'));

	gulp.src(paths.docs.templates)
	.pipe(ngTemplates({
		module: 'docsApp',
		standalone: false,
		filename: 'templates.js'
	}))
	.pipe(gulp.dest('build/docs/js'));
});

gulp.task('templates', function () {
	gulp.src(paths.templates)
		.pipe(jade())
		.pipe(ngTemplates({
			module: 'mobie',
			standalone: false,
			filename: 'mobie.tpl.js'
		}))
		.pipe(gulp.dest('build'));
});

gulp.task('stylesheets', function () {
	sass('stylesheets/mobie.scss')
		.pipe(pleeease())
		.pipe(cssmin())
		.pipe(gulp.dest('build'));
});

gulp.task('stylesheets-brands', function () {
	var brands = [{
		name: 'primary',
		color: '#387ef5'
	}, {
		name: 'success',
		color: '#33cd5f'
	}, {
		name: 'info',
		color: '#ffc900'
	}, {
		name: 'danger',
		color: '#ef473a'
	}];
	var components = ['item', 'tabs', 'bar', 'range'];
	var files = [
		'stylesheets/templates/brands.template.scss'
	];
	var basePath = 'stylesheets/templates';
	_.forEach(components, function (componentName) {
		files.push(path.resolve(basePath, ['_' + componentName, 'template', 'scss'].join('.')));
	});

	gulp.src(files)
	.pipe(nunjucks({
		brands: brands,
		components: components
	}))
	.pipe(rename(function (path) {
		path.basename = path.basename.replace(/\.template/, '');
	}))
	.pipe(gulp.dest('stylesheets/brands')).on('end', function () {
		process.exit(0);
	});
});

var scriptsHeaderObj = {
	header: `(function (document, window, angular, undefined) { 'use strict';`,
	footer: `}(document, window, angular, undefined))`
};

gulp.task('scripts-min', function () {
	gulp.src(paths.scripts)
		.pipe(ngAnnotate())
		.pipe(uglify())
		.pipe(concat('mobie.min.js'))
		.pipe(wrapper(scriptsHeaderObj))
		.pipe(gulp.dest('build'));
});

gulp.task('jshint', function () {
	gulp.src(paths.scripts.concat(paths.docs.scripts))
		.pipe(jshint({ lookup: true }))
		.pipe(jshint.reporter());
});

gulp.task('scripts', ['scripts-min'], function () {
	gulp.src(paths.scripts)
		.pipe(ngAnnotate())
		.pipe(uglify({
			mangle: false,
			output: {
				beautify: true,
			}
		}))
		.pipe(concat('mobie.js'))
		.pipe(wrapper(scriptsHeaderObj))
		.pipe(gulp.dest('build'));
});

gulp.task('build', ['scripts', 'templates', 'stylesheets']);
gulp.task('default', ['build', 'livereload', 'watch'])<commit_msg>gulpfile.js: removed unnecessary brand colors, for we are using variables definition in templates<commit_after>var _ = require('lodash');
var log = require('gulp-util').log;
var path = require('path');
var gulp = require('gulp');
var jade = require('gulp-jade');
var sass = require('gulp-ruby-sass');
var bower = require('bower');
var Dgeni = require('dgeni');
var cssmin = require('gulp-cssmin');
var jshint = require('gulp-jshint');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var wrapper = require('gulp-wrapper');
var nunjucks = require('./nunjucks-build');
var pleeease = require('gulp-pleeease');
var ngAnnotate = require('gulp-ng-annotate');
var livereload = require('gulp-livereload');
var ngTemplates = require('gulp-ng-templates');

var paths = {
	templates: [
		'src/**/*.jade'
	],
	scripts: [
		'src/**/*.js',
		'!src/**/*_test.js'
	],
	stylesheets: ['stylesheets/**/*.scss'],
	docs: {
		scripts: ['docs/app/src/**/*.js'],
		assets: ['docs/app/assets/**/*.*'],
		templates: ['docs/app/src/**/*.html']
	}
};

gulp.task('docs-assets', function () {
	gulp.src(paths.docs.assets)
	.pipe(gulp.dest('build/docs'));
});

gulp.task('docs-scripts', function () {
	gulp.src(paths.docs.scripts)
	.pipe(ngAnnotate())
	.pipe(uglify())
	.pipe(concat('app.js'))
	.pipe(wrapper({
		header: `(function (window, angular, undefined) {`,
		footer: `}(window, angular, undefined));`
	}))
	.pipe(gulp.dest('build/docs/js'));
});

gulp.task('docs-mobie-build', function () {
	gulp.src([
		'build/mobie.js',
		'build/mobie.css',
		'build/mobie.tpl.js'
	])
	.pipe(gulp.dest('build/docs/lib'));
});

gulp.task('docs-deps', [
	'build',
	'docs-scripts',
	'docs-templates',
	'docs-assets',
	'docs-mobie-build'
], function (done) {
	var bowerTask = bower.commands.install([], {}, {
		directory: 'build/docs/lib'
	});

	bowerTask.on('log', function (result) {
		log('bower:', result.id, result.data.endpoint.name);
	});

	bowerTask.on('error', function (error) {
		log(error);
	});

	bowerTask.on('end', function () {
		done();
	});
});

gulp.task('docs-build', ['docs-deps'], function () {
	var dgeni = new Dgeni([require('./docs/config')])
	return dgeni.generate();
});

gulp.task('docs-livereload', function () {
	livereload.listen();
	gulp.watch([
		'build/docs/{js,css,partials}/*.{js,css,html}',
		'build/docs/lib/mobie.*'
	]).on('change', livereload.changed);
});

gulp.task('docs-stylesheets', function () {
	sass('./docs/app/scss/app.scss')
	.pipe(cssmin())
	.pipe(gulp.dest('build/docs/css'));
});

gulp.task('docs-watch', ['docs-livereload'], function () {
	gulp.watch('docs/app/scss/**/*.scss', ['docs-stylesheets']);
	gulp.watch('docs/app/src/**/*.js', ['docs-scripts']);
	gulp.watch('docs/app/src/**/*.{html,jade}', ['docs-templates']);
	gulp.watch('docs/config/**/*.{js,html}', ['docs-build']);

	gulp.watch(paths.scripts, ['scripts']);
	gulp.watch(paths.templates, ['templates']);
	gulp.watch(paths.stylesheets, ['stylesheets']);

	gulp.watch('build/mobie.*', ['docs-mobie-build']);
});

var express = require('express');
gulp.task('docs-serve', ['docs-watch'], function () {
	var app = express();
	app.use(express.static('build/docs'));
	app.get('/', function (req, res) {
		res.render('index.html');
	});
	app.listen(8080, function () {
		console.log('Documentation server is running at 0.0.0.0:8080');
	});
});

gulp.task('docs-templates', function () {
	gulp.src(['docs/app/src/**/*.mobile.jade'])
	.pipe(jade())
	.pipe(gulp.dest('build/docs'));

	gulp.src(paths.docs.templates)
	.pipe(ngTemplates({
		module: 'docsApp',
		standalone: false,
		filename: 'templates.js'
	}))
	.pipe(gulp.dest('build/docs/js'));
});

gulp.task('templates', function () {
	gulp.src(paths.templates)
		.pipe(jade())
		.pipe(ngTemplates({
			module: 'mobie',
			standalone: false,
			filename: 'mobie.tpl.js'
		}))
		.pipe(gulp.dest('build'));
});

gulp.task('stylesheets', function () {
	sass('stylesheets/mobie.scss')
		.pipe(pleeease())
		.pipe(cssmin())
		.pipe(gulp.dest('build'));
});

gulp.task('stylesheets-brands', function () {
	var brands = ['primary', 'success', 'danger', 'info'];
	var components = ['item', 'tabs', 'bar', 'range', 'button'];
	var files = [
		'stylesheets/templates/brands.template.scss'
	];
	var basePath = 'stylesheets/templates';
	_.forEach(components, function (componentName) {
		files.push(path.resolve(basePath, ['_' + componentName, 'template', 'scss'].join('.')));
	});

	gulp.src(files)
	.pipe(nunjucks({
		brands: brands,
		components: components
	}))
	.pipe(rename(function (path) {
		path.basename = path.basename.replace(/\.template/, '');
	}))
	.pipe(gulp.dest('stylesheets/brands')).on('end', function () {
		process.exit(0);
	});
});

var scriptsHeaderObj = {
	header: `(function (document, window, angular, undefined) { 'use strict';`,
	footer: `}(document, window, angular, undefined))`
};

gulp.task('scripts-min', function () {
	gulp.src(paths.scripts)
		.pipe(ngAnnotate())
		.pipe(uglify())
		.pipe(concat('mobie.min.js'))
		.pipe(wrapper(scriptsHeaderObj))
		.pipe(gulp.dest('build'));
});

gulp.task('jshint', function () {
	gulp.src(paths.scripts.concat(paths.docs.scripts))
		.pipe(jshint({ lookup: true }))
		.pipe(jshint.reporter());
});

gulp.task('scripts', ['scripts-min'], function () {
	gulp.src(paths.scripts)
		.pipe(ngAnnotate())
		.pipe(uglify({
			mangle: false,
			output: {
				beautify: true,
			}
		}))
		.pipe(concat('mobie.js'))
		.pipe(wrapper(scriptsHeaderObj))
		.pipe(gulp.dest('build'));
});

gulp.task('build', ['scripts', 'templates', 'stylesheets']);
gulp.task('default', ['build', 'livereload', 'watch'])<|endoftext|>


<commit_before>'use strict';

/*=====================================
=        Default Configuration        =
=====================================*/

// Please use config.js to override these selectively:

var config = {
  dest: 'www',
  minify_images: true,

  vendor: {
    js: [
      './bower_components/jquery/dist/jquery.js',
      './bower_components/modernizr/modernizr.js',
      './bower_components/angular/angular.js',
      './bower_components/angular-route/angular-route.js',
      './bower_components/angular-translate/angular-translate.js',
      './bower_components/angular-translate-loader-static-files/angular-translate-loader-static-files.js',
      './bower_components/mobile-angular-ui/dist/js/mobile-angular-ui.js',
      './bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
      './bower_components/angular-ui-select/dist/select.js',
      './bower_components/angular-elastic/elastic.js',
      './bower_components/angular-bindonce/bindonce.js',
      './bower_components/waypoints/waypoints.js',
      './bower_components/SHA-1/sha1.js',
      './bower_components/angulartics/src/angulartics.js',
      './bower_components/angulartics/src/angulartics-piwik.js',
      './bower_components/angular-swellrt/angular-swellrt.js',
      './bower_components/hammerjs/hammer.js',
      './bower_components/ryanmullins-angular-hammer/angular.hammer.js',
      './bower_components/angular-sanitize/angular-sanitize.js',
      './bower_components/angular-animate/angular-animate.js'
    ],

    fonts: [
      './bower_components/font-awesome/fonts/fontawesome-webfont.*',
      './src/fonts/*'
    ]
  },

  swellrt: {
    host: 'demo-swellrt.p2pvalue.eu',
    protocol: 'https://',
    // user and pass have to be credentials of an existing user in wave server
    user : 'test@local.net',
    pass : 'test',
    // WaveIds have to exist in wave server
    chatpadWaveId : 'local.net/gen+12345abcde1',
    communityListWaveId: 'local.net/gen+12345abcd2',
    docker: {
      name: 'pear2pear-swellrt'
    }
  },

  angularSwellrt: {
    path: './bower_components/angular-swellrt'
  },

  server: {
    host: '0.0.0.0',
    port: '8000'
  },

  serverTest: {
    host: '127.0.0.1',
    port: '9001'
  },

  weinre: {
    httpPort:     8001,
    boundHost:    'localhost',
    verbose:      false,
    debug:        false,
    readTimeout:  5,
    deathTimeout: 15
  },

  piwik: false,

  deploy: {
    branch: 'dist'
  }
};

if (require('fs').existsSync('./config.js')) {
  var configFn = require('./config');
  configFn(config);
}

// Build SwellRT url
if (! config.swellrt.server) {
  config.swellrt.server = config.swellrt.protocol + config.swellrt.host;
  if (config.swellrt.port) {
    config.swellrt.server += ':' + config.swellrt.port;
  }
}

// Setup angular-swellrt stuff, depending on path
config.vendor.js.push(config.angularSwellrt.path + '/angular-swellrt.js');
config.angularSwellrt.swellrt = require(config.angularSwellrt.path + '/swellrt.json');

// Fill docker options
if (config.swellrt.docker.host) {
  config.swellrt.docker.host = config.swellrt.host;
}

if (!config.swellrt.docker.tag) {
  config.swellrt.docker.tag = config.angularSwellrt.swellrt.version;
}

// Use configuration in other modules, such as Karma
module.exports.config = config;

/*-----  End of Configuration  ------*/

/*========================================
=            Requiring stuffs            =
========================================*/

var gulp           = require('gulp'),
  seq            = require('run-sequence'),
  connect        = require('gulp-connect'),
  sass           = require('gulp-sass'),
  uglify         = require('gulp-uglify'),
  sourcemaps     = require('gulp-sourcemaps'),
  cssmin         = require('gulp-cssmin'),
  order          = require('gulp-order'),
  concat         = require('gulp-concat'),
  ignore         = require('gulp-ignore'),
  rimraf         = require('gulp-rimraf'),
  imagemin       = require('gulp-imagemin'),
  pngcrush       = require('imagemin-pngcrush'),
  templateCache  = require('gulp-angular-templatecache'),
  mobilizer      = require('gulp-mobilizer'),
  ngAnnotate     = require('gulp-ng-annotate'),
  replace        = require('gulp-replace'),
  ngFilesort     = require('gulp-angular-filesort'),
  streamqueue    = require('streamqueue'),
  rename         = require('gulp-rename'),
  path           = require('path'),
  watch          = require('gulp-watch'),
  jshint         = require('gulp-jshint'),
  karma          = require('karma').server,
  angularProtractor = require('gulp-angular-protractor'),
  ghPages        = require('gulp-gh-pages'),
  dockerSwellrt  = require('gulp-docker-swellrt');

/*================================================
=            Report Errors to Console            =
================================================*/

gulp.on('error', function(e) {
  throw(e);
});

/*=========================================
=            Clean dest folder            =
=========================================*/

gulp.task('clean', function (cb) {
  return gulp.src([
    path.join(config.dest, 'index.html'),
    path.join(config.dest, 'images'),
    path.join(config.dest, 'css'),
    path.join(config.dest, 'js'),
    path.join(config.dest, 'fonts'),
    path.join(config.dest, 'l10n')
  ], { read: false })
 .pipe(rimraf());
});

/*==========================================
=            Start a web server            =
==========================================*/

gulp.task('connect', function() {
if (typeof config.server === 'object') {
  connect.server({
    root: config.dest,
    host: config.server.host,
    port: config.server.port,
    livereload: true
  });
} else {
  throw new Error('Connect is not configured');
}
});

/*==============================================================
=            Setup live reloading on source changes            =
==============================================================*/

gulp.task('livereload', function () {
gulp.src(path.join(config.dest, '*.html'))
  .pipe(connect.reload());
});

/*=====================================
=            Minify images            =
=====================================*/

gulp.task('images', function () {
  var stream = gulp.src('src/images/**/*');

  if (config.minify_images) {
    stream = stream.pipe(imagemin({
      progressive: true,
      svgoPlugins: [{removeViewBox: false}],
      use: [pngcrush()]
    }));
  }

  return stream.pipe(gulp.dest(path.join(config.dest, 'images')));
});

/*==================================
=            Copy fonts            =
==================================*/

gulp.task('fonts', function() {
  return gulp.src(config.vendor.fonts)
    .pipe(gulp.dest(path.join(config.dest, 'fonts')));
});

/*==================================
=            Copy l10n            =
==================================*/

gulp.task('l10n', function() {
  return gulp.src('src/l10n/**/*')
    .pipe(gulp.dest(path.join(config.dest, 'l10n')));
});

/*=================================================
=            Copy html files to dest              =
=================================================*/

gulp.task('html', function() {
  var inject = [];

  if (config.swellrt) {
    inject.push('');
    inject.push('');
  }

  if (config.piwik) {
    inject.push('');
    inject.push('

');
  }

  if (config.piwik) {
    inject.push('');
    inject.push('

');
  }

  if (typeof config.weinre === 'object') {
    inject.push('');
  }

  gulp.src(['src/html/**/*.html'])
  .pipe(replace('', inject.join('\n    ')))
  .pipe(gulp.dest(config.dest));
});

/*======================================================================
=            Compile, minify, mobilize Sass                            =
======================================================================*/

gulp.task('sass', function () {
  gulp.src('./src/sass/app.sass')
    .pipe(sourcemaps.init())
    .pipe(sass({
      includePaths: [ path.resolve(__dirname, 'src/sass'), path.resolve(__dirname, 'bower_components') ]
    }).on('error', sass.logError))
    /* Currently not working with sourcemaps
    .pipe(mobilizer('app.css', {
      'app.css': {
        hover: 'exclude',
        screens: ['0px']
      },
      'hover.css': {
        hover: 'only',
        screens: ['0px']
      }
    }))
    */
    .pipe(cssmin())
    .pipe(rename({suffix: '.min'}))
    .pipe(sourcemaps.write('.', {
      sourceMappingURLPrefix: '/css/'
    }))
    .pipe(gulp.dest(path.join(config.dest, 'css')));
});

/*====================================================================
=                             jshint                                 =
====================================================================*/

gulp.task('jshint', function() {
  return gulp.src('./src/js/**/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'));
});

/*====================================================================
=            Compile and minify js generating source maps            =
====================================================================*/
// - Orders ng deps automatically
// - Precompile templates to ng templateCache

gulp.task('js', function() {
    streamqueue({ objectMode: true },
      gulp.src(config.vendor.js),
      gulp.src('./src/js/**/*.js').pipe(ngFilesort()),
      gulp.src(['src/templates/**/*.html']).pipe(templateCache({ module: 'Pear2Pear' }))
    )
    .pipe(sourcemaps.init())
    .pipe(concat('app.js'))
    .pipe(ngAnnotate())
    .pipe(uglify())
    .pipe(rename({suffix: '.min'}))
    .pipe(sourcemaps.write('.', {
      sourceMappingURLPrefix: '/js/'
    }))
    .pipe(gulp.dest(path.join(config.dest, 'js')));
  });

/*===================================================================
=            Watch for source changes and rebuild/reload            =
===================================================================*/

gulp.task('watch', function () {
  if (typeof config.server === 'object') {
    watch([config.dest + '/**/*'], function() { gulp.start('livereload'); });
  }
  watch(['./src/html/**/*'], function() { gulp.start('html'); });
  watch(['./src/sass/**/*'], function() { gulp.start('sass'); });
  watch(config.vendor.js.concat(['./src/js/**/*', './src/templates/**/*']), function() { gulp.start(['jshint', 'js']); });
  watch(['./src/images/**/*'], function() { gulp.start('images'); });
  watch(['./src/l10n/**/*'], function() { gulp.start('l10n'); });
});

/*===================================================
=            Starts a Weinre Server                 =
===================================================*/

gulp.task('weinre', function() {
  if (typeof config.weinre === 'object') {
    var weinre = require('./node_modules/weinre/lib/weinre');
    weinre.run(config.weinre);
  } else {
    throw new Error('Weinre is not configured');
  }
});

/*======================================
=            Build Sequence            =
======================================*/

gulp.task('build', function(done) {
  var tasks = ['html', 'fonts', 'l10n', 'images', 'sass', 'js'];
  seq('clean', tasks, done);
});

/*====================================
=      Run SwellRT with Docker       =
====================================*/

gulp.task('docker:swellrt', function(done) {
  dockerSwellrt(config.swellrt.docker, done);
});

/*======================================
=        Unit testing with Karma       =
======================================*/

gulp.task('unit-test', function(done) {
  karma.start({
    configFile: __dirname + '/test/karma.conf.js',
    singleRun: true
  }, function() {
      done();
  });
});

/*================================================
=        End to end testing with protractor      =
=================================================*/

gulp.task('e2e-test', function(done) {
  connect.server({
    root: config.dest,
    host: config.serverTest.host,
    port: config.serverTest.port
  });

  gulp.src(['./test/e2e/**/*.js'])
    .pipe(angularProtractor({
      'configFile': 'test/protractor.conf.js',
      'autoStartStopServer': true,
      'debug': true
    }))
    .on('error', function(e) { connect.serverClose(); throw e; })
    .on('end', function() { connect.serverClose(); done(); });
});

/*====================================
=              Test Task             =
====================================*/

gulp.task('test', function(done){
  seq('docker:swellrt', 'unit-test', 'e2e-test', done);
});

/*====================================
=              Deploy Task           =
====================================*/

gulp.task('deploy', function() {
  return gulp.src('./www/**/*')
    .pipe(ghPages(config.deploy));
});

/*============================================
=         Continous Delivery Task            =
============================================*/

gulp.task('cd', function(done) {
  seq('build', 'test', 'deploy', done);
});

/*====================================
=            Default Task            =
====================================*/

gulp.task('default', function(done){
  var tasks = [];

  if (config.swellrt.docker) {
    tasks.push('docker:swellrt');
  }

  if (typeof config.weinre === 'object') {
    tasks.push('weinre');
  }

  if (typeof config.server === 'object') {
    tasks.push('connect');
  }

  tasks.push('watch');

  seq('build', tasks, done);
});
<commit_msg>Remove filling docker host<commit_after>'use strict';

/*=====================================
=        Default Configuration        =
=====================================*/

// Please use config.js to override these selectively:

var config = {
  dest: 'www',
  minify_images: true,

  vendor: {
    js: [
      './bower_components/jquery/dist/jquery.js',
      './bower_components/modernizr/modernizr.js',
      './bower_components/angular/angular.js',
      './bower_components/angular-route/angular-route.js',
      './bower_components/angular-translate/angular-translate.js',
      './bower_components/angular-translate-loader-static-files/angular-translate-loader-static-files.js',
      './bower_components/mobile-angular-ui/dist/js/mobile-angular-ui.js',
      './bower_components/angular-bootstrap/ui-bootstrap-tpls.js',
      './bower_components/angular-ui-select/dist/select.js',
      './bower_components/angular-elastic/elastic.js',
      './bower_components/angular-bindonce/bindonce.js',
      './bower_components/waypoints/waypoints.js',
      './bower_components/SHA-1/sha1.js',
      './bower_components/angulartics/src/angulartics.js',
      './bower_components/angulartics/src/angulartics-piwik.js',
      './bower_components/angular-swellrt/angular-swellrt.js',
      './bower_components/hammerjs/hammer.js',
      './bower_components/ryanmullins-angular-hammer/angular.hammer.js',
      './bower_components/angular-sanitize/angular-sanitize.js',
      './bower_components/angular-animate/angular-animate.js'
    ],

    fonts: [
      './bower_components/font-awesome/fonts/fontawesome-webfont.*',
      './src/fonts/*'
    ]
  },

  swellrt: {
    host: 'demo-swellrt.p2pvalue.eu',
    protocol: 'https://',
    // user and pass have to be credentials of an existing user in wave server
    user : 'test@local.net',
    pass : 'test',
    // WaveIds have to exist in wave server
    chatpadWaveId : 'local.net/gen+12345abcde1',
    communityListWaveId: 'local.net/gen+12345abcd2',
    docker: {
      name: 'pear2pear-swellrt'
    }
  },

  angularSwellrt: {
    path: './bower_components/angular-swellrt'
  },

  server: {
    host: '0.0.0.0',
    port: '8000'
  },

  serverTest: {
    host: '127.0.0.1',
    port: '9001'
  },

  weinre: {
    httpPort:     8001,
    boundHost:    'localhost',
    verbose:      false,
    debug:        false,
    readTimeout:  5,
    deathTimeout: 15
  },

  piwik: false,

  deploy: {
    branch: 'dist'
  }
};

if (require('fs').existsSync('./config.js')) {
  var configFn = require('./config');
  configFn(config);
}

// Build SwellRT url
if (! config.swellrt.server) {
  config.swellrt.server = config.swellrt.protocol + config.swellrt.host;
  if (config.swellrt.port) {
    config.swellrt.server += ':' + config.swellrt.port;
  }
}

// Setup angular-swellrt stuff, depending on path
config.vendor.js.push(config.angularSwellrt.path + '/angular-swellrt.js');
config.angularSwellrt.swellrt = require(config.angularSwellrt.path + '/swellrt.json');

// Fill docker options
if (!config.swellrt.docker.tag) {
  config.swellrt.docker.tag = config.angularSwellrt.swellrt.version;
}

// Use configuration in other modules, such as Karma
module.exports.config = config;

/*-----  End of Configuration  ------*/

/*========================================
=            Requiring stuffs            =
========================================*/

var gulp           = require('gulp'),
  seq            = require('run-sequence'),
  connect        = require('gulp-connect'),
  sass           = require('gulp-sass'),
  uglify         = require('gulp-uglify'),
  sourcemaps     = require('gulp-sourcemaps'),
  cssmin         = require('gulp-cssmin'),
  order          = require('gulp-order'),
  concat         = require('gulp-concat'),
  ignore         = require('gulp-ignore'),
  rimraf         = require('gulp-rimraf'),
  imagemin       = require('gulp-imagemin'),
  pngcrush       = require('imagemin-pngcrush'),
  templateCache  = require('gulp-angular-templatecache'),
  mobilizer      = require('gulp-mobilizer'),
  ngAnnotate     = require('gulp-ng-annotate'),
  replace        = require('gulp-replace'),
  ngFilesort     = require('gulp-angular-filesort'),
  streamqueue    = require('streamqueue'),
  rename         = require('gulp-rename'),
  path           = require('path'),
  watch          = require('gulp-watch'),
  jshint         = require('gulp-jshint'),
  karma          = require('karma').server,
  angularProtractor = require('gulp-angular-protractor'),
  ghPages        = require('gulp-gh-pages'),
  dockerSwellrt  = require('gulp-docker-swellrt');

/*================================================
=            Report Errors to Console            =
================================================*/

gulp.on('error', function(e) {
  throw(e);
});

/*=========================================
=            Clean dest folder            =
=========================================*/

gulp.task('clean', function (cb) {
  return gulp.src([
    path.join(config.dest, 'index.html'),
    path.join(config.dest, 'images'),
    path.join(config.dest, 'css'),
    path.join(config.dest, 'js'),
    path.join(config.dest, 'fonts'),
    path.join(config.dest, 'l10n')
  ], { read: false })
 .pipe(rimraf());
});

/*==========================================
=            Start a web server            =
==========================================*/

gulp.task('connect', function() {
if (typeof config.server === 'object') {
  connect.server({
    root: config.dest,
    host: config.server.host,
    port: config.server.port,
    livereload: true
  });
} else {
  throw new Error('Connect is not configured');
}
});

/*==============================================================
=            Setup live reloading on source changes            =
==============================================================*/

gulp.task('livereload', function () {
gulp.src(path.join(config.dest, '*.html'))
  .pipe(connect.reload());
});

/*=====================================
=            Minify images            =
=====================================*/

gulp.task('images', function () {
  var stream = gulp.src('src/images/**/*');

  if (config.minify_images) {
    stream = stream.pipe(imagemin({
      progressive: true,
      svgoPlugins: [{removeViewBox: false}],
      use: [pngcrush()]
    }));
  }

  return stream.pipe(gulp.dest(path.join(config.dest, 'images')));
});

/*==================================
=            Copy fonts            =
==================================*/

gulp.task('fonts', function() {
  return gulp.src(config.vendor.fonts)
    .pipe(gulp.dest(path.join(config.dest, 'fonts')));
});

/*==================================
=            Copy l10n            =
==================================*/

gulp.task('l10n', function() {
  return gulp.src('src/l10n/**/*')
    .pipe(gulp.dest(path.join(config.dest, 'l10n')));
});

/*=================================================
=            Copy html files to dest              =
=================================================*/

gulp.task('html', function() {
  var inject = [];

  if (config.swellrt) {
    inject.push('');
    inject.push('');
  }

  if (config.piwik) {
    inject.push('');
    inject.push('

');
  }

  if (config.piwik) {
    inject.push('');
    inject.push('

');
  }

  if (typeof config.weinre === 'object') {
    inject.push('');
  }

  gulp.src(['src/html/**/*.html'])
  .pipe(replace('', inject.join('\n    ')))
  .pipe(gulp.dest(config.dest));
});

/*======================================================================
=            Compile, minify, mobilize Sass                            =
======================================================================*/

gulp.task('sass', function () {
  gulp.src('./src/sass/app.sass')
    .pipe(sourcemaps.init())
    .pipe(sass({
      includePaths: [ path.resolve(__dirname, 'src/sass'), path.resolve(__dirname, 'bower_components') ]
    }).on('error', sass.logError))
    /* Currently not working with sourcemaps
    .pipe(mobilizer('app.css', {
      'app.css': {
        hover: 'exclude',
        screens: ['0px']
      },
      'hover.css': {
        hover: 'only',
        screens: ['0px']
      }
    }))
    */
    .pipe(cssmin())
    .pipe(rename({suffix: '.min'}))
    .pipe(sourcemaps.write('.', {
      sourceMappingURLPrefix: '/css/'
    }))
    .pipe(gulp.dest(path.join(config.dest, 'css')));
});

/*====================================================================
=                             jshint                                 =
====================================================================*/

gulp.task('jshint', function() {
  return gulp.src('./src/js/**/*.js')
    .pipe(jshint())
    .pipe(jshint.reporter('jshint-stylish'));
});

/*====================================================================
=            Compile and minify js generating source maps            =
====================================================================*/
// - Orders ng deps automatically
// - Precompile templates to ng templateCache

gulp.task('js', function() {
    streamqueue({ objectMode: true },
      gulp.src(config.vendor.js),
      gulp.src('./src/js/**/*.js').pipe(ngFilesort()),
      gulp.src(['src/templates/**/*.html']).pipe(templateCache({ module: 'Pear2Pear' }))
    )
    .pipe(sourcemaps.init())
    .pipe(concat('app.js'))
    .pipe(ngAnnotate())
    .pipe(uglify())
    .pipe(rename({suffix: '.min'}))
    .pipe(sourcemaps.write('.', {
      sourceMappingURLPrefix: '/js/'
    }))
    .pipe(gulp.dest(path.join(config.dest, 'js')));
  });

/*===================================================================
=            Watch for source changes and rebuild/reload            =
===================================================================*/

gulp.task('watch', function () {
  if (typeof config.server === 'object') {
    watch([config.dest + '/**/*'], function() { gulp.start('livereload'); });
  }
  watch(['./src/html/**/*'], function() { gulp.start('html'); });
  watch(['./src/sass/**/*'], function() { gulp.start('sass'); });
  watch(config.vendor.js.concat(['./src/js/**/*', './src/templates/**/*']), function() { gulp.start(['jshint', 'js']); });
  watch(['./src/images/**/*'], function() { gulp.start('images'); });
  watch(['./src/l10n/**/*'], function() { gulp.start('l10n'); });
});

/*===================================================
=            Starts a Weinre Server                 =
===================================================*/

gulp.task('weinre', function() {
  if (typeof config.weinre === 'object') {
    var weinre = require('./node_modules/weinre/lib/weinre');
    weinre.run(config.weinre);
  } else {
    throw new Error('Weinre is not configured');
  }
});

/*======================================
=            Build Sequence            =
======================================*/

gulp.task('build', function(done) {
  var tasks = ['html', 'fonts', 'l10n', 'images', 'sass', 'js'];
  seq('clean', tasks, done);
});

/*====================================
=      Run SwellRT with Docker       =
====================================*/

gulp.task('docker:swellrt', function(done) {
  dockerSwellrt(config.swellrt.docker, done);
});

/*======================================
=        Unit testing with Karma       =
======================================*/

gulp.task('unit-test', function(done) {
  karma.start({
    configFile: __dirname + '/test/karma.conf.js',
    singleRun: true
  }, function() {
      done();
  });
});

/*================================================
=        End to end testing with protractor      =
=================================================*/

gulp.task('e2e-test', function(done) {
  connect.server({
    root: config.dest,
    host: config.serverTest.host,
    port: config.serverTest.port
  });

  gulp.src(['./test/e2e/**/*.js'])
    .pipe(angularProtractor({
      'configFile': 'test/protractor.conf.js',
      'autoStartStopServer': true,
      'debug': true
    }))
    .on('error', function(e) { connect.serverClose(); throw e; })
    .on('end', function() { connect.serverClose(); done(); });
});

/*====================================
=              Test Task             =
====================================*/

gulp.task('test', function(done){
  seq('docker:swellrt', 'unit-test', 'e2e-test', done);
});

/*====================================
=              Deploy Task           =
====================================*/

gulp.task('deploy', function() {
  return gulp.src('./www/**/*')
    .pipe(ghPages(config.deploy));
});

/*============================================
=         Continous Delivery Task            =
============================================*/

gulp.task('cd', function(done) {
  seq('build', 'test', 'deploy', done);
});

/*====================================
=            Default Task            =
====================================*/

gulp.task('default', function(done){
  var tasks = [];

  if (config.swellrt.docker) {
    tasks.push('docker:swellrt');
  }

  if (typeof config.weinre === 'object') {
    tasks.push('weinre');
  }

  if (typeof config.server === 'object') {
    tasks.push('connect');
  }

  tasks.push('watch');

  seq('build', tasks, done);
});
<|endoftext|>