<commit_before>'use strict';

function Encoder() {
  this.buffer_ = [];
  this.bitIndex_ = 0;
}

Encoder.prototype.encodeOctet = function(o) {
  this.buffer_.push(o & 0xff);
};

Encoder.prototype.encodeInteger = function(firstOctetMask, N, I) {
  var nextMarker = (1 << N) - 1;

  if (I < nextMarker) {
    this.encodeOctet(firstOctetMask | I);
    return;
  }

  if (N > 0) {
    this.encodeOctet(firstOctetMask | nextMarker);
  }

  I -= nextMarker;
  while (I >= 128) {
    this.encodeOctet(I % 128 | 128);
    I /= 128;
  }
  this.encodeOctet(I);
}

Encoder.prototype.encodeASCIIString = function(str) {
  this.encodeInteger(0, 0, str.length);
  for (var i = 0; i < str.length; ++i) {
    this.encodeOctet(str.charCodeAt(i));
  }
}

Encoder.prototype.encodeIndexedHeader = function(index) {
  var opCode = 0x80;
  var prefixLength = 7;
  this.encodeInteger(opCode, prefixLength, index);
}

Encoder.prototype.encodeLiteralHeaderWithoutIndexing = function(
  indexOrName, value) {
  var opCode = 0x60;
  var prefixLength = 5;
  switch (typeof indexOrName) {
    case 'number':
      this.encodeInteger(opCode, prefixLength, indexOrName + 1);
      this.encodeASCIIString(value);
      return;

    case 'string':
      this.encodeInteger(opCode, prefixLength, 0);
      this.encodeASCIIString(indexOrName);
      this.encodeASCIIString(value);
      return;
  }

  throw new Error('not an index or name: ' + indexOrName);
}
<commit_msg>Implement Encoder.encodeLiteralHeaderWithIncrementalIndexing()<commit_after>'use strict';

function Encoder() {
  this.buffer_ = [];
  this.bitIndex_ = 0;
}

Encoder.prototype.encodeOctet = function(o) {
  this.buffer_.push(o & 0xff);
};

Encoder.prototype.encodeInteger = function(firstOctetMask, N, I) {
  var nextMarker = (1 << N) - 1;

  if (I < nextMarker) {
    this.encodeOctet(firstOctetMask | I);
    return;
  }

  if (N > 0) {
    this.encodeOctet(firstOctetMask | nextMarker);
  }

  I -= nextMarker;
  while (I >= 128) {
    this.encodeOctet(I % 128 | 128);
    I /= 128;
  }
  this.encodeOctet(I);
}

Encoder.prototype.encodeASCIIString = function(str) {
  this.encodeInteger(0, 0, str.length);
  for (var i = 0; i < str.length; ++i) {
    this.encodeOctet(str.charCodeAt(i));
  }
}

Encoder.prototype.encodeIndexedHeader = function(index) {
  var opCode = 0x80;
  var prefixLength = 7;
  this.encodeInteger(opCode, prefixLength, index);
}

Encoder.prototype.encodeLiteralHeaderWithoutIndexing = function(
  indexOrName, value) {
  var opCode = 0x60;
  var prefixLength = 5;
  switch (typeof indexOrName) {
    case 'number':
      this.encodeInteger(opCode, prefixLength, indexOrName + 1);
      this.encodeASCIIString(value);
      return;

    case 'string':
      this.encodeInteger(opCode, prefixLength, 0);
      this.encodeASCIIString(indexOrName);
      this.encodeASCIIString(value);
      return;
  }

  throw new Error('not an index or name: ' + indexOrName);
}

Encoder.prototype.encodeLiteralHeaderWithIncrementalIndexing = function(
  indexOrName, value) {
  var opCode = 0x20;
  var prefixLength = 5;
  switch (typeof indexOrName) {
    case 'number':
      this.encodeInteger(opCode, prefixLength, indexOrName + 1);
      this.encodeASCIIString(value);
      return;

    case 'string':
      this.encodeInteger(opCode, prefixLength, 0);
      this.encodeASCIIString(indexOrName);
      this.encodeASCIIString(value);
      return;
  }

  throw new Error('not an index or name: ' + indexOrName);
}
<|endoftext|>


<commit_before>/*jshint esnext:true */

var EXPORTED_SYMBOLS = ["specter"];

Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://specter/configuration.jsm");
Components.utils.import("resource://specter/progress_listener.jsm");
Components.utils.import("resource://specter/imagelib.jsm");
Components.utils.import("resource://specter/test_results.jsm");

const windowMediator =
        Components.classes["@mozilla.org/appshell/window-mediator;1"]
                .getService(Components.interfaces.nsIWindowMediator);

const xulAppInfo =
        Components.classes["@mozilla.org/xre/app-info;1"]
                .getService(Components.interfaces.nsIXULAppInfo);

const dirsvc =
        Components.classes["@mozilla.org/file/directory_service;1"]
                .getService(Components.interfaces.nsIProperties);

const timer =
        Components.classes["@mozilla.org/timer;1"]
                .createInstance(Components.interfaces.nsITimer);

var [major, minor, patch] = xulAppInfo.version.split('.');
var _version = {
    major: checkInt(major),
    minor: checkInt(minor),
    patch: checkInt(patch),
    __exposedProps__ : {
        major:'r',
        minor:'r',
        patch:'r'
    }
};
function checkInt(val) {
    let v = parseInt(val)
    if (isNaN(v))
        return 0;
    return v;
}

var parentwin = windowMediator.getMostRecentWindow("specter");
var window, browser, loaded=false, pagedone=true;
var queue=[], testFile, testName, pagesize;
var fnOnload, fnOnunload;

// convenience function
function $(selector) {
    var doc = browser.contentWindow.wrappedJSObject.document;
    return doc.querySelector(selector);
}

// capture an element, given its selector
function capture(selector, filename) {

    // find the element on screen or exit
    var clip,
        el = $(selector);

    if (el) {
        if (el.offsetWidth <= 0 || el.offsetHeight <= 0) {
            log("NotVisibleError: Unable to capture '" + selector + "'.");
            return;
        }
        clip = el.getBoundingClientRect();
    } else {
        log("NotFoundError: Unable to capture '" + selector + "' in " + testFile.path);
        TestResults.error(filename);
        return;
    }

    if (!configuration.testroot.contains(testFile, false)) {
        log('ConfigError: Test files are not within "testroot".');
        exit(-255);
    }
    // determine the relative path to the test file from the base dir
    let _dirs = [], _testfile = testFile.parent.clone();
    while (!_testfile.equals(configuration.testroot)) {
        _dirs.unshift(_testfile.leafName);
        _testfile = _testfile.parent;
    }

    // build the name of the capture file
    var capture_name = [testName, filename, pagesize].join('-');

    // determine the expected location of the baseline image
    var baseline = configuration.baseline.clone();
    for (let i=0; i<_dirs.length; i++) {
        baseline.append(_dirs[i]);
    }
    baseline.append(capture_name + '.png');

    // if rebasing, delete old baseline
    if (configuration.rebase) {
        if (baseline.exists()) {
            baseline.remove(false);
        }
    }

    if (baseline.exists()) {
        // capture and compare
        let content = imagelib.capture(window, clip, null);
        let blob = File(baseline);
        let basedata = imagelib.createImage(blob);
        let diff = imagelib.compare(content, basedata);
        if (diff) {
            let diffFile = configuration.diffdir.clone();
            for (let i=0; i<_dirs.length; i++) {
                diffFile.append(_dirs[i]);
            }
            diffFile.append(capture_name + '-diff.png');
            imagelib.saveCanvas(diff, diffFile);
            _dirs.unshift(configuration.diffdir.path);
            _dirs.push(capture_name + '-diff.png');
            TestResults.fail(_dirs.join('/'));
        } else {
            TestResults.pass(capture_name);
        }
    } else {
        // capture and save
        imagelib.capture(window, clip, baseline);
        TestResults.rebase(capture_name);
    }
    return;
}

function click(selector) {
    queue.push(function clickSelector() {
        var w = browser.contentWindow.wrappedJSObject,
            el = w.document.querySelector(selector);
        if (el) {
            el.click();
        } else {
            log("ClickError: element not found '" + selector + "' in " + testFile.path);
        }
    });
}

function exit(code) {
    dump("\n");
    let c = code || 0;
    data = 'exit ' + c;

    try {
        var file = Components.classes["@mozilla.org/file/local;1"]
                       .createInstance(Components.interfaces.nsILocalFile);
        file.initWithPath(configuration.outfile);
        if (!file.exists()) {
            file.create(Components.interfaces.nsIFile.NORMAL_FILE_TYPE,
                parseInt('0666', 8));
        }
        var fstream =
                Components.classes["@mozilla.org/network/file-output-stream;1"]
                    .createInstance(Components.interfaces.nsIFileOutputStream);
        fstream.init(file, 2, 0x200, false);
        var cstream =
                Components.classes["@mozilla.org/intl/converter-output-stream;1"]
                    .createInstance(Components.interfaces.nsIConverterOutputStream);
        cstream.init(fstream, 'UTF-8', data.length,
                Components.interfaces.nsIConverterInputStream.DEFAULTREPLACEMENT_CHARACTER);

        // if a failviewer is defined run it for failed diffs
        if (TestResults.failCount > 0 && configuration.failviewer) {
            cstream.writeString(configuration.failviewer + ' ' +
                    TestResults.failedTests.join(' ') + '\n');
        }

        cstream.writeString(data);
        cstream.close();
        fstream.close();
    //} catch(ex) {
    //    log(ex);
    } finally {
        Services.startup.quit(Components.interfaces.nsIAppStartup.eForceQuit);
    }
}

function hide(selector) {
    queue.push(function hideSelector(){
        var w = browser.contentWindow.wrappedJSObject,
            el = w.document.querySelector(selector);
        el.style.display = 'none';
    });
}

function log(s) {
    dump(s + "\n");
}

function onLoad(callback) {
    fnOnload = callback;
}

function onUnload(callback) {
    fnOnunload = callback;
}

function open(uri, callback) {
    loaded = false;
    pagedone = false;

    let features = "chrome,dialog=no,scrollbars=yes";
        features += ",width=1000,height=500";

    window = parentwin.openDialog(
            'chrome://specter/content/webpage.xul',
            '_blank', features, { callback:function(b){

        browser = b;
        addLoadListener(callback);

        try {
            browser.loadURI(getURL(uri), null, null);
            //browser.webNavigation.loadURI(uri,
            //    0, null, null, null);
        } catch(ex) {
            log(ex);
            loaded = true;
            pagedone = true;
        }
    }});
}

function waitForLoad() {
    queue.push(function() {
        taskready = function() { return false; }
        addLoadListener(function loadDone() {
            taskready = function() { return true; }
        });
    });
}

function addLoadListener(callback) {
    ProgressListener.setListener(function loadListener(){
        loaded = true;
        ProgressListener.setListener(function(){});
        browser.removeProgressListener(ProgressListener);
        if (fnOnload && typeof fnOnload === 'function') {
            fnOnload();
        }
        callback();
    });
    browser.addProgressListener(ProgressListener,
            Components.interfaces.nsIWebProgress.NOTIFY_STATE_DOCUMENT);
}

function getURL(uri) {
    var match=null, path='';
    // check for relative URL
    if (uri.indexOf('://') < 0) {

        // determine the relative path to the test file from the base dir
        let _dirs = [], _testfile = testFile.clone();
        while (!_testfile.equals(configuration.testroot)) {
            _dirs.unshift(_testfile.leafName);
            _testfile = _testfile.parent;
        }
        let _path = _dirs.join('/');

        for (path in configuration.hostnames) {
            if (_path.indexOf(path) === 0) {
                return configuration.hostnames[path] + uri;
            }
        }
        if (configuration.hostname) {
            return configuration.hostname + uri;
        } else {
            let dir = testFile.parent.clone();
            dir.append(uri);
            return 'file://' + dir.path;
        }
    } else {
        return uri;
    }
}

function perform(fn) {
    queue.push(fn.bind(specter));
}

function remove(selector) {
    queue.push(function removeSelector(){
        var w = browser.contentWindow.wrappedJSObject,
            el = w.document.querySelector(selector);
        el.parentNode.removeChild(el);
    });
}

function show(selector) {
    queue.push(function showSelector(){
        var w = browser.contentWindow.wrappedJSObject,
            el = w.document.querySelector(selector);
        el.style.display = '';
    });
}

function taskready() {
    return true;
}

function dequeue() {
    if (taskready()) {
        var fn;
        if (fn = queue.shift()) {
            fn();
        } else {
            timer.cancel();
            if (fnOnunload && typeof fnOnunload === 'function') {
                fnOnunload();
            }
            pagedone = true;
            if (browser) {
                browser = null;
            }
            if (window) {
                window.close();
                window = null;
            }
        }
    }
}

function runTests(){
    timer.initWithCallback(dequeue, 50, timer.TYPE_REPEATING_SLACK);
}

function setViewport(width, height) {
    window.resizeTo(width, height);
}

function test(sizes, testFunc) {
    if (({}).toString.call(sizes).indexOf("Array") < 0) {
        sizes = [sizes];
    }
    for (let size in sizes) {
        let mysize = String(sizes[size]);

        queue.push(function(){
            pagesize = mysize;
            let s = pagesize.split(/[x:,-]/);
            if (s.length > 1) {
                setViewport(s[0], s[1]);
            } else {
                setViewport(s[0], 400);
            }
        });
        queue.push(testFunc);
    }
}

function wait (delay) {
    queue.push(function(){
        var start = new Date();
        taskready = function() {
            return (new Date() - start) > delay;
        };
    });
}

function waitFor(readyFn) {
    var timeout = 5000,
        start = new Date();
    if (arguments.length > 1 && !isNaN(arguments[1])) {
        timeout = arguments[1];
    }
    queue.push(function(){
        taskready = function() {
            var now = new Date();
            if (now - start > timeout) {
                while (queue.length) {
                    queue.shift();
                }
                taskready = function() { return true; };
                TestResults.error(testFile.path);
            } else {
                if (readyFn()) {
                    taskready = function() { return true; };
                }
            }
        };
    }.bind(specter));
}

var specter = {

    capture: capture,

    // clear all current FTP/HTTP authentication sessions
    clearHttpAuth : function() {
        // clear all auth tokens
        let sdr = Components.classes["@mozilla.org/security/sdr;1"]
                    .getService(Components.interfaces.nsISecretDecoderRing);
        sdr.logoutAndTeardown();
        // clear FTP and plain HTTP auth sessions
        Services.obs.notifyObservers(null, "net:clear-active-logins", null);
    },

    click: click,

    get config() {
        return configuration;
    },

    exit: exit,
    hide: hide,
    log: log,
    onLoad: onLoad,
    onUnload: onUnload,
    open: open,
    perform: perform,

    get ready() {
        return pagedone;
    },

    remove: remove,
    runTests: runTests,
    show: show,
    test: test,

    turn_off_animations: function() {
        //
    },

    setTestFile: function(file) {
        testFile = file;
        testName = file.leafName.replace(/(^test[_\-])|(\.js$)/g, '');
    },

    get version() {
        return _version;
    },

    viewport: function(w, h) {
        //page.viewportSize({width: w, height: h});
    },

    wait: wait,
    waitFor: waitFor,
    waitForLoad: waitForLoad,

    get window() {
        try {
            return browser.contentWindow.wrappedJSObject;
        } catch (ex) {
            return null;
        }
    },

    __exposedProps__ : {
        capture: 'r',
        click: 'r',
        config: 'r',
        debug: 'r',
        exit: 'r',
        hide: 'r',
        log: 'r',
        onLoad: 'r',
        onUnload: 'r',
        open: 'r',
        ready: 'r',
        remove: 'r',
        runTests: 'r',
        setTestFile: 'r',
        show: 'r',
        test: 'r',
        testName: 'rw',
        turn_off_animations: 'r',
        version: 'r',
        viewport: 'r',
        wait: 'r',
        waitFor: 'r',
        waitForLoad: 'r'
    }
};
<commit_msg>line breaks for errors, closes #34<commit_after>/*jshint esnext:true */

var EXPORTED_SYMBOLS = ["specter"];

Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://specter/configuration.jsm");
Components.utils.import("resource://specter/progress_listener.jsm");
Components.utils.import("resource://specter/imagelib.jsm");
Components.utils.import("resource://specter/test_results.jsm");

const windowMediator =
        Components.classes["@mozilla.org/appshell/window-mediator;1"]
                .getService(Components.interfaces.nsIWindowMediator);

const xulAppInfo =
        Components.classes["@mozilla.org/xre/app-info;1"]
                .getService(Components.interfaces.nsIXULAppInfo);

const dirsvc =
        Components.classes["@mozilla.org/file/directory_service;1"]
                .getService(Components.interfaces.nsIProperties);

const timer =
        Components.classes["@mozilla.org/timer;1"]
                .createInstance(Components.interfaces.nsITimer);

var [major, minor, patch] = xulAppInfo.version.split('.');
var _version = {
    major: checkInt(major),
    minor: checkInt(minor),
    patch: checkInt(patch),
    __exposedProps__ : {
        major:'r',
        minor:'r',
        patch:'r'
    }
};
function checkInt(val) {
    let v = parseInt(val)
    if (isNaN(v))
        return 0;
    return v;
}

var parentwin = windowMediator.getMostRecentWindow("specter");
var window, browser, loaded=false, pagedone=true;
var queue=[], testFile, testName, pagesize;
var fnOnload, fnOnunload;

// convenience function
function $(selector) {
    var doc = browser.contentWindow.wrappedJSObject.document;
    return doc.querySelector(selector);
}

// capture an element, given its selector
function capture(selector, filename) {

    // find the element on screen or exit
    var clip,
        el = $(selector);

    if (el) {
        if (el.offsetWidth <= 0 || el.offsetHeight <= 0) {
            log("\nNotVisibleError: Unable to capture '" + selector + "'.\n");
            return;
        }
        clip = el.getBoundingClientRect();
    } else {
        log("\nNotFoundError: Unable to capture '" + selector + "' in " + testFile.path + "\n");
        TestResults.error(filename);
        return;
    }

    if (!configuration.testroot.contains(testFile, false)) {
        log('\nConfigError: Test files are not within "testroot".\n');
        exit(-255);
    }
    // determine the relative path to the test file from the base dir
    let _dirs = [], _testfile = testFile.parent.clone();
    while (!_testfile.equals(configuration.testroot)) {
        _dirs.unshift(_testfile.leafName);
        _testfile = _testfile.parent;
    }

    // build the name of the capture file
    var capture_name = [testName, filename, pagesize].join('-');

    // determine the expected location of the baseline image
    var baseline = configuration.baseline.clone();
    for (let i=0; i<_dirs.length; i++) {
        baseline.append(_dirs[i]);
    }
    baseline.append(capture_name + '.png');

    // if rebasing, delete old baseline
    if (configuration.rebase) {
        if (baseline.exists()) {
            baseline.remove(false);
        }
    }

    if (baseline.exists()) {
        // capture and compare
        let content = imagelib.capture(window, clip, null);
        let blob = File(baseline);
        let basedata = imagelib.createImage(blob);
        let diff = imagelib.compare(content, basedata);
        if (diff) {
            let diffFile = configuration.diffdir.clone();
            for (let i=0; i<_dirs.length; i++) {
                diffFile.append(_dirs[i]);
            }
            diffFile.append(capture_name + '-diff.png');
            imagelib.saveCanvas(diff, diffFile);
            _dirs.unshift(configuration.diffdir.path);
            _dirs.push(capture_name + '-diff.png');
            TestResults.fail(_dirs.join('/'));
        } else {
            TestResults.pass(capture_name);
        }
    } else {
        // capture and save
        imagelib.capture(window, clip, baseline);
        TestResults.rebase(capture_name);
    }
    return;
}

function click(selector) {
    queue.push(function clickSelector() {
        var w = browser.contentWindow.wrappedJSObject,
            el = w.document.querySelector(selector);
        if (el) {
            el.click();
        } else {
            log("\nClickError: element not found '" + selector + "' in " + testFile.path + "\n");
        }
    });
}

function exit(code) {
    dump("\n");
    let c = code || 0;
    data = 'exit ' + c;

    try {
        var file = Components.classes["@mozilla.org/file/local;1"]
                       .createInstance(Components.interfaces.nsILocalFile);
        file.initWithPath(configuration.outfile);
        if (!file.exists()) {
            file.create(Components.interfaces.nsIFile.NORMAL_FILE_TYPE,
                parseInt('0666', 8));
        }
        var fstream =
                Components.classes["@mozilla.org/network/file-output-stream;1"]
                    .createInstance(Components.interfaces.nsIFileOutputStream);
        fstream.init(file, 2, 0x200, false);
        var cstream =
                Components.classes["@mozilla.org/intl/converter-output-stream;1"]
                    .createInstance(Components.interfaces.nsIConverterOutputStream);
        cstream.init(fstream, 'UTF-8', data.length,
                Components.interfaces.nsIConverterInputStream.DEFAULTREPLACEMENT_CHARACTER);

        // if a failviewer is defined run it for failed diffs
        if (TestResults.failCount > 0 && configuration.failviewer) {
            cstream.writeString(configuration.failviewer + ' ' +
                    TestResults.failedTests.join(' ') + '\n');
        }

        cstream.writeString(data);
        cstream.close();
        fstream.close();
    //} catch(ex) {
    //    log(ex);
    } finally {
        Services.startup.quit(Components.interfaces.nsIAppStartup.eForceQuit);
    }
}

function hide(selector) {
    queue.push(function hideSelector(){
        var w = browser.contentWindow.wrappedJSObject,
            el = w.document.querySelector(selector);
        el.style.display = 'none';
    });
}

function log(s) {
    dump(s + "\n");
}

function onLoad(callback) {
    fnOnload = callback;
}

function onUnload(callback) {
    fnOnunload = callback;
}

function open(uri, callback) {
    loaded = false;
    pagedone = false;

    let features = "chrome,dialog=no,scrollbars=yes";
        features += ",width=1000,height=500";

    window = parentwin.openDialog(
            'chrome://specter/content/webpage.xul',
            '_blank', features, { callback:function(b){

        browser = b;
        addLoadListener(callback);

        try {
            browser.loadURI(getURL(uri), null, null);
            //browser.webNavigation.loadURI(uri,
            //    0, null, null, null);
        } catch(ex) {
            log(ex);
            loaded = true;
            pagedone = true;
        }
    }});
}

function waitForLoad() {
    queue.push(function() {
        taskready = function() { return false; }
        addLoadListener(function loadDone() {
            taskready = function() { return true; }
        });
    });
}

function addLoadListener(callback) {
    ProgressListener.setListener(function loadListener(){
        loaded = true;
        ProgressListener.setListener(function(){});
        browser.removeProgressListener(ProgressListener);
        if (fnOnload && typeof fnOnload === 'function') {
            fnOnload();
        }
        callback();
    });
    browser.addProgressListener(ProgressListener,
            Components.interfaces.nsIWebProgress.NOTIFY_STATE_DOCUMENT);
}

function getURL(uri) {
    var match=null, path='';
    // check for relative URL
    if (uri.indexOf('://') < 0) {

        // determine the relative path to the test file from the base dir
        let _dirs = [], _testfile = testFile.clone();
        while (!_testfile.equals(configuration.testroot)) {
            _dirs.unshift(_testfile.leafName);
            _testfile = _testfile.parent;
        }
        let _path = _dirs.join('/');

        for (path in configuration.hostnames) {
            if (_path.indexOf(path) === 0) {
                return configuration.hostnames[path] + uri;
            }
        }
        if (configuration.hostname) {
            return configuration.hostname + uri;
        } else {
            let dir = testFile.parent.clone();
            dir.append(uri);
            return 'file://' + dir.path;
        }
    } else {
        return uri;
    }
}

function perform(fn) {
    queue.push(fn.bind(specter));
}

function remove(selector) {
    queue.push(function removeSelector(){
        var w = browser.contentWindow.wrappedJSObject,
            el = w.document.querySelector(selector);
        el.parentNode.removeChild(el);
    });
}

function show(selector) {
    queue.push(function showSelector(){
        var w = browser.contentWindow.wrappedJSObject,
            el = w.document.querySelector(selector);
        el.style.display = '';
    });
}

function taskready() {
    return true;
}

function dequeue() {
    if (taskready()) {
        var fn;
        if (fn = queue.shift()) {
            fn();
        } else {
            timer.cancel();
            if (fnOnunload && typeof fnOnunload === 'function') {
                fnOnunload();
            }
            pagedone = true;
            if (browser) {
                browser = null;
            }
            if (window) {
                window.close();
                window = null;
            }
        }
    }
}

function runTests(){
    timer.initWithCallback(dequeue, 50, timer.TYPE_REPEATING_SLACK);
}

function setViewport(width, height) {
    window.resizeTo(width, height);
}

function test(sizes, testFunc) {
    if (({}).toString.call(sizes).indexOf("Array") < 0) {
        sizes = [sizes];
    }
    for (let size in sizes) {
        let mysize = String(sizes[size]);

        queue.push(function(){
            pagesize = mysize;
            let s = pagesize.split(/[x:,-]/);
            if (s.length > 1) {
                setViewport(s[0], s[1]);
            } else {
                setViewport(s[0], 400);
            }
        });
        queue.push(testFunc);
    }
}

function wait (delay) {
    queue.push(function(){
        var start = new Date();
        taskready = function() {
            return (new Date() - start) > delay;
        };
    });
}

function waitFor(readyFn) {
    var timeout = 5000,
        start = new Date();
    if (arguments.length > 1 && !isNaN(arguments[1])) {
        timeout = arguments[1];
    }
    queue.push(function(){
        taskready = function() {
            var now = new Date();
            if (now - start > timeout) {
                while (queue.length) {
                    queue.shift();
                }
                taskready = function() { return true; };
                TestResults.error(testFile.path);
            } else {
                if (readyFn()) {
                    taskready = function() { return true; };
                }
            }
        };
    }.bind(specter));
}

var specter = {

    capture: capture,

    // clear all current FTP/HTTP authentication sessions
    clearHttpAuth : function() {
        // clear all auth tokens
        let sdr = Components.classes["@mozilla.org/security/sdr;1"]
                    .getService(Components.interfaces.nsISecretDecoderRing);
        sdr.logoutAndTeardown();
        // clear FTP and plain HTTP auth sessions
        Services.obs.notifyObservers(null, "net:clear-active-logins", null);
    },

    click: click,

    get config() {
        return configuration;
    },

    exit: exit,
    hide: hide,
    log: log,
    onLoad: onLoad,
    onUnload: onUnload,
    open: open,
    perform: perform,

    get ready() {
        return pagedone;
    },

    remove: remove,
    runTests: runTests,
    show: show,
    test: test,

    turn_off_animations: function() {
        //
    },

    setTestFile: function(file) {
        testFile = file;
        testName = file.leafName.replace(/(^test[_\-])|(\.js$)/g, '');
    },

    get version() {
        return _version;
    },

    viewport: function(w, h) {
        //page.viewportSize({width: w, height: h});
    },

    wait: wait,
    waitFor: waitFor,
    waitForLoad: waitForLoad,

    get window() {
        try {
            return browser.contentWindow.wrappedJSObject;
        } catch (ex) {
            return null;
        }
    },

    __exposedProps__ : {
        capture: 'r',
        click: 'r',
        config: 'r',
        debug: 'r',
        exit: 'r',
        hide: 'r',
        log: 'r',
        onLoad: 'r',
        onUnload: 'r',
        open: 'r',
        ready: 'r',
        remove: 'r',
        runTests: 'r',
        setTestFile: 'r',
        show: 'r',
        test: 'r',
        testName: 'rw',
        turn_off_animations: 'r',
        version: 'r',
        viewport: 'r',
        wait: 'r',
        waitFor: 'r',
        waitForLoad: 'r'
    }
};
<|endoftext|>


<commit_before>// Copyright 2002-2014, University of Colorado Boulder

/**
 * RequireJS configuration file for the 'Fraction Matcher' sim.
 * Paths are relative to the location of this file.
 *
 * @author Anton Ulyanov (Mlearner)
 */

require.config( {

  deps: [ 'fraction-matcher-main' ],

  config: {
    i18n: {
      locale: 'en_us'
    }
  },

  paths: {
// third-party libs
    text: '../../sherpa/text',
    image: '../../chipper/requirejs-plugins/image',
    audio: '../../chipper/requirejs-plugins/audio',
    string: '../../chipper/requirejs-plugins/string',

    // PhET libs, uppercase names to identify them in require.js imports
    AXON: '../../axon/js',
    BRAND: '../../brand/js',
    DOT: '../../dot/js',
    JOIST: '../../joist/js',
    KITE: '../../kite/js',
    PHET_CORE: '../../phet-core/js',
    PHETCOMMON: '../../phetcommon/js',
    SHERPA: '../../sherpa',
    SCENERY: '../../scenery/js',
    SCENERY_PHET: '../../scenery-phet/js',
    SUN: '../../sun/js',
    VIBE: '../../vibe/js',
    VEGAS: '../../vegas/js',
    // contrib dependencies required by common directories
    stats: '../../phetcommon/contrib/stats-r11',

    //Sim code
    FRACTION_MATCHER: '.'
  },
  // Configure the dependencies and exports for older, traditional 'browser globals' scripts
  // that do not use define() to declare the dependencies and set a module value.
  shim: {
    stats: {
      exports: 'Stats'
    }
  },
  urlArgs: new Date().getTime()  // cache buster to make browser refresh load all included scripts
} );
<commit_msg>Added cache buster as an option & standardized formatting for config files, see https://github.com/phetsims/joist/issues/196<commit_after>// Copyright 2002-2014, University of Colorado Boulder

/**
 * RequireJS configuration file for the 'Fraction Matcher' sim.
 * Paths are relative to the location of this file.
 *
 * @author Anton Ulyanov (Mlearner)
 */

require.config( {

  deps: [ 'fraction-matcher-main' ],

  config: {
    i18n: {
      locale: 'en_us'
    }
  },

  paths: {
// third-party libs
    text: '../../sherpa/text',
    image: '../../chipper/requirejs-plugins/image',
    audio: '../../chipper/requirejs-plugins/audio',
    string: '../../chipper/requirejs-plugins/string',

    // PhET libs, uppercase names to identify them in require.js imports
    AXON: '../../axon/js',
    BRAND: '../../brand/js',
    DOT: '../../dot/js',
    JOIST: '../../joist/js',
    KITE: '../../kite/js',
    PHET_CORE: '../../phet-core/js',
    PHETCOMMON: '../../phetcommon/js',
    SHERPA: '../../sherpa',
    SCENERY: '../../scenery/js',
    SCENERY_PHET: '../../scenery-phet/js',
    SUN: '../../sun/js',
    VIBE: '../../vibe/js',
    VEGAS: '../../vegas/js',
    // contrib dependencies required by common directories
    stats: '../../phetcommon/contrib/stats-r11',

    //Sim code
    FRACTION_MATCHER: '.'
  },
  // Configure the dependencies and exports for older, traditional 'browser globals' scripts
  // that do not use define() to declare the dependencies and set a module value.
  shim: {
    stats: {
      exports: 'Stats'
    }
  },

  // optional cache buster to make browser refresh load all included scripts, can be disabled with ?cacheBuster=false
  urlArgs: phet.phetcommon.getCacheBusterArgs()
} );
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var parallel = require('run-parallel');
var TypedError = require('error/typed');
var util = require('util');

var EndpointAlreadyDefinedError = TypedError({
    type: 'endpoint-already-defined',
    message: 'endpoint {endpoint} already defined on service {service}',
    service: null,
    endpoint: null,
    oldHandler: null,
    newHandler:  null
});

var InvalidHandlerError = TypedError({
    type: 'invalid-handler',
    message: 'invalid handler function'
});

function TChannelEndpointHandler(serviceName) {
    if (!(this instanceof TChannelEndpointHandler)) {
        return new TChannelEndpointHandler(serviceName);
    }
    var self = this;
    self.serviceName = serviceName;
    self.endpoints = Object.create(null);
    self.type = null;
}

TChannelEndpointHandler.prototype.register = function register(name, handler) {
    var self = this;
    if (self.endpoints[name] !== undefined) {
        throw EndpointAlreadyDefinedError({
            service: self.serviceName,
            endpoint: name,
            oldHandler: self.endpoints[name],
            newHandler: handler
        });
    }
    if (typeof handler !== 'function') {
        throw InvalidHandlerError();
    }
    self.endpoints[name] = handler;
    return handler;
};

TChannelEndpointHandler.prototype.handleRequest = function handleRequest(req, res) {
    var self = this;
    // TODO: waterfall
    req.arg1.onValueReady(function arg1Ready(err, arg1) {
        if (err) throw err; // TODO: protocol error, respond with error frame
        handleArg1(arg1);
    });

    function handleArg1(arg1) {
        var name = String(arg1);
        var handler = self.endpoints[name];
        if (!handler) {
            sendError('BadRequest', util.format(
                'no such endpoint service=%j endpoint=%j',
                req.service, name));
        } else if (handler.canStream) {
            handler(req, res);
        } else {
            parallel({
                arg2: req.arg2.onValueReady,
                arg3: req.arg3.onValueReady
            }, argsDone);
        }

        function argsDone(err, args) {
            if (err) {
                throw err; // TODO: protocol error, respond with error frame
            } else {
                compatHandle(handler, args);
            }
        }

        function compatHandle(handler, args) {
            handler(req, res, args.arg2, args.arg3);
        }
    }

    function sendError(code, mess) {
        res.sendError(code, mess);
    }
};

module.exports = TChannelEndpointHandler;
<commit_msg>endpoint-handler: send UnexpectedError frame rather than throwing<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var parallel = require('run-parallel');
var TypedError = require('error/typed');
var util = require('util');

var EndpointAlreadyDefinedError = TypedError({
    type: 'endpoint-already-defined',
    message: 'endpoint {endpoint} already defined on service {service}',
    service: null,
    endpoint: null,
    oldHandler: null,
    newHandler:  null
});

var InvalidHandlerError = TypedError({
    type: 'invalid-handler',
    message: 'invalid handler function'
});

function TChannelEndpointHandler(serviceName) {
    if (!(this instanceof TChannelEndpointHandler)) {
        return new TChannelEndpointHandler(serviceName);
    }
    var self = this;
    self.serviceName = serviceName;
    self.endpoints = Object.create(null);
    self.type = null;
}

TChannelEndpointHandler.prototype.register = function register(name, handler) {
    var self = this;
    if (self.endpoints[name] !== undefined) {
        throw EndpointAlreadyDefinedError({
            service: self.serviceName,
            endpoint: name,
            oldHandler: self.endpoints[name],
            newHandler: handler
        });
    }
    if (typeof handler !== 'function') {
        throw InvalidHandlerError();
    }
    self.endpoints[name] = handler;
    return handler;
};

TChannelEndpointHandler.prototype.handleRequest = function handleRequest(req, res) {
    var self = this;
    // TODO: waterfall
    req.arg1.onValueReady(function arg1Ready(err, arg1) {
        if (err) {
            // TODO: log error
            sendError('UnexpectedError', util.format(
                'error accumulating arg1: %s: %s',
                err.constructor.name, err.message));
        } else {
            handleArg1(arg1);
        }
    });

    function handleArg1(arg1) {
        var name = String(arg1);
        var handler = self.endpoints[name];
        if (!handler) {
            sendError('BadRequest', util.format(
                'no such endpoint service=%j endpoint=%j',
                req.service, name));
        } else if (handler.canStream) {
            handler(req, res);
        } else {
            parallel({
                arg2: req.arg2.onValueReady,
                arg3: req.arg3.onValueReady
            }, argsDone);
        }

        function argsDone(err, args) {
            if (err) {
                // TODO: log error
                sendError('UnexpectedError', util.format(
                    'error accumulating arg2/arg3: %s: %s',
                    err.constructor.name, err.message));
            } else {
                compatHandle(handler, args);
            }
        }

        function compatHandle(handler, args) {
            handler(req, res, args.arg2, args.arg3);
        }
    }

    function sendError(code, mess) {
        res.sendError(code, mess);
    }
};

module.exports = TChannelEndpointHandler;
<|endoftext|>


<commit_before>"use strict"
var userToken = process.env.AGENDOR_TOKEN;
var agendorUrl = "https://api.agendor.com.br/v1/";
var request = require('request');

module.exports.nextTask = function nextTask(sendTextMessage, sender, res) {
  request({
    url: agendorUrl + "tasks",
    headers: {"Authorization": "Token " + userToken},
    qs: {page:1, per_page:1},
    method: 'GET'
  }, function(error, response, body) {
    if (error) {
      console.log('Error sending messages: ', error)
    } else if (response.body.error) {
      console.log('Error: ', response.body.error)
    }
    console.log("statusCode");
    console.log(JSON.parse(body));
    console.log("end statusCode");
    if (!error && response.statusCode == 200) {
      var text = formatTask(body);
      sendTextMessage(text, sender);
      res.sendStatus(200);
    }
  });
};

function formatTask(task) {
  var entity;
  var entityDesc;
  if (task.deal) {
    entityDesc = "o negócio";
    entity = task.deal.name;
  } else if (task.organization) {
    entityDesc = "a empresa";
    entity = task.organization.legalName;
  } else if (task.person) {
    entityDesc = "a pessoa";
    entity = task.person.name;
  }

  var text = task.text;
  var dueDate = task.dueDate;

  var textMessage = "Você possuí uma tarefa para " + entityDesc + ": " + entity + " ";
  if (dueDate) {
    textMessage += "às " + dueDate;
  }
  if (text) {
    textMessage += "\n Descrição:\n" + text;
  }
  return textMessage;
}
<commit_msg>Fix some issues<commit_after>"use strict"
var userToken = process.env.AGENDOR_TOKEN;
var agendorUrl = "https://api.agendor.com.br/v1/";
var request = require('request');

module.exports.nextTask = function nextTask(sendTextMessage, sender, res) {
  request({
    url: agendorUrl + "tasks",
    headers: {"Authorization": "Token " + userToken},
    qs: {page:1, per_page:1},
    method: 'GET'
  }, function(error, response, body) {
    if (error) {
      console.log('Error sending messages: ', error)
    } else if (response.body.error) {
      console.log('Error: ', response.body.error)
    }
    console.log("statusCode");
    console.log(JSON.parse(body)[0]);
    console.log("end statusCode");
    if (!error && response.statusCode == 200) {
      var text = formatTask(body);
      sendTextMessage(text, sender);
      res.sendStatus(200);
    }
  });
};

function formatTask(task) {
  var entity;
  var entityDesc;
  if (task.deal) {
    entityDesc = "o negócio";
    entity = task.deal.name;
  } else if (task.organization) {
    entityDesc = "a empresa";
    entity = task.organization.legalName;
  } else if (task.person) {
    entityDesc = "a pessoa";
    entity = task.person.name;
  }

  var text = task.text;
  var dueDate = task.dueDate;

  var textMessage = "Você possuí uma tarefa para " + entityDesc + ": " + entity + " ";
  if (dueDate) {
    textMessage += "às " + dueDate;
  }
  if (text) {
    textMessage += "\n Descrição:\n" + text;
  }
  return textMessage;
}
<|endoftext|>


<commit_before>const { injectBabelPlugin, getLoader, getBabelLoader, loaderNameMatches } = require('react-app-rewired')

module.exports = function override(config, env) {
  // Inject all babel plugins before rewiring typescript

  // Inject babel-plugin-emotion
  config = injectBabelPlugin(
    [
      'emotion',
      {
        autoLabel: true,
        hoist: env === 'production',
        labelFormat: '[filename]--[local]'
      }
    ],
    config
  )

  // Rewire typescript with our rewired babel config
  const babelLoader = getBabelLoader(config.module.rules)
  const tsLoader = getLoader(config.module.rules, rule => /ts|tsx/.test(rule.test))
  tsLoader.use.unshift({
    loader: babelLoader.loader,
    options: babelLoader.options
  })

  return config
}
<commit_msg>Add sourceMap to babel-emotion-plugin config<commit_after>const { injectBabelPlugin, getLoader, getBabelLoader, loaderNameMatches } = require('react-app-rewired')

module.exports = function override(config, env) {
  // Inject all babel plugins before rewiring typescript

  // Inject babel-plugin-emotion
  config = injectBabelPlugin(
    [
      'emotion',
      {
        autoLabel: true,
        hoist: env === 'production',
        labelFormat: '[filename]--[local]',
        sourceMap: env !== 'production'
      }
    ],
    config
  )

  // Rewire typescript with our rewired babel config
  const babelLoader = getBabelLoader(config.module.rules)
  const tsLoader = getLoader(config.module.rules, rule => /ts|tsx/.test(rule.test))
  tsLoader.use.unshift({
    loader: babelLoader.loader,
    options: babelLoader.options
  })

  return config
}
<|endoftext|>


<commit_before>// Copyright 2002-2015, University of Colorado Boulder

/**
 * Report which media files (such as images and audio) from a sim were not used in the simulation with a require statement.
 *
 * Each time a resource is loaded by a plugin (image, audio, mipmap,...) its license info is added to this global by
 * the plugin.  After all resources are loaded, the global will contain the list of all resources that are actually used
 * by the sim.  Comparing what's in the filesystem to this list identifies resources that are unused.
 *
 * See https://github.com/phetsims/chipper/issues/172
 *
 * @author Sam Reid
 */

// The following comment permits node-specific globals (such as process.cwd()) to pass jshint
/* jslint node: true */
'use strict';

// modules
var assert = require( 'assert' );

/**
 * @param grunt the grunt instance
 * @param {string} simNameUppercase - the upper-case string prefix such as BALANCING_ACT
 */
module.exports = function( grunt, simNameUppercase ) {

  // globals that should be defined by this point
  assert( global.phet.chipper.licenseEntries, 'missing global.phet.chipper.licenseEntries' );

  var directory = process.cwd();

  var endsWith = function( string, substring ) {
    return string.indexOf( substring ) === string.length - substring.length;
  };

  // Iterate over image directories and sub-directories
  if ( grunt.file.exists( directory + '/images' ) ) {
    grunt.file.recurse( directory + '/images', function( abspath, rootdir, subdir, filename ) {

      // check if the file on the HDD was loaded during requirejs
      var key = simNameUppercase + '/' + filename;

      if ( filename !== 'license.json' &&
           filename !== 'README.txt' &&
           global.phet.chipper.licenseEntries.images &&
           (!global.phet.chipper.licenseEntries.images.hasOwnProperty( key )) ) {
        grunt.log.warn( 'Unused image: ' + key );
      }
    } );
  }

  // Iterate over audio directories and sub-directories
  if ( grunt.file.exists( directory + '/audio' ) ) {
    grunt.file.recurse( directory + '/audio', function( abspath, rootdir, subdir, filename ) {

      // check if the file on the HDD was loaded during requirejs
      var key = simNameUppercase + '/' + filename;

      // if it is an audio file, strip off the suffix .mp3 or .ogg because audio is loaded without a suffix
      // The only exception is VIBE/empty.mp3 which doesn't require an ogg version (WHY?)
      if ( key !== 'VIBE/empty.mp3' ) {
        if ( endsWith( key, '.mp3' ) || endsWith( key, '.ogg' ) ) {
          key = key.substring( 0, key.length - 4 );
        }
      }
      if ( filename !== 'license.json' &&
           filename !== 'README.txt' &&
           global.phet.chipper.licenseEntries.audio &&
           (!global.phet.chipper.licenseEntries.audio.hasOwnProperty( key )) ) {
        grunt.log.warn( 'Unused image: ' + key );
      }
    } );
  }
};<commit_msg>#260 simNameUppercase -> requirejsNamespace<commit_after>// Copyright 2002-2015, University of Colorado Boulder

/**
 * Report which media files (such as images and audio) from a sim were not used in the simulation with a require statement.
 *
 * Each time a resource is loaded by a plugin (image, audio, mipmap,...) its license info is added to this global by
 * the plugin.  After all resources are loaded, the global will contain the list of all resources that are actually used
 * by the sim.  Comparing what's in the filesystem to this list identifies resources that are unused.
 *
 * See https://github.com/phetsims/chipper/issues/172
 *
 * @author Sam Reid
 */

// The following comment permits node-specific globals (such as process.cwd()) to pass jshint
/* jslint node: true */
'use strict';

// modules
var assert = require( 'assert' );

/**
 * @param grunt the grunt instance
 * @param {string} requirejsNamespace - requirejs namespace that appears in config.js, eg, BALANCING_ACT
 */
module.exports = function( grunt, requirejsNamespace ) {

  // globals that should be defined by this point
  assert( global.phet.chipper.licenseEntries, 'missing global.phet.chipper.licenseEntries' );

  var directory = process.cwd();

  var endsWith = function( string, substring ) {
    return string.indexOf( substring ) === string.length - substring.length;
  };

  // Iterate over image directories and sub-directories
  if ( grunt.file.exists( directory + '/images' ) ) {
    grunt.file.recurse( directory + '/images', function( abspath, rootdir, subdir, filename ) {

      // check if the file on the HDD was loaded during requirejs
      var key = requirejsNamespace + '/' + filename;

      if ( filename !== 'license.json' &&
           filename !== 'README.txt' &&
           global.phet.chipper.licenseEntries.images &&
           (!global.phet.chipper.licenseEntries.images.hasOwnProperty( key )) ) {
        grunt.log.warn( 'Unused image: ' + key );
      }
    } );
  }

  // Iterate over audio directories and sub-directories
  if ( grunt.file.exists( directory + '/audio' ) ) {
    grunt.file.recurse( directory + '/audio', function( abspath, rootdir, subdir, filename ) {

      // check if the file on the HDD was loaded during requirejs
      var key = requirejsNamespace + '/' + filename;

      // if it is an audio file, strip off the suffix .mp3 or .ogg because audio is loaded without a suffix
      // The only exception is VIBE/empty.mp3 which doesn't require an ogg version (WHY?)
      if ( key !== 'VIBE/empty.mp3' ) {
        if ( endsWith( key, '.mp3' ) || endsWith( key, '.ogg' ) ) {
          key = key.substring( 0, key.length - 4 );
        }
      }
      if ( filename !== 'license.json' &&
           filename !== 'README.txt' &&
           global.phet.chipper.licenseEntries.audio &&
           (!global.phet.chipper.licenseEntries.audio.hasOwnProperty( key )) ) {
        grunt.log.warn( 'Unused image: ' + key );
      }
    } );
  }
};<|endoftext|>


<commit_before>/**
 * @module Fire.Runtime
 */

var JS = Fire.JS;
var Ticker = Fire._Ticker;
var Time = Fire.Time;

var Utils = require('./utils');
var NYI = Utils.NYI;
var NYI_Accessor = Utils.NYI_Accessor;

//var SceneWrapper = require('./scene');

/**
 * !#zh 这个类用来封装编辑器对引擎的操作，并且提供运行时的一些全局接口和状态。
 * !#en Access to engine runtime data.
 * This class contains methods for looking up information about and controlling the runtime data.
 *
 * You should override:
 * - initRuntime
 * - playRuntime
 * - stopRuntime
 * - pauseRuntime
 * - resumeRuntime
 * - getCurrentRuntimeScene
 * - _setCurrentRuntimeScene
 * - tick (if useDefaultMainLoop)
 * - canvasSize
 * - getRuntimeInstanceById
 *
 * @class EngineWrapper
 * @extends Playable
 * @constructor
 * @param {boolean} useDefaultMainLoop - if true, tick() will be invoked every frame
 */
var EngineWrapper = Fire.Class({
    name: 'Fire.Runtime.EngineWrapper',
    extends: Fire.Playable,

    constructor: function () {
        var useDefaultMainLoop = arguments[0];

        /**
         * We should use this id to cancel ticker, otherwise if the engine stop and replay immediately,
         * last ticker will not cancel correctly.
         *
         * @property _requestId
         * @type {number}
         * @private
         */
        this._requestId = -1;

        this._useDefaultMainLoop = useDefaultMainLoop;
        this._isInitialized = false;

        // Scene name to uuid
        this._sceneInfos = {};

        // current scene
        this._scene = null;

        this._loadingScene = '';

        this._bindedTick = useDefaultMainLoop && this._tick.bind(this);
    },

    properties: {
        /**
         * @property {boolean} isInitialized - Indicates whether the engine instance is initialized.
         * @readOnly
         */
        isInitialized: {
            get: function () {
                return this._isInitialized;
            }
        },

        /**
         * @property {boolean} loadingScene
         * @readOnly
         */
        loadingScene: {
            get: function () {
                return this._loadingScene;
            }
        },

        /**
         * @property {Fire.Vec2} canvasSize - Resize the rendering canvas.
         */
        canvasSize: NYI_Accessor(Fire.Vec2.zero)
    },

    // TO OVERRIDE

    /**
     * @callback InitCallback
     * @param {string} [error] - null or the error info
     */

    /**
     * Initialize the runtime. This method will be called by init method.
     * @method initRuntime
     * @param {object} options
     * @param {number} options.width
     * @param {number} options.height
     * @param {Canvas} [options.canvas]
     * @param {InitCallback} callback
     */
    initRuntime: function (options, callback) {
        NYI();
        callback();
    },

    /**
     * Starts playback.
     * @method playRuntime
     */
    playRuntime: NYI,

    /**
     * Stops playback.
     * @method stopRuntime
     */
    stopRuntime: NYI,

    /**
     * Pauses playback.
     * @method pauseRuntime
     */
    pauseRuntime: NYI,

    /**
     * Resumes playback.
     * @method resumeRuntime
     */
    resumeRuntime: NYI,

    ///**
    // * Steps playback.
    // * @method stepRuntime
    // */
    //stepRuntime: NYI,

    /**
     * Get the current running runtime scene.
     * @method getCurrentRuntimeScene
     * @return {RuntimeNode}
     */
    getCurrentRuntimeScene: NYI,

    /**
     * Set the current running runtime scene.
     * @method _setCurrentRuntimeScene
     * @param {RuntimeNode}
     */
    _setCurrentRuntimeScene: NYI,

    /**
     * Returns the node which id is id.
     * @method getRuntimeInstanceById
     * @param {String} id
     * @return {Object}
     */
    getRuntimeInstanceById: NYI,

    tickInEditMode: function () {

    },

    /**
     * @method tick
     * @param {number} deltaTime
     * @param {boolean} updateLogic
     */
    tick: function (deltaTime, updateLogic) {
        NYI();

        // Example: (not required)
        if (updateLogic) {
            // update input
            // update logic
            // update particle
            // update animation
        }
        // render scene
    },

    // PUBLIC

    /**
     * Initialize the engine. This method will be called by boot.js or editor.
     * @method init
     * @param {object} options
     * @param {number} options.width
     * @param {number} options.height
     * @param {Canvas} [options.canvas]
     * @param {initCallback} callback
     */
    init: function (options, callback) {
        if (this._isInitialized) {
            Fire.error('Engine already initialized');
            return;
        }
        this._isInitialized = true;

        if (options) {
            JS.mixin(this._sceneInfos, options.scenes);
            //Resources._resBundle.init(options.resBundle);
        }

        this.initRuntime(options, function (err) {
            //if ((FIRE_EDITOR || FIRE_TEST) && !err) {
            //    //var scene = SceneWrapper.getCurrentRuntimeScene()
            //    //if (editorCallback.onSceneLoaded) {
            //    //    editorCallback.onSceneLoaded(this._scene);
            //    //}
            //    editorCallback.onSceneLaunched(this._scene);
            //}
            callback(err);
        });
    },

    // OVERRIDE

    onError: function (error) {
        if (FIRE_EDITOR) {
            switch (error) {
                case 'already-playing':
                    Fire.warn('Fireball is already playing');
                    break;
            }
        }
    },
    onResume: function () {
       // if (FIRE_EDITOR) {
       //     FObject._clearDeferredDestroyTimer();
       //     editorCallback.onEnginePlayed(true);
       // }
       this.resumeRuntime();
    },
    onPause: function () {
       // if (FIRE_EDITOR) {
       //     editorCallback.onEnginePaused();
       // }
       this.pauseRuntime();
    },
    onPlay: function () {
        //if (FIRE_EDITOR && ! this._isPaused) {
        //    FObject._clearDeferredDestroyTimer();
        //}

        this.playRuntime();

        if (this._useDefaultMainLoop) {
            var now = Ticker.now();
            Time._restart(now);
            this._tick();
        }

        //if (FIRE_EDITOR) {
        //    editorCallback.onEnginePlayed(false);
        //}
    },

    onStop: function () {
        //FObject._deferredDestroy();

        this.stopRuntime();

        // reset states
        this._loadingScene = ''; // TODO: what if loading scene ?

        if (this._useDefaultMainLoop) {
            if (this._requestId !== -1) {
                Ticker.cancelAnimationFrame(this._requestId);
                this._requestId = -1;
            }
        }

        //if (FIRE_EDITOR) {
        //    editorCallback.onEngineStopped();
        //}
    },

    // PRIVATE

    /**
     * @method _tick
     * @private
     */
    _tick: function (unused) {
        if (!this._isPlaying) {
            return;
        }
        this._requestId = Ticker.requestAnimationFrame(this._bindedTick);

        //if (sceneLoadingQueue) {
        //    return;
        //}

        var updateLogic = !this._isPaused || this._stepOnce;
        var now = Ticker.now();
        Time._update(now, !updateLogic, this._stepOnce ? 1 / 60 : 0);
        this._stepOnce = false;

        //if (this._scene) {
            this.tick(Time.deltaTime, updateLogic);
        //}
    }
});

JS.obsolete(EngineWrapper.prototype, 'EngineWrapper.resize', 'resizeCanvas');

module.exports = EngineWrapper;
<commit_msg>Revert "add tickInEditMode"<commit_after>/**
 * @module Fire.Runtime
 */

var JS = Fire.JS;
var Ticker = Fire._Ticker;
var Time = Fire.Time;

var Utils = require('./utils');
var NYI = Utils.NYI;
var NYI_Accessor = Utils.NYI_Accessor;

//var SceneWrapper = require('./scene');

/**
 * !#zh 这个类用来封装编辑器对引擎的操作，并且提供运行时的一些全局接口和状态。
 * !#en Access to engine runtime data.
 * This class contains methods for looking up information about and controlling the runtime data.
 *
 * You should override:
 * - initRuntime
 * - playRuntime
 * - stopRuntime
 * - pauseRuntime
 * - resumeRuntime
 * - getCurrentRuntimeScene
 * - _setCurrentRuntimeScene
 * - tick (if useDefaultMainLoop)
 * - canvasSize
 * - getRuntimeInstanceById
 *
 * @class EngineWrapper
 * @extends Playable
 * @constructor
 * @param {boolean} useDefaultMainLoop - if true, tick() will be invoked every frame
 */
var EngineWrapper = Fire.Class({
    name: 'Fire.Runtime.EngineWrapper',
    extends: Fire.Playable,

    constructor: function () {
        var useDefaultMainLoop = arguments[0];

        /**
         * We should use this id to cancel ticker, otherwise if the engine stop and replay immediately,
         * last ticker will not cancel correctly.
         *
         * @property _requestId
         * @type {number}
         * @private
         */
        this._requestId = -1;

        this._useDefaultMainLoop = useDefaultMainLoop;
        this._isInitialized = false;

        // Scene name to uuid
        this._sceneInfos = {};

        // current scene
        this._scene = null;

        this._loadingScene = '';

        this._bindedTick = useDefaultMainLoop && this._tick.bind(this);
    },

    properties: {
        /**
         * @property {boolean} isInitialized - Indicates whether the engine instance is initialized.
         * @readOnly
         */
        isInitialized: {
            get: function () {
                return this._isInitialized;
            }
        },

        /**
         * @property {boolean} loadingScene
         * @readOnly
         */
        loadingScene: {
            get: function () {
                return this._loadingScene;
            }
        },

        /**
         * @property {Fire.Vec2} canvasSize - Resize the rendering canvas.
         */
        canvasSize: NYI_Accessor(Fire.Vec2.zero)
    },

    // TO OVERRIDE

    /**
     * @callback InitCallback
     * @param {string} [error] - null or the error info
     */

    /**
     * Initialize the runtime. This method will be called by init method.
     * @method initRuntime
     * @param {object} options
     * @param {number} options.width
     * @param {number} options.height
     * @param {Canvas} [options.canvas]
     * @param {InitCallback} callback
     */
    initRuntime: function (options, callback) {
        NYI();
        callback();
    },

    /**
     * Starts playback.
     * @method playRuntime
     */
    playRuntime: NYI,

    /**
     * Stops playback.
     * @method stopRuntime
     */
    stopRuntime: NYI,

    /**
     * Pauses playback.
     * @method pauseRuntime
     */
    pauseRuntime: NYI,

    /**
     * Resumes playback.
     * @method resumeRuntime
     */
    resumeRuntime: NYI,

    ///**
    // * Steps playback.
    // * @method stepRuntime
    // */
    //stepRuntime: NYI,

    /**
     * Get the current running runtime scene.
     * @method getCurrentRuntimeScene
     * @return {RuntimeNode}
     */
    getCurrentRuntimeScene: NYI,

    /**
     * Set the current running runtime scene.
     * @method _setCurrentRuntimeScene
     * @param {RuntimeNode}
     */
    _setCurrentRuntimeScene: NYI,

    /**
     * Returns the node which id is id.
     * @method getRuntimeInstanceById
     * @param {String} id
     * @return {Object}
     */
    getRuntimeInstanceById: NYI,

    /**
     * @method tick
     * @param {number} deltaTime
     * @param {boolean} updateLogic
     */
    tick: function (deltaTime, updateLogic) {
        NYI();

        // Example: (not required)
        if (updateLogic) {
            // update input
            // update logic
            // update particle
            // update animation
        }
        // render scene
    },

    // PUBLIC

    /**
     * Initialize the engine. This method will be called by boot.js or editor.
     * @method init
     * @param {object} options
     * @param {number} options.width
     * @param {number} options.height
     * @param {Canvas} [options.canvas]
     * @param {initCallback} callback
     */
    init: function (options, callback) {
        if (this._isInitialized) {
            Fire.error('Engine already initialized');
            return;
        }
        this._isInitialized = true;

        if (options) {
            JS.mixin(this._sceneInfos, options.scenes);
            //Resources._resBundle.init(options.resBundle);
        }

        this.initRuntime(options, function (err) {
            //if ((FIRE_EDITOR || FIRE_TEST) && !err) {
            //    //var scene = SceneWrapper.getCurrentRuntimeScene()
            //    //if (editorCallback.onSceneLoaded) {
            //    //    editorCallback.onSceneLoaded(this._scene);
            //    //}
            //    editorCallback.onSceneLaunched(this._scene);
            //}
            callback(err);
        });
    },

    // OVERRIDE

    onError: function (error) {
        if (FIRE_EDITOR) {
            switch (error) {
                case 'already-playing':
                    Fire.warn('Fireball is already playing');
                    break;
            }
        }
    },
    onResume: function () {
       // if (FIRE_EDITOR) {
       //     FObject._clearDeferredDestroyTimer();
       //     editorCallback.onEnginePlayed(true);
       // }
       this.resumeRuntime();
    },
    onPause: function () {
       // if (FIRE_EDITOR) {
       //     editorCallback.onEnginePaused();
       // }
       this.pauseRuntime();
    },
    onPlay: function () {
        //if (FIRE_EDITOR && ! this._isPaused) {
        //    FObject._clearDeferredDestroyTimer();
        //}

        this.playRuntime();

        if (this._useDefaultMainLoop) {
            var now = Ticker.now();
            Time._restart(now);
            this._tick();
        }

        //if (FIRE_EDITOR) {
        //    editorCallback.onEnginePlayed(false);
        //}
    },

    onStop: function () {
        //FObject._deferredDestroy();

        this.stopRuntime();

        // reset states
        this._loadingScene = ''; // TODO: what if loading scene ?

        if (this._useDefaultMainLoop) {
            if (this._requestId !== -1) {
                Ticker.cancelAnimationFrame(this._requestId);
                this._requestId = -1;
            }
        }

        //if (FIRE_EDITOR) {
        //    editorCallback.onEngineStopped();
        //}
    },

    // PRIVATE

    /**
     * @method _tick
     * @private
     */
    _tick: function (unused) {
        if (!this._isPlaying) {
            return;
        }
        this._requestId = Ticker.requestAnimationFrame(this._bindedTick);

        //if (sceneLoadingQueue) {
        //    return;
        //}

        var updateLogic = !this._isPaused || this._stepOnce;
        var now = Ticker.now();
        Time._update(now, !updateLogic, this._stepOnce ? 1 / 60 : 0);
        this._stepOnce = false;

        //if (this._scene) {
            this.tick(Time.deltaTime, updateLogic);
        //}
    }
});

JS.obsolete(EngineWrapper.prototype, 'EngineWrapper.resize', 'resizeCanvas');

module.exports = EngineWrapper;
<|endoftext|>


<commit_before>let nextID = 0;

export default class OptimisticValue {
  constructor() {
    this._pending = true;
    this._rejected = false;
    this._value = '__bicycle_optimistic_value_' + (nextID++) + '__';
    this._err = null;
  }
  resolve(value) {
    this._pending = false;
    this._value = value;
  }
  reject(err) {
    this._pending = false;
    this._rejected = true;
    this._err = err;
  }
  isPending() {
    return this._pending;
  }
  isRejected() {
    return this._rejected;
  }
  getError() {
    return this._err;
  }
  toString() {
    return this._value + '';
  }
  inspect() {
    return this._value;
  }
  toJSON() {
    return this._value;
  }
  valueOf() {
    return this._value;
  }
}

export default OptimisticValue;
<commit_msg>Fix syntax error in optimistic-value.js<commit_after>let nextID = 0;

class OptimisticValue {
  constructor() {
    this._pending = true;
    this._rejected = false;
    this._value = '__bicycle_optimistic_value_' + (nextID++) + '__';
    this._err = null;
  }
  resolve(value) {
    this._pending = false;
    this._value = value;
  }
  reject(err) {
    this._pending = false;
    this._rejected = true;
    this._err = err;
  }
  isPending() {
    return this._pending;
  }
  isRejected() {
    return this._rejected;
  }
  getError() {
    return this._err;
  }
  toString() {
    return this._value + '';
  }
  inspect() {
    return this._value;
  }
  toJSON() {
    return this._value;
  }
  valueOf() {
    return this._value;
  }
}

export default OptimisticValue;
<|endoftext|>


<commit_before>/*jshint boss: true */

load("jshint.js");

(function (args) {
    var name   = args[0],
        optstr = args[1], // arg1=val1,arg2=val2,...
        opts   = { rhino: true },
        predef = {},
        input;

    if (!name) {
        print('Usage: jshint.js file.js');
        quit(1);
    }

    if (optstr) {
        optstr.split(',').forEach(function (arg) {
            var o = arg.split('=');
            opts[o[0]] = (function (ov) {
                switch (ov) {
                case 'true':
                    return true;
                case 'false':
                    return false;
                default:
                    return ov;
                }
            })(o[1]);
        });
        if (opts.predef) {
            opts.predef.split(';').forEach(function (def) {
                var d = def.split(':');
                predef[d[0]] = (function (dv) {
                    return (dv === 'false') ? false : true;
                })(d[1]);
            });
            opts.predef = predef;
        }
    }

    input = readFile(name);

    if (!input) {
        print('jshint: Couldn\'t open file ' + name);
        quit(1);
    }

    if (!JSHINT(input, opts)) {
        for (var i = 0, err; err = JSHINT.errors[i]; i++) {
            print(err.reason + ' (line: ' + err.line + ', character: ' + err.character + ')');
            print('> ' + (err.evidence || '').replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1"));
            print('');
        }
        quit(1);
    }

    quit(0);
}(arguments));
<commit_msg>provide more informative error from rhino wrapper<commit_after>/*jshint boss: true */

load("jshint.js");

(function (args) {
    var name   = args[0],
        optstr = args[1], // arg1=val1,arg2=val2,...
        opts   = { rhino: true },
        predef = {},
        input;

    if (!name) {
        print('Usage: jshint.js file.js');
        quit(1);
    }

    if (optstr) {
        optstr.split(',').forEach(function (arg) {
            var o = arg.split('=');
            opts[o[0]] = (function (ov) {
                switch (ov) {
                case 'true':
                    return true;
                case 'false':
                    return false;
                default:
                    return ov;
                }
            })(o[1]);
        });
        if (opts.predef) {
            opts.predef.split(';').forEach(function (def) {
                var d = def.split(':');
                predef[d[0]] = (function (dv) {
                    return (dv === 'false') ? false : true;
                })(d[1]);
            });
            opts.predef = predef;
        }
    }

    input = readFile(name);

    if (!input) {
        print('jshint: Couldn\'t open file ' + name);
        quit(1);
    }

    if (!JSHINT(input, opts)) {
        for (var i = 0, err; err = JSHINT.errors[i]; i++) {
            print(err.reason + ' (' + name + ':' + err.line + ':' + err.character + ')');
            print('> ' + (err.evidence || '').replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1"));
            print('');
        }
        quit(1);
    }

    quit(0);
}(arguments));
<|endoftext|>


<commit_before>(function (){

// Data taken from Pardus. 'i' is the icon, minus the image pack prefix and the
// .png suffix. 'n' is the proper name of a commodity.

var COMMODITIES = {
	1: { i: 'food',
	     n: 'Food' },
	2: { i: 'energy',
	     n: 'Energy' },
	3: { i: 'water',
	     n: 'Water' },
	4: { i: 'animal_embryos',
	     n: 'Animal embryos' },
	5: { i: 'ore',
	     n: 'Ore' },
	6: { i: 'metal',
	     n: 'Metal' },
	7: { i: 'electronics',
	     n: 'Electronics' },
	8: { i: 'robots',
	     n: 'Robots' },
	9: { i: 'heavy-plastics',
	     n: 'Heavy plastics' },
	10: { i: 'hand-weapons',
	      n: 'Hand weapons' },
	11: { i: 'medicines',
	      n: 'Medicines' },
	12: { i: 'nebula-gas',
	      n: 'Nebula gas' },
	13: { i: 'chemical-supplies',
	      n: 'Chemical supplies' },
	14: { i: 'gem-stones',
	      n: 'Gem stones' },
	15: { i: 'liquor',
	      n: 'Liquor' },
	16: { i: 'hydrogen-fuel',
	      n: 'Hydrogen fuel' },
	17: { i: 'exotic_matter',
	      n: 'Exotic matter' },
	18: { i: 'optical_components',
	      n: 'Optical components' },
	19: { i: 'radioactive_cells',
	      n: 'Radioactive cells' },
	20: { i: 'droid_modules',
	      n: 'Droid modules' },
	21: { i: 'biowaste',
	      n: 'Bio-waste' },
	22: { i: 'leech_baby',
	      n: 'Leech baby' },
	23: { i: 'nutrient_clods',
	      n: 'Nutrient clods' },
	24: { i: 'cybernetic_x993_parts',
	      n: 'Cybernetic X-993 Parts' },
	25: { i: 'x993_repairdrone',
	      n: 'X-993 Repair-Drone' },
	26: { i: 'neural_stimulator',
	      n: 'Neural Stimulator' },
	27: { i: 'battleweapon_parts',
	      n: 'Battleweapon Parts' },
	28: { i: 'neural_tissue',
	      n: 'Neural Tissue' },
	29: { i: 'stim_chip',
	      n: 'Stim Chip' },
	30: { i: 'stim_chip_fed',
	      n: 'Capri Stim' },
	31: { i: 'stim_chip_emp',
	      n: 'Crimson Stim' },
	32: { i: 'stim_chip_uni',
	      n: 'Amber Stim' },
	50: { i: 'slaves',
	      n: 'Slaves' },
	51: { i: 'drugs',
	      n: 'Drugs' },
	100: { i: 'package',
	       n: 'Package' },
	101: { i: 'package_faction',
	       n: 'Faction package' },
	102: { i: 'explosives',
	       n: 'Explosives' },
	103: { i: 'vip',
	       n: 'VIP' },
	104: { i: 'christmas_glitter',
	       n: 'Christmas Glitter' },
	105: { i: 'explosives_military',
	       n: 'Military Explosives' },
	150: { i: 'exotic_crystal',
	       n: 'Exotic Crystal' },
	151: { i: 'feral_egg',
	       n: 'Feral Egg' },
	201: { i: 'human_intestines',
	       n: 'Human intestines' },
	202: { i: 'skaari_limbs',
	       n: 'Skaari limbs' },
	203: { i: 'keldon_brains',
	       n: 'Keldon brains' },
	204: { i: 'rashkir_bones',
	       n: 'Rashkir bones' },
	211: { i: 'jewels_fed',
	       n: 'Blue Sapphire jewels' },
	212: { i: 'jewels_emp',
	       n: 'Ruby jewels' },
	213: { i: 'jewels_uni',
	       n: 'Golden Beryl jewels' }
};
// This is handy to preserve order
var COMMODITY_INDICES = Object.keys( COMMODITIES ).sort( compareAsInt );

var BUILDING_SHORTNAMES = {
	'Alliance Command Station': 'ACS',
	'Asteroid Mine': 'AM',
	'Battleweapons Factory': 'BWF',
	'Brewery': 'Brew',
	'Chemical Laboratory': 'CL',
	'Clod Generator': 'Clod',
	'Dark Dome': 'Dome',
	'Droid Assembly Complex': 'DAC',
	'Drug Station': 'DS',
	'Electronics Facility': 'EF',
	'Energy Well': 'Ewell',
	'Fuel Collector': 'FC',
	'Gas Collector': 'GC',
	'Handweapons Factory': 'HWF',
	'Leech Nursery': 'Leech',
	'Medical Laboratory': 'ML',
	'Nebula Plant': 'NP',
	'Neural Laboratory': 'Neur',
	'Optics Research Center': 'ORC',
	'Plastics Facility': 'PF',
	'Radiation Collector': 'RC',
	'Recyclotron': 'Recyc',
	'Robot Factory': 'RF',
	'Slave Camp': 'SC',
	'Smelting Facility': 'Smelt',
	'Space Farm': 'Farm',
	'Stim Chip Mill': 'SCM'
};

var WEEKDAYS = [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ];
var MONTHS = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
	       'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec' ];

function compareAsInt( a, b ) {
	return parseInt(a) - parseInt(b);
}

var credits_img = "";
var universe = getUniverse();
var buildingListId = universe + "BuildingList";

function showOverview( data ) {
	// Data contains a property named as the contents of the buildingListId
	// variable.  This is an array of location IDs of every building tracked.
	var buildingList = data[ buildingListId ],
	    prefix = universe + "Building",
	    buildingKeys = [],
	    i, end;

	// Build an array of storage keys that we'll need to display the overview.
	for( i = 0, end = buildingList.length; i < end; i++ ) {
		buildingKeys.push( prefix + buildingList[i] );
	}

	// Query everything in one swoop.
	chrome.storage.local.get( buildingKeys, showOverviewBuildings );
}

// Return an array of commodities actually in use by the collection of buildings
// given.
function getCommoditiesInUse( buildingData ) {
	// Now figure out which commodities are actually in use by at least one building.
	var in_use = new Object(),
	    key, commodity;

	for( key in buildingData ) {
		// XXX - do we need to check something other than `amount` ?
		for( commodity in buildingData[key].amount )
			in_use[commodity] = true;
	}

	return Object.keys( in_use ).sort( compareAsInt );
}

function showOverviewBuildings( buildingData ) {
	var in_use, key, ckey, i, end, commodity, table, tr, cell, img, building, n;

	// Parse each building.
	for( key in buildingData )
		buildingData[key] = JSON.parse( buildingData[key] );

	in_use = getCommoditiesInUse( buildingData );

	// Build the table and headers
	table = document.createElement( 'table' );

	tr = document.createElement( 'tr' );
	addTH( tr, 'Location' );
	addTH( tr, 'Owner' );
	addTH( tr, 'Type' );
	addTH( tr, 'Lvl' );
	for( i = 0, end = in_use.length; i < end; i++ ) {
		ckey = in_use[i];
		commodity = COMMODITIES[ckey];
		img = document.createElement( 'img' );
		img.src = '//static.pardus.at/img/stdhq/res/'
			+ commodity.i + '.png';
		img.title = commodity.n;
		addTH( tr, img );
	}

	addTH( tr, 'Updated' );
	addTH( tr, '' ); // the bin icon column
	table.appendChild( tr );

	// Now add a row per building
	for( key in buildingData ) {
		building = buildingData[ key ];
		tr = document.createElement( 'tr' );

		addTD( tr, humanCoords( building ) );
		addTD( tr, building.owner || 'need update' );
		if( building.type ) {
			cell = addTD( tr, BUILDING_SHORTNAMES[building.type] || building.type );
			cell.title = building.type;
		}
		else
			addTD( tr, 'need update' );
		addTD( tr, building.level ? String(building.level) : '?');

		for( i = 0, end = in_use.length; i < end; i++ ) {
			ckey = in_use[i];
			commodity = COMMODITIES[ckey];

			// If upkeep we do amount - min, else we do max - amount and make it negative..
			if( building.res_upkeep[ckey] )
				n = String( -(building.amount_max[ckey] - building.amount[ckey]) );
			else if( building.res_production[ckey] )
				n = String( building.amount[ckey] - building.amount_min[ckey] );
			else
				n = null;

			cell = addTD( tr, n );
			if( n )
				cell.title = commodity.n;
		}

		cell = makeTimeTD( building.time );
		tr.appendChild( cell );

		img = document.createElement("img");
		img.src = "http://static.pardus.at/img/stdhq/ui_trash.png";
		img.onclick = function() {
			removeBuilding( building.loc, universe );
			row.style.display = "none";
		};
		addTD( tr, img );
		table.appendChild( tr );
	}

	table.style.background = "url(//static.pardus.at/img/stdhq/bgdark.gif)";
	table.setAttribute("class" , "messagestyle");
	table.align = "center"
	document.getElementsByTagName("h1")[0].parentNode.appendChild(table);

	// Shorthands we use above..
	function addTH( tr, content ) { return addChild( tr, 'th', content ); }
	function addTD( tr, content ) { return addChild( tr, 'td', content ); }
	function addChild( parent, tagname, content ) {
		if( typeof content == 'string' )
			content = document.createTextNode( String(content) );
		var elt = document.createElement( tagname );
		if( content )
			elt.appendChild( content );
		parent.appendChild( elt );
		return elt;
	}
}

function makeTimeTD( timestamp ) {
	var t = new Date( timestamp ),
	    now = Date.now(),
	    s, td;

	// If the date is old, we just display the day and month.
	// 432000000 is the number of milliseconds in five days.
	if( now - timestamp > 432000000 ) {
		s = MONTHS[ t.getMonth() ] + ' ' + t.getDate();
	}
	else {
		now = new Date( now );
		if( now.getDate() == t.getDate() )
			// This is today.  Just the time will do.
			// We'll add seconds because why not.
			s = twoDigits( t.getHours() )
			  + ':' + twoDigits( t.getMinutes() )
			  + ':' + twoDigits( t.getSeconds() );
		else
			// Show weekday and time.
			s = WEEKDAYS[ t.getDay() ] + ' '
			  + twoDigits( t.getHours() )
			  + ':' + twoDigits( t.getMinutes() );
	}

	td = document.createElement( 'td' );
	td.appendChild( document.createTextNode(s) );
	td.title = t.toLocaleString();

	return td;

	function twoDigits( n ) {
		n = String(n);
		return n.length < 2 ? '0' + n : n;
	}
}

function humanCoords( building ) {
	if( building.sector ) {
		return building.sector + ' [' +
			(typeof building.x == 'number' ? building.x : '?') + ',' +
			(typeof building.y == 'number' ? building.y : '?') + ']';
	}
	return 'need update';
}

//chrome.storage.local.get(null,function (data){console.log(JSON.stringify(data))});

chrome.storage.local.get(buildingListId,showOverview);

// To do
// X Make universe specific. -> added on 4 sept '17
// * Add owner (since it is in the building_trade html).
// * Add type based on res_upkeep or res_production (or from building trade html)
// * Sum all rows of a single column.
// * Add building delete button.
// * Add option to allow own buildings to be added.
// * Find a way to convert location number to Sector [x,y].

})();
<commit_msg>Added Ticks to overview<commit_after>(function (){

// Data taken from Pardus. 'i' is the icon, minus the image pack prefix and the
// .png suffix. 'n' is the proper name of a commodity.

var COMMODITIES = {
	1: { i: 'food',
	     n: 'Food' },
	2: { i: 'energy',
	     n: 'Energy' },
	3: { i: 'water',
	     n: 'Water' },
	4: { i: 'animal_embryos',
	     n: 'Animal embryos' },
	5: { i: 'ore',
	     n: 'Ore' },
	6: { i: 'metal',
	     n: 'Metal' },
	7: { i: 'electronics',
	     n: 'Electronics' },
	8: { i: 'robots',
	     n: 'Robots' },
	9: { i: 'heavy-plastics',
	     n: 'Heavy plastics' },
	10: { i: 'hand-weapons',
	      n: 'Hand weapons' },
	11: { i: 'medicines',
	      n: 'Medicines' },
	12: { i: 'nebula-gas',
	      n: 'Nebula gas' },
	13: { i: 'chemical-supplies',
	      n: 'Chemical supplies' },
	14: { i: 'gem-stones',
	      n: 'Gem stones' },
	15: { i: 'liquor',
	      n: 'Liquor' },
	16: { i: 'hydrogen-fuel',
	      n: 'Hydrogen fuel' },
	17: { i: 'exotic_matter',
	      n: 'Exotic matter' },
	18: { i: 'optical_components',
	      n: 'Optical components' },
	19: { i: 'radioactive_cells',
	      n: 'Radioactive cells' },
	20: { i: 'droid_modules',
	      n: 'Droid modules' },
	21: { i: 'biowaste',
	      n: 'Bio-waste' },
	22: { i: 'leech_baby',
	      n: 'Leech baby' },
	23: { i: 'nutrient_clods',
	      n: 'Nutrient clods' },
	24: { i: 'cybernetic_x993_parts',
	      n: 'Cybernetic X-993 Parts' },
	25: { i: 'x993_repairdrone',
	      n: 'X-993 Repair-Drone' },
	26: { i: 'neural_stimulator',
	      n: 'Neural Stimulator' },
	27: { i: 'battleweapon_parts',
	      n: 'Battleweapon Parts' },
	28: { i: 'neural_tissue',
	      n: 'Neural Tissue' },
	29: { i: 'stim_chip',
	      n: 'Stim Chip' },
	30: { i: 'stim_chip_fed',
	      n: 'Capri Stim' },
	31: { i: 'stim_chip_emp',
	      n: 'Crimson Stim' },
	32: { i: 'stim_chip_uni',
	      n: 'Amber Stim' },
	50: { i: 'slaves',
	      n: 'Slaves' },
	51: { i: 'drugs',
	      n: 'Drugs' },
	100: { i: 'package',
	       n: 'Package' },
	101: { i: 'package_faction',
	       n: 'Faction package' },
	102: { i: 'explosives',
	       n: 'Explosives' },
	103: { i: 'vip',
	       n: 'VIP' },
	104: { i: 'christmas_glitter',
	       n: 'Christmas Glitter' },
	105: { i: 'explosives_military',
	       n: 'Military Explosives' },
	150: { i: 'exotic_crystal',
	       n: 'Exotic Crystal' },
	151: { i: 'feral_egg',
	       n: 'Feral Egg' },
	201: { i: 'human_intestines',
	       n: 'Human intestines' },
	202: { i: 'skaari_limbs',
	       n: 'Skaari limbs' },
	203: { i: 'keldon_brains',
	       n: 'Keldon brains' },
	204: { i: 'rashkir_bones',
	       n: 'Rashkir bones' },
	211: { i: 'jewels_fed',
	       n: 'Blue Sapphire jewels' },
	212: { i: 'jewels_emp',
	       n: 'Ruby jewels' },
	213: { i: 'jewels_uni',
	       n: 'Golden Beryl jewels' }
};
// This is handy to preserve order
var COMMODITY_INDICES = Object.keys( COMMODITIES ).sort( compareAsInt );

var BUILDING_SHORTNAMES = {
	'Alliance Command Station': 'ACS',
	'Asteroid Mine': 'AM',
	'Battleweapons Factory': 'BWF',
	'Brewery': 'Brew',
	'Chemical Laboratory': 'CL',
	'Clod Generator': 'Clod',
	'Dark Dome': 'Dome',
	'Droid Assembly Complex': 'DAC',
	'Drug Station': 'DS',
	'Electronics Facility': 'EF',
	'Energy Well': 'Ewell',
	'Fuel Collector': 'FC',
	'Gas Collector': 'GC',
	'Handweapons Factory': 'HWF',
	'Leech Nursery': 'Leech',
	'Medical Laboratory': 'ML',
	'Nebula Plant': 'NP',
	'Neural Laboratory': 'Neur',
	'Optics Research Center': 'ORC',
	'Plastics Facility': 'PF',
	'Radiation Collector': 'RC',
	'Recyclotron': 'Recyc',
	'Robot Factory': 'RF',
	'Slave Camp': 'SC',
	'Smelting Facility': 'Smelt',
	'Space Farm': 'Farm',
	'Stim Chip Mill': 'SCM'
};

var WEEKDAYS = [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat' ];
var MONTHS = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
	       'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec' ];

function compareAsInt( a, b ) {
	return parseInt(a) - parseInt(b);
}

var credits_img = "";
var universe = getUniverse();
var buildingListId = universe + "BuildingList";

function showOverview( data ) {
	// Data contains a property named as the contents of the buildingListId
	// variable.  This is an array of location IDs of every building tracked.
	var buildingList = data[ buildingListId ],
	    prefix = universe + "Building",
	    buildingKeys = [],
	    i, end;

	// Build an array of storage keys that we'll need to display the overview.
	for( i = 0, end = buildingList.length; i < end; i++ ) {
		buildingKeys.push( prefix + buildingList[i] );
	}

	// Query everything in one swoop.
	chrome.storage.local.get( buildingKeys, showOverviewBuildings );
}

// Return an array of commodities actually in use by the collection of buildings
// given.
function getCommoditiesInUse( buildingData ) {
	// Now figure out which commodities are actually in use by at least one building.
	var in_use = new Object(),
	    key, commodity;

	for( key in buildingData ) {
		// XXX - do we need to check something other than `amount` ?
		for( commodity in buildingData[key].amount )
			in_use[commodity] = true;
	}

	return Object.keys( in_use ).sort( compareAsInt );
}

function showOverviewBuildings( buildingData ) {
	var in_use, key, ckey, i, end, commodity, table, tr, cell, img, building, n;

	// Parse each building.
	for( key in buildingData )
		buildingData[key] = JSON.parse( buildingData[key] );

	in_use = getCommoditiesInUse( buildingData );

	// Build the table and headers
	table = document.createElement( 'table' );

	tr = document.createElement( 'tr' );
	addTH( tr, 'Location' );
	addTH( tr, 'Owner' );
	addTH( tr, 'Type' );
	addTH( tr, 'Lvl' );
	for( i = 0, end = in_use.length; i < end; i++ ) {
		ckey = in_use[i];
		commodity = COMMODITIES[ckey];
		img = document.createElement( 'img' );
		img.src = '//static.pardus.at/img/stdhq/res/'
			+ commodity.i + '.png';
		img.title = commodity.n;
		addTH( tr, img );
	}

	addTH( tr, 'Updated' );
	addTH( tr, 'Ticks' );

	addTH( tr, '' ); // the bin icon column
	table.appendChild( tr );

	// Now add a row per building
	for( key in buildingData ) {
		building = buildingData[ key ];
		tr = document.createElement( 'tr' );

		addTD( tr, humanCoords( building ) );
		addTD( tr, building.owner || 'need update' );
		if( building.type ) {
			cell = addTD( tr, BUILDING_SHORTNAMES[building.type] || building.type );
			cell.title = building.type;
		}
		else
			addTD( tr, 'need update' );
		addTD( tr, building.level ? String(building.level) : '?');

		for( i = 0, end = in_use.length; i < end; i++ ) {
			ckey = in_use[i];
			commodity = COMMODITIES[ckey];

			// If upkeep we do amount - min, else we do max - amount and make it negative..
			if( building.res_upkeep[ckey] )
				n = String( -(building.amount_max[ckey] - building.amount[ckey]) );
			else if( building.res_production[ckey] )
				n = String( building.amount[ckey] - building.amount_min[ckey] );
			else
				n = null;

			cell = addTD( tr, n );
			if( n )
				cell.title = commodity.n;
		}

		cell = makeTimeTD( building.time );
		tr.appendChild( cell );

		img = document.createElement("img");
		img.src = "http://static.pardus.at/img/stdhq/ui_trash.png";
		img.onclick = function() {
			removeBuilding( building.loc, universe );
			row.style.display = "none";
		};

		addTD( tr, numberOfTicks( building ).toString() );
		addTD( tr, img );
		table.appendChild( tr );
	}

	table.style.background = "url(//static.pardus.at/img/stdhq/bgdark.gif)";
	table.setAttribute("class" , "messagestyle");
	table.align = "center"
	document.getElementsByTagName("h1")[0].parentNode.appendChild(table);

	// Shorthands we use above..
	function addTH( tr, content ) { return addChild( tr, 'th', content ); }
	function addTD( tr, content ) { return addChild( tr, 'td', content ); }
	function addChild( parent, tagname, content ) {
		if( typeof content == 'string' )
			content = document.createTextNode( String(content) );
		var elt = document.createElement( tagname );
		if( content )
			elt.appendChild( content );
		parent.appendChild( elt );
		return elt;
	}
}

function makeTimeTD( timestamp ) {
	var t = new Date( timestamp ),
	    now = Date.now(),
	    s, td;

	// If the date is old, we just display the day and month.
	// 432000000 is the number of milliseconds in five days.
	if( now - timestamp > 432000000 ) {
		s = MONTHS[ t.getMonth() ] + ' ' + t.getDate();
	}
	else {
		now = new Date( now );
		if( now.getDate() == t.getDate() )
			// This is today.  Just the time will do.
			// We'll add seconds because why not.
			s = twoDigits( t.getHours() )
			  + ':' + twoDigits( t.getMinutes() )
			  + ':' + twoDigits( t.getSeconds() );
		else
			// Show weekday and time.
			s = WEEKDAYS[ t.getDay() ] + ' '
			  + twoDigits( t.getHours() )
			  + ':' + twoDigits( t.getMinutes() );
	}

	td = document.createElement( 'td' );
	td.appendChild( document.createTextNode(s) );
	td.title = t.toLocaleString();

	return td;

	function twoDigits( n ) {
		n = String(n);
		return n.length < 2 ? '0' + n : n;
	}
}

function humanCoords( building ) {
	if( building.sector ) {
		return building.sector + ' [' +
			(typeof building.x == 'number' ? building.x : '?') + ',' +
			(typeof building.y == 'number' ? building.y : '?') + ']';
	}
	return 'need update';
}

function numberOfTicks( building ) {
	var minAmount = 9999;
	var minKey = "0";

	for (var key in building.res_upkeep) {
		if (building.amount[key]/building.res_upkeep[key] < minAmount) {
			minAmount = building.amount[key];
			minKey = key;
		}
	}
	var tickAmount = ((building.level - 1) * 0.4 + 1) * building.res_upkeep[minKey];
	var ticks = Math.floor(minAmount / tickAmount);
	return ticks;
}

//chrome.storage.local.get(null,function (data){console.log(JSON.stringify(data))});

chrome.storage.local.get(buildingListId,showOverview);

// To do
// X Make universe specific. -> added on 4 sept '17
// * Add owner (since it is in the building_trade html).
// * Add type based on res_upkeep or res_production (or from building trade html)
// * Sum all rows of a single column.
// * Add building delete button.
// * Add option to allow own buildings to be added.
// * Find a way to convert location number to Sector [x,y].

})();
<|endoftext|>


<commit_before>exports.reportError = function(res) {
  return function(err) {
    var status = err.status || 422
    var result = {}
    if ('message' in err) {
      result.err = err.message
    }
    res.status(status).jsonp(result)
  }
}

/**
 * @constructor
 */
exports.BadRequestException = function(message) {
  this.message = message || "Bad Request"
  this.status = 400
}

/**
 * @constructor
 */
exports.ForbiddenException = function(message) {
  this.message = message || "Forbidden"
  this.status = 403
}

/**
 * @constructor
 */
exports.NotFoundException = function(message) {
  this.message = message || "Not found"
  this.status = 404
}
<commit_msg>Add ValidationException<commit_after>exports.reportError = function(res) {
  return function(err) {
    var status = err.status || 422
    var result = {}
    if ('message' in err) {
      result.err = err.message
    }
    res.status(status).jsonp(result)
  }
}

/**
 * @constructor
 */
exports.BadRequestException = function(message) {
  this.message = message || "Bad Request"
  this.status = 400
}

/**
 * @constructor
 */
exports.ForbiddenException = function(message) {
  this.message = message || "Forbidden"
  this.status = 403
}

/**
 * @constructor
 */
exports.NotFoundException = function(message) {
  this.message = message || "Not found"
  this.status = 404
}

/**
 * @constructor
 */
exports.ValidationException = function(message) {
  this.message = message || "Invalid"
  this.status = 422
}
<|endoftext|>


<commit_before>// based on feross/run-parallel
module.exports = function (tasks, cb) {
  var results, pending, errors = []
  if (Array.isArray(tasks)) {
    results = []
    pending = tasks.length
  }

  function done (err, result) {
  	if (result) {
    	results.push(result)
    }
    if (err) {
    	errors.push(err);
    }
    if (--pending === 0) {
      cb && cb(errors, results)
      cb = null
    }
  }

  if (!pending) {
    // empty
    cb && cb(null, results)
    cb = null
  } else {
    // array
    tasks.forEach(function (task) {
      task(done)
    })
  }
}<commit_msg>[=] pass a null if `errors` is empty<commit_after>// based on feross/run-parallel
module.exports = function (tasks, cb) {
  var results, pending, errors = []
  if (Array.isArray(tasks)) {
    results = []
    pending = tasks.length
  }

  function done (err, result) {
  	if (result) {
    	results.push(result)
    }
    if (err) {
    	errors.push(err);
    }
    if (--pending === 0) {
      cb && cb(errors.length ? errors : null, results)
      cb = null
    }
  }

  if (!pending) {
    // empty
    cb && cb(null, results)
    cb = null
  } else {
    // array
    tasks.forEach(function (task) {
      task(done)
    })
  }
}<|endoftext|>


<commit_before>const exec = require('child_process').spawn;
const fs = require('fs');
const csv = require('csv-parser');

const tools = require('../toolbox.js');

exports.name = 'assignment-fasta-vsearch';
exports.multicore = true;
exports.category = 'Assignment';

exports.run = function (os, config, callback) {
	let directory = '/app/data/' + os.token + '/';
	let tmp_uc = tools.tmp_filename() + '.uc';

	var options = ['--usearch_global', directory + config.params.inputs.fasta,
		'--threads', os.cores, '--notrunclabels',
		'--db', directory + config.params.inputs.db,
		'--uc', directory + tmp_uc,
		'--id', config.params.params.similarity,
		'--uc_allhits', '--maxaccept', config.params.params.cons_num];

	console.log("Running vsearch with the command line:");
	console.log('/app/lib/vsearch/bin/vsearch', options.join(' '));
	fs.appendFileSync(directory + config.log, '--- Command ---\n');
	fs.appendFileSync(directory + config.log, 'vsearch ' + options.join(' ') + '\n');
	fs.appendFileSync(directory + config.log, '--- Exec ---\n');
	var child = exec('/app/lib/vsearch/bin/vsearch', options);

	child.stdout.on('data', function(data) {
		fs.appendFileSync(directory + config.log, data);
	});
	child.stderr.on('data', function(data) {
		fs.appendFileSync(directory + config.log, data);
	});
	child.on('close', function(code) {
		if (code == 0) {
			// Parse the results of the analysis and translate them into the right format.
			let options = ['/app/lib/python_scripts/assignment2tsv.py',
							'-uc', directory + tmp_uc,
							'-out', directory + config.params.outputs.assigned];
<<<<<<< HEAD
=======

			// Print the command line
			fs.appendFileSync(directory + config.log, "python3 " + options.join(" ") + "\n");
			console.log(os.token + ": python3 " + options.join(" "))

			// Exec the command line
>>>>>>> fork/master
			child = exec("python3", options);
			child.stdout.on('data', function(data) {
				fs.appendFileSync(directory + config.log, data);
			});
			child.stderr.on('data', function(data) {
				fs.appendFileSync(directory + config.log, data);
			});

			child.on('close', function(code) {
				fs.unlink(directory + tmp_uc, ()=>{});

				if (code == 0)
					callback(os, null);
				else {
					callback(os, "assignment: Impossible to generate the annotated otu from the clustering files");
				}
			});
		} else {
			console.log("vsearch terminate on code " + code);
			callback(os, "vsearch terminate on code " + code);
		}
	});
};
<commit_msg>Update assignment-fasta-vsearch.js<commit_after>const exec = require('child_process').spawn;
const fs = require('fs');
const csv = require('csv-parser');

const tools = require('../toolbox.js');

exports.name = 'assignment-fasta-vsearch';
exports.multicore = true;
exports.category = 'Assignment';

exports.run = function (os, config, callback) {
	let directory = '/app/data/' + os.token + '/';
	let tmp_uc = tools.tmp_filename() + '.uc';

	var options = ['--usearch_global', directory + config.params.inputs.fasta,
		'--threads', os.cores, '--notrunclabels',
		'--db', directory + config.params.inputs.db,
		'--uc', directory + tmp_uc,
		'--id', config.params.params.similarity,
		'--uc_allhits', '--maxaccept', config.params.params.cons_num];

	console.log("Running vsearch with the command line:");
	console.log('/app/lib/vsearch/bin/vsearch', options.join(' '));
	fs.appendFileSync(directory + config.log, '--- Command ---\n');
	fs.appendFileSync(directory + config.log, 'vsearch ' + options.join(' ') + '\n');
	fs.appendFileSync(directory + config.log, '--- Exec ---\n');
	var child = exec('/app/lib/vsearch/bin/vsearch', options);

	child.stdout.on('data', function(data) {
		fs.appendFileSync(directory + config.log, data);
	});
	child.stderr.on('data', function(data) {
		fs.appendFileSync(directory + config.log, data);
	});
	child.on('close', function(code) {
		if (code == 0) {
			// Parse the results of the analysis and translate them into the right format.
			let options = ['/app/lib/python_scripts/assignment2tsv.py',
							'-uc', directory + tmp_uc,
							'-out', directory + config.params.outputs.assigned];

			// Print the command line
			fs.appendFileSync(directory + config.log, "python3 " + options.join(" ") + "\n");
			console.log(os.token + ": python3 " + options.join(" "))

			// Exec the command line
			child = exec("python3", options);
			child.stdout.on('data', function(data) {
				fs.appendFileSync(directory + config.log, data);
			});
			child.stderr.on('data', function(data) {
				fs.appendFileSync(directory + config.log, data);
			});

			child.on('close', function(code) {
				fs.unlink(directory + tmp_uc, ()=>{});

				if (code == 0)
					callback(os, null);
				else {
					callback(os, "assignment: Impossible to generate the annotated otu from the clustering files");
				}
			});
		} else {
			console.log("vsearch terminate on code " + code);
			callback(os, "vsearch terminate on code " + code);
		}
	});
};
<|endoftext|>