<commit_before>define([
  'angular',
  'angular-mocks',
  'app',
  'routes'
], function (angular, mocks) {
  'use strict';
  describe('Routes', function () {

    var $rootScope,
      $state,
      $location;

    beforeEach(mocks.module('lsseedApp'));

    beforeEach(mocks.inject(function(_$rootScope_, _$state_, _$location_, $templateCache) {
      $rootScope = _$rootScope_;
      $state = _$state_;
      $location = _$location_;
      $templateCache.put('public/views/about.html', '');
      $templateCache.put('public/views/hello1.html', '');
      $templateCache.put('public/views/hello2.html', '');
      $templateCache.put('public/views/hello3.html', '');
      $templateCache.put('public/views/welcome.html', '');
    }));

    function goTo(url) {
      $location.url(url);
      $rootScope.$digest();
    }

    describe('State: home', function() {

      var state = 'home';

      it('has a url of "/"', function() {
        var homeConfig = $state.get(state);
        expect(homeConfig.url).toBe('/');
      });

      it('has a controller', function () {
        var homeConfig = $state.get(state);
        expect(homeConfig.controller).toBeDefined();
      });

      it('transitions to "home" when the url is "/"', function () {
        goTo('/');
        expect($state.current.name).toBe('home');
      });

      it('transitions to "home" when the url is empty', function () {
        goTo('');
        expect($state.current.name).toBe('home');
      });

    });

    describe('State: hello1', function () {
      var state = 'hello1';

      it('has a url of "/hello1"', function() {
        var homeConfig = $state.get(state);
        expect(homeConfig.url).toBe('/hello1');
      });

      it('has a controller', function () {
        var homeConfig = $state.get(state);
        expect(homeConfig.controller).toBeDefined();
      });

      it('transitions to "hello1" when the url is "/hello1"', function () {
        goTo('/hello1');
        expect($state.current.name).toBe('hello1');
      });

    });
  });
});<commit_msg>Rename 'public' to 'ui'<commit_after>define([
  'angular',
  'angular-mocks',
  'app',
  'routes'
], function (angular, mocks) {
  'use strict';
  describe('Routes', function () {

    var $rootScope,
      $state,
      $location;

    beforeEach(mocks.module('lsseedApp'));

    beforeEach(mocks.inject(function(_$rootScope_, _$state_, _$location_, $templateCache) {
      $rootScope = _$rootScope_;
      $state = _$state_;
      $location = _$location_;
      $templateCache.put('ui/views/about.html', '');
      $templateCache.put('ui/views/hello1.html', '');
      $templateCache.put('ui/views/hello2.html', '');
      $templateCache.put('ui/views/hello3.html', '');
      $templateCache.put('ui/views/welcome.html', '');
    }));

    function goTo(url) {
      $location.url(url);
      $rootScope.$digest();
    }

    describe('State: home', function() {

      var state = 'home';

      it('has a url of "/"', function() {
        var homeConfig = $state.get(state);
        expect(homeConfig.url).toBe('/');
      });

      it('has a controller', function () {
        var homeConfig = $state.get(state);
        expect(homeConfig.controller).toBeDefined();
      });

      it('transitions to "home" when the url is "/"', function () {
        goTo('/');
        expect($state.current.name).toBe('home');
      });

      it('transitions to "home" when the url is empty', function () {
        goTo('');
        expect($state.current.name).toBe('home');
      });

    });

    describe('State: hello1', function () {
      var state = 'hello1';

      it('has a url of "/hello1"', function() {
        var homeConfig = $state.get(state);
        expect(homeConfig.url).toBe('/hello1');
      });

      it('has a controller', function () {
        var homeConfig = $state.get(state);
        expect(homeConfig.controller).toBeDefined();
      });

      it('transitions to "hello1" when the url is "/hello1"', function () {
        goTo('/hello1');
        expect($state.current.name).toBe('hello1');
      });

    });
  });
});<|endoftext|>


<commit_before>'use strict';

describe('beacon', function() {

  it('should create a new beacon', function() {

    new ibeacon.Beacon({
      identifier: 'my-identifier',
      uuid: 'C53AD517-0815-410B-B124-68FFDFBFE0B3',
      major: 12345,
      minor: 67890,
      power: -60,
    });

  });

  it('should throw an error because of missing major', function() {

    var createRegion = function() {
      new ibeacon.Beacon({
        uuid: 'C53AD517-0815-410B-B124-68FFDFBFE0B3',
        minor: 67890,
      });
    };

    expect(createRegion).toThrow(new Error('Parameter "major" has to be an integer value.'));

  });

  it('should throw an error because of wrong major', function() {

    var createRegion = function() {
      new ibeacon.Beacon({
        uuid: 'C53AD517-0815-410B-B124-68FFDFBFE0B3',
        major: 'wrong',
        minor: 67890,
      });
    };

    expect(createRegion).toThrow(new Error('Parameter "major" has to be an integer value.'));

  });

  it('should throw an error because of missing minor', function() {

    var createRegion = function() {
      new ibeacon.Beacon({
        uuid: 'C53AD517-0815-410B-B124-68FFDFBFE0B3',
        major: 67890,
      });
    };

    expect(createRegion).toThrow(new Error('Parameter "minor" has to be an integer value.'));

  });

  it('should throw an error because of wrong minor', function() {

    var createRegion = function() {
      new ibeacon.Beacon({
        uuid: 'C53AD517-0815-410B-B124-68FFDFBFE0B3',
        major: 67890,
        minor: 'wrong',
      });
    };

    expect(createRegion).toThrow(new Error('Parameter "minor" has to be an integer value.'));

  });

  it('should throw an error because of wrong power', function() {

    var createRegion = function() {
      new ibeacon.Beacon({
        uuid: 'C53AD517-0815-410B-B124-68FFDFBFE0B3',
        major: 67890,
        minor: 12345,
        power: 'wrong'
      });
    };

    expect(createRegion).toThrow(new Error('Parameter "power" has to be an integer value.'));

  });

  it('should create a new beacon with immediate proximity', function() {

    new ibeacon.Beacon({
      uuid: 'C53AD517-0815-410B-B124-68FFDFBFE0B3',
      major: 67890,
      minor: 12345,
      proximity: 'immediate'
    });

  });

  it('should create a new beacon with near proximity', function() {

    new ibeacon.Beacon({
      uuid: 'C53AD517-0815-410B-B124-68FFDFBFE0B3',
      major: 67890,
      minor: 12345,
      proximity: 'near'
    });

  });

  it('should create a new beacon with far proximity', function() {

    new ibeacon.Beacon({
      uuid: 'C53AD517-0815-410B-B124-68FFDFBFE0B3',
      major: 67890,
      minor: 12345,
      proximity: 'far'
    });

  });

  it('should create a new beacon with unknown proximity', function() {

    new ibeacon.Beacon({
      uuid: 'C53AD517-0815-410B-B124-68FFDFBFE0B3',
      major: 67890,
      minor: 12345,
      proximity: 'unknown'
    });

  });

  it('should throw an error because of wrong proximity', function() {

    var createRegion = function() {
      new ibeacon.Beacon({
        uuid: 'C53AD517-0815-410B-B124-68FFDFBFE0B3',
        major: 67890,
        minor: 12345,
        proximity: 'wrong'
      });
    };

    expect(createRegion).toThrow(new Error('Parameter "proximity" has to be a valid string.'));

  });

  it('should set isAdvertising to false as default', function() {

    var beacon = new ibeacon.Beacon({
      identifier: 'my-identifier',
      uuid: 'C53AD517-0815-410B-B124-68FFDFBFE0B3',
      major: 12345,
      minor: 67890,
      power: -60,
    });

    expect(beacon.isAdvertising).toBe(false);

  });

});
<commit_msg>remove test<commit_after>'use strict';

describe('beacon', function() {

  it('should create a new beacon', function() {

    new ibeacon.Beacon({
      identifier: 'my-identifier',
      uuid: 'C53AD517-0815-410B-B124-68FFDFBFE0B3',
      major: 12345,
      minor: 67890,
      power: -60,
    });

  });

  it('should throw an error because of missing major', function() {

    var createRegion = function() {
      new ibeacon.Beacon({
        uuid: 'C53AD517-0815-410B-B124-68FFDFBFE0B3',
        minor: 67890,
      });
    };

    expect(createRegion).toThrow(new Error('Parameter "major" has to be an integer value.'));

  });

  it('should throw an error because of wrong major', function() {

    var createRegion = function() {
      new ibeacon.Beacon({
        uuid: 'C53AD517-0815-410B-B124-68FFDFBFE0B3',
        major: 'wrong',
        minor: 67890,
      });
    };

    expect(createRegion).toThrow(new Error('Parameter "major" has to be an integer value.'));

  });

  it('should throw an error because of missing minor', function() {

    var createRegion = function() {
      new ibeacon.Beacon({
        uuid: 'C53AD517-0815-410B-B124-68FFDFBFE0B3',
        major: 67890,
      });
    };

    expect(createRegion).toThrow(new Error('Parameter "minor" has to be an integer value.'));

  });

  it('should throw an error because of wrong minor', function() {

    var createRegion = function() {
      new ibeacon.Beacon({
        uuid: 'C53AD517-0815-410B-B124-68FFDFBFE0B3',
        major: 67890,
        minor: 'wrong',
      });
    };

    expect(createRegion).toThrow(new Error('Parameter "minor" has to be an integer value.'));

  });

  it('should throw an error because of wrong power', function() {

    var createRegion = function() {
      new ibeacon.Beacon({
        uuid: 'C53AD517-0815-410B-B124-68FFDFBFE0B3',
        major: 67890,
        minor: 12345,
        power: 'wrong'
      });
    };

    expect(createRegion).toThrow(new Error('Parameter "power" has to be an integer value.'));

  });

  it('should create a new beacon with immediate proximity', function() {

    new ibeacon.Beacon({
      uuid: 'C53AD517-0815-410B-B124-68FFDFBFE0B3',
      major: 67890,
      minor: 12345,
      proximity: 'immediate'
    });

  });

  it('should create a new beacon with near proximity', function() {

    new ibeacon.Beacon({
      uuid: 'C53AD517-0815-410B-B124-68FFDFBFE0B3',
      major: 67890,
      minor: 12345,
      proximity: 'near'
    });

  });

  it('should create a new beacon with far proximity', function() {

    new ibeacon.Beacon({
      uuid: 'C53AD517-0815-410B-B124-68FFDFBFE0B3',
      major: 67890,
      minor: 12345,
      proximity: 'far'
    });

  });

  it('should create a new beacon with unknown proximity', function() {

    new ibeacon.Beacon({
      uuid: 'C53AD517-0815-410B-B124-68FFDFBFE0B3',
      major: 67890,
      minor: 12345,
      proximity: 'unknown'
    });

  });

  it('should throw an error because of wrong proximity', function() {

    var createRegion = function() {
      new ibeacon.Beacon({
        uuid: 'C53AD517-0815-410B-B124-68FFDFBFE0B3',
        major: 67890,
        minor: 12345,
        proximity: 'wrong'
      });
    };

    expect(createRegion).toThrow(new Error('Parameter "proximity" has to be a valid string.'));

  });

});
<|endoftext|>


<commit_before>//var Module = Module || {};

if (!String.prototype.endsWith) {
	String.prototype.endsWith = function(search, this_len) {
		if (this_len === undefined || this_len > this.length) {
			this_len = this.length;
		}
		return this.substring(this_len - search.length, this_len) === search;
	};
}

Module = Module || {};

Module["preRun"] = Module["preRun"] || [];

Module["preRun"].push(function () {
    var i;

    Module["FS_createFolder"]("/", "fonts", true, true);

    if (!self.subContent) {
        // We can use sync xhr cause we're inside Web Worker
        if (self.subUrl.endsWith(".br")) {
            self.subContent = Module["BrotliDecode"](readBinary(self.subUrl))
        } else {
            self.subContent = read_(self.subUrl);
        }
    }

    if (self.availableFonts && self.availableFonts.length !== 0) {
        var sections = parseAss(self.subContent);
            for (var i = 0; i < sections.length; i++) {
                for (var j = 0; j < sections[i].body.length; j++) {
                    if (sections[i].body[j].key === 'Style') {
                        self.writeFontToFS(sections[i].body[j].value['Fontname']);
                    }
                }
            }

            var regex = /\\fn([^\\}]*?)[\\}]/g;
            var matches;
            while (matches = regex.exec(self.subContent)) {
                self.writeFontToFS(matches[1]);
            }
        }

    if (self.subContent) {
        Module["FS"].writeFile("/sub.ass", self.subContent);
    }

    self.subContent = null;

    //Module["FS"].mount(Module["FS"].filesystems.IDBFS, {}, '/fonts');
    var fontFiles = self.fontFiles || [];
    for (i = 0; i < fontFiles.length; i++) {
        Module["FS_createPreloadedFile"]("/fonts", 'font' + i + '-' + fontFiles[i].split('/').pop(), fontFiles[i], true, true);
    }
});

Module['onRuntimeInitialized'] = function () {
    self.init = Module['cwrap']('libassjs_init', 'number', ['number', 'number', 'string']);
    self._resize = Module['cwrap']('libassjs_resize', null, ['number', 'number']);
    self._render = Module['cwrap']('libassjs_render', null, ['number', 'number']);
    self._free_track = Module['cwrap']('libassjs_free_track', null, null);
    self._create_track = Module['cwrap']('libassjs_create_track', null, ['string']);
    self.quit = Module['cwrap']('libassjs_quit', null, []);
    self.changed = Module._malloc(4);

    self.init(screen.width, screen.height, "/sub.ass");
};

Module["print"] = function (text) {
    if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
    console.log(text);
};
Module["printErr"] = function (text) {
    if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
    console.error(text);
};

// Modified from https://github.com/kripken/emscripten/blob/6dc4ac5f9e4d8484e273e4dcc554f809738cedd6/src/proxyWorker.js
if (typeof console === 'undefined') {
    // we can't call Module.printErr because that might be circular
    var console = {
        log: function (x) {
            if (typeof dump === 'function') dump('log: ' + x + '\n');
        },
        debug: function (x) {
            if (typeof dump === 'function') dump('debug: ' + x + '\n');
        },
        info: function (x) {
            if (typeof dump === 'function') dump('info: ' + x + '\n');
        },
        warn: function (x) {
            if (typeof dump === 'function') dump('warn: ' + x + '\n');
        },
        error: function (x) {
            if (typeof dump === 'function') dump('error: ' + x + '\n');
        },
    };
}

// performance.now() polyfill
if ("performance" in self === false) {
    self.performance = {};
}
Date.now = (Date.now || function () {
    return new Date().getTime();
});
if ("now" in self.performance === false) {
    var nowOffset = Date.now();
    if (performance.timing && performance.timing.navigationStart) {
        nowOffset = performance.timing.navigationStart
    }
    self.performance.now = function now() {
        return Date.now() - nowOffset;
    }
}
<commit_msg>Implement custom console.log family for older browsers<commit_after>//var Module = Module || {};

if (!String.prototype.endsWith) {
	String.prototype.endsWith = function(search, this_len) {
		if (this_len === undefined || this_len > this.length) {
			this_len = this.length;
		}
		return this.substring(this_len - search.length, this_len) === search;
	};
}

// implement console methods if they're missing
if (typeof console === "undefined") {
    function postConsoleMessage(prefix, args) {
        postMessage({
            target: "console-" + prefix,
            content: JSON.stringify(Array.prototype.slice.call(args)),
        })
    }

    var console = {
        log: function() {
            postConsoleMessage("log", arguments);
        },
        debug: function() {
            postConsoleMessage("debug", arguments);
        },
        info: function() {
            postConsoleMessage("info", arguments);
        },
        warn: function() {
            postConsoleMessage("warn", arguments);
        },
        error: function() {
            postConsoleMessage("error", arguments);
        }
    };
}

Module = Module || {};

Module["preRun"] = Module["preRun"] || [];

Module["preRun"].push(function () {
    var i;

    Module["FS_createFolder"]("/", "fonts", true, true);

    if (!self.subContent) {
        // We can use sync xhr cause we're inside Web Worker
        if (self.subUrl.endsWith(".br")) {
            self.subContent = Module["BrotliDecode"](readBinary(self.subUrl))
        } else {
            self.subContent = read_(self.subUrl);
        }
    }

    if (self.availableFonts && self.availableFonts.length !== 0) {
        var sections = parseAss(self.subContent);
            for (var i = 0; i < sections.length; i++) {
                for (var j = 0; j < sections[i].body.length; j++) {
                    if (sections[i].body[j].key === 'Style') {
                        self.writeFontToFS(sections[i].body[j].value['Fontname']);
                    }
                }
            }

            var regex = /\\fn([^\\}]*?)[\\}]/g;
            var matches;
            while (matches = regex.exec(self.subContent)) {
                self.writeFontToFS(matches[1]);
            }
        }

    if (self.subContent) {
        Module["FS"].writeFile("/sub.ass", self.subContent);
    }

    self.subContent = null;

    //Module["FS"].mount(Module["FS"].filesystems.IDBFS, {}, '/fonts');
    var fontFiles = self.fontFiles || [];
    for (i = 0; i < fontFiles.length; i++) {
        Module["FS_createPreloadedFile"]("/fonts", 'font' + i + '-' + fontFiles[i].split('/').pop(), fontFiles[i], true, true);
    }
});

Module['onRuntimeInitialized'] = function () {
    self.init = Module['cwrap']('libassjs_init', 'number', ['number', 'number', 'string']);
    self._resize = Module['cwrap']('libassjs_resize', null, ['number', 'number']);
    self._render = Module['cwrap']('libassjs_render', null, ['number', 'number']);
    self._free_track = Module['cwrap']('libassjs_free_track', null, null);
    self._create_track = Module['cwrap']('libassjs_create_track', null, ['string']);
    self.quit = Module['cwrap']('libassjs_quit', null, []);
    self.changed = Module._malloc(4);

    self.init(screen.width, screen.height, "/sub.ass");
};

Module["print"] = function (text) {
    if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
    console.log(text);
};
Module["printErr"] = function (text) {
    if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
    console.error(text);
};

// Modified from https://github.com/kripken/emscripten/blob/6dc4ac5f9e4d8484e273e4dcc554f809738cedd6/src/proxyWorker.js
if (typeof console === 'undefined') {
    // we can't call Module.printErr because that might be circular
    var console = {
        log: function (x) {
            if (typeof dump === 'function') dump('log: ' + x + '\n');
        },
        debug: function (x) {
            if (typeof dump === 'function') dump('debug: ' + x + '\n');
        },
        info: function (x) {
            if (typeof dump === 'function') dump('info: ' + x + '\n');
        },
        warn: function (x) {
            if (typeof dump === 'function') dump('warn: ' + x + '\n');
        },
        error: function (x) {
            if (typeof dump === 'function') dump('error: ' + x + '\n');
        },
    };
}

// performance.now() polyfill
if ("performance" in self === false) {
    self.performance = {};
}
Date.now = (Date.now || function () {
    return new Date().getTime();
});
if ("now" in self.performance === false) {
    var nowOffset = Date.now();
    if (performance.timing && performance.timing.navigationStart) {
        nowOffset = performance.timing.navigationStart
    }
    self.performance.now = function now() {
        return Date.now() - nowOffset;
    }
}
<|endoftext|>


<commit_before>var parse = require('csv-parse');
var fs = require('fs');
var batch = require('batchflow');
var sink = require('through2-sink');

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

/*
  This function finds all the `latest` files in `meta/`, CSV parses them,
  extracts the required fields, and assigns to a big collection
*/
function readData(directory, types, wofRecords, callback) {
  batch(types).parallel(2).each(function(idx, type, done) {
    var csv_parser = parse({ delimiter: ',', columns: true });
    var is_valid_data_file_path = readStreamComponents.is_valid_data_file_path();
    var normalize_file_path = readStreamComponents.normalize_file_path();
    var file_is_readable = readStreamComponents.file_is_readable(directory + 'data/');
    var json_parse_stream = readStreamComponents.json_parse_stream(directory + 'data/');
    var filter_incomplete_files_stream = readStreamComponents.filter_incomplete_files_stream();
    var map_fields_stream = readStreamComponents.map_fields_stream();

    fs.createReadStream(directory + 'meta/wof-' + type + '-latest.csv')
    .pipe(csv_parser)
    .pipe(is_valid_data_file_path)
    .pipe(normalize_file_path)
    .pipe(file_is_readable)
    .pipe(json_parse_stream)
    .pipe(filter_incomplete_files_stream)
    .pipe(map_fields_stream)
    .pipe(sink.obj(function(wofRecord) {
      wofRecords[wofRecord.id] = wofRecord;
    }))
    .on('finish', done);

  }).error(function(err) {
    console.error(err);
  }).end(function() {
    callback();
  });

}

module.exports = readData;
<commit_msg>included filterOutNamelessRecords into readStream pipeline<commit_after>var parse = require('csv-parse');
var fs = require('fs');
var batch = require('batchflow');
var sink = require('through2-sink');

var readStreamComponents = require('./readStreamComponents');
var filterOutNamelessRecords = require('./components/filterOutNamelessRecords');

/*
  This function finds all the `latest` files in `meta/`, CSV parses them,
  extracts the required fields, and assigns to a big collection
*/
function readData(directory, types, wofRecords, callback) {
  batch(types).parallel(2).each(function(idx, type, done) {
    var csv_parser = parse({ delimiter: ',', columns: true });
    var is_valid_data_file_path = readStreamComponents.is_valid_data_file_path();
    var normalize_file_path = readStreamComponents.normalize_file_path();
    var file_is_readable = readStreamComponents.file_is_readable(directory + 'data/');
    var json_parse_stream = readStreamComponents.json_parse_stream(directory + 'data/');
    var filter_incomplete_files_stream = readStreamComponents.filter_incomplete_files_stream();
    var map_fields_stream = readStreamComponents.map_fields_stream();
    var filter_out_nameless_records = filterOutNamelessRecords.create();

    fs.createReadStream(directory + 'meta/wof-' + type + '-latest.csv')
    .pipe(csv_parser)
    .pipe(is_valid_data_file_path)
    .pipe(normalize_file_path)
    .pipe(file_is_readable)
    .pipe(json_parse_stream)
    .pipe(filter_incomplete_files_stream)
    .pipe(map_fields_stream)
    .pipe(filter_out_nameless_records)
    .pipe(sink.obj(function(wofRecord) {
      wofRecords[wofRecord.id] = wofRecord;
    }))
    .on('finish', done);

  }).error(function(err) {
    console.error(err);
  }).end(function() {
    callback();
  });

}

module.exports = readData;
<|endoftext|>


<commit_before>// upload-file-test.js
//
// Test uploading a file to a server
//
// Copyright 2012, E14N https://e14n.com/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var assert = require("assert"),
    vows = require("vows"),
    Step = require("step"),
    os = require("os"),
    fs = require("fs"),
    path = require("path"),
    mkdirp = require("mkdirp"),
    rimraf = require("rimraf"),
    _ = require("underscore"),
    httputil = require("./lib/http"),
    oauthutil = require("./lib/oauth"),
    actutil = require("./lib/activity"),
    setupAppConfig = oauthutil.setupAppConfig,
    newCredentials = oauthutil.newCredentials,
    newPair = oauthutil.newPair,
    newClient = oauthutil.newClient,
    register = oauthutil.register,
    accessToken = oauthutil.accessToken;

var suite = vows.describe("upload file test");

var makeCred = function(cl, pair) {
    return {
        consumer_key: cl.client_id,
        consumer_secret: cl.client_secret,
        token: pair.token,
        token_secret: pair.token_secret
    };
};

var assertValidFeed = function(feed) {
    assert.include(feed, "totalItems");
    assert.isNumber(feed.totalItems);
    assert.include(feed, "url");
    assert.isString(feed.url);
    assert.include(feed, "items");
    assert.isArray(feed.items);
};

suite.addBatch({
    "When we create a temporary upload dir": {
        topic: function() {
            var callback = this.callback,
                dirname = path.join(os.tmpDir(),
                                    "upload-file-test",
                                    ""+Date.now());
            mkdirp(dirname, function (err) {
                if (err) {
                    callback(err, null);
                } else {
                    callback(null, dirname);
                }
            });
        },
        "it works": function(err, dir) {
            assert.ifError(err);
            assert.isString(dir);
        },
        teardown: function(dir) {
            rimraf(dir, function(err) {
            });
        },
        "and we set up the app": {
            topic: function(dir) {
                setupAppConfig({uploaddir: dir},
                               this.callback);
            },
            teardown: function(app) {
                if (app && app.close) {
                    app.close();
                }
            },
            "it works": function(err, app) {
                assert.ifError(err);
            },
            "and we register a client": {
                topic: function() {
                    newClient(this.callback);
                },
                "it works": function(err, cl) {
                    assert.ifError(err);
                    assert.isObject(cl);
                },
                "and we create a new user": {
                    topic: function(cl) {
                        newPair(cl, "mike", "stormtroopers_hittin_the_ground", this.callback);
                    },
                    "it works": function(err, pair) {
                        assert.ifError(err);
                        assert.isObject(pair);
                    },
                    "and we check the uploads endpoint":
                    httputil.endpoint("/api/user/mike/uploads", ["POST", "GET"]),
                    "and we get the uploads endpoint of a new user": {
                        topic: function(pair, cl) {
                            var cred = makeCred(cl, pair),
                                callback = this.callback,
                                url = "http://localhost:4815/api/user/mike/uploads";

                            Step(
                                function() {
                                    httputil.getJSON(url, cred, this);
                                },
                                function(err, feed, response) {
                                    return callback(err, feed);
                                }
                            );
                        },
                        "it works": function(err, feed) {
                            assert.ifError(err);
                            assert.isObject(feed);
                        },
                        "it is correct": function(err, feed) {
                            assert.ifError(err);
                            assert.isObject(feed);
                            assertValidFeed(feed);
                        },
                        "it is empty": function(err, feed) {
                            assert.ifError(err);
                            assert.isObject(feed);
                            assert.equal(feed.totalItems, 0);
                            assert.lengthOf(feed.items, 0);
                        },
                        "and we upload a file": {
                            topic: function(feed, pair, cl) {
                                var cred = makeCred(cl, pair),
                                    callback = this.callback,
                                    url = "http://localhost:4815/api/user/mike/uploads",
                                    fileName = path.join(__dirname, "data", "image1.jpg");

                                Step(
                                    function() {
                                        httputil.postFile(url, cred, fileName, "image/jpeg", this);
                                    },
                                    function(err, doc, response) {
                                        return callback(err, doc);
                                    }
                                );
                            },
                            "it works": function(err, doc) {
                                assert.ifError(err);
                                assert.isObject(doc);
                            },
                            "it looks right": function(err, doc) {
                                assert.ifError(err);
                                assert.isObject(doc);
                                assert.include(doc, "objectType");
                                assert.equal(doc.objectType, "image");
                                assert.include(doc, "fullImage");
                                assert.isObject(doc.fullImage);
                                assert.include(doc.fullImage, "url");
                                assert.isString(doc.fullImage.url);
                                assert.isFalse(_.has(doc, "_slug"));
                                assert.isFalse(_.has(doc, "_uuid"));
                            },
                            "and we get the file": {
                                topic: function(doc, feed, pair, cl) {
                                    var cred = makeCred(cl, pair),
                                        callback = this.callback,
                                        url = doc.fullImage.url,
                                        oa;

                                    oa = httputil.newOAuth(url, cred);

                                    Step(
                                        function() {
                                            oa.get(url, cred.token, cred.token_secret, this);
                                        },
                                        function(err, data, response) {
                                            callback(err, data);
                                        }
                                    );
                                },
                                "it works": function(err, data) {
                                    assert.ifError(err);
                                }
                            },
                            "and we get the uploads feed again": {
                                topic: function(doc, feed, pair, cl) {
                                    var cred = makeCred(cl, pair),
                                        callback = this.callback,
                                        url = "http://localhost:4815/api/user/mike/uploads";

                                    Step(
                                        function() {
                                            httputil.getJSON(url, cred, this);
                                        },
                                        function(err, feed, response) {
                                            return callback(err, feed, doc);
                                        }
                                    );
                                },
                                "it works": function(err, feed, doc) {
                                    assert.ifError(err);
                                    assert.isObject(feed);
                                },
                                "it is correct": function(err, feed, doc) {
                                    assert.ifError(err);
                                    assert.isObject(feed);
                                    assertValidFeed(feed);
                                },
                                "it has our upload": function(err, feed, doc) {
                                    assert.ifError(err);
                                    assert.isObject(feed);
                                    assert.equal(feed.totalItems, 1);
                                    assert.lengthOf(feed.items, 1);
                                    assert.equal(feed.items[0].id, doc.id);
                                }
                            },
                            "and we post an activity with the upload as the object": {
                                topic: function(upl, feed, pair, cl) {
                                    var cred = makeCred(cl, pair),
                                        callback = this.callback,
                                        url = "http://localhost:4815/api/user/mike/feed",
                                        act = {
                                            verb: "post",
                                            object: upl
                                        };

                                    Step(
                                        function() {
                                            httputil.postJSON(url, cred, act, this);
                                        },
                                        function(err, doc, response) {
                                            return callback(err, doc);
                                        }
                                    );
                                },
                                "it works": function(err, act) {
                                    assert.ifError(err);
                                    assert.isObject(act);
                                }
                            }
                        }
                    }
                },
                "and we register another user": {
                    topic: function(cl) {
                        newPair(cl, "tom", "pick*eat*rate", this.callback);
                    },
                    "it works": function(err, pair) {
                        assert.ifError(err);
                        assert.isObject(pair);
                    },
                    "and we upload a file as a Binary object": {
                        topic: function(pair, cl) {
                            var cred = makeCred(cl, pair),
                                callback = this.callback,
                                url = "http://localhost:4815/api/user/tom/uploads",
                                fileName = path.join(__dirname, "data", "image2.jpg");

                            Step(
                                function() {
                                    fs.readFile(fileName, this);
                                },
                                function(err, data) {
                                    var bin;
                                    if (err) throw err;
                                    bin = {length: data.length,
                                           mimeType: "image/jpeg"
                                          };
                                    bin.data = data.toString("base64")
                                        .replace(/\+/g, "-")
                                        .replace(/\//g, "_")
                                        .replace(/=/g, "");

                                    httputil.postJSON(url, cred, bin, this);
                                },
                                function(err, doc, result) {
                                    if (err) {
                                        callback(err, null);
                                    } else {
                                        callback(null, doc);
                                    }
                                }
                            );
                        },
                        "it works": function(err, doc) {
                            assert.ifError(err);
                            assert.isObject(doc);
                        },
                        "it looks right": function(err, doc) {
                            assert.ifError(err);
                            assert.isObject(doc);
                            assert.include(doc, "objectType");
                            assert.equal(doc.objectType, "image");
                            assert.include(doc, "fullImage");
                            assert.isObject(doc.fullImage);
                            assert.include(doc.fullImage, "url");
                            assert.isString(doc.fullImage.url);
                            assert.isFalse(_.has(doc, "_slug"));
                            assert.isFalse(_.has(doc, "_uuid"));
                        }
                    }
                }
            }
        }
    }
});

suite["export"](module);
<commit_msg>Remove accessToken import from upload-file-test<commit_after>// upload-file-test.js
//
// Test uploading a file to a server
//
// Copyright 2012, E14N https://e14n.com/
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

var assert = require("assert"),
    vows = require("vows"),
    Step = require("step"),
    os = require("os"),
    fs = require("fs"),
    path = require("path"),
    mkdirp = require("mkdirp"),
    rimraf = require("rimraf"),
    _ = require("underscore"),
    httputil = require("./lib/http"),
    oauthutil = require("./lib/oauth"),
    actutil = require("./lib/activity"),
    setupAppConfig = oauthutil.setupAppConfig,
    newCredentials = oauthutil.newCredentials,
    newPair = oauthutil.newPair,
    newClient = oauthutil.newClient,
    register = oauthutil.register;

var suite = vows.describe("upload file test");

var makeCred = function(cl, pair) {
    return {
        consumer_key: cl.client_id,
        consumer_secret: cl.client_secret,
        token: pair.token,
        token_secret: pair.token_secret
    };
};

var assertValidFeed = function(feed) {
    assert.include(feed, "totalItems");
    assert.isNumber(feed.totalItems);
    assert.include(feed, "url");
    assert.isString(feed.url);
    assert.include(feed, "items");
    assert.isArray(feed.items);
};

suite.addBatch({
    "When we create a temporary upload dir": {
        topic: function() {
            var callback = this.callback,
                dirname = path.join(os.tmpDir(),
                                    "upload-file-test",
                                    ""+Date.now());
            mkdirp(dirname, function (err) {
                if (err) {
                    callback(err, null);
                } else {
                    callback(null, dirname);
                }
            });
        },
        "it works": function(err, dir) {
            assert.ifError(err);
            assert.isString(dir);
        },
        teardown: function(dir) {
            rimraf(dir, function(err) {
            });
        },
        "and we set up the app": {
            topic: function(dir) {
                setupAppConfig({uploaddir: dir},
                               this.callback);
            },
            teardown: function(app) {
                if (app && app.close) {
                    app.close();
                }
            },
            "it works": function(err, app) {
                assert.ifError(err);
            },
            "and we register a client": {
                topic: function() {
                    newClient(this.callback);
                },
                "it works": function(err, cl) {
                    assert.ifError(err);
                    assert.isObject(cl);
                },
                "and we create a new user": {
                    topic: function(cl) {
                        newPair(cl, "mike", "stormtroopers_hittin_the_ground", this.callback);
                    },
                    "it works": function(err, pair) {
                        assert.ifError(err);
                        assert.isObject(pair);
                    },
                    "and we check the uploads endpoint":
                    httputil.endpoint("/api/user/mike/uploads", ["POST", "GET"]),
                    "and we get the uploads endpoint of a new user": {
                        topic: function(pair, cl) {
                            var cred = makeCred(cl, pair),
                                callback = this.callback,
                                url = "http://localhost:4815/api/user/mike/uploads";

                            Step(
                                function() {
                                    httputil.getJSON(url, cred, this);
                                },
                                function(err, feed, response) {
                                    return callback(err, feed);
                                }
                            );
                        },
                        "it works": function(err, feed) {
                            assert.ifError(err);
                            assert.isObject(feed);
                        },
                        "it is correct": function(err, feed) {
                            assert.ifError(err);
                            assert.isObject(feed);
                            assertValidFeed(feed);
                        },
                        "it is empty": function(err, feed) {
                            assert.ifError(err);
                            assert.isObject(feed);
                            assert.equal(feed.totalItems, 0);
                            assert.lengthOf(feed.items, 0);
                        },
                        "and we upload a file": {
                            topic: function(feed, pair, cl) {
                                var cred = makeCred(cl, pair),
                                    callback = this.callback,
                                    url = "http://localhost:4815/api/user/mike/uploads",
                                    fileName = path.join(__dirname, "data", "image1.jpg");

                                Step(
                                    function() {
                                        httputil.postFile(url, cred, fileName, "image/jpeg", this);
                                    },
                                    function(err, doc, response) {
                                        return callback(err, doc);
                                    }
                                );
                            },
                            "it works": function(err, doc) {
                                assert.ifError(err);
                                assert.isObject(doc);
                            },
                            "it looks right": function(err, doc) {
                                assert.ifError(err);
                                assert.isObject(doc);
                                assert.include(doc, "objectType");
                                assert.equal(doc.objectType, "image");
                                assert.include(doc, "fullImage");
                                assert.isObject(doc.fullImage);
                                assert.include(doc.fullImage, "url");
                                assert.isString(doc.fullImage.url);
                                assert.isFalse(_.has(doc, "_slug"));
                                assert.isFalse(_.has(doc, "_uuid"));
                            },
                            "and we get the file": {
                                topic: function(doc, feed, pair, cl) {
                                    var cred = makeCred(cl, pair),
                                        callback = this.callback,
                                        url = doc.fullImage.url,
                                        oa;

                                    oa = httputil.newOAuth(url, cred);

                                    Step(
                                        function() {
                                            oa.get(url, cred.token, cred.token_secret, this);
                                        },
                                        function(err, data, response) {
                                            callback(err, data);
                                        }
                                    );
                                },
                                "it works": function(err, data) {
                                    assert.ifError(err);
                                }
                            },
                            "and we get the uploads feed again": {
                                topic: function(doc, feed, pair, cl) {
                                    var cred = makeCred(cl, pair),
                                        callback = this.callback,
                                        url = "http://localhost:4815/api/user/mike/uploads";

                                    Step(
                                        function() {
                                            httputil.getJSON(url, cred, this);
                                        },
                                        function(err, feed, response) {
                                            return callback(err, feed, doc);
                                        }
                                    );
                                },
                                "it works": function(err, feed, doc) {
                                    assert.ifError(err);
                                    assert.isObject(feed);
                                },
                                "it is correct": function(err, feed, doc) {
                                    assert.ifError(err);
                                    assert.isObject(feed);
                                    assertValidFeed(feed);
                                },
                                "it has our upload": function(err, feed, doc) {
                                    assert.ifError(err);
                                    assert.isObject(feed);
                                    assert.equal(feed.totalItems, 1);
                                    assert.lengthOf(feed.items, 1);
                                    assert.equal(feed.items[0].id, doc.id);
                                }
                            },
                            "and we post an activity with the upload as the object": {
                                topic: function(upl, feed, pair, cl) {
                                    var cred = makeCred(cl, pair),
                                        callback = this.callback,
                                        url = "http://localhost:4815/api/user/mike/feed",
                                        act = {
                                            verb: "post",
                                            object: upl
                                        };

                                    Step(
                                        function() {
                                            httputil.postJSON(url, cred, act, this);
                                        },
                                        function(err, doc, response) {
                                            return callback(err, doc);
                                        }
                                    );
                                },
                                "it works": function(err, act) {
                                    assert.ifError(err);
                                    assert.isObject(act);
                                }
                            }
                        }
                    }
                },
                "and we register another user": {
                    topic: function(cl) {
                        newPair(cl, "tom", "pick*eat*rate", this.callback);
                    },
                    "it works": function(err, pair) {
                        assert.ifError(err);
                        assert.isObject(pair);
                    },
                    "and we upload a file as a Binary object": {
                        topic: function(pair, cl) {
                            var cred = makeCred(cl, pair),
                                callback = this.callback,
                                url = "http://localhost:4815/api/user/tom/uploads",
                                fileName = path.join(__dirname, "data", "image2.jpg");

                            Step(
                                function() {
                                    fs.readFile(fileName, this);
                                },
                                function(err, data) {
                                    var bin;
                                    if (err) throw err;
                                    bin = {length: data.length,
                                           mimeType: "image/jpeg"
                                          };
                                    bin.data = data.toString("base64")
                                        .replace(/\+/g, "-")
                                        .replace(/\//g, "_")
                                        .replace(/=/g, "");

                                    httputil.postJSON(url, cred, bin, this);
                                },
                                function(err, doc, result) {
                                    if (err) {
                                        callback(err, null);
                                    } else {
                                        callback(null, doc);
                                    }
                                }
                            );
                        },
                        "it works": function(err, doc) {
                            assert.ifError(err);
                            assert.isObject(doc);
                        },
                        "it looks right": function(err, doc) {
                            assert.ifError(err);
                            assert.isObject(doc);
                            assert.include(doc, "objectType");
                            assert.equal(doc.objectType, "image");
                            assert.include(doc, "fullImage");
                            assert.isObject(doc.fullImage);
                            assert.include(doc.fullImage, "url");
                            assert.isString(doc.fullImage.url);
                            assert.isFalse(_.has(doc, "_slug"));
                            assert.isFalse(_.has(doc, "_uuid"));
                        }
                    }
                }
            }
        }
    }
});

suite["export"](module);
<|endoftext|>


<commit_before>// Checks for equality of elements in two arrays.
var arrays_equal = function(a1, a2) {
  if (a1.length !== a2.length) return false;
  for (var i = 0; i < a1.length; ++i) {
    if (a1[i] !== a2[i]) return false;
  }
  return true;
};

// Given width w and height h, rescale the dimensions to satisfy
// the specified number of pixels.
var rescale_dimensions = function(w, h, pixels) {
  var aspect_ratio = w / h;
  var scaling_factor = Math.sqrt(pixels / aspect_ratio);
  var rescaled_w = Math.floor(aspect_ratio * scaling_factor);
  var rescaled_h = Math.floor(scaling_factor);
  return [rescaled_w, rescaled_h];
};

// Given an Image, return a dataset with pixel colors.
// If resized_pixels > 0, image will be resized prior to building
// the dataset.
// return: [[R,G,B,a], [R,G,B,a], [R,G,B,a], ...]
var get_pixel_dataset = function(img, resized_pixels) {
  if (resized_pixels === undefined) resized_pixels = -1;
  // Get pixel colors from a <canvas> with the image
  var canvas = document.createElement("canvas");
  var img_n_pixels = img.width * img.height;
  var canvas_width = img.width;
  var canvas_height = img.height;
  if (resized_pixels > 0 && img_n_pixels > resized_pixels) {
    var rescaled = rescale_dimensions(img.width, img.height, resized_pixels)
    canvas_width = rescaled[0];
    canvas_height = rescaled[1];
  }
  canvas.width = canvas_width;
  canvas.height = canvas_height;
  var canvas_n_pixels = canvas_width * canvas_height;
  var context = canvas.getContext("2d");
  context.drawImage(img, 0, 0, canvas_width, canvas_height);
  var flattened_dataset = context.getImageData(
      0, 0, canvas_width, canvas_height).data;
  var n_channels = flattened_dataset.length / canvas_n_pixels;
  var dataset = [];
  for (var i = 0; i < flattened_dataset.length; i += n_channels) {
    dataset.push(flattened_dataset.slice(i, i + n_channels));
  }
  return dataset;
};

// Given a point and a list of neighbor points, return the index
// for the neighbor that's closest to the point.
var nearest_neighbor = function(point, neighbors) {
  var best_dist = Infinity; // squared distance
  var best_index = -1;
  for (var i = 0; i < neighbors.length; ++i) {
    var neighbor = neighbors[i];
    var dist = 0;
    for (var j = 0; j < point.length; ++j) {
      dist += Math.pow(point[j] - neighbor[j], 2);
    }
    if (dist < best_dist) {
      best_dist = dist;
      best_index = i;
    }
  }
  return best_index;
};

// Returns the centroid of a dataset.
var centroid = function(dataset) {
  if (dataset.length === 0) return [];
  // Calculate running means.
  var running_centroid = [];
  for (var i = 0; i < dataset[0].length; ++i) {
    running_centroid.push(0);
  }
  for (var i = 0; i < dataset.length; ++i) {
    var point = dataset[i];
    for (var j = 0; j < point.length; ++j) {
      running_centroid[j] += (point[j] - running_centroid[j]) / (i+1);
    }
  }
  return running_centroid;
};

// Returns the k-means centroids.
var k_means = function(dataset, k) {
  if (k === undefined) k = Math.min(3, dataset.length);
  // Use a seeded random number generator instead of Math.random(),
  // so that k-means always produces the same centroids for the same
  // input.
  rng_seed = 0;
  var random = function() {
    rng_seed = (rng_seed * 9301 + 49297) % 233280;
    return rng_seed / 233280;
  };
  // Choose initial centroids randomly.
  centroids = [];
  for (var i = 0; i < k; ++i) {
    var idx = Math.floor(random() * dataset.length);
    centroids.push(dataset[idx]);
  }
  while (true) {
    // 'clusters' is an array of arrays. each sub-array corresponds to
    // a cluster, and has the points in that cluster.
    var clusters = [];
    for (var i = 0; i < k; ++i) {
      clusters.push([]);
    }
    for (var i = 0; i < dataset.length; ++i) {
      var point = dataset[i];
      var nearest_centroid = nearest_neighbor(point, centroids);
      clusters[nearest_centroid].push(point);
    }
    var converged = true;
    for (var i = 0; i < k; ++i) {
      var cluster = clusters[i];
      var centroid_i = [];
      if (cluster.length > 0) {
        centroid_i = centroid(cluster);
      } else {
        // For an empty cluster, set a random point as the centroid.
        var idx = Math.floor(random() * dataset.length);
        centroid_i = dataset[idx];
      }
      converged = converged && arrays_equal(centroid_i, centroids[i]);
      centroids[i] = centroid_i;
    }
    if (converged) break;
  }
  return centroids;
};

var quantize = function(img, destination_img, k) {
  // quantized dimensions
  var quantized_w = img.width;
  var quantized_h = img.height;
  // Resize to a smaller image to speed quantizing.
  var MAX_QUANTIZED_PIXELS = -1;
  if (MAX_QUANTIZED_PIXELS > 0
      && quantized_h * quantized_w > MAX_QUANTIZED_PIXELS) {
    var rescaled = rescale_dimensions(
        quantized_w, quantized_h, MAX_QUANTIZED_PIXELS);
    quantized_w = rescaled[0];
    quantized_h = rescaled[1];
  }

  // Use a fixed maximum so that k-means works fast.
  var MAX_K_MEANS_PIXELS = 50000;
  var pixel_dataset = get_pixel_dataset(img, MAX_K_MEANS_PIXELS);

  // Calculate cluster centroids of all pixels in the image.
  centroids = k_means(pixel_dataset, k);

  var source_canvas = document.createElement("canvas");
  source_canvas.width = quantized_w;
  source_canvas.height = quantized_h;
  var source_context = source_canvas.getContext("2d");
  source_context.drawImage(img, 0, 0, quantized_w, quantized_h);

  // flattened_*_data = [R, G, B, a, R, G, B, a, ...] where
  // (R, G, B, a) groups each correspond to a single pixel, and they are
  // column-major ordered.
  var flattened_source_data = source_context.getImageData(
      0, 0, quantized_w, quantized_h).data;
  var n_pixels = quantized_w * quantized_h;
  var n_channels = flattened_source_data.length / n_pixels;

  var flattened_quantized_data = new Uint8ClampedArray(
      flattened_source_data.length);

  // Set each pixel to its nearest centroid.
  for (var i = 0; i < flattened_source_data.length; i += n_channels) {
    var pixel = flattened_source_data.slice(i, i + n_channels);
    var nearest_centroid_index = nearest_neighbor(pixel, centroids);
    var nearest_centroid = centroids[nearest_centroid_index];
    for (var j = 0; j < nearest_centroid.length; ++j) {
      flattened_quantized_data[i+j] = nearest_centroid[j];
    }
  }

  var quantized_canvas = document.createElement("canvas");
  quantized_canvas.width = quantized_w;
  quantized_canvas.height = quantized_h;
  var quantized_context = quantized_canvas.getContext("2d");

  var image = quantized_context.createImageData(quantized_w, quantized_h);
  image.data.set(flattened_quantized_data);
  quantized_context.putImageData(image, 0, 0);
  destination_img.src = quantized_canvas.toDataURL();
};

// HTML Elements
var input_file_element = document.getElementById("input_file");
var quantize_btn_element = document.getElementById("quantize_btn");
var k_selections_element = document.getElementById("k_selections");
var status_element = document.getElementById("status");

// Fill k selections.
k_options = [2,3,4,5,6,7,8,9,10,11,12];
default_k = 3;
for (var i = 0; i < k_options.length; ++i) {
  var k = k_options[i];
  var option_element = document.createElement("option");
  option_element.value = k;
  option_element.textContent = k;
  k_selections_element.appendChild(option_element);
  if (k === default_k) k_selections_element.selectedIndex = i;
}

// Enable the quantize button if a file has been selected, and
// disable otherwise.
var set_quantize_button = function() {
  files = input_file_element.files;
  quantize_btn_element.disabled = !files || !files.length;
};

input_file_element.addEventListener("change", set_quantize_button);
window.addEventListener("load", set_quantize_button);

var pre_quantize = function() {
  // Clear any existing image.
  if (quantized_img.hasAttribute("src")) {
    quantized_img.removeAttribute("src");
  }
  quantize_btn_element.disabled = true;
  input_file_element.disabled = true;
  k_selections_element.disabled = true;
  status_element.textContent = "Processing...";
};

var post_quantize = function() {
  quantize_btn_element.disabled = false;
  input_file_element.disabled = false;
  k_selections_element.disabled = false;
  status_element.textContent = "";
};

// Handle "Quantize" button.
quantize_btn_element.addEventListener("click", function() {
  files = input_file_element.files;
  if (!FileReader || !files || !files.length) return;
  var quantized_img = document.getElementById("quantized_img");
  var reader = new FileReader();
  reader.addEventListener("load", function() {
    var k = parseInt(k_selections_element.value);
    var img = new Image();
    img.onload = function() {
      // Use a combination of requestAnimationFrame and setTimeout
      // to run quantize/post_quantize after the next repaint, which is
      // triggered by pre_quantize().
      requestAnimationFrame(function() {
        setTimeout(function() {
          quantize(img, quantized_img, k);
          post_quantize();
        }, 0);
      });
      pre_quantize();
    };
    img.src = reader.result;
  });
  reader.readAsDataURL(files[0]);
});

<commit_msg>Use a for loop instead of Array.slice.<commit_after>// Checks for equality of elements in two arrays.
var arrays_equal = function(a1, a2) {
  if (a1.length !== a2.length) return false;
  for (var i = 0; i < a1.length; ++i) {
    if (a1[i] !== a2[i]) return false;
  }
  return true;
};

// Given width w and height h, rescale the dimensions to satisfy
// the specified number of pixels.
var rescale_dimensions = function(w, h, pixels) {
  var aspect_ratio = w / h;
  var scaling_factor = Math.sqrt(pixels / aspect_ratio);
  var rescaled_w = Math.floor(aspect_ratio * scaling_factor);
  var rescaled_h = Math.floor(scaling_factor);
  return [rescaled_w, rescaled_h];
};

// Given an Image, return a dataset with pixel colors.
// If resized_pixels > 0, image will be resized prior to building
// the dataset.
// return: [[R,G,B,a], [R,G,B,a], [R,G,B,a], ...]
var get_pixel_dataset = function(img, resized_pixels) {
  if (resized_pixels === undefined) resized_pixels = -1;
  // Get pixel colors from a <canvas> with the image
  var canvas = document.createElement("canvas");
  var img_n_pixels = img.width * img.height;
  var canvas_width = img.width;
  var canvas_height = img.height;
  if (resized_pixels > 0 && img_n_pixels > resized_pixels) {
    var rescaled = rescale_dimensions(img.width, img.height, resized_pixels)
    canvas_width = rescaled[0];
    canvas_height = rescaled[1];
  }
  canvas.width = canvas_width;
  canvas.height = canvas_height;
  var canvas_n_pixels = canvas_width * canvas_height;
  var context = canvas.getContext("2d");
  context.drawImage(img, 0, 0, canvas_width, canvas_height);
  var flattened_dataset = context.getImageData(
      0, 0, canvas_width, canvas_height).data;
  var n_channels = flattened_dataset.length / canvas_n_pixels;
  var dataset = [];
  for (var i = 0; i < flattened_dataset.length; i += n_channels) {
    dataset.push(flattened_dataset.slice(i, i + n_channels));
  }
  return dataset;
};

// Given a point and a list of neighbor points, return the index
// for the neighbor that's closest to the point.
var nearest_neighbor = function(point, neighbors) {
  var best_dist = Infinity; // squared distance
  var best_index = -1;
  for (var i = 0; i < neighbors.length; ++i) {
    var neighbor = neighbors[i];
    var dist = 0;
    for (var j = 0; j < point.length; ++j) {
      dist += Math.pow(point[j] - neighbor[j], 2);
    }
    if (dist < best_dist) {
      best_dist = dist;
      best_index = i;
    }
  }
  return best_index;
};

// Returns the centroid of a dataset.
var centroid = function(dataset) {
  if (dataset.length === 0) return [];
  // Calculate running means.
  var running_centroid = [];
  for (var i = 0; i < dataset[0].length; ++i) {
    running_centroid.push(0);
  }
  for (var i = 0; i < dataset.length; ++i) {
    var point = dataset[i];
    for (var j = 0; j < point.length; ++j) {
      running_centroid[j] += (point[j] - running_centroid[j]) / (i+1);
    }
  }
  return running_centroid;
};

// Returns the k-means centroids.
var k_means = function(dataset, k) {
  if (k === undefined) k = Math.min(3, dataset.length);
  // Use a seeded random number generator instead of Math.random(),
  // so that k-means always produces the same centroids for the same
  // input.
  rng_seed = 0;
  var random = function() {
    rng_seed = (rng_seed * 9301 + 49297) % 233280;
    return rng_seed / 233280;
  };
  // Choose initial centroids randomly.
  centroids = [];
  for (var i = 0; i < k; ++i) {
    var idx = Math.floor(random() * dataset.length);
    centroids.push(dataset[idx]);
  }
  while (true) {
    // 'clusters' is an array of arrays. each sub-array corresponds to
    // a cluster, and has the points in that cluster.
    var clusters = [];
    for (var i = 0; i < k; ++i) {
      clusters.push([]);
    }
    for (var i = 0; i < dataset.length; ++i) {
      var point = dataset[i];
      var nearest_centroid = nearest_neighbor(point, centroids);
      clusters[nearest_centroid].push(point);
    }
    var converged = true;
    for (var i = 0; i < k; ++i) {
      var cluster = clusters[i];
      var centroid_i = [];
      if (cluster.length > 0) {
        centroid_i = centroid(cluster);
      } else {
        // For an empty cluster, set a random point as the centroid.
        var idx = Math.floor(random() * dataset.length);
        centroid_i = dataset[idx];
      }
      converged = converged && arrays_equal(centroid_i, centroids[i]);
      centroids[i] = centroid_i;
    }
    if (converged) break;
  }
  return centroids;
};

var quantize = function(img, destination_img, k) {
  // quantized dimensions
  var quantized_w = img.width;
  var quantized_h = img.height;
  // Resize to a smaller image to speed quantizing.
  var MAX_QUANTIZED_PIXELS = -1;
  if (MAX_QUANTIZED_PIXELS > 0
      && quantized_h * quantized_w > MAX_QUANTIZED_PIXELS) {
    var rescaled = rescale_dimensions(
        quantized_w, quantized_h, MAX_QUANTIZED_PIXELS);
    quantized_w = rescaled[0];
    quantized_h = rescaled[1];
  }

  // Use a fixed maximum so that k-means works fast.
  var MAX_K_MEANS_PIXELS = 50000;
  var pixel_dataset = get_pixel_dataset(img, MAX_K_MEANS_PIXELS);

  // Calculate cluster centroids of all pixels in the image.
  centroids = k_means(pixel_dataset, k);

  var source_canvas = document.createElement("canvas");
  source_canvas.width = quantized_w;
  source_canvas.height = quantized_h;
  var source_context = source_canvas.getContext("2d");
  source_context.drawImage(img, 0, 0, quantized_w, quantized_h);

  // flattened_*_data = [R, G, B, a, R, G, B, a, ...] where
  // (R, G, B, a) groups each correspond to a single pixel, and they are
  // column-major ordered.
  var flattened_source_data = source_context.getImageData(
      0, 0, quantized_w, quantized_h).data;
  var n_pixels = quantized_w * quantized_h;
  var n_channels = flattened_source_data.length / n_pixels;

  var flattened_quantized_data = new Uint8ClampedArray(
      flattened_source_data.length);

  // Set each pixel to its nearest centroid.
  var current_pixel = new Uint8ClampedArray(n_channels);
  for (var i = 0; i < flattened_source_data.length; i += n_channels) {
    // This for loop approach is faster than using Array.slice().
    for (var j = 0; j < n_channels; ++j) {
      current_pixel[j] = flattened_source_data[i + j];
    }
    var nearest_centroid_index = nearest_neighbor(current_pixel, centroids);
    var nearest_centroid = centroids[nearest_centroid_index];
    for (var j = 0; j < nearest_centroid.length; ++j) {
      flattened_quantized_data[i+j] = nearest_centroid[j];
    }
  }

  var quantized_canvas = document.createElement("canvas");
  quantized_canvas.width = quantized_w;
  quantized_canvas.height = quantized_h;
  var quantized_context = quantized_canvas.getContext("2d");

  var image = quantized_context.createImageData(quantized_w, quantized_h);
  image.data.set(flattened_quantized_data);
  quantized_context.putImageData(image, 0, 0);
  destination_img.src = quantized_canvas.toDataURL();
};

// HTML Elements
var input_file_element = document.getElementById("input_file");
var quantize_btn_element = document.getElementById("quantize_btn");
var k_selections_element = document.getElementById("k_selections");
var status_element = document.getElementById("status");

// Fill k selections.
k_options = [2,3,4,5,6,7,8,9,10,11,12];
default_k = 3;
for (var i = 0; i < k_options.length; ++i) {
  var k = k_options[i];
  var option_element = document.createElement("option");
  option_element.value = k;
  option_element.textContent = k;
  k_selections_element.appendChild(option_element);
  if (k === default_k) k_selections_element.selectedIndex = i;
}

// Enable the quantize button if a file has been selected, and
// disable otherwise.
var set_quantize_button = function() {
  files = input_file_element.files;
  quantize_btn_element.disabled = !files || !files.length;
};

input_file_element.addEventListener("change", set_quantize_button);
window.addEventListener("load", set_quantize_button);

var pre_quantize = function() {
  // Clear any existing image.
  if (quantized_img.hasAttribute("src")) {
    quantized_img.removeAttribute("src");
  }
  quantize_btn_element.disabled = true;
  input_file_element.disabled = true;
  k_selections_element.disabled = true;
  status_element.textContent = "Processing...";
};

var post_quantize = function() {
  quantize_btn_element.disabled = false;
  input_file_element.disabled = false;
  k_selections_element.disabled = false;
  status_element.textContent = "";
};

// Handle "Quantize" button.
quantize_btn_element.addEventListener("click", function() {
  files = input_file_element.files;
  if (!FileReader || !files || !files.length) return;
  var quantized_img = document.getElementById("quantized_img");
  var reader = new FileReader();
  reader.addEventListener("load", function() {
    var k = parseInt(k_selections_element.value);
    var img = new Image();
    img.onload = function() {
      // Use a combination of requestAnimationFrame and setTimeout
      // to run quantize/post_quantize after the next repaint, which is
      // triggered by pre_quantize().
      requestAnimationFrame(function() {
        setTimeout(function() {
          quantize(img, quantized_img, k);
          post_quantize();
        }, 0);
      });
      pre_quantize();
    };
    img.src = reader.result;
  });
  reader.readAsDataURL(files[0]);
});

<|endoftext|>


<commit_before>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/* globals PDFJS, expect, it, describe, Promise, combineUrl, waitsFor,
           isArray */

'use strict';

describe('api', function() {
  // TODO run with worker enabled
  var basicApiUrl = combineUrl(window.location.href, '../pdfs/basicapi.pdf');
  function waitsForPromiseResolved(promise, successCallback) {
    var data;
    promise.then(function(val) {
      data = val;
      successCallback(data);
    },
    function(error) {
      // Shouldn't get here.
      expect(false).toEqual(true);
    });
    waitsFor(function() {
      return data !== undefined;
    }, 20000);
  }
  function waitsForPromiseRejected(promise, failureCallback) {
    var data;
    promise.then(function(val) {
      // Shouldn't get here.
      expect(false).toEqual(true);
    },
    function(error) {
      data = error;
      failureCallback(data);
    });
    waitsFor(function() {
      return data !== undefined;
    }, 20000);
  }
  describe('PDFJS', function() {
    describe('getDocument', function() {
      it('creates pdf doc from URL', function() {
        var promise = PDFJS.getDocument(basicApiUrl);
        waitsForPromiseResolved(promise, function(data) {
          expect(true).toEqual(true);
        });
      });
      it('creates pdf doc from typed array', function() {
        var nonBinaryRequest = PDFJS.disableWorker;
        var request = new XMLHttpRequest();
        request.open('GET', basicApiUrl, false);
        if (!nonBinaryRequest) {
          try {
            request.responseType = 'arraybuffer';
            nonBinaryRequest = request.responseType !== 'arraybuffer';
          } catch (e) {
            nonBinaryRequest = true;
          }
        }
        if (nonBinaryRequest && request.overrideMimeType) {
          request.overrideMimeType('text/plain; charset=x-user-defined');
        }
        request.send(null);

        var typedArrayPdf;
        if (nonBinaryRequest) {
          var data = Array.prototype.map.call(request.responseText,
              function (ch) {
            return ch.charCodeAt(0) & 0xFF;
          });
          typedArrayPdf = new Uint8Array(data);
        } else {
          typedArrayPdf = new Uint8Array(request.response);
        }
        // Sanity check to make sure that we fetched the entire PDF file.
        expect(typedArrayPdf.length).toEqual(105779);

        var promise = PDFJS.getDocument(typedArrayPdf);
        waitsForPromiseResolved(promise, function(data) {
          expect(true).toEqual(true);
        });
      });
    });
  });
  describe('PDFDocument', function() {
    var promise = PDFJS.getDocument(basicApiUrl);
    var doc;
    waitsForPromiseResolved(promise, function(data) {
      doc = data;
    });
    it('gets number of pages', function() {
      expect(doc.numPages).toEqual(3);
    });
    it('gets fingerprint', function() {
      expect(typeof doc.fingerprint).toEqual('string');
    });
    it('gets page', function() {
      var promise = doc.getPage(1);
      waitsForPromiseResolved(promise, function(data) {
        expect(true).toEqual(true);
      });
    });
    it('gets page index', function() {
      // reference to second page
      var ref = {num: 17, gen: 0};
      var promise = doc.getPageIndex(ref);
      waitsForPromiseResolved(promise, function(pageIndex) {
        expect(pageIndex).toEqual(1);
      });
    });
    it('gets destinations', function() {
      var promise = doc.getDestinations();
      waitsForPromiseResolved(promise, function(data) {
        expect(data).toEqual({ chapter1: [{ gen: 0, num: 17 }, { name: 'XYZ' },
                                          0, 841.89, null] });
      });
    });
    it('gets attachments', function() {
      var promise = doc.getAttachments();
      waitsForPromiseResolved(promise, function (data) {
        expect(data).toEqual(null);
      });
    });
    it('gets javascript', function() {
      var promise = doc.getJavaScript();
      waitsForPromiseResolved(promise, function (data) {
        expect(data).toEqual([]);
      });
    });
    it('gets outline', function() {
      var promise = doc.getOutline();
      waitsForPromiseResolved(promise, function(outline) {
        // Two top level entries.
        expect(outline.length).toEqual(2);
        // Make sure some basic attributes are set.
        expect(outline[1].title).toEqual('Chapter 1');
        expect(outline[1].items.length).toEqual(1);
        expect(outline[1].items[0].title).toEqual('Paragraph 1.1');
      });
    });
    it('gets metadata', function() {
      var promise = doc.getMetadata();
      waitsForPromiseResolved(promise, function(metadata) {
        expect(metadata.info['Title']).toEqual('Basic API Test');
        expect(metadata.metadata.get('dc:title')).toEqual('Basic API Test');
      });
    });
    it('gets data', function() {
      var promise = doc.getData();
      waitsForPromiseResolved(promise, function (data) {
        expect(true).toEqual(true);
      });
    });
    it('gets filesize in bytes', function() {
      var promise = doc.getDownloadInfo();
      waitsForPromiseResolved(promise, function (data) {
        expect(data.length).toEqual(105779);
      });
    });
    it('gets stats', function() {
      var promise = doc.getStats();
      waitsForPromiseResolved(promise, function (stats) {
        expect(isArray(stats.streamTypes)).toEqual(true);
        expect(isArray(stats.fontTypes)).toEqual(true);
      });
    });
  });
  describe('Page', function() {
    var resolvePromise;
    var promise = new Promise(function (resolve) {
      resolvePromise = resolve;
    });
    PDFJS.getDocument(basicApiUrl).then(function(doc) {
      doc.getPage(1).then(function(data) {
        resolvePromise(data);
      });
    });
    var page;
    waitsForPromiseResolved(promise, function(data) {
      page = data;
    });
    it('gets page number', function () {
      expect(page.pageNumber).toEqual(1);
    });
    it('gets rotate', function () {
      expect(page.rotate).toEqual(0);
    });
    it('gets ref', function () {
      expect(page.ref).toEqual({ num: 15, gen: 0 });
    });
    it('gets view', function () {
      expect(page.view).toEqual([0, 0, 595.28, 841.89]);
    });
    it('gets viewport', function () {
      var viewport = page.getViewport(1.5, 90);
      expect(viewport.viewBox).toEqual(page.view);
      expect(viewport.scale).toEqual(1.5);
      expect(viewport.rotation).toEqual(90);
      expect(viewport.transform).toEqual([0, 1.5, 1.5, 0, 0, 0]);
      expect(viewport.width).toEqual(1262.835);
      expect(viewport.height).toEqual(892.92);
    });
    it('gets annotations', function () {
      var promise = page.getAnnotations();
      waitsForPromiseResolved(promise, function (data) {
        expect(data.length).toEqual(4);
      });
    });
    it('gets text content', function () {
      var promise = page.getTextContent();
      waitsForPromiseResolved(promise, function (data) {
        expect(!!data.items).toEqual(true);
        expect(data.items.length).toEqual(7);
        expect(!!data.styles).toEqual(true);
      });
    });
    it('gets operator list', function() {
      var promise = page.getOperatorList();
      waitsForPromiseResolved(promise, function (oplist) {
        expect(!!oplist.fnArray).toEqual(true);
        expect(!!oplist.argsArray).toEqual(true);
        expect(oplist.lastChunk).toEqual(true);
      });
    });
  });
});
<commit_msg>Add unit test for |MissingPDFException|<commit_after>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/* globals PDFJS, expect, it, describe, Promise, combineUrl, waitsFor,
           isArray, MissingPDFException */

'use strict';

describe('api', function() {
  // TODO run with worker enabled
  var basicApiUrl = combineUrl(window.location.href, '../pdfs/basicapi.pdf');
  function waitsForPromiseResolved(promise, successCallback) {
    var data;
    promise.then(function(val) {
      data = val;
      successCallback(data);
    },
    function(error) {
      // Shouldn't get here.
      expect(false).toEqual(true);
    });
    waitsFor(function() {
      return data !== undefined;
    }, 20000);
  }
  function waitsForPromiseRejected(promise, failureCallback) {
    var data;
    promise.then(function(val) {
      // Shouldn't get here.
      expect(false).toEqual(true);
    },
    function(error) {
      data = error;
      failureCallback(data);
    });
    waitsFor(function() {
      return data !== undefined;
    }, 20000);
  }
  describe('PDFJS', function() {
    describe('getDocument', function() {
      it('creates pdf doc from URL', function() {
        var promise = PDFJS.getDocument(basicApiUrl);
        waitsForPromiseResolved(promise, function(data) {
          expect(true).toEqual(true);
        });
      });
      it('creates pdf doc from typed array', function() {
        var nonBinaryRequest = PDFJS.disableWorker;
        var request = new XMLHttpRequest();
        request.open('GET', basicApiUrl, false);
        if (!nonBinaryRequest) {
          try {
            request.responseType = 'arraybuffer';
            nonBinaryRequest = request.responseType !== 'arraybuffer';
          } catch (e) {
            nonBinaryRequest = true;
          }
        }
        if (nonBinaryRequest && request.overrideMimeType) {
          request.overrideMimeType('text/plain; charset=x-user-defined');
        }
        request.send(null);

        var typedArrayPdf;
        if (nonBinaryRequest) {
          var data = Array.prototype.map.call(request.responseText,
              function (ch) {
            return ch.charCodeAt(0) & 0xFF;
          });
          typedArrayPdf = new Uint8Array(data);
        } else {
          typedArrayPdf = new Uint8Array(request.response);
        }
        // Sanity check to make sure that we fetched the entire PDF file.
        expect(typedArrayPdf.length).toEqual(105779);

        var promise = PDFJS.getDocument(typedArrayPdf);
        waitsForPromiseResolved(promise, function(data) {
          expect(true).toEqual(true);
        });
      });
      it('creates pdf doc from non-existent URL', function() {
        var nonExistentUrl = combineUrl(window.location.href,
                                        '../pdfs/non-existent.pdf');
        var promise = PDFJS.getDocument(nonExistentUrl);
        waitsForPromiseRejected(promise, function(error) {
          expect(error instanceof MissingPDFException).toEqual(true);
        });
      });
    });
  });
  describe('PDFDocument', function() {
    var promise = PDFJS.getDocument(basicApiUrl);
    var doc;
    waitsForPromiseResolved(promise, function(data) {
      doc = data;
    });
    it('gets number of pages', function() {
      expect(doc.numPages).toEqual(3);
    });
    it('gets fingerprint', function() {
      expect(typeof doc.fingerprint).toEqual('string');
    });
    it('gets page', function() {
      var promise = doc.getPage(1);
      waitsForPromiseResolved(promise, function(data) {
        expect(true).toEqual(true);
      });
    });
    it('gets page index', function() {
      // reference to second page
      var ref = {num: 17, gen: 0};
      var promise = doc.getPageIndex(ref);
      waitsForPromiseResolved(promise, function(pageIndex) {
        expect(pageIndex).toEqual(1);
      });
    });
    it('gets destinations', function() {
      var promise = doc.getDestinations();
      waitsForPromiseResolved(promise, function(data) {
        expect(data).toEqual({ chapter1: [{ gen: 0, num: 17 }, { name: 'XYZ' },
                                          0, 841.89, null] });
      });
    });
    it('gets attachments', function() {
      var promise = doc.getAttachments();
      waitsForPromiseResolved(promise, function (data) {
        expect(data).toEqual(null);
      });
    });
    it('gets javascript', function() {
      var promise = doc.getJavaScript();
      waitsForPromiseResolved(promise, function (data) {
        expect(data).toEqual([]);
      });
    });
    it('gets outline', function() {
      var promise = doc.getOutline();
      waitsForPromiseResolved(promise, function(outline) {
        // Two top level entries.
        expect(outline.length).toEqual(2);
        // Make sure some basic attributes are set.
        expect(outline[1].title).toEqual('Chapter 1');
        expect(outline[1].items.length).toEqual(1);
        expect(outline[1].items[0].title).toEqual('Paragraph 1.1');
      });
    });
    it('gets metadata', function() {
      var promise = doc.getMetadata();
      waitsForPromiseResolved(promise, function(metadata) {
        expect(metadata.info['Title']).toEqual('Basic API Test');
        expect(metadata.metadata.get('dc:title')).toEqual('Basic API Test');
      });
    });
    it('gets data', function() {
      var promise = doc.getData();
      waitsForPromiseResolved(promise, function (data) {
        expect(true).toEqual(true);
      });
    });
    it('gets filesize in bytes', function() {
      var promise = doc.getDownloadInfo();
      waitsForPromiseResolved(promise, function (data) {
        expect(data.length).toEqual(105779);
      });
    });
    it('gets stats', function() {
      var promise = doc.getStats();
      waitsForPromiseResolved(promise, function (stats) {
        expect(isArray(stats.streamTypes)).toEqual(true);
        expect(isArray(stats.fontTypes)).toEqual(true);
      });
    });
  });
  describe('Page', function() {
    var resolvePromise;
    var promise = new Promise(function (resolve) {
      resolvePromise = resolve;
    });
    PDFJS.getDocument(basicApiUrl).then(function(doc) {
      doc.getPage(1).then(function(data) {
        resolvePromise(data);
      });
    });
    var page;
    waitsForPromiseResolved(promise, function(data) {
      page = data;
    });
    it('gets page number', function () {
      expect(page.pageNumber).toEqual(1);
    });
    it('gets rotate', function () {
      expect(page.rotate).toEqual(0);
    });
    it('gets ref', function () {
      expect(page.ref).toEqual({ num: 15, gen: 0 });
    });
    it('gets view', function () {
      expect(page.view).toEqual([0, 0, 595.28, 841.89]);
    });
    it('gets viewport', function () {
      var viewport = page.getViewport(1.5, 90);
      expect(viewport.viewBox).toEqual(page.view);
      expect(viewport.scale).toEqual(1.5);
      expect(viewport.rotation).toEqual(90);
      expect(viewport.transform).toEqual([0, 1.5, 1.5, 0, 0, 0]);
      expect(viewport.width).toEqual(1262.835);
      expect(viewport.height).toEqual(892.92);
    });
    it('gets annotations', function () {
      var promise = page.getAnnotations();
      waitsForPromiseResolved(promise, function (data) {
        expect(data.length).toEqual(4);
      });
    });
    it('gets text content', function () {
      var promise = page.getTextContent();
      waitsForPromiseResolved(promise, function (data) {
        expect(!!data.items).toEqual(true);
        expect(data.items.length).toEqual(7);
        expect(!!data.styles).toEqual(true);
      });
    });
    it('gets operator list', function() {
      var promise = page.getOperatorList();
      waitsForPromiseResolved(promise, function (oplist) {
        expect(!!oplist.fnArray).toEqual(true);
        expect(!!oplist.argsArray).toEqual(true);
        expect(oplist.lastChunk).toEqual(true);
      });
    });
  });
});
<|endoftext|>


<commit_before>

function createtable(type, size1, size2) {
        var body = document.getElementById('body');
        var table = document.getElementById(type);
        table.setAttribute('border','1');
        var tbody = document.createElement('tbody');
        for (var i = 0; i <= size2+1; i++) {

            var row = document.createElement('tr');
            for (var j = 0; j <= size1+1; j++) {

                var cell = document.createElement('td');
                if ((i <= 1) || (j <= 1)) { cell.setAttribute("class","header") }
                cell.appendChild(document.createTextNode("0"));
                cell.id = type + parseInt(i) +"_" + parseInt(j);
                row.appendChild(cell);
            }

            tbody.appendChild(row);
        }

        table.replaceChild(tbody,table.childNodes[0]);
}

function setCell(row, col, table, text) {
    var cell = document.getElementById(table + parseInt(row) + "_" + parseInt(col));
    cell.replaceChild(document.createTextNode(text), cell.childNodes[0]);

}

function setSequences(sequence1, sequence2) {
    for (var i = 0; i <= sequence1.length-1; i++) {
        setCell(0,i+2,'score',sequence1[i]);
        setCell(0,i+2,'trace',sequence1[i]);
    }
    for (var i = 0; i <= sequence2.length-1; i++) {
        setCell(i+2,0,'score',sequence2[i]);

        setCell(i+2,0,'trace',sequence2[i]);
    }

}

function getCell(row,col, table) {
    return document.getElementById(table + parseInt(row) + "_" + parseInt(col)).innerHTML;
}

function calCell(row, col, method) {
    var fromTop = parseInt(getCell(row-1,col,'score')) + Gap;
    var fromLeft = parseInt(getCell(row,col-1,'score')) + Gap;
    if (getCell(0,col,'score') == getCell(row,0,'score')) {
        var fromTopLeft = parseInt(getCell(row-1,col-1,'score')) + Match;

    }
    else {
        var fromTopLeft = parseInt(getCell(row-1,col-1,'score')) + Mismatch;
    }

    if (method == 'water') {
        fromTop = Math.max(fromTop,0);
        fromLeft = Math.max(fromLeft,0);
        fromTopLeft = Math.max(fromTopLeft,0);
    }

    var THighest = false;
    var LHighest = false;
    var TLHiguest = false;
    if ((fromTop >= fromLeft) && (fromTop >= fromTopLeft)) {
        THighest = true;
        setCell(row,col,'score',fromTop)
    }
    if ((fromLeft >= fromTop) && (fromLeft >= fromTopLeft)) {
        LHighest = true;
        setCell(row,col,'score',fromLeft);
    }
    if ((fromTopLeft >= fromLeft) && (fromTopLeft >= fromTop)) {
        TLHighest = true;
        setCell(row,col,'score',fromTopLeft);
    }
    var trace = '';
    if (THighest) { trace = trace + String.fromCharCode(8593)}
    if (LHighest) { trace = trace + String.fromCharCode(8592)}
    if (TLHighest) { trace = trace + String.fromCharCode(8598)}
    setCell(row,col,'trace',trace);
}

function setGaps(Size1,Size2) {
    for (var i = 0; i <= Size1-1; i++) {
        var left = parseInt(getCell(1,i+1,'score'))
        setCell(1,i+2,'score', left + Gap);
        setCell(1,i+2,'trace',String.fromCharCode(8592));
    }
    for (var i = 0; i <= Size2-1; i++) {
        var top = parseInt(getCell(i+1,1,'score'))
        setCell(i+2,1,'score', top + Gap);
        setCell(i+2,1,'trace', String.fromCharCode(8593));
    }

}

function calCells(Size1,Size2, method) {
    for (var row = 2; row <= Size2+1; row++) {
        for (var col = 2; col <= Size1+1; col++) {
            calCell(row,col, method);

        }
    }
}

function initialize(method) {
    Gap = parseInt(document.getElementById("Gap").value);
    Match = parseInt(document.getElementById("Match").value);
    Mismatch = parseInt(document.getElementById("Mismatch").value);
    var Seq1 = document.getElementById("seq1").value;
    var Seq2 = document.getElementById("seq2").value;
    var Size1 = Seq1.length;
    var Size2 = Seq2.length;
    createtable('score', Size1, Size2);
    createtable('trace', Size1, Size2);

    setSequences(Seq1,Seq2);
    if (method == 'needle') { setGaps(Size1,Size2); }
    calCells(Size1,Size2, method);

}
<commit_msg>Adding titles to js<commit_after>

function createtable(type, size1, size2) {
        var body = document.getElementById('body');
        var table = document.getElementById(type);
        table.setAttribute('border','1');
        var tbody = document.createElement('tbody');
        for (var i = 0; i <= size2+1; i++) {

            var row = document.createElement('tr');
            for (var j = 0; j <= size1+1; j++) {

                var cell = document.createElement('td');
                if ((i <= 1) || (j <= 1)) { cell.setAttribute("class","header") }
                cell.appendChild(document.createTextNode("0"));
                cell.id = type + parseInt(i) +"_" + parseInt(j);
                row.appendChild(cell);
            }

            tbody.appendChild(row);
        }

        table.replaceChild(tbody,table.childNodes[0]);
}

function setCell(row, col, table, text) {
    var cell = document.getElementById(table + parseInt(row) + "_" + parseInt(col));
    cell.replaceChild(document.createTextNode(text), cell.childNodes[0]);

}

function setSequences(sequence1, sequence2) {
    for (var i = 0; i <= sequence1.length-1; i++) {
        setCell(0,i+2,'score',sequence1[i]);
        setCell(0,i+2,'trace',sequence1[i]);
    }
    for (var i = 0; i <= sequence2.length-1; i++) {
        setCell(i+2,0,'score',sequence2[i]);

        setCell(i+2,0,'trace',sequence2[i]);
    }

}

function getCell(row,col, table) {
    return document.getElementById(table + parseInt(row) + "_" + parseInt(col)).innerHTML;
}

function calCell(row, col, method) {
    var fromTop = parseInt(getCell(row-1,col,'score')) + Gap;
    var fromLeft = parseInt(getCell(row,col-1,'score')) + Gap;
    if (getCell(0,col,'score') == getCell(row,0,'score')) {
        var fromTopLeft = parseInt(getCell(row-1,col-1,'score')) + Match;

    }
    else {
        var fromTopLeft = parseInt(getCell(row-1,col-1,'score')) + Mismatch;
    }

    if (method == 'water') {
        fromTop = Math.max(fromTop,0);
        fromLeft = Math.max(fromLeft,0);
        fromTopLeft = Math.max(fromTopLeft,0);
    }

    var THighest = false;
    var LHighest = false;
    var TLHiguest = false;
    if ((fromTop >= fromLeft) && (fromTop >= fromTopLeft)) {
        THighest = true;
        setCell(row,col,'score',fromTop)
    }
    if ((fromLeft >= fromTop) && (fromLeft >= fromTopLeft)) {
        LHighest = true;
        setCell(row,col,'score',fromLeft);
    }
    if ((fromTopLeft >= fromLeft) && (fromTopLeft >= fromTop)) {
        TLHighest = true;
        setCell(row,col,'score',fromTopLeft);
    }
    var trace = '';
    if (THighest) { trace = trace + String.fromCharCode(8593)}
    if (LHighest) { trace = trace + String.fromCharCode(8592)}
    if (TLHighest) { trace = trace + String.fromCharCode(8598)}
    setCell(row,col,'trace',trace);
}

function setGaps(Size1,Size2) {
    for (var i = 0; i <= Size1-1; i++) {
        var left = parseInt(getCell(1,i+1,'score'))
        setCell(1,i+2,'score', left + Gap);
        setCell(1,i+2,'trace',String.fromCharCode(8592));
    }
    for (var i = 0; i <= Size2-1; i++) {
        var top = parseInt(getCell(i+1,1,'score'))
        setCell(i+2,1,'score', top + Gap);
        setCell(i+2,1,'trace', String.fromCharCode(8593));
    }

}

function calCells(Size1,Size2, method) {
    for (var row = 2; row <= Size2+1; row++) {
        for (var col = 2; col <= Size1+1; col++) {
            calCell(row,col, method);

        }
    }
}

function insertTitles() {
    document.getElementById("scoretitle").innerHTML = "Score Table";
    document.getElementById("tracetitle").innerHTML = "Traceback Table";
}

function initialize(method) {
    insertTitles();
    Gap = parseInt(document.getElementById("Gap").value);
    Match = parseInt(document.getElementById("Match").value);
    Mismatch = parseInt(document.getElementById("Mismatch").value);
    var Seq1 = document.getElementById("seq1").value;
    var Seq2 = document.getElementById("seq2").value;
    var Size1 = Seq1.length;
    var Size2 = Seq2.length;
    createtable('score', Size1, Size2);
    createtable('trace', Size1, Size2);

    setSequences(Seq1,Seq2);
    if (method == 'needle') { setGaps(Size1,Size2); }
    calCells(Size1,Size2, method);

}
<|endoftext|>