<commit_before>/*
 * grunt-contrib-jasmine
 * http://gruntjs.com/
 *
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  // node api
  var fs   = require('fs'),
    path = require('path'),
    resultsArr = [];

  // npm lib
  var phantomjs = require('grunt-lib-phantomjs').init(grunt);

  var childProcess = require('child_process');

  var _ = grunt.util._;

  function fetchOption(namespace, option, options, defaults) {
    if (Object.prototype.hasOwnProperty.call(options, namespace) && Object.prototype.hasOwnProperty.call(options[namespace], option)) {
      return options[namespace][option]
    } else if (Object.prototype.hasOwnProperty.call(defaults, namespace) && Object.prototype.hasOwnProperty.call(defaults[namespace], option)) {
      return defaults[namespace][option];
    } else {
      return undefined;
    }
  }

  grunt.registerMultiTask('yslow', 'Run Yslow headlessly through PhantomJS.', function() {

    var urls = this.data.files;
    var testCount = urls.length;
    var testsRun = 0;
    var logBufferArr = [], thresholdArr = [];
    var options = this.options({});

    var temp = testCount;

    while(temp--) {
      logBufferArr.push('');
      thresholdArr.push({
        thresholdWeight: null,
        thresholdRequests: null,
        thresholdScore: null,
        thresholdSpeed: null
      });
    }

    logWrite('Testing ' + testCount + ' URLs, this might take a few moments...\n\n');

    // This task is asynchronous.
    var done = this.async();

    var createPhantomRunner = function(i) {
      // console.log('createPhantomRunner', i);

      var url = urls[i].src[0];
      var data = urls[i];

      // setup thresholds
      thresholdArr[i].thresholdWeight = fetchOption('thresholds', 'weight', data, options);
      thresholdArr[i].thresholdRequests = fetchOption('thresholds', 'requests', data, options);
      thresholdArr[i].thresholdScore = fetchOption('thresholds', 'score', data, options);
      thresholdArr[i].thresholdSpeed = fetchOption('thresholds', 'speed', data, options);

      // get phantomjs binary, or depend on a global(/path) install if it can't be found
      var phantom, cmd;

      try {
        // Look up first
        phantom = require('phantomjs');
        cmd = phantom.path;
      } catch (e) {
        try {
          // Look down if that fails
          phantom = require(path.join(__dirname, '..', 'node_modules', 'grunt-lib-phantomjs', 'node_modules', 'phantomjs'));
          cmd = phantom.path;
        } catch (e) {
          // This should never happen since 'grunt-lib-phantomjs' would have enforced one of the above
          cmd = 'phantomjs';
        }
      }

      var phantomjsOptions = fetchOption('phantomjs', 'options', data, options);
      // creates a seperate scope for child variable
      cmd += ' ' + phantomjsOptions + ' node_modules/grunt-yslow/tasks/lib/yslow.js --info basic';

      // Add any custom parameters
      var userAgent = fetchOption('yslowOptions', 'userAgent', data, options);
      var cdns = fetchOption('yslowOptions', 'cdns', data, options);
      var viewport = fetchOption('yslowOptions', 'viewport', data, options);
      var headers = fetchOption('yslowOptions', 'headers', data, options);

      if (userAgent) {
        cmd += ' --ua "' + userAgent +'"';
      }
      if (cdns) {
        cmd += ' --cdns "' + cdns.join(',') +'"';
      }
      if (viewport) {
        cmd += ' --viewport "' + viewport + '"';
      }
      if (headers) {
        cmd += " --headers '" + JSON.stringify(headers) + "'";
      }
      cmd += ' ' + url;

      var child = childProcess.exec(cmd, [], function (err, stdout, stderr) {

          var results = JSON.parse(stdout);

          var str = '';

          str = logBuffer(str, _checkResult(thresholdArr[i].thresholdRequests >= results.r, thresholdArr[i].thresholdRequests + ' requests', 'Requests: ' + results.r));
          str = logBuffer(str, _checkResult(thresholdArr[i].thresholdScore <= results.o, thresholdArr[i].thresholdScore, 'YSlow score: ' + results.o + '/100'));
          str = logBuffer(str, _checkResult(thresholdArr[i].thresholdSpeed >= results.lt, thresholdArr[i].thresholdSpeed + 'ms', 'Page load time: ' + results.lt + 'ms'));
          str = logBuffer(str, _checkResult(thresholdArr[i].thresholdWeight >= (results.w/1000), thresholdArr[i].thresholdWeight + 'kb', 'Page weight: ' + (results.w/1000) + 'kb'));

          grunt.log.ok('\n');

          if (str.match(/\[FAIL\]/g)) {

            grunt.log.error('\n\n-----------------------------------------------' +
              '\nTest ' + (i+1) + ': ' + urls[i].src + ' \t  FAILED' +
            '\n-----------------------------------------------\n\n');

            grunt.log.error(str);

            done(false);

          } else {
            grunt.log.ok('\n\n-----------------------------------------------' +
              '\nTest ' + (i+1) + ': ' + urls[i].src +
            '\n-----------------------------------------------\n\n');

            grunt.log.ok(str);
          }
          testsRun++;
          if (testsRun >= testCount) {
            done();
          }

      });
    };

    for (var i=0; i<urls.length; i++) {
      createPhantomRunner(i);
    }

  });

  var _checkResult = function(res, threshold, msg) {
    if (res) {
      return msg + ' [PASS]';
    } else {
      return msg + ' [FAIL] threshold is ' + threshold;
    }
  };

  function logWrite(text, isInline) {

    text += (isInline ? '' : '\n');
    grunt.log.ok(text);
  }

  function logBuffer(str, text, isInline) {
    text += (isInline ? '' : '\n');
    return str + text;
  }

};
<commit_msg>Update tasks.js<commit_after>/*
 * grunt-contrib-jasmine
 * http://gruntjs.com/
 *
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  // node api
  var fs   = require('fs'),
    path = require('path'),
    resultsArr = [];

  // npm lib
  var phantomjs = require('grunt-lib-phantomjs').init(grunt);

  var childProcess = require('child_process');

  var _ = grunt.util._;

  function fetchOption(namespace, option, options, defaults) {
    if (Object.prototype.hasOwnProperty.call(options, namespace) && Object.prototype.hasOwnProperty.call(options[namespace], option)) {
      return options[namespace][option]
    } else if (Object.prototype.hasOwnProperty.call(defaults, namespace) && Object.prototype.hasOwnProperty.call(defaults[namespace], option)) {
      return defaults[namespace][option];
    } else {
      return undefined;
    }
  }

  grunt.registerMultiTask('yslow', 'Run Yslow headlessly through PhantomJS.', function() {

    var urls = this.data.files;
    var testCount = urls.length;
    var testsRun = 0;
    var logBufferArr = [], thresholdArr = [];
    var options = this.options({});

    var temp = testCount;

    while(temp--) {
      logBufferArr.push('');
      thresholdArr.push({
        thresholdWeight: null,
        thresholdRequests: null,
        thresholdScore: null,
        thresholdSpeed: null
      });
    }

    logWrite('Testing ' + testCount + ' URLs, this might take a few moments...\n\n');

    // This task is asynchronous.
    var done = this.async();

    var createPhantomRunner = function(i) {
      // console.log('createPhantomRunner', i);

      var url = urls[i].src[0];
      var data = urls[i];

      // setup thresholds
      thresholdArr[i].thresholdWeight = fetchOption('thresholds', 'weight', data, options);
      thresholdArr[i].thresholdRequests = fetchOption('thresholds', 'requests', data, options);
      thresholdArr[i].thresholdScore = fetchOption('thresholds', 'score', data, options);
      thresholdArr[i].thresholdSpeed = fetchOption('thresholds', 'speed', data, options);

      // get phantomjs binary, or depend on a global(/path) install if it can't be found
      var phantom, cmd;

      try {
        // Look up first
        phantom = require('phantomjs-prebuilt');
        cmd = phantom.path;
      } catch (e) {
        try {
          // Look down if that fails
          phantom = require(path.join(__dirname, '..', 'node_modules', 'grunt-lib-phantomjs', 'node_modules', 'phantomjs'));
          cmd = phantom.path;
        } catch (e) {
          // This should never happen since 'grunt-lib-phantomjs' would have enforced one of the above
          cmd = 'phantomjs';
        }
      }

      var phantomjsOptions = fetchOption('phantomjs', 'options', data, options);
      // creates a seperate scope for child variable
      cmd += ' ' + phantomjsOptions + ' node_modules/grunt-yslow/tasks/lib/yslow.js --info basic';

      // Add any custom parameters
      var userAgent = fetchOption('yslowOptions', 'userAgent', data, options);
      var cdns = fetchOption('yslowOptions', 'cdns', data, options);
      var viewport = fetchOption('yslowOptions', 'viewport', data, options);
      var headers = fetchOption('yslowOptions', 'headers', data, options);

      if (userAgent) {
        cmd += ' --ua "' + userAgent +'"';
      }
      if (cdns) {
        cmd += ' --cdns "' + cdns.join(',') +'"';
      }
      if (viewport) {
        cmd += ' --viewport "' + viewport + '"';
      }
      if (headers) {
        cmd += " --headers '" + JSON.stringify(headers) + "'";
      }
      cmd += ' ' + url;

      var child = childProcess.exec(cmd, [], function (err, stdout, stderr) {

          var results = JSON.parse(stdout);

          var str = '';

          str = logBuffer(str, _checkResult(thresholdArr[i].thresholdRequests >= results.r, thresholdArr[i].thresholdRequests + ' requests', 'Requests: ' + results.r));
          str = logBuffer(str, _checkResult(thresholdArr[i].thresholdScore <= results.o, thresholdArr[i].thresholdScore, 'YSlow score: ' + results.o + '/100'));
          str = logBuffer(str, _checkResult(thresholdArr[i].thresholdSpeed >= results.lt, thresholdArr[i].thresholdSpeed + 'ms', 'Page load time: ' + results.lt + 'ms'));
          str = logBuffer(str, _checkResult(thresholdArr[i].thresholdWeight >= (results.w/1000), thresholdArr[i].thresholdWeight + 'kb', 'Page weight: ' + (results.w/1000) + 'kb'));

          grunt.log.ok('\n');

          if (str.match(/\[FAIL\]/g)) {

            grunt.log.error('\n\n-----------------------------------------------' +
              '\nTest ' + (i+1) + ': ' + urls[i].src + ' \t  FAILED' +
            '\n-----------------------------------------------\n\n');

            grunt.log.error(str);

            done(false);

          } else {
            grunt.log.ok('\n\n-----------------------------------------------' +
              '\nTest ' + (i+1) + ': ' + urls[i].src +
            '\n-----------------------------------------------\n\n');

            grunt.log.ok(str);
          }
          testsRun++;
          if (testsRun >= testCount) {
            done();
          }

      });
    };

    for (var i=0; i<urls.length; i++) {
      createPhantomRunner(i);
    }

  });

  var _checkResult = function(res, threshold, msg) {
    if (res) {
      return msg + ' [PASS]';
    } else {
      return msg + ' [FAIL] threshold is ' + threshold;
    }
  };

  function logWrite(text, isInline) {

    text += (isInline ? '' : '\n');
    grunt.log.ok(text);
  }

  function logBuffer(str, text, isInline) {
    text += (isInline ? '' : '\n');
    return str + text;
  }

};
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();

var Config = require('./config');

var browserSync = require('browser-sync');
var reload = browserSync.reload;

var modRewrite = require('connect-modrewrite');
var rewriteRules = [
  '!\\.html|\\.xml|\\images|\\.js|\\.css|\\.png|\\.jpg|\\.woff|\\.ttf|\\.svg|\\.map /index.html [L]'
];

gulp.task('server:dist', function() {
  browserSync({
    port: 9000,
    notify: false,
    logPrefix: 'www.secxbrl.info',
    open: false,
    server: {
      baseDir: ['dist'],
      middleware: [
        modRewrite(rewriteRules)
      ]
    }
  });
});

//run the server after having built generated files, and watch for changes
gulp.task('server:dev', function() {
  browserSync({
    port: 9000,
    notify: false,
    logPrefix: 'www.secxbrl.info',
    server: {
      baseDir: ['.', Config.paths.app],
      middleware: [
        modRewrite(rewriteRules)
      ]
    },
    browser: 'default'
  });

  gulp.watch(Config.paths.html, reload);
  gulp.watch(Config.less, ['less', reload]);
  gulp.watch(Config.paths.js, reload);
  gulp.watch(Config.paths.json, ['jsonlint']);
});

gulp.task('server:stop', browserSync.exit);

/* jshint camelcase:false*/
//var webdriverStandalone = require('gulp-protractor').webdriver_standalone;
var webdriverUpdate = require('gulp-protractor').webdriver_update;

var Config = require('./config');

var protractorConfig = require('../tests/e2e/config/protractor-shared-conf.js');

//update webdriver if necessary, this task will be used by e2e task
gulp.task('webdriver:update', webdriverUpdate);

// Run e2e tests using protractor, make sure serve task is running.
gulp.task('test:e2e', ['webdriver:update'], function() {
  var configs = {
    prod: 'tests/e2e/config/protractor-travis-nosaucelabs-conf.js',
    ci: 'tests/e2e/config/protractor-travis-nosaucelabs-conf.js',
    dev: 'tests/e2e/config/protractor-conf.js'
  };

  var configFile = Config.isOnTravis ? configs.prod : configs.dev;

  return gulp.src(protractorConfig.config.specs)
    .pipe($.protractor.protractor({
      configFile: configFile
    }))
    .on('error', function(e) {
      console.error(e);
      process.exit(1);
    });
});

gulp.task('test:unit', function (done) {
    var karma = require('karma').server;
    karma.start({
        configFile: __dirname + '/../karma.conf.js',
        singleRun: true
    }, done);
});
<commit_msg>Run e2e tests against the s3 deployment<commit_after>'use strict';

var gulp = require('gulp');
var $ = require('gulp-load-plugins')();

var Config = require('./config');

var browserSync = require('browser-sync');
var reload = browserSync.reload;

var modRewrite = require('connect-modrewrite');
var rewriteRules = [
  '!\\.html|\\.xml|\\images|\\.js|\\.css|\\.png|\\.jpg|\\.woff|\\.ttf|\\.svg|\\.map /index.html [L]'
];

gulp.task('server:dist', function() {
  browserSync({
    port: 9000,
    notify: false,
    logPrefix: 'www.secxbrl.info',
    open: false,
    server: {
      baseDir: ['dist'],
      middleware: [
        modRewrite(rewriteRules)
      ]
    }
  });
});

//run the server after having built generated files, and watch for changes
gulp.task('server:dev', function() {
  browserSync({
    port: 9000,
    notify: false,
    logPrefix: 'www.secxbrl.info',
    server: {
      baseDir: ['.', Config.paths.app],
      middleware: [
        modRewrite(rewriteRules)
      ]
    },
    browser: 'default'
  });

  gulp.watch(Config.paths.html, reload);
  gulp.watch(Config.less, ['less', reload]);
  gulp.watch(Config.paths.js, reload);
  gulp.watch(Config.paths.json, ['jsonlint']);
});

gulp.task('server:stop', browserSync.exit);

/* jshint camelcase:false*/
//var webdriverStandalone = require('gulp-protractor').webdriver_standalone;
var webdriverUpdate = require('gulp-protractor').webdriver_update;

var Config = require('./config');

var protractorConfig = require('../tests/e2e/config/protractor-shared-conf.js');

//update webdriver if necessary, this task will be used by e2e task
gulp.task('webdriver:update', webdriverUpdate);

// Run e2e tests using protractor, make sure serve task is running.
gulp.task('test:e2e', ['webdriver:update'], function() {
  var configs = {
    travis: 'tests/e2e/config/protractor-travis-nosaucelabs-conf.js',
    local: 'tests/e2e/config/protractor-conf.js'
  };

  var configFile = Config.isOnTravis ? configs.travis : configs.local;
  var args = [];
  if(Config.isOnTravis) {
      args.push('--baseUrl');
      args.push('http://' + Config.bucketName + '.s3-website-us-east-1.amazonaws.com');
  }
  return gulp.src(protractorConfig.config.specs)
    .pipe($.protractor.protractor({
      configFile: configFile,
          args: args
    }))
    .on('error', function(e) {
      console.error(e);
      process.exit(1);
    });
});

gulp.task('test:unit', function (done) {
    var karma = require('karma').server;
    karma.start({
        configFile: __dirname + '/../karma.conf.js',
        singleRun: true
    }, done);
});
<|endoftext|>


<commit_before>/*
 * grunt-assets-wp
 * https://github.com/hariadi/grunt-assets-wp
 *
 * Base from:
 * https://github.com/roots/roots/blob/master/tasks/version.js
 * https://github.com/yeoman/grunt-filerev
 *
 * Copyright (c) 2013 Hariadi Hinta
 * Licensed under the MIT license.
 */
'use strict';

var fs = require('fs')
  , path = require('path')
  , crypto = require('crypto');

module.exports = function(grunt) {

  grunt.registerMultiTask('wprev', 'WordPress assets revving', function() {

    var dest = this.data.dest
      , options = this.options({
          encoding: 'utf8',
          algorithm: 'md5',
          format: true,
          length: 4,
          rename: false
        });

    this.files.forEach(function(files) {

      files.src.forEach(function (file) {

        if (file.length === 0) {
          grunt.log.warn('src does not exists');
          return false;
        }

        var basename = path.basename
          , name = basename(file)
          , content = grunt.file.read(file)
          , hash = crypto.createHash(options.algorithm).update(content, options.encoding).digest('hex')
          , suffix = hash.slice(0, options.length)
          , ext = path.extname(file)
          , newName = options.format ? [suffix, basename(file, ext), ext.slice(1)].join('.') : [basename(file, ext), suffix, ext.slice(1)].join('.');

        // Copy/rename file base on hash and format
        var resultPath = path.resolve(path.dirname(file), newName);
        if (options.rename) {
          fs.renameSync(file, resultPath);
        } else {
          grunt.file.copy(file, resultPath);
        }

        // Get target, find and change references assets to new hashed.
        var wpcontent = grunt.file.read(dest)
          , match = new RegExp('[a-z0-9]{'+ options.length +'}.' + name, "g")
          , re = ( match.test(wpcontent) ) ? match : new RegExp(name, "g");
        wpcontent = wpcontent.replace(re, newName);

        grunt.file.write(dest, wpcontent);
        grunt.log.writeln('  ' + file.grey + (' changed to ') + newName.green);
      });
    });
  });
};<commit_msg>Better status.<commit_after>/*
 * grunt-assets-wp
 * https://github.com/hariadi/grunt-assets-wp
 *
 * Base from:
 * https://github.com/roots/roots/blob/master/tasks/version.js
 * https://github.com/yeoman/grunt-filerev
 *
 * Copyright (c) 2013 Hariadi Hinta
 * Licensed under the MIT license.
 */
'use strict';

var fs = require('fs')
  , path = require('path')
  , crypto = require('crypto');

module.exports = function(grunt) {

  grunt.registerMultiTask('wprev', 'WordPress assets revving', function() {

    var dest = this.data.dest
      , options = this.options({
          encoding: 'utf8',
          algorithm: 'md5',
          format: true,
          length: 4,
          rename: false
        });

    this.files.forEach(function(files) {

      files.src.forEach(function (file) {

        if (file.length === 0) {
          grunt.log.warn('src does not exists');
          return false;
        }

        var basename = path.basename
          , name = basename(file)
          , content = grunt.file.read(file)
          , hash = crypto.createHash(options.algorithm).update(content, options.encoding).digest('hex')
          , suffix = hash.slice(0, options.length)
          , ext = path.extname(file)
          , newName = options.format ? [suffix, basename(file, ext), ext.slice(1)].join('.') : [basename(file, ext), suffix, ext.slice(1)].join('.');

        // Copy/rename file base on hash and format
        var resultPath = path.resolve(path.dirname(file), newName);
        if (options.rename) {
          fs.renameSync(file, resultPath);
        } else {
          grunt.file.copy(file, resultPath);
        }

        // Get target, find and change references assets to new hashed.
        var wpcontent = grunt.file.read(dest)
          , match = new RegExp('[a-z0-9]{'+ options.length +'}.' + name, "g")
          , re = ( match.test(wpcontent) ) ? match : new RegExp(name, "g");
        wpcontent = wpcontent.replace(re, newName);

        grunt.file.write(dest, wpcontent);
        var status = (options.rename) ? ' rename' : ' change';
        grunt.log.writeln('  ' + file.grey + status + ' to ' + newName.green);
      });
    });
  });
};<|endoftext|>


<commit_before>/*
 * Filename: documentations.js
 */
var DocumentationsDocumentation = require(__dirname+'/documentation.js');

var self = this; // Set the context locally, for access protection

/**
 * Create a new Documentations that let users create sub-documentations.
 * @return {Documentations}
 */
function Documentations() {
  self._proxies = {}; // Will be set
  self._filepath = ''; // Will be set
  self._filename = ''; // Will be set
  self._title = 'Documentations'; // Will be set
}

Documentations.prototype.proxies = function() {
  return self._proxies;
}

Documentations.prototype.setproxies = function(fnOrValue) {
  self._proxies = fnOrValue;
}

Documentations.prototype.filepath = function() {
  return self._filepath;
}

Documentations.prototype.setfilepath = function(fnOrValue) {
  self._filepath = fnOrValue;
}

Documentations.prototype.filename = function() {
  return self._filename;
}

Documentations.prototype.setfilename = function(fnOrValue) {
  self._filename = fnOrValue;
}

Documentations.prototype.title = function() {
  return self._title;
}

Documentations.prototype.settitle = function(fnOrValue) {
  self._title = fnOrValue;
}

/**
 * Create a new DocumentationsDocumentation object.
 * @return {DocumentationsDocumentation}
 */
Documentations.prototype.documentation = function() {
  console.log('documentations documentation called')
  var _document = 'documentation.html';
  var _directory = 'documentation';
  var _proxies = this.proxies();
  var _filepath = this.filepath();
  var _title = this.title();
  var _linktitle = 'Documentation';

  console.log('documentations documentation ++++ CHECKPOINT 111')

  var _path = _proxies().proxy().libraries().library().path();

  console.log('documentations documentation ++++ CHECKPOINT 222')

  this._documentationsdocumentation = new DocumentationsDocumentation();
  this._documentationsdocumentation.setfilename(_document);
  this._documentationsdocumentation.setfilepath(_path.join(_filepath, _directory));
  this._documentationsdocumentation.setproxies(_proxies);
  this._documentationsdocumentation.append = this.append();
  this._documentationsdocumentation.buildHtml = this.buildHtml();
  this._documentationsdocumentation.ensureExists = this.ensureExists();
  this._documentationsdocumentation.append('<title>' + _title + '</title>','
' + _title + '

' + _linktitle + '

');
  return this._documentationsdocumentation;
}

Documentations.prototype.append = function(header, body) {
  console.log('documentations append called')
  var _header = typeof header !== 'undefined' ? header : '';
  var _body = typeof body !== 'undefined' ? body : '';
  var _proxies = this.proxies();
  var _filepath = this.filepath();
  var _filename = this.filename();
  // temporarily we do all the file creation and appending in here
  // move most of this logic out to its best location. e.g. at documentation level

  console.log('documentations - append(header, body) +++++++ CHECKPOINT 000');

  var _path = _proxies().proxy().libraries().library().path();

  console.log('documentations - append(header, body) +++++++ CHECKPOINT 001');

  var filePathAndName = _path.join(_filepath, _filename);

  var _buildHtml = this.buildHtml(_header, _body);

  console.log('documentations - append(header, body) +++++++ CHECKPOINT 003');

  this.ensureExists(_filepath, 0744, function(err) {
    if (err) { // handle folder creation error
      console.log('documentations - error', err)
    }
    else { // we're all good
      //var fs = _proxies.proxy().libraries().library().fs(); // DOESN'T WORK!!
      var fs = require('fs');
      var stream = fs.createWriteStream(filePathAndName);
      stream.once('open', function(fd) {
        var html = _buildHtml;

        stream.end(html);
      });
    }
  });

  console.log('documentations - append(header, body) +++++++ CHECKPOINT 004');
}

Documentations.prototype.buildHtml = function(head, body) {
  console.log('documentations - buildHtml(head, body) called')
  var head = typeof head !== 'undefined' ? head : '';
  var body = typeof body !== 'undefined' ? body : '';
  // concatenate head string
  // concatenate body string

  // START OF TEST AREA
  var _proxies = this.proxies();
  // var _jsdom = _proxies().proxy().libraries().library().jsdom(); // DOESN'T WORK!!
  var _jsdom = require('jsdom');

  var _document = _jsdom.jsdom().implementation.createHTMLDocument('');
  _document.head.append(head);
  _document.body.append(body);
  //For example: _document.body.setAttribute('onscroll', 'foo');

  console.log('documentations - buildHtml(head, body) _document: ', _document)

  // END OF TEST AREA

  return '<!DOCTYPE html>'
       + '' + head + '' + body + '';
};

// This function is documented here:
// http://lmws.net/making-directory-along-with-missing-parents-in-node-js
Documentations.prototype.ensureExists = function(path, mask, callback) {
  console.log('documentations - ensureExists(path, mask, callback) called')
  console.log('documentations - ensureExists: path: ', path)
  console.log('documentations - ensureExists: mask: ', mask)
  if (typeof mask == 'function') { // Allow the `mask` parameter to be optional
    callback = mask;
    mask = 0777; // Read and Write permissions
  }
  var fs = require('fs');
  fs.mkdir(path, mask, function(error) {
    if (error) {
      if (error.code == 'EEXIST') {
      	// Ignore the error if the folder already exists
      	callback(null);
      }
      else {
      	// Something else went wrong
        // When it fail in this way, do the custom steps
        if (error && error.errno === 34) {
          // Create all the parents recursively
          fs.mkdirParent(path.dirname(dirPath), mode, callback);
          // And then the directory
          fs.mkdirParent(dirPath, mode, callback);
        }
        // Manually run the callback since we used our own callback to do all these
        callback && callback(error);
      }
    }
    else {
      // Successfully created folder
      callback(null);
    }
  });
};

module.exports = Documentations;
<commit_msg>Modified<commit_after>/*
 * Filename: documentations.js
 */
var DocumentationsDocumentation = require(__dirname+'/documentation.js');

var self = this; // Set the context locally, for access protection

/**
 * Create a new Documentations that let users create sub-documentations.
 * @return {Documentations}
 */
function Documentations() {
  self._proxies = {}; // Will be set
  self._filepath = ''; // Will be set
  self._filename = ''; // Will be set
  self._title = 'Documentations'; // Will be set
}

Documentations.prototype.proxies = function() {
  return self._proxies;
}

Documentations.prototype.setproxies = function(fnOrValue) {
  self._proxies = fnOrValue;
}

Documentations.prototype.filepath = function() {
  return self._filepath;
}

Documentations.prototype.setfilepath = function(fnOrValue) {
  self._filepath = fnOrValue;
}

Documentations.prototype.filename = function() {
  return self._filename;
}

Documentations.prototype.setfilename = function(fnOrValue) {
  self._filename = fnOrValue;
}

Documentations.prototype.title = function() {
  return self._title;
}

Documentations.prototype.settitle = function(fnOrValue) {
  self._title = fnOrValue;
}

/**
 * Create a new DocumentationsDocumentation object.
 * @return {DocumentationsDocumentation}
 */
Documentations.prototype.documentation = function() {
  console.log('documentations documentation called')
  var _document = 'documentation.html';
  var _directory = 'documentation';
  var _proxies = this.proxies();
  var _filepath = this.filepath();
  var _title = this.title();
  var _linktitle = 'Documentation';

  console.log('documentations documentation ++++ CHECKPOINT 111')

  var _path = _proxies().proxy().libraries().library().path();

  console.log('documentations documentation ++++ CHECKPOINT 222')

  this._documentationsdocumentation = new DocumentationsDocumentation();
  this._documentationsdocumentation.setfilename(_document);
  this._documentationsdocumentation.setfilepath(_path.join(_filepath, _directory));
  this._documentationsdocumentation.setproxies(_proxies);
  this._documentationsdocumentation.append = this.append();
  this._documentationsdocumentation.buildHtml = this.buildHtml();
  this._documentationsdocumentation.ensureExists = this.ensureExists();

  // START TEST AREA
  // var _jsdom = _proxies().proxy().libraries().library().jsdom(); // DOESN'T WORK!!
  var _jsdom = require('jsdom');

  var _document = _jsdom.jsdom().implementation.createHTMLDocument('');
  var _script = _document.createElement("script");

  // Create a Node that contains the Title to go into the Head of the HTML Document
  var _title = _document.createElement("title");
  console.log('+++++++++++++++++++++++++++++++ _title: ', _title)

  // Create a Node that contains the Links to go into the Body of the HTML Document
  var _ul = _document.createElement("ul");
  console.log('+++++++++++++++++++++++++++++++ _ul: ', _ul)

  // END TEST AREA

  this._documentationsdocumentation.append('<title>' + _title + '</title>','
' + _title + '

' + _linktitle + '

');
  return this._documentationsdocumentation;
}

Documentations.prototype.append = function(header, body) {
  console.log('documentations append called')
  var _header = typeof header !== 'undefined' ? header : '';
  var _body = typeof body !== 'undefined' ? body : '';
  var _proxies = this.proxies();
  var _filepath = this.filepath();
  var _filename = this.filename();
  // temporarily we do all the file creation and appending in here
  // move most of this logic out to its best location. e.g. at documentation level

  console.log('documentations - append(header, body) +++++++ CHECKPOINT 000');

  var _path = _proxies().proxy().libraries().library().path();

  console.log('documentations - append(header, body) +++++++ CHECKPOINT 001');

  var filePathAndName = _path.join(_filepath, _filename);

  var _buildHtml = this.buildHtml(_header, _body);

  console.log('documentations - append(header, body) +++++++ CHECKPOINT 003');

  this.ensureExists(_filepath, 0744, function(err) {
    if (err) { // handle folder creation error
      console.log('documentations - error', err)
    }
    else { // we're all good
      //var fs = _proxies.proxy().libraries().library().fs(); // DOESN'T WORK!!
      var fs = require('fs');
      var stream = fs.createWriteStream(filePathAndName);
      stream.once('open', function(fd) {
        var html = _buildHtml;

        stream.end(html);
      });
    }
  });
  console.log('documentations - append(header, body) +++++++ CHECKPOINT 004');
}

Documentations.prototype.buildHtml = function(head, body) {
  console.log('documentations - buildHtml(head, body) called')
  var head = typeof head !== 'undefined' ? head : '';
  var body = typeof body !== 'undefined' ? body : '';
  // concatenate head string
  // concatenate body string

  // START OF TEST AREA
  var _proxies = this.proxies();
  // var _jsdom = _proxies().proxy().libraries().library().jsdom(); // DOESN'T WORK!!
  var _jsdom = require('jsdom');

  var _document = _jsdom.jsdom().implementation.createHTMLDocument('');
  //_document.head.appendChild(head);
  //_document.body.appendChild(body);
  //For example: _document.body.setAttribute('onscroll', 'foo');

  console.log('documentations - buildHtml(head, body) _document: ', _document)

  // END OF TEST AREA

  return '<!DOCTYPE html>'
       + '' + head + '' + body + '';
};

// This function is documented here:
// http://lmws.net/making-directory-along-with-missing-parents-in-node-js
Documentations.prototype.ensureExists = function(path, mask, callback) {
  console.log('documentations - ensureExists(path, mask, callback) called')
  console.log('documentations - ensureExists: path: ', path)
  console.log('documentations - ensureExists: mask: ', mask)
  if (typeof mask == 'function') { // Allow the `mask` parameter to be optional
    callback = mask;
    mask = 0777; // Read and Write permissions
  }
  var fs = require('fs');
  fs.mkdir(path, mask, function(error) {
    if (error) {
      if (error.code == 'EEXIST') {
      	// Ignore the error if the folder already exists
      	callback(null);
      }
      else {
      	// Something else went wrong
        // When it fail in this way, do the custom steps
        if (error && error.errno === 34) {
          // Create all the parents recursively
          fs.mkdirParent(path.dirname(dirPath), mode, callback);
          // And then the directory
          fs.mkdirParent(dirPath, mode, callback);
        }
        // Manually run the callback since we used our own callback to do all these
        callback && callback(error);
      }
    }
    else {
      // Successfully created folder
      callback(null);
    }
  });
};

module.exports = Documentations;
<|endoftext|>


<commit_before>//var async = require('async');
var express = require('express');
var app = express();

var util = require('util');
var eep = require('eep');

var heatingTimeout = null;

var Heating = require('./lib/heating');
var heating = new Heating();

var DEFAULT_TIMER = 1; // TODO REVIEW!!!!

var BASE_LINE_TEMP = 20;
var BASE_LINE_TOLERANCE = 0.1;

var monotonics = {};
var monotonic_avg = eep.EventWorld.make().windows().monotonic(eep.Stats.all, new eep.CountingClock());
monotonic_avg.on('emit', function(values) {
  var hi_temp = BASE_LINE_TEMP + BASE_LINE_TOLERANCE;
  var lo_temp = BASE_LINE_TEMP - BASE_LINE_TOLERANCE;

  if (values['mean'] != 0) {
    console.log("AVG (all) => " + JSON.stringify(values));
    if (values['mean'] != 0) {
      if (values['mean'] < lo_temp ) {
        console.log("turn ON heating! " + values['mean'] + ' <= ' + lo_temp);
        turnOnHeating();
      } else if (values['mean'] > hi_temp) {
        console.log("turn OFF heating! " + values['mean'] + ' > ' + hi_temp);
        turnOffHeating();
      } else {
        console.log('Do nothing! ' + lo_temp + ' <= ' + values['mean'] + ' <= ' + hi_temp);
      }
    }
  }
});

var intervalTickAvg = setInterval(monotonic_avg.tick, 10000);

function tickMonotonics() {
  for (var i in monotonics) {
    monotonics[i].tick();
  }
}
var intervalTick = setInterval(tickMonotonics, 5000);

// Deal with the temperature values
function manageTemperatureMeasurement (sensorId, temp, presence) {
  if (monotonics[sensorId]) {
    //// Your business logic here!
  } else {
    monotonics[sensorId] = eep.EventWorld.make().windows().monotonic(eep.Stats.all, new eep.CountingClock());
    monotonics[sensorId].on('emit', function(values) {
      if (values['mean'] != 0) {
        console.log("id: " + sensorId + " => " + JSON.stringify(values));
        monotonic_avg.enqueue(values['mean']);
      }
    });
  }

  // Enqueue data on corresponding window
  monotonics[sensorId].enqueue(temp);
}

function turnOnHeating (minutes) {
  if (typeof minutes === 'undefined' || minutes < 0) {
     minutes = DEFAULT_TIMER;
  }

  // Set a timout for X minutes, calcel previous timer
  if (heatingTimeout) {
    clearTimeout(heatingTimeout);
  }

  heatingTimeout = setTimeout(function() {
    console.log('FINER: time out reached!');
    // Stop the heating
    heating.off ();
  }, minutes * 60 * 1000);

  // turn on the heating
  heating.on();
}

function turnOffHeating () {
  // clear timer
  clearTimeout(heatingTimeout);

  // turn off the heating
  heating.off();
}

// temp measurement
app.get('/temp/:sensorId/:temp/:presence', function (req, res) {
  var temp = new Number(req.params.temp);
  var presence = req.params.presence == "true";
  var sensorId = req.params.sensorId;

  manageTemperatureMeasurement(sensorId, temp, presence);

  res.send({ name: req.params.sensorId, temp: req.params.temp });
});

// temp measurement
app.get('/temp/:sensorId/:temp', function (req, res) {
  var temp = new Number(req.params.temp);
  var presence = false;
  var sensorId = req.params.sensorId;

  manageTemperatureMeasurement(sensorId, temp, presence);

  res.send({ name: req.params.sensorId, temp: req.params.temp });
});

// Heting command: on/off
app.put('/heating/:cmd/:minutes*?', function (req, res) {
  var cmd = req.params.cmd;
  var minutes = req.params.minutes;
  console.log('FINE: /heating/' + cmd + '/' + minutes);
  if (typeof minutes === 'undefined') {
     minutes = DEFAULT_TIMER;
  }

  var resp = null, desc = null;
  if (cmd == 'on' || cmd == 'ON') {
      if (minutes > 0) {
        turnOnHeating (minutes);
        resp = 'ACK';
        desc = 'Heating ON';
      } else {
        // Bad cmd
        resp = 'NACK';
        desc = 'Bad command: ' + cmd + ' minutes: ' + minutes;
      }
  } else if (cmd == 'off' || cmd == 'OFF') {
      turnOffHeating ();
      resp = 'ACK';
      desc = 'Heating OFF';
  } else {
      // Bad cmd
      resp = 'NACK';
      desc = 'Bad command: ' + cmd + ' minutes: ' + minutes;
  }

  res.send({ cmd: cmd, resp: resp, desc: desc });
});

// Heting command: on/off
app.get('/heating/status', function (req, res) {
  var response = null, desc = null;
  var resp = null, desc = null;
  var status = heating.status();
  resp = 'ACK';
  desc = 'Heating ' + (status == 1 ? 'ON' : 'OFF');

  res.send({ status: status, resp: resp, desc: desc });
});

app.listen(3000);
<commit_msg>Adding Heating module<commit_after>//var async = require('async');
var express = require('express');
var app = express();

var util = require('util');
var eep = require('eep');

var heatingTimeout = null;

var Heating = require('./lib/heating');
var heating = new Heating();

var DEFAULT_TIMER = 1; // TODO REVIEW!!!!

var BASE_LINE_TEMP = 20;
var BASE_LINE_TOLERANCE = 0.1;

var monotonics = {};
var monotonic_avg = eep.EventWorld.make().windows().monotonic(eep.Stats.all, new eep.CountingClock());
monotonic_avg.on('emit', function(values) {
  var hi_temp = BASE_LINE_TEMP + BASE_LINE_TOLERANCE;
  var lo_temp = BASE_LINE_TEMP - BASE_LINE_TOLERANCE;

  if (values['mean'] != 0) {
    console.log("AVG (all) => " + JSON.stringify(values));
    if (values['mean'] != 0) {
      if (values['mean'] < lo_temp ) {
        console.log("turn ON heating! " + values['mean'] + ' <= ' + lo_temp);
        turnOnHeating();
      } else if (values['mean'] > hi_temp) {
        console.log("turn OFF heating! " + values['mean'] + ' > ' + hi_temp);
        turnOffHeating();
      } else {
        console.log('Do nothing! ' + lo_temp + ' <= ' + values['mean'] + ' <= ' + hi_temp);
      }
    }
  }
});

var intervalTickAvg = setInterval(monotonic_avg.tick, 10000);

function tickMonotonics() {
  for (var i in monotonics) {
    monotonics[i].tick();
  }
}
var intervalTick = setInterval(tickMonotonics, 5000);

// Deal with the temperature values
function manageTemperatureMeasurement (sensorId, temp, presence) {
  if (monotonics[sensorId]) {
    //// Your business logic here!
  } else {
    monotonics[sensorId] = eep.EventWorld.make().windows().monotonic(eep.Stats.all, new eep.CountingClock());
    monotonics[sensorId].on('emit', function(values) {
      if (values['mean'] != 0) {
        console.log("id: " + sensorId + " => " + JSON.stringify(values));
        monotonic_avg.enqueue(values['mean']);
      }
    });
  }

  // Enqueue data on corresponding window
  monotonics[sensorId].enqueue(temp);
}

function turnOnHeating (minutes) {
  if (typeof minutes === 'undefined' || minutes < 0) {
     minutes = DEFAULT_TIMER;
  }

  // Set a timout for X minutes, calcel previous timer
  if (heatingTimeout) {
    clearTimeout(heatingTimeout);
  }

  heatingTimeout = setTimeout(function() {
    console.log('FINER: time out reached!');
    // Stop the heating
    heating.off ();
  }, minutes * 60 * 1000);

  // turn on the heating
  heating.on();
}

function turnOffHeating () {
  // clear timer
  clearTimeout(heatingTimeout);

  // turn off the heating
  heating.off();
}

// temp measurement
app.get('/temp/:sensorId/:temp/:presence', function (req, res) {
  var temp = new Number(req.params.temp);
  var presence = req.params.presence == "true";
  var sensorId = req.params.sensorId;

  manageTemperatureMeasurement(sensorId, temp, presence);

  res.send({ name: req.params.sensorId, temp: req.params.temp });
});

// temp measurement
app.get('/temp/:sensorId/:temp', function (req, res) {
  var temp = new Number(req.params.temp);
  var presence = false;
  var sensorId = req.params.sensorId;

  manageTemperatureMeasurement(sensorId, temp, presence);

  res.send({ name: req.params.sensorId, temp: req.params.temp });
});

// Heting command: on/off
app.put('/heating/:cmd/:minutes*?', function (req, res) {
  var cmd = req.params.cmd;
  var minutes = req.params.minutes;
  console.log('FINE: /heating/' + cmd + '/' + minutes);
  if (typeof minutes === 'undefined') {
     minutes = DEFAULT_TIMER;
  }

  var resp = null, desc = null;
  if (cmd == 'on' || cmd == 'ON') {
      if (minutes > 0) {
        turnOnHeating (minutes);
        resp = 'ACK';
        desc = 'Heating ON';
      } else {
        // Bad cmd
        resp = 'NACK';
        desc = 'Bad command: ' + cmd + ' minutes: ' + minutes;
      }
  } else if (cmd == 'off' || cmd == 'OFF') {
      turnOffHeating ();
      resp = 'ACK';
      desc = 'Heating OFF';
  } else {
      // Bad cmd
      resp = 'NACK';
      desc = 'Bad command: ' + cmd + ' minutes: ' + minutes;
  }

  res.send({ cmd: cmd, resp: resp, desc: desc });
});

// Heting command: on/off
app.get('/heating/status', function (req, res) {
  var response = null, desc = null;
  var resp = null, desc = null;
  var status = heating.status();
  resp = 'ACK';
  desc = 'Heating ' + (status == 1 ? 'ON' : 'OFF');

  res.send({ status: status, resp: resp, desc: desc });
});

app.listen(3000);

//////
function exitHandler(options, err) {
    if (options.cleanup) {
      console.log('FINE: cleaning');
      heating.destroy();
    }
    if (err) console.log(err.stack);
    if (options.exit) process.exit();
}

//do something when app is closing
process.on('exit', exitHandler.bind(null,{cleanup:true}));
//catches ctrl+c event
process.on('SIGINT', exitHandler.bind(null, {exit:true}));
//catches uncaught exceptions
process.on('uncaughtException', exitHandler.bind(null, {exit:true}));
//////
<|endoftext|>


<commit_before>/**
  * Fonction d'orientation de message entrant
  */
var rxTools = {
//Orientation du message reçu
	rxRouting : function (scope,rootScope,data){
        var mType = data.messageType;

        switch(mType) {
            case "treeForShow":
//                alert(data.message);
            	manageRxTree.getTree(scope,data);
                break;

            default:
                alert("Type de message inconnue!");
            	console.info("ORNI: ",data);
        }
    }

};
var manageRxTree = {
		getTree: function (scope,jsonData){
			scope.majCatego(jsonData.treeBookMark);
		}//,
}

<commit_msg>mise au propore de la tabulation...<commit_after>/**
  * Fonction d'orientation de message entrant
  */
var rxTools = {
//Orientation du message reçu
	rxRouting : function (scope,rootScope,data){
        var mType = data.messageType;

        switch(mType) {
            case "treeForShow":
//                alert(data.message);
            	manageRxTree.getTree(scope,data);
                break;

            default:
                alert("Type de message inconnue!");
            	console.info("ORNI: ",data);
        }
    }

};
var manageRxTree = {
	getTree: function (scope,jsonData){
		scope.majCatego(jsonData.treeBookMark);
	}//,
}

<|endoftext|>


<commit_before>var fs = require('fs');
var cheerio = require('cheerio');
var json2html = require('node-json2html');

var $ = cheerio.load(fs.readFileSync('sampleIndex.html'));

var temparray = [];
var array = [];

$('[id]').filter(function() {
    var temp = {
        id: $(this).attr("id"),
        href: $(this).attr("href"),
        text: $(this).clone().children().remove().end().text().replace(/\s+/g, " ").trim()
    }
    temparray.push(temp);

});

// did this so I can remove the id's that have no text
// we could probably figure out a better way to do this since im using 2 arrays this way but fokit
for (var i = 0; i <= temparray.length - 1; i++) {
    if (temparray[i].text) {
        var ids = temparray[i].id;
        var href = temparray[i].href
        var texts = temparray[i].text;

        var temp = {
            id: ids,
            href:href,
            text: texts
        }

        array.push(temp);
    }
}

var myJsonString = JSON.stringify(array, null, 4);
// console.log(myJsonString)

fs.writeFile('sample.json', myJsonString, (err) => {
    if (err) throw err;
    console.log('The file has been saved!');
});

var transform = { '<>': 'div', 'id': '${id}', 'html': '${text}' }

var html = json2html.transform(array, transform);

fs.writeFile('test.html', html, (err) => {
    if (err) throw err;
})
<commit_msg>added Sample files - but the sampleIndex is not complete yet<commit_after>var fs = require('fs');
var cheerio = require('cheerio');
var json2html = require('node-json2html');

var $ = cheerio.load(fs.readFileSync('sampleIndex.html'));

var temparray = [];
var array = [];

$('[id]').filter(function() {
    var temp = {
        id: $(this).attr("id"),
        href: $(this).attr("href"),
        text: $(this).clone().children().remove().end().text().replace(/\s+/g, " ").trim()
    }
    temparray.push(temp);

});

// did this so I can remove the id's that have no text
// we could probably figure out a better way to do this since im using 2 arrays this way but fokit
for (var i = 0; i <= temparray.length - 1; i++) {
    if (temparray[i].text) {
        var ids = temparray[i].id;
        var href = temparray[i].href
        var texts = temparray[i].text;

        var temp = {
            id: ids,
            href:href,
            text: texts
        }

        array.push(temp);
    }
}

var myJsonString = JSON.stringify(array, null, 4);
// console.log(myJsonString)

fs.writeFile('sample.json', myJsonString, (err) => {
    if (err) throw err;
    console.log('The file has been saved!');
});

var transform = { '<>': 'div', 'id': '${id}', 'html': '${text}' }

var html = json2html.transform(array, transform);

fs.writeFile('test.html', html, (err) => {
    if (err) throw err;
});
<|endoftext|>


<commit_before>/*jslint node: true */
'use strict';

const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const ProcessExitCode = require('../../plugin/process-exit-code');
const { OutputKeepAlivePlugin } = require('../../plugin/output-keep-alive');
const skyPagesConfigUtil = require('../sky-pages/sky-pages.config');
const aliasBuilder = require('./alias-builder');

function spaPath() {
  return skyPagesConfigUtil.spaPath.apply(skyPagesConfigUtil, arguments);
}

function outPath() {
  return skyPagesConfigUtil.outPath.apply(skyPagesConfigUtil, arguments);
}

/**
 * Called when loaded via require.
 * @name getWebpackConfig
 * @param {SkyPagesConfig} skyPagesConfig
 * @returns {WebpackConfig} webpackConfig
 */
function getWebpackConfig(skyPagesConfig, argv = {}) {
  const resolves = [
    process.cwd(),
    spaPath('node_modules'),
    outPath('node_modules')
  ];

  let alias = aliasBuilder.buildAliasList(skyPagesConfig);

  const outConfigMode = skyPagesConfig && skyPagesConfig.skyux && skyPagesConfig.skyux.mode;
  let appPath;

  switch (outConfigMode) {
    case 'advanced':
      appPath = spaPath('src', 'main.ts');
      break;

    default:
      appPath = outPath('src', 'main-internal.ts');
      break;
  }

  return {
    entry: {
      polyfills: [outPath('src', 'polyfills.ts')],
      vendor: [outPath('src', 'vendor.ts')],
      skyux: [outPath('src', 'skyux.ts')],
      app: [appPath]
    },
    output: {
      filename: '[name].js',
      chunkFilename: '[id].chunk.js',
      path: spaPath('dist'),
    },
    resolveLoader: {
      modules: resolves
    },
    resolve: {
      alias: alias,
      modules: resolves,
      extensions: [
        '.js',
        '.ts'
      ]
    },
    module: {
      rules: [
        {
          enforce: 'pre',
          test: /runtime\/config\.ts$/,
          loader: outPath('loader', 'sky-app-config')
        },
        {
          enforce: 'pre',
          test: [
            /\.(html|s?css)$/,
            /sky-pages\.module\.ts/
          ],
          loader: outPath('loader', 'sky-assets')
        },
        {
          enforce: 'pre',
          test: /sky-pages\.module\.ts$/,
          loader: outPath('loader', 'sky-pages-module')
        },
        {
          enforce: 'pre',
          loader: outPath('loader', 'sky-processor', 'preload'),
          exclude: /node_modules/
        },
        {
          test: /\.s?css$/,
          use: [
            'raw-loader',
            'sass-loader'
          ]
        },
        {
          test: /\.html$/,
          loader: 'raw-loader'
        }
      ]
    },
    plugins: [
      // Some properties are required on the root object passed to HtmlWebpackPlugin
      new HtmlWebpackPlugin({
        template: skyPagesConfig.runtime.app.template,
        inject: skyPagesConfig.runtime.app.inject,
        runtime: skyPagesConfig.runtime,
        skyux: skyPagesConfig.skyux
      }),

      new CommonsChunkPlugin({
        name: ['skyux', 'vendor', 'polyfills']
      }),

      new webpack.DefinePlugin({
        'skyPagesConfig': JSON.stringify(skyPagesConfig)
      }),

      new ProgressBarPlugin(),

      new LoaderOptionsPlugin({
        options: {
          context: __dirname,
          skyPagesConfig: skyPagesConfig
        }
      }),

      new ContextReplacementPlugin(
        // The (\\|\/) piece accounts for path separators in *nix and Windows
        /angular(\\|\/)core(\\|\/)@angular/,
        spaPath('src'),
        {}
      ),

      // Webpack 2 behavior does not correctly return non-zero exit code.
      new ProcessExitCode(),

      new OutputKeepAlivePlugin({
        enabled: argv['output-keep-alive']
      })
    ]
  };
}

module.exports = {
  getWebpackConfig: getWebpackConfig
};
<commit_msg>Update common.webpack.config.js<commit_after>/*jslint node: true */
'use strict';

const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const ProcessExitCode = require('../../plugin/process-exit-code');
const { OutputKeepAlivePlugin } = require('../../plugin/output-keep-alive');
const skyPagesConfigUtil = require('../sky-pages/sky-pages.config');
const aliasBuilder = require('./alias-builder');

function spaPath() {
  return skyPagesConfigUtil.spaPath.apply(skyPagesConfigUtil, arguments);
}

function outPath() {
  return skyPagesConfigUtil.outPath.apply(skyPagesConfigUtil, arguments);
}

/**
 * Called when loaded via require.
 * @name getWebpackConfig
 * @param {SkyPagesConfig} skyPagesConfig
 * @returns {WebpackConfig} webpackConfig
 */
function getWebpackConfig(skyPagesConfig, argv = {}) {
  const resolves = [
    process.cwd(),
    spaPath('node_modules'),
    outPath('node_modules')
  ];

  let alias = aliasBuilder.buildAliasList(skyPagesConfig);

  const outConfigMode = skyPagesConfig && skyPagesConfig.skyux && skyPagesConfig.skyux.mode;
  let appPath;

  switch (outConfigMode) {
    case 'advanced':
      appPath = spaPath('src', 'main.ts');
      break;

    default:
      appPath = outPath('src', 'main-internal.ts');
      break;
  }

  return {
    entry: {
      polyfills: [outPath('src', 'polyfills.ts')],
      vendor: [outPath('src', 'vendor.ts')],
      skyux: [outPath('src', 'skyux.ts')],
      app: [appPath]
    },
    output: {
      filename: '[name].js',
      chunkFilename: '[id].chunk.js',
      path: spaPath('dist'),
    },
    resolveLoader: {
      modules: resolves
    },
    resolve: {
      alias: alias,
      modules: resolves,
      extensions: [
        '.js',
        '.ts'
      ]
    },
    module: {
      rules: [
        {
          enforce: 'pre',
          test: /config\.ts$/,
          loader: outPath('loader', 'sky-app-config'),
          include: outPath('runtime')
        },
        {
          enforce: 'pre',
          test: [
            /\.(html|s?css)$/,
            /sky-pages\.module\.ts/
          ],
          loader: outPath('loader', 'sky-assets')
        },
        {
          enforce: 'pre',
          test: /sky-pages\.module\.ts$/,
          loader: outPath('loader', 'sky-pages-module'),
          include: outPath('src', 'app'),
        },
        {
          enforce: 'pre',
          loader: outPath('loader', 'sky-processor', 'preload'),
          include: spaPath('src'),
          exclude: /node_modules/
        },
        {
          test: /\.s?css$/,
          use: [
            'raw-loader',
            'sass-loader'
          ]
        },
        {
          test: /\.html$/,
          loader: 'raw-loader'
        }
      ]
    },
    plugins: [
      // Some properties are required on the root object passed to HtmlWebpackPlugin
      new HtmlWebpackPlugin({
        template: skyPagesConfig.runtime.app.template,
        inject: skyPagesConfig.runtime.app.inject,
        runtime: skyPagesConfig.runtime,
        skyux: skyPagesConfig.skyux
      }),

      new CommonsChunkPlugin({
        name: ['skyux', 'vendor', 'polyfills']
      }),

      new webpack.DefinePlugin({
        'skyPagesConfig': JSON.stringify(skyPagesConfig)
      }),

      new ProgressBarPlugin(),

      new LoaderOptionsPlugin({
        options: {
          context: __dirname,
          skyPagesConfig: skyPagesConfig
        }
      }),

      new ContextReplacementPlugin(
        // The (\\|\/) piece accounts for path separators in *nix and Windows
        /angular(\\|\/)core(\\|\/)@angular/,
        spaPath('src'),
        {}
      ),

      // Webpack 2 behavior does not correctly return non-zero exit code.
      new ProcessExitCode(),

      new OutputKeepAlivePlugin({
        enabled: argv['output-keep-alive']
      })
    ]
  };
}

module.exports = {
  getWebpackConfig: getWebpackConfig
};
<|endoftext|>


<commit_before>define(
  [
    'underscore',
    'models/base',
    'collections/instances',
    'models/instance',
    'collections/volumes',
    'models/volume'
  ],
  function (_, Base, InstanceCollection, Instance, VolumeCollection, Volume) {

    return Backbone.Model.extend({

      parse: function (response) {
        response.start_date = new Date(response.start_date);
        response.instances = new InstanceCollection(_.map(response.instances, function (model) {
          return Instance.prototype.parse(model);
        }), {provider_id: null, identity_id: null});
        response.volumes = new VolumeCollection(_.map(response.volumes, function (model) {
          return Volume.prototype.parse(model);
        }), {provider_id: null, identity_id: null});
        return response;
      },

      url: function () {
        if (this.id)
          return this.urlRoot + '/project/' + this.id;
        else
          return this.urlRoot + '/project/';
      },

      isEmpty: function () {
        return this.get('instances').isEmpty() && this.get('volumes').isEmpty();
      },

      canBeDeleted: function () {
        return this.get('name') !== 'Default';
      },

      objectUrl: function (model) {
        var objectType = Project.objectType(model);
        return this.url() + objectType + '/' + model.id + '/';
      },

      putItem: function (model, options) {
        var url = this.objectUrl(model);
        $.ajax({
          dataType: 'json',
          contentType: 'application/json',
          url: url,
          type: 'PUT'
        });
        // this is so bad. Sorry
        this.get(Project.objectType(model) + 's').add(model);
      },

      removeItem: function (model, options) {
        var url = this.objectUrl(model);
        $.ajax({
          dataType: 'json',
          contentType: 'application/json',
          url: url,
          type: 'DELETE'
        });
        // this is so bad. Sorry
        this.get(Project.objectType(model) + 's').remove(model);
      }

    }, statics);

    return Project;

  });
<commit_msg>inherit Project model from Backbone directly<commit_after>define(
  [
    'underscore',
    'backbone',
    'collections/instances',
    'models/instance',
    'collections/volumes',
    'models/volume',
    'globals'
  ],
  function (_, Backbone, InstanceCollection, Instance, VolumeCollection, Volume, globals) {

    var statics = {
      objectType: function (model) {
        var objectType;
        if (model instanceof Instance)
          objectType = 'instance';
        else if (model instanceof Volume)
          objectType = 'volume';
        else
          throw "Unknown model type";
        return objectType;
      }
    };

    var Project = Backbone.Model.extend({

      urlRoot: globals.API_ROOT + "/project",

      url: function () {
        var url = Backbone.Model.prototype.url.apply(this) + globals.slash();
        return url;
      },

      parse: function (response) {
        response.start_date = new Date(response.start_date);
        response.instances = new InstanceCollection(_.map(response.instances, function (model) {
          return Instance.prototype.parse(model);
        }), {provider_id: null, identity_id: null});
        response.volumes = new VolumeCollection(_.map(response.volumes, function (model) {
          return Volume.prototype.parse(model);
        }), {provider_id: null, identity_id: null});
        return response;
      },

      isEmpty: function () {
        return this.get('instances').isEmpty() && this.get('volumes').isEmpty();
      },

      canBeDeleted: function () {
        return this.get('name') !== 'Default';
      },

      objectUrl: function (model) {
        var objectType = Project.objectType(model);
        return this.url() + objectType + '/' + model.id + '/';
      },

      putItem: function (model, options) {
        var url = this.objectUrl(model);
        $.ajax({
          dataType: 'json',
          contentType: 'application/json',
          url: url,
          type: 'PUT'
        });
        // this is so bad. Sorry
        this.get(Project.objectType(model) + 's').add(model);
      },

      removeItem: function (model, options) {
        var url = this.objectUrl(model);
        $.ajax({
          dataType: 'json',
          contentType: 'application/json',
          url: url,
          type: 'DELETE'
        });
        // this is so bad. Sorry
        this.get(Project.objectType(model) + 's').remove(model);
      }

    }, statics);

    return Project;

  });
<|endoftext|>


<commit_before>/** Created by hhj on 4/21/16. */
import * as muiColors from 'material-ui/lib/styles/colors'

module.exports = {
  ...muiColors
}

export default muiColors
<commit_msg>fix: material-ui colors import<commit_after>/** Created by hhj on 4/21/16. */
import * as muiColors from 'material-ui/styles/colors'

module.exports = {
  ...muiColors
}

export default muiColors
<|endoftext|>


<commit_before>(function(){

    'use strict';

    window.App = window.App || {};
    App.BASE = App.HOST = (function() {
        var origin = location.origin;
        // remove the trailer port number if running on local
        if (origin.match(/[0-9]{4,4}/)) {
            origin = origin.split(':');
            origin.pop();
            origin = origin.join(':') + ':5000';
        }
        return origin;
    })();
    App.DEBUG = true;

    // get wrapper, logs and calls the callback or fail fn
    App.utils.httpGet = function httpGet(url, success, fail, always) {
        if (App.DEBUG) {
            console.log('[GET] ' + url);
        }
        return $.get(url).done(success).fail(fail || logFailure);
    };

    App.Router = Backbone.Router.extend({
        routes: {
            ':user/:repo/timeline': 'timeline',
            ':user/:repo'         : 'timeline',
            ':user/:repo/graphs'  : 'graphs',
            ':user/:repo/insights': 'insights',
            '*index'              : 'index'
        }
    });

    App.Views = {};
    App.Views.Topbar = Backbone.View.extend({
        el: $('#topbar .menu'),
        events: {
            'click li': 'changeView'
        },

        changeView: function(item) {
            var $el = $(item.target);
            var action = $el.text().toLowerCase();
            location.hash = '/' + App.REPO + '/' + action;
        }
    });

    App.Views.RepoSelector = Backbone.View.extend({
        el: $('#repo-select-trigger'),
        initialize: function() {
            getAllRepos(addRepos);
        },
        events: {
            'click'   : 'toggle',
            'click li': 'switchRepo'
        },
        toggle: function() {
            var $container = $('.repo-select');
            var $repoList = $('ul', $container);

            $container.toggleClass('hidden');
            $repoList.addClass('show--fade-in');

            if ($container.hasClass('hidden')) {
                $('.show--fade-in').removeClass('show--fade-in');
            } else {
                var cb = this.hideTooltip.bind(this);
                $(window).on('keydown', cb);
            }
        },
        hideTooltip: function(e) {
            if (e.keyCode == 27) { // ESC
                $(window).off('keydown');
                this.toggle();
            }

        },
        switchRepo: function(event) {
            // remove all the events in the timeline
            // leave in only the loading spinner
            var repo = $(event.target).text();
            emptyTimeline();
            location.hash = '/' + repo + '/timeline';
        }
    });

    App.Views.PullIssueBadge = Backbone.View.extend({
        el: $('#pull-issue-badges'),
        initialize: function() {
            populateOpenIssues();
            populateOpenPulls();
        }
    });

    var topbar = new App.Views.Topbar();
    var repoSelecttor = new App.Views.RepoSelector();
    var pullIssueBadge;
    var appRouter = new App.Router();

    appRouter.on('route:index', function() {
        getRandomRepo(function(repo) {
            location.hash = '/' + repo + '/timeline';
        });
    });

    function initIssuePullBadges() {
        pullIssueBadge = new App.Views.PullIssueBadge();
    }

    appRouter.on('route:insights', function(user, repo){
        if (App.DEBUG) {
            console.log('[INSIGHTS]');
        }
        if (arguments.length > 3) {
            console.error('Bad request. Format is /<user>/<repo>/insights');
            if (App.DEBUG) {
                console.log(arguments);
            }
            return;
        }
        checkForRepo(user, repo, function(res) {
            if (res) {

                App.REPO = user + '/' + repo;
                App.BASE = App.HOST + '/' + App.REPO;

                $('#user-repo').text(App.REPO);

                drawInsights();
                $('.tab').hide();
                $('#tab-3').show();

                stopScrollListener();
                initIssuePullBadges();

            }
        });
    });

    appRouter.on('route:graphs', function(user, repo) {
        if (App.DEBUG) {
            console.log('[GRAPHS]');
        }
        if (arguments.length > 3) {
            console.error('Bad request. Format is /<user>/<repo>/graph');
            if (App.DEBUG) {
                console.log(arguments);
            }
            return;
        }
        checkForRepo(user, repo, function(res) {
            if (res) {

                App.REPO = user + '/' + repo;
                App.BASE = App.HOST + '/' + App.REPO;

                $('#user-repo').text(App.REPO);

                drawGraphs();
                $('.tab').hide();
                $('#tab-2').show();

                stopScrollListener();
                initIssuePullBadges();

            }
        });
    });

    appRouter.on('route:timeline', function(user, repo) {
        checkForRepo(user, repo, function(res) {
            if (res) {
                if (App.DEBUG) {
                    console.log('[TIMELINE] ' + user + ' ' + repo);
                }
                $('.tab').hide();
                $('#tab-1').show();

                App.REPO = user + '/' + repo;
                App.BASE = App.HOST + '/' + App.REPO;

                $('#user-repo').text(App.REPO);

                initTimeline();
                initIssuePullBadges();
            } else {
                console.error('No such repo');
            }
        });
    });

    function checkForRepo(user, repo, fn) {
        var url = App.HOST + '/available_repos';
        var s = user + '/' + repo;
        App.utils.httpGet(url, function(data) {
            var r = data.data.some(function(repo) {
                return repo.match(s);
            });
            fn(r);
        });
    }

    function getAllRepos(cb) {
        var url = App.HOST + '/available_repos';
        App.utils.httpGet(url, cb);
    }

    // make a request for all available repos
    // call the callback with a random repo
    function getRandomRepo(fn) {
        getAllRepos(function(data) {
            var idx = parseInt(Math.random() * 100 % data.data.length, 10);
            var randomRepo = data.data[idx];
            fn(randomRepo);
        });
    }

    // generic fail method for logging
    function logFailure(data) {
        if (App.DEBUG) {
            console.log('Request failed.');
            console.log(data);
        }
    }

    // populate repo tooltip with all available repos
    function addRepos (data) {
        var $container = $('.repo-select');

        var $repoList = $('ul', $container);
        data.data.forEach(function (repo) {
            // TODO add actual links
            var repoLink = $('').text(repo);
            var repoLI = $('
').append(repoLink);
            $repoList.append(repoLI);
        });
    }

    function initTimeline() {
        emptyTimeline();
        populateTimeline();
        addScrollListener();
    }

    function addScrollListener() {
        var $timeline = $('#timeline');
        $(document).on('scroll', function () {
            if (App.DEBUG) {
                console.log('[TIMELINE] scroll listener');
            }
            if($(window).scrollTop() + $(window).height() >= $(document).height() - 10) {
                populateTimeline(App.PER_PAGE, $timeline.children('.timeline-item').length);
            }
        });
    }

    function stopScrollListener() {
        $(document).off('scroll');
    }

    function populateOpenIssues() {
        App.utils.httpGet(App.BASE + "/issues_count", function (data) {
            var count = data.data.open;
            var $el = $('#open-issues-count');
            var url = 'http://github.com/' + App.REPO + '/issues?state=open';

            $el.text(count).attr('href', url);
        });
    }

    function populateOpenPulls() {
        App.utils.httpGet(App.BASE + "/pulls_count", function (data) {
            var count = data.data.open;
            var $el = $('#open-pulls-count');
            var url = 'http://github.com/' + App.REPO + '/pulls?state=open';

            $el.text(count).attr('href', url);
        });
    }

    Backbone.history.start();

})();

function logFailure(msg) {
    console.log('[FAILURE]', msg.statusText);
}

function displayFailMessage(fail) {

    var $tabContainer = $('#tab-container');

    if (fail.status != 404) {
        logFailure(fail);
        return;
    }

    $('#counts-container').remove();
    $tabContainer.empty();

    var msg = "
No data for this repository yet. Retrying in 2 minutes.
";
    $tabContainer.append(msg);

    setTimeout(function() {
        location.reload();
    }, 1000 * 60 * 2);
}
<commit_msg>Stop reload of previous views<commit_after>(function(){

    'use strict';

    window.App = window.App || {};
    App.BASE = App.HOST = (function() {
        var origin = location.origin;
        // remove the trailer port number if running on local
        if (origin.match(/[0-9]{4,4}/)) {
            origin = origin.split(':');
            origin.pop();
            origin = origin.join(':') + ':5000';
        }
        return origin;
    })();
    App.Components = {
        timeline: false,
        graph: false,
        insights: false
    };
    App.DEBUG = true;

    // get wrapper, logs and calls the callback or fail fn
    App.utils.httpGet = function httpGet(url, success, fail, always) {
        if (App.DEBUG) {
            console.log('[GET] ' + url);
        }
        return $.get(url).done(success).fail(fail || logFailure);
    };

    App.Router = Backbone.Router.extend({
        routes: {
            ':user/:repo/timeline': 'timeline',
            ':user/:repo'         : 'timeline',
            ':user/:repo/graphs'  : 'graphs',
            ':user/:repo/insights': 'insights',
            '*index'              : 'index'
        }
    });

    App.Views = {};
    App.Views.Topbar = Backbone.View.extend({
        el: $('#topbar .menu'),
        events: {
            'click li': 'changeView'
        },

        changeView: function(item) {
            var $el = $(item.target);
            var action = $el.text().toLowerCase();
            location.hash = '/' + App.REPO + '/' + action;
        }
    });

    App.Views.RepoSelector = Backbone.View.extend({
        el: $('#repo-select-trigger'),
        initialize: function() {
            getAllRepos(addRepos);
        },
        events: {
            'click'   : 'toggle',
            'click li': 'switchRepo'
        },
        toggle: function() {
            var $container = $('.repo-select');
            var $repoList = $('ul', $container);

            $container.toggleClass('hidden');
            $repoList.addClass('show--fade-in');

            if ($container.hasClass('hidden')) {
                $('.show--fade-in').removeClass('show--fade-in');
            } else {
                var cb = this.hideTooltip.bind(this);
                $(window).on('keydown', cb);
            }
        },
        hideTooltip: function(e) {
            if (e.keyCode == 27) { // ESC
                $(window).off('keydown');
                this.toggle();
            }

        },
        switchRepo: function(event) {
            // remove all the events in the timeline
            // leave in only the loading spinner
            var repo = $(event.target).text();
            emptyTimeline();
            location.hash = '/' + repo + '/timeline';
        }
    });

    App.Views.PullIssueBadge = Backbone.View.extend({
        el: $('#pull-issue-badges'),
        initialize: function() {
            populateOpenIssues();
            populateOpenPulls();
        }
    });

    var topbar = new App.Views.Topbar();
    var repoSelecttor = new App.Views.RepoSelector();
    var pullIssueBadge;
    var appRouter = new App.Router();

    appRouter.on('route:index', function() {
        getRandomRepo(function(repo) {
            location.hash = '/' + repo + '/timeline';
        });
    });

    function initIssuePullBadges() {
        pullIssueBadge = new App.Views.PullIssueBadge();
    }

    appRouter.on('route:insights', function(user, repo){
        if (App.DEBUG) {
            console.log('[INSIGHTS]');
        }
        if (arguments.length > 3) {
            console.error('Bad request. Format is /<user>/<repo>/insights');
            if (App.DEBUG) {
                console.log(arguments);
            }
            return;
        }
        checkForRepo(user, repo, function(res) {
            if (res) {

                App.REPO = user + '/' + repo;
                App.BASE = App.HOST + '/' + App.REPO;

                $('#user-repo').text(App.REPO);

                if (!App.Components.insights) {
                    drawInsights();
                    App.Components.insights = true;
                }
                $('.tab').hide();
                $('#tab-3').show();

                stopScrollListener();
                initIssuePullBadges();

            }
        });
    });

    appRouter.on('route:graphs', function(user, repo) {
        if (App.DEBUG) {
            console.log('[GRAPHS]');
        }
        if (arguments.length > 3) {
            console.error('Bad request. Format is /<user>/<repo>/graph');
            if (App.DEBUG) {
                console.log(arguments);
            }
            return;
        }
        checkForRepo(user, repo, function(res) {
            if (res) {

                App.REPO = user + '/' + repo;
                App.BASE = App.HOST + '/' + App.REPO;

                $('#user-repo').text(App.REPO);

                if (!App.Components.graph) {
                    drawGraphs();
                    App.Components.graph = true;
                }
                $('.tab').hide();
                $('#tab-2').show();

                stopScrollListener();
                initIssuePullBadges();

            }
        });
    });

    appRouter.on('route:timeline', function(user, repo) {
        checkForRepo(user, repo, function(res) {
            if (res) {
                if (App.DEBUG) {
                    console.log('[TIMELINE] ' + user + ' ' + repo);
                }
                $('.tab').hide();
                $('#tab-1').show();

                App.REPO = user + '/' + repo;
                App.BASE = App.HOST + '/' + App.REPO;

                $('#user-repo').text(App.REPO);

                if (!App.Components.timeline) {
                    initTimeline();
                    App.Components.timeline = true;
                }
                initIssuePullBadges();
                addScrollListener();
            } else {
                console.error('No such repo');
            }
        });
    });

    function checkForRepo(user, repo, fn) {
        var url = App.HOST + '/available_repos';
        var s = user + '/' + repo;
        App.utils.httpGet(url, function(data) {
            var r = data.data.some(function(repo) {
                return repo.match(s);
            });
            fn(r);
        });
    }

    function getAllRepos(cb) {
        var url = App.HOST + '/available_repos';
        App.utils.httpGet(url, cb);
    }

    // make a request for all available repos
    // call the callback with a random repo
    function getRandomRepo(fn) {
        getAllRepos(function(data) {
            var idx = parseInt(Math.random() * 100 % data.data.length, 10);
            var randomRepo = data.data[idx];
            fn(randomRepo);
        });
    }

    // generic fail method for logging
    function logFailure(data) {
        if (App.DEBUG) {
            console.log('Request failed.');
            console.log(data);
        }
    }

    // populate repo tooltip with all available repos
    function addRepos (data) {
        var $container = $('.repo-select');

        var $repoList = $('ul', $container);
        data.data.forEach(function (repo) {
            // TODO add actual links
            var repoLink = $('').text(repo);
            var repoLI = $('
').append(repoLink);
            $repoList.append(repoLI);
        });
    }

    function initTimeline() {
        emptyTimeline();
        populateTimeline();
    }

    function addScrollListener() {
        var $timeline = $('#timeline');
        $(document).on('scroll', function () {
            if (App.DEBUG) {
                console.log('[TIMELINE] scroll listener');
            }
            if($(window).scrollTop() + $(window).height() >= $(document).height() - 10) {
                populateTimeline(App.PER_PAGE, $timeline.children('.timeline-item').length);
            }
        });
    }

    function stopScrollListener() {
        $(document).off('scroll');
    }

    function populateOpenIssues() {
        App.utils.httpGet(App.BASE + "/issues_count", function (data) {
            var count = data.data.open;
            var $el = $('#open-issues-count');
            var url = 'http://github.com/' + App.REPO + '/issues?state=open';

            $el.text(count).attr('href', url);
        });
    }

    function populateOpenPulls() {
        App.utils.httpGet(App.BASE + "/pulls_count", function (data) {
            var count = data.data.open;
            var $el = $('#open-pulls-count');
            var url = 'http://github.com/' + App.REPO + '/pulls?state=open';

            $el.text(count).attr('href', url);
        });
    }

    Backbone.history.start();

    $(window).on('hashchange', function(e) {
        if (location.hash.match(App.REPO)) return;
        App.Components = {
            timeline: false,
            graph: false,
            insights: false
        };
    });

})();

function logFailure(msg) {
    console.log('[FAILURE]', msg.statusText);
}

function displayFailMessage(fail) {

    var $tabContainer = $('#tab-container');

    if (fail.status != 404) {
        logFailure(fail);
        return;
    }

    $('#counts-container').remove();
    $tabContainer.empty();

    var msg = "
No data for this repository yet. Retrying in 2 minutes.
";
    $tabContainer.append(msg);

    setTimeout(function() {
        location.reload();
    }, 1000 * 60 * 2);
}
<|endoftext|>


<commit_before>(function($) {
	var json;
	var prefs = nsPreferences;
	var key_base = "extensions.bkviewer.";
	var frame_color = prefs.copyUnicharPref(key_base + "frame_color",
						"#0ac");
	var bg_color =    prefs.copyUnicharPref(key_base + "bg_color",
						"#fff");
	var text_color =  prefs.copyUnicharPref(key_base + "text_color",
						"#00f");
	json = {
		"body": {
			"background-color": bg_color,
			"color": text_color,
		},
		".es-clearfix:after": {
			"content":    "\".\"",
			"clear":      "both",
			"display":    "block",
			"height":     "0",
			"visibility": "hidden",
		},

		".es-clearfix": {
			"display": "inline-block",
		},

		"* html .es-clearfix": {
			"height": "1%",
		},

		".es-clearfix": {
			"display": "block",
		},

		"ul.bk-category": {
			"padding-top":   "0pt",
			"padding-left":  "0pt",
			"padding-right": "0pt",
			"margin-left":   "0pt",
			"margin-right":  "0pt",
			"border-color":  frame_color,
			"border-width":  "1pt",
			"border-style":  "solid",
			"border-radius": "10pt",
		},

		"li.bk-category": {
			"color":	    bg_color,
			"background-color": frame_color,
			"text-align":       "center",
			"font-weight":      "bold",
			"list-style-type":  "none",
			"clear":            "left",
			"margin-top":       "0pt",
			"margin-bottom":    "5pt",
			"border-radius":    "8pt 8pt 0pt 0pt",
		},

		"ul.bk-item": {
			"padding-left":  "0pt",
			"padding-right": "0pt",
			"margin-left":   "0pt",
			"margin-right":  "0pt",
		},

		"li.bk-item": {
			"width":           "150pt",
			"list-style-type": "none",
			"float":           "left",
			"margin-top":      "2pt",
			"margin-bottom":   "2pt",
			"text-align":      "center",
		},

		"a.bk-item": {
			"text-decoration": "none",
			"color": text_color,
		},

		"img.favicon": {
			"width":   "16px",
			"height":  "16px",
			"margin":  "5px 5px 0px 0px",
			"padding": "0px 0px 0px 0px",
		},
	};

	$('style').stylist(json);

} (jQuery));
<commit_msg>Use px instead of pt for rounded_box<commit_after>(function($) {
	var json;
	var prefs = nsPreferences;
	var key_base = "extensions.bkviewer.";
	var frame_color = prefs.copyUnicharPref(key_base + "frame_color",
						"#0ac");
	var bg_color =    prefs.copyUnicharPref(key_base + "bg_color",
						"#fff");
	var text_color =  prefs.copyUnicharPref(key_base + "text_color",
						"#00f");
	json = {
		"body": {
			"background-color": bg_color,
			"color": text_color,
		},
		".es-clearfix:after": {
			"content":    "\".\"",
			"clear":      "both",
			"display":    "block",
			"height":     "0",
			"visibility": "hidden",
		},

		".es-clearfix": {
			"display": "inline-block",
		},

		"* html .es-clearfix": {
			"height": "1%",
		},

		".es-clearfix": {
			"display": "block",
		},

		"ul.bk-category": {
			"padding-top":   "0px",
			"padding-left":  "0px",
			"padding-right": "0px",
			"margin-left":   "0px",
			"margin-right":  "0px",
			"border-color":  frame_color,
			"border-width":  "1px",
			"border-style":  "solid",
			"border-radius": "10px",
		},

		"li.bk-category": {
			"color":	    bg_color,
			"background-color": frame_color,
			"text-align":       "center",
			"font-weight":      "bold",
			"list-style-type":  "none",
			"clear":            "left",
			"margin-top":       "0px",
			"margin-bottom":    "5px",
			"border-radius":    "8px 8px 0px 0px",
		},

		"ul.bk-item": {
			"padding-left":  "0px",
			"padding-right": "0px",
			"margin-left":   "0px",
			"margin-right":  "0px",
		},

		"li.bk-item": {
			"width":           "210px",
			"list-style-type": "none",
			"float":           "left",
			"margin-top":      "2px",
			"margin-bottom":   "2px",
			"text-align":      "center",
		},

		"a.bk-item": {
			"text-decoration": "none",
			"color": text_color,
		},

		"img.favicon": {
			"width":   "16px",
			"height":  "16px",
			"margin":  "5px 5px 0px 0px",
			"padding": "0px 0px 0px 0px",
		},
	};

	$('style').stylist(json);

} (jQuery));
<|endoftext|>