<commit_before>#!/usr/bin/env node

var commander = require("commander");
var transform = require("../../lib/6to5/transformation/transform");
var util      = require("../../lib/6to5/util");
var fs        = require("fs");
var _         = require("lodash");

commander.option("-t, --source-maps-inline", "Append sourceMappingURL comment to bottom of code");
commander.option("-s, --source-maps", "Save source map alongside the compiled code");
commander.option("-f, --filename [filename]", "Filename to use when reading from stdin - this will be used in source-maps, errors etc [stdin]", "stdin");
commander.option("-w, --watch", "Recompile files on changes");
commander.option("-r, --runtime", "Replace 6to5 declarations with references to a runtime");
commander.option("-e, --experimental", "Enable experimental support for proposed ES7 features");
commander.option("-p, --playground", "Enable playground support");

commander.option("-m, --modules [modules]", "Module formatter type to use [common]", "common");
commander.option("-l, --whitelist [whitelist]", "Whitelist of transformers to ONLY use", util.list);
commander.option("-b, --blacklist [blacklist]", "Blacklist of transformers to NOT use", util.list);
commander.option("-i, --optional [list]", "List of optional transformers to enable", util.list);
commander.option("--loose [list]", "List of transformers to enable their loose mode", util.list);
commander.option("-o, --out-file [out]", "Compile all input files into a single file");
commander.option("-d, --out-dir [out]", "Compile an input directory of modules into an output directory");
commander.option("-c, --remove-comments", "Remove comments from the compiled code", false);
commander.option("-I, --indent [width]", "Indent width [2]", 2);
commander.option("-a, --amd-module-ids", "Insert module id in AMD modules", false); // todo: remove in 3.0.0
commander.option("-m, --module-ids", "Insert module id in modules", false);
commander.option("-R, --react-compat", "Makes the react transformer produce pre-v0.12 code");
commander.option("-E, --include-regenerator", "Include the regenerator runtime if necessary", false);
commander.option("--keep-module-id-extensions", "Keep extensions when generating module ids", false);

commander.on("--help", function(){
  var outKeys = function (title, obj) {
    console.log("  " + title + ":");
    console.log();

    _.each(_.keys(obj).sort(), function (key) {
      if (key[0] === "_") return;
      console.log("    - " + key);
    });

    console.log();
  };

  outKeys("Transformers", transform.transformers);
  outKeys("Module formatters", transform.moduleFormatters);
});

var pkg = require("../../package.json");
commander.version(pkg.version);
commander.usage("[options] <files ...>");
commander.parse(process.argv);

//

var errors = [];

var filenames = commander.args;

_.each(filenames, function (filename) {
  if (!fs.existsSync(filename)) {
    errors.push(filename + " doesn't exist");
  }
});

if (commander.outDir && !filenames.length) {
  errors.push("filenames required for --out-dir");
}

if (commander.outFile && commander.outDir) {
  errors.push("cannot have --out-file and --out-dir");
}

if (commander.watch) {
  if (!commander.outFile && !commander.outDir) {
    errors.push("--watch requires --out-file or --out-dir");
  }

  if (!filenames.length) {
    errors.push("--watch requires filenames");
  }
}

if (commander.sourceMaps) {
  if (!commander.outFile && !commander.outDir) {
    errors.push("--source-maps requires --out-file or --out-dir");
  }
}

if (errors.length) {
  console.error(errors.join(". "));
  process.exit(2);
}

//

exports.opts = {
  keepModuleIdExtensions: commander.keepModuleIdExtensions,
  includeRegenerator:     commander.includeRegenerator,
  sourceMapName:          commander.outFile,
  experimental:           commander.experimental,
  reactCompat:            commander.reactCompat,
  playground:             commander.playground,
  moduleIds:              commander.amdModuleIds || commander.moduleIds,
  blacklist:              commander.blacklist,
  whitelist:              commander.whitelist,
  sourceMap:              commander.sourceMaps || commander.sourceMapsInline,
  optional:               commander.optional,
  comments:               !commander.removeComments,
  runtime:                commander.runtime,
  modules:                commander.modules,
  loose:                  commander.loose,
  format: {
    indent: {
      style:     util.repeat(parseInt(commander.indent))
    }
  }
};

var fn;

if (commander.outDir) {
  fn = require("./dir");
} else {
  fn = require("./file");
}

fn(commander, filenames, exports.opts);
<commit_msg>remove indent option from cli<commit_after>#!/usr/bin/env node

var commander = require("commander");
var transform = require("../../lib/6to5/transformation/transform");
var util      = require("../../lib/6to5/util");
var fs        = require("fs");
var _         = require("lodash");

commander.option("-t, --source-maps-inline", "Append sourceMappingURL comment to bottom of code");
commander.option("-s, --source-maps", "Save source map alongside the compiled code");
commander.option("-f, --filename [filename]", "Filename to use when reading from stdin - this will be used in source-maps, errors etc [stdin]", "stdin");
commander.option("-w, --watch", "Recompile files on changes");
commander.option("-r, --runtime", "Replace 6to5 declarations with references to a runtime");
commander.option("-e, --experimental", "Enable experimental support for proposed ES7 features");
commander.option("-p, --playground", "Enable playground support");

commander.option("-m, --modules [modules]", "Module formatter type to use [common]", "common");
commander.option("-l, --whitelist [whitelist]", "Whitelist of transformers to ONLY use", util.list);
commander.option("-b, --blacklist [blacklist]", "Blacklist of transformers to NOT use", util.list);
commander.option("-i, --optional [list]", "List of optional transformers to enable", util.list);
commander.option("--loose [list]", "List of transformers to enable their loose mode", util.list);
commander.option("-o, --out-file [out]", "Compile all input files into a single file");
commander.option("-d, --out-dir [out]", "Compile an input directory of modules into an output directory");
commander.option("-c, --remove-comments", "Remove comments from the compiled code", false);
commander.option("-a, --amd-module-ids", "Insert module id in AMD modules", false); // todo: remove in 3.0.0
commander.option("-m, --module-ids", "Insert module id in modules", false);
commander.option("-R, --react-compat", "Makes the react transformer produce pre-v0.12 code");
commander.option("-E, --include-regenerator", "Include the regenerator runtime if necessary", false);
commander.option("--keep-module-id-extensions", "Keep extensions when generating module ids", false);

commander.on("--help", function(){
  var outKeys = function (title, obj) {
    console.log("  " + title + ":");
    console.log();

    _.each(_.keys(obj).sort(), function (key) {
      if (key[0] === "_") return;
      console.log("    - " + key);
    });

    console.log();
  };

  outKeys("Transformers", transform.transformers);
  outKeys("Module formatters", transform.moduleFormatters);
});

var pkg = require("../../package.json");
commander.version(pkg.version);
commander.usage("[options] <files ...>");
commander.parse(process.argv);

//

var errors = [];

var filenames = commander.args;

_.each(filenames, function (filename) {
  if (!fs.existsSync(filename)) {
    errors.push(filename + " doesn't exist");
  }
});

if (commander.outDir && !filenames.length) {
  errors.push("filenames required for --out-dir");
}

if (commander.outFile && commander.outDir) {
  errors.push("cannot have --out-file and --out-dir");
}

if (commander.watch) {
  if (!commander.outFile && !commander.outDir) {
    errors.push("--watch requires --out-file or --out-dir");
  }

  if (!filenames.length) {
    errors.push("--watch requires filenames");
  }
}

if (commander.sourceMaps) {
  if (!commander.outFile && !commander.outDir) {
    errors.push("--source-maps requires --out-file or --out-dir");
  }
}

if (errors.length) {
  console.error(errors.join(". "));
  process.exit(2);
}

//

exports.opts = {
  keepModuleIdExtensions: commander.keepModuleIdExtensions,
  includeRegenerator:     commander.includeRegenerator,
  sourceMapName:          commander.outFile,
  experimental:           commander.experimental,
  reactCompat:            commander.reactCompat,
  playground:             commander.playground,
  moduleIds:              commander.amdModuleIds || commander.moduleIds,
  blacklist:              commander.blacklist,
  whitelist:              commander.whitelist,
  sourceMap:              commander.sourceMaps || commander.sourceMapsInline,
  optional:               commander.optional,
  comments:               !commander.removeComments,
  runtime:                commander.runtime,
  modules:                commander.modules,
  loose:                  commander.loose
};

var fn;

if (commander.outDir) {
  fn = require("./dir");
} else {
  fn = require("./file");
}

fn(commander, filenames, exports.opts);
<|endoftext|>


<commit_before>/*
 * Copyright 2016 Red Hat Inc.
 *
 * 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.
 */
'use strict';

var fs = require("fs");
var Promise = require('bluebird');

var AddressCtrl = function (host, port, ca_file) {
    this.host = host;
    this.port = port;
    this.ca_file = ca_file;
    this.address_space = process.env.ADDRESS_SPACE
    this.http = ca_file !== undefined ? require('https') : require('http');
    this.auth_string = undefined;
    if (process.env.ADDRESS_SPACE_PASSWORD_FILE) {
        this.auth_string = 'Basic ' + new Buffer(process.env.ADDRESS_SPACE + ":" + fs.readFileSync(process.env.ADDRESS_SPACE_PASSWORD_FILE)).toString('base64');
    }

    this.addr_path = "/v1/addresses/";
    if (this.address_space) {
        this.addr_path += this.address_space + "/";
    }
}

AddressCtrl.prototype.request = function (path, method, headers, body, handler) {
    var self = this;
    return new Promise(function (resolve, reject) {
        var options = {
            hostname: self.host,
            port: self.port
        };
        options.path = path;
        options.method = method || 'GET';
        options.headers = {};

        if (headers) {
            options.headers = headers;
        }

        if (self.auth_string) {
            options.headers['Authorization'] = self.auth_string
        }

        if (self.ca_file) {
            options.ca = fs.readFileSync(self.ca_file);
        }

        var req = self.http.request(options, function(res) {
            if (res.statusCode === 200) {
                if (handler) {
                    var text = '';
                    res.setEncoding('utf8');
                    res.on('data', function (chunk) {
                        text += chunk;
                    });
                    res.on('end', function () {
                        try {
                            resolve(handler(text));
                        } catch (e) {
                            reject(e);
                        }
                    });
                } else {
                    resolve();
                }
            } else {
                var text = 'Error: ' + res.statusCode + ' for ' + options.method + ' on ' + options.path;
                console.error(text);
                text += ' ';
                res.setEncoding('utf8');
                res.on('data', function (chunk) {
                    text += chunk;
                });
                res.on('end', function () {
                    reject(new Error(text));
                });
            }
        });
        req.on('error', function(e) {
            console.error('Error: ' + e.message + ' for ' + options.method + ' on ' + options.path);
            reject(e);
        });
        if (body) {
            req.write(body);
        }
        req.end();
    });
}

AddressCtrl.prototype.create_address = function (address) {
    var data = {
        "apiVersion": "enmasse.io/v1",
        "kind": "AddressList",
        "items" : [
            {
                "metadata": {
                    "name": address.address
                },
                "spec": {
                    "address": address.address,
                    "type": address.type,
                    "plan": address.plan
                }
            }
        ]
    };
    return this.request(this.addr_path, 'POST', {'content-type': 'application/json'}, JSON.stringify(data));
}

AddressCtrl.prototype.delete_address = function(address) {
    return this.request(this.addr_path + address.address, 'DELETE');
}

function index(list) {
    return list.reduce(function (map, item) { map[item.name] = item; return map; }, {});
}

function address_types(text) {
    var object = JSON.parse(text);
    if (object.kind === 'Schema') {
        //TODO: retrieve type for current address-space (assume 'standard' for now)
        return index(object.spec.addressSpaceTypes)['standard'].addressTypes;
    } else {
        throw new Error('Unexpected object kind: ' + object.kind);
    }
}

AddressCtrl.prototype.get_address_types = function () {
    return this.request('/v1/schema/', 'GET', undefined, undefined, address_types);
}

module.exports.create = function () {
    var host = 'localhost';
    var port = 8080;
    if (process.env.ADDRESS_SPACE_SERVICE_HOST) {
        host = process.env.ADDRESS_SPACE_SERVICE_HOST;
    } else if (process.env.ADDRESS_CONTROLLER_SERVICE_HOST) {
        host = process.env.ADDRESS_CONTROLLER_SERVICE_HOST;
        if (process.env.ADDRESS_CONTROLLER_SERVICE_PORT_HTTPS) {
            port = process.env.ADDRESS_CONTROLLER_SERVICE_PORT_HTTPS;
        }
    }

    var ca_file = undefined; //process.env.ADDRESS_CONTROLLER_CA;

    return new AddressCtrl(host, port, ca_file)
};
<commit_msg>Update console bits after review<commit_after>/*
 * Copyright 2016 Red Hat Inc.
 *
 * 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.
 */
'use strict';

var fs = require("fs");
var Promise = require('bluebird');

var AddressCtrl = function (host, port, ca, auth_string) {
    this.host = host;
    this.port = port;
    this.address_space = process.env.ADDRESS_SPACE
    this.http = ca ? require('https') : require('http');
    this.ca = ca;
    this.auth_string = auth_string;

    this.addr_path = "/v1/addresses/";
    if (this.address_space) {
        this.addr_path += this.address_space + "/";
    }
}

AddressCtrl.prototype.request = function (addr_path, method, headers, body, handler) {
    var self = this;
    return new Promise(function (resolve, reject) {
        var options = {
            hostname: self.host,
            port: self.port
        };
        options.path = addr_path;
        options.method = method || 'GET';
        options.headers = headers || {};

        if (self.auth_string) {
            options.headers['Authorization'] = self.auth_string
        }

        if (self.ca) {
            options.ca = self.ca;
        }

        var req = self.http.request(options, function(res) {
            if (res.statusCode === 200) {
                if (handler) {
                    var text = '';
                    res.setEncoding('utf8');
                    res.on('data', function (chunk) {
                        text += chunk;
                    });
                    res.on('end', function () {
                        try {
                            resolve(handler(text));
                        } catch (e) {
                            reject(e);
                        }
                    });
                } else {
                    resolve();
                }
            } else {
                var text = 'Error: ' + res.statusCode + ' for ' + options.method + ' on ' + options.path;
                console.error(text);
                text += ' ';
                res.setEncoding('utf8');
                res.on('data', function (chunk) {
                    text += chunk;
                });
                res.on('end', function () {
                    reject(new Error(text));
                });
            }
        });
        req.on('error', function(e) {
            console.error('Error: ' + e.message + ' for ' + options.method + ' on ' + options.path);
            reject(e);
        });
        if (body) {
            req.write(body);
        }
        req.end();
    });
}

AddressCtrl.prototype.create_address = function (address) {
    var data = {
        "apiVersion": "enmasse.io/v1",
        "kind": "AddressList",
        "items" : [
            {
                "metadata": {
                    "name": address.address
                },
                "spec": {
                    "address": address.address,
                    "type": address.type,
                    "plan": address.plan
                }
            }
        ]
    };
    return this.request(this.addr_path, 'POST', {'content-type': 'application/json'}, JSON.stringify(data));
}

AddressCtrl.prototype.delete_address = function(address) {
    return this.request(this.addr_path + address.address, 'DELETE');
}

function index(list) {
    return list.reduce(function (map, item) { map[item.name] = item; return map; }, {});
}

function address_types(text) {
    var object = JSON.parse(text);
    if (object.kind === 'Schema') {
        //TODO: retrieve type for current address-space (assume 'standard' for now)
        return index(object.spec.addressSpaceTypes)['standard'].addressTypes;
    } else {
        throw new Error('Unexpected object kind: ' + object.kind);
    }
}

AddressCtrl.prototype.get_address_types = function () {
    return this.request('/v1/schema/', 'GET', undefined, undefined, address_types);
}

module.exports.create = function () {
    var host = 'localhost';
    var port = 8080;
    if (process.env.ADDRESS_SPACE_SERVICE_HOST) {
        host = process.env.ADDRESS_SPACE_SERVICE_HOST;
    } else if (process.env.ADDRESS_CONTROLLER_SERVICE_HOST) {
        host = process.env.ADDRESS_CONTROLLER_SERVICE_HOST;
        if (process.env.ADDRESS_CONTROLLER_SERVICE_PORT_HTTPS) {
            port = process.env.ADDRESS_CONTROLLER_SERVICE_PORT_HTTPS;
        }
    }
    var ca = undefined;
    if (process.env.ADDRESS_CONTROLLER_CA) {
        ca = fs.readFileSync(process.env.ADDRESS_CONTROLLER_CA);
    }

    var auth_string = undefined;
    if (process.env.ADDRESS_SPACE_PASSWORD_FILE) {
        auth_string = 'Basic ' + new Buffer(process.env.ADDRESS_SPACE + ":" + fs.readFileSync(process.env.ADDRESS_SPACE_PASSWORD_FILE)).toString('base64');
    }

    return new AddressCtrl(host, port, ca, auth_string);
};
<|endoftext|>


<commit_before>/* jshint strict: false, sub: true */
/* global */
'use strict';

// //////////////////////////////////////////////////////////////////////////////
// / DISCLAIMER
// /
// / Copyright 2016 ArangoDB GmbH, Cologne, Germany
// / Copyright 2014 triagens GmbH, Cologne, Germany
// /
// / 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.
// /
// / Copyright holder is ArangoDB GmbH, Cologne, Germany
// /
// / @author Max Neunhoeffer
// //////////////////////////////////////////////////////////////////////////////

const functionsDocumentation = {
  'catch': 'catch test suites'
};
const optionsDocumentation = [
  '   - `skipCache`: if set to true, the hash cache unittests are skipped',
  '   - `skipCatch`: if set to true the catch unittests are skipped',
  '   - `skipGeo`: if set to true the geo index tests are skipped'
];

const fs = require('fs');
const pu = require('@arangodb/process-utils');

// //////////////////////////////////////////////////////////////////////////////
// / @brief TEST: Catch
// //////////////////////////////////////////////////////////////////////////////

function locateCatchTest (name) {
  var file = fs.join(pu.UNITTESTS_DIR, name + pu.executableExt);

  if (!fs.exists(file)) {
    return '';
  }
  return file;
}

function catchRunner (options) {
  let results = {};
  let rootDir = pu.UNITTESTS_DIR;

  const icuDir = pu.UNITTESTS_DIR + '/';
  require('internal').env.ICU_DATA = icuDir;
  const run = locateCatchTest('arangodbtests');
  if (!options.skipCatch) {
    if (run !== '') {
      let argv = [
        '[exclude:longRunning][exclude:cache]',
        '-r',
        'junit',
        '-o',
        fs.join('out', 'catch-standard.xml')];
      results.basics = pu.executeAndWait(run, argv, options, 'all-catch', rootDir);
    } else {
      results.basics = {
        status: false,
        message: 'binary "basics_suite" not found'
      };
    }
  }

  if (!options.skipCache) {
    if (run !== '') {
      let argv = ['[cache]',
                  '-r',
                  'junit',
                  '-o',
                  fs.join('out', 'catch-cache.xml')
                 ];
      results.cache_suite = pu.executeAndWait(run, argv, options,
                                           'cache_suite', rootDir);
    } else {
      results.cache_suite = {
        status: false,
        message: 'binary "cache_suite" not found'
      };
    }
  }

  if (!options.skipGeo) {
    if (run !== '') {
      let argv = ['[geo]',
                  '-r',
                  'junit',
                  '-o',
                  fs.join('out', 'catch-geo.xml')
                 ];
      results.geo_suite = pu.executeAndWait(run, argv, options, 'geo_suite', rootDir);
    } else {
      results.geo_suite = {
        status: false,
        message: 'binary "geo_suite" not found'
      };
    }
  }

  return results;
}

function setup (testFns, defaultFns, opts, fnDocs, optionsDoc) {
  testFns['catch'] = catchRunner;
  testFns['boost'] = catchRunner;

  opts['skipCatch'] = false;
  opts['skipCache'] = true;
  opts['skipGeo'] = false;

  defaultFns.push('catch');

  for (var attrname in functionsDocumentation) { fnDocs[attrname] = functionsDocumentation[attrname]; }
  for (var i = 0; i < optionsDocumentation.length; i++) { optionsDoc.push(optionsDocumentation[i]); }
}

exports.setup = setup;
<commit_msg>exclude longrunning tests<commit_after>/* jshint strict: false, sub: true */
/* global */
'use strict';

// //////////////////////////////////////////////////////////////////////////////
// / DISCLAIMER
// /
// / Copyright 2016 ArangoDB GmbH, Cologne, Germany
// / Copyright 2014 triagens GmbH, Cologne, Germany
// /
// / 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.
// /
// / Copyright holder is ArangoDB GmbH, Cologne, Germany
// /
// / @author Max Neunhoeffer
// //////////////////////////////////////////////////////////////////////////////

const functionsDocumentation = {
  'catch': 'catch test suites'
};
const optionsDocumentation = [
  '   - `skipCache`: if set to true, the hash cache unittests are skipped',
  '   - `skipCatch`: if set to true the catch unittests are skipped',
  '   - `skipGeo`: if set to true the geo index tests are skipped'
];

const fs = require('fs');
const pu = require('@arangodb/process-utils');

// //////////////////////////////////////////////////////////////////////////////
// / @brief TEST: Catch
// //////////////////////////////////////////////////////////////////////////////

function locateCatchTest (name) {
  var file = fs.join(pu.UNITTESTS_DIR, name + pu.executableExt);

  if (!fs.exists(file)) {
    return '';
  }
  return file;
}

function catchRunner (options) {
  let results = {};
  let rootDir = pu.UNITTESTS_DIR;

  const icuDir = pu.UNITTESTS_DIR + '/';
  require('internal').env.ICU_DATA = icuDir;
  const run = locateCatchTest('arangodbtests');
  if (!options.skipCatch) {
    if (run !== '') {
      let argv = [
        '[exclude:longRunning][exclude:cache]',
        '-r',
        'junit',
        '-o',
        fs.join('out', 'catch-standard.xml')];
      results.basics = pu.executeAndWait(run, argv, options, 'all-catch', rootDir);
    } else {
      results.basics = {
        status: false,
        message: 'binary "basics_suite" not found'
      };
    }
  }

  if (!options.skipCache) {
    if (run !== '') {
      let argv = ['[cache][exclude:longRunning]',
                  '-r',
                  'junit',
                  '-o',
                  fs.join('out', 'catch-cache.xml')
                 ];
      results.cache_suite = pu.executeAndWait(run, argv, options,
                                           'cache_suite', rootDir);
    } else {
      results.cache_suite = {
        status: false,
        message: 'binary "cache_suite" not found'
      };
    }
  }

  if (!options.skipGeo) {
    if (run !== '') {
      let argv = ['[geo]',
                  '-r',
                  'junit',
                  '-o',
                  fs.join('out', 'catch-geo.xml')
                 ];
      results.geo_suite = pu.executeAndWait(run, argv, options, 'geo_suite', rootDir);
    } else {
      results.geo_suite = {
        status: false,
        message: 'binary "geo_suite" not found'
      };
    }
  }

  return results;
}

function setup (testFns, defaultFns, opts, fnDocs, optionsDoc) {
  testFns['catch'] = catchRunner;
  testFns['boost'] = catchRunner;

  opts['skipCatch'] = false;
  opts['skipCache'] = true;
  opts['skipGeo'] = false;

  defaultFns.push('catch');

  for (var attrname in functionsDocumentation) { fnDocs[attrname] = functionsDocumentation[attrname]; }
  for (var i = 0; i < optionsDocumentation.length; i++) { optionsDoc.push(optionsDocumentation[i]); }
}

exports.setup = setup;
<|endoftext|>


<commit_before>import {MAX_SAFE_INTEGER} from './input-tags.constants';
import AutoCompleteComponent from './auto-complete.component';
import './input-tags.style.scss';

/**
 * @ngdoc component
 * @name inputTags
 * @module angularjs-input-tags
 *
 * @description
 * Renders an input box with tag editing support.
 */
class InputTags {
  $onInit() {
    this.autocompleteVisible = false;

    this.tags = this.tags || [];
    this.suggestions = this.suggestions || {};
    this.displayProperty = this.displayProperty || 'text';
    this.keyProperty = this.keyProperty || '';
    this.placeholder = this.placeholder || 'Add a tag';
    this.spellcheck = this.spellcheck || true;
    this.minLength = this.minLength || 1;
    this.maxLength = this.maxLength || MAX_SAFE_INTEGER;
    this.inputDebounce = this.inputDebounce || 125;
  }

  track(tag) {
    return tag[this.keyProperty || this.displayProperty];
  }

  getTagText(tag) {
    return tag[this.displayProperty];
  }

  addTag(tag) {
    const tagText = this.getTagText(tag);
    const key = this.keyProperty || this.displayProperty;
    const valid = tagText &&
      tagText.length >= this.minLength &&
      tagText.length <= this.maxLength &&
      !this.tags.some(element => element[key] === tag[key]);

    if (this.onTagAdding) {
      this.onTagAdding(tag);
    }

    if (valid) {
      this.tags.push(tag);

      if (this.onTagAdded) {
        this.onTagAdded(tag);
      }
    } else if (this.onTagAddFailed) {
      this.onTagAddFailed(tag);
    }

    return tag;
  }

  removeTag(tag) {

    if (this.onTagRemoving) {
      this.onTagRemoving(tag);
    }

    for (let i = this.tags.length - 1; i >= 0; i--) {
      if (this.tags[i].code === tag.code) {
        this.tags.splice(i, 1);
      }
    }

    if (this.onTagRemoved) {
      this.onTagRemoved(tag);
    }

    return tag;
  }

  inputChange() {
    if (this.getSuggestions) {
      this.getSuggestions(this.inputSearch);
    }
  }

  triggerFocus() {
    this.autocompleteVisible = true;
  }

  triggerBlur() {
    this.autocompleteVisible = false;
  }
}

const InputTagsComponent = {
  template: require('./input-tags.template.html'),
  controller: InputTags,
  bindings: {
    displayProperty: '@',
    keyProperty: '@',
    placeholder: '@',
    tabindex: '@',
    spellcheck: '@',
    minLength: '@',
    maxLength: '@',
    inputDebounce: '@',
    tags: '<',
    suggestions: '<',
    disabled: '<',
    getSuggestions: '<',
    onTagAdding: '<',
    onTagAdded: '<',
    onTagAddFailed: '<',
    onTagRemoving: '<',
    onTagRemoved: '<',
    onTagClicked: '<'
  }
};

angular.module('angularjs-input-tags', [])
  .component('inputTags', InputTagsComponent)
  .component('inputTagsAutoComplete', AutoCompleteComponent);
<commit_msg>Add TODO<commit_after>import {MAX_SAFE_INTEGER} from './input-tags.constants';
import AutoCompleteComponent from './auto-complete.component';
import './input-tags.style.scss';

/**
 * @ngdoc component
 * @name inputTags
 * @module angularjs-input-tags
 *
 * @description
 * Renders an input box with tag editing support.
 */
class InputTags {
  $onInit() {
    this.autocompleteVisible = false;

    this.tags = this.tags || [];
    this.suggestions = this.suggestions || {};
    this.displayProperty = this.displayProperty || 'text';
    this.keyProperty = this.keyProperty || '';
    this.placeholder = this.placeholder || 'Add a tag';
    this.spellcheck = this.spellcheck || true;
    this.minLength = this.minLength || 1;
    this.maxLength = this.maxLength || MAX_SAFE_INTEGER;
    this.inputDebounce = this.inputDebounce || 125;
  }

  track(tag) {
    return tag[this.keyProperty || this.displayProperty];
  }

  getTagText(tag) {
    return tag[this.displayProperty];
  }

  addTag(tag) {
    const tagText = this.getTagText(tag);
    const key = this.keyProperty || this.displayProperty;
    const valid = tagText &&
      tagText.length >= this.minLength &&
      tagText.length <= this.maxLength &&
      !this.tags.some(element => element[key] === tag[key]);

    if (this.onTagAdding) {
      this.onTagAdding(tag);
    }

    if (valid) {
      this.tags.push(tag);

      if (this.onTagAdded) {
        this.onTagAdded(tag);
      }
    } else if (this.onTagAddFailed) {
      this.onTagAddFailed(tag);
    }

    return tag;
  }

  removeTag(tag) {

    if (this.onTagRemoving) {
      this.onTagRemoving(tag);
    }

    for (let i = this.tags.length - 1; i >= 0; i--) {
      if (this.tags[i].code === tag.code) {
        this.tags.splice(i, 1);
      }
    }

    if (this.onTagRemoved) {
      this.onTagRemoved(tag);
    }

    return tag;
  }

  inputChange() {
    // TODO: Rename `getSuggestions` into something like `inputChanged`
    if (this.getSuggestions) {
      this.getSuggestions(this.inputSearch);
    }
  }

  triggerFocus() {
    this.autocompleteVisible = true;
  }

  triggerBlur() {
    this.autocompleteVisible = false;
  }
}

const InputTagsComponent = {
  template: require('./input-tags.template.html'),
  controller: InputTags,
  bindings: {
    displayProperty: '@',
    keyProperty: '@',
    placeholder: '@',
    tabindex: '@',
    spellcheck: '@',
    minLength: '@',
    maxLength: '@',
    inputDebounce: '@',
    tags: '<',
    suggestions: '<',
    disabled: '<',
    getSuggestions: '<',
    onTagAdding: '<',
    onTagAdded: '<',
    onTagAddFailed: '<',
    onTagRemoving: '<',
    onTagRemoved: '<',
    onTagClicked: '<'
  }
};

angular.module('angularjs-input-tags', [])
  .component('inputTags', InputTagsComponent)
  .component('inputTagsAutoComplete', AutoCompleteComponent);
<|endoftext|>


<commit_before>import _ from 'lodash'
import AbstractInput from './abstract-input'
import computed, {readOnly} from 'ember-computed-decorators'
import layout from 'ember-frost-bunsen/templates/components/frost-bunsen-input-checkbox-array'
import Ember from 'ember'
const {get, isEmpty} = Ember

export default AbstractInput.extend({
  // == Component Properties ===================================================

  classNames: [
    'frost-bunsen-input-checkbox-array',
    'frost-field'
  ],

  layout,

  // == State Properties =======================================================

  getDefaultProps () {
    return {
      selected: []
    }
  },

  // == Computed Properties ====================================================
  @readOnly
  @computed('cellConfig')
  size (cellConfig) {
    return _.get(cellConfig, 'renderer.size') || 'medium'
  },

  @readOnly
  @computed('bunsenModel', 'cellConfig', 'value')
  options (bunsenModel, cellConfig, value) {
    const items = get(bunsenModel, 'items.enum') || []
    const labels = get(cellConfig, 'renderer.labels') || []

    value = value || []

    return items.map((item) => {
      return {
        checked: value.indexOf(item) > -1,
        label: labels[item] || item,
        value: item
      }
    })
  },

  // == Functions ==============================================================
  /**
   * Convert value to appropriate format for template
   * @param {Boolean|String} data - value to parse
   * @returns {any} parsed value
   */
  parseValue (data) {
    var selected = this.get('selected')
    if (data.value) {
      selected.push(data.id)
    } else {
      var index = selected.indexOf(data.id)
      selected.splice(index, 1)
    }
    return selected
  }
})
<commit_msg>removed unused value<commit_after>import _ from 'lodash'
import AbstractInput from './abstract-input'
import computed, {readOnly} from 'ember-computed-decorators'
import layout from 'ember-frost-bunsen/templates/components/frost-bunsen-input-checkbox-array'
import Ember from 'ember'
const {get} = Ember

export default AbstractInput.extend({
  // == Component Properties ===================================================

  classNames: [
    'frost-bunsen-input-checkbox-array',
    'frost-field'
  ],

  layout,

  // == State Properties =======================================================

  getDefaultProps () {
    return {
      selected: []
    }
  },

  // == Computed Properties ====================================================
  @readOnly
  @computed('cellConfig')
  size (cellConfig) {
    return _.get(cellConfig, 'renderer.size') || 'medium'
  },

  @readOnly
  @computed('bunsenModel', 'cellConfig', 'value')
  options (bunsenModel, cellConfig, value) {
    const items = get(bunsenModel, 'items.enum') || []
    const labels = get(cellConfig, 'renderer.labels') || []

    value = value || []

    return items.map((item) => {
      return {
        checked: value.indexOf(item) > -1,
        label: labels[item] || item,
        value: item
      }
    })
  },

  // == Functions ==============================================================
  /**
   * Convert value to appropriate format for template
   * @param {Boolean|String} data - value to parse
   * @returns {any} parsed value
   */
  parseValue (data) {
    var selected = this.get('selected')
    if (data.value) {
      selected.push(data.id)
    } else {
      var index = selected.indexOf(data.id)
      selected.splice(index, 1)
    }
    return selected
  }
})
<|endoftext|>


<commit_before>/* eslint-disable no-console */
/* eslint-disable no-fallthrough */
// <nowiki>

(function() {

	/* 反importScript */
	var whitelist = ["Xiplus", "A2093064-test", "A2093064-bot"];
	if (whitelist.indexOf(mw.config.get('wgUserName')) === -1) {
		alert("請勿importScript User:Xiplus/global.js！可能有未預期的危害發生。");
		return;
	}

	console.log("using User:Xiplus/global.js");

	mw.loader.using(['mediawiki.util']).done(function() {
		/* mediawiki.util */

		// mw.loader.load('https://xiplus.ddns.net/Xiplus-zhWP/APIedit.js');
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/APIedit.js&action=raw&ctype=text/javascript');
		mw.loader.using(['mediawiki.util']).done(function() {
			mw.loader.load('https://en.wikipedia.org/w/index.php?title=MediaWiki:Gadget-ShowMessageNames.js&oldid=554722666&action=raw&ctype=text/javascript'); // 08:46, 5 August 2018 (UTC)
		});
		// [[File:Krinkle_CVNSimpleOverlay_wiki.js]]
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Krinkle/Scripts/CVNSimpleOverlay_wiki.js&oldid=18174822&action=raw&ctype=text/javascript'); // 08:46, 5 August 2018 (UTC)
		mw.loader.load("https://zh.wikipedia.org/w/index.php?title=User:Bluedeck/serve/edit-count.js&oldid=49623399&action=raw&ctype=text/javascript"); // 08:46, 5 August 2018 (UTC)
		mw.loader.load('//en.wikipedia.org/w/index.php?title=MediaWiki:Gadget-edittop.js&action=raw&ctype=text/javascript');

		/* wikiplus */
		// mw.loader.load('https://xiplus.ddns.net/Xiplus-zhWP/w.js');
		mw.loader.load('https://wikiplus-app.com/Main.min.js');
		(function() {
			function wikiplusSettingdefaultSummary(w) {
				if (w.sectionNumber == -1) {
					return ' ';
				}
				if (w.sectionNumber === 0) {
					return '/* 首段 */ ';
				}
				return '/* ' + w.sectionName + ' */ ';
			}
			var wikiplusSetting = {
				"defaultSummary": wikiplusSettingdefaultSummary.toString().replace(/\s+/g, " "),
				"documatation": "http://zh.moegirl.org/User:%E5%A6%B9%E7%A9%BA%E9%85%B1/Wikiplus/%E8%AE%BE%E7%BD%AE%E8%AF%B4%E6%98%8E"
			};
			localStorage.setItem("Wikiplus_Settings", JSON.stringify(wikiplusSetting));
		})();

		/* XTools */
		mw.loader.load('https://www.mediawiki.org/w/index.php?title=XTools/ArticleInfo.js&oldid=2625658&action=raw&ctype=text/javascript'); // 08:46, 5 August 2018 (UTC)

		/* FakeRollback */
		if ($.inArray('sysop', mw.config.get('wgUserGroups')) === -1) {
			mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:WhitePhosphorus/js/FakeRollback.js&action=raw&ctype=text/javascript');
		}

		/* AutoUndo */
		if ($.inArray('sysop', mw.config.get('wgUserGroups')) === -1) {
			mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:WhitePhosphorus/js/AutoUndo.js&action=raw&ctype=text/javascript');
		}

		/* AutoUndoGlobal */
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:WhitePhosphorus/js/AutoUndoGlobal.js&action=raw&ctype=text/javascript');

		/* cvn-smart */
		// mw.loader.load('https://xiplus.ddns.net/wikipedia_rc/gadget.js');
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/cvn-smart-gadget.js&action=raw&ctype=text/javascript');

		/* history-merge */
		if ($.inArray('sysop', mw.config.get('wgUserGroups')) !== -1) {
			mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/history-merge.js&action=raw&ctype=text/javascript');
		}

		/* list-user-last-active */
		switch (mw.config.get('wgDBname')) {
			case 'zhwiki':
				break;
			default:
				mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/list-user-last-active.js&action=raw&ctype=text/javascript');
				break;
		}

		/* smart rollback */
		if (typeof window.smartRollbackConfig === 'undefined') {
			window.smartRollbackConfig = {};
		}
		var smartRollbackConfig = window.smartRollbackConfig;
		smartRollbackConfig.toolLinkMethod = 'p-tb';
		smartRollbackConfig.editSummaries = ['批量回退無意義文字', '批量回退破壞'];
		mw.loader.load('//meta.wikimedia.org/w/index.php?title=User:Hoo_man/smart_rollback.js&action=raw&ctype=text/javascript');

		/* get-translatewiki-link */
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/get-translatewiki-link.js&action=raw&ctype=text/javascript');

		/* UTC clock */
		mw.loader.load('//www.mediawiki.org/w/index.php?title=MediaWiki:Gadget-UTCLiveClock.js&action=raw&ctype=text/javascript');

		/* CentralAuth */
		function showCentralAuth(username) {
			if (username === undefined) {
				return;
			}
			if (mw.util.isIPAddress(username, true)) {
				username = username.replace(/\/\d+$/, '');
				mw.util.addPortletLink(
					'p-cactions',
					'https://tools.wmflabs.org/meta/stalktoy/' + username,
					'全域封禁'
				);
				mw.util.addPortletLink(
					'p-cactions',
					'https://whatismyipaddress.com/ip/' + username,
					'地理位置'
				);
				mw.util.addPortletLink(
					'p-cactions',
					'http://whois.tanet.edu.tw/showWhoisPublic.php?queryString=' + username,
					'TANet'
				);
				mw.util.addPortletLink(
					'p-cactions',
					'https://tools.wmflabs.org/ipcheck/index.php?ip=' + username,
					'Proxy Checker'
				);
			} else {
				mw.util.addPortletLink(
					'p-cactions',
					mw.config.get('wgServer') + mw.config.get('wgArticlePath').replace('$1', 'Special:CentralAuth') + '?target=' + encodeURIComponent(username),
					'全域帳號'
				);
			}
			mw.util.addPortletLink(
				'p-cactions',
				'https://xtools.wmflabs.org/globalcontribs/' + username,
				'全域貢獻 (xtools)'
			);
			mw.util.addPortletLink(
				'p-cactions',
				'https://tools.wmflabs.org/guc/?by=date&user=' + username,
				'全域貢獻 (guc)'
			);
		}
		if (mw.config.get('wgNamespaceNumber') === 2 || mw.config.get('wgNamespaceNumber') === 3) {
			showCentralAuth(mw.config.get('wgTitle').replace(/^([^/]+).*$/, '$1'));
		} else if (mw.config.get('wgRelevantUserName') !== null) {
			showCentralAuth(mw.config.get('wgRelevantUserName'));
		} else if (mw.config.get('wgCanonicalSpecialPageName') === 'Contributions') {
			showCentralAuth($('[name="target"]').val());
		}

		/* Admin list */
		switch (mw.config.get('wgDBname')) {
			// case 'zh_classicalwiki':
			// case 'zh_yuewiki':
			case 'zhwiki':
				// case 'zhwikibooks':
				// case 'zhwikinews':
				// case 'zhwikiquote':
				// case 'zhwikisource':
				// case 'zhwikivoyage':
				// case 'zhwiktionary':
				break;
			default:
				mw.util.addPortletLink(
					'p-cactions',
					mw.config.get('wgServer') + mw.config.get('wgArticlePath').replace('$1', 'Special:Userlist') + '?group=sysop',
					'管理員列表'
				);
		}

		/* Twinkle */
		switch (mw.config.get('wgDBname')) {
			case 'enwiki':
			// case 'simplewiki':
			case 'test2wiki':
			case 'zh_classicalwiki':
			case 'zhwiki':
			case 'zhwikibooks':
			// case 'zhwikinews':
			case 'zhwikiquote':
			// case 'zhwikisource':
			case 'zhwikiversity':
			case 'zhwikivoyage':
			case 'zhwiktionary':
				break;
			default:
				console.log("載入 Gadget-site-lib.js");
				mw.loader.load('//zh.wikipedia.org/w/index.php?title=MediaWiki:Gadget-site-lib.js&action=raw&ctype=text/javascript');
				console.log("測試版Twinkle");
				mw.loader.using(['mediawiki.user', 'mediawiki.util', 'mediawiki.RegExp', 'mediawiki.Title', 'jquery.ui.dialog', 'jquery.tipsy']).done(function() {
					console.log("Loading");
					mw.loader.load('//zh.wikipedia.org/w/index.php?title=User:Xiplus/Twinkle-dev.js&action=raw&ctype=text/javascript');
				});
				break;
		}

		/* Popup */
		switch (mw.config.get('wgDBname')) {
			case 'enwiki':
			case 'zhwiki':
				break;
			default:
				console.log("載入 A2569875Popup");
				mw.loader.load('//zh.wikipedia.org/w/index.php?title=User:A2569875-sandbox/MyPopupsSetting_zh-hant.js&action=raw&ctype=text/javascript');
				mw.loader.load('//zh.wikipedia.org/w/index.php?title=User:A2569875-sandbox/MyPopups.css&action=raw&ctype=text/css', 'text/css');
				break;
		}

		/* tagger */
		if ($.inArray('sysop', mw.config.get('wgUserGroups')) === -1) {
			switch (mw.config.get('wgDBname')) {
				case 'enwiki':
					break;
				default:
					if (typeof (window.taggerConfig) == 'undefined') window.taggerConfig = {};
					var taggerConfig = window.taggerConfig;
					taggerConfig.noDeleteOnly = false;

					if (typeof (taggerConfig) == 'undefined') taggerConfig = {};
					taggerConfig.tags = [];
					taggerConfig.editSummary = [];
					taggerConfig.tags[1] = '{{delete|Vandalism}}';
					taggerConfig.editSummary[taggerConfig.tags[1]] = '+delete';
					taggerConfig.tags[2] = '{{delete|Nonsense}}';
					taggerConfig.editSummary[taggerConfig.tags[2]] = '+delete';
					taggerConfig.tags[3] = '{{delete|Vandalism. Created by LTA from zhwiki.}}';
					taggerConfig.editSummary[taggerConfig.tags[3]] = '+delete';
					taggerConfig.tags.other = 'This is used for the option you have to select to be able to insert a custom template';
					mw.loader.load('//meta.wikimedia.org/w/index.php?title=User:Hoo_man/tagger.js&action=raw&ctype=text/javascript');
					break;
			}
		}

		/* 側欄 */
		mw.util.addPortletLink(
			'p-tb',
			'/wiki/Special:PrefixIndex/' + mw.config.get('wgPageName'),
			'前綴索引',
			't-prefixindex',
			'',
			'',
			$('#t-specialpages')
		);

		if (mw.config.get("wgNamespaceNumber") == 8) {
			mw.util.addPortletLink(
				'p-cactions',
				'https://translatewiki.net/wiki/' + mw.config.get("wgPageName").split("/")[0] + '/zh-hant?action=edit',
				'translatewiki'
			);
		}

		mw.loader.using(['mediawiki.api']).done(function() {
			new mw.Api().get({
				action: "query",
				format: "json",
				list: "logevents",
				leprop: "comment|type",
				letype: "delete",
				letitle: mw.config.get('wgPageName')
			}).then(function(data) {
				for (var i = 0; i < data.query.logevents.length; i++) {
					var comment = data.query.logevents[i].comment;
					console.log(comment);
				}
			});
		});

		/* mediawiki.util */
	});

	/* CurIDLink */
	mw.loader.using(['mediawiki.api', 'mediawiki.ForeignApi', 'mediawiki.notify']).then(function() {
		if (mw.config.get('wgDBname') === 'metawiki') {
			var api = new mw.Api();
		} else {
			var api = new mw.ForeignApi('//meta.wikimedia.org/w/api.php');
		}
		api.loadMessagesIfMissing(['Link-by-id', 'Link-by-id-desc']).then(function() {
			mw.loader.load('https://meta.wikimedia.org/w/index.php?title=MediaWiki:Gadget-CurIDLink.js&action=raw&ctype=text/javascript');
		}, function() {
			mw.notify('Load CurIDLink messages failed', { type: 'error' })
		});
	}, function() {
		console.error('Load CurIDLink dependencies failed');
	});

	/* shortURL */
	mw.loader.using(['mediawiki.util', 'oojs-ui', 'mediawiki.ForeignApi', 'mediawiki.notify']).done(function() {
		mw.loader.getScript('https://zh.wikipedia.org/w/index.php?title=MediaWiki:Gadget-site-lib.js&action=raw&ctype=text/javascript').then(function() {
			mw.loader.load('https://zh.wikipedia.org/w/index.php?title=MediaWiki:Gadget-shortURL.js&action=raw&ctype=text/javascript');
		});
	});

	console.log("global.js end");

})();

// </nowiki>
<commit_msg>Update interface-global.js<commit_after>/* eslint-disable no-console */
/* eslint-disable no-fallthrough */
// <nowiki>

(function() {

	/* 反importScript */
	var whitelist = ["Xiplus", "A2093064-test", "A2093064-bot"];
	if (whitelist.indexOf(mw.config.get('wgUserName')) === -1) {
		alert("請勿importScript User:Xiplus/global.js！可能有未預期的危害發生。");
		return;
	}

	console.log("using User:Xiplus/global.js");

	mw.loader.using(['mediawiki.util']).done(function() {
		/* mediawiki.util */

		// mw.loader.load('https://xiplus.ddns.net/Xiplus-zhWP/APIedit.js');
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/APIedit.js&action=raw&ctype=text/javascript');
		mw.loader.using(['mediawiki.util']).done(function() {
			mw.loader.load('https://en.wikipedia.org/w/index.php?title=MediaWiki:Gadget-ShowMessageNames.js&oldid=554722666&action=raw&ctype=text/javascript'); // 08:46, 5 August 2018 (UTC)
		});
		// [[File:Krinkle_CVNSimpleOverlay_wiki.js]]
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Krinkle/Scripts/CVNSimpleOverlay_wiki.js&oldid=18174822&action=raw&ctype=text/javascript'); // 08:46, 5 August 2018 (UTC)
		mw.loader.load("https://zh.wikipedia.org/w/index.php?title=User:Bluedeck/serve/edit-count.js&oldid=49623399&action=raw&ctype=text/javascript"); // 08:46, 5 August 2018 (UTC)
		mw.loader.load('//en.wikipedia.org/w/index.php?title=MediaWiki:Gadget-edittop.js&action=raw&ctype=text/javascript');

		/* wikiplus */
		// mw.loader.load('https://xiplus.ddns.net/Xiplus-zhWP/w.js');
		mw.loader.load('https://wikiplus-app.com/Main.min.js');
		(function() {
			function wikiplusSettingdefaultSummary(w) {
				if (w.sectionNumber == -1) {
					return ' ';
				}
				if (w.sectionNumber === 0) {
					return '/* 首段 */ ';
				}
				return '/* ' + w.sectionName + ' */ ';
			}
			var wikiplusSetting = {
				"defaultSummary": wikiplusSettingdefaultSummary.toString().replace(/\s+/g, " "),
				"documatation": "http://zh.moegirl.org/User:%E5%A6%B9%E7%A9%BA%E9%85%B1/Wikiplus/%E8%AE%BE%E7%BD%AE%E8%AF%B4%E6%98%8E"
			};
			localStorage.setItem("Wikiplus_Settings", JSON.stringify(wikiplusSetting));
		})();

		/* XTools */
		mw.loader.load('https://www.mediawiki.org/w/index.php?title=XTools/ArticleInfo.js&oldid=2625658&action=raw&ctype=text/javascript'); // 08:46, 5 August 2018 (UTC)

		/* FakeRollback */
		if ($.inArray('sysop', mw.config.get('wgUserGroups')) === -1) {
			mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:WhitePhosphorus/js/FakeRollback.js&action=raw&ctype=text/javascript');
		}

		/* AutoUndo */
		if ($.inArray('sysop', mw.config.get('wgUserGroups')) === -1) {
			mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:WhitePhosphorus/js/AutoUndo.js&action=raw&ctype=text/javascript');
		}

		/* AutoUndoGlobal */
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:WhitePhosphorus/js/AutoUndoGlobal.js&action=raw&ctype=text/javascript');

		/* cvn-smart */
		// mw.loader.load('https://xiplus.ddns.net/wikipedia_rc/gadget.js');
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/cvn-smart-gadget.js&action=raw&ctype=text/javascript');

		/* history-merge */
		if ($.inArray('sysop', mw.config.get('wgUserGroups')) !== -1) {
			mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/history-merge.js&action=raw&ctype=text/javascript');
		}

		/* list-user-last-active */
		switch (mw.config.get('wgDBname')) {
			case 'zhwiki':
				break;
			default:
				mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/list-user-last-active.js&action=raw&ctype=text/javascript');
				break;
		}

		/* smart rollback */
		if (typeof window.smartRollbackConfig === 'undefined') {
			window.smartRollbackConfig = {};
		}
		var smartRollbackConfig = window.smartRollbackConfig;
		smartRollbackConfig.toolLinkMethod = 'p-tb';
		smartRollbackConfig.editSummaries = ['批量回退無意義文字', '批量回退破壞'];
		mw.loader.load('//meta.wikimedia.org/w/index.php?title=User:Hoo_man/smart_rollback.js&action=raw&ctype=text/javascript');

		/* get-translatewiki-link */
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/get-translatewiki-link.js&action=raw&ctype=text/javascript');

		/* UTC clock */
		mw.loader.load('//www.mediawiki.org/w/index.php?title=MediaWiki:Gadget-UTCLiveClock.js&action=raw&ctype=text/javascript');

		/* CentralAuth */
		function showCentralAuth(username) {
			if (username === undefined) {
				return;
			}
			if (mw.util.isIPAddress(username, true)) {
				username = username.replace(/\/\d+$/, '');
				mw.util.addPortletLink(
					'p-cactions',
					'https://tools.wmflabs.org/meta/stalktoy/' + username,
					'全域封禁'
				);
				mw.util.addPortletLink(
					'p-cactions',
					'https://whatismyipaddress.com/ip/' + username,
					'地理位置'
				);
				mw.util.addPortletLink(
					'p-cactions',
					'http://whois.tanet.edu.tw/showWhoisPublic.php?queryString=' + username,
					'TANet'
				);
				mw.util.addPortletLink(
					'p-cactions',
					'https://tools.wmflabs.org/ipcheck/index.php?ip=' + username,
					'Proxy Checker'
				);
			} else {
				mw.util.addPortletLink(
					'p-cactions',
					mw.config.get('wgServer') + mw.config.get('wgArticlePath').replace('$1', 'Special:CentralAuth') + '?target=' + encodeURIComponent(username),
					'全域帳號'
				);
			}
			mw.util.addPortletLink(
				'p-cactions',
				'https://xtools.wmflabs.org/globalcontribs/' + username,
				'全域貢獻 (xtools)'
			);
			mw.util.addPortletLink(
				'p-cactions',
				'https://tools.wmflabs.org/guc/?by=date&user=' + username,
				'全域貢獻 (guc)'
			);
		}
		if (mw.config.get('wgNamespaceNumber') === 2 || mw.config.get('wgNamespaceNumber') === 3) {
			showCentralAuth(mw.config.get('wgTitle').replace(/^([^/]+).*$/, '$1'));
		} else if (mw.config.get('wgRelevantUserName') !== null) {
			showCentralAuth(mw.config.get('wgRelevantUserName'));
		} else if (mw.config.get('wgCanonicalSpecialPageName') === 'Contributions') {
			showCentralAuth($('[name="target"]').val());
		}

		/* Admin list */
		switch (mw.config.get('wgDBname')) {
			// case 'zh_classicalwiki':
			// case 'zh_yuewiki':
			case 'zhwiki':
				// case 'zhwikibooks':
				// case 'zhwikinews':
				// case 'zhwikiquote':
				// case 'zhwikisource':
				// case 'zhwikivoyage':
				// case 'zhwiktionary':
				break;
			default:
				mw.util.addPortletLink(
					'p-cactions',
					mw.config.get('wgServer') + mw.config.get('wgArticlePath').replace('$1', 'Special:Userlist') + '?group=sysop',
					'管理員列表'
				);
		}

		/* Twinkle */
		switch (mw.config.get('wgDBname')) {
			case 'enwiki':
			case 'simplewiki':
			case 'test2wiki':
			case 'zh_classicalwiki':
			case 'zhwiki':
			case 'zhwikibooks':
			// case 'zhwikinews':
			case 'zhwikiquote':
			// case 'zhwikisource':
			case 'zhwikiversity':
			case 'zhwikivoyage':
			case 'zhwiktionary':
				break;
			default:
				console.log("載入 Gadget-site-lib.js");
				mw.loader.load('//zh.wikipedia.org/w/index.php?title=MediaWiki:Gadget-site-lib.js&action=raw&ctype=text/javascript');
				console.log("測試版Twinkle");
				mw.loader.using(['mediawiki.user', 'mediawiki.util', 'mediawiki.RegExp', 'mediawiki.Title', 'jquery.ui.dialog', 'jquery.tipsy']).done(function() {
					console.log("Loading");
					mw.loader.load('//zh.wikipedia.org/w/index.php?title=User:Xiplus/Twinkle-dev.js&action=raw&ctype=text/javascript');
				});
				break;
		}

		/* Popup */
		switch (mw.config.get('wgDBname')) {
			case 'enwiki':
			case 'zhwiki':
				break;
			default:
				console.log("載入 A2569875Popup");
				mw.loader.load('//zh.wikipedia.org/w/index.php?title=User:A2569875-sandbox/MyPopupsSetting_zh-hant.js&action=raw&ctype=text/javascript');
				mw.loader.load('//zh.wikipedia.org/w/index.php?title=User:A2569875-sandbox/MyPopups.css&action=raw&ctype=text/css', 'text/css');
				break;
		}

		/* tagger */
		if ($.inArray('sysop', mw.config.get('wgUserGroups')) === -1) {
			switch (mw.config.get('wgDBname')) {
				case 'enwiki':
					break;
				default:
					if (typeof (window.taggerConfig) == 'undefined') window.taggerConfig = {};
					var taggerConfig = window.taggerConfig;
					taggerConfig.noDeleteOnly = false;

					if (typeof (taggerConfig) == 'undefined') taggerConfig = {};
					taggerConfig.tags = [];
					taggerConfig.editSummary = [];
					taggerConfig.tags[1] = '{{delete|Vandalism}}';
					taggerConfig.editSummary[taggerConfig.tags[1]] = '+delete';
					taggerConfig.tags[2] = '{{delete|Nonsense}}';
					taggerConfig.editSummary[taggerConfig.tags[2]] = '+delete';
					taggerConfig.tags[3] = '{{delete|Vandalism. Created by LTA from zhwiki.}}';
					taggerConfig.editSummary[taggerConfig.tags[3]] = '+delete';
					taggerConfig.tags.other = 'This is used for the option you have to select to be able to insert a custom template';
					mw.loader.load('//meta.wikimedia.org/w/index.php?title=User:Hoo_man/tagger.js&action=raw&ctype=text/javascript');
					break;
			}
		}

		/* 側欄 */
		mw.util.addPortletLink(
			'p-tb',
			'/wiki/Special:PrefixIndex/' + mw.config.get('wgPageName'),
			'前綴索引',
			't-prefixindex',
			'',
			'',
			$('#t-specialpages')
		);

		if (mw.config.get("wgNamespaceNumber") == 8) {
			mw.util.addPortletLink(
				'p-cactions',
				'https://translatewiki.net/wiki/' + mw.config.get("wgPageName").split("/")[0] + '/zh-hant?action=edit',
				'translatewiki'
			);
		}

		mw.loader.using(['mediawiki.api']).done(function() {
			new mw.Api().get({
				action: "query",
				format: "json",
				list: "logevents",
				leprop: "comment|type",
				letype: "delete",
				letitle: mw.config.get('wgPageName')
			}).then(function(data) {
				for (var i = 0; i < data.query.logevents.length; i++) {
					var comment = data.query.logevents[i].comment;
					console.log(comment);
				}
			});
		});

		/* mediawiki.util */
	});

	/* CurIDLink */
	mw.loader.using(['mediawiki.api', 'mediawiki.ForeignApi', 'mediawiki.notify']).then(function() {
		if (mw.config.get('wgDBname') === 'metawiki') {
			var api = new mw.Api();
		} else {
			var api = new mw.ForeignApi('//meta.wikimedia.org/w/api.php');
		}
		api.loadMessagesIfMissing(['Link-by-id', 'Link-by-id-desc']).then(function() {
			mw.loader.load('https://meta.wikimedia.org/w/index.php?title=MediaWiki:Gadget-CurIDLink.js&action=raw&ctype=text/javascript');
		}, function() {
			mw.notify('Load CurIDLink messages failed', { type: 'error' })
		});
	}, function() {
		console.error('Load CurIDLink dependencies failed');
	});

	/* shortURL */
	mw.loader.using(['mediawiki.util', 'oojs-ui', 'mediawiki.ForeignApi', 'mediawiki.notify']).done(function() {
		mw.loader.getScript('https://zh.wikipedia.org/w/index.php?title=MediaWiki:Gadget-site-lib.js&action=raw&ctype=text/javascript').then(function() {
			mw.loader.load('https://zh.wikipedia.org/w/index.php?title=MediaWiki:Gadget-shortURL.js&action=raw&ctype=text/javascript');
		});
	});

	console.log("global.js end");

})();

// </nowiki>
<|endoftext|>


<commit_before>(function () {

    var updateIntervalMs = 1000;

    (function createLineChart() {
        var randomData = Array(20);
        var last = 0;
        for (var i = 0; i < randomData.length; i++) {
            var num = last + (Math.random() * 2 - 1);
            randomData[i] = num;
            num = last;
        }
        randomData.unshift('header');

        var chart = c3.generate({
            bindto: '#chart-1',
            data: {
                columns: [
                    randomData
                ],
                colors: {
                    data: "#34ccff"
                },
            },
            axis: {
                y: { min: -10, max: 10, padding: { top: 0, bottom: 0} }
            },
            grid: {
                x: { show: true },
                y: { show: true }
            },
            padding: {
                top: 0,
                right: 0,
                bottom: 0,
                left: 20
            },
            legend: { hide: true },
            interaction: { enabled: false },
            transition: { duration: 200 }
        });

        window.setInterval(function () {
            var header = randomData.shift();
            randomData.shift();
            randomData.unshift(header);
            var num = randomData[randomData.length - 1];
            randomData.push(num + (Math.random() * 2 - 1));
            chart.load({
                columns: [randomData]
            });
        }, updateIntervalMs);
    }());

    (function createGaugeCharts() {
        var gaugeElements = document.querySelectorAll('.gauge-chart');
        var gaugeCharts = [];
        for (var el of gaugeElements) {
            var value = Math.random();
            var chart = c3.generate({
                bindto: el,
                size: {
                    width: 100,
                    height: 100
                },
                padding: {
                    top: 0,
                    right: 0,
                    bottom: 0,
                    left: 0
                },
                data: {
                    columns: [
                        ['data', value]
                    ],
                    colors: {
                        data: "#34ccff"
                    },
                    type: 'gauge'
                },
                gauge: {
                    min: 0,
                    max: 1
                },
                interaction: { enabled: false },
            });
            gaugeCharts.push(chart);
        }
        window.setInterval(function () {
            for (var chart of gaugeCharts) {
                var value = Math.random();
                chart.load({
                    columns: [['data', value]]
                });
            }
        }, updateIntervalMs);
    }());

}());
<commit_msg>Allow chart animations to be easily disabled through code<commit_after>(function () {

    var updateIntervalMs = 1000;
    var animate = false;

    (function createLineChart() {
        var randomData = Array(20);
        var last = 0;
        for (var i = 0; i < randomData.length; i++) {
            var num = last + (Math.random() * 2 - 1);
            randomData[i] = num;
            num = last;
        }
        randomData.unshift('header');

        var chart = c3.generate({
            bindto: '#chart-1',
            data: {
                columns: [
                    randomData
                ],
                colors: {
                    data: "#34ccff"
                },
            },
            axis: {
                y: { min: -10, max: 10, padding: { top: 0, bottom: 0} }
            },
            grid: {
                x: { show: true },
                y: { show: true }
            },
            padding: {
                top: 0,
                right: 0,
                bottom: 0,
                left: 20
            },
            legend: { hide: true },
            interaction: { enabled: false },
            transition: { duration: 200 }
        });

        if (!animate) { return; }
        window.setInterval(function () {
            var header = randomData.shift();
            randomData.shift();
            randomData.unshift(header);
            var num = randomData[randomData.length - 1];
            randomData.push(num + (Math.random() * 2 - 1));
            chart.load({
                columns: [randomData]
            });
        }, updateIntervalMs);
    }());

    (function createGaugeCharts() {
        var gaugeElements = document.querySelectorAll('.gauge-chart');
        var gaugeCharts = [];
        for (var el of gaugeElements) {
            var value = Math.random();
            var chart = c3.generate({
                bindto: el,
                size: {
                    width: 100,
                    height: 100
                },
                padding: {
                    top: 0,
                    right: 0,
                    bottom: 0,
                    left: 0
                },
                data: {
                    columns: [
                        ['data', value]
                    ],
                    colors: {
                        data: "#34ccff"
                    },
                    type: 'gauge'
                },
                gauge: {
                    min: 0,
                    max: 1
                },
                interaction: { enabled: false },
            });
            gaugeCharts.push(chart);
        }

        if (!animate) { return; }
        window.setInterval(function () {
            for (var chart of gaugeCharts) {
                var value = Math.random();
                chart.load({
                    columns: [['data', value]]
                });
            }
        }, updateIntervalMs);
    }());

}());
<|endoftext|>


<commit_before>/* @flow weak */

/**
 * OfflineMobile Android Index
 * Sustainable Solutions (NZ) Ltd. 2016
 */

import React from 'react';
import {
  Image,
  StyleSheet,
  Text,
  View,
} from 'react-native';

import {
  Button,
} from '../widgets';
import Icon from 'react-native-vector-icons/FontAwesome';

import globalStyles, {
  APP_FONT_FAMILY,
  DARK_GREY,
  DARKER_GREY,
  SHADOW_BORDER,
} from '../globalStyles';

export function MenuPage(props) {
  return (
    <View style={[globalStyles.pageContentContainer, localStyles.pageContentContainer]}>
      <View style={[globalStyles.horizontalContainer, localStyles.horizontalContainer]}>
        <View style={localStyles.container}>
          <Image
            style={localStyles.image}
            resizeMode="contain"
            source={require('../images/menu_people.png')}
          />
          <Button
            style={globalStyles.menuButton}
            textStyle={globalStyles.menuButtonText}
            text="Customers"
            onPress={() => props.navigateTo('customers', 'Customers')}
          />
          <Button
            style={globalStyles.menuButton}
            textStyle={globalStyles.menuButtonText}
            text="Customer Invoices"
            onPress={() => props.navigateTo('customerInvoices', 'Customer Invoices')}
          />
        </View>

        <View style={localStyles.container}>
          <Image
            style={localStyles.image}
            resizeMode="contain"
            source={require('../images/menu_truck.png')}
          />
          <Button
            style={globalStyles.menuButton}
            textStyle={globalStyles.menuButtonText}
            text="Supplier Invoices"
            onPress={() => props.navigateTo('supplierInvoices', 'Supplier Invoices')}
          />
          <Button
            style={globalStyles.menuButton}
            textStyle={globalStyles.menuButtonText}
            text="Stock Histories"
            onPress={() => props.navigateTo('stockHistories', 'Stock Histories')}
          />
        </View>

        <View style={localStyles.container}>
          <Image
            style={localStyles.image}
            resizeMode="contain"
            source={require('../images/menu_pc_clipboard.png')}
          />
          <Button
            style={globalStyles.menuButton}
            textStyle={globalStyles.menuButtonText}
            text="Current Stock"
            onPress={() => props.navigateTo('stock', 'Stock')}
          />
          <Button
            style={globalStyles.menuButton}
            textStyle={globalStyles.menuButtonText}
            text="Stocktakes"
            onPress={() => props.navigateTo('stocktakes', 'Stocktakes')}
          />
          <Button
            style={globalStyles.menuButton}
            textStyle={globalStyles.menuButtonText}
            text="Realm Explorer"
            onPress={() => props.navigateTo('realmExplorer', 'Database Contents')}
          />
        </View>
      </View>
      <View style={[globalStyles.horizontalContainer, { flex: 1, marginHorizontal: 20 }]}>
        <Icon.Button
          name="power-off"
          underlayColor="#888888"
          iconStyle={localStyles.logOutIcon}
          borderRadius={4}
          backgroundColor="rgba(255,255,255,0)"
          onPress={props.logOut()}
        >
          <Text style={localStyles.logOutText}>LOG OUT</Text>
        </Icon.Button>
      </View>
    </View>
  );
}

MenuPage.propTypes = {
  navigateTo: React.PropTypes.func.isRequired,
  logOut: React.PropTypes.func.isRequired,
};

const localStyles = StyleSheet.create({
  pageContentContainer: {
    padding: 0,
  },
  horizontalContainer: {
    flex: 9,
  },
  container: {
    alignSelf: 'stretch',
    flex: 1,
    paddingTop: 30,
    paddingHorizontal: 30,
    marginHorizontal: 20,
    borderColor: SHADOW_BORDER,
    borderWidth: 1,
    justifyContent: 'flex-start',
    alignItems: 'center',
    backgroundColor: 'white',
  },
  image: {
    height: 150,
    width: 150,
    marginBottom: 30,
  },
  logOutText: {
    fontFamily: APP_FONT_FAMILY,
    color: DARKER_GREY,
  },
  logOutIcon: {
    color: DARK_GREY,
  },
});
<commit_msg>Colours of logout button in MenuPage match design better<commit_after>/* @flow weak */

/**
 * OfflineMobile Android Index
 * Sustainable Solutions (NZ) Ltd. 2016
 */

import React from 'react';
import {
  Image,
  StyleSheet,
  Text,
  View,
} from 'react-native';

import {
  Button,
} from '../widgets';
import Icon from 'react-native-vector-icons/FontAwesome';

import globalStyles, {
  APP_FONT_FAMILY,
  DARK_GREY,
  DARKER_GREY,
  SHADOW_BORDER,
} from '../globalStyles';

export function MenuPage(props) {
  return (
    <View style={[globalStyles.pageContentContainer, localStyles.pageContentContainer]}>
      <View style={[globalStyles.horizontalContainer, localStyles.horizontalContainer]}>
        <View style={localStyles.container}>
          <Image
            style={localStyles.image}
            resizeMode="contain"
            source={require('../images/menu_people.png')}
          />
          <Button
            style={globalStyles.menuButton}
            textStyle={globalStyles.menuButtonText}
            text="Customers"
            onPress={() => props.navigateTo('customers', 'Customers')}
          />
          <Button
            style={globalStyles.menuButton}
            textStyle={globalStyles.menuButtonText}
            text="Customer Invoices"
            onPress={() => props.navigateTo('customerInvoices', 'Customer Invoices')}
          />
        </View>

        <View style={localStyles.container}>
          <Image
            style={localStyles.image}
            resizeMode="contain"
            source={require('../images/menu_truck.png')}
          />
          <Button
            style={globalStyles.menuButton}
            textStyle={globalStyles.menuButtonText}
            text="Supplier Invoices"
            onPress={() => props.navigateTo('supplierInvoices', 'Supplier Invoices')}
          />
          <Button
            style={globalStyles.menuButton}
            textStyle={globalStyles.menuButtonText}
            text="Stock Histories"
            onPress={() => props.navigateTo('stockHistories', 'Stock Histories')}
          />
        </View>

        <View style={localStyles.container}>
          <Image
            style={localStyles.image}
            resizeMode="contain"
            source={require('../images/menu_pc_clipboard.png')}
          />
          <Button
            style={globalStyles.menuButton}
            textStyle={globalStyles.menuButtonText}
            text="Current Stock"
            onPress={() => props.navigateTo('stock', 'Stock')}
          />
          <Button
            style={globalStyles.menuButton}
            textStyle={globalStyles.menuButtonText}
            text="Stocktakes"
            onPress={() => props.navigateTo('stocktakes', 'Stocktakes')}
          />
          <Button
            style={globalStyles.menuButton}
            textStyle={globalStyles.menuButtonText}
            text="Realm Explorer"
            onPress={() => props.navigateTo('realmExplorer', 'Database Contents')}
          />
        </View>
      </View>
      <View style={[globalStyles.horizontalContainer, { flex: 1, marginHorizontal: 20 }]}>
        <Icon.Button
          name="power-off"
          underlayColor="#888888"
          iconStyle={localStyles.logOutIcon}
          borderRadius={4}
          backgroundColor="rgba(255,255,255,0)"
          onPress={props.logOut()}
        >
          <Text style={localStyles.logOutText}>LOG OUT</Text>
        </Icon.Button>
      </View>
    </View>
  );
}

MenuPage.propTypes = {
  navigateTo: React.PropTypes.func.isRequired,
  logOut: React.PropTypes.func.isRequired,
};

const localStyles = StyleSheet.create({
  pageContentContainer: {
    padding: 0,
  },
  horizontalContainer: {
    flex: 9,
  },
  container: {
    alignSelf: 'stretch',
    flex: 1,
    paddingTop: 30,
    paddingHorizontal: 30,
    marginHorizontal: 20,
    borderColor: SHADOW_BORDER,
    borderWidth: 1,
    justifyContent: 'flex-start',
    alignItems: 'center',
    backgroundColor: 'white',
  },
  image: {
    height: 150,
    width: 150,
    marginBottom: 30,
  },
  logOutText: {
    fontFamily: APP_FONT_FAMILY,
    color: '#a8aaac',
  },
  logOutIcon: {
    color: '#909192',
  },
});
<|endoftext|>


<commit_before>/*
 *	Copyright (C) 2012 Andr jr Steenveld all rights reserved
 *	Licensed under the MIT public license for the full license see the LICENSE file
 *
 */
define( [ ".", "lib" ], function( chess, lib ){

	chess.Player = lib.declare( [ ], {

		handles: null,

		game: null,

		color: null,
		board: null,

		constructor: function( _player_ ){
			"color" in _player_ && ( this.color = _player_.color );
			"game" in _player_ && this.join( _player_.game );
		},

		//
		// Player methods
		//
		join: function( game, color ){

			if( ( this.color = game.join( this, this.color ) ) ){

				this.game  = game;
				this.board = game.board;

				this.handles = {
					//
					// General game events
					//
					start: game.on( "Start", this.started.bind( this ) ),
					draw:  game.on( "Draw",  this.draw.bind( this ) ),

					end: game.on( "End",
						Function.bind( this, function( _end_ ){

							// The game doesn't do all the triggering of events, its more a general thing
							// so if we want to fire win/lose events and then the more general end event
							// we will have to do a little event routing of our own.
							if( _end_.result === "check mate" || _end_.result === "surrender" ){

								_end_.winner === this
									? this.win.onIdle( this ).then( this.ended.bind( this, [ _end_ ] ) )
									: this.lose.onIdle( this ).then( this.ended.bind( this, [ _end_ ] ) );

							} else { // This is a stale mate, a draw or 3 board repetition

								this.ended.onIdle( this, [ _end_ ] );

							}

						})
					),

					//
					// Movement stuff
					//
					turn: game.on( this.color === "white" ? "WhiteTurn" : "BlackTurn", this.turn.bind( this ) ),

					placed: game.on( "Placed", this.placed.bind( this ) ),

					moved: game.on( "Moved", this.moved.bind( this ) ),

					//
					// To the player
					//
					check: game.on( "Checked", this.check.bind( this ) ),

					mated: game.on( "CheckMate", this.mate.bind( this ) ),

					staleMate: game.on( "StaleMate", this.staleMate.bind( this ) )

				};

			}

		},

		leave: function( ){
			this.game = null;
			this.board = null;

			this.game.leave( this );
		},

		//
		// Handlers for general game events
		//
		started: function( ){ /* when the game has started */ },

		ended: function( ){ /* called when the game comes to an end */ },

		lose: function( ){ /* Called when the player loses */ },

		draw: function( ){ /* Called when the players have agreed on a draw */ },

		win: function( ){ /* Called when the player wins the game */ },

		//
		// Actions involving the other player
		//
		offerDraw: function( ){ },

		acceptDraw: function( ){ /* called when the other player offers a draw. Returns true to accept, false to reject */ },

		surrender: function( ){
			this.game.end({
				result: "surrender",
				loser: this,
				winner: this.color === "white"
					? this.board.black
					: this.board.white
			});
		},

		//
		// Game event handlers
		//
		turn: function( ){ /* when this player recieves the turn */ },

		placed: function( ){ /* when a piece has been placed on the board */ },

		moved: function( ){ /* when any player has moved a piece */ },

		//
		// Handlers for events after something happend to the player
		//
		checked: function( ){ /* Called when the other player checked you */ },

		mates: function( ){ /* Called when the other player mates you */ },

		staleMates: function( ){ /* Called when you are stale mated */ }

	});

	return chess.Player;
});<commit_msg>Game unit tests are running, need to make more<commit_after>/*
 *	Copyright (C) 2012 Andr jr Steenveld all rights reserved
 *	Licensed under the MIT public license for the full license see the LICENSE file
 *
 */
define( [ ".", "lib" ], function( chess, lib ){

	chess.Player = lib.declare( [ ], {

		handles: null,

		game: null,

		color: null,
		board: null,

		constructor: function( _player_ ){
			"color" in _player_ && ( this.color = _player_.color );
			"game" in _player_ && this.join( _player_.game );
		},

		//
		// Player methods
		//
		join: function( game, color ){

			if( ( this.color = game.join( this, this.color ) ) ){

				this.game  = game;
				this.board = game.board;

				this.handles = {
					//
					// General game events
					//
					start: game.on( "Start", this.started.bind( this ) ),
					draw:  game.on( "Draw",  this.draw.bind( this ) ),

					end: game.on( "End",
						Function.bind( this, function( _end_ ){

							// The game doesn't do all the triggering of events, its more a general thing
							// so if we want to fire win/lose events and then the more general end event
							// we will have to do a little event routing of our own.
							if( _end_.result === "check mate" || _end_.result === "surrender" ){

								_end_.winner === this
									? this.win.onIdle( this ).then( this.ended.bind( this, [ _end_ ] ) )
									: this.lose.onIdle( this ).then( this.ended.bind( this, [ _end_ ] ) );

							} else { // This is a stale mate, a draw or 3 board repetition

								this.ended.onIdle( this, [ _end_ ] );

							}

						})
					),

					//
					// Movement stuff
					//
					turn: game.on( this.color === "white" ? "WhiteTurn" : "BlackTurn", this.turn.bind( this ) ),

					placed: game.on( "Placed", this.placed.bind( this ) ),

					moved: game.on( "Moved", this.moved.bind( this ) ),

					//
					// To the player
					//
					check: game.on( "Checked", this.check.bind( this ) ),

					mated: game.on( "CheckMate", this.mate.bind( this ) ),

					staleMate: game.on( "StaleMate", this.staleMate.bind( this ) )

				};

			}

		},

		leave: function( ){
			this.game = null;
			this.board = null;

			this.game.leave( this );
		},

		//
		// Handlers for general game events
		//
		started: function( ){ /* when the game has started */ },

		ended: function( ){ /* called when the game comes to an end */ },

		lose: function( ){ /* Called when the player loses */ },

		draw: function( ){ /* Called when the players have agreed on a draw */ },

		win: function( ){ /* Called when the player wins the game */ },

		//
		// Actions involving the other player
		//
		offerDraw: function( ){ },

		acceptDraw: function( ){ /* called when the other player offers a draw. Returns true to accept, false to reject */ },

		surrender: function( ){
			this.game.end({
				result: "surrender",
				loser: this,
				winner: this.color === "white"
					? this.board.black
					: this.board.white
			});
		},

		//
		// Game event handlers
		//
		turn: function( ){ /* when this player recieves the turn */ },

		placed: function( ){ /* when a piece has been placed on the board */ },

		moved: function( ){ /* when any player has moved a piece */ },

		//
		// Handlers for events after something happend to the player
		//
		check: function( ){ /* Called when the other player checked you */ },

		mate: function( ){ /* Called when the other player mates you */ },

		staleMate: function( ){ /* Called when you are stale mated */ }

	});

	return chess.Player;
});<|endoftext|>


<commit_before>/**
 * Configuration of Organisms plugin
 *
 * @author flatline
 */
const Config = {
    /**
     * {Number} Maximum value of mutation period in iterations. It's used
     * in mutations of org.mutationPeriod parameter
     */
    ORG_MAX_MUTATION_PERIOD: 10000,
    /**
     * {Number} Maximum amount of iterations for clone period
     */
    ORG_MAX_CLONE_PERIOD: 10000,
    /**
     * {Number} Index of first color of organism. After maximum color this
     * color will be applied
     */
    ORG_FIRST_COLOR: 1,
    /**
     * {Number} Maximum color index of organism
     */
    ORG_MAX_COLOR: Number.MAX_SAFE_INTEGER,
    /**
     * {Number} Max value, which we may use in orgMutationProbs array. We may use
     * range: [0...ORG_MUTATION_PROBS_MAX_VAL] including these values
     */
    ORG_MUTATION_PROBS_MAX_VAL: 100,
    /**
     * {Array} Probabilities which used, when mutator decides what to do:
     * add, change, delete code line inside the vm; change amount of
     * mutations or change mutations period... Depending on these
     * values, organism may have different strategies of living.
     * For example: if add value is bigger then del and change,
     * then vm size will be grow up all the time. If del value is
     * bigger then other, then it will be decreased to zero lines
     * of vm and organism will die.
     * Format: [
     *     add           - Probability of adding new line to the code
     *     change        - Probability of changing existing line of code
     *     delete        - Probability of deleting a line of code
     *     small-change  - Probability of "small change" - change part of one code line
     *     clone         - Probability for sharing of energy percent on clone
     *     copy          - Probability of copying of code lines inside it's own code
     *     period        - Probability of period of organism mutations
     *     amount        - Probability of amount of mutations per period
     *     probs         - Probability of change one of probability coefficient in this array
     *     clone-percent - Probability of change clone energy percent value
     *     clone-period  - Probability of change clone period value
     * ]
     */
    orgMutationProbs: [10,1,1,100,1,1,1,1,1,1,1],
    /**
     * {Number} Percent of mutations from vm size, which will be applied to
     * organism after cloning. Should be <= 1.0 (1.0 === 100%)
     */
    orgCloneMutationPercent: 0.0,
    /**
     * {Number} Amount of iterations between cloning. Set it to 0 to turn it off
     */
    orgClonePeriod: 100,
    /**
     * {Number} Amount of iterations, after which crossover will be applied
     * to random organisms. May be set to 0 to turn crossover off
     */
    orgCrossoverPeriod: 300,
    /**
     * {Number} Period of tournament between organisms. If amount of organisms
     * is >= of maximum (orgMaxOrgs), then looser organism will be killed. This
     * is how natural selection is implemented in our system. Set this parameter
     * to 0 and tournament mechanism will be turned off
     */
    orgTournamentPeriod: 100,
    /**
     * {Number} Amount of iterations within organism's life loop, after that we
     * do mutations according to orgRainMutationPercent config. If 0, then
     * mutations will be disabled. Should be less then ORGANISM_MAX_MUTATION_PERIOD
     */
    orgRainMutationPeriod: 300,
    /**
     * {Number} Percent of mutations from code size. 0 is a possible value if
     * we want to disable mutations. Should be less then 1.0 (1.0 === 100%)
     */
    orgRainMutationPercent: 0.2,
    /**
     * {Number} Amount of organisms we have to create on program start
     */
    orgStartAmount: 300,
    /**
     * {Number} Amount of energy for first organisms. They are like Adam and
     * Eve. It means that these empty (without vm) organism were created
     * by operator and not by evolution.
     */
    orgStartEnergy: 50000,
    /**
     * {Number} Begin color of "empty" organism (organism without code). Color
     * should be set in HEX-RGB mode. Example: 0xRRGGBB
     */
    orgStartColor: 0xFF0000,
    /**
     * {Number} Amount of iterations within organism's life loop, after that we decrease
     * some amount of energy. If 0, then energy decreasing will be disabled.
     */
    orgEnergySpendPeriod: 10,
    /**
     * {Number} Amount of iterations when organism is alive. It will die after
     * this period. If 0, then will not be used and organism may leave forever
     */
    orgAlivePeriod: 5000,
    /**
     * {Number} This value means the period between organism codeSizes, which
     * affects energy grabbing by the system. For example: we have two
     * organisms: org1.energy = 10, org2.energy = 10, org1.codeSize = 6,
     * org2.codeSize = 9, OConfig.orgGarbagePeriod = 5. It means that
     * during energy grabbing by the system org1 and org2 will spend the
     * same amount of energy - 1 unit. This is because the period goes
     * from 1..5, 6..10,... and both organisms are in the same period. In
     * simple words, if your size is between 0-20, then 1 unit of energy will
     * be grabbed from you. If your size is between 21-40, then 2 units of
     * energy will be grabbed from you and so on...
     */
    orgGarbagePeriod: 6,
    /**
     * {Number} Size of organism stack (internal memory)
     */
    orgMemSize: 128,
    /**
     * {Number} Percent of energy, which will be given to the child. Set to 0.0
     * to share the same amount of energy with child (energy duplication)
     */
    orgCloneEnergyPercent: 0.5,
    /**
     * {Number} Percent of energy, which will be minused from organism after
     * stepping from one instance to another.
     */
    orgStepEnergySpendPercent: 0.1,
    /**
     * {Number} Maximum amount of organisms in a world. If some organism will
     * try to clone itself, when entire amount of organisms are equal
     * this value, the cloning will not happen.
     */
    orgMaxOrgs: 800,
    /**
     * {Number} If organism reach this limit of amount of vm lines, then codeSizeCoef
     * will be used during it's energy grabbing by system. We use this approach,
     * because our CPU's are slow and organisms with big codes are very slow. But
     * it's possible for organisms to go outside the limit by inventing new
     * effective mechanisms of energy obtaining.
     */
    codeMaxSize: 64,
    /**
     * {Number} Amount of bits per one variable. It affects maximum value,
     * which this variable may contain. This value shouldn't be less then 2.
     */
    codeBitsPerVar: 2,
    /**
     * {Number} The value from -X/2 to X/2, which is used for setting
     * default value, while organism is delivering. So, if the value is
     * 1000, then ragne will be: -500..500
     */
    codeVarInitRange: 1000,
    /**
     * {Number} This value is amount of code lines, which will be run for one
     * organism without interruption by one VM. Set this value to value bigger
     * then codeMaxSize, then entire code of organism will be run
     */
    codeYieldPeriod: 5,
    /**
     * {Number} Amount of bits for storing operator. This is first XX bits
     * in a number.
     */
    codeBitsPerOperator: 8,
    /**
     * {Number} Amount of bits, which stores maximum block length. Under block
     * length we mean maximum amount of lines in one block like if, for,...
     */
    codeBitsPerBlock: 4,
    /**
     * {Number} Amount of iterations between calls to V8 event loop. See
     * Manager._initLoop(), Manager.run() methods for details.
     */
    codeIterationsPerOnce: 200,
};

module.exports = Config;<commit_msg>changed default configs<commit_after>/**
 * Configuration of Organisms plugin
 *
 * @author flatline
 */
const Config = {
    /**
     * {Number} Maximum value of mutation period in iterations. It's used
     * in mutations of org.mutationPeriod parameter
     */
    ORG_MAX_MUTATION_PERIOD: 10000,
    /**
     * {Number} Maximum amount of iterations for clone period
     */
    ORG_MAX_CLONE_PERIOD: 10000,
    /**
     * {Number} Index of first color of organism. After maximum color this
     * color will be applied
     */
    ORG_FIRST_COLOR: 1,
    /**
     * {Number} Maximum color index of organism
     */
    ORG_MAX_COLOR: Number.MAX_SAFE_INTEGER,
    /**
     * {Number} Max value, which we may use in orgMutationProbs array. We may use
     * range: [0...ORG_MUTATION_PROBS_MAX_VAL] including these values
     */
    ORG_MUTATION_PROBS_MAX_VAL: 100,
    /**
     * {Array} Probabilities which used, when mutator decides what to do:
     * add, change, delete code line inside the vm; change amount of
     * mutations or change mutations period... Depending on these
     * values, organism may have different strategies of living.
     * For example: if add value is bigger then del and change,
     * then vm size will be grow up all the time. If del value is
     * bigger then other, then it will be decreased to zero lines
     * of vm and organism will die.
     * Format: [
     *     add           - Probability of adding new line to the code
     *     change        - Probability of changing existing line of code
     *     delete        - Probability of deleting a line of code
     *     small-change  - Probability of "small change" - change part of one code line
     *     clone         - Probability for sharing of energy percent on clone
     *     copy          - Probability of copying of code lines inside it's own code
     *     period        - Probability of period of organism mutations
     *     amount        - Probability of amount of mutations per period
     *     probs         - Probability of change one of probability coefficient in this array
     *     clone-percent - Probability of change clone energy percent value
     *     clone-period  - Probability of change clone period value
     * ]
     */
    orgMutationProbs: [10,1,1,100,1,1,1,1,1,1,1],
    /**
     * {Number} Percent of mutations from vm size, which will be applied to
     * organism after cloning. Should be <= 1.0 (1.0 === 100%)
     */
    orgCloneMutationPercent: 0.0,
    /**
     * {Number} Amount of iterations between cloning. Set it to 0 to turn it off
     */
    orgClonePeriod: 100,
    /**
     * {Number} Amount of iterations, after which crossover will be applied
     * to random organisms. May be set to 0 to turn crossover off
     */
    orgCrossoverPeriod: 300,
    /**
     * {Number} Period of tournament between organisms. If amount of organisms
     * is >= of maximum (orgMaxOrgs), then looser organism will be killed. This
     * is how natural selection is implemented in our system. Set this parameter
     * to 0 and tournament mechanism will be turned off
     */
    orgTournamentPeriod: 80,
    /**
     * {Number} Amount of iterations within organism's life loop, after that we
     * do mutations according to orgRainMutationPercent config. If 0, then
     * mutations will be disabled. Should be less then ORGANISM_MAX_MUTATION_PERIOD
     */
    orgRainMutationPeriod: 300,
    /**
     * {Number} Percent of mutations from code size. 0 is a possible value if
     * we want to disable mutations. Should be less then 1.0 (1.0 === 100%)
     */
    orgRainMutationPercent: 0.2,
    /**
     * {Number} Amount of organisms we have to create on program start
     */
    orgStartAmount: 300,
    /**
     * {Number} Amount of energy for first organisms. They are like Adam and
     * Eve. It means that these empty (without vm) organism were created
     * by operator and not by evolution.
     */
    orgStartEnergy: 50000,
    /**
     * {Number} Begin color of "empty" organism (organism without code). Color
     * should be set in HEX-RGB mode. Example: 0xRRGGBB
     */
    orgStartColor: 0xFF0000,
    /**
     * {Number} Amount of iterations within organism's life loop, after that we decrease
     * some amount of energy. If 0, then energy decreasing will be disabled.
     */
    orgEnergySpendPeriod: 10,
    /**
     * {Number} Amount of iterations when organism is alive. It will die after
     * this period. If 0, then will not be used and organism may leave forever
     */
    orgAlivePeriod: 5000,
    /**
     * {Number} This value means the period between organism codeSizes, which
     * affects energy grabbing by the system. For example: we have two
     * organisms: org1.energy = 10, org2.energy = 10, org1.codeSize = 6,
     * org2.codeSize = 9, OConfig.orgGarbagePeriod = 5. It means that
     * during energy grabbing by the system org1 and org2 will spend the
     * same amount of energy - 1 unit. This is because the period goes
     * from 1..5, 6..10,... and both organisms are in the same period. In
     * simple words, if your size is between 0-20, then 1 unit of energy will
     * be grabbed from you. If your size is between 21-40, then 2 units of
     * energy will be grabbed from you and so on...
     */
    orgGarbagePeriod: 6,
    /**
     * {Number} Size of organism stack (internal memory)
     */
    orgMemSize: 128,
    /**
     * {Number} Percent of energy, which will be given to the child. Set to 0.0
     * to share the same amount of energy with child (energy duplication)
     */
    orgCloneEnergyPercent: 0.5,
    /**
     * {Number} Percent of energy, which will be minused from organism after
     * stepping from one instance to another.
     */
    orgStepEnergySpendPercent: 0.1,
    /**
     * {Number} Maximum amount of organisms in a world. If some organism will
     * try to clone itself, when entire amount of organisms are equal
     * this value, the cloning will not happen.
     */
    orgMaxOrgs: 200,
    /**
     * {Number} If organism reach this limit of amount of vm lines, then codeSizeCoef
     * will be used during it's energy grabbing by system. We use this approach,
     * because our CPU's are slow and organisms with big codes are very slow. But
     * it's possible for organisms to go outside the limit by inventing new
     * effective mechanisms of energy obtaining.
     */
    codeMaxSize: 64,
    /**
     * {Number} Amount of bits per one variable. It affects maximum value,
     * which this variable may contain. This value shouldn't be less then 2.
     */
    codeBitsPerVar: 2,
    /**
     * {Number} The value from -X/2 to X/2, which is used for setting
     * default value, while organism is delivering. So, if the value is
     * 1000, then ragne will be: -500..500
     */
    codeVarInitRange: 1000,
    /**
     * {Number} This value is amount of code lines, which will be run for one
     * organism without interruption by one VM. Set this value to value bigger
     * then codeMaxSize, then entire code of organism will be run
     */
    codeYieldPeriod: 5,
    /**
     * {Number} Amount of bits for storing operator. This is first XX bits
     * in a number.
     */
    codeBitsPerOperator: 8,
    /**
     * {Number} Amount of bits, which stores maximum block length. Under block
     * length we mean maximum amount of lines in one block like if, for,...
     */
    codeBitsPerBlock: 4,
    /**
     * {Number} Amount of iterations between calls to V8 event loop. See
     * Manager._initLoop(), Manager.run() methods for details.
     */
    codeIterationsPerOnce: 200,
};

module.exports = Config;<|endoftext|>


<commit_before>var child = {};
var path  = require("path");

process.on("message", function(msg){
  switch(msg.type){
    case "require":
      for (var key in msg.dependencies){
        if (msg.dependencies.hasOwnProperty(key)){
          var dir = path.resolve( process.cwd() + "/" + msg.dependencies[key] );
          child[key] = require(dir);
        }
      }
    break;
    case "registerTasks":
      child.tasks = msg.tasks;
    break;
    case "execute":
      var ret_val = msg.datum;
      for (var i = 0; i < child.tasks.length; i++){
        ret_val = child[child.tasks[i].namespace][child.tasks[i].function](ret_val);
      }
      var ret_msg = { "key" : msg.key, "value" : ret_val};
      process.send(ret_msg);
    break;
  }
});
<commit_msg>pass index<commit_after>var child = {};
var path  = require("path");

process.on("message", function(msg){
  switch(msg.type){
    case "require":
      for (var key in msg.dependencies){
        if (msg.dependencies.hasOwnProperty(key)){
          var dir = path.resolve( process.cwd() + "/" + msg.dependencies[key] );
          child[key] = require(dir);
        }
      }
    break;
    case "registerTasks":
      child.tasks = msg.tasks;
    break;
    case "execute":
      var ret_val = msg.datum;
      for (var i = 0; i < child.tasks.length; i++){
        ret_val = child[child.tasks[i].namespace][child.tasks[i].function](ret_val, msg.key);
      }
      var ret_msg = { "key" : msg.key, "value" : ret_val};
      process.send(ret_msg);
    break;
  }
});
<|endoftext|>