<commit_before>'use strict';

module.exports = function (grunt) {
    grunt.initConfig({
        gitstash: {
            stash: {
                options: {
                    create: true
                }
            },
            apply: {
                options: {
                    command: 'apply',
                    staged: true,
                    stash: '0'
                }
            }
        },
    });

    grunt.registerTask('change', 'Generate changes', function () {
        grunt.file.write('test.txt', 'test');
    });

    grunt.registerTask('stage', 'Stages the changed file', function (cb) {
        var addFile = function (file, cb) {
            grunt.util.spawn({
                cmd: "git",
                args: ["add", file]
            }, function (err, res, code) {});
        };

        addFile('test.txt');
    });

    grunt.loadTasks('../../tasks');
    grunt.registerTask('default', ['change', 'stage', 'gitstash']);
};<commit_msg>Updated test Gruntfile with proper callback<commit_after>'use strict';

module.exports = function (grunt) {
    grunt.initConfig({
        gitstash: {
            stash: {
                options: {
                    create: true
                }
            },
            apply: {
                options: {
                    command: 'apply',
                    staged: true,
                    stash: '0'
                }
            }
        },
    });

    grunt.registerTask('change', 'Generate changes', function () {
        grunt.file.write('test.txt', 'test');
    });

    grunt.registerTask('stage', 'Stages the changed file', function () {
        var addFile = function (file, cb) {
            grunt.util.spawn({
                cmd: "git",
                args: ["add", file]
            }, function (err, res, code) { cb(); });
        };

        var cb = this.async();

        addFile('test.txt', cb);
    });

    grunt.loadTasks('../../tasks');
    grunt.registerTask('default', ['change', 'stage', 'gitstash']);
};<|endoftext|>


<commit_before>import testRule from 'stylelint-test-rule-tape'

import declarationStrictValue, { ruleName } from '../src'

const { rule } = declarationStrictValue

// ignore keywords hash
testRule(rule, {
  ruleName,
  skipBasicChecks: true,

  config: [['/color$/', 'fill', 'z-index'], {
    ignoreValues: {
      '/color$/': ['transparent', '/^red$/i'],
      'fill': 'inherit',
      'z-index': '/^\\d+$/',
    },
  }],

  accept: [
    { code: '.foo { color: transparent; }' },
    { code: '.foo { color: red; }' },
    { code: '.foo { color: RED; }' },
    { code: '.foo { background-color: transparent; }' },
    { code: '.foo { background-color: red; }' },
    { code: '.foo { background-color: RED; }' },
    { code: '.foo { border-color: transparent; }' },
    { code: '.foo { border-color: red; }' },
    { code: '.foo { border-color: RED; }' },
    { code: '.foo { fill: inherit; }' },
    { code: '.foo { z-index: 0; }' },
    { code: '.foo { z-index: 1000; }' },
  ],

  reject: [
    {
      code: '.foo { color: inherit; }',
      message: `Expected variable, function or keyword for "inherit" of "color" (${ruleName})`,
      line: 1,
      column: 8,
    },
    {
      code: '.foo { fill: currentColor; }',
      message: `Expected variable, function or keyword for "currentColor" of "fill" (${ruleName})`,
      line: 1,
      column: 8,
    },
    {
      code: '.foo { z-index: foo; }',
      message: `Expected variable, function or keyword for "foo" of "z-index" (${ruleName})`,
      line: 1,
      column: 8,
    },
  ],
})
<commit_msg>test: fix coverage of value hash<commit_after>import testRule from 'stylelint-test-rule-tape'

import declarationStrictValue, { ruleName } from '../src'

const { rule } = declarationStrictValue

// ignore keywords hash
testRule(rule, {
  ruleName,
  skipBasicChecks: true,

  config: [['/color$/', 'fill', 'z-index', 'display'], {
    ignoreValues: {
      '/color$/': ['transparent', '/^red$/i'],
      'fill': 'inherit',
      'z-index': '/^\\d+$/',
      '': 'initial',
    },
  }],

  accept: [
    { code: '.foo { color: transparent; }' },
    { code: '.foo { color: red; }' },
    { code: '.foo { color: RED; }' },
    { code: '.foo { background-color: transparent; }' },
    { code: '.foo { background-color: red; }' },
    { code: '.foo { background-color: RED; }' },
    { code: '.foo { border-color: transparent; }' },
    { code: '.foo { border-color: red; }' },
    { code: '.foo { border-color: RED; }' },
    { code: '.foo { fill: inherit; }' },
    { code: '.foo { z-index: 0; }' },
    { code: '.foo { z-index: 1000; }' },
    { code: '.foo { display: initial; }' },
  ],

  reject: [
    {
      code: '.foo { color: inherit; }',
      message: `Expected variable, function or keyword for "inherit" of "color" (${ruleName})`,
      line: 1,
      column: 8,
    },
    {
      code: '.foo { fill: currentColor; }',
      message: `Expected variable, function or keyword for "currentColor" of "fill" (${ruleName})`,
      line: 1,
      column: 8,
    },
    {
      code: '.foo { z-index: foo; }',
      message: `Expected variable, function or keyword for "foo" of "z-index" (${ruleName})`,
      line: 1,
      column: 8,
    },
    {
      code: '.foo { display: block; }',
      message: `Expected variable, function or keyword for "block" of "display" (${ruleName})`,
      line: 1,
      column: 8,
    },
  ],
})
<|endoftext|>


<commit_before>'use strict';
let fs = require('fs');
let path = require('path');
let gulp = require('gulp');
let browserify = require('browserify');
let mergeStream = require('merge-stream');
let runSequence = require('run-sequence').use(gulp);
let streamToPromise = require('stream-to-promise');
let source = require('vinyl-source-stream');
let plumber = require('gulp-plumber');
let sourcemaps = require('gulp-sourcemaps');
let stylish = require('gulp-tslint-stylish');
let tslint = require('gulp-tslint');
let typescript = require('gulp-typescript');

module.exports = function (opts) {
    opts = opts || {};
    opts.lint = opts.lint || ['src/**/*.ts'];
    opts.umd = opts.umd || {
        src: ['src/**/*.ts', '!src/test/**', '!src/public/script/**'],
        dest: 'lib/',
        configPath: 'src/tsconfig.json'
    };
    opts.browserify = opts.browserify || [{
        src: 'src/public/script/main.ts',
        dest: 'lib/public/script/'
    }];

    let project = typescript.createProject(opts.umd.configPath, {
        typescript: require('typescript')
    });

    let releaseProject = typescript.createProject(opts.umd.configPath, {
        removeComments: true,
        typescript: require('typescript')
    });

    gulp.task('ts:build', function (callback) {
        runSequence('ts:lint', 'ts:compile', callback);
    });
    gulp.task('ts:release', function (callback) {
        runSequence('ts:lint', 'ts:release-compile', callback);
    });

    gulp.task('ts:lint', function () {
        return gulp.src(opts.lint)
            .pipe(plumber())
            .pipe(tslint())
            .pipe(tslint.report(stylish, {
                emitError: false,
                sort: true,
                bell: false
            }));
    });

    gulp.task('ts:compile:umd', function () {
        return gulp.src(opts.umd.src)
            .pipe(sourcemaps.init())
            .pipe(typescript(project))
            .pipe(sourcemaps.write())
            .pipe(gulp.dest(opts.umd.dest));
    });

    gulp.task('ts:release-compile:umd', function () {
        return gulp.src(opts.umd.src)
            .pipe(typescript(releaseProject))
            .pipe(gulp.dest(opts.umd.dest));
    });

    gulp.task('ts:compile:browserify', function () {
        return Promise.all(opts.browserify.map(x => {
            new Promise(function (resolve, reject) {
                fs.exists(x.src, function (exists) {
                    if (!exists) {
                        resolve();
                        return;
                    }
                    let id = setTimeout(function () {
                        resolve = () => { };
                        reject(new Error('Timeout'));
                    }, 10 * 1000);

                    let basename = path.basename(x.src);
                    let outputName = basename.replace(new RegExp(path.extname(basename) + '$'), '.js');
                    browserify({
                        entries: [x.src],
                        debug: true
                    })
                        .plugin('tsify', {
                            target: 'ES5',
                            typescript: require('typescript')
                        })
                        .bundle()
                        .on('error', function (err) { console.error(err.message); })
                        .pipe(source(outputName))
                        .pipe(gulp.dest(x.dest))
                        .on('end', function () {
                            clearTimeout(id);
                            resolve();
                        });
                });
            })
        }));
    });

    gulp.task('ts:release-compile:browserify', function () {
        return new Promise(function (resolve, reject) {
            fs.exists(opts.browserify.src, function (exists) {
                if (!exists) {
                    resolve();
                    return;
                }
                let id = setTimeout(function () {
                    reject(new Error('Timeout'));
                }, 10 * 1000);
                browserify({
                    entries: [opts.browserify.src]
                })
                    .plugin('tsify', {
                        target: 'ES5',
                        removeComments: true,
                        typescript: require('typescript')
                    })
                    .bundle()
                    .on('error', function (err) { console.error(err.message); })
                    .pipe(source(opts.browserify.dest[1]))
                    .pipe(gulp.dest(opts.browserify.dest[0]))
                    .on('end', function () {
                        clearTimeout(id);
                        resolve();
                    });
            });
        });
    });

    gulp.task('ts:compile', ['ts:compile:umd', 'ts:compile:browserify']);

    gulp.task('ts:release-compile', ['ts:release-compile:umd', 'ts:release-compile:browserify']);
};
<commit_msg>Remove dependency<commit_after>'use strict';
let fs = require('fs');
let path = require('path');
let gulp = require('gulp');
let browserify = require('browserify');
let runSequence = require('run-sequence').use(gulp);
let streamToPromise = require('stream-to-promise');
let source = require('vinyl-source-stream');
let plumber = require('gulp-plumber');
let sourcemaps = require('gulp-sourcemaps');
let stylish = require('gulp-tslint-stylish');
let tslint = require('gulp-tslint');
let typescript = require('gulp-typescript');

module.exports = function (opts) {
    opts = opts || {};
    opts.lint = opts.lint || ['src/**/*.ts'];
    opts.umd = opts.umd || {
        src: ['src/**/*.ts', '!src/test/**', '!src/public/script/**'],
        dest: 'lib/',
        configPath: 'src/tsconfig.json'
    };
    opts.browserify = opts.browserify || [{
        src: 'src/public/script/main.ts',
        dest: 'lib/public/script/'
    }];

    let project = typescript.createProject(opts.umd.configPath, {
        typescript: require('typescript')
    });

    let releaseProject = typescript.createProject(opts.umd.configPath, {
        removeComments: true,
        typescript: require('typescript')
    });

    gulp.task('ts:build', function (callback) {
        runSequence('ts:lint', 'ts:compile', callback);
    });
    gulp.task('ts:release', function (callback) {
        runSequence('ts:lint', 'ts:release-compile', callback);
    });

    gulp.task('ts:lint', function () {
        return gulp.src(opts.lint)
            .pipe(plumber())
            .pipe(tslint())
            .pipe(tslint.report(stylish, {
                emitError: false,
                sort: true,
                bell: false
            }));
    });

    gulp.task('ts:compile:umd', function () {
        return gulp.src(opts.umd.src)
            .pipe(sourcemaps.init())
            .pipe(typescript(project))
            .pipe(sourcemaps.write())
            .pipe(gulp.dest(opts.umd.dest));
    });

    gulp.task('ts:release-compile:umd', function () {
        return gulp.src(opts.umd.src)
            .pipe(typescript(releaseProject))
            .pipe(gulp.dest(opts.umd.dest));
    });

    gulp.task('ts:compile:browserify', function () {
        return Promise.all(opts.browserify.map(x => {
            new Promise(function (resolve, reject) {
                fs.exists(x.src, function (exists) {
                    if (!exists) {
                        resolve();
                        return;
                    }
                    let id = setTimeout(function () {
                        resolve = () => { };
                        reject(new Error('Timeout'));
                    }, 10 * 1000);

                    let basename = path.basename(x.src);
                    let outputName = basename.replace(new RegExp(path.extname(basename) + '$'), '.js');
                    browserify({
                        entries: [x.src],
                        debug: true
                    })
                        .plugin('tsify', {
                            target: 'ES5',
                            typescript: require('typescript')
                        })
                        .bundle()
                        .on('error', function (err) { console.error(err.message); })
                        .pipe(source(outputName))
                        .pipe(gulp.dest(x.dest))
                        .on('end', function () {
                            clearTimeout(id);
                            resolve();
                        });
                });
            })
        }));
    });

    gulp.task('ts:release-compile:browserify', function () {
        return new Promise(function (resolve, reject) {
            fs.exists(opts.browserify.src, function (exists) {
                if (!exists) {
                    resolve();
                    return;
                }
                let id = setTimeout(function () {
                    reject(new Error('Timeout'));
                }, 10 * 1000);
                browserify({
                    entries: [opts.browserify.src]
                })
                    .plugin('tsify', {
                        target: 'ES5',
                        removeComments: true,
                        typescript: require('typescript')
                    })
                    .bundle()
                    .on('error', function (err) { console.error(err.message); })
                    .pipe(source(opts.browserify.dest[1]))
                    .pipe(gulp.dest(opts.browserify.dest[0]))
                    .on('end', function () {
                        clearTimeout(id);
                        resolve();
                    });
            });
        });
    });

    gulp.task('ts:compile', ['ts:compile:umd', 'ts:compile:browserify']);

    gulp.task('ts:release-compile', ['ts:release-compile:umd', 'ts:release-compile:browserify']);
};
<|endoftext|>


<commit_before>'use strict';

var chai = require('chai'),
    viewer = require('../lib/viewer.js');

chai.should();

describe('Viewer', function() {
  var bulkData = {
    "nodes": [
      {"id": "A"},
      {"id": "B"},
      {"id": "C"},
      {"id": "D"},
      {"id": "E"},
      {"id": "F"},
      {"id": "G"}
    ],
    "links": [
      {"source": "A", "target": "B"},
      {"source": "B", "target": "C"},
      {"source": "A", "target": "D"},
      {"source": "B", "target": "E"},
      {"source": "C", "target": "E"},
      {"source": "D", "target": "E"},
      {"source": "E", "target": "F"},
      {"source": "F", "target": "G"}]
  };
  var streamData = {"stream": [{"type": "node", "id": "H"}, {"type": "link", "source": "H", "target": "A"}]};
  describe('#setupLayout()', function() {
    before(function(done) {
      viewer.setupLayout({w: 960, h: 500});
      done();
    });
    it('should set the expected layout properties', function(done) {
      ['nodes', 'links', 'size', 'linkDistance', 'charge'].map(function(p) {
        viewer.layout.should.have.property(p);
      });
      done();
    });
  });
  describe('#insertInLayout()', function() {
    before(function(done) {
      viewer.setupLayout({w: 480, h: 250});
      viewer.insertInLayout(bulkData.nodes, bulkData.links);
      done();
    });
    it('should insert nodes in the layout', function(done) {
      var nodes = viewer.layout.nodes();
      bulkData.nodes.map(function(d) { return d.id; }).should.eql(nodes.map(function(d) { return d.id; }));
      done();
    });
    it('should insert link sources in the layout', function(done) {
      var links = viewer.layout.links();
      bulkData.links.map(function(d) { return d.source; }).should.eql(links.map(function(d) { return d.source.id; }));
      done();
    });
    it('should insert link targets in the layout', function(done) {
      var links = viewer.layout.links();
      bulkData.links.map(function(d) { return d.target; }).should.eql(links.map(function(d) { return d.target.id; }));
      done();
    });
    it('should set correct link properties', function(done) {
      var links = viewer.layout.links();
      ['index', 'weight', 'x', 'y', 'px', 'py'].map(function(p) {
        links.map(function(d) {
          d.source.should.have.property(p);
          d.target.should.have.property(p);
        });
      });
      done();
    });
  });
  describe('data formatting', function() {
    before(function(done) {
      // setup mock server
      done();
    });
    describe('#dataIn()', function() {
      it('should format bulk data correctly', function(done) {
        // sanity test
        var data = viewer.dataIn(bulkData);
        ['nodes', 'links'].forEach(function(p) {
          data.should.have.property(p);
          data[p].should.be.a('array');
          data[p].length.should.above(0);
        });
        done();
      });
    });
    describe('#streamIn()', function() {
      it('should format stream-ready nodes correctly', function(done) {
        var data = viewer.streamIn({'stream': viewer.getNodes(streamData)});
        data.should.have.property('nodes');
        data.nodes.should.be.a('array');
        data.nodes.length.should.above(0);
        data.should.have.property('links').with.length(0);
        done();
      });
      it('should format stream-ready links correctly', function(done) {
        var data = viewer.streamIn({'stream': viewer.getLinks(streamData)});
        data.should.have.property('nodes').with.length(0);
        data.should.have.property('links');
        data.links.should.be.a('array');
        data.links.length.should.above(0);
        done();
      });
      it('should format stream-ready simultaneous nodes and links correctly', function(done) {
        var data = viewer.streamIn(streamData);
        ['nodes', 'links'].forEach(function(p) {
          data.should.have.property(p);
          data[p].should.be.a('array');
          data[p].length.should.above(0);
        });
        done();
      });
    });
  });
  // describe('data acquisition', function() {
  //   before(function(done) {
  //     // setup mock server
  //     done();
  //   });
  // });
});
<commit_msg>cleanup<commit_after>'use strict';

var chai = require('chai'),
    viewer = require('../lib/viewer.js');

chai.should();

describe('Viewer', function() {
  var bulkData = {
    "nodes": [
      {"id": "A"},
      {"id": "B"},
      {"id": "C"},
      {"id": "D"},
      {"id": "E"},
      {"id": "F"},
      {"id": "G"}
    ],
    "links": [
      {"source": "A", "target": "B"},
      {"source": "B", "target": "C"},
      {"source": "A", "target": "D"},
      {"source": "B", "target": "E"},
      {"source": "C", "target": "E"},
      {"source": "D", "target": "E"},
      {"source": "E", "target": "F"},
      {"source": "F", "target": "G"}]
  };
  var streamData = {"stream": [{"type": "node", "id": "H"}, {"type": "link", "source": "H", "target": "A"}]};
  describe('#setupLayout()', function() {
    before(function(done) {
      viewer.setupLayout({w: 960, h: 500});
      done();
    });
    it('should set the expected layout properties', function(done) {
      ['nodes', 'links', 'size', 'linkDistance', 'charge'].map(function(p) {
        viewer.layout.should.have.property(p);
      });
      done();
    });
  });
  describe('#insertInLayout()', function() {
    before(function(done) {
      viewer.setupLayout({w: 480, h: 250});
      viewer.insertInLayout(bulkData.nodes, bulkData.links);
      done();
    });
    it('should insert nodes in the layout', function(done) {
      var nodes = viewer.layout.nodes();
      bulkData.nodes.map(function(d) { return d.id; }).should.eql(nodes.map(function(d) { return d.id; }));
      done();
    });
    it('should insert link sources in the layout', function(done) {
      var links = viewer.layout.links();
      bulkData.links.map(function(d) { return d.source; }).should.eql(links.map(function(d) { return d.source.id; }));
      done();
    });
    it('should insert link targets in the layout', function(done) {
      var links = viewer.layout.links();
      bulkData.links.map(function(d) { return d.target; }).should.eql(links.map(function(d) { return d.target.id; }));
      done();
    });
    it('should set correct link properties', function(done) {
      var links = viewer.layout.links();
      ['index', 'weight', 'x', 'y', 'px', 'py'].map(function(p) {
        links.map(function(d) {
          d.source.should.have.property(p);
          d.target.should.have.property(p);
        });
      });
      done();
    });
  });
  describe('data formatting', function() {
    describe('#dataIn()', function() {
      it('should format bulk data correctly', function(done) {
        // sanity test
        var data = viewer.dataIn(bulkData);
        ['nodes', 'links'].forEach(function(p) {
          data.should.have.property(p);
          data[p].should.be.a('array');
          data[p].length.should.above(0);
        });
        done();
      });
    });
    describe('#streamIn()', function() {
      it('should format stream-ready nodes correctly', function(done) {
        var data = viewer.streamIn({'stream': viewer.getNodes(streamData)});
        data.should.have.property('nodes');
        data.nodes.should.be.a('array');
        data.nodes.length.should.above(0);
        data.should.have.property('links').with.length(0);
        done();
      });
      it('should format stream-ready links correctly', function(done) {
        var data = viewer.streamIn({'stream': viewer.getLinks(streamData)});
        data.should.have.property('nodes').with.length(0);
        data.should.have.property('links');
        data.links.should.be.a('array');
        data.links.length.should.above(0);
        done();
      });
      it('should format stream-ready simultaneous nodes and links correctly', function(done) {
        var data = viewer.streamIn(streamData);
        ['nodes', 'links'].forEach(function(p) {
          data.should.have.property(p);
          data[p].should.be.a('array');
          data[p].length.should.above(0);
        });
        done();
      });
    });
  });
  // describe('data acquisition', function() {
  //   before(function(done) {
  //     // setup mock server
  //     done();
  //   });
  // });
});
<|endoftext|>


<commit_before>exports.Location = function(){

    this.alias
    this.id

    this.lastSeen

    this.resolution

    this.recent
    this.recentRange

    this.start
    this.end

    this.setAlias = function(alias){
        this.alias = alias
    }

    this.setId = function(id){
        this.id = id
    }

    this.setLastSeen = function(lastSeen){
        this.lastSeen = lastSeen
    }

    this.setTimeRelative = function(recentRange, resolution, lastSeen){
        if (lastSeen !== undefined) {
            this.lastSeen = lastSeen
        }
        this.recent = true
        this.recentRange = recentRange
        this.resolution = resolution
    }

    this.setTimeAbsolute = function(start, end, resolution){
        this.recent = false
        this.lastSeen = false

        this.resolution = resolution

        this.start = start
        this.end = end
    }

    this.toJSON = function(){

        var payload = {}

        // id or alias
        if (this.id === undefined) {
            payload.alias = this.alias
        }
        else {
            payload.id = this.id
        }

        payload.date = {}

        if (this.recent === true) {

            payload.date.recent = {}
            payload.date.recent[this.resolution] = this.recentRange

        } else {

            if (this.resolution === 'minutes') {

                payload.date.minutes = {}

                var splitStart = this.start.toJSON().split('T')
                var splitEnd = this.end.toJSON().split('T')

                payload.date.minutes.start = splitStart[0] + ' ' + splitStart[1].substring(0,5)
                payload.date.minutes.end = splitEnd[0] + ' ' + splitEnd[1].substring(0,5)

            } else if (this.resolution === 'hours') {

                payload.date.hours = {}

                var splitStart = this.start.toJSON().split('T')
                var splitEnd = this.end.toJSON().split('T')

                payload.date.hours.start = splitStart[0] + ' ' + splitStart[1].substring(0,3)
                payload.date.hours.end = splitEnd[0] + ' ' + splitEnd[1].substring(0,3)

            } else if (this.resolution === 'days') {

                payload.date.days = {}

                var splitStart = this.start.toJSON().split('T')
                var splitEnd = this.end.toJSON().split('T')

                payload.date.days.start = splitStart[0]
                payload.date.days.end = splitEnd[0]

            } else if (this.resolution === 'weeks') {
                // TODO FIX THIS SHIT
                payload.date.weeks = {}

                var splitStart = this.start.toJSON().split('T')

                payload.date.weeks.start = splitStart[0].substring(0,5) + '-W' + this.start.getUTCWeek();
                payload.date.weeks.end = splitEnd[0]

            } else if (this.resolution === 'months') {

                payload.date.months = {}

                var splitStart = this.start.toJSON().split('T')
                var splitEnd = this.end.toJSON().split('T')

                payload.date.months.start = splitStart[0].substring(0,7)
                payload.date.months.end = splitEnd[0].substring(0,7)

            } else if (this.resolution === 'years') {

                payload.date.years = {}

                var splitStart = this.start.toJSON().split('T')
                var splitEnd = this.end.toJSON().split('T')

                payload.date.years.start = splitStart[0].substring(0,4)
                payload.date.years.end = splitEnd[0].substring(0,4)

            }
        }

        return payload

    }

}<commit_msg>Location to style<commit_after>exports.Location = Location

function Location() {
  this.alias = null
  this.id = null
  this.lastSeen = null
  this.resolution = null
  this.recent = null
  this.recentRange = null
  this.start = null
  this.end = null
}

var cons = Location
  , proto = cons.prototype

proto.constructor = cons

proto.setAlias = function(alias) {
  this.alias = alias
}

proto.setId = function(id) {
  this.id = id
}

proto.setLastSeen = function(lastSeen) {
  this.lastSeen = lastSeen
}

proto.setTimeRelative = function(recentRange, resolution, lastSeen) {
  if(lastSeen !== undefined) {
    this.lastSeen = lastSeen
  }

  this.recent = true
  this.recentRange = recentRange
  this.resolution = resolution
}

proto.setTimeAbsolute = function(start, end, resolution) {
  this.recent = false
  this.lastSeen = false
  this.resolution = resolution
  this.start = start
  this.end = end
}

proto.toJSON = function() {
  var payload = {}

  // id or alias
  if(this.id === undefined) {
    payload.alias = this.alias
  } else {
    payload.id = this.id
  }

  payload.date = {}

  if(this.recent === true) {
    payload.date.recent = {}
    payload.date.recent[this.resolution] = this.recentRange
  } else {
    var split_start = this.start.toJSON().split('T')
      , split_end = this.end.toJSON().split('T')

    payload.date[this.resolution] = {}

    if(this.resolution === 'minutes') {
      payload.date.minutes.start = [
          split_start[0]
        , splitStart[1].substring(0, 5)
      ].join(' ')
      payload.date.minutes.end = [
          split_end[0]
        , splitEnd[1].substring(0,5)
      ].join(' ')
    } else if(this.resolution === 'hours') {
      payload.date.hours.start = [
          split_start[0]
        , split_start[1].substring(0, 3)
      ].join(' ')
      payload.date.hours.end = [
          split_end[0]
        , split_end[1].substring(0,3)
      ].join(' ')
    } else if(this.resolution === 'days') {
      payload.date.days.start = split_start[0]
      payload.date.days.end = split_end[0]
    } else if(this.resolution === 'weeks') {
      // TODO FIX THIS SHIT
      payload.date.weeks.start = [
          split_start[0].substring(0, 5)
        , this.start.getUTCWeek()
      ].join('-W')
      payload.date.weeks.end = split_end[0]
    } else if(this.resolution === 'months') {
      payload.date.months.start = splitStart[0].substring(0, 7)
      payload.date.months.end = splitEnd[0].substring(0, 7)
    } else if(this.resolution === 'years') {
      payload.date.years.start = splitStart[0].substring(0, 4)
      payload.date.years.end = splitEnd[0].substring(0, 4)
    }
  }

  return payload

}
<|endoftext|>


<commit_before>// ==UserScript==
// @name         MidenQuestPlus
// @namespace    http://tampermonkey.net/
// @version      0.70
// @description  Provides the user with some enhancements to MidenQuest
// @author       Ryalane
// @updateURL    https://github.com/Ryalane/MidenQuestPlus/raw/master/MQP.user.js
// @match        http://www.midenquest.com/Game.aspx
// @resource     MainStylesheet https://raw.githubusercontent.com/Ryalane/MidenQuestPlus/master/style.css
// @resource     NavbarFile https://raw.githubusercontent.com/Ryalane/MidenQuestPlus/master/Navbar.html
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_addStyle
// @grant        GM_getResourceText
// @grant        GM_xmlhttpRequest
// ==/UserScript==

(function() {
    'use strict';
    GM_addStyle(GM_getResourceText("MainStylesheet"));

/* Handle Settings */
// Settings Used
// Workload_useAlerts = true/false
// Chat_AllowTabCycling = true/false
var SetupSettings = function() {
    // Set Workload Alerts
      if (GM_getValue('Workload_useAlerts')) {
          $('input[name="WorkloadAlert"]').prop('checked', true);
      } else {
          // Should be default, but let's do it anyways
          $('input[name="WorkloadAlert"]').prop('checked', false);
      }

    // Set Tab Cycling
    if (GM_getValue('Chat_AllowTabCycling')) {
          $('input[name="TabCycling"]').prop('checked', true);
      } else {
          // Should be default, but let's do it anyways
          $('input[name="TabCycling"]').prop('checked', false);
      }
};

/* Change the look of the page slightly */

    GM_xmlhttpRequest({
  method: "GET",
  url: "https://raw.githubusercontent.com/Ryalane/MidenQuestPlus/master/Navbar.html",
  onload: function(response) {
    $("body").prepend(response.responseText);
    SetupSettings();
  }
});

    // Match the navbar size
    $('#MainPanel').css('width', '1002px');
    // Center the text a bit better
    $('.prgActionOverlay').css('margin-top', '-19px');

/* Modify the title of the page */
    var useAlerts = 'false';
    var doneAlerting = false;
    var Production = '';
    var ProductionTitle = '';
    var isWorking = false;

    var MaxWorkload = 0;
    var CurWorkLoad = 0;

    var CheckWorkloadSettings = function() {
        useAlerts = $('input[name="WorkloadAlert"]').is(':checked');

        // Save every check
        if (GM_getValue('Workload_useAlerts') !== useAlerts) {
            console.log("Saving because GM = " + GM_getValue('Workload_useAlerts') + ' local = ' + useAlerts);
            GM_setValue('Workload_useAlerts', useAlerts);
            $('input[name="WorkloadAlert"]').prop('checked', useAlerts);
        }
    };

    var CheckWork = function() {
      Production = $('.prgActionOverlay').text();
      if (Production[0] === 'S') {
        isWorking = true;
        ProductionTitle = 'Selling';
      } else if (Production[0] === 'M') {
        isWorking = true;
        ProductionTitle = 'Mining';
      } else if (Production[0] === 'G') {
        isWorking = true;
        ProductionTitle = 'Gathering';
      } else if (Production[0] === 'L') {
        isWorking = true;
        ProductionTitle = 'Cutting';
      } else if (Production[0] === 'F') {
        isWorking = true;
        ProductionTitle = 'Fishing';
      } else {
        isWorking = false;
      }

      // After the check, update the current/max workload
      if (isWorking) {
        var tempWorkload = Production.split(' ')[1].split('/');
        CurWorkLoad = tempWorkload[0];
        MaxWorkload = tempWorkload[1];
          if (doneAlerting) {
              doneAlerting = false;
          }
      }
    };

    // Little helper method for setting the title
    var UpdateTitle = function() {
      var title = '';

      if (isWorking) {
        title = ProductionTitle + ' ' + CurWorkLoad + ' / ' + MaxWorkload;
      } else {
        if (ProductionTitle) {
            if (useAlerts && !doneAlerting) {

                alert(ProductionTitle + ' has stopped');
                doneAlerting = true;
            } else {
                title = ProductionTitle + ' has stopped';
            }
        } else {
          title = 'MidenQuest Online';
        }
      }

      document.title = title;
    };

    // Check what the title should be and then update it

    var titlething = setInterval(function () {
    CheckWorkloadSettings();
    CheckWork();
    UpdateTitle();
    }, 1000);

/* Handle chat tabs */
    var TabContainer = $('.Tabs>ul');
    var tabAmount = $('.Tabs>ul').children().size();
    var selectedTab = 1;
    var allowTabCycling = true;

    var HandleChatSettings = function() {
        allowTabCycling = $('input[name="TabCycling"]').is(':checked');

        // Save every check
        if (GM_getValue('Chat_AllowTabCycling') !== useAlerts) {
            GM_setValue('Chat_AllowTabCycling', useAlerts);
            $('input[name="TabCycling"]').prop('checked', useAlerts);
        }
    };

    // Create a couple helper functions
    var NextTab = function() {
        // Set what the next tab is
        if (selectedTab < 4) {
            selectedTab++;
        } else {
            selectedTab = 1;
        }

        // Switch to the next tab
        setTimeout(function () { ChangeChatChannel(selectedTab); }, 100);
    };

    // Set the tab to #1 just in case
    setTimeout(function () { ChangeChatChannel(1); }, 1000);

    setInterval(function () {
        HandleChatSettings();
    }, 250);

    // Setup the key events
    $( document ).keydown(function(e) {
        var keycode = (e.which) ? e.which : e.keyCode;
        if (keycode == 9)
        {
          // TODO: Shift + tab for PreviousTab()
          if (allowTabCycling) {
            NextTab();
            e.preventDefault();
          }
        }
    });
})();
<commit_msg>Update: 0.71<commit_after>// ==UserScript==
// @name         MidenQuestPlus
// @namespace    http://tampermonkey.net/
// @version      0.71
// @description  Provides the user with some enhancements to MidenQuest
// @author       Ryalane
// @updateURL    https://github.com/Ryalane/MidenQuestPlus/raw/master/MQP.user.js
// @match        http://www.midenquest.com/Game.aspx
// @resource     MainStylesheet https://raw.githubusercontent.com/Ryalane/MidenQuestPlus/master/style.css
// @resource     NavbarFile https://raw.githubusercontent.com/Ryalane/MidenQuestPlus/master/Navbar.html
// @grant        GM_getValue
// @grant        GM_setValue
// @grant        GM_addStyle
// @grant        GM_getResourceText
// @grant        GM_xmlhttpRequest
// ==/UserScript==

(function() {
    'use strict';
    GM_addStyle(GM_getResourceText("MainStylesheet"));

/* Handle Settings */
// Settings Used
// Workload_useAlerts = true/false
// Chat_AllowTabCycling = true/false
var SetupSettings = function() {
    // Set Workload Alerts
      if (GM_getValue('Workload_useAlerts')) {
          $('input[name="WorkloadAlert"]').prop('checked', true);
      } else {
          // Should be default, but let's do it anyways
          $('input[name="WorkloadAlert"]').prop('checked', false);
      }

    // Set Tab Cycling
    if (GM_getValue('Chat_AllowTabCycling')) {
          $('input[name="TabCycling"]').prop('checked', true);
      } else {
          // Should be default, but let's do it anyways
          $('input[name="TabCycling"]').prop('checked', false);
      }
};

/* Change the look of the page slightly */

    GM_xmlhttpRequest({
  method: "GET",
  url: "https://raw.githubusercontent.com/Ryalane/MidenQuestPlus/master/Navbar.html",
  onload: function(response) {
    $("body").prepend(response.responseText);
    SetupSettings();
  }
});

    // Match the navbar size
    $('#MainPanel').css('width', '1002px');
    // Center the text a bit better
    $('.prgActionOverlay').css('margin-top', '-19px');

/* Modify the title of the page */
    var useAlerts = 'false';
    var doneAlerting = false;
    var Production = '';
    var ProductionTitle = '';
    var isWorking = false;

    var MaxWorkload = 0;
    var CurWorkLoad = 0;

    var CheckWorkloadSettings = function() {
        useAlerts = $('input[name="WorkloadAlert"]').is(':checked');

        // Save every check
        if (GM_getValue('Workload_useAlerts') !== useAlerts) {
            console.log("Saving because GM = " + GM_getValue('Workload_useAlerts') + ' local = ' + useAlerts);
            GM_setValue('Workload_useAlerts', useAlerts);
            $('input[name="WorkloadAlert"]').prop('checked', useAlerts);
        }
    };

    var CheckWork = function() {
      Production = $('.prgActionOverlay').text();
      if (Production[0] === 'S') {
        isWorking = true;
        ProductionTitle = 'Selling';
      } else if (Production[0] === 'M') {
        isWorking = true;
        ProductionTitle = 'Mining';
      } else if (Production[0] === 'G') {
        isWorking = true;
        ProductionTitle = 'Gathering';
      } else if (Production[0] === 'L') {
        isWorking = true;
        ProductionTitle = 'Cutting';
      } else if (Production[0] === 'F') {
        isWorking = true;
        ProductionTitle = 'Fishing';
      } else {
        isWorking = false;
      }

      // After the check, update the current/max workload
      if (isWorking) {
        var tempWorkload = Production.split(' ')[1].split('/');
        CurWorkLoad = tempWorkload[0];
        MaxWorkload = tempWorkload[1];
          if (doneAlerting) {
              doneAlerting = false;
          }
      }
    };

    // Little helper method for setting the title
    var UpdateTitle = function() {
      var title = '';

      if (isWorking) {
        title = ProductionTitle + ' ' + CurWorkLoad + ' / ' + MaxWorkload;
      } else {
        if (ProductionTitle) {
            if (useAlerts && !doneAlerting) {

                alert(ProductionTitle + ' has stopped');
                doneAlerting = true;
            } else {
                title = ProductionTitle + ' has stopped';
            }
        } else {
          title = 'MidenQuest Online';
        }
      }

      document.title = title;
    };

    // Check what the title should be and then update it

    var titlething = setInterval(function () {
    CheckWorkloadSettings();
    CheckWork();
    UpdateTitle();
    }, 1000);

/* Handle chat tabs */
    var TabContainer = $('.Tabs>ul');
    var tabAmount = $('.Tabs>ul').children().size();
    var selectedTab = 1;
    var allowTabCycling = true;

    var HandleChatSettings = function() {
        allowTabCycling = $('input[name="TabCycling"]').is(':checked');

        // Save every check
        if (GM_getValue('Chat_AllowTabCycling') !== useAlerts) {
            GM_setValue('Chat_AllowTabCycling', useAlerts);
            $('input[name="TabCycling"]').prop('checked', useAlerts);
        }
    };

    // Create a couple helper functions
    var NextTab = function() {
        // Set what the next tab is
        if (selectedTab < 4) {
            selectedTab++;
        } else {
            selectedTab = 1;
        }

        // Switch to the next tab
        setTimeout(function () { ChangeChatChannel(selectedTab); }, 100);
    };

    // Set the tab to #1 just in case
    setTimeout(function () { ChangeChatChannel(1); }, 1000);

    setInterval(function () {
        HandleChatSettings();
    }, 250);

    // Handle Chat tab clicking
    $('#ChatCh1').click(function () {
      selectedTab = 1;
    });
    $('#ChatCh2').click(function () {
      selectedTab = 2;
    });
    $('#ChatCh3').click(function () {
      selectedTab = 3;
    });
    $('#ChatCh4').click(function () {
      selectedTab = 4;
    });

    // Setup the key events
    $( document ).keydown(function(e) {
        var keycode = (e.which) ? e.which : e.keyCode;
        if (keycode == 9)
        {
          // TODO: Shift + tab for PreviousTab()
          if (allowTabCycling) {
            NextTab();
            e.preventDefault();
          }
        }
    });
})();
<|endoftext|>


<commit_before>/**
 * @fileoverview Build file
 * @author nzakas
 */
/*global cat, cd, cp, echo, exec, exit, find, mkdir, mv, pwd, rm, target, test*/

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

require("shelljs/make");

var path = require("path"),
    dateformat = require("dateformat"),
    nodeCLI = require("shelljs-nodecli"),
    os = require("os");

//------------------------------------------------------------------------------
// Settings
//------------------------------------------------------------------------------

/*
 * A little bit fuzzy. My computer has a first CPU speed of 3093 and the perf test
 * always completes in < 2000ms. However, Travis is less predictable due to
 * multiple different VM types. So I'm fudging this for now in the hopes that it
 * at least provides some sort of useful signal.
 */
var PERF_MULTIPLIER = 7.5e6;

//------------------------------------------------------------------------------
// Data
//------------------------------------------------------------------------------

var NODE = "node ", // intentional extra space
    NODE_MODULES = "./node_modules/",
    TEMP_DIR = "./tmp/",
    BUILD_DIR = "./build/",

    // Utilities - intentional extra space at the end of each string
    MOCHA = NODE_MODULES + "mocha/bin/_mocha ",
    ESLINT = NODE + " bin/eslint.js ",

    // Files
    MAKEFILE = "./Makefile.js",
    /*eslint-disable no-use-before-define */
    JS_FILES = find("lib/").filter(fileType("js")).join(" "),
    JSON_FILES = find("conf/").filter(fileType("json")).join(" ") + " .eslintrc",
    TEST_FILES = find("tests/lib/").filter(fileType("js")).join(" ");
    /*eslint-enable no-use-before-define */

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

/**
 * Generates a function that matches files with a particular extension.
 * @param {string} extension The file extension (i.e. "js")
 * @returns {Function} The function to pass into a filter method.
 * @private
 */
function fileType(extension) {
    return function(filename) {
        return filename.substring(filename.lastIndexOf(".") + 1) === extension;
    };
}

/**
 * Generates a static file that includes each rule by name rather than dynamically
 * looking up based on directory. This is used for the browser version of ESLint.
 * @param {string} basedir The directory in which to look for code.
 * @returns {void}
 */
function generateRulesIndex(basedir) {
    var output = "module.exports = function() {\n";
    output += "    var rules = Object.create(null);\n";

    find(basedir + "rules/").filter(fileType("js")).forEach(function(filename) {
        var basename = path.basename(filename, ".js");
        output += "    rules[\"" + basename + "\"] = require(\"./rules/" + basename + "\");\n";
    });

    output += "\n    return rules;\n};";
    output.to(basedir + "load-rules.js");
}

/**
 * Creates a release version tag and pushes to origin.
 * @param {string} type The type of release to do (patch, minor, major)
 * @returns {void}
 */
function release(type) {
    target.test();
    exec("npm version " + type);
    target.changelog();
    exec("git push origin master --tags");
    exec("npm publish");
    target.gensite();
}

//------------------------------------------------------------------------------
// Tasks
//------------------------------------------------------------------------------

target.all = function() {
    target.test();
};

target.lint = function() {
    echo("Validating Makefile.js");
    exec(ESLINT + MAKEFILE);

    echo("Validating JSON Files");
    nodeCLI.exec("jsonlint", "-q -c", JSON_FILES);

    echo("Validating JavaScript files");
    exec(ESLINT + JS_FILES);

    echo("Validating JavaScript test files");
    exec(ESLINT + TEST_FILES);
};

target.test = function() {
    target.lint();
    target.checkRuleFiles();
    var errors = 0,
        lastReturn;

    // exec(ISTANBUL + " cover " + MOCHA + "-- -c " + TEST_FILES);
    lastReturn = nodeCLI.exec("istanbul", "cover", MOCHA, "-- -c", TEST_FILES);
    if (lastReturn.code !== 0) {
      errors++;
    }

    // exec(ISTANBUL + "check-coverage --statement 99 --branch 98 --function 99 --lines 99");
    lastReturn = nodeCLI.exec("istanbul", "check-coverage", "--statement 99 --branch 98 --function 99 --lines 99");
    if (lastReturn.code !== 0) {
      errors++;
    }

    target.browserify();

    lastReturn = nodeCLI.exec("mocha-phantomjs", "-R dot", "tests/tests.htm");
    if (lastReturn.code !== 0) {
      errors++;
    }

    if (errors) {
        exit(1);
    }
};

target.docs = function() {
    echo("Generating documentation");
    nodeCLI.exec("jsdoc", "-d jsdoc lib");
    echo("Documentation has been output to /jsdoc");
};

target.gensite = function() {

    echo("Generating eslint.org");
    var docsDir = "../eslint.github.io/docs",
        currentDir = pwd();

    rm("-r", docsDir);
    mkdir(docsDir);
    cp("-rf", "docs/*", docsDir);

    find(docsDir).forEach(function(filename) {
        if (test("-f", filename)) {
            var text = cat(filename);
            text = "---\ntitle: ESLint\nlayout: doc\n---\n<!-- Note: No pull requests accepted for this file. See README.md in the root directory for details. -->\n" + text;
            text.replace(/.md\)/g, ".html)").replace("README.html", "index.html").to(filename.replace("README.md", "index.md"));
        }
    });

    cd(docsDir);
    exec("git add -A .");
    exec("git commit -m \"Autogenerated new docs at " + dateformat(new Date()) + "\"");
    exec("git fetch origin && git rebase origin/master");
    exec("git push origin master");
    cd(currentDir);

};

target.browserify = function() {

    // 1. create temp and build directory
    if (!test("-d", TEMP_DIR)) {
        mkdir(TEMP_DIR);
    }

    if (!test("-d", BUILD_DIR)) {
        mkdir(BUILD_DIR);
    }

    // 2. copy files into temp directory
    cp("-r", "lib/*", TEMP_DIR);

    // 3. delete the load-rules.js file
    rm(TEMP_DIR + "load-rules.js");

    // 4. create new load-rule.js with hardcoded requires
    generateRulesIndex(TEMP_DIR);

    // 5. browserify the temp directory
    nodeCLI.exec("browserify", TEMP_DIR + "eslint.js", "-o", BUILD_DIR + "eslint.js", "-s eslint");
    // exec(BROWSERIFY + TEMP_DIR + "eslint.js -o " + BUILD_DIR + "eslint.js -s eslint");

    // 6. remove temp directory
    rm("-r", TEMP_DIR);
};

target.changelog = function() {

    // get most recent two tags
    var tags = exec("git tag", { silent: true }).output.trim().split(/\s/g),
        rangeTags = tags.slice(tags.length - 2),
        now = new Date(),
        timestamp = dateformat(now, "mmmm d, yyyy");

    // output header
    (rangeTags[1] + " - " + timestamp + "\n").to("CHANGELOG.tmp");

    // get log statements
    var logs = exec("git log --pretty=format:\"* %s (%an)\" " + rangeTags.join(".."), {silent:true}).output.split(/\n/g);
    logs = logs.filter(function(line) {
        return line.indexOf("Merge pull request") === -1 && line.indexOf("Merge branch") === -1;
    });
    logs.push(""); // to create empty lines
    logs.unshift("");

    // output log statements
    logs.join("\n").toEnd("CHANGELOG.tmp");

    // switch-o change-o
    cat("CHANGELOG.tmp", "CHANGELOG.md").to("CHANGELOG.md.tmp");
    rm("CHANGELOG.tmp");
    rm("CHANGELOG.md");
    mv("CHANGELOG.md.tmp", "CHANGELOG.md");

    // add into commit
    exec("git add CHANGELOG.md");
    exec("git commit --amend --no-edit");

};

target.checkRuleFiles = function() {

    echo("Validating rules");

    var eslintConf = require("./conf/eslint.json");
    var environmentsConf = require("./conf/environments.json");

    var confRules = {};
    confRules["default"] = eslintConf.rules;
    Object.keys(environmentsConf).forEach(function (env) {
        confRules[env] = environmentsConf[env].rules;
    });

    var ruleFiles = find("lib/rules/").filter(fileType("js")),
        rulesIndexText = cat("docs/rules/README.md"),
        errors = 0;

    ruleFiles.forEach(function(filename) {
        var basename = path.basename(filename, ".js");
        var docFilename = "docs/rules/" + basename + ".md";

        var indexLine = new RegExp("\\* \\[" + basename + "\\].*").exec(rulesIndexText);
        indexLine = indexLine ? indexLine[0] : "";

        function isInConfig(env) {
            return confRules[env] && confRules[env].hasOwnProperty(basename);
        }

        function isOffInConfig(env) {
            var envRule = confRules[env][basename];
            return envRule === 0 || (envRule && envRule[0] === 0);
        }

        function isOnInConfig(env) {
            return !isOffInConfig(env);
        }

        function isOffInIndex(env) {
            if (env === "default") {
                return indexLine.indexOf("(off by default)") !== -1;
            } else {
                return indexLine.indexOf("(off by default in the " + env + " environment)") !== -1;
            }
        }

        function isOnInIndex(env) {
            if (env === "default") {
                return indexLine.indexOf("(off by default)") === -1;
            } else {
                return indexLine.indexOf("(on by default in the " + env + " environment)") !== -1;
            }
        }

        function hasIdInTitle(basename) {
            var docText = cat(docFilename);
            var idInTitleRegExp = new RegExp("^# (.*?) \\(" + basename + "\\)");
            return idInTitleRegExp.test(docText);
        }

        // check for docs
        if (!test("-f", docFilename)) {
            console.error("Missing documentation for rule %s", basename);
            errors++;
        } else {

            // check for entry in docs index
            if (rulesIndexText.indexOf("(" + basename + ".md)") === -1) {
                console.error("Missing link to documentation for rule %s in index", basename);
                errors++;
            }

            // check for proper doc format
            if (!hasIdInTitle(basename)) {
                console.error("Missing id in the doc page's title of rule %s", basename);
                errors++;
            }
        }

        // check for default configuration
        if (!isInConfig("default")) {
            console.error("Missing default setting for %s in eslint.json", basename);
            errors++;
        }

        // check that rule is not on in docs but off in default config
        if (isOnInIndex("default") && isOffInConfig("default")) {
            console.error("Missing '(off by default)' for rule %s in index", basename);
            errors++;
        }

        // check that rule is not off in docs but on in default config
        if (isOffInIndex("default") && isOnInConfig("default")) {
            console.error("Rule documentation says that %s is off by default but it is enabled in eslint.json.", basename);
            errors++;
        }

        // check rule config for each environment
        Object.keys(confRules).forEach(function (env) {
            if (env === "default") {
                return;
            }

            // only check if rule has been explicitly set for environment
            if (isInConfig(env)) {

                // check that rule is not on in docs but off in environment config
                if (isOnInIndex(env)) {
                    if (isOffInConfig(env)) {
                        console.error("Rule documentation says that %s is off in environment %s but it is enabled in eslint.json.", basename, env);
                        errors++;
                    }

                // check that rule is not off in docs but on in default config
                } else if (isOffInIndex(env)) {
                    if (isOnInConfig(env)) {
                        console.error("Rule documentation says that %s is on in environment %s but it is disabled in eslint.json.", basename, env);
                        errors++;
                    }

                // rule has been overridden in environment but is not in docs
                } else {
                    console.error("Missing '(%s by default in the %s environment)' for rule %s in index", isOnInConfig(env) ? "on" : "off", env, basename);
                    errors++;
                }

            }
        });

        // check for tests
        if (!test("-f", "tests/lib/rules/" + basename + ".js")) {
            console.error("Missing tests for rule %s", basename);
            errors++;
        }

    });

    if (errors) {
        exit(1);
    }

};

function time(cmd, runs, runNumber, results, cb) {
    var start = process.hrtime();
    exec(cmd, { silent: true }, function() {
        var diff = process.hrtime(start),
            actual = (diff[0] * 1e3 + diff[1] / 1e6); // ms

        results.push(actual);
        echo("Performance Run #" + runNumber + ":  %dms", actual);
        if (runs > 1) {
            time(cmd, runs - 1, runNumber + 1, results, cb);
        } else {
            cb(results);
        }
    });

}

target.perf = function() {
    var cpuSpeed = os.cpus()[0].speed,
        max = PERF_MULTIPLIER / cpuSpeed,
        cmd = ESLINT + "./tests/performance/jshint.js";

    echo("CPU Speed is %d with multiplier %d", cpuSpeed, PERF_MULTIPLIER);

    time(cmd, 5, 1, [], function(results) {
        results.sort(function(a, b) {
            return a - b;
        });

        var median = results[~~(results.length / 2)];

        if (median > max) {
            echo("Performance budget exceeded: %dms (limit: %dms)", median, max);
            exit(1);
        } else {
            echo("Performance budget ok:  %dms (limit: %dms)", median, max);
        }
    });

};

target.patch = function() {
    release("patch");
};

target.minor = function() {
    release("minor");
};

target.major = function() {
    release("major");
};
<commit_msg>Build + Docs: Adding generated resource links to rule docs (Fixes #1021)<commit_after>/**
 * @fileoverview Build file
 * @author nzakas
 */
/*global cat, cd, cp, echo, exec, exit, find, mkdir, mv, pwd, rm, target, test*/

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

require("shelljs/make");

var path = require("path"),
    dateformat = require("dateformat"),
    nodeCLI = require("shelljs-nodecli"),
    os = require("os");

//------------------------------------------------------------------------------
// Settings
//------------------------------------------------------------------------------

/*
 * A little bit fuzzy. My computer has a first CPU speed of 3093 and the perf test
 * always completes in < 2000ms. However, Travis is less predictable due to
 * multiple different VM types. So I'm fudging this for now in the hopes that it
 * at least provides some sort of useful signal.
 */
var PERF_MULTIPLIER = 7.5e6;

//------------------------------------------------------------------------------
// Data
//------------------------------------------------------------------------------

var NODE = "node ", // intentional extra space
    NODE_MODULES = "./node_modules/",
    TEMP_DIR = "./tmp/",
    BUILD_DIR = "./build/",

    // Utilities - intentional extra space at the end of each string
    MOCHA = NODE_MODULES + "mocha/bin/_mocha ",
    ESLINT = NODE + " bin/eslint.js ",

    // Files
    MAKEFILE = "./Makefile.js",
    /*eslint-disable no-use-before-define */
    JS_FILES = find("lib/").filter(fileType("js")).join(" "),
    JSON_FILES = find("conf/").filter(fileType("json")).join(" ") + " .eslintrc",
    TEST_FILES = find("tests/lib/").filter(fileType("js")).join(" ");
    /*eslint-enable no-use-before-define */

//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------

/**
 * Generates a function that matches files with a particular extension.
 * @param {string} extension The file extension (i.e. "js")
 * @returns {Function} The function to pass into a filter method.
 * @private
 */
function fileType(extension) {
    return function(filename) {
        return filename.substring(filename.lastIndexOf(".") + 1) === extension;
    };
}

/**
 * Generates a static file that includes each rule by name rather than dynamically
 * looking up based on directory. This is used for the browser version of ESLint.
 * @param {string} basedir The directory in which to look for code.
 * @returns {void}
 */
function generateRulesIndex(basedir) {
    var output = "module.exports = function() {\n";
    output += "    var rules = Object.create(null);\n";

    find(basedir + "rules/").filter(fileType("js")).forEach(function(filename) {
        var basename = path.basename(filename, ".js");
        output += "    rules[\"" + basename + "\"] = require(\"./rules/" + basename + "\");\n";
    });

    output += "\n    return rules;\n};";
    output.to(basedir + "load-rules.js");
}

/**
 * Creates a release version tag and pushes to origin.
 * @param {string} type The type of release to do (patch, minor, major)
 * @returns {void}
 */
function release(type) {
    target.test();
    exec("npm version " + type);
    target.changelog();
    exec("git push origin master --tags");
    exec("npm publish");
    target.gensite();
}

//------------------------------------------------------------------------------
// Tasks
//------------------------------------------------------------------------------

target.all = function() {
    target.test();
};

target.lint = function() {
    echo("Validating Makefile.js");
    exec(ESLINT + MAKEFILE);

    echo("Validating JSON Files");
    nodeCLI.exec("jsonlint", "-q -c", JSON_FILES);

    echo("Validating JavaScript files");
    exec(ESLINT + JS_FILES);

    echo("Validating JavaScript test files");
    exec(ESLINT + TEST_FILES);
};

target.test = function() {
    target.lint();
    target.checkRuleFiles();
    var errors = 0,
        lastReturn;

    // exec(ISTANBUL + " cover " + MOCHA + "-- -c " + TEST_FILES);
    lastReturn = nodeCLI.exec("istanbul", "cover", MOCHA, "-- -c", TEST_FILES);
    if (lastReturn.code !== 0) {
      errors++;
    }

    // exec(ISTANBUL + "check-coverage --statement 99 --branch 98 --function 99 --lines 99");
    lastReturn = nodeCLI.exec("istanbul", "check-coverage", "--statement 99 --branch 98 --function 99 --lines 99");
    if (lastReturn.code !== 0) {
      errors++;
    }

    target.browserify();

    lastReturn = nodeCLI.exec("mocha-phantomjs", "-R dot", "tests/tests.htm");
    if (lastReturn.code !== 0) {
      errors++;
    }

    if (errors) {
        exit(1);
    }
};

target.docs = function() {
    echo("Generating documentation");
    nodeCLI.exec("jsdoc", "-d jsdoc lib");
    echo("Documentation has been output to /jsdoc");
};

target.gensite = function() {

    echo("Generating eslint.org");
    var docsDir = "../eslint.github.io/docs",
        currentDir = pwd();

    rm("-r", docsDir);
    mkdir(docsDir);
    cp("-rf", "docs/*", docsDir);

    find(docsDir).forEach(function(filename) {
        if (test("-f", filename)) {
            var rulesUrl = "https://github.com/eslint/eslint/tree/master/lib/rules/";
            var docsUrl = "https://github.com/eslint/eslint/tree/master/docs/rules/";

            var text = cat(filename);

            text = "---\ntitle: ESLint\nlayout: doc\n---\n<!-- Note: No pull requests accepted for this file. See README.md in the root directory for details. -->\n" + text;

            text = text.replace(/.md\)/g, ".html)").replace("README.html", "index.html");

            if (filename.indexOf("rules/") !== -1) {
                text += "\n## Resources\n\n";
                text += "* [Rule source](" + rulesUrl + path.basename(filename, ".md") + ".js)\n";
                text += "* [Documentation source](" + docsUrl + path.basename(filename) + ")\n";
            }

            text.to(filename.replace("README.md", "index.md"));
        }
    });

    cd(docsDir);
    exec("git add -A .");
    exec("git commit -m \"Autogenerated new docs at " + dateformat(new Date()) + "\"");
    exec("git fetch origin && git rebase origin/master");
    exec("git push origin master");
    cd(currentDir);

};

target.browserify = function() {

    // 1. create temp and build directory
    if (!test("-d", TEMP_DIR)) {
        mkdir(TEMP_DIR);
    }

    if (!test("-d", BUILD_DIR)) {
        mkdir(BUILD_DIR);
    }

    // 2. copy files into temp directory
    cp("-r", "lib/*", TEMP_DIR);

    // 3. delete the load-rules.js file
    rm(TEMP_DIR + "load-rules.js");

    // 4. create new load-rule.js with hardcoded requires
    generateRulesIndex(TEMP_DIR);

    // 5. browserify the temp directory
    nodeCLI.exec("browserify", TEMP_DIR + "eslint.js", "-o", BUILD_DIR + "eslint.js", "-s eslint");
    // exec(BROWSERIFY + TEMP_DIR + "eslint.js -o " + BUILD_DIR + "eslint.js -s eslint");

    // 6. remove temp directory
    rm("-r", TEMP_DIR);
};

target.changelog = function() {

    // get most recent two tags
    var tags = exec("git tag", { silent: true }).output.trim().split(/\s/g),
        rangeTags = tags.slice(tags.length - 2),
        now = new Date(),
        timestamp = dateformat(now, "mmmm d, yyyy");

    // output header
    (rangeTags[1] + " - " + timestamp + "\n").to("CHANGELOG.tmp");

    // get log statements
    var logs = exec("git log --pretty=format:\"* %s (%an)\" " + rangeTags.join(".."), {silent:true}).output.split(/\n/g);
    logs = logs.filter(function(line) {
        return line.indexOf("Merge pull request") === -1 && line.indexOf("Merge branch") === -1;
    });
    logs.push(""); // to create empty lines
    logs.unshift("");

    // output log statements
    logs.join("\n").toEnd("CHANGELOG.tmp");

    // switch-o change-o
    cat("CHANGELOG.tmp", "CHANGELOG.md").to("CHANGELOG.md.tmp");
    rm("CHANGELOG.tmp");
    rm("CHANGELOG.md");
    mv("CHANGELOG.md.tmp", "CHANGELOG.md");

    // add into commit
    exec("git add CHANGELOG.md");
    exec("git commit --amend --no-edit");

};

target.checkRuleFiles = function() {

    echo("Validating rules");

    var eslintConf = require("./conf/eslint.json");
    var environmentsConf = require("./conf/environments.json");

    var confRules = {};
    confRules["default"] = eslintConf.rules;
    Object.keys(environmentsConf).forEach(function (env) {
        confRules[env] = environmentsConf[env].rules;
    });

    var ruleFiles = find("lib/rules/").filter(fileType("js")),
        rulesIndexText = cat("docs/rules/README.md"),
        errors = 0;

    ruleFiles.forEach(function(filename) {
        var basename = path.basename(filename, ".js");
        var docFilename = "docs/rules/" + basename + ".md";

        var indexLine = new RegExp("\\* \\[" + basename + "\\].*").exec(rulesIndexText);
        indexLine = indexLine ? indexLine[0] : "";

        function isInConfig(env) {
            return confRules[env] && confRules[env].hasOwnProperty(basename);
        }

        function isOffInConfig(env) {
            var envRule = confRules[env][basename];
            return envRule === 0 || (envRule && envRule[0] === 0);
        }

        function isOnInConfig(env) {
            return !isOffInConfig(env);
        }

        function isOffInIndex(env) {
            if (env === "default") {
                return indexLine.indexOf("(off by default)") !== -1;
            } else {
                return indexLine.indexOf("(off by default in the " + env + " environment)") !== -1;
            }
        }

        function isOnInIndex(env) {
            if (env === "default") {
                return indexLine.indexOf("(off by default)") === -1;
            } else {
                return indexLine.indexOf("(on by default in the " + env + " environment)") !== -1;
            }
        }

        function hasIdInTitle(basename) {
            var docText = cat(docFilename);
            var idInTitleRegExp = new RegExp("^# (.*?) \\(" + basename + "\\)");
            return idInTitleRegExp.test(docText);
        }

        // check for docs
        if (!test("-f", docFilename)) {
            console.error("Missing documentation for rule %s", basename);
            errors++;
        } else {

            // check for entry in docs index
            if (rulesIndexText.indexOf("(" + basename + ".md)") === -1) {
                console.error("Missing link to documentation for rule %s in index", basename);
                errors++;
            }

            // check for proper doc format
            if (!hasIdInTitle(basename)) {
                console.error("Missing id in the doc page's title of rule %s", basename);
                errors++;
            }
        }

        // check for default configuration
        if (!isInConfig("default")) {
            console.error("Missing default setting for %s in eslint.json", basename);
            errors++;
        }

        // check that rule is not on in docs but off in default config
        if (isOnInIndex("default") && isOffInConfig("default")) {
            console.error("Missing '(off by default)' for rule %s in index", basename);
            errors++;
        }

        // check that rule is not off in docs but on in default config
        if (isOffInIndex("default") && isOnInConfig("default")) {
            console.error("Rule documentation says that %s is off by default but it is enabled in eslint.json.", basename);
            errors++;
        }

        // check rule config for each environment
        Object.keys(confRules).forEach(function (env) {
            if (env === "default") {
                return;
            }

            // only check if rule has been explicitly set for environment
            if (isInConfig(env)) {

                // check that rule is not on in docs but off in environment config
                if (isOnInIndex(env)) {
                    if (isOffInConfig(env)) {
                        console.error("Rule documentation says that %s is off in environment %s but it is enabled in eslint.json.", basename, env);
                        errors++;
                    }

                // check that rule is not off in docs but on in default config
                } else if (isOffInIndex(env)) {
                    if (isOnInConfig(env)) {
                        console.error("Rule documentation says that %s is on in environment %s but it is disabled in eslint.json.", basename, env);
                        errors++;
                    }

                // rule has been overridden in environment but is not in docs
                } else {
                    console.error("Missing '(%s by default in the %s environment)' for rule %s in index", isOnInConfig(env) ? "on" : "off", env, basename);
                    errors++;
                }

            }
        });

        // check for tests
        if (!test("-f", "tests/lib/rules/" + basename + ".js")) {
            console.error("Missing tests for rule %s", basename);
            errors++;
        }

    });

    if (errors) {
        exit(1);
    }

};

function time(cmd, runs, runNumber, results, cb) {
    var start = process.hrtime();
    exec(cmd, { silent: true }, function() {
        var diff = process.hrtime(start),
            actual = (diff[0] * 1e3 + diff[1] / 1e6); // ms

        results.push(actual);
        echo("Performance Run #" + runNumber + ":  %dms", actual);
        if (runs > 1) {
            time(cmd, runs - 1, runNumber + 1, results, cb);
        } else {
            cb(results);
        }
    });

}

target.perf = function() {
    var cpuSpeed = os.cpus()[0].speed,
        max = PERF_MULTIPLIER / cpuSpeed,
        cmd = ESLINT + "./tests/performance/jshint.js";

    echo("CPU Speed is %d with multiplier %d", cpuSpeed, PERF_MULTIPLIER);

    time(cmd, 5, 1, [], function(results) {
        results.sort(function(a, b) {
            return a - b;
        });

        var median = results[~~(results.length / 2)];

        if (median > max) {
            echo("Performance budget exceeded: %dms (limit: %dms)", median, max);
            exit(1);
        } else {
            echo("Performance budget ok:  %dms (limit: %dms)", median, max);
        }
    });

};

target.patch = function() {
    release("patch");
};

target.minor = function() {
    release("minor");
};

target.major = function() {
    release("major");
};
<|endoftext|>


<commit_before>// Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
// Lincense: New BSD Lincense
// Reference: http://dev.w3.org/html5/websockets/
// Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol

if (!window.WebSocket) {

  if (!window.console) console = {log: function(){ }, error: function(){ }};

  WebSocket = function(url, protocol, proxyHost, proxyPort, headers) {
    var self = this;
    self.readyState = WebSocket.CONNECTING;
    self.bufferedAmount = 0;
    WebSocket.__addTask(function() {
      self.__flash =
        WebSocket.__flash.create(url, protocol, proxyHost || null, proxyPort || 0, headers || null);

      self.__flash.addEventListener("open", function(fe) {
        try {
          if (self.onopen) self.onopen();
        } catch (e) {
          console.error(e.toString());
        }
      });

      self.__flash.addEventListener("close", function(fe) {
        try {
          if (self.onclose) self.onclose();
        } catch (e) {
          console.error(e.toString());
        }
      });

      self.__flash.addEventListener("message", function(fe) {
        var data = decodeURIComponent(fe.getData());
        try {
          if (self.onmessage) {
            var e;
            if (window.MessageEvent) {
              e = document.createEvent("MessageEvent");
              e.initMessageEvent("message", false, false, data, null, null, window);
            } else { // IE
              e = {data: data};
            }
            self.onmessage(e);
          }
        } catch (e) {
          console.error(e.toString());
        }
      });

      self.__flash.addEventListener("stateChange", function(fe) {
        try {
          self.readyState = fe.getReadyState();
          self.bufferedAmount = fe.getBufferedAmount();
        } catch (e) {
          console.error(e.toString());
        }
      });

      //console.log("[WebSocket] Flash object is ready");
    });
  }

  WebSocket.prototype.send = function(data) {
    if (!this.__flash || this.readyState == WebSocket.CONNECTING) {
      throw "INVALID_STATE_ERR: Web Socket connection has not been established";
    }
    var result = this.__flash.send(data);
    if (result < 0) { // success
      return true;
    } else {
      this.bufferedAmount = result;
      return false;
    }
  };

  WebSocket.prototype.close = function() {
    if (!this.__flash) return;
    if (this.readyState != WebSocket.OPEN) return;
    this.__flash.close();
    // Sets/calls them manually here because Flash WebSocketConnection.close cannot fire events
    // which causes weird error:
    // > You are trying to call recursively into the Flash Player which is not allowed.
    this.readyState = WebSocket.CLOSED;
    if (this.onclose) this.onclose();
  };

  /**
   * Implementation of {@link DOM 2 EventTarget Interface}
   *
   * @param {string} type
   * @param {function} listener
   * @param {boolean} useCapture !NB Not implemented yet
   * @return void
   */
  WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
    if (!('__events' in this)) {
      this.__events = {};
    }
    if (!(type in this.__events)) {
      this.__events[type] = [];
      if ('function' == typeof this['on' + type]) {
        this.__events[type].defaultHandler = this['on' + type];
        this['on' + type] = WebSocket_FireEvent(this, type);
      }
    }
    this.__events[type].push(listener);
  };

  /**
   * Implementation of {@link DOM 2 EventTarget Interface}
   *
   * @param {string} type
   * @param {function} listener
   * @param {boolean} useCapture NB! Not implemented yet
   * @return void
   */
  WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {
    if (!('__events' in this)) {
      this.__events = {};
    }
    if (!(type in this.__events)) return;
    for (var i = this.__events.length; i > -1; --i) {
      if (listener === this.__events[type][i]) {
        this.__events[type].splice(i, 1);
        break;
      }
    }
  };

  /**
   * Implementation of {@link DOM 2 EventTarget Interface}
   *
   * @param {WebSocketEvent} event
   * @return void
   */
  WebSocket.prototype.dispatchEvent = function(event) {
    if (!('__events' in this)) throw 'UNSPECIFIED_EVENT_TYPE_ERR';
    if (!(event.type in this.__events)) throw 'UNSPECIFIED_EVENT_TYPE_ERR';

    for (var i = 0, l = this.__events[event.type].length; i < l; ++ i) {
      this.__events[event.type][i](event);
      if (event.cancelBubble) break;
    }

    if (false !== event.returnValue &&
        'function' == typeof this.__events[event.type].defaultHandler)
    {
      this.__events[event.type].defaultHandler(event);
    }
  };

  /**
   *
   * @param {object} object
   * @param {string} type
   */
  function WebSocket_FireEvent(object, type) {
    return function(data) {
      var event = new WebSocketEvent();
      event.initEvent(type, true, true);
      event.target = event.currentTarget = object;
      for (var key in data) {
        event[key] = data[key];
      }
      object.dispatchEvent(event, arguments);
    };
  }

  /**
   * Basic implementation of {@link DOM 2 EventInterface}
   *
   * @class
   * @constructor
   */
  function WebSocketEvent(){}

  /**
   *
   * @type boolean
   */
  WebSocketEvent.prototype.cancelable = true;

  /**
   *
   * @type boolean
   */
  WebSocketEvent.prototype.cancelBubble = false;

  /**
   *
   * @return void
   */
  WebSocketEvent.prototype.preventDefault = function() {
    if (this.cancelable) {
      this.returnValue = false;
    }
  };

  /**
   *
   * @return void
   */
  WebSocketEvent.prototype.stopPropagation = function() {
    this.cancelBubble = true;
  };

  /**
   *
   * @param {string} eventTypeArg
   * @param {boolean} canBubbleArg
   * @param {boolean} cancelableArg
   * @return void
   */
  WebSocketEvent.prototype.initEvent = function(eventTypeArg, canBubbleArg, cancelableArg) {
    this.type = eventTypeArg;
    this.cancelable = cancelableArg;
    this.timeStamp = new Date();
  };

  WebSocket.CONNECTING = 0;
  WebSocket.OPEN = 1;
  WebSocket.CLOSED = 2;

  WebSocket.__tasks = [];

  WebSocket.__initialize = function() {
    if (!WebSocket.__swfLocation) {
      console.error("[WebSocket] set WebSocket.__swfLocation to location of WebSocketMain.swf");
      return;
    }
    var container = document.createElement("div");
    container.id = "webSocketContainer";
    // Puts the Flash out of the window. Note that we cannot use display: none or visibility: hidden
    // here because it prevents Flash from loading at least in IE.
    container.style.position = "absolute";
    container.style.left = "-100px";
    container.style.top = "-100px";
    var holder = document.createElement("div");
    holder.id = "webSocketFlash";
    container.appendChild(holder);
    document.body.appendChild(container);
    swfobject.embedSWF(
      WebSocket.__swfLocation, "webSocketFlash", "10", "10", "9.0.0",
      null, {bridgeName: "webSocket"}, null, null,
      function(e) {
        if (!e.success) console.error("[WebSocket] swfobject.embedSWF failed");
      }
    );
    FABridge.addInitializationCallback("webSocket", function() {
      try {
        //console.log("[WebSocket] FABridge initializad");
        WebSocket.__flash = FABridge.webSocket.root();
        WebSocket.__flash.setCallerUrl(location.href);
        for (var i = 0; i < WebSocket.__tasks.length; ++i) {
          WebSocket.__tasks[i]();
        }
        WebSocket.__tasks = [];
      } catch (e) {
        console.error("[WebSocket] " + e.toString());
      }
    });
  };

  WebSocket.__addTask = function(task) {
    if (WebSocket.__flash) {
      task();
    } else {
      WebSocket.__tasks.push(task);
    }
  }

  // called from Flash
  function webSocketLog(message) {
    console.log(decodeURIComponent(message));
  }

  // called from Flash
  function webSocketError(message) {
    console.error(decodeURIComponent(message));
  }

  if (window.addEventListener) {
    window.addEventListener("load", WebSocket.__initialize, false);
  } else {
    window.attachEvent("onload", WebSocket.__initialize);
  }
}
<commit_msg>Modifying styles. Making Flash detection work on Firefox.<commit_after>// Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
// Lincense: New BSD Lincense
// Reference: http://dev.w3.org/html5/websockets/
// Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol

(function() {

  if (window.WebSocket) return;

  var console = window.console;
  if (!console) console = {log: function(){ }, error: function(){ }};

  function hasFlash() {
    if ('navigator' in window && 'plugins' in navigator && navigator.plugins['Shockwave Flash']) {
      return !!navigator.plugins['Shockwave Flash'].description;
    }
    if ('ActiveXObject' in window) {
      try {
        return !!new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version');
      } catch (e) {}
    }
    return false;
  }

  if (!hasFlash()) {
    console.error("Flash Player is not installed.");
    return;
  }

  WebSocket = function(url, protocol, proxyHost, proxyPort, headers) {
    var self = this;
    self.readyState = WebSocket.CONNECTING;
    self.bufferedAmount = 0;
    WebSocket.__addTask(function() {
      self.__flash =
        WebSocket.__flash.create(url, protocol, proxyHost || null, proxyPort || 0, headers || null);

      self.__flash.addEventListener("open", function(fe) {
        try {
          if (self.onopen) self.onopen();
        } catch (e) {
          console.error(e.toString());
        }
      });

      self.__flash.addEventListener("close", function(fe) {
        try {
          if (self.onclose) self.onclose();
        } catch (e) {
          console.error(e.toString());
        }
      });

      self.__flash.addEventListener("message", function(fe) {
        var data = decodeURIComponent(fe.getData());
        try {
          if (self.onmessage) {
            var e;
            if (window.MessageEvent) {
              e = document.createEvent("MessageEvent");
              e.initMessageEvent("message", false, false, data, null, null, window);
            } else { // IE
              e = {data: data};
            }
            self.onmessage(e);
          }
        } catch (e) {
          console.error(e.toString());
        }
      });

      self.__flash.addEventListener("stateChange", function(fe) {
        try {
          self.readyState = fe.getReadyState();
          self.bufferedAmount = fe.getBufferedAmount();
        } catch (e) {
          console.error(e.toString());
        }
      });

      //console.log("[WebSocket] Flash object is ready");
    });
  }

  WebSocket.prototype.send = function(data) {
    if (!this.__flash || this.readyState == WebSocket.CONNECTING) {
      throw "INVALID_STATE_ERR: Web Socket connection has not been established";
    }
    var result = this.__flash.send(data);
    if (result < 0) { // success
      return true;
    } else {
      this.bufferedAmount = result;
      return false;
    }
  };

  WebSocket.prototype.close = function() {
    if (!this.__flash) return;
    if (this.readyState != WebSocket.OPEN) return;
    this.__flash.close();
    // Sets/calls them manually here because Flash WebSocketConnection.close cannot fire events
    // which causes weird error:
    // > You are trying to call recursively into the Flash Player which is not allowed.
    this.readyState = WebSocket.CLOSED;
    if (this.onclose) this.onclose();
  };

  /**
   * Implementation of {@link DOM 2 EventTarget Interface}
   *
   * @param {string} type
   * @param {function} listener
   * @param {boolean} useCapture !NB Not implemented yet
   * @return void
   */
  WebSocket.prototype.addEventListener = function(type, listener, useCapture) {
    if (!('__events' in this)) {
      this.__events = {};
    }
    if (!(type in this.__events)) {
      this.__events[type] = [];
      if ('function' == typeof this['on' + type]) {
        this.__events[type].defaultHandler = this['on' + type];
        this['on' + type] = WebSocket_FireEvent(this, type);
      }
    }
    this.__events[type].push(listener);
  };

  /**
   * Implementation of {@link DOM 2 EventTarget Interface}
   *
   * @param {string} type
   * @param {function} listener
   * @param {boolean} useCapture NB! Not implemented yet
   * @return void
   */
  WebSocket.prototype.removeEventListener = function(type, listener, useCapture) {
    if (!('__events' in this)) {
      this.__events = {};
    }
    if (!(type in this.__events)) return;
    for (var i = this.__events.length; i > -1; --i) {
      if (listener === this.__events[type][i]) {
        this.__events[type].splice(i, 1);
        break;
      }
    }
  };

  /**
   * Implementation of {@link DOM 2 EventTarget Interface}
   *
   * @param {WebSocketEvent} event
   * @return void
   */
  WebSocket.prototype.dispatchEvent = function(event) {
    if (!('__events' in this)) throw 'UNSPECIFIED_EVENT_TYPE_ERR';
    if (!(event.type in this.__events)) throw 'UNSPECIFIED_EVENT_TYPE_ERR';

    for (var i = 0, l = this.__events[event.type].length; i < l; ++ i) {
      this.__events[event.type][i](event);
      if (event.cancelBubble) break;
    }

    if (false !== event.returnValue &&
        'function' == typeof this.__events[event.type].defaultHandler)
    {
      this.__events[event.type].defaultHandler(event);
    }
  };

  /**
   *
   * @param {object} object
   * @param {string} type
   */
  function WebSocket_FireEvent(object, type) {
    return function(data) {
      var event = new WebSocketEvent();
      event.initEvent(type, true, true);
      event.target = event.currentTarget = object;
      for (var key in data) {
        event[key] = data[key];
      }
      object.dispatchEvent(event, arguments);
    };
  }

  /**
   * Basic implementation of {@link DOM 2 EventInterface}
   *
   * @class
   * @constructor
   */
  function WebSocketEvent(){}

  /**
   *
   * @type boolean
   */
  WebSocketEvent.prototype.cancelable = true;

  /**
   *
   * @type boolean
   */
  WebSocketEvent.prototype.cancelBubble = false;

  /**
   *
   * @return void
   */
  WebSocketEvent.prototype.preventDefault = function() {
    if (this.cancelable) {
      this.returnValue = false;
    }
  };

  /**
   *
   * @return void
   */
  WebSocketEvent.prototype.stopPropagation = function() {
    this.cancelBubble = true;
  };

  /**
   *
   * @param {string} eventTypeArg
   * @param {boolean} canBubbleArg
   * @param {boolean} cancelableArg
   * @return void
   */
  WebSocketEvent.prototype.initEvent = function(eventTypeArg, canBubbleArg, cancelableArg) {
    this.type = eventTypeArg;
    this.cancelable = cancelableArg;
    this.timeStamp = new Date();
  };

  WebSocket.CONNECTING = 0;
  WebSocket.OPEN = 1;
  WebSocket.CLOSED = 2;

  WebSocket.__tasks = [];

  WebSocket.__initialize = function() {
    if (!WebSocket.__swfLocation) {
      console.error("[WebSocket] set WebSocket.__swfLocation to location of WebSocketMain.swf");
      return;
    }
    var container = document.createElement("div");
    container.id = "webSocketContainer";
    // Puts the Flash out of the window. Note that we cannot use display: none or visibility: hidden
    // here because it prevents Flash from loading at least in IE.
    container.style.position = "absolute";
    container.style.left = "-100px";
    container.style.top = "-100px";
    var holder = document.createElement("div");
    holder.id = "webSocketFlash";
    container.appendChild(holder);
    document.body.appendChild(container);
    swfobject.embedSWF(
      WebSocket.__swfLocation, "webSocketFlash", "10", "10", "9.0.0",
      null, {bridgeName: "webSocket"}, null, null,
      function(e) {
        if (!e.success) console.error("[WebSocket] swfobject.embedSWF failed");
      }
    );
    FABridge.addInitializationCallback("webSocket", function() {
      try {
        //console.log("[WebSocket] FABridge initializad");
        WebSocket.__flash = FABridge.webSocket.root();
        WebSocket.__flash.setCallerUrl(location.href);
        for (var i = 0; i < WebSocket.__tasks.length; ++i) {
          WebSocket.__tasks[i]();
        }
        WebSocket.__tasks = [];
      } catch (e) {
        console.error("[WebSocket] " + e.toString());
      }
    });
  };

  WebSocket.__addTask = function(task) {
    if (WebSocket.__flash) {
      task();
    } else {
      WebSocket.__tasks.push(task);
    }
  }

  // called from Flash
  function webSocketLog(message) {
    console.log(decodeURIComponent(message));
  }

  // called from Flash
  function webSocketError(message) {
    console.error(decodeURIComponent(message));
  }

  if (window.addEventListener) {
    window.addEventListener("load", WebSocket.__initialize, false);
  } else {
    window.attachEvent("onload", WebSocket.__initialize);
  }

})();
<|endoftext|>


<commit_before>#!/usr/bin/env node
"use strict";

process.on("unhandledRejection", exn => { throw exn; });
const V86 = require("../../build/libv86-debug.js").V86;
const fs = require("fs");

const test_file = new Uint8Array(fs.readFileSync(__dirname + "/test-file"));
const tests =
[
    {
        name: "Read Existing",
        start: () =>
        {
            emulator.serial0_send("cp /etc/profile /mnt/read-existing\n");
            emulator.serial0_send("echo start-capture; base64 /etc/profile; echo done-read-existing\n");
        },
        capture_trigger: "start-capture",
        end_trigger: "done-read-existing",
        end: expected =>
        {
            emulator.read_file("read-existing", function(err, data)
            {
                if(err)
                {
                    console.log("Reading read-existing failed: " + err);
                    process.exit(1);
                }
                const actual = Buffer.from(data).toString('base64');
                if(actual !== expected)
                {
                    console.log("Fail: Incorrect data");
                    process.exit(1);
                }
            });
        },
    },
    {
        name: "Read New",
        start: () =>
        {
            emulator.serial0_send("dd if=/dev/zero of=/mnt/read-new bs=1k count=512\n");
            emulator.serial0_send("echo done-read-new\n");
        },
        end_trigger: "done-read-new",
        end: () =>
        {
            emulator.read_file("read-new", function(err, data)
            {
                if(err)
                {
                    console.log("Reading read-new failed: " + err);
                    process.exit(1);
                }
                if(data.length < 512 * 1024)
                {
                    console.log("Fail: Incorrect size");
                    process.exit(1);
                }
                if(data.find(v => v !== 0))
                {
                    console.log("Fail: Incorrect data");
                    process.exit(1);
                }
            });
        },
    },
    {
        name: "Write New",
        start: () =>
        {
            emulator.serial0_send("echo start-capture; base64 /mnt/write-new; echo done-write-new\n");
        },
        capture_trigger: "start-capture",
        end_trigger: "done-write-new",
        end: actual  =>
        {
            const expected = Buffer.from(test_file).toString('base64');
            if(actual !== expected)
            {
                console.log("Fail: Incorrect data");
                process.exit(1);
            }
        },
    },
];

let test_num = 0;

const emulator = new V86({
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    hda: { url: __dirname + "/../../images/debian-bench.img" },
    autostart: true,
    memory_size: 512 * 1024 * 1024,
    filesystem: {},
    log_level: 0,
});

let ran_command = false;
let line = "";
let capturing = true;
let capture = "";

emulator.bus.register("emulator-started", function()
{
    console.log("Booting up... Note: the debian image takes a while to boot");
    emulator.create_file("write-new", test_file);
});

emulator.add_listener("serial0-output-char", function(chr)
{
    if(chr < " " && chr !== "\n" && chr !== "\t" || chr > "~")
    {
        return;
    }

    let new_line;
    if(chr === "\n")
    {
        new_line = line;
        console.log("Serial: %s", line);
        line = "";
    }
    else
    {
        line += chr;
    }

    if(capturing)
    {
        capture += chr;
    }

    if(!ran_command && line.endsWith("~# "))
    {
        ran_command = true;
        emulator.serial0_send("mount host9p -t 9p /mnt\n");

        console.log("Starting: " + tests[0].name);
        tests[0].start();
    }

    if(new_line === tests[test_num].capture_trigger)
    {
        capture = "";
        capturing = true;
    }

    if(new_line === tests[test_num].end_trigger)
    {
        const capture_result = capture.slice(0, -1 - tests[test_num].end_trigger.length);
        console.log("Captured:\n" + capture_result);

        tests[test_num].end(capture_result);
        console.log("Passed: " + tests[test_num].name);

        test_num++;
        capture = "";
        capturing = false;

        if(test_num > tests.length)
        {
            console.log("Tests finished");
            emulator.stop();
            process.exit(0);
        }

        console.log("Starting: " + tests[test_num].name);
        tests[test_num].start();
    }
});
<commit_msg>Fix virtio 9p tests<commit_after>#!/usr/bin/env node
"use strict";

process.on("unhandledRejection", exn => { throw exn; });
const V86 = require("../../build/libv86-debug.js").V86;
const fs = require("fs");

const test_file = (new Uint8Array(1024*512)).map(v => Math.random() * 256);
const tests =
[
    {
        name: "Read Existing",
        start: () =>
        {
            emulator.serial0_send("cp /etc/profile /mnt/read-existing\n");
            emulator.serial0_send("echo start-capture; base64 /etc/profile; echo done-read-existing\n");
        },
        capture_trigger: "start-capture",
        end_trigger: "done-read-existing",
        end: capture =>
        {
            emulator.read_file("read-existing", function(err, data)
            {
                if(err)
                {
                    console.log("Reading read-existing failed: " + err);
                    process.exit(1);
                }
                const expected = capture.replace(/\s/g,'');
                const actual = Buffer.from(data).toString('base64');
                if(actual !== expected)
                {
                    console.log("Fail: Incorrect data");
                    console.log("Expected:\n", expected);
                    console.log("Actual:\n", actual);
                    process.exit(1);
                }
            });
        },
    },
    {
        name: "Read New",
        start: () =>
        {
            emulator.serial0_send("dd if=/dev/zero of=/mnt/read-new bs=1k count=512\n");
            emulator.serial0_send("echo done-read-new\n");
        },
        end_trigger: "done-read-new",
        end: () =>
        {
            emulator.read_file("read-new", function(err, data)
            {
                if(err)
                {
                    console.log("Reading read-new failed: " + err);
                    process.exit(1);
                }
                if(data.length < 512 * 1024)
                {
                    console.log("Fail: Incorrect size");
                    process.exit(1);
                }
                if(data.find(v => v !== 0))
                {
                    console.log("Fail: Incorrect data. Expected all zeros.");
                    process.exit(1);
                }
            });
        },
    },
    {
        name: "Write New",
        start: () =>
        {
            emulator.serial0_send("echo start-capture; base64 /mnt/write-new; echo done-write-new\n");
        },
        capture_trigger: "start-capture",
        end_trigger: "done-write-new",
        end: capture  =>
        {
            const actual = capture.replace(/\s/g,'');
            const expected = Buffer.from(test_file).toString('base64');
            if(actual !== expected)
            {
                console.log("Fail: Incorrect data");
                console.log("Expected:\n", expected);
                console.log("Actual:\n", actual);
                process.exit(1);
            }
        },
    },
];

let test_num = 0;

const emulator = new V86({
    bios: { url: __dirname + "/../../bios/seabios.bin" },
    vga_bios: { url: __dirname + "/../../bios/vgabios.bin" },
    hda: { url: __dirname + "/../../images/debian-bench.img" },
    autostart: true,
    memory_size: 512 * 1024 * 1024,
    filesystem: {},
    log_level: 0,
});

let ran_command = false;
let line = "";
let capturing = true;
let capture = "";

emulator.bus.register("emulator-started", function()
{
    console.log("Booting up... Note: the debian image takes a while to boot");
    emulator.create_file("write-new", test_file);
});

emulator.add_listener("serial0-output-char", function(chr)
{
    if(chr < " " && chr !== "\n" && chr !== "\t" || chr > "~")
    {
        return;
    }

    let new_line;
    if(chr === "\n")
    {
        new_line = line;
        console.log("Serial: %s", line);
        line = "";
    }
    else
    {
        line += chr;
    }

    if(capturing)
    {
        capture += chr;
    }

    if(!ran_command && line.endsWith("~# "))
    {
        ran_command = true;
        emulator.serial0_send("mount host9p -t 9p /mnt\n");

        console.log("Starting: " + tests[0].name);
        tests[0].start();
    }

    if(new_line === tests[test_num].capture_trigger)
    {
        capture = "";
        capturing = true;
    }

    if(new_line === tests[test_num].end_trigger)
    {
        const capture_result = capture.slice(0, -1 - tests[test_num].end_trigger.length);

        tests[test_num].end(capture_result);
        console.log("Passed: " + tests[test_num].name);

        test_num++;
        capture = "";
        capturing = false;

        if(test_num >= tests.length)
        {
            console.log("Tests finished");
            emulator.stop();
            process.exit(0);
        }

        console.log("Starting: " + tests[test_num].name);
        tests[test_num].start();
    }
});
<|endoftext|>


<commit_before>const mongoose = require("mongoose");
const NotificationsHistory = new mongoose.Schema({
    senderId:{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    receiverId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    sentMsg: {
        type: String,
    },
    sentDate: {
        type: Date,
        default: new Date()
    },
    carPlate: {
        type: String,
        required: true,
        index: true,
    },
    receivedDevices: [{
            type: mongoose.Schema.Types.ObjectId,
            ref: 'Device'
        }],
    geoLocation: {
        lat: Number,
        log: Number,
        fullAddress: Object,
        formatedAddress: String
    }

});

module.exports = mongoose.model('NotificationsHistory', NotificationsHistory);
<commit_msg>ESLINT<commit_after>const mongoose = require('mongoose');

const NotificationsHistory = new mongoose.Schema({
  senderId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
  },
  receiverId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
  },
  sentMsg: {
    type: String,
  },
  sentDate: {
    type: Date,
    default: new Date(),
  },
  carPlate: {
    type: String,
    required: true,
    index: true,
  },
  receivedDevices: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Device',
  }],
  geoLocation: {
    lat: Number,
    log: Number,
    fullAddress: Object,
    formatedAddress: String,
  },

});

module.exports = mongoose.model('NotificationsHistory', NotificationsHistory);
<|endoftext|>