<commit_before>"use strict";

/**
 * Copyright 2017 XcooBee LLC

 * 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.
 */
const path = require("path");
const fs = require("fs");

let parametersFilePath = "parameters.json";
let outputPath = path.resolve("./");
let ttl = 30000;

// The amount of time reserved for clean up tasks
const timeToCleanUp = 5000;

// Track the number of open write streams
const streamArray = [];

const argv = process.argv;
let callbackCalled = false;

const closeStreams = () => {
    streamArray.forEach((value) => {
        value.close();
    });
};

let globalSequence = 1;
const getNextId = () => {
    const current = globalSequence;
    globalSequence += 1;
    return current;
};

const createServices = (inputFilePath) => {
    // TODO: Validation for fileName, what should happen if the user requests a writeStream for an
    // already created fileName
    // Create the services object
    const services = {
        // Just log a message to the system console
        log: (message, type) => {
            const chunk = `${Date.now()},${type},${message}\n`;
            console.log(chunk);
        },
        // email service to mock the sending of an email
        mail: () => {
            // TODO: What do in here? Log something? Do Nothing?
        },
        getNextId,
        addParam: (key, value) => {
            console.log(`${key} => ${value} added to the next bee`);
        },
        timeToRun: () => ttl,
        // The default streams for reading and writing
        readStream: fs.createReadStream(inputFilePath),
        writeStream: fs.createWriteStream(`${outputPath}${path.sep}output${path.sep}bee_default_output`),
        writeStreamManager: () => ({
            getWriteStream: (fileName, type) => {
                const typePath = type === "wip" ? "workFiles" : "output";
                const stream = fs.createWriteStream(`${outputPath}${path.sep}${typePath}${path.sep}${fileName}`);
                streamArray.push(stream);
                return stream;
            },
            getReadStream: (fileName, type) => {
                const typePath = type === "wip" ? "workFiles" : "output";
                const stream = fs.createReadStream(`${outputPath}${path.sep}${typePath}${path.sep}${fileName}`);
                return stream;
            },
        }),
    };

    return services;
};

// Assume we are on the node project directory
// unless otherwise specified by the --bee switch
let beeModule = null;
try {
    const beeIndex = argv.indexOf("--bee");
    if (beeIndex !== -1) {
        beeModule = require(path.resolve(argv[beeIndex + 1]));
    } else {
        // TODO: Don't rely on cwd
        beeModule = require(process.cwd());
    }
} catch (err) {
    console.log("It was not possible to load the bee, make sure you are inside a valid node project or use the '--bee' switch");
    process.exit(1);
}

// Set the size instance in which this bee will be run
// We use the size to, among other things, choose the proper ttl
const sizeIndex = argv.indexOf("--size");
if (sizeIndex !== -1) {
    const validSizes = ["s", "m", "l"];
    const size = argv[sizeIndex + 1].toLowerCase();

    if (validSizes.indexOf(size) === -1) {
        console.log(`'${size}' is not a valid size, must be one of [s, m, l]`);
        process.exit(1);
    }

    if (size === "s") {
        ttl = 30000;
    } else if (size === "m") {
        ttl = 150000;
    } else {
        ttl = 300000;
    }
}

// Substract the timeToCleanUp from ttl to get the net time the bee got available
ttl -= timeToCleanUp;

// If no params file are provided we assume the bee won't require integrations
// nor parameters, unless the '--params' flag is used in which case it is, probably,
// an user error pointing to an unexistent file
const paramsIndex = argv.indexOf("--params");
if (paramsIndex !== -1) {
    parametersFilePath = path.resolve(argv[paramsIndex + 1]);

    if (!fs.existsSync(parametersFilePath)) {
        console.log(`${parametersFilePath} doesn't exist`);
        process.exit(1);
    }
}

// If the user specifies the output as a directory, use a default file name 'output' with no extension
// The output directory must exists, the utility WON'T create it
const outputIndex = argv.indexOf("--out");
if (outputIndex !== -1) {
    outputPath = path.resolve(argv[outputIndex + 1]);

    // TODO: A way to create the hierarchy
    if (!fs.existsSync(outputPath)) {
        console.log(`${outputPath} is not a valid directory`);
        process.exit(1);
    }

    const stats = fs.lstatSync(outputPath);

    if (!stats.isDirectory()) {
        console.log(`${outputPath} is not a valid directory`);
        process.exit(1);
    }
}

if (!fs.existsSync(`${outputPath}${path.sep}output`)) {
    fs.mkdirSync(`${outputPath}${path.sep}output`);
}

if (!fs.existsSync(`${outputPath}${path.sep}workFiles`)) {
    fs.mkdirSync(`${outputPath}${path.sep}workFiles`);
}

// The input file must be the first argument
const inputFilePath = path.resolve(argv[2]);

if (!fs.existsSync(inputFilePath)) {
    console.log(`Input file '${inputFilePath}' doesn't exist`);
    process.exit(1);
}

const services = createServices(inputFilePath);

const data = {
    // Mock data just for testing purposes
    user_data: {
        first_name: "John",
        last_name: "Testerson",
        xcoobee_id: "~johnt",
    },
};

let parametersContent = null;

if (fs.existsSync(parametersFilePath)) {
    try {
        parametersContent = JSON.parse(fs.readFileSync(parametersFilePath, "utf8"));
        data.integrations = parametersContent.integrations;
        data.parameters = parametersContent.bee_params;
    } catch (err) {
        console.log(`${parametersFilePath} is not a valid JSON file`);
        process.exit(1);
    }
}

const beeCallback = (err, result) => {
    callbackCalled = true;
    clearInterval();
    closeStreams();
    if (err) {
        console.log(err);
        process.exit(1);
    }

    console.log(result);
    process.exit(0);
};

setTimeout(() => {
    if (!callbackCalled) {
        console.log("Timed-out");
        clearInterval();
        closeStreams();
        process.exit(2);
    }
}, ttl);

setInterval(() => {
    ttl -= 100;
}, 100);

beeModule.flight(services, data, beeCallback);
<commit_msg>Refactors test-utility<commit_after>"use strict";

/**
 * Copyright 2017 XcooBee LLC

 * 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.
 */
const runTest = (argv, callback) => {
    const path = require("path");
    const fs = require("fs");

    let parametersFilePath = path.resolve("./parameters.json");
    let outputPath = path.resolve("./");
    let ttl = 30000;
    // How long have we been running?
    let ellapsed = 0;

    // The amount of time reserved for clean up tasks
    const timeToCleanUp = 5000;

    // Track the number of open write streams
    const streamArray = [];

    let callbackCalled = false;

    const closeStreams = () => {
        streamArray.forEach((value) => {
            value.close();
        });
    };

    let globalSequence = 1;
    const getNextId = () => {
        const current = globalSequence;
        globalSequence += 1;
        return current;
    };

    const createServices = (inputFilePath) => {
        // TODO: Validation for fileName, what should happen if the user requests a writeStream for an
        // already created fileName
        // Create the services object
        const services = {
            // Just log a message to the system console
            log: (message, type) => {
                const chunk = `${Date.now()},${type},${message}\n`;
                console.log(chunk);
            },
            // email service to mock the sending of an email
            mail: () => {
                // TODO: What do in here? Log something? Do Nothing?
            },
            getNextId,
            addParam: (key, value) => {
                console.log(`${key} => ${value} added to the next bee`);
            },
            timeToRun: () => ttl - ellapsed,
            // The default streams for reading and writing
            readStream: fs.createReadStream(inputFilePath),
            // TODO: Should overwrite the files
            writeStream: fs.createWriteStream(`${outputPath}${path.sep}output${path.sep}bee_default_output`),
            writeStreamManager: () => ({
                getWriteStream: (fileName, type) => {
                    const typePath = type === "wip" ? "workFiles" : "output";
                    const stream = fs.createWriteStream(`${outputPath}${path.sep}${typePath}${path.sep}${fileName}`);
                    streamArray.push(stream);
                    return stream;
                },
                getReadStream: (fileName, type) => {
                    const typePath = type === "wip" ? "workFiles" : "output";
                    const stream = fs.createReadStream(`${outputPath}${path.sep}${typePath}${path.sep}${fileName}`);
                    return stream;
                },
            }),
        };

        return services;
    };

    // Assume we are on the node project directory
    // unless otherwise specified by the --bee switch
    let beeModule = null;
    try {
        const beeIndex = argv.indexOf("--bee");
        if (beeIndex !== -1) {
            const pathToBee = path.resolve(argv[beeIndex + 1]);
            beeModule = require(pathToBee);
        } else {
            // TODO: Don't rely on cwd
            beeModule = require(process.cwd());
        }
    } catch (err) {
        callback(new Error("It was not possible to load the bee, make sure you are inside a valid node project or use the '--bee' switch"));
    }

    // Set the size instance in which this bee will be run
    // We use the size to, among other things, choose the proper ttl
    const sizeIndex = argv.indexOf("--size");
    if (sizeIndex !== -1) {
        const validSizes = ["s", "m", "l"];
        const size = argv[sizeIndex + 1].toLowerCase();

        if (validSizes.indexOf(size) === -1) {
            callback(new Error(`'${size}' is not a valid size, must be one of [s, m, l]`));
        }

        if (size === "s") {
            ttl = 30000;
        } else if (size === "m") {
            ttl = 150000;
        } else {
            ttl = 300000;
        }
    }

    // Substract the timeToCleanUp from ttl to get the net time the bee got available
    ttl -= timeToCleanUp;

    // If no params file are provided we assume the bee won't require integrations
    // nor parameters, unless the '--params' flag is used in which case it is, probably,
    // an user error pointing to an unexistent file
    const paramsIndex = argv.indexOf("--params");
    if (paramsIndex !== -1) {
        parametersFilePath = path.resolve(argv[paramsIndex + 1]);

        if (!fs.existsSync(parametersFilePath)) {
            callback(Error(`${parametersFilePath} doesn't exist`));
        }
    }

    // If the user specifies the output as a directory, use a default file name 'output' with no extension
    // The output directory must exists, the utility WON'T create it
    const outputIndex = argv.indexOf("--out");
    if (outputIndex !== -1) {
        outputPath = path.resolve(argv[outputIndex + 1]);

        // TODO: A way to create the hierarchy
        if (!fs.existsSync(outputPath)) {
            callback(new Error(`${outputPath} is not a valid directory`));
        }

        const stats = fs.lstatSync(outputPath);

        if (!stats.isDirectory()) {
            callback(new Error(`${outputPath} is not a valid directory`));
        }
    }

    if (!fs.existsSync(`${outputPath}${path.sep}output`)) {
        fs.mkdirSync(`${outputPath}${path.sep}output`);
    }

    if (!fs.existsSync(`${outputPath}${path.sep}workFiles`)) {
        fs.mkdirSync(`${outputPath}${path.sep}workFiles`);
    }

    // The input file must be the first argument
    const inputFilePath = path.resolve(argv[2]);

    if (!fs.existsSync(inputFilePath)) {
        callback(new Error(`Input file '${inputFilePath}' doesn't exist`));
    }

    const services = createServices(inputFilePath);

    const data = {
        // Mock data just for testing purposes
        user_data: {
            first_name: "John",
            last_name: "Testerson",
            xcoobee_id: "~johnt",
        },
    };

    let parametersContent = null;

    if (fs.existsSync(parametersFilePath)) {
        try {
            parametersContent = JSON.parse(fs.readFileSync(parametersFilePath, "utf8"));
            data.integrations = parametersContent.integrations;
            data.parameters = parametersContent.bee_params;
        } catch (err) {
            callback(new Error(`${parametersFilePath} is not a valid JSON file`));
        }
    }

    const beeCallback = (err, result) => {
        callbackCalled = true;
        clearInterval();
        console.log(`Total exec time: ${ellapsed} millis`);
        closeStreams();
        if (err) {
            return callback(err);
        }

        return callback(null, result);
    };

    setTimeout(() => {
        if (!callbackCalled) {
            clearInterval();
            closeStreams();
            callback(new Error("Timed-out"));
        }
    }, ttl);

    setInterval(() => {
        ellapsed += 2;
    }, 2);

    beeModule.flight(services, data, beeCallback);
};

if (require.main === module) {
    const callback = (err, result) => {
        if (err) {
            console.log(err.message);
            return process.exit(1);
        }
        console.log(result);
        return process.exit(0);
    };
    runTest(process.argv, callback);
}

module.exports.runTest = (argv, callback) => {
    runTest(argv, callback);
};
<|endoftext|>


<commit_before>'use strict';

const common = module.exports = {};

common.getBasename = function (filename) {
    let base = filename.replace(/.*\//, '');
    return base.replace(/\.[0-9]+$/, '');
};

common.getExtension = function (filename) {
    let extension = common.getBasename(filename);
    return extension.replace(/.*\./, '').toLowerCase();
};

common.getFilename = function (typeEntry) {
    let keys = Object.keys(typeEntry);
    for (let i = 0; i < keys.length; i++) {
        if (typeEntry[keys[i]] && typeEntry[keys[i]].filename) {
            return typeEntry[keys[i]].filename;
        }
    }
};

common.basenameFind = function (typeEntries, filename) {
    let reference = common.getBasename(filename);

    return typeEntries.find(typeEntry => {
        return common.getBasename(common.getFilename(typeEntry)) === reference;
    });
};

common.getTargetProperty = function (filename) {
    switch (common.getExtension(filename)) {
        case 'jdx':
        case 'dx':
        case 'jcamp':
            return 'jcamp';
        case 'png':
        case 'jpg':
        case 'jpeg':
        case 'tif':
        case 'tiff':
            return 'image';
        case 'cif':
            return 'cif';
        case 'pdb':
            return 'pdb';
        case 'xml':
            return 'xml';
        case 'cdf':
        case 'nc':
        case 'netcdf':
            return 'cdf';
        case 'pdf':
            return 'pdf';
        default :
            return 'file'
    }
};
<commit_msg>add extension txt, text, csv, tsv for upload<commit_after>'use strict';

const common = module.exports = {};

common.getBasename = function (filename) {
    let base = filename.replace(/.*\//, '');
    return base.replace(/\.[0-9]+$/, '');
};

common.getExtension = function (filename) {
    let extension = common.getBasename(filename);
    return extension.replace(/.*\./, '').toLowerCase();
};

common.getFilename = function (typeEntry) {
    let keys = Object.keys(typeEntry);
    for (let i = 0; i < keys.length; i++) {
        if (typeEntry[keys[i]] && typeEntry[keys[i]].filename) {
            return typeEntry[keys[i]].filename;
        }
    }
};

common.basenameFind = function (typeEntries, filename) {
    let reference = common.getBasename(filename);

    return typeEntries.find(typeEntry => {
        return common.getBasename(common.getFilename(typeEntry)) === reference;
    });
};

common.getTargetProperty = function (filename) {
    switch (common.getExtension(filename)) {
        case 'jdx':
        case 'dx':
        case 'jcamp':
            return 'jcamp';
        case 'png':
        case 'jpg':
        case 'jpeg':
        case 'tif':
        case 'tiff':
            return 'image';
        case 'cif':
            return 'cif';
        case 'pdb':
            return 'pdb';
        case 'xml':
            return 'xml';
        case 'cdf':
        case 'nc':
        case 'netcdf':
            return 'cdf';
        case 'pdf':
            return 'pdf';
        case 'txt':
        case 'text':
        case 'csv':
        case 'tsv':
            return 'text';
        default :
            return 'file'
    }
};
<|endoftext|>


<commit_before>module.exports = function (grunt) {

	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),

		clean: {
			bootstrap: ['ui/app/static/css/bootstrap.css']
		},

		sass: {
			dev: {
				options: {
					compass: true,
					style: 'expanded'
				},
				files: {
					'ui/app/static/css/bootstrap.css': 'scss/bootstrap.scss'
				}
			},

			dist: {
				options: {
					compass: true,
					style: 'compressed'
				},
				files: {
					'ui/app/static/css/bootstrap.css': 'scss/bootstrap.scss'
				}
			}
		}
	});

	grunt.registerTask('dev', ['sass:dev']);

	grunt.loadNpmTasks('grunt-contrib-clean');
	grunt.loadNpmTasks('grunt-contrib-sass');
	grunt.loadNpmTasks('grunt-contrib-watch');

};<commit_msg>add distribution task to grunt<commit_after>module.exports = function (grunt) {

	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),

		clean: {
			bootstrap: ['ui/app/static/css/bootstrap.css']
		},

		sass: {
			dev: {
				options: {
					compass: true,
					style: 'expanded'
				},
				files: {
					'ui/app/static/css/bootstrap.css': 'scss/bootstrap.scss'
				}
			},

			dist: {
				options: {
					compass: true,
					style: 'compressed'
				},
				files: {
					'ui/app/static/css/bootstrap.css': 'scss/bootstrap.scss'
				}
			}
		}
	});

	// Distribution
	grunt.registerTask('dist', ['sass:dist']);

	// Development
	grunt.registerTask('dev', ['sass:dev']);

	// Load NPM Tasks
	grunt.loadNpmTasks('grunt-contrib-clean');
	grunt.loadNpmTasks('grunt-contrib-sass');
	grunt.loadNpmTasks('grunt-contrib-watch');

};<|endoftext|>


<commit_before>"use strict";
var Settings = {
  _buffer: {},
  bufferToLoad: null,
  frameIdsForTab: null,
  urlForTab: null,
  extIds: [chrome.runtime.id],
  get: function(key) {
    if (! (key in this._buffer)) {
      return this._buffer[key] = !(key in localStorage) ? this.defaults[key]
        : (key in this.NonJSON) ? localStorage[key]
        : JSON.parse(localStorage[key]);
    }
    return this._buffer[key];
  },
  set: function(key, value) {
    var ref;
    this._buffer[key] = value;
    if (key in this.nonPersistent) {
    } else if (value === this.defaults[key]) {
      delete localStorage[key];
      this.Sync.clear(key);
    } else {
      this.Sync.set(key, localStorage[key] = (key in this.NonJSON)
        ? value : JSON.stringify(value));
    }
    if (ref = this.updateHooks[key]) {
      ref.call(this, value, key);
    }
  },
  postUpdate: function(key, value) {
    this.updateHooks[key].call(this, value !== undefined ? value : this.get(key), key);
  },
  updateHooks: {
    broadcast: function (request) {
      chrome.tabs.query({status: "complete"}, function(tabs) {
        for (var i = tabs.length, t = chrome.tabs, req = request; 0 <= --i; ) {
          t.sendMessage(tabs[i].id, req, null);
        }
      });
      var r = chrome.runtime, arr = Settings.extIds, i, req;
      req = {"vimium++": {request: request}};
      for (i = arr.length; 1 <= --i; ) {
        r.sendMessage(arr[i], req, null);
      }
    },
    bufferToLoad: function() {
      var _i, key, ref = this.valuesToLoad, ref2 = this.bufferToLoad = {};
      ref2.__proto__ = null;
      for (_i = ref.length; 0 <= --_i;) {
        key = ref[_i];
        ref2[key] = this.get(key);
      }
    },
    searchEngines: function() {
      this.set("searchEnginesMap", { "": [] });
    },
    searchUrl: function(value) {
      this.parseSearchEngines("~:" + value);
    },
    searchEnginesMap: function(value) {
      this.parseSearchEngines(this.get("searchEngines"), value);
      this.parseSearchEngines("~:" + this.get("searchUrl"), value);
      this.postUpdate("postSearchEnginesMap", null);
    },
    userDefinedCss: function(css) {
      if (css && (css = css.replace(/\r/g, ""))) {
        if (css.indexOf("\n") >= 0) {
          css = (css.startsWith('\n') ? "" : '\n') + css + (css.endsWith('\n') ? "" : '\n');
        }
      } else {
        css = "";
      }
      this.set("userDefinedCss_f", css);
    }
  },
  parseSearchEngines: function(searchEnginesText, map) {
    var a, pairs, key, val, name, obj, _i, _j, _len, _len2, key0, //
    rEscapeSpace = /\\\s/g, rSpace = /\s/, rEscapeS = /\\s/g, rColon = /\\:/g;
    map = map || this.get("searchEnginesMap");
    a = searchEnginesText.replace(/\\\n/g, '').split('\n');
    for (_i = 0, _len = a.length; _i < _len; _i++) {
      val = a[_i].trim();
      if (!(val.charCodeAt(0) > 35)) { continue; } // mask: /[ !"#]/
      _j = 0;
      do {
        _j = val.indexOf(":", _j + 1);
      } while (val[_j - 1] === '\\');
      if (_j <= 0 || !(key = val.substring(0, _j).trimRight())) continue;
      val = val.substring(_j + 1).trimLeft();
      if (!val) continue;
      val = val.replace(rEscapeSpace, "\\s");
      _j = val.search(rSpace);
      if (_j > 0) {
        name = val.substring(_j + 1).trimLeft();
        key0 = "";
        val = val.substring(0, _j);
      } else {
        name = null;
      }
      val = val.replace(rEscapeS, " ");
      obj = {url: val};
      key = key.replace(rColon, ":");
      pairs = key.split('|');
      for (_j = 0, _len2 = pairs.length; _j < _len2; _j++) {
        if (key = pairs[_j].trim()) {
          if (name) {
            if (!key0) { key0 = key; }
          } else {
            key0 = name = key;
          }
          map[key] = obj;
        }
      }
      if (!name) continue;
      obj.name = name;
      obj.$s = val.indexOf("%s") + 1;
      obj.$S = val.indexOf("%S") + 1;
      if (pairs = this.reparseSearchUrl(obj, key0)) {
        map[""].push(pairs);
      }
    }
  },
  reparseSearchUrl: function (pattern, name) {
    var url, ind = pattern.$s || pattern.$S, prefix;
    if (!ind || !Utils.hasOrdinaryUrlPrefix(url = pattern.url)) { return; }
    url = url.substring(0, ind - 1);
    if (ind = (url.indexOf("?") + 1) || (url.indexOf("#") + 1)) {
      prefix = url.substring(0, ind - 1);
      url = url.substring(ind);
      if (ind = url.lastIndexOf("&") + 1) {
        url = url.substring(ind);
      }
      if (url && url !== "=" && !url.endsWith("/")) {
        url = url.toLowerCase().replace(RegexpCache._escapeRegex, "\\$&");
        if (prefix.startsWith("https://")) {
          prefix = "http" + prefix.substring(5);
        }
        return [prefix, new RegExp("[?#&]" + url + "([^&#]*)", "i"), name];
      }
      url = pattern.url.substring(0, (pattern.$s || pattern.$S) - 1);
    }
    prefix = url;
    url = pattern.url.substring(url.length + 2);
    if (ind = (url.indexOf("?") + 1) || (url.indexOf("#") + 1)) {
      url = url.substring(0, ind);
    }
    url = url.toLowerCase().replace(RegexpCache._escapeRegex, "\\$&");
    if (prefix.startsWith("https://")) {
      prefix = "http" + prefix.substring(5);
    }
    return [prefix, new RegExp("^([^?#]*)" + url, "i"), name];
  },
  reloadFiles: function() {
    var files = this.files, id;
    for (id in files) {
      this.set(id, "");
      Utils.fetchHttpContents(files[id], this.set.bind(this, id));
    }
  },
  // clear localStorage & sync, if value === @defaults[key]
  defaults: {
    UILanguage: null,
    exclusionRules: [{pattern: "http*://mail.google.com/*", passKeys: ""}],
    filterLinkHints: false,
    findModeRawQuery: "",
    hideHud: false,
    keyMappings: "",
    linkHintCharacters: "asdqwerzxcv",
    linkHintNumbers: "1234567890",
    newTabUrl: "",
    nextPatterns: "next,more,>,\u2192,\xbb,\u226b,>>",
    previousPatterns: "prev,previous,back,<,\u2190,\xab,\u226a,<<",
    regexFindMode: false,
    scrollStepSize: 100,
    searchUrl: "http://www.baidu.com/s?ie=utf-8&wd=%s Baidu",
    searchEngines: "b|ba|baidu|Baidu: www.baidu.com/s?ie=utf-8&wd=%s \u767e\u5ea6"
      + "\nbi|bing|Bing: https://www.bing.com/search?q=%s Bing"
      + "\ng|go|gg|google|Google: http://www.google.com/search?q=%s Google"
      + "\njs\\:: javascript:\\ %S; Javascript"
      + "\nw|wiki:\\\n  http://www.wikipedia.org/w/index.php?search=%s Wikipedia (en-US)"
      ,
    showActionIcon: true,
    showAdvancedCommands: 0,
    showAdvancedOptions: 1,
    showOmniRelevancy: false,
    smoothScroll: true,
    userDefinedCss: "",
    vimSync: false
  },
  NonJSON: {
    findModeRawQuery: true,
    keyMappings: true, linkHintCharacters: true, linkHintNumbers: true,
    newTabUrl: true, nextPatterns: true, previousPatterns: true,
    searchEngines: true, searchUrl: true, userDefinedCss: true
  },
  // not set localStorage, neither sync, if key in @nonPersistent
  // not clean if exists (for simpler logic)
  nonPersistent: {
    help_dialog: true,
    newTabUrl_f: true,
    searchEnginesMap: true,
    settingsVersion: true,
    userDefinedCss_f: true,
    vomnibar: true
  },
  files: {
    help_dialog: "pages/help_dialog.html",
    vomnibar: "pages/vomnibar.html"
  },
  icons: {
    disabled: {
      "19": "icons/disabled_19.png",
      "38": "icons/disabled_38.png"
    },
    enabled: {
      "19": "icons/enabled_19.png",
      "38": "icons/enabled_38.png"
    },
    partial: {
      "19": "icons/partial_19.png",
      "38": "icons/partial_38.png"
    }
  },
  valuesToLoad: ["filterLinkHints", "findModeRawQuery", "findModeRawQueryList" //
    , "hideHud", "linkHintCharacters", "linkHintNumbers", "nextPatterns" //
    , "previousPatterns", "regexFindMode", "scrollStepSize", "smoothScroll" //
  ],
  Sync: null,
  CONST: {
    ChromeInnerNewTab: "chrome-search://local-ntp/local-ntp.html", // should keep lower case
    ChromeVersion: 37,
    ContentScripts: null,
    CurrentVersion: "",
    OnMac: false,
    OptionsPage: "",
    Timer: 0
  }
};
Settings.__proto__ = null;
Settings._buffer.__proto__ = null;
Settings.updateHooks.__proto__ = null;
Settings.defaults.__proto__ = null;
Settings.NonJSON.__proto__ = null;
Settings.nonPersistent.__proto__ = null;
Settings.icons.__proto__ = null;
Settings.CONST.__proto__ = null;

// note: if changed, ../pages/newtab.js also needs change.
Settings.defaults.newTabUrl = Settings.CONST.ChromeInnerNewTab;

(function() {
  var ref, ref2, ref3, i, func;
  func = (function(path) { return this(path); }).bind(chrome.runtime.getURL);
  ref = chrome.runtime.getManifest();
  Settings.CONST.CurrentVersion = ref.version;
  Settings.CONST.OptionsPage = func(ref.options_page);
  ref = ref.content_scripts;
  ref3 = { all_frames: false, css: [], js: [] };
  ref3.__proto__ = null;
  for (i = 0; i < ref.length; i++) {
    ref2 = ref[i];
    if (ref2.matches.indexOf("<all_urls>") === -1) { continue; }
    ref3.all_frames || (ref3.all_frames = ref2.all_frames);
    ref3.css = ref3.css.concat(ref2.css.map(func));
    ref3.js = ref3.js.concat(ref2.js.map(func));
  }
  ref3.js.push(func("content/inject-end.js"));
  Settings.CONST.ContentScripts = ref3;

  i = navigator.appVersion.indexOf("Chrome");
  Settings.ChromeVersion = parseFloat(navigator.appVersion.substring(i + 7));

  func = function() {};
  Settings.Sync = {clear: func, set: func};
  Settings.Sync.__proto__ = null;
})();

chrome.runtime.getPlatformInfo(function(info) {
  Settings.CONST.OnMac = info.os === "mac";
});
<commit_msg>fix a bug that ChromeVersion should be in Settings.CONST<commit_after>"use strict";
var Settings = {
  _buffer: {},
  bufferToLoad: null,
  frameIdsForTab: null,
  urlForTab: null,
  extIds: [chrome.runtime.id],
  get: function(key) {
    if (! (key in this._buffer)) {
      return this._buffer[key] = !(key in localStorage) ? this.defaults[key]
        : (key in this.NonJSON) ? localStorage[key]
        : JSON.parse(localStorage[key]);
    }
    return this._buffer[key];
  },
  set: function(key, value) {
    var ref;
    this._buffer[key] = value;
    if (key in this.nonPersistent) {
    } else if (value === this.defaults[key]) {
      delete localStorage[key];
      this.Sync.clear(key);
    } else {
      this.Sync.set(key, localStorage[key] = (key in this.NonJSON)
        ? value : JSON.stringify(value));
    }
    if (ref = this.updateHooks[key]) {
      ref.call(this, value, key);
    }
  },
  postUpdate: function(key, value) {
    this.updateHooks[key].call(this, value !== undefined ? value : this.get(key), key);
  },
  updateHooks: {
    broadcast: function (request) {
      chrome.tabs.query({status: "complete"}, function(tabs) {
        for (var i = tabs.length, t = chrome.tabs, req = request; 0 <= --i; ) {
          t.sendMessage(tabs[i].id, req, null);
        }
      });
      var r = chrome.runtime, arr = Settings.extIds, i, req;
      req = {"vimium++": {request: request}};
      for (i = arr.length; 1 <= --i; ) {
        r.sendMessage(arr[i], req, null);
      }
    },
    bufferToLoad: function() {
      var _i, key, ref = this.valuesToLoad, ref2 = this.bufferToLoad = {};
      ref2.__proto__ = null;
      for (_i = ref.length; 0 <= --_i;) {
        key = ref[_i];
        ref2[key] = this.get(key);
      }
    },
    searchEngines: function() {
      this.set("searchEnginesMap", { "": [] });
    },
    searchUrl: function(value) {
      this.parseSearchEngines("~:" + value);
    },
    searchEnginesMap: function(value) {
      this.parseSearchEngines(this.get("searchEngines"), value);
      this.parseSearchEngines("~:" + this.get("searchUrl"), value);
      this.postUpdate("postSearchEnginesMap", null);
    },
    userDefinedCss: function(css) {
      if (css && (css = css.replace(/\r/g, ""))) {
        if (css.indexOf("\n") >= 0) {
          css = (css.startsWith('\n') ? "" : '\n') + css + (css.endsWith('\n') ? "" : '\n');
        }
      } else {
        css = "";
      }
      this.set("userDefinedCss_f", css);
    }
  },
  parseSearchEngines: function(searchEnginesText, map) {
    var a, pairs, key, val, name, obj, _i, _j, _len, _len2, key0, //
    rEscapeSpace = /\\\s/g, rSpace = /\s/, rEscapeS = /\\s/g, rColon = /\\:/g;
    map = map || this.get("searchEnginesMap");
    a = searchEnginesText.replace(/\\\n/g, '').split('\n');
    for (_i = 0, _len = a.length; _i < _len; _i++) {
      val = a[_i].trim();
      if (!(val.charCodeAt(0) > 35)) { continue; } // mask: /[ !"#]/
      _j = 0;
      do {
        _j = val.indexOf(":", _j + 1);
      } while (val[_j - 1] === '\\');
      if (_j <= 0 || !(key = val.substring(0, _j).trimRight())) continue;
      val = val.substring(_j + 1).trimLeft();
      if (!val) continue;
      val = val.replace(rEscapeSpace, "\\s");
      _j = val.search(rSpace);
      if (_j > 0) {
        name = val.substring(_j + 1).trimLeft();
        key0 = "";
        val = val.substring(0, _j);
      } else {
        name = null;
      }
      val = val.replace(rEscapeS, " ");
      obj = {url: val};
      key = key.replace(rColon, ":");
      pairs = key.split('|');
      for (_j = 0, _len2 = pairs.length; _j < _len2; _j++) {
        if (key = pairs[_j].trim()) {
          if (name) {
            if (!key0) { key0 = key; }
          } else {
            key0 = name = key;
          }
          map[key] = obj;
        }
      }
      if (!name) continue;
      obj.name = name;
      obj.$s = val.indexOf("%s") + 1;
      obj.$S = val.indexOf("%S") + 1;
      if (pairs = this.reparseSearchUrl(obj, key0)) {
        map[""].push(pairs);
      }
    }
  },
  reparseSearchUrl: function (pattern, name) {
    var url, ind = pattern.$s || pattern.$S, prefix;
    if (!ind || !Utils.hasOrdinaryUrlPrefix(url = pattern.url)) { return; }
    url = url.substring(0, ind - 1);
    if (ind = (url.indexOf("?") + 1) || (url.indexOf("#") + 1)) {
      prefix = url.substring(0, ind - 1);
      url = url.substring(ind);
      if (ind = url.lastIndexOf("&") + 1) {
        url = url.substring(ind);
      }
      if (url && url !== "=" && !url.endsWith("/")) {
        url = url.toLowerCase().replace(RegexpCache._escapeRegex, "\\$&");
        if (prefix.startsWith("https://")) {
          prefix = "http" + prefix.substring(5);
        }
        return [prefix, new RegExp("[?#&]" + url + "([^&#]*)", "i"), name];
      }
      url = pattern.url.substring(0, (pattern.$s || pattern.$S) - 1);
    }
    prefix = url;
    url = pattern.url.substring(url.length + 2);
    if (ind = (url.indexOf("?") + 1) || (url.indexOf("#") + 1)) {
      url = url.substring(0, ind);
    }
    url = url.toLowerCase().replace(RegexpCache._escapeRegex, "\\$&");
    if (prefix.startsWith("https://")) {
      prefix = "http" + prefix.substring(5);
    }
    return [prefix, new RegExp("^([^?#]*)" + url, "i"), name];
  },
  reloadFiles: function() {
    var files = this.files, id;
    for (id in files) {
      this.set(id, "");
      Utils.fetchHttpContents(files[id], this.set.bind(this, id));
    }
  },
  // clear localStorage & sync, if value === @defaults[key]
  defaults: {
    UILanguage: null,
    exclusionRules: [{pattern: "http*://mail.google.com/*", passKeys: ""}],
    filterLinkHints: false,
    findModeRawQuery: "",
    hideHud: false,
    keyMappings: "",
    linkHintCharacters: "asdqwerzxcv",
    linkHintNumbers: "1234567890",
    newTabUrl: "",
    nextPatterns: "next,more,>,\u2192,\xbb,\u226b,>>",
    previousPatterns: "prev,previous,back,<,\u2190,\xab,\u226a,<<",
    regexFindMode: false,
    scrollStepSize: 100,
    searchUrl: "http://www.baidu.com/s?ie=utf-8&wd=%s Baidu",
    searchEngines: "b|ba|baidu|Baidu: www.baidu.com/s?ie=utf-8&wd=%s \u767e\u5ea6"
      + "\nbi|bing|Bing: https://www.bing.com/search?q=%s Bing"
      + "\ng|go|gg|google|Google: http://www.google.com/search?q=%s Google"
      + "\njs\\:: javascript:\\ %S; Javascript"
      + "\nw|wiki:\\\n  http://www.wikipedia.org/w/index.php?search=%s Wikipedia (en-US)"
      ,
    showActionIcon: true,
    showAdvancedCommands: 0,
    showAdvancedOptions: 1,
    showOmniRelevancy: false,
    smoothScroll: true,
    userDefinedCss: "",
    vimSync: false
  },
  NonJSON: {
    findModeRawQuery: true,
    keyMappings: true, linkHintCharacters: true, linkHintNumbers: true,
    newTabUrl: true, nextPatterns: true, previousPatterns: true,
    searchEngines: true, searchUrl: true, userDefinedCss: true
  },
  // not set localStorage, neither sync, if key in @nonPersistent
  // not clean if exists (for simpler logic)
  nonPersistent: {
    help_dialog: true,
    newTabUrl_f: true,
    searchEnginesMap: true,
    settingsVersion: true,
    userDefinedCss_f: true,
    vomnibar: true
  },
  files: {
    help_dialog: "pages/help_dialog.html",
    vomnibar: "pages/vomnibar.html"
  },
  icons: {
    disabled: {
      "19": "icons/disabled_19.png",
      "38": "icons/disabled_38.png"
    },
    enabled: {
      "19": "icons/enabled_19.png",
      "38": "icons/enabled_38.png"
    },
    partial: {
      "19": "icons/partial_19.png",
      "38": "icons/partial_38.png"
    }
  },
  valuesToLoad: ["filterLinkHints", "findModeRawQuery", "findModeRawQueryList" //
    , "hideHud", "linkHintCharacters", "linkHintNumbers", "nextPatterns" //
    , "previousPatterns", "regexFindMode", "scrollStepSize", "smoothScroll" //
  ],
  Sync: null,
  CONST: {
    ChromeInnerNewTab: "chrome-search://local-ntp/local-ntp.html", // should keep lower case
    ChromeVersion: 37,
    ContentScripts: null,
    CurrentVersion: "",
    OnMac: false,
    OptionsPage: "",
    Timer: 0
  }
};
Settings.__proto__ = null;
Settings._buffer.__proto__ = null;
Settings.updateHooks.__proto__ = null;
Settings.defaults.__proto__ = null;
Settings.NonJSON.__proto__ = null;
Settings.nonPersistent.__proto__ = null;
Settings.icons.__proto__ = null;
Settings.CONST.__proto__ = null;

// note: if changed, ../pages/newtab.js also needs change.
Settings.defaults.newTabUrl = Settings.CONST.ChromeInnerNewTab;

(function() {
  var ref, ref2, ref3, i, func;
  func = (function(path) { return this(path); }).bind(chrome.runtime.getURL);
  ref = chrome.runtime.getManifest();
  Settings.CONST.CurrentVersion = ref.version;
  Settings.CONST.OptionsPage = func(ref.options_page);
  ref = ref.content_scripts;
  ref3 = { all_frames: false, css: [], js: [] };
  ref3.__proto__ = null;
  for (i = 0; i < ref.length; i++) {
    ref2 = ref[i];
    if (ref2.matches.indexOf("<all_urls>") === -1) { continue; }
    ref3.all_frames || (ref3.all_frames = ref2.all_frames);
    ref3.css = ref3.css.concat(ref2.css.map(func));
    ref3.js = ref3.js.concat(ref2.js.map(func));
  }
  ref3.js.push(func("content/inject-end.js"));
  Settings.CONST.ContentScripts = ref3;

  i = navigator.appVersion.indexOf("Chrome");
  Settings.CONST.ChromeVersion = parseFloat(navigator.appVersion.substring(i + 7));

  func = function() {};
  Settings.Sync = {clear: func, set: func};
  Settings.Sync.__proto__ = null;
})();

chrome.runtime.getPlatformInfo(function(info) {
  Settings.CONST.OnMac = info.os === "mac";
});
<|endoftext|>


<commit_before>'use strict';

module.exports = { accesskey: true, class: true, dir: true, hidden: true,
	id: true, intert: true, lang: true, spellcheck: true, style: true,
	title: true, translate: true };
<commit_msg>Add onkeypress to globally allowed html attrs<commit_after>'use strict';

module.exports = { accesskey: true, class: true, dir: true, hidden: true,
	id: true, intert: true, lang: true, spellcheck: true, style: true,
	title: true, translate: true, onkeypress: true };
<|endoftext|>


<commit_before>/* ©Copyright Utrecht University (Department of Information and Computing Sciences) */

/*
    This file contains all functionality pertaining to the mini map shown in the upper right corner in the editor
*/

var MiniMap;

(function()
{
    "use strict";

    var zoom = 1,
        // Show details? Set to false to speed up editor processing in large scenarios
        detailed = true;

    MiniMap =
    {
        zoom: zoom,
        detailed: detailed,
        initialise: initialise,
        attachScrollListener: attachScrollListener,
        update: update,
        activate: activate,
        deactivate: deactivate
    };

    // Turned on for this session? (based on e.g. browser)
    var enabled = true,
    // Allowed by the context? If not, hidden completely, including controls
    active = true,
    // Turned on by the user? If not, hidden, but controls are still visible
    shown = false;

    function initialise()
    {
        recallShown();
        if (!shown)
        {
            $("#minimap").hide();
            $("#enableMinimap").prop("checked", false);
        }

        $("#miniwrap").css("display","block");
        $("#minimap").css("width", "300px");
        $("#minimap").css("height", "300px");
        $("#minimap").css("overflow", "hidden");

        $("#minimap").on("click", function(e)
        {
            updateScrollPosition(e);
        });
        $("#mainCell #main").on("scroll", function()
        {
            update(false);
        });

        // Zoomed in scroll event listeners for minimap are created by attachScrollListener,
        // called by createEmptyTree()!

        // Listeners for minimap checkboxes
        $("#enableMinimap").on("click", function()
        {
            if (this.checked)
            {
                setAndStoreShown(true);
                showAnimated($("#minimap"));
            }
            else
            {
                hideAnimated($("#minimap"));
                setAndStoreShown(false);
            }
        });
        $("#simpleMinimap").on("click", function()
        {
            if (this.checked)
            {
                detailed = false;
                $("#scaledDiv").empty();
                update(false);
            }
            else
            {
                detailed = true;
                update(true);
            }
        });
    }

    function attachScrollListener(treeDiv)
    {
        if (!enabled) return;

        treeDiv.on('scroll', function(e)
        {
            update(false);
        });
    }

    function updateScrollPosition(e)
    {
        var minimapSelectorX = e.pageX - $("#minimap").offset().left - $("#minimapSelector").width() / 2;
        var minimapSelectorY = e.pageY - $("#minimap").offset().top - $("#minimapSelector").height() / 2;

        // Limit the minimum/maximum positions of the selector
        var maxX = $("#minimap").width() - $("#minimapSelector").width();
        var maxY = $("#minimap").height() - $("#minimapSelector").height();
        if (minimapSelectorX < 0) minimapSelectorX = 0;
        if (minimapSelectorY < 0) minimapSelectorY = 0;
        if (minimapSelectorX > maxX) minimapSelectorX = maxX;
        if (minimapSelectorY > maxY) minimapSelectorY = maxY;

        $("#minimapSelector").css("top", minimapSelectorY+"px");
        $("#minimapSelector").css("left", minimapSelectorX+"px");

        minimapSelectorX /= zoom;
        minimapSelectorY /= zoom;

        if (!Zoom.isZoomed())   // Nothing is zoomed
        {
            $("#mainCell > #main").scrollLeft(minimapSelectorX);
            $("#mainCell > #main").scrollTop(minimapSelectorY);
        }
        else
        {
            $("#mainCell .treeContainer.zoom > .treeDiv").scrollLeft(minimapSelectorX);
            $("#mainCell .treeContainer.zoom > .treeDiv").scrollTop(minimapSelectorY);
        }

        update(false);
    }

    // Scale the minimap according to the main div dimensions
    // and optionally refresh the map by cloning the main div
    function update(refresh)
    {
        if (!(enabled && active && shown)) return;

        var realWidth, realHeight;
        var viewportWidth, viewportHeight, viewportX, viewportY, zoomFactor;

        var main = $("#mainCell > #main");

        if (!Zoom.isZoomed())   // Nothing is zoomed
        {
            realWidth = main[0].scrollWidth;
            realHeight = main[0].scrollHeight;
            viewportX = main.scrollLeft();
            viewportY = main.scrollTop();
        }
        else
        {
            var treeDiv = $("#mainCell .treeContainer.zoom .treeDiv");
            realWidth = treeDiv[0].scrollWidth;
            realHeight = treeDiv[0].scrollHeight + $("#mainCell .subjectDiv")[0].scrollHeight;
            viewportX = treeDiv.scrollLeft();
            viewportY = treeDiv.scrollTop() + $("#mainCell .subjectDiv")[0].scrollHeight;
        }
        viewportWidth = main.width();
        viewportHeight = main.height();

        $("#scaledDiv").css("width", realWidth+"px");
        $("#scaledDiv").css("height", realHeight+"px");
        $("#minimap").css("height", $("#sidebar").height()-25+"px");

        // Show a cloned and scaled down version of the main div in the minimap
        if (detailed && refresh)
        {
            $("#scaledDiv").empty();
            var clonedMain = main.clone();
            // Remove inappropriate elements from the cloned main
            clonedMain.find("#gridIndicator").remove();
            if (Zoom.isZoomed()) clonedMain.find(".treeContainer").not(".zoom").remove();
            else clonedMain.find(".treeDiv").remove();
            // Remove all event handlers and IDs from the cloned main
            clonedMain.find("*").addBack().off().removeAttr("id");
            $("#scaledDiv").append(clonedMain);
        }

        // Standard width/height for minimap container
        var width = 300;
        var height = 300;

        var widthFactor = width/realWidth;
        var heightFactor = height/realHeight;

        zoomFactor = widthFactor;
        // minimap gets taller than the allowed screenheight
        if (zoomFactor * realHeight > $("#sidebar").height())
        {
            zoomFactor = $("#sidebar").height()/(realHeight+realHeight*0.1);
        }

        var minimapSize = {
            width: realWidth * zoomFactor + "px",
            height: realHeight * zoomFactor + "px"
        };
        $("#minimap").css(minimapSize);
        $("#minimap").data("savedSize", minimapSize);

        if (detailed && refresh)
        {
            $("#scaledDiv .treeContainer.zoom").css("left", 0 + "px");
            $("#scaledDiv .treeContainer.zoom").css("top", 0 + "px");
            $("#scaledDiv .treeContainer.zoom > .treeDiv").css("height", realHeight + "px");
            $("#scaledDiv .treeContainer.zoom > .treeDiv").css("width", realWidth + "px");
        }

        $("#scaledDiv").css({
            transform: "scale(" + zoomFactor + ")",
            transformOrigin: "top left"
        });

        // Scale and reposition the minimap selector
        $("#minimapSelector").css({
            width: viewportWidth * zoomFactor + "px",
            height: viewportHeight * zoomFactor + "px",
            top: viewportY * zoomFactor + "px",
            left: viewportX * zoomFactor + "px"
        });

        zoom = zoomFactor;
    }

    function recallShown()
    {
        var recalledShown = localStorage.getItem('MiniMap.shown');
        if (recalledShown !== null) shown = Boolean(JSON.parse(recalledShown));
    }

    function setAndStoreShown(newShown)
    {
        shown = Boolean(newShown);
        try
        {
            localStorage.setItem('MiniMap.shown', JSON.stringify(shown));
        }
        catch (e)
        {
            // storage is an enhancement, so ignore failure
        }
    }

    function showAnimated(element)
    {
        // slide Down with animation stopper
        var savedSize = element.data('savedSize');
        var finalHeight = savedSize ? savedSize.height : element.css('height', 'auto').height();
        element.height(0).show().stop(true,false).animate({height: finalHeight}, 400);
    }

    function hideAnimated(element)
    {
        // slide Up with animation stopper
        element.stop(true,false).animate({height: 0}, 400,
            'swing', function(){ element.hide(); });
    }

    function activate()
    {
        if (!enabled) return;

        if (!active) showAnimated($("#miniwrap"));
        active = true;
        update(true);
    }

    function deactivate()
    {
        if (!enabled) return;

        if (active) hideAnimated($("#miniwrap"));
        active = false;
    }
})();
<commit_msg>Added update just before displaying (enabling) minimap<commit_after>/* ©Copyright Utrecht University (Department of Information and Computing Sciences) */

/*
    This file contains all functionality pertaining to the mini map shown in the upper right corner in the editor
*/

var MiniMap;

(function()
{
    "use strict";

    var zoom = 1,
        // Show details? Set to false to speed up editor processing in large scenarios
        detailed = true;

    MiniMap =
    {
        zoom: zoom,
        detailed: detailed,
        initialise: initialise,
        attachScrollListener: attachScrollListener,
        update: update,
        activate: activate,
        deactivate: deactivate
    };

    // Turned on for this session? (based on e.g. browser)
    var enabled = true,
    // Allowed by the context? If not, hidden completely, including controls
    active = true,
    // Turned on by the user? If not, hidden, but controls are still visible
    shown = false;

    function initialise()
    {
        recallShown();
        if (!shown)
        {
            $("#minimap").hide();
            $("#enableMinimap").prop("checked", false);
        }

        $("#miniwrap").css("display","block");
        $("#minimap").css("width", "300px");
        $("#minimap").css("height", "300px");
        $("#minimap").css("overflow", "hidden");

        $("#minimap").on("click", function(e)
        {
            updateScrollPosition(e);
        });
        $("#mainCell #main").on("scroll", function()
        {
            update(false);
        });

        // Zoomed in scroll event listeners for minimap are created by attachScrollListener,
        // called by createEmptyTree()!

        // Listeners for minimap checkboxes
        $("#enableMinimap").on("click", function()
        {
            if (this.checked)
            {
                setAndStoreShown(true);
                update(true);
                showAnimated($("#minimap"));
            }
            else
            {
                hideAnimated($("#minimap"));
                setAndStoreShown(false);
            }
        });
        $("#simpleMinimap").on("click", function()
        {
            if (this.checked)
            {
                detailed = false;
                $("#scaledDiv").empty();
                update(false);
            }
            else
            {
                detailed = true;
                update(true);
            }
        });
    }

    function attachScrollListener(treeDiv)
    {
        if (!enabled) return;

        treeDiv.on('scroll', function(e)
        {
            update(false);
        });
    }

    function updateScrollPosition(e)
    {
        var minimapSelectorX = e.pageX - $("#minimap").offset().left - $("#minimapSelector").width() / 2;
        var minimapSelectorY = e.pageY - $("#minimap").offset().top - $("#minimapSelector").height() / 2;

        // Limit the minimum/maximum positions of the selector
        var maxX = $("#minimap").width() - $("#minimapSelector").width();
        var maxY = $("#minimap").height() - $("#minimapSelector").height();
        if (minimapSelectorX < 0) minimapSelectorX = 0;
        if (minimapSelectorY < 0) minimapSelectorY = 0;
        if (minimapSelectorX > maxX) minimapSelectorX = maxX;
        if (minimapSelectorY > maxY) minimapSelectorY = maxY;

        $("#minimapSelector").css("top", minimapSelectorY+"px");
        $("#minimapSelector").css("left", minimapSelectorX+"px");

        minimapSelectorX /= zoom;
        minimapSelectorY /= zoom;

        if (!Zoom.isZoomed())   // Nothing is zoomed
        {
            $("#mainCell > #main").scrollLeft(minimapSelectorX);
            $("#mainCell > #main").scrollTop(minimapSelectorY);
        }
        else
        {
            $("#mainCell .treeContainer.zoom > .treeDiv").scrollLeft(minimapSelectorX);
            $("#mainCell .treeContainer.zoom > .treeDiv").scrollTop(minimapSelectorY);
        }

        update(false);
    }

    // Scale the minimap according to the main div dimensions
    // and optionally refresh the map by cloning the main div
    function update(refresh)
    {
        if (!(enabled && active && shown)) return;

        var realWidth, realHeight;
        var viewportWidth, viewportHeight, viewportX, viewportY, zoomFactor;

        var main = $("#mainCell > #main");

        if (!Zoom.isZoomed())   // Nothing is zoomed
        {
            realWidth = main[0].scrollWidth;
            realHeight = main[0].scrollHeight;
            viewportX = main.scrollLeft();
            viewportY = main.scrollTop();
        }
        else
        {
            var treeDiv = $("#mainCell .treeContainer.zoom .treeDiv");
            realWidth = treeDiv[0].scrollWidth;
            realHeight = treeDiv[0].scrollHeight + $("#mainCell .subjectDiv")[0].scrollHeight;
            viewportX = treeDiv.scrollLeft();
            viewportY = treeDiv.scrollTop() + $("#mainCell .subjectDiv")[0].scrollHeight;
        }
        viewportWidth = main.width();
        viewportHeight = main.height();

        $("#scaledDiv").css("width", realWidth+"px");
        $("#scaledDiv").css("height", realHeight+"px");
        $("#minimap").css("height", $("#sidebar").height()-25+"px");

        // Show a cloned and scaled down version of the main div in the minimap
        if (detailed && refresh)
        {
            $("#scaledDiv").empty();
            var clonedMain = main.clone();
            // Remove inappropriate elements from the cloned main
            clonedMain.find("#gridIndicator").remove();
            if (Zoom.isZoomed()) clonedMain.find(".treeContainer").not(".zoom").remove();
            else clonedMain.find(".treeDiv").remove();
            // Remove all event handlers and IDs from the cloned main
            clonedMain.find("*").addBack().off().removeAttr("id");
            $("#scaledDiv").append(clonedMain);
        }

        // Standard width/height for minimap container
        var width = 300;
        var height = 300;

        var widthFactor = width/realWidth;
        var heightFactor = height/realHeight;

        zoomFactor = widthFactor;
        // minimap gets taller than the allowed screenheight
        if (zoomFactor * realHeight > $("#sidebar").height())
        {
            zoomFactor = $("#sidebar").height()/(realHeight+realHeight*0.1);
        }

        var minimapSize = {
            width: realWidth * zoomFactor + "px",
            height: realHeight * zoomFactor + "px"
        };
        $("#minimap").css(minimapSize);
        $("#minimap").data("savedSize", minimapSize);

        if (detailed && refresh)
        {
            $("#scaledDiv .treeContainer.zoom").css("left", 0 + "px");
            $("#scaledDiv .treeContainer.zoom").css("top", 0 + "px");
            $("#scaledDiv .treeContainer.zoom > .treeDiv").css("height", realHeight + "px");
            $("#scaledDiv .treeContainer.zoom > .treeDiv").css("width", realWidth + "px");
        }

        $("#scaledDiv").css({
            transform: "scale(" + zoomFactor + ")",
            transformOrigin: "top left"
        });

        // Scale and reposition the minimap selector
        $("#minimapSelector").css({
            width: viewportWidth * zoomFactor + "px",
            height: viewportHeight * zoomFactor + "px",
            top: viewportY * zoomFactor + "px",
            left: viewportX * zoomFactor + "px"
        });

        zoom = zoomFactor;
    }

    function recallShown()
    {
        var recalledShown = localStorage.getItem('MiniMap.shown');
        if (recalledShown !== null) shown = Boolean(JSON.parse(recalledShown));
    }

    function setAndStoreShown(newShown)
    {
        shown = Boolean(newShown);
        try
        {
            localStorage.setItem('MiniMap.shown', JSON.stringify(shown));
        }
        catch (e)
        {
            // storage is an enhancement, so ignore failure
        }
    }

    function showAnimated(element)
    {
        // slide Down with animation stopper
        var savedSize = element.data('savedSize');
        var finalHeight = savedSize ? savedSize.height : element.css('height', 'auto').height();
        element.height(0).show().stop(true,false).animate({height: finalHeight}, 400);
    }

    function hideAnimated(element)
    {
        // slide Up with animation stopper
        element.stop(true,false).animate({height: 0}, 400,
            'swing', function(){ element.hide(); });
    }

    function activate()
    {
        if (!enabled) return;

        if (!active) showAnimated($("#miniwrap"));
        active = true;
        update(true);
    }

    function deactivate()
    {
        if (!enabled) return;

        if (active) hideAnimated($("#miniwrap"));
        active = false;
    }
})();
<|endoftext|>


<commit_before>var clone = function (o) {
	if (typeof o != 'object') return (o);
	if (o == null) return (o);
	var ret = (typeof o.length == 'number') ? [] : {};
	for (var key in o) ret[key] = clone(o[key]);
	return ret;
};

function Replayer(midiFile, timeWarp, eventProcessor) {
	var trackStates = [];
	var beatsPerMinute = 120;
	var ticksPerBeat = midiFile.header.ticksPerBeat;

	for (var i = 0; i < midiFile.tracks.length; i++) {
		trackStates[i] = {
			'nextEventIndex': 0,
			'ticksToNextEvent': (
				midiFile.tracks[i].length ?
					midiFile.tracks[i][0].deltaTime :
					null
			)
		};
	}

	var nextEventInfo;
	var samplesToNextEvent = 0;

	function getNextEvent() {
		var ticksToNextEvent = null;
		var nextEventTrack = null;
		var nextEventIndex = null;

		for (var i = 0; i < trackStates.length; i++) {
			if (
				trackStates[i].ticksToNextEvent != null
				&& (ticksToNextEvent == null || trackStates[i].ticksToNextEvent < ticksToNextEvent)
			) {
				ticksToNextEvent = trackStates[i].ticksToNextEvent;
				nextEventTrack = i;
				nextEventIndex = trackStates[i].nextEventIndex;
			}
		}
		if (nextEventTrack != null) {
			/* consume event from that track */
			var nextEvent = midiFile.tracks[nextEventTrack][nextEventIndex];
			if (midiFile.tracks[nextEventTrack][nextEventIndex + 1]) {
				trackStates[nextEventTrack].ticksToNextEvent += midiFile.tracks[nextEventTrack][nextEventIndex + 1].deltaTime;
			} else {
				trackStates[nextEventTrack].ticksToNextEvent = null;
			}
			trackStates[nextEventTrack].nextEventIndex += 1;
			/* advance timings on all tracks by ticksToNextEvent */
			for (var i = 0; i < trackStates.length; i++) {
				if (trackStates[i].ticksToNextEvent != null) {
					trackStates[i].ticksToNextEvent -= ticksToNextEvent
				}
			}
			return {
				"ticksToEvent": ticksToNextEvent,
				"event": nextEvent,
				"track": nextEventTrack
			}
		} else {
			return null;
		}
	};
	//
	var midiEvent;
	var temporal = [];
	//
	function processEvents() {
		function processNext() {
			if ( midiEvent.event.type == "meta" && midiEvent.event.subtype == "setTempo" ) {
				// tempo change events can occur anywhere in the middle and affect events that follow
				beatsPerMinute = 60000000 / midiEvent.event.microsecondsPerBeat;
			}
			if (midiEvent.ticksToEvent > 0) {
				var beatsToGenerate = midiEvent.ticksToEvent / ticksPerBeat;
				var secondsToGenerate = beatsToGenerate / (beatsPerMinute / 60);
			}
			var time = (secondsToGenerate * 1000 * timeWarp) || 0;
			temporal.push([ midiEvent, time]);
			midiEvent = getNextEvent();
		};
		//
		if (midiEvent = getNextEvent()) {
			while(midiEvent) processNext(true);
		}
	};
	processEvents();
	return {
		"getData": function() {
			return clone(temporal);
		}
	};
};
<commit_msg>Update replayer.js<commit_after>var clone = function (o) {
	if (typeof o != 'object') return (o);
	if (o == null) return (o);
	var ret = (typeof o.length == 'number') ? [] : {};
	for (var key in o) ret[key] = clone(o[key]);
	return ret;
};

function Replayer(midiFile, timeWarp, eventProcessor) {
	var trackStates = [];
	var beatsPerMinute = 120;
	var ticksPerBeat = midiFile.header.ticksPerBeat;

	for (var i = 0; i < midiFile.tracks.length; i++) {
		trackStates[i] = {
			'nextEventIndex': 0,
			'ticksToNextEvent': (
				midiFile.tracks[i].length ?
					midiFile.tracks[i][0].deltaTime :
					null
			)
		};
	}

	var nextEventInfo;
	var samplesToNextEvent = 0;

	function getNextEvent() {
		var ticksToNextEvent = null;
		var nextEventTrack = null;
		var nextEventIndex = null;

		for (var i = 0; i < trackStates.length; i++) {
			if (
				trackStates[i].ticksToNextEvent != null
				&& (ticksToNextEvent == null || trackStates[i].ticksToNextEvent < ticksToNextEvent)
			) {
				ticksToNextEvent = trackStates[i].ticksToNextEvent;
				nextEventTrack = i;
				nextEventIndex = trackStates[i].nextEventIndex;
			}
		}
		if (nextEventTrack != null) {
			/* consume event from that track */
			var nextEvent = midiFile.tracks[nextEventTrack][nextEventIndex];
			if (midiFile.tracks[nextEventTrack][nextEventIndex + 1]) {
				trackStates[nextEventTrack].ticksToNextEvent += midiFile.tracks[nextEventTrack][nextEventIndex + 1].deltaTime;
			} else {
				trackStates[nextEventTrack].ticksToNextEvent = null;
			}
			trackStates[nextEventTrack].nextEventIndex += 1;
			/* advance timings on all tracks by ticksToNextEvent */
			for (var i = 0; i < trackStates.length; i++) {
				if (trackStates[i].ticksToNextEvent != null) {
					trackStates[i].ticksToNextEvent -= ticksToNextEvent
				}
			}
			return {
				"ticksToEvent": ticksToNextEvent,
				"event": nextEvent,
				"track": nextEventTrack
			}
		} else {
			return null;
		}
	};
	//
	var midiEvent;
	var temporal = [];
	//
	function processEvents() {
		function processNext() {
			var beatsToGenerate;
			var secondsToGenerate;
			if ( midiEvent.event.type == "meta" && midiEvent.event.subtype == "setTempo" ) {
				// tempo change events can occur anywhere in the middle and affect events that follow
				beatsPerMinute = 60000000 / midiEvent.event.microsecondsPerBeat;
			}
			if (midiEvent.ticksToEvent > 0) {
				beatsToGenerate = midiEvent.ticksToEvent / ticksPerBeat;
				secondsToGenerate = beatsToGenerate / (beatsPerMinute / 60);
			}
			var time = (secondsToGenerate * 1000 * timeWarp) || 0;
			temporal.push([ midiEvent, time]);
			midiEvent = getNextEvent();
		};
		//
		if (midiEvent = getNextEvent()) {
			while(midiEvent) processNext(true);
		}
	};
	processEvents();
	return {
		"getData": function() {
			return clone(temporal);
		}
	};
};
<|endoftext|>


<commit_before>var currentPos;
var disableAboveArray = [];
var disableBelowArray = [];

var rookAction = function() {
	$( ".white-square, .black-square" ).droppable({
		activeClass: "ui-state-hover",
		hoverClass: "ui-state-active",
		disabled: false,
		// accept: ".valid",

		drop: function( event, ui ) {

			var findPieceAbove = function() {
			  var chessIndex = startPos.parent().index();
			  disableAboveArray = [];
              for(placement = chessIndex - 1; placement > 0; placement--) {
              	if(startPos.parent().siblings().eq(placement).children("span").eq(startPos.index()).children().hasClass("chess-piece")) {
              	  for (neighbor = (placement - 1); neighbor > 1; neighbor --) {
                  	var disableAbove = startPos.parent().siblings().eq(neighbor).index();
                    disableAboveArray.push(disableAbove);
                  };

                  return disableAboveArray;
              	};
              };
			};

			var findPieceBelow = function() {
			  var chessIndex = startPos.parent().index();
			  disableBelowArray = [];
              for(placement = chessIndex; placement < 10; placement++) {
              	if(startPos.parent().siblings().eq(placement).children("span").eq(startPos.index()).children().hasClass("chess-piece")) {
              	  for (neighbor = (placement); neighbor < 10; neighbor ++) {
                  	var disableBelow = startPos.parent().siblings().eq(neighbor).index();
                    disableBelowArray.push(disableBelow);
                  };

                  return disableBelowArray;
              	};
              };
			};

			findPieceAbove();
			findPieceBelow();
			console.log(disableBelowArray);
			currentPos = $(this);
				if($(this).index() === startPos.index() && $(this).parent().index() != startPos.parent().siblings().eq(disableBelowArray[0]).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableBelowArray[0] + 1).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableBelowArray[0] + 2).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableBelowArray[0] + 3).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableBelowArray[0] + 4).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableBelowArray[0] + 5).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableBelowArray[0] + 6).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableBelowArray[0] + 7).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableAboveArray[disableAboveArray[0]]).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableAboveArray[disableAboveArray[0]]).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableAboveArray[disableAboveArray[0] - 1]).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableAboveArray[disableAboveArray[0] - 2]).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableAboveArray[disableAboveArray[0] - 3]).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableAboveArray[disableAboveArray[0] - 4]).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableAboveArray[disableAboveArray[0] - 5]).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableAboveArray[disableAboveArray[0] - 6]).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableAboveArray[disableAboveArray[0] - 7]).index() && startPos.children().hasClass("white-rook") && $(this).children().hasClass("white-piece") === false){
				    debugger
				    // findPiece();
				    playerTurn();
				    return $( this )
				    .html( ui.draggable );
				}

				else if($(this).parent()[0] === startPos.parent()[0] && startPos.children().hasClass("white-rook") && $(this).children().hasClass("white-piece") === false){

			    // findPiece();
			    playerTurn();
			    return $( this )
			    .html( ui.draggable );
				};

			if($(this).index() === startPos.index() && startPos.children().hasClass("black-rook") && $(this).children().hasClass("black-piece") === false){
			    // findPiece();
			    playerTurn();
			    return $( this )
			    .html( ui.draggable );
			}
			else if($(this).parent()[0] === startPos.parent()[0] && startPos.children().hasClass("black-rook") && $(this).children().hasClass("black-piece") === false){
			    // findPiece();
			    playerTurn();
			    return $( this )
			    .html( ui.draggable );
			};
		}
	});
};<commit_msg>Complete functionality for Rooks.<commit_after>var currentPos;
var disableAboveArray = [];
var disableBelowArray = [];
var disableLeftArray = [];
var disableRightArray = [];

var rookAction = function() {
	$( ".white-square, .black-square" ).droppable({
		activeClass: "ui-state-hover",
		hoverClass: "ui-state-active",
		disabled: false,
		// accept: ".valid",

		drop: function( event, ui ) {

			var findPieceAbove = function() {
			  var chessIndex = startPos.parent().index();
			  disableAboveArray = [];
              for(placement = chessIndex - 1; placement > 0; placement--) {
              	if(startPos.parent().siblings().eq(placement).children("span").eq(startPos.index()).children().hasClass("chess-piece")) {
              	  for(neighbor = (placement - 1); neighbor > 1; neighbor --) {
                  	var disableAbove = startPos.parent().siblings().eq(neighbor).index();
                    disableAboveArray.push(disableAbove);
                  };
                return disableAboveArray;
              	};
              };
			};
			var findPieceBelow = function() {
			  var chessIndex = startPos.parent().index();
			  disableBelowArray = [];
              for(placement = chessIndex; placement < 10; placement++) {
              	if(startPos.parent().siblings().eq(placement).children("span").eq(startPos.index()).children().hasClass("chess-piece")) {
              	  for(neighbor = (placement); neighbor < 10; neighbor ++) {
                  	var disableBelow = startPos.parent().siblings().eq(neighbor).index();
                    disableBelowArray.push(disableBelow);
                  };
                return disableBelowArray;
              	};
              };
			};
			var findPieceLeft = function() {
              var chessPieceIndex = startPos.index();
              disableLeftArray = [];
              for(placement = chessPieceIndex - 1; placement > 0; placement --) {
                if(startPos.siblings().eq(placement).children().hasClass("chess-piece")) {
                  for(neighbor = (placement - 1); neighbor > -1; neighbor --) {
                  	var disableLeft = startPos.siblings().eq(neighbor).index();
                  	disableLeftArray.push(disableLeft);
                  };
                return disableLeftArray
                };
              };
			};
			var findPieceRight = function() {
              var chessPieceIndex = startPos.index();
              disableRightArray = [];
              for(placement = chessPieceIndex; placement < 9; placement ++) {
                if(startPos.siblings().eq(placement).children().hasClass("chess-piece")) {
                  for(neighbor = (placement); neighbor < 9; neighbor ++) {
                  	var disableRight = startPos.siblings().eq(neighbor).index();
                  	disableRightArray.push(disableRight);
                  };
                return disableRightArray
                };
              };
			};

			findPieceAbove();
			findPieceBelow();
			findPieceLeft();
			findPieceRight();
			currentPos = $(this);

			//white vertical movement
			if($(this).index() === startPos.index() && $(this).parent().index() != startPos.parent().siblings().eq(disableBelowArray[0]).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableBelowArray[0] + 1).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableBelowArray[0] + 2).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableBelowArray[0] + 3).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableBelowArray[0] + 4).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableBelowArray[0] + 5).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableBelowArray[0] + 6).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableBelowArray[0] + 7).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableAboveArray[disableAboveArray[0]]).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableAboveArray[disableAboveArray[0]]).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableAboveArray[disableAboveArray[0] - 1]).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableAboveArray[disableAboveArray[0] - 2]).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableAboveArray[disableAboveArray[0] - 3]).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableAboveArray[disableAboveArray[0] - 4]).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableAboveArray[disableAboveArray[0] - 5]).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableAboveArray[disableAboveArray[0] - 6]).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableAboveArray[disableAboveArray[0] - 7]).index() && startPos.children().hasClass("white-rook") && $(this).children().hasClass("white-piece") === false){
			    playerTurn();
			    return $( this )
			    .html( ui.draggable );
			}
			//white horizontal movement
			else if($(this).parent()[0] === startPos.parent()[0] && $(this).index() != startPos.siblings().eq(disableLeftArray[disableLeftArray[0]]).index() && $(this).index() != startPos.siblings().eq(disableLeftArray[disableLeftArray[0] - 1]).index() && $(this).index() != startPos.siblings().eq(disableLeftArray[disableLeftArray[0] - 2]).index() && $(this).index() != startPos.siblings().eq(disableLeftArray[disableLeftArray[0] - 3]).index() && $(this).index() != startPos.siblings().eq(disableLeftArray[disableLeftArray[0] - 4]).index() && $(this).index() != startPos.siblings().eq(disableLeftArray[disableLeftArray[0] - 5]).index() && $(this).index() != startPos.siblings().eq(disableLeftArray[disableLeftArray[0] - 6]).index() && $(this).index() != startPos.siblings().eq(disableLeftArray[disableLeftArray[0] - 7]).index() && $(this).index() != startPos.siblings().eq(disableRightArray[0]).index() && $(this).index() != startPos.siblings().eq(disableRightArray[0] + 1).index() && $(this).index() != startPos.siblings().eq(disableRightArray[0] + 2).index() && $(this).index() != startPos.siblings().eq(disableRightArray[0] + 3).index() && $(this).index() != startPos.siblings().eq(disableRightArray[0] + 4).index() && $(this).index() != startPos.siblings().eq(disableRightArray[0] + 5).index() && $(this).index() != startPos.siblings().eq(disableRightArray[0] + 6).index() && $(this).index() != startPos.siblings().eq(disableRightArray[0] + 7).index() && startPos.children().hasClass("white-rook") && $(this).children().hasClass("white-piece") === false){
			debugger
			    playerTurn();
			    return $( this )
			    .html( ui.draggable );
			};

			//black vertical movement
			if($(this).index() === startPos.index() && $(this).parent().index() != startPos.parent().siblings().eq(disableBelowArray[0]).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableBelowArray[0] + 1).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableBelowArray[0] + 2).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableBelowArray[0] + 3).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableBelowArray[0] + 4).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableBelowArray[0] + 5).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableBelowArray[0] + 6).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableBelowArray[0] + 7).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableAboveArray[disableAboveArray[0]]).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableAboveArray[disableAboveArray[0]]).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableAboveArray[disableAboveArray[0] - 1]).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableAboveArray[disableAboveArray[0] - 2]).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableAboveArray[disableAboveArray[0] - 3]).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableAboveArray[disableAboveArray[0] - 4]).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableAboveArray[disableAboveArray[0] - 5]).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableAboveArray[disableAboveArray[0] - 6]).index() && $(this).parent().index() != startPos.parent().siblings().eq(disableAboveArray[disableAboveArray[0] - 7]).index() && startPos.children().hasClass("black-rook") && $(this).children().hasClass("black-piece") === false){
			    playerTurn();
			    return $( this )
			    .html( ui.draggable );
			}
			//black horizontal movement
			else if($(this).parent()[0] === startPos.parent()[0] && $(this).index() != startPos.siblings().eq(disableLeftArray[disableLeftArray[0]]).index() && $(this).index() != startPos.siblings().eq(disableLeftArray[disableLeftArray[0] - 1]).index() && $(this).index() != startPos.siblings().eq(disableLeftArray[disableLeftArray[0] - 2]).index() && $(this).index() != startPos.siblings().eq(disableLeftArray[disableLeftArray[0] - 3]).index() && $(this).index() != startPos.siblings().eq(disableLeftArray[disableLeftArray[0] - 4]).index() && $(this).index() != startPos.siblings().eq(disableLeftArray[disableLeftArray[0] - 5]).index() && $(this).index() != startPos.siblings().eq(disableLeftArray[disableLeftArray[0] - 6]).index() && $(this).index() != startPos.siblings().eq(disableLeftArray[disableLeftArray[0] - 7]).index() && $(this).index() != startPos.siblings().eq(disableRightArray[0]).index() && $(this).index() != startPos.siblings().eq(disableRightArray[0] + 1).index() && $(this).index() != startPos.siblings().eq(disableRightArray[0] + 2).index() && $(this).index() != startPos.siblings().eq(disableRightArray[0] + 3).index() && $(this).index() != startPos.siblings().eq(disableRightArray[0] + 4).index() && $(this).index() != startPos.siblings().eq(disableRightArray[0] + 5).index() && $(this).index() != startPos.siblings().eq(disableRightArray[0] + 6).index() && $(this).index() != startPos.siblings().eq(disableRightArray[0] + 7).index() && startPos.children().hasClass("black-rook") && $(this).children().hasClass("black-piece") === false){
			    // findPiece();
			    playerTurn();
			    return $( this )
			    .html( ui.draggable );
			};
		}
	});
};<|endoftext|>


<commit_before>"use strict";

import AppDispatcher from "../dispatcher/AppDispatcher";
import {ChangeEmitter} from "../utils/ChangeEmitter.js";

import CollectionStore from "./CollectionStore.js";

import PlaylistConstants from "../constants/PlaylistConstants.js";

class Item {
  constructor(path, transforms) {
    this._path = path;
    this._transforms = transforms;
  }

  path() {
    return this._path;
  }

  transform(root, keys) {
    if (this._transforms === null) {
      return keys;
    }
    let result = [];
    for (let i = 0; i < keys.length; i++) {
      let k = CollectionStore.pathToKey(root.concat(keys[i]));
      let skip = false;
      for (let j = 0; j < this._transforms.length; j++) {
        if (this._transforms[j].Action === "remove") {
          if (CollectionStore.pathToKey(this._transforms[j].Path) === k) {
            skip = true;
            break;
          }
        }
      }
      if (!skip) {
        result.push(keys[i]);
      }
    }
    return result;
  }
}

class Playlist {
  constructor() {
    this._items = [];
    this._cursor = null;
  }

  addItem(item) {
    this._items.push(item);
  }

  clear() {
    this._items = [];
  }

  items() {
    return this._items;
  }

  cursor() {
    return this._cursor;
  }
}

var _playlist = new Playlist();

function getKeys(path) {
  let c = CollectionStore.getCollection(path);
  let keys = [];

  if (!c) {
    return keys;
  }

  if (c.Tracks) {
    keys = c.Tracks.map(function(k, i) {
      return i;
    });
  }

  if (c.Groups) {
    keys = c.Groups.map(function(g) {
      return g.Key;
    });
  }
  return keys;
}

class PlaylistStore extends ChangeEmitter {

  getPlaylist() {
    return _playlist.items();
  }

  getItemKeys(index, path) {
    let keys = getKeys(path);
    let item = _playlist.items()[index];
    keys = item.transform(path, keys);
    return keys;
  }

}

var _store = new PlaylistStore();

_store.dispatchToken = AppDispatcher.register(function(payload) {
  var action = payload.action;
  var source = payload.source;

  if (source === "SERVER_ACTION") {
    if (action.actionType === PlaylistConstants.PLAYLIST) {
      _playlist.clear();
      let items = action.data.items || [];
      items.forEach(function(item) {
        _playlist.addItem(new Item(item.path, item.transforms));
      });
      _store.emitChange();
    }
  }

  if (source === "VIEW_ACTION") {
    switch (action.actionType) {

      case PlaylistConstants.ADD_ITEM:
        // TODO: Implement
        break;

      case PlaylistConstants.ADD_ITEM_PLAY_NOW:
        // TODO: Implement
        break;

      case PlaylistConstants.CLEAR_PLAYLIST:
        // TODO: Implement
        break;

      default:
        break;
    }
  }

  return true;
});

export default _store;
<commit_msg>Fix playlist transform processing to use correct fields.<commit_after>"use strict";

import AppDispatcher from "../dispatcher/AppDispatcher";
import {ChangeEmitter} from "../utils/ChangeEmitter.js";

import CollectionStore from "./CollectionStore.js";

import PlaylistConstants from "../constants/PlaylistConstants.js";

class Item {
  constructor(path, transforms) {
    this._path = path;
    this._transforms = transforms;
  }

  path() {
    return this._path;
  }

  transform(root, keys) {
    if (this._transforms === null) {
      return keys;
    }
    let result = [];
    for (let i = 0; i < keys.length; i++) {
      let k = CollectionStore.pathToKey(root.concat(keys[i]));
      let skip = false;
      for (let j = 0; j < this._transforms.length; j++) {
        if (this._transforms[j].action === "remove") {
          if (CollectionStore.pathToKey(this._transforms[j].path) === k) {
            skip = true;
            break;
          }
        }
      }
      if (!skip) {
        result.push(keys[i]);
      }
    }
    return result;
  }
}

class Playlist {
  constructor() {
    this._items = [];
    this._cursor = null;
  }

  addItem(item) {
    this._items.push(item);
  }

  clear() {
    this._items = [];
  }

  items() {
    return this._items;
  }

  cursor() {
    return this._cursor;
  }
}

var _playlist = new Playlist();

function getKeys(path) {
  let c = CollectionStore.getCollection(path);
  let keys = [];

  if (!c) {
    return keys;
  }

  if (c.Tracks) {
    keys = c.Tracks.map(function(k, i) {
      return i;
    });
  }

  if (c.Groups) {
    keys = c.Groups.map(function(g) {
      return g.Key;
    });
  }
  return keys;
}

class PlaylistStore extends ChangeEmitter {

  getPlaylist() {
    return _playlist.items();
  }

  getItemKeys(index, path) {
    let keys = getKeys(path);
    let item = _playlist.items()[index];
    keys = item.transform(path, keys);
    return keys;
  }

}

var _store = new PlaylistStore();

_store.dispatchToken = AppDispatcher.register(function(payload) {
  var action = payload.action;
  var source = payload.source;

  if (source === "SERVER_ACTION") {
    if (action.actionType === PlaylistConstants.PLAYLIST) {
      _playlist.clear();
      let items = action.data.items || [];
      items.forEach(function(item) {
        _playlist.addItem(new Item(item.path, item.transforms));
      });
      _store.emitChange();
    }
  }

  if (source === "VIEW_ACTION") {
    switch (action.actionType) {

      case PlaylistConstants.ADD_ITEM:
        // TODO: Implement
        break;

      case PlaylistConstants.ADD_ITEM_PLAY_NOW:
        // TODO: Implement
        break;

      case PlaylistConstants.CLEAR_PLAYLIST:
        // TODO: Implement
        break;

      default:
        break;
    }
  }

  return true;
});

export default _store;
<|endoftext|>


<commit_before>// Invoked by: API Gateway
// Returns: Error, or API Gateway proxy response object
//
// Handles GitHub webhook event payload requests. It does a bit of validation on
// the request, and then forwards the payload to an SNS topic, where other
// Lambdas will pick it up and process the event.

const crypto = require('crypto');
const AWS = require('aws-sdk');

const OK_RESPONSE = { statusCode: 200, headers: {}, body: null };

const sns = new AWS.SNS({apiVersion: '2010-03-31'});

exports.handler = (event, context, callback) => {
    try {
        main(event, context, callback);
    } catch(e) {
        console.error('Unhandled exception!');
        callback(e);
    }
};

function main(event, context, callback) {
    const githubSignature = event.headers['X-Hub-Signature'].split('=')[1];

    console.log(`Checking event signature: ${githubSignature}...`);

    const key = process.env.GITHUB_WEBHOOK_SECRET;
    const data = event.body;
    const check = crypto.createHmac('sha1', key).update(data).digest('hex');

    if (githubSignature === check) {
        handleEvent(event, callback);
    } else {
        // Raising an error here so it's visible if we start getting requests
        // that aren't valid.
        console.error('...Request signature was invalid!');
        callback(new Error('Invalid signature!'));
    }
}

function handleEvent(event, callback) {
    console.log(`...Handling event: ${event.headers['X-GitHub-Event']}...`);
    switch (event.headers['X-GitHub-Event']) {
        case 'ping':
            // Blackhole `ping` events
            callback(null, OK_RESPONSE);
            break;
        default:
            publishEvent(event, callback);
    }
}

function publishEvent(event, callback) {
    console.log(`...Publishing event to SNS...`);

    sns.publish({
        TopicArn: process.env.GITHUB_EVENT_HANDLER_TOPIC_ARN,
        Message: event.body,
        MessageAttributes: {
            githubEvent: {
                DataType: 'String',
                StringValue: event.headers['X-GitHub-Event']
            }, githubDeliveryId: {
                DataType: 'String',
                StringValue: event.headers['X-GitHub-Delivery']
            }
        }
    }, (err, data) => {
        if (err) {
            console.error(`...Publishing event failed!`);
            callback(err);
        } else {
            console.log(`...Event published!`);
            callback(null, OK_RESPONSE);
        }
    });
}
<commit_msg>Cleanup GitHub web hook lambda (linting)<commit_after>// Invoked by: API Gateway
// Returns: Error, or API Gateway proxy response object
//
// Handles GitHub webhook event payload requests. It does a bit of validation on
// the request, and then forwards the payload to an SNS topic, where other
// Lambdas will pick it up and process the event.

const crypto = require('crypto');
const AWS = require('aws-sdk');

const OK_RESPONSE = { statusCode: 200, headers: {}, body: null };

const sns = new AWS.SNS({ apiVersion: '2010-03-31' });

function publishEvent(event, callback) {
    console.log('...Publishing event to SNS...');

    sns.publish({
        TopicArn: process.env.GITHUB_EVENT_HANDLER_TOPIC_ARN,
        Message: event.body,
        MessageAttributes: {
            githubEvent: {
                DataType: 'String',
                StringValue: event.headers['X-GitHub-Event'],
            },
            githubDeliveryId: {
                DataType: 'String',
                StringValue: event.headers['X-GitHub-Delivery'],
            },
        },
    }, (err) => {
        if (err) {
            console.error('...Publishing event failed!');
            callback(err);
        } else {
            console.log('...Event published!');
            callback(null, OK_RESPONSE);
        }
    });
}

function handleEvent(event, callback) {
    console.log(`...Handling event: ${event.headers['X-GitHub-Event']}...`);
    switch (event.headers['X-GitHub-Event']) {
        case 'ping':
            // Blackhole `ping` events
            callback(null, OK_RESPONSE);
            break;
        default:
            publishEvent(event, callback);
    }
}

function main(event, context, callback) {
    const githubSignature = event.headers['X-Hub-Signature'].split('=')[1];

    console.log(`Checking event signature: ${githubSignature}...`);

    const key = process.env.GITHUB_WEBHOOK_SECRET;
    const data = event.body;
    const check = crypto.createHmac('sha1', key).update(data).digest('hex');

    if (githubSignature === check) {
        handleEvent(event, callback);
    } else {
        // Raising an error here so it's visible if we start getting requests
        // that aren't valid.
        console.error('...Request signature was invalid!');
        callback(new Error('Invalid signature!'));
    }
}

exports.handler = (event, context, callback) => {
    try {
        main(event, context, callback);
    } catch (e) {
        console.error('Unhandled exception!');
        callback(e);
    }
};
<|endoftext|>


<commit_before>/**
 * Doranis Preloader
 * Doranis.preloader | Monday, June 16, 2014
 * @author Pezhvak IMV (pezhvakimv@gmail.com)
 * @package doranis
 * @version 1.0
 **/
(function($){
    $.doranis.preloader = {}

    $.doranis.preloader.preload = function (opts)
    {
        opts = $.extend({collection: [], progress: function(opts){}, complete: function(opts){}, fail: function(opts){}}, opts);
        var loaded = new Array();

        $.each(opts.collection,function(i, entry)
        {
            var img = new Image();
            var url = '';
            var img_obj = img;
            var title = '';

            if ('object' != typeof entry)
            {
                url = $(entry).attr('src') || $(entry).css('background-image').replace(/^url\((?:"|')?(.*)(?:'|")?\)$/mg, "$1");
                img_obj = entry;
            }
            else{
                url = entry.url;
                title = entry.title;
            }

            $(img).bind('load error', function(e)
            {
                loaded.push(img_obj);
                $.data(img_obj, 'loaded', ('error'==e.type)?false:true);
                if('error'==e.type)
                    opts.fail({title: title, total: opts.collection.length, loaded: loaded.length, percentage: (100/opts.collection.length) * loaded.length, url: url, object: img_obj});
                else
                    opts.progress({title: title, total: opts.collection.length, loaded: loaded.length, percentage: (100/opts.collection.length) * loaded.length, url: url, object: img_obj});

                if (loaded.length>=opts.collection.length)
                    opts.progress({loaded: loaded});

                $(this).unbind('load error');
            });

            img.src = url;
        });
    };

    $.fn.preload = function(opts)
    {
        opts = $.extend(opts, {collection:[this]});
        $.doranis.preloader.preload(opts);

        // continue chaining
        return this;
    };
})(jQuery);<commit_msg>preloader fixed<commit_after>/**
 * Doranis Preloader
 * Doranis.preloader | Monday, June 16, 2014
 * @author Pezhvak IMV (pezhvakimv@gmail.com)
 * @package doranis
 * @version 1.0
 **/
(function($){
    $.doranis.preloader = {}

    $.doranis.preloader.preload = function (opts)
    {
        opts = $.extend({collection: [], progress: function(opts){}, complete: function(opts){}, fail: function(opts){}}, opts);
        var loaded = new Array();

        $.each(opts.collection,function(i, entry)
        {
            var img = new Image();
            var url = '';
            var img_obj = img;
            var title = '';

            if ('object' != typeof entry)
            {
                url = $(entry).attr('src') || $(entry).css('background-image').replace(/^url\((?:"|')?(.*)(?:'|")?\)$/mg, "$1");
                img_obj = entry;
            }
            else{
                url = entry.url;
                title = entry.title;
            }

            $(img).bind('load error', function(e)
            {
                loaded.push(img_obj);
                $.data(img_obj, 'loaded', ('error'==e.type)?false:true);
                if('error'==e.type)
                    opts.fail({title: title, total: opts.collection.length, loaded: loaded.length, percentage: (100/opts.collection.length) * loaded.length, url: url, object: img_obj});
                else
                    opts.progress({title: title, total: opts.collection.length, loaded: loaded.length, percentage: (100/opts.collection.length) * loaded.length, url: url, object: img_obj});

                if (loaded.length>=opts.collection.length)
                    opts.complete({loaded: loaded});

                $(this).unbind('load error');
            });

            img.src = url;
        });
    };

    $.fn.preload = function(opts)
    {
        opts = $.extend(opts, {collection:[this]});
        $.doranis.preloader.preload(opts);

        // continue chaining
        return this;
    };
})(jQuery);<|endoftext|>


<commit_before>// eslint-disable-next-line import/no-unresolved
import { TokenCache } from 'google-oauth-jwt';
import fs from 'fs';

import { Meteor } from 'meteor/meteor';
import { HTTP } from 'meteor/http';

const GOOGLE_AUTH_SCOPES = ['https://www.googleapis.com/auth/devstorage.read_write'];
const GOOGLE_STORAGE_API_BASE_URL = 'https://www.googleapis.com/storage/v1';

const tokens = new TokenCache();
const syncGetTokenFn = Meteor.wrapAsync(tokens.get, tokens);

class GoogleCloudStorage {
  constructor({ bucket, email, keyFile, scopes = GOOGLE_AUTH_SCOPES }) {
    this._bucket = bucket;
    this._authOptions = { email, keyFile: this._assetsFolderAbsolutePath(keyFile), scopes };
  }

  _generateAuthCredentials() {
    const token = syncGetTokenFn(this._authOptions);

    return {
      token,
      type: 'Bearer',
    };
  }

  _assetsFolderAbsolutePath(fileName) {
    const meteorRoot = fs.realpathSync(`${process.cwd()}/../`);

    const assetsFolder = `${meteorRoot}/server/assets/app`;

    if (fileName) {
      return `${assetsFolder}/${fileName}`;
    }

    return assetsFolder;
  }

  _getAuthHeaders() {
    const accessCredentials = this._generateAuthCredentials();
    return {
      Authorization: `${accessCredentials.type} ${accessCredentials.token}`,
    };
  }

  makeRequestToGoogleStorage(requestMethod, url, headers = {}) {
    const wholeUrl = `${GOOGLE_STORAGE_API_BASE_URL}/${url}`;
    try {
      return HTTP.call(
        requestMethod,
        wholeUrl,
        {
          headers: {
            'Content-Type': 'application/json',
            ...this._getAuthHeaders(),
            ...headers,
          },
        }
      );
    } catch (error) {
      // eslint-disable-next-line no-console
      console.error('Error while requesting Google Api', error);
      return false;
    }
  }

  removeFile(object) {
    return this.makeRequestToGoogleStorage('DELETE', `/b/${this._bucket}/o/${object}`);
  }
}

export { GoogleCloudStorage };
<commit_msg>Fix removal method bug<commit_after>// eslint-disable-next-line import/no-unresolved
import { TokenCache } from 'google-oauth-jwt';
import fs from 'fs';

import { Meteor } from 'meteor/meteor';
import { HTTP } from 'meteor/http';

const GOOGLE_AUTH_SCOPES = ['https://www.googleapis.com/auth/devstorage.read_write'];
const GOOGLE_STORAGE_API_BASE_URL = 'https://www.googleapis.com/storage/v1';

const tokens = new TokenCache();
const syncGetTokenFn = Meteor.wrapAsync(tokens.get, tokens);

class GoogleCloudStorage {
  constructor({ bucket, email, keyFile, scopes = GOOGLE_AUTH_SCOPES }) {
    this._bucket = bucket;
    this._authOptions = { email, keyFile: this._assetsFolderAbsolutePath(keyFile), scopes };
  }

  _generateAuthCredentials() {
    const token = syncGetTokenFn(this._authOptions);

    return {
      token,
      type: 'Bearer',
    };
  }

  _assetsFolderAbsolutePath(fileName) {
    const meteorRoot = fs.realpathSync(`${process.cwd()}/../`);

    const assetsFolder = `${meteorRoot}/server/assets/app`;

    if (fileName) {
      return `${assetsFolder}/${fileName}`;
    }

    return assetsFolder;
  }

  _getAuthHeaders() {
    const accessCredentials = this._generateAuthCredentials();
    return {
      Authorization: `${accessCredentials.type} ${accessCredentials.token}`,
    };
  }

  makeRequestToGoogleStorage(requestMethod, urlPath, headers = {}) {
    try {
      return HTTP.call(
        requestMethod,
        `${GOOGLE_STORAGE_API_BASE_URL}/${urlPath}`,
        {
          headers: {
            'Content-Type': 'application/json',
            ...this._getAuthHeaders(),
            ...headers,
          },
        }
      );
    } catch (error) {
      // eslint-disable-next-line no-console
      console.error('Error while requesting Google Api', error);
      return false;
    }
  }

  removeFile(object) {
    return this.makeRequestToGoogleStorage('DELETE', `b/${this._bucket}/o/${object}`);
  }
}

export { GoogleCloudStorage };
<|endoftext|>