<commit_before>if (typeof(module) !== 'undefined' && typeof(exports) !== 'undefined') {
    module.exports = OAuth;
}

/**
 * Constructor
 * @param {Object} opts consumer key and secret
 */
function OAuth(opts) {
    if(!(this instanceof OAuth)) {
        return new OAuth(opts);
    }

    if(!opts) {
        opts = {};
    }

    if(!opts.consumer) {
        throw new Error('consumer option is required');
    }

    this.consumer            = opts.consumer;
    this.nonce_length        = opts.nonce_length || 32;
    this.version             = opts.version || '1.0';
    this.parameter_seperator = opts.parameter_seperator || ', ';
    this.realm               = opts.realm;

    if(typeof opts.last_ampersand === 'undefined') {
        this.last_ampersand = true;
    } else {
        this.last_ampersand = opts.last_ampersand;
    }

    // default signature_method is 'PLAINTEXT'
    this.signature_method = opts.signature_method || 'PLAINTEXT';

    if(this.signature_method == 'PLAINTEXT' && !opts.hash_function) {
        opts.hash_function = function(base_string, key) {
            return key;
        }
    }

    if(!opts.hash_function) {
        throw new Error('hash_function option is required');
    }

    this.hash_function = opts.hash_function;
}

/**
 * OAuth request authorize
 * @param  {Object} request data
 * {
 *     method,
 *     url,
 *     data
 * }
 * @param  {Object} key and secret token
 * @return {Object} OAuth Authorized data
 */
OAuth.prototype.authorize = function(request, token) {
    var oauth_data = {
        oauth_consumer_key: this.consumer.key,
        oauth_nonce: this.getNonce(),
        oauth_signature_method: this.signature_method,
        oauth_timestamp: this.getTimeStamp(),
        oauth_version: this.version
    };

    if(!token) {
        token = {};
    }

    if(token.key !== undefined) {
        oauth_data.oauth_token = token.key;
    }

    if(!request.data) {
        request.data = {};
    }

    if(request.includeBodyHash) {
      oauth_data.oauth_body_hash = this.getBodyHash(request, token.secret)
    }

    oauth_data.oauth_signature = this.getSignature(request, token.secret, oauth_data);

    return oauth_data;
};

/**
 * Create a OAuth Signature
 * @param  {Object} request data
 * @param  {Object} token_secret key and secret token
 * @param  {Object} oauth_data   OAuth data
 * @return {String} Signature
 */
OAuth.prototype.getSignature = function(request, token_secret, oauth_data) {
    return this.hash_function(this.getBaseString(request, oauth_data), this.getSigningKey(token_secret));
};

/**
 * Create a OAuth Body Hash
 * @param {Object} request data
 */
OAuth.prototype.getBodyHash = function(request, token_secret) {
  var body = typeof request.data === 'string' ? request.data : JSON.stringify(request.data)

  return this.hash_function(body, this.getSigningKey(token_secret))
};

/**
 * Base String = Method + Base Url + ParameterString
 * @param  {Object} request data
 * @param  {Object} OAuth data
 * @return {String} Base String
 */
OAuth.prototype.getBaseString = function(request, oauth_data) {
    return request.method.toUpperCase() + '&' + this.percentEncode(this.getBaseUrl(request.url)) + '&' + this.percentEncode(this.getParameterString(request, oauth_data));
};

/**
 * Get data from url
 * -> merge with oauth data
 * -> percent encode key & value
 * -> sort
 *
 * @param  {Object} request data
 * @param  {Object} OAuth data
 * @return {Object} Parameter string data
 */
OAuth.prototype.getParameterString = function(request, oauth_data) {
    var base_string_data;
    if (oauth_data.oauth_body_hash) {
        base_string_data = this.sortObject(this.percentEncodeData(this.mergeObject(oauth_data, this.deParamUrl(request.url))));
    } else {
        base_string_data = this.sortObject(this.percentEncodeData(this.mergeObject(oauth_data, this.mergeObject(request.data, this.deParamUrl(request.url)))));
    }

    var data_str = '';

    //base_string_data to string
    for(var i in base_string_data) {
        var key = base_string_data[i].key;
        var value = base_string_data[i].value;
        // check if the value is an array
        // this means that this key has multiple values
        if (value && Array.isArray(value)){
          // sort the array first
          value.sort();

          var valString = "";
          // serialize all values for this key: e.g. formkey=formvalue1&formkey=formvalue2
          value.forEach((function(item, i){
            valString += key + '=' + item;
            if (i < value.length){
              valString += "&";
            }
          }).bind(this));
          data_str += valString;
        } else {
          data_str += key + '=' + value + '&';
        }
    }

    //remove the last character
    data_str = data_str.substr(0, data_str.length - 1);
    return data_str;
};

/**
 * Create a Signing Key
 * @param  {String} token_secret Secret Token
 * @return {String} Signing Key
 */
OAuth.prototype.getSigningKey = function(token_secret) {
    token_secret = token_secret || '';

    if(!this.last_ampersand && !token_secret) {
        return this.percentEncode(this.consumer.secret);
    }

    return this.percentEncode(this.consumer.secret) + '&' + this.percentEncode(token_secret);
};

/**
 * Get base url
 * @param  {String} url
 * @return {String}
 */
OAuth.prototype.getBaseUrl = function(url) {
    return url.split('?')[0];
};

/**
 * Get data from String
 * @param  {String} string
 * @return {Object}
 */
OAuth.prototype.deParam = function(string) {
    var arr = string.split('&');
    var data = {};

    for(var i = 0; i < arr.length; i++) {
        var item = arr[i].split('=');

        // '' value
        item[1] = item[1] || '';

        data[item[0]] = decodeURIComponent(item[1]);
    }

    return data;
};

/**
 * Get data from url
 * @param  {String} url
 * @return {Object}
 */
OAuth.prototype.deParamUrl = function(url) {
    var tmp = url.split('?');

    if (tmp.length === 1)
        return {};

    return this.deParam(tmp[1]);
};

/**
 * Percent Encode
 * @param  {String} str
 * @return {String} percent encoded string
 */
OAuth.prototype.percentEncode = function(str) {
    return encodeURIComponent(str)
        .replace(/\!/g, "%21")
        .replace(/\*/g, "%2A")
        .replace(/\'/g, "%27")
        .replace(/\(/g, "%28")
        .replace(/\)/g, "%29");
};

/**
 * Percent Encode Object
 * @param  {Object} data
 * @return {Object} percent encoded data
 */
OAuth.prototype.percentEncodeData = function(data) {
    var result = {};

    for(var key in data) {
        var value = data[key];
        // check if the value is an array
        if (value && Array.isArray(value)){
          var newValue = [];
          // percentEncode every value
          value.forEach((function(val){
            newValue.push(this.percentEncode(val));
          }).bind(this));
          value = newValue;
        } else {
          value = this.percentEncode(value);
        }
        result[this.percentEncode(key)] = value;
    }

    return result;
};

/**
 * Get OAuth data as Header
 * @param  {Object} oauth_data
 * @return {String} Header data key - value
 */
OAuth.prototype.toHeader = function(oauth_data) {
    var sorted = this.sortObject(oauth_data);

    var header_value = 'OAuth ';

    if (this.realm) {
        header_value += 'realm="' + this.realm + '"' + this.parameter_seperator;
    }

    for(var i = 0; i < sorted.length; i++) {
        if (sorted[i].key.indexOf('oauth_') !== 0)
            continue;

        header_value += this.percentEncode(sorted[i].key) + '="' + this.percentEncode(sorted[i].value) + '"' + this.parameter_seperator;
    }

    return {
        Authorization: header_value.substr(0, header_value.length - this.parameter_seperator.length) //cut the last chars
    };
};

/**
 * Create a random word characters string with input length
 * @return {String} a random word characters string
 */
OAuth.prototype.getNonce = function() {
    var word_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    var result = '';

    for(var i = 0; i < this.nonce_length; i++) {
        result += word_characters[parseInt(Math.random() * word_characters.length, 10)];
    }

    return result;
};

/**
 * Get Current Unix TimeStamp
 * @return {Int} current unix timestamp
 */
OAuth.prototype.getTimeStamp = function() {
    return parseInt(new Date().getTime()/1000, 10);
};

////////////////////// HELPER FUNCTIONS //////////////////////

/**
 * Merge object
 * @param  {Object} obj1
 * @param  {Object} obj2
 * @return {Object}
 */
OAuth.prototype.mergeObject = function(obj1, obj2) {
    obj1 = obj1 || {};
    obj2 = obj2 || {};

    var merged_obj = obj1;
    for(var key in obj2) {
        merged_obj[key] = obj2[key];
    }
    return merged_obj;
};

/**
 * Sort object by key
 * @param  {Object} data
 * @return {Object} sorted object
 */
OAuth.prototype.sortObject = function(data) {
    var keys = Object.keys(data);
    var result = [];

    keys.sort();

    for(var i = 0; i < keys.length; i++) {
        var key = keys[i];
        result.push({
            key: key,
            value: data[key],
        });
    }

    return result;
};
<commit_msg>Change elements iteration in getParameterString (fix for issue #55) (#56)<commit_after>if (typeof(module) !== 'undefined' && typeof(exports) !== 'undefined') {
    module.exports = OAuth;
}

/**
 * Constructor
 * @param {Object} opts consumer key and secret
 */
function OAuth(opts) {
    if(!(this instanceof OAuth)) {
        return new OAuth(opts);
    }

    if(!opts) {
        opts = {};
    }

    if(!opts.consumer) {
        throw new Error('consumer option is required');
    }

    this.consumer            = opts.consumer;
    this.nonce_length        = opts.nonce_length || 32;
    this.version             = opts.version || '1.0';
    this.parameter_seperator = opts.parameter_seperator || ', ';
    this.realm               = opts.realm;

    if(typeof opts.last_ampersand === 'undefined') {
        this.last_ampersand = true;
    } else {
        this.last_ampersand = opts.last_ampersand;
    }

    // default signature_method is 'PLAINTEXT'
    this.signature_method = opts.signature_method || 'PLAINTEXT';

    if(this.signature_method == 'PLAINTEXT' && !opts.hash_function) {
        opts.hash_function = function(base_string, key) {
            return key;
        }
    }

    if(!opts.hash_function) {
        throw new Error('hash_function option is required');
    }

    this.hash_function = opts.hash_function;
}

/**
 * OAuth request authorize
 * @param  {Object} request data
 * {
 *     method,
 *     url,
 *     data
 * }
 * @param  {Object} key and secret token
 * @return {Object} OAuth Authorized data
 */
OAuth.prototype.authorize = function(request, token) {
    var oauth_data = {
        oauth_consumer_key: this.consumer.key,
        oauth_nonce: this.getNonce(),
        oauth_signature_method: this.signature_method,
        oauth_timestamp: this.getTimeStamp(),
        oauth_version: this.version
    };

    if(!token) {
        token = {};
    }

    if(token.key !== undefined) {
        oauth_data.oauth_token = token.key;
    }

    if(!request.data) {
        request.data = {};
    }

    if(request.includeBodyHash) {
      oauth_data.oauth_body_hash = this.getBodyHash(request, token.secret)
    }

    oauth_data.oauth_signature = this.getSignature(request, token.secret, oauth_data);

    return oauth_data;
};

/**
 * Create a OAuth Signature
 * @param  {Object} request data
 * @param  {Object} token_secret key and secret token
 * @param  {Object} oauth_data   OAuth data
 * @return {String} Signature
 */
OAuth.prototype.getSignature = function(request, token_secret, oauth_data) {
    return this.hash_function(this.getBaseString(request, oauth_data), this.getSigningKey(token_secret));
};

/**
 * Create a OAuth Body Hash
 * @param {Object} request data
 */
OAuth.prototype.getBodyHash = function(request, token_secret) {
  var body = typeof request.data === 'string' ? request.data : JSON.stringify(request.data)

  return this.hash_function(body, this.getSigningKey(token_secret))
};

/**
 * Base String = Method + Base Url + ParameterString
 * @param  {Object} request data
 * @param  {Object} OAuth data
 * @return {String} Base String
 */
OAuth.prototype.getBaseString = function(request, oauth_data) {
    return request.method.toUpperCase() + '&' + this.percentEncode(this.getBaseUrl(request.url)) + '&' + this.percentEncode(this.getParameterString(request, oauth_data));
};

/**
 * Get data from url
 * -> merge with oauth data
 * -> percent encode key & value
 * -> sort
 *
 * @param  {Object} request data
 * @param  {Object} OAuth data
 * @return {Object} Parameter string data
 */
OAuth.prototype.getParameterString = function(request, oauth_data) {
    var base_string_data;
    if (oauth_data.oauth_body_hash) {
        base_string_data = this.sortObject(this.percentEncodeData(this.mergeObject(oauth_data, this.deParamUrl(request.url))));
    } else {
        base_string_data = this.sortObject(this.percentEncodeData(this.mergeObject(oauth_data, this.mergeObject(request.data, this.deParamUrl(request.url)))));
    }

    var data_str = '';

    //base_string_data to string
    for(var i = 0; i < base_string_data.length; i++) {
        var key = base_string_data[i].key;
        var value = base_string_data[i].value;
        // check if the value is an array
        // this means that this key has multiple values
        if (value && Array.isArray(value)){
          // sort the array first
          value.sort();

          var valString = "";
          // serialize all values for this key: e.g. formkey=formvalue1&formkey=formvalue2
          value.forEach((function(item, i){
            valString += key + '=' + item;
            if (i < value.length){
              valString += "&";
            }
          }).bind(this));
          data_str += valString;
        } else {
          data_str += key + '=' + value + '&';
        }
    }

    //remove the last character
    data_str = data_str.substr(0, data_str.length - 1);
    return data_str;
};

/**
 * Create a Signing Key
 * @param  {String} token_secret Secret Token
 * @return {String} Signing Key
 */
OAuth.prototype.getSigningKey = function(token_secret) {
    token_secret = token_secret || '';

    if(!this.last_ampersand && !token_secret) {
        return this.percentEncode(this.consumer.secret);
    }

    return this.percentEncode(this.consumer.secret) + '&' + this.percentEncode(token_secret);
};

/**
 * Get base url
 * @param  {String} url
 * @return {String}
 */
OAuth.prototype.getBaseUrl = function(url) {
    return url.split('?')[0];
};

/**
 * Get data from String
 * @param  {String} string
 * @return {Object}
 */
OAuth.prototype.deParam = function(string) {
    var arr = string.split('&');
    var data = {};

    for(var i = 0; i < arr.length; i++) {
        var item = arr[i].split('=');

        // '' value
        item[1] = item[1] || '';

        data[item[0]] = decodeURIComponent(item[1]);
    }

    return data;
};

/**
 * Get data from url
 * @param  {String} url
 * @return {Object}
 */
OAuth.prototype.deParamUrl = function(url) {
    var tmp = url.split('?');

    if (tmp.length === 1)
        return {};

    return this.deParam(tmp[1]);
};

/**
 * Percent Encode
 * @param  {String} str
 * @return {String} percent encoded string
 */
OAuth.prototype.percentEncode = function(str) {
    return encodeURIComponent(str)
        .replace(/\!/g, "%21")
        .replace(/\*/g, "%2A")
        .replace(/\'/g, "%27")
        .replace(/\(/g, "%28")
        .replace(/\)/g, "%29");
};

/**
 * Percent Encode Object
 * @param  {Object} data
 * @return {Object} percent encoded data
 */
OAuth.prototype.percentEncodeData = function(data) {
    var result = {};

    for(var key in data) {
        var value = data[key];
        // check if the value is an array
        if (value && Array.isArray(value)){
          var newValue = [];
          // percentEncode every value
          value.forEach((function(val){
            newValue.push(this.percentEncode(val));
          }).bind(this));
          value = newValue;
        } else {
          value = this.percentEncode(value);
        }
        result[this.percentEncode(key)] = value;
    }

    return result;
};

/**
 * Get OAuth data as Header
 * @param  {Object} oauth_data
 * @return {String} Header data key - value
 */
OAuth.prototype.toHeader = function(oauth_data) {
    var sorted = this.sortObject(oauth_data);

    var header_value = 'OAuth ';

    if (this.realm) {
        header_value += 'realm="' + this.realm + '"' + this.parameter_seperator;
    }

    for(var i = 0; i < sorted.length; i++) {
        if (sorted[i].key.indexOf('oauth_') !== 0)
            continue;

        header_value += this.percentEncode(sorted[i].key) + '="' + this.percentEncode(sorted[i].value) + '"' + this.parameter_seperator;
    }

    return {
        Authorization: header_value.substr(0, header_value.length - this.parameter_seperator.length) //cut the last chars
    };
};

/**
 * Create a random word characters string with input length
 * @return {String} a random word characters string
 */
OAuth.prototype.getNonce = function() {
    var word_characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    var result = '';

    for(var i = 0; i < this.nonce_length; i++) {
        result += word_characters[parseInt(Math.random() * word_characters.length, 10)];
    }

    return result;
};

/**
 * Get Current Unix TimeStamp
 * @return {Int} current unix timestamp
 */
OAuth.prototype.getTimeStamp = function() {
    return parseInt(new Date().getTime()/1000, 10);
};

////////////////////// HELPER FUNCTIONS //////////////////////

/**
 * Merge object
 * @param  {Object} obj1
 * @param  {Object} obj2
 * @return {Object}
 */
OAuth.prototype.mergeObject = function(obj1, obj2) {
    obj1 = obj1 || {};
    obj2 = obj2 || {};

    var merged_obj = obj1;
    for(var key in obj2) {
        merged_obj[key] = obj2[key];
    }
    return merged_obj;
};

/**
 * Sort object by key
 * @param  {Object} data
 * @return {Object} sorted object
 */
OAuth.prototype.sortObject = function(data) {
    var keys = Object.keys(data);
    var result = [];

    keys.sort();

    for(var i = 0; i < keys.length; i++) {
        var key = keys[i];
        result.push({
            key: key,
            value: data[key],
        });
    }

    return result;
};
<|endoftext|>


<commit_before>export default function mix(Parent) {

	class Mixed extends Parent {}

	return {
		Mixed,
		with() {
			let mixins = Array.prototype.slice.call(arguments, 1);

			for (let mixin of mixins) {
				for (let prop in mixin) {
					Mixed.prototype[prop] = mixin[prop];
				}
			}

			return Mixed;
		}
	};
};	<commit_msg>adds prototype methods to mix object<commit_after>export default function mix(Parent) {

	class Mixed extends Parent {}

	return {
		Mixed,
		with(...mixins) {

			for (let mixin of mixins) {
				for (let prop in mixin) {
					Mixed.prototype[prop] = mixin[prop];
				}

				for (let prop in mixin.prototype) {
					Mixed.prototype[prop] = mixin.prototype[prop];
				}
			}

			return Mixed;
		}
	};
};	<|endoftext|>


<commit_before>$("#run").click(function() {

  /* Results Table Manipulation */

  var resultsTable = $("#results-table");

  function appendHeading(heading) {
    resultsTable.append(
      "
" + heading + "
"
    );
  }

  function appendResult(klass, title, url, inputSize, parseTime) {
    var KB      = 1024;
    var MS_IN_S = 1000;

    resultsTable.append(
        "
"
      +   ""
      +     (url !== null ? "" : "")
      +       title
      +     (url !== null ? "" : "")
      +   "	"
      +   ""
      +     ""
      +       (inputSize / KB).toFixed(2)
      +     ""
      +     " kB"
      +   "	"
      +   ""
      +     ""
      +       parseTime.toFixed(2)
      +     ""
      +     " ms"
      +   "	"
      +   ""
      +     ""
      +       ((inputSize / KB) / (parseTime / MS_IN_S)).toFixed(2)
      +     ""
      +     " kB/s"
      +   "	"
      + "
"
    );
  }

  /* Main */

  /*
   * Each input is parsed multiple times and the results are averaged. We
   * do this for two reasons:
   *
   *   1. To warm up the interpreter (PEG.js-generated parsers will be
   *      most likely used repeatedly, so it makes sense to measure
   *      performance after warming up).
   *
   *   2. To minimize random errors.
   */

  var runCount = parseInt($("#run-count").val(), 10);
  if (isNaN(runCount) || runCount <= 0) {
    alert("Number of runs must be a positive integer.");
    return;
  }

  var options = {
    cache:    $("#cache").is(":checked"),
    optimize: $("#optimize").val()
  };

  Runner.run(benchmarks, runCount, options, {
    readFile: function(file) {
      return $.ajax({
        type:     "GET",
        url:      file,
        dataType: "text",
        async:    false
      }).responseText;
    },

    testStart: function(benchmark, test) {
      /* Nothing to do. */
    },

    testFinish: function(benchmark, test, inputSize, parseTime) {
      appendResult(
        "individual",
        test.title,
        benchmark.id + "/" + test.file,
        inputSize,
        parseTime
      );
    },

    benchmarkStart: function(benchmark) {
      appendHeading(benchmark.title);
    },

    benchmarkFinish: function(benchmark, inputSize, parseTime) {
      appendResult(
        "benchmark-total",
        benchmark.title + " total",
        null,
        inputSize,
        parseTime
      );
    },

    start: function() {
      $("#run-count, #cache, #run").attr("disabled", "disabled");

      resultsTable.show();
      $("#results-table tr").slice(1).remove();
    },

    finish: function(inputSize, parseTime) {
      appendResult(
        "total",
        "Total",
        null,
        inputSize,
        parseTime
      );

      $.scrollTo("max", { axis: "y", duration: 500 });

      $("#run-count, #cache, #run").removeAttr("disabled");
    }
  });

});

$(document).ready(function() {
  $("#run").focus();
});
<commit_msg>Small cleanup of benchmark/index.js<commit_after>$("#run").click(function() {

  /* Results Table Manipulation */

  var resultsTable = $("#results-table");

  function appendHeading(heading) {
    resultsTable.append(
      "
" + heading + "
"
    );
  }

  function appendResult(klass, title, url, inputSize, parseTime) {
    var KB      = 1024,
        MS_IN_S = 1000;

    resultsTable.append(
        "
"
      +   ""
      +     (url !== null ? "" : "")
      +       title
      +     (url !== null ? "" : "")
      +   "	"
      +   ""
      +     ""
      +       (inputSize / KB).toFixed(2)
      +     ""
      +     " kB"
      +   "	"
      +   ""
      +     ""
      +       parseTime.toFixed(2)
      +     ""
      +     " ms"
      +   "	"
      +   ""
      +     ""
      +       ((inputSize / KB) / (parseTime / MS_IN_S)).toFixed(2)
      +     ""
      +     " kB/s"
      +   "	"
      + "
"
    );
  }

  /* Main */

  /*
   * Each input is parsed multiple times and the results are averaged. We
   * do this for two reasons:
   *
   *   1. To warm up the interpreter (PEG.js-generated parsers will be
   *      most likely used repeatedly, so it makes sense to measure
   *      performance after warming up).
   *
   *   2. To minimize random errors.
   */

  var runCount = parseInt($("#run-count").val(), 10),
      options  = {
        cache:    $("#cache").is(":checked"),
        optimize: $("#optimize").val()
      };

  if (isNaN(runCount) || runCount <= 0) {
    alert("Number of runs must be a positive integer.");
    return;
  }

  Runner.run(benchmarks, runCount, options, {
    readFile: function(file) {
      return $.ajax({
        type:     "GET",
        url:      file,
        dataType: "text",
        async:    false
      }).responseText;
    },

    testStart: function(benchmark, test) {
      /* Nothing to do. */
    },

    testFinish: function(benchmark, test, inputSize, parseTime) {
      appendResult(
        "individual",
        test.title,
        benchmark.id + "/" + test.file,
        inputSize,
        parseTime
      );
    },

    benchmarkStart: function(benchmark) {
      appendHeading(benchmark.title);
    },

    benchmarkFinish: function(benchmark, inputSize, parseTime) {
      appendResult(
        "benchmark-total",
        benchmark.title + " total",
        null,
        inputSize,
        parseTime
      );
    },

    start: function() {
      $("#run-count, #cache, #run").attr("disabled", "disabled");

      resultsTable.show();
      $("#results-table tr").slice(1).remove();
    },

    finish: function(inputSize, parseTime) {
      appendResult(
        "total",
        "Total",
        null,
        inputSize,
        parseTime
      );

      $.scrollTo("max", { axis: "y", duration: 500 });

      $("#run-count, #cache, #run").removeAttr("disabled");
    }
  });

});

$(document).ready(function() {
  $("#run").focus();
});
<|endoftext|>


<commit_before>Error.stackTraceLimit = Infinity;

var jsTrans = require("jstransform");
var traceur = require("traceur");
var es6tr   = require("es6-transpiler");
var es6now  = require("es6now");
//var esnext  = require("esnext");
var to5     = require("../lib/6to5");

//var uglify  = require("uglify-js");
var matcha  = require("matcha");
var path    = require("path");
var fs      = require("fs");
var _       = require("lodash");

var readResolve = function (filename) {
  try {
    filename = require.resolve(filename);
  } catch (err) {
    return null;
  }
  return fs.readFileSync(filename, "utf8");
};

var getVersion = function (name) {
  return require(name + "/package.json").version;
};

var jsTransVisitors = [];

_.each([
  "arrow-function-visitors", "class-visitors", "destructuring-visitors",
  "object-concise-method-visitors", "object-short-notation-visitors",
  "rest-param-visitors", "template-visitors"
], function (name) {
  var mod = require("jstransform/visitors/es6-" + name);
  jsTransVisitors = jsTransVisitors.concat(mod.visitorList);
});

var compilers = {
  "6to5": {
    version: getVersion(".."),
    compile: function (code, filename) {
      return to5.transform(code, { filename: filename }).code;
    }
  },

  traceur: {
    runtime: readResolve("traceur/bin/traceur-runtime.js"),
    compile: function (code) {
      return traceur.compile(code, {
        modules: "commonjs",
        experimental: true
      });
    }
  },

  /*esnext: {
    runtime: readResolve("esnext/node_modules/regenerator/runtime.js") || readResolve("regenerator/runtime.js"),
    compile: function (code) {
      return esnext.compile(code).code;
    }
  },*/

  es6now: {
    runtime: readResolve("es6now/runtime/ES6.js"),
    compile: function (code) {
      return es6now.translate(code);
    }
  },

  "es6-transpiler": {
    compile: function (code) {
      var result = es6tr.run({ src: code });
      if (result.errors.length) throw new Error(result.join("; "));
      return result.src;
    }
  },

  jstransform: {
    compile: function (code) {
      return jsTrans.transform(jsTransVisitors, code).code;
    }
  }
};

// versions

//var uglifyTitle = "uglify v" + getVersion("uglify-js");

_.each(compilers, function (compiler, name) {
  compiler.title = name + " v" + (compiler.version || getVersion(name));
});

//

var sizeBenchmark = function (code, loc, name, compiler) {
  var log = function (output, title) {
    title = [compiler.title].concat(title || []).join(" + ");

    var text;
    var color;
    if (output.stack) {
      text = "error";
      color = "red";
    } else {
      var kilo  = (output.length / 1024).toFixed(2);
      text = kilo + "KB";
      color = "cyan";
    }

    text = matcha.utils.color(matcha.utils.padBefore(text, 22), color);

    console.log(text, matcha.utils.color("» " + title, "gray"));

    if (output.stack) {
      console.error(output.stack);
    }
  };

  var go = function (getOutput, title) {
    var code;
    try {
      code = getOutput();
    } catch (err) {
      log(err, title);
      return;
    }

    log(code, title);
  };

  var output;
  go(function () {
    return output = compiler.compile(code, loc);
  });
  if (!output) return;

  //go(function () {
  //  return uglify.minify(output, { fromString: true }).code;
  //}, uglifyTitle);
};

//

_.each(fs.readdirSync(__dirname + "/fixtures"), function (name) {
  var alias = path.basename(name, path.extname(name));

  suite(alias, function () {
    set("delay", 0);

    var loc  = __dirname + "/fixtures/" + name;
    var code = fs.readFileSync(loc, "utf8");

    before(function () {
      _.each(compilers, function (compiler, name) {
        sizeBenchmark(code, loc, name, compiler);
      });
    });

    _.each(compilers, function (compiler) {
      bench(compiler.title, function () {
        compiler.compile(code, loc);
      });
    });
  });
});
<commit_msg>disable es6-transpiler<commit_after>Error.stackTraceLimit = Infinity;

var jsTrans = require("jstransform");
var traceur = require("traceur");
//var es6tr   = require("es6-transpiler");
var es6now  = require("es6now");
//var esnext  = require("esnext");
var to5     = require("../lib/6to5");

//var uglify  = require("uglify-js");
var matcha  = require("matcha");
var path    = require("path");
var fs      = require("fs");
var _       = require("lodash");

var readResolve = function (filename) {
  try {
    filename = require.resolve(filename);
  } catch (err) {
    return null;
  }
  return fs.readFileSync(filename, "utf8");
};

var getVersion = function (name) {
  return require(name + "/package.json").version;
};

var jsTransVisitors = [];

_.each([
  "arrow-function-visitors", "class-visitors", "destructuring-visitors",
  "object-concise-method-visitors", "object-short-notation-visitors",
  "rest-param-visitors", "template-visitors"
], function (name) {
  var mod = require("jstransform/visitors/es6-" + name);
  jsTransVisitors = jsTransVisitors.concat(mod.visitorList);
});

var compilers = {
  "6to5": {
    version: getVersion(".."),
    compile: function (code, filename) {
      return to5.transform(code, { filename: filename }).code;
    }
  },

  traceur: {
    runtime: readResolve("traceur/bin/traceur-runtime.js"),
    compile: function (code) {
      return traceur.compile(code, {
        modules: "commonjs",
        experimental: true
      });
    }
  },

  /*esnext: {
    runtime: readResolve("esnext/node_modules/regenerator/runtime.js") || readResolve("regenerator/runtime.js"),
    compile: function (code) {
      return esnext.compile(code).code;
    }
  },*/

  es6now: {
    runtime: readResolve("es6now/runtime/ES6.js"),
    compile: function (code) {
      return es6now.translate(code);
    }
  },

  /*"es6-transpiler": {
    compile: function (code) {
      var result = es6tr.run({ src: code });
      if (result.errors.length) throw new Error(result.join("; "));
      return result.src;
    }
  },*/

  jstransform: {
    compile: function (code) {
      return jsTrans.transform(jsTransVisitors, code).code;
    }
  }
};

// versions

//var uglifyTitle = "uglify v" + getVersion("uglify-js");

_.each(compilers, function (compiler, name) {
  compiler.title = name + " v" + (compiler.version || getVersion(name));
});

//

var sizeBenchmark = function (code, loc, name, compiler) {
  var log = function (output, title) {
    title = [compiler.title].concat(title || []).join(" + ");

    var text;
    var color;
    if (output.stack) {
      text = "error";
      color = "red";
    } else {
      var kilo  = (output.length / 1024).toFixed(2);
      text = kilo + "KB";
      color = "cyan";
    }

    text = matcha.utils.color(matcha.utils.padBefore(text, 22), color);

    console.log(text, matcha.utils.color("» " + title, "gray"));

    if (output.stack) {
      console.error(output.stack);
    }
  };

  var go = function (getOutput, title) {
    var code;
    try {
      code = getOutput();
    } catch (err) {
      log(err, title);
      return;
    }

    log(code, title);
  };

  var output;
  go(function () {
    return output = compiler.compile(code, loc);
  });
  if (!output) return;

  //go(function () {
  //  return uglify.minify(output, { fromString: true }).code;
  //}, uglifyTitle);
};

//

_.each(fs.readdirSync(__dirname + "/fixtures"), function (name) {
  var alias = path.basename(name, path.extname(name));

  suite(alias, function () {
    set("delay", 0);

    var loc  = __dirname + "/fixtures/" + name;
    var code = fs.readFileSync(loc, "utf8");

    before(function () {
      _.each(compilers, function (compiler, name) {
        sizeBenchmark(code, loc, name, compiler);
      });
    });

    _.each(compilers, function (compiler) {
      bench(compiler.title, function () {
        compiler.compile(code, loc);
      });
    });
  });
});
<|endoftext|>


<commit_before>~function() {
    var gradient = 0,
        stroke,
        x = 0,
        y = 0,
        xSpacing = 90,
        ySpacing = 90,
        template = document.querySelector('#wave-orb').innerHTML,
        viewport = {},

        adjustElement = function(element, left, top) {
            element.style.position = 'fixed';
            element.style.marginTop = -45 + 'px';
            element.style.marginLeft = -45 + 'px';
            element.style.paddingLeft = left + 'px';
            element.style.paddingTop = top + 'px';
        },
        colorElement = function(element) {
            element.querySelector('.ring').style.borderColor = stroke;
            element.querySelector('.particle').style.background = stroke;

            if (gradient[y]) {
                element.querySelector('.ring').style.background = 'rgba(' + gradient[y].join(',') + ', 0.75)';
            }
        },
        getGradient = function(samples, rgbTo, rgbFrom) {
            var rgbDiff = [
                    rgbTo[0] - rgbFrom[0],
                    rgbTo[1] - rgbFrom[1],
                    rgbTo[2] - rgbFrom[2]
                ],
                hues = [],
                i;

            for (i = 0; i < samples; i++) {
                hues.push(getGradientPoint(i / samples, rgbDiff, rgbFrom));
            }
            return hues;
        },
        getGradientPoint = function(delta, rgbDiff, rgbFrom) {
            return [
                Math.floor(rgbDiff[0] * delta + rgbFrom[0]),
                Math.floor(rgbDiff[1] * delta + rgbFrom[1]),
                Math.floor(rgbDiff[2] * delta + rgbFrom[2])
            ];
        },
        resetValues = function() {
            x = 0;
            y = 0;
        },
        storeViewport = function() {
            viewport.height = window.innerHeight,
            viewport.width = window.innerWidth;
        },
        resetAll = function() {
            resetValues();
            storeViewport();
            gradient = getGradient(viewport.height / ySpacing, [167, 219, 216], [105, 210, 231]);
            stroke = '#00BCD1';
            document.body.innerHTML = '';
        };

    window.addEventListener('resize', resetAll);
    resetAll();
    setInterval(function() {
        var el,
            left = x * xSpacing,
            top = y * ySpacing;

        if (top < viewport.height + 45) {
            el = document.createElement('div'),
            el.innerHTML = template;
            adjustElement(el, left, top);
            colorElement(el);
            document.body.appendChild(el);

            if (left > viewport.width) {
                y++;
                x = 0;
            } else {
                x++;
            }
        }
    }, 25);
}();
<commit_msg>waves > Random colors.<commit_after>~function() {
    var colors = [
            [[199,237,232], [160,222,214], [69,181,196]],
            [[176,248,255], [174,232,251], [0,188,209]],
            [[0,185,189], [0,126,128], [0,72,83]]
        ],
        gradient = 0,
        stroke,
        x = 0,
        y = 0,
        xSpacing = 90,
        ySpacing = 90,
        template = document.querySelector('#wave-orb').innerHTML,
        viewport = {},

        adjustElement = function(element, left, top) {
            element.style.position = 'fixed';
            element.style.marginTop = -45 + 'px';
            element.style.marginLeft = -45 + 'px';
            element.style.paddingLeft = left + 'px';
            element.style.paddingTop = top + 'px';
        },
        colorElement = function(element) {
            element.querySelector('.ring').style.borderColor = rgba(stroke, 1);
            element.querySelector('.particle').style.background = rgba(stroke, 1);

            if (gradient[y]) {
                element.querySelector('.ring').style.background = rgba(gradient[y], 0.75);
            }
        },
        getGradient = function(samples, rgbTo, rgbFrom) {
            var rgbDiff = [
                    rgbTo[0] - rgbFrom[0],
                    rgbTo[1] - rgbFrom[1],
                    rgbTo[2] - rgbFrom[2]
                ],
                hues = [],
                i;

            for (i = 0; i < samples; i++) {
                hues.push(getGradientPoint(i / samples, rgbDiff, rgbFrom));
            }
            return hues;
        },
        getGradientPoint = function(delta, rgbDiff, rgbFrom) {
            return [
                Math.floor(rgbDiff[0] * delta + rgbFrom[0]),
                Math.floor(rgbDiff[1] * delta + rgbFrom[1]),
                Math.floor(rgbDiff[2] * delta + rgbFrom[2])
            ];
        },
        getRandomColors = function() {
            return colors[Math.floor((Math.random() * colors.length))];
        },
        rgba = function(colors, alpha) {
            return 'rgba(' + colors.join(',') + ', ' + alpha + ')';
        },
        resetValues = function() {
            x = 0;
            y = 0;
        },
        storeViewport = function() {
            viewport.height = window.innerHeight,
            viewport.width = window.innerWidth;
        },
        resetAll = function() {
            var colorSet = getRandomColors();

            resetValues();
            storeViewport();
            gradient = getGradient(viewport.height / ySpacing, colorSet[0], colorSet[1]);
            stroke = colorSet[2];
            document.body.innerHTML = '';
        };

    window.addEventListener('resize', resetAll);
    resetAll();
    setInterval(function() {
        var el,
            left = x * xSpacing,
            top = y * ySpacing;

        if (top < viewport.height + 45) {
            el = document.createElement('div'),
            el.innerHTML = template;
            adjustElement(el, left, top);
            colorElement(el);
            document.body.appendChild(el);

            if (left > viewport.width) {
                y++;
                x = 0;
            } else {
                x++;
            }
        }
    }, 25);
}();
<|endoftext|>


<commit_before>exports.config = {
  //
  // ==================
  // Specify Test Files
  // ==================
  // Define which test specs should run. The pattern is relative to the directory
  // from which `wdio` was called. Notice that, if you are calling `wdio` from an
  // NPM script (see https://docs.npmjs.com/cli/run-script) then the current working
  // directory is where your package.json resides, so `wdio` will be called from there.
  //
  specs: [
    './e2e_test/**/*.js'
  ],
  // Patterns to exclude.
  exclude: [
    // 'path/to/excluded/files'
  ],
  //
  // ============
  // Capabilities
  // ============
  // Define your capabilities here. WebdriverIO can run multiple capabilties at the same
  // time. Depending on the number of capabilities, WebdriverIO launches several test
  // sessions. Within your capabilities you can overwrite the spec and exclude option in
  // order to group specific specs to a specific capability.
  //
  // If you have trouble getting all important capabilities together, check out the
  // Sauce Labs platform configurator - a great tool to configure your capabilities:
  // https://docs.saucelabs.com/reference/platforms-configurator
  //
  capabilities: [
    // {
    //   browserName: 'phantomjs',
    //   'phantomjs.binary.path': require('phantomjs').path
    // },
    {
      browserName: 'chrome'
    }
  ],
  //
  // ===================
  // Test Configurations
  // ===================
  // Define all options that are relevant for the WebdriverIO instance here
  //
  // Level of logging verbosity: silent | verbose | command | data | result | error
  logLevel: 'command',
  //
  // Enables colors for log output.
  coloredLogs: true,
  //
  // Saves a screenshot to a given path if a command fails.
  screenshotPath: './errorShots/',
  //
  // Set a base URL in order to shorten url command calls. If your url parameter starts
  // with "/", the base url gets prepended.
  baseUrl: 'http://localhost:8000',
  //
  // Default timeout for all waitForXXX commands.
  waitforTimeout: 10000,
  //
  // Initialize the browser instance with a WebdriverIO plugin. The object should have the
  // plugin name as key and the desired plugin options as property. Make sure you have
  // the plugin installed before running any tests. The following plugins are currently
  // available:
  // WebdriverCSS: https://github.com/webdriverio/webdrivercss
  // WebdriverRTC: https://github.com/webdriverio/webdriverrtc
  // Browserevent: https://github.com/webdriverio/browserevent
  // plugins: {
  //     webdrivercss: {
  //         screenshotRoot: 'my-shots',
  //         failedComparisonsRoot: 'diffs',
  //         misMatchTolerance: 0.05,
  //         screenWidth: [320,480,640,1024]
  //     },
  //     webdriverrtc: {},
  //     browserevent: {}
  // },
  //
  // Framework you want to run your specs with.
  // The following are supported: mocha, jasmine and cucumber
  // see also: http://webdriver.io/guide/testrunner/frameworks.html
  //
  // Make sure you have the node package for the specific framework installed before running
  // any tests. If not please install the following package:
  // Mocha: `$ npm install mocha`
  // Jasmine: `$ npm install jasmine`
  // Cucumber: `$ npm install cucumber`
  framework: 'jasmine',
  //
  // Test reporter for stdout.
  // The following are supported: dot (default), spec and xunit
  // see also: http://webdriver.io/guide/testrunner/reporters.html
  reporter: 'spec',

  //
  // Options to be passed to Jasmine.
  jasmineNodeOpts: {
    //
    // Jasmine default timeout
    defaultTimeoutInterval: 10000,
    //
    // The Jasmine framework allows it to intercept each assertion in order to log the state of the application
    // or website depending on the result. For example it is pretty handy to take a screenshot everytime
    // an assertion fails.
    expectationResultHandler: function (passed, assertion) {
      /**
       * only take screenshot if assertion failed
       */
      if (passed) {
        return
      }

      var title = assertion.message.replace(/\s/g, '-')
      browser.saveScreenshot(('./errorShots/assertionError_' + title + '.png'))
    }
  },

  //
  // =====
  // Hooks
  // =====
  // Run functions before or after the test. If one of them returns with a promise, WebdriverIO
  // will wait until that promise got resolved to continue.
  //
  // Gets executed before all workers get launched.
  onPrepare: function () {
    // do something
  },
  //
  // Gets executed before test execution begins. At this point you will have access to all global
  // variables like `browser`. It is the perfect place to define custom commands.
  before: function () {
    // do something
  },
  //
  // Gets executed after all tests are done. You still have access to all global variables from
  // the test.
  after: function (failures, pid) {
    // do something
  },
  //
  // Gets executed after all workers got shut down and the process is about to exit. It is not
  // possible to defer the end of the process using a promise.
  onComplete: function () {
    // do something
  }
}
<commit_msg>minor fix wdio.conf.js<commit_after>exports.config = {
  //
  // ==================
  // Specify Test Files
  // ==================
  // Define which test specs should run. The pattern is relative to the directory
  // from which `wdio` was called. Notice that, if you are calling `wdio` from an
  // NPM script (see https://docs.npmjs.com/cli/run-script) then the current working
  // directory is where your package.json resides, so `wdio` will be called from there.
  //
  specs: [
    './e2e_test/**/*.spec.js'
  ],
  // Patterns to exclude.
  exclude: [
    './e2e_test/libs/**/*.*'
  // 'path/to/excluded/files'
  ],
  //
  // ============
  // Capabilities
  // ============
  // Define your capabilities here. WebdriverIO can run multiple capabilties at the same
  // time. Depending on the number of capabilities, WebdriverIO launches several test
  // sessions. Within your capabilities you can overwrite the spec and exclude option in
  // order to group specific specs to a specific capability.
  //
  // If you have trouble getting all important capabilities together, check out the
  // Sauce Labs platform configurator - a great tool to configure your capabilities:
  // https://docs.saucelabs.com/reference/platforms-configurator
  //
  capabilities: [
    // {
    //   browserName: 'phantomjs',
    //   'phantomjs.binary.path': require('phantomjs').path
    // },
    {
      browserName: 'chrome'
    }
  ],
  //
  // ===================
  // Test Configurations
  // ===================
  // Define all options that are relevant for the WebdriverIO instance here
  //
  // Level of logging verbosity: silent | verbose | command | data | result | error
  logLevel: 'command',
  //
  // Enables colors for log output.
  coloredLogs: true,
  //
  // Saves a screenshot to a given path if a command fails.
  screenshotPath: './errorShots/',
  //
  // Set a base URL in order to shorten url command calls. If your url parameter starts
  // with "/", the base url gets prepended.
  baseUrl: 'http://localhost:8000',
  //
  // Default timeout for all waitForXXX commands.
  waitforTimeout: 10000,
  //
  // Initialize the browser instance with a WebdriverIO plugin. The object should have the
  // plugin name as key and the desired plugin options as property. Make sure you have
  // the plugin installed before running any tests. The following plugins are currently
  // available:
  // WebdriverCSS: https://github.com/webdriverio/webdrivercss
  // WebdriverRTC: https://github.com/webdriverio/webdriverrtc
  // Browserevent: https://github.com/webdriverio/browserevent
  // plugins: {
  // webdrivercss: {
  //     screenshotRoot: 'my-shots',
  //     failedComparisonsRoot: 'diffs',
  //     misMatchTolerance: 0.05,
  //     screenWidth: [320,480,640,1024]
  // },
  // webdriverrtc: {},
  // browserevent: {}
  // },
  //
  // Framework you want to run your specs with.
  // The following are supported: mocha, jasmine and cucumber
  // see also: http://webdriver.io/guide/testrunner/frameworks.html
  //
  // Make sure you have the node package for the specific framework installed before running
  // any tests. If not please install the following package:
  // Mocha: `$ npm install mocha`
  // Jasmine: `$ npm install jasmine`
  // Cucumber: `$ npm install cucumber`
  framework: 'jasmine',
  //
  // Test reporter for stdout.
  // The following are supported: dot (default), spec and xunit
  // see also: http://webdriver.io/guide/testrunner/reporters.html
  reporter: 'spec',

  //
  // Options to be passed to Jasmine.
  jasmineNodeOpts: {
    //
    // Jasmine default timeout
    defaultTimeoutInterval: 10000,
    //
    // The Jasmine framework allows it to intercept each assertion in order to log the state of the application
    // or website depending on the result. For example it is pretty handy to take a screenshot everytime
    // an assertion fails.
    expectationResultHandler: function (passed, assertion) {
      /**
       * only take screenshot if assertion failed
       */
      if (passed) {
        return
      }

      var title = assertion.message.replace(/\s/g, '-')
      browser.saveScreenshot(('./errorShots/assertionError_' + title + '.png'))
    }
  },

  //
  // =====
  // Hooks
  // =====
  // Run functions before or after the test. If one of them returns with a promise, WebdriverIO
  // will wait until that promise got resolved to continue.
  //
  // Gets executed before all workers get launched.
  onPrepare: function () {
    // do something
  },
  //
  // Gets executed before test execution begins. At this point you will have access to all global
  // variables like `browser`. It is the perfect place to define custom commands.
  before: function () {
    // do something
  },
  //
  // Gets executed after all tests are done. You still have access to all global variables from
  // the test.
  after: function (failures, pid) {
    // do something
  },
  //
  // Gets executed after all workers got shut down and the process is about to exit. It is not
  // possible to defer the end of the process using a promise.
  onComplete: function () {
    // do something
  }
}
<|endoftext|>


<commit_before>const request = require("request")
const resolve = require("url").resolve

const config = {
  specs: [
    "./e2e-tests/**/*.tests.js"
  ],
  exclude: [],
  maxInstances: 10,
  sync: true,
  logLevel: "result",
  coloredLogs: true,
  screenshotPath: "./e2e-tests/error-screenshots",
  baseUrl: "http://the8-dev.azurewebsites.net",
  waitforTimeout: 10000,
  connectionRetryTimeout: 90000,
  connectionRetryCount: 3,
  framework: "jasmine",
  jasmineNodeOpts: {
    defaultTimeoutInterval: 10000
  },
  reporters: ["spec"],
  reporterOptions: {
    outputDir: "./e2e-tests/test-results"
  },
  services: ["phantomjs"],
  capabilities: [
    {
      maxInstances: 5,
      browserName: "chrome"
    }
  ],
  afterTest: test => console.log(test)
}

if (process.env.APPVEYOR) {
  console.log("Detected AppVeyor")
  const url = resolve(process.env.APPVEYOR_API_URL, "/api/tests")

  config.afterTest = test => {
    const body = {
      "testName": test.fullName,
      "testFramework": "WebdriverIO",
      "fileName": test.file,
      "outcome": test.passed ? "Passed" : "Failed",
      "durationMilliseconds": test.duration
    }

    console.log("Sending test results to AppVeyor")
    console.log(body)

    request({
      url,
      json: true,
      body
    })
  }
}

exports.config = config<commit_msg>More logging<commit_after>const request = require("request")
const resolve = require("url").resolve

const config = {
  specs: [
    "./e2e-tests/**/*.tests.js"
  ],
  exclude: [],
  maxInstances: 10,
  sync: true,
  logLevel: "result",
  coloredLogs: true,
  screenshotPath: "./e2e-tests/error-screenshots",
  baseUrl: "http://the8-dev.azurewebsites.net",
  waitforTimeout: 10000,
  connectionRetryTimeout: 90000,
  connectionRetryCount: 3,
  framework: "jasmine",
  jasmineNodeOpts: {
    defaultTimeoutInterval: 10000
  },
  reporters: ["spec"],
  reporterOptions: {
    outputDir: "./e2e-tests/test-results"
  },
  services: ["phantomjs"],
  capabilities: [
    {
      maxInstances: 5,
      browserName: "chrome"
    }
  ],
  afterTest: test => console.log(test)
}

if (process.env.APPVEYOR) {
  console.log("Detected AppVeyor")
  const url = resolve(process.env.APPVEYOR_API_URL, "/api/tests")
  console.log(`Posting test results to ${url}`)

  config.afterTest = test => {
    const body = {
      "testName": test.fullName,
      "testFramework": "WebdriverIO",
      "fileName": test.file,
      "outcome": test.passed ? "Passed" : "Failed",
      "durationMilliseconds": test.duration
    }

    console.log("Sending test results to AppVeyor")
    console.log(body)

    request({
      url,
      json: true,
      body
    })
  }
}

exports.config = config<|endoftext|>


<commit_before>Metrix.Board = function(pixi) {
  this.pixi = pixi;
  this.updateTime = 1000;

  // columns / rows
  this.columns = 8;
  this.rows = 12;

  // blocks[columns][rows]
  this.blockSize = this.pixi.screenScale * 100 / this.rows;
  this.blocks = new Array(this.columns * this.rows);
  for (var i = 0; i < this.columns * this.rows; i++) {
    this.blocks[i] = new Metrix.Block(this, this.blockSize);
  }
  this.blocksMaxIndex = -1;

  // use a board container to manage blocks and grid content on one layer
  this.container = new PIXI.Container();
  this.pixi.stage.addChild(this.container);

  // grid to manage blocks in fields
  this.grid = new Metrix.Grid(this, this.columns, this.rows);
  this.grid.addGfx();

  // add default text elements
  this.points = 0;
  this.pointsPrefixText = "Points: ";
  this.pointsText = new Metrix.Text(this, this.pointsPrefixText + this.points, 1, 12, "left");
  this.credits = new Metrix.Text(this, "idx.codelab", 9, 12, "right");

};

Metrix.Board.prototype.constructor = Metrix.Board;

Metrix.Board.prototype.addRandomBlock = function() {
  var blockRandColumn = Math.round(Math.random() * (this.grid.columns - 1));
  this.addBlock(blockRandColumn, 0);
};

Metrix.Board.prototype.addBlock = function(column, row) {
  this.blocksMaxIndex += 1;
  this.blocks[this.blocksMaxIndex].setPosition(column, row);
  this.blocks[this.blocksMaxIndex].setRandomColor();
  this.blocks[this.blocksMaxIndex].addGfx();
  this.blocks[this.blocksMaxIndex].show();
  // register block as grid field
  this.grid.setBlockIndex(column, row, this.blocksMaxIndex);
  this.grid.setMovementField(column, row); // every new block is located in a movement field
};

Metrix.Board.prototype.addPoints = function(pointsToAdd) {
  this.points += pointsToAdd;
  this.pointsText.setText(this.pointsPrefixText + this.points);
};

Metrix.Board.prototype.moveBlocks = function(enableMovement) {
  if (enableMovement === true) {
    for (var i = 0; i < this.grid.columns; i++) {
      // scan from bottom to top to avoid extra movements
      for (var j = this.grid.rows - 1; j > -1; j--) {
        var blockIndex = this.grid.setSelectedFieldDown(i, j);
        if (blockIndex > -1) {
          this.blocks[blockIndex].moveDown();
        } else if (this.grid.isMovementField(i, j) == true) {
          enableMovement = false;
          this.addPoints(100);
        }
      }
    }
  }
  if (enableMovement !== true)
    this.addRandomBlock();
  var scope = this;
  setTimeout(function() { scope.moveBlocks(true); }, scope.updateTime);
};

Metrix.Board.prototype.setControl = function() {
  this.control = new Metrix.Control(this);
  this.control.setKeyEvents();
  this.control.setButtonEvents();
};
<commit_msg>set block if a free field is available<commit_after>Metrix.Board = function(pixi) {
  this.pixi = pixi;
  this.updateTime = 1000;

  // columns / rows
  this.columns = 8;
  this.rows = 12;

  // blocks[columns][rows]
  this.blockSize = this.pixi.screenScale * 100 / this.rows;
  this.blocks = new Array(this.columns * this.rows);
  for (var i = 0; i < this.columns * this.rows; i++) {
    this.blocks[i] = new Metrix.Block(this, this.blockSize);
  }
  this.blocksMaxIndex = -1;

  // use a board container to manage blocks and grid content on one layer
  this.container = new PIXI.Container();
  this.pixi.stage.addChild(this.container);

  // grid to manage blocks in fields
  this.grid = new Metrix.Grid(this, this.columns, this.rows);
  this.grid.addGfx();

  // add default text elements
  this.points = 0;
  this.pointsPrefixText = "Points: ";
  this.pointsText = new Metrix.Text(this, this.pointsPrefixText + this.points, 1, 12, "left");
  this.credits = new Metrix.Text(this, "idx.codelab", 9, 12, "right");

};

Metrix.Board.prototype.constructor = Metrix.Board;

Metrix.Board.prototype.addRandomBlock = function() {
  var loopCount = 0;
  var added = false;
  do {
    var blockRandColumn = Math.round(Math.random() * (this.grid.columns - 1));
    added = this.addBlock(blockRandColumn, 0);
    loopCount++;
  } while (loopCount < 100 && added === false);
  return added;
};

Metrix.Board.prototype.addBlock = function(column, row) {
  var blockIndex = this.grid.getBlockIndex(column, row);
  if (blockIndex == -1) {
    this.blocksMaxIndex += 1;
    this.blocks[this.blocksMaxIndex].setPosition(column, row);
    this.blocks[this.blocksMaxIndex].setRandomColor();
    this.blocks[this.blocksMaxIndex].addGfx();
    this.blocks[this.blocksMaxIndex].show();
    // register block as grid field
    this.grid.setBlockIndex(column, row, this.blocksMaxIndex);
    this.grid.setMovementField(column, row); // every new block is located in a movement field
    return true;
  }
  return false;
};

Metrix.Board.prototype.addPoints = function(pointsToAdd) {
  this.points += pointsToAdd;
  this.pointsText.setText(this.pointsPrefixText + this.points);
};

Metrix.Board.prototype.moveBlocks = function(enableMovement) {
  if (enableMovement === true) {
    for (var i = 0; i < this.grid.columns; i++) {
      // scan from bottom to top to avoid extra movements
      for (var j = this.grid.rows - 1; j > -1; j--) {
        var blockIndex = this.grid.setSelectedFieldDown(i, j);
        if (blockIndex > -1) {
          this.blocks[blockIndex].moveDown();
          this.grid.countFields(i, j+1);

        } else if (this.grid.isMovementField(i, j) == true) {
          enableMovement = false;
          //this.addPoints(100);
        }
      }
    }
  }
  if (enableMovement !== true) {
    if (this.addRandomBlock() === false)
      console.log("game over");
  }
  var scope = this;
  setTimeout(function() { scope.moveBlocks(true); }, scope.updateTime);
};

Metrix.Board.prototype.setControl = function() {
  this.control = new Metrix.Control(this);
  this.control.setKeyEvents();
  this.control.setButtonEvents();
};
<|endoftext|>


<commit_before>// ==UserScript==
// @name              Pixiv自動ブックマークタグ付け
// @description       Pixivのブックマークタグ付けを半自動化してくれる
// @include           http://www.pixiv.net/bookmark_add.php?type=illust&illust_id=*
// @include           http://www.pixiv.net/member_illust.php?mode=medium&illust_id=*
// @run-at            document-end
// @version           0.2.1
// ==/UserScript==

// デフォルトルール
var defaultRuleStr = 'private R-18';

// タグ入力欄
var input = document.querySelector('#input_tag');

// 設定テキストを解析し、連想配列で返す
var parseRules = function(ruleStr) {
	var patternRule    = [];
	var patternAllRule = [];
	var privateRule    = [];
	var errors         = [];

	// 正規表現を表す文字列のリストから、正規表現のリストを作成
	var createRegExpFromStrAry = function(regexpStrAry, lineNumber) {
		var regexps = [];
		regexpStrAry.forEach(function(regexpStr) {
			try { regexps.push(new RegExp(regexpStr)); }
			catch (e) { errors.push({ lineNumber: lineNumber, message: ('RegularExpression Error:' + e.name + ':' + e.massage + ', Str:' + regexpStr) }); }
		});
		return regexps;
	};

	// strに完全一致する正規表現を生成
	var createRegExpPerfectMatch = function(str) {
		return new RegExp('^' + str.replace(/[.*+?^${}()|\[\]\\]/g, '\\$&') + '$');
	};

	ruleStr.split('\n').forEach(function(line, i) {
		var parsed = line.split(/\s+/);
		var matchData;
		var rule;
		if ( parsed.length >= 3 && (matchData = parsed[0].match(/^match(|_all)$/i)) ) {  // 一致
			rule = { tag: parsed[1], regexps: parsed.slice(2).map(createRegExpPerfectMatch) };
		} else if ( parsed.length >= 3 && (matchData = parsed[0].match(/^pattern(|_all)$/i)) ) { // 正規表現
			var regexps = createRegExpFromStrAry(parsed.slice(2), i + 1);
			rule = { tag: parsed[1], regexps: regexps };
		} else if ( parsed.length >= 2 && parsed[0].match(/^private$/i) ) {                     // 非公開タグ
			privateRule.push.apply(privateRule, parsed.slice(1));
			return;
		} else if ( line.match(/^\s*$|^\s*#/) ) {                                               // 空行 or コメント行
			return;
		} else {
			errors.push({ lineNumber: (i+1), message: ('CommandError:Invalid Command or Too Few Arguments, Str:' + line) });
			return;
		}

		Array.prototype.push.call(matchData[1].length === 0 ? patternRule : patternAllRule, rule);
	});
	return { privateRule: privateRule, patternRule: patternRule, patternAllRule: patternAllRule, errors: errors };
};

// matchDataの配列を渡すと文中の~数字をそれで置き換える
var replaceWithMatch = function(input, matchData) {
	return input.split(/(~\d)/).map(function(str) {
		var match = str.match(/^~(\d)/);
		if(match) { return matchData[parseInt(match[1])] || ''; }
		return str;
	}).join('');
};

// 設定画面の生成・消去
var toggleSettingsView = function() {
	// すでに存在していたなら消去
	var settingsView = document.querySelector('#autotag-settings-view');
	if (settingsView) { settingsView.remove(); return; }

	// 保存済みデータの取得
	var ruleStr = window.localStorage.pixivAutoTag_taggingRule || defaultRuleStr;

	// フォームの作成
	settingsView = document.createElement('form');
	settingsView.id = 'autotag-settings-view';
	settingsView.style.backgroundColor = '#FFFFFF';
	settingsView.style.marginTop    = '5px';
	settingsView.style.padding      = '10px 9px';
	settingsView.style.borderRadius = '5px';

	var templateStr  = '
タグ付けルール
<textarea id="autotag-settings-tagging-rule" cols="80" rows="10" style="height:auto;">{{:rule}}</textarea>
';
	settingsView.innerHTML = templateStr.replace('{{:rule}}', ruleStr);

	var buttonsParagraph = document.createElement('p');

	var saveButton = document.createElement('input');
	saveButton.type = 'submit';
	saveButton.className = '_button';
	saveButton.value = '保存';
	settingsView.onsubmit = function() {
		var ruleStr = document.querySelector('#autotag-settings-tagging-rule').value;
		var rule = parseRules(ruleStr);
		if (rule.errors.length === 0) {
			window.localStorage.pixivAutoTag_taggingRule = ruleStr;
			alert('保存しました');
		} else {
			alert(rule.errors.map(function(err) { return '[Error] line: ' + err.lineNumber + ', message: ' + err.message; }).join('\n'));
		}
		return false;
	};
	buttonsParagraph.appendChild(saveButton);

	var cancelButton = document.createElement('input');
	cancelButton.className = '_button';
	cancelButton.type = 'reset';
	cancelButton.value = 'キャンセル';
	// cancelButton.onclick = function() { document.querySelector('#autotag-settings-view').remove(); };
	buttonsParagraph.appendChild(cancelButton);

	settingsView.appendChild(buttonsParagraph);

	var settingsButton = document.querySelector('#autotag-settings-button');
	settingsButton.parentElement.insertBefore(settingsView, settingsButton.nextSibling);
};

// タグの自動追加関数
var autoTag = function() {
	var ruleText = window.localStorage.pixivAutoTag_taggingRule || defaultRuleStr;
	var rule = parseRules(ruleText);

	// 作品タグとタグクラウドの取得
	var tagCloud = Array.prototype.slice.call(document.querySelectorAll('section.list-container.tag-container.tag-cloud-container > ul.list-items.tag-cloud > li')).map(function(item) { return item.textContent; });
	var tagsExist = Array.prototype.concat.apply([], Array.prototype.slice.call(document.querySelectorAll('section.list-container.tag-container.work-tags-container > div > ul span.tag')).map(function(item) { return item.textContent.replace(/^\*/, '').split('/'); }));

	// 非公開タグが含まれていた場合、自動で非公開に設定
	var privateButton = document.querySelector('div.submit-container > ul > li:nth-child(2) > label > input[type="radio"]');
	if (tagsExist.some(function(tag){ return rule.privateRule.indexOf(tag) !== -1; })) {
		privateButton.checked = true;
	}

	// ブックマークタグリストの生成
	if (input.value.length === 0) {
		// 作品タグとタグクラウドの共通タグを抽出
		var tagsFound = tagsExist.filter(function(existTag) { return tagCloud.some(function(cloudTag){ return existTag === cloudTag; }); });

		// 付与タグリストの生成
		var tagsAdded = [];
		tagsExist.forEach(function(tag) { // それぞれの作品タグが
			rule.patternRule.forEach(function(patternRule) { // それぞれのルール文に対し
				var matchData = [];
				var foundMatchFlag = patternRule.regexps.some(function(pattern) { // いずれかのパターンに一致するか
					return (matchData = tag.match(pattern));
				});
				if (foundMatchFlag) { tagsAdded.push(replaceWithMatch(patternRule.tag, matchData)); }
			});
		});

		rule.patternAllRule.forEach(function(patternRule) { // それぞれのルール文の
			var matchData = [];
			var foundMatchFlag = patternRule.regexps.every(function(pattern) { // すべてのパターンが
				return tagsExist.some(function(tag) { return (matchData = tag.match(pattern)); }); // いずれかの作品タグに一致するか？
			});
			if (foundMatchFlag) { tagsAdded.push(replaceWithMatch(patternRule.tag, matchData)); }
		});

		// タグを消去する
		tagsFound = tagsFound.filter(function(foundTag) { return tagsAdded.indexOf('-'+foundTag) === -1; });
		tagsAdded = tagsAdded.filter(function(tag) { return !tag.match(/^-/); });

		// 重複の削除
		var uniqueAry = tagsFound.concat(tagsAdded).filter(function(elem, i, ary) { return ary.indexOf(elem) === i; }).join(' ');

		// ブックマークタグを設定する
		input.value = uniqueAry;

		// タグのハイライトを表示させる
		var keyupEvent = document.createEvent('HTMLEvents');
		keyupEvent.initEvent('keyup', true, true);
		input.dispatchEvent(keyupEvent);

		// タグ付けが終わったら、背景を緑色にして補完がされたことを示す
		input.parentNode.style.backgroundColor = '#76B6E0';
		// それと入力欄にフォーカスする
		input.focus();
	}
};

(function() {
	// 自動タグ付けの実行
	if (window.location.href.match(/member_illust/)) {
		var ul = document.querySelector('section.list-container.tag-container.work-tags-container > div > ul');
		var func = function(fn) { (ul.childNodes.length > 0) ? window.setTimeout(autoTag, 750) : window.setTimeout(fn, 750, fn); };
		window.setTimeout(func, 1250, func);
	} else {
		window.setTimeout(autoTag, 750);
	}

	// 設定ボタンの生成
	var settingsButton = document.createElement('button');
	settingsButton.className = '_button';
	settingsButton.style.marginLeft = '1em';
	settingsButton.id = 'autotag-settings-button';
	settingsButton.textContent = 'タグ自動化設定';
	settingsButton.addEventListener('click', toggleSettingsView, false);

	var target = document.querySelector('section.list-container.tag-container.work-tags-container > div > h1');
	target.parentElement.insertBefore(settingsButton, target.nextSibling);

	// タグ付けボタンの生成
	var autoTagButton = document.createElement('button');
	autoTagButton.className = '_button';
	autoTagButton.style.marginLeft = '0.25em';
	autoTagButton.id = 'autotag-button';
	autoTagButton.textContent = '上書きタグ付け';
	autoTagButton.addEventListener('click', function() { input.value = ''; autoTag(); }, false);
	target.parentElement.insertBefore(autoTagButton, settingsButton.nextSibling);
})();
<commit_msg>enhancement: 一部の関数名を分かりやすくした<commit_after>// ==UserScript==
// @name              Pixiv自動ブックマークタグ付け
// @description       Pixivのブックマークタグ付けを半自動化してくれる
// @include           http://www.pixiv.net/bookmark_add.php?type=illust&illust_id=*
// @include           http://www.pixiv.net/member_illust.php?mode=medium&illust_id=*
// @run-at            document-end
// @version           0.2.1
// ==/UserScript==

// デフォルトルール
var defaultRuleStr = 'private R-18';

// タグ入力欄
var input = document.querySelector('#input_tag');

// 設定テキストを解析し、連想配列で返す
var parseRules = function(ruleStr) {
	var patternRule    = [];
	var patternAllRule = [];
	var privateRule    = [];
	var errors         = [];

	// 正規表現を表す文字列のリストから、正規表現のリストを作成
	var createRegExpFromStrAry = function(regexpStrAry, lineNumber) {
		var regexps = [];
		regexpStrAry.forEach(function(regexpStr) {
			try { regexps.push(new RegExp(regexpStr)); }
			catch (e) { errors.push({ lineNumber: lineNumber, message: ('RegularExpression Error:' + e.name + ':' + e.massage + ', Str:' + regexpStr) }); }
		});
		return regexps;
	};

	// strに完全一致する正規表現を生成
	var createRegExpPerfectMatch = function(str) {
		return new RegExp('^' + str.replace(/[.*+?^${}()|\[\]\\]/g, '\\$&') + '$');
	};

	ruleStr.split('\n').forEach(function(line, i) {
		var parsed = line.split(/\s+/);
		var matchData;
		var rule;
		if ( parsed.length >= 3 && (matchData = parsed[0].match(/^match(|_all)$/i)) ) {  // 一致
			rule = { tag: parsed[1], regexps: parsed.slice(2).map(createRegExpPerfectMatch) };
		} else if ( parsed.length >= 3 && (matchData = parsed[0].match(/^pattern(|_all)$/i)) ) { // 正規表現
			var regexps = createRegExpFromStrAry(parsed.slice(2), i + 1);
			rule = { tag: parsed[1], regexps: regexps };
		} else if ( parsed.length >= 2 && parsed[0].match(/^private$/i) ) {                     // 非公開タグ
			privateRule.push.apply(privateRule, parsed.slice(1));
			return;
		} else if ( line.match(/^\s*$|^\s*#/) ) {                                               // 空行 or コメント行
			return;
		} else {
			errors.push({ lineNumber: (i+1), message: ('CommandError:Invalid Command or Too Few Arguments, Str:' + line) });
			return;
		}

		Array.prototype.push.call(matchData[1].length === 0 ? patternRule : patternAllRule, rule);
	});
	return { privateRule: privateRule, patternRule: patternRule, patternAllRule: patternAllRule, errors: errors };
};

// matchDataの配列を渡すと文中の~数字をそれで置き換える
var replaceWithMatch = function(input, matchData) {
	return input.split(/(~\d)/).map(function(str) {
		var match = str.match(/^~(\d)/);
		if(match) { return matchData[parseInt(match[1])] || ''; }
		return str;
	}).join('');
};

// 設定画面の生成・消去
var toggleSettingsView = function() {
	// すでに存在していたなら消去
	var settingsView = document.querySelector('#autotag-settings-view');
	if (settingsView) { settingsView.remove(); return; }

	// 保存済みデータの取得
	var ruleStr = window.localStorage.pixivAutoTag_taggingRule || defaultRuleStr;

	// フォームの作成
	settingsView = document.createElement('form');
	settingsView.id = 'autotag-settings-view';
	settingsView.style.backgroundColor = '#FFFFFF';
	settingsView.style.marginTop    = '5px';
	settingsView.style.padding      = '10px 9px';
	settingsView.style.borderRadius = '5px';

	var templateStr  = '
タグ付けルール
<textarea id="autotag-settings-tagging-rule" cols="80" rows="10" style="height:auto;">{{:rule}}</textarea>
';
	settingsView.innerHTML = templateStr.replace('{{:rule}}', ruleStr);

	var buttonsParagraph = document.createElement('p');

	var saveButton = document.createElement('input');
	saveButton.type = 'submit';
	saveButton.className = '_button';
	saveButton.value = '保存';
	settingsView.onsubmit = function() {
		var ruleStr = document.querySelector('#autotag-settings-tagging-rule').value;
		var rule = parseRules(ruleStr);
		if (rule.errors.length === 0) {
			window.localStorage.pixivAutoTag_taggingRule = ruleStr;
			alert('保存しました');
		} else {
			alert(rule.errors.map(function(err) { return '[Error] line: ' + err.lineNumber + ', message: ' + err.message; }).join('\n'));
		}
		return false;
	};
	buttonsParagraph.appendChild(saveButton);

	var cancelButton = document.createElement('input');
	cancelButton.className = '_button';
	cancelButton.type = 'reset';
	cancelButton.value = 'キャンセル';
	// cancelButton.onclick = function() { document.querySelector('#autotag-settings-view').remove(); };
	buttonsParagraph.appendChild(cancelButton);

	settingsView.appendChild(buttonsParagraph);

	var settingsButton = document.querySelector('#autotag-settings-button');
	settingsButton.parentElement.insertBefore(settingsView, settingsButton.nextSibling);
};

// タグの自動追加関数
var autoTag = function() {
	var ruleText = window.localStorage.pixivAutoTag_taggingRule || defaultRuleStr;
	var rule = parseRules(ruleText);

	// 作品タグとタグクラウドの取得
	var tagCloud = Array.prototype.slice.call(document.querySelectorAll('section.list-container.tag-container.tag-cloud-container > ul.list-items.tag-cloud > li')).map(function(item) { return item.textContent; });
	var tagsExist = Array.prototype.concat.apply([], Array.prototype.slice.call(document.querySelectorAll('section.list-container.tag-container.work-tags-container > div > ul span.tag')).map(function(item) { return item.textContent.replace(/^\*/, '').split('/'); }));

	// 非公開タグが含まれていた場合、自動で非公開に設定
	var privateButton = document.querySelector('div.submit-container > ul > li:nth-child(2) > label > input[type="radio"]');
	if (tagsExist.some(function(tag){ return rule.privateRule.indexOf(tag) !== -1; })) {
		privateButton.checked = true;
	}

	// ブックマークタグリストの生成
	if (input.value.length === 0) {
		// 作品タグとタグクラウドの共通タグを抽出
		var tagsFound = tagsExist.filter(function(existTag) { return tagCloud.some(function(cloudTag){ return existTag === cloudTag; }); });

		// 付与タグリストの生成
		var tagsAdded = [];
		tagsExist.forEach(function(tag) { // それぞれの作品タグが
			rule.patternRule.forEach(function(patternRule) { // それぞれのルール文に対し
				var matchData = [];
				var foundMatchFlag = patternRule.regexps.some(function(pattern) { // いずれかのパターンに一致するか
					return (matchData = tag.match(pattern));
				});
				if (foundMatchFlag) { tagsAdded.push(replaceWithMatch(patternRule.tag, matchData)); }
			});
		});

		rule.patternAllRule.forEach(function(patternRule) { // それぞれのルール文の
			var matchData = [];
			var foundMatchFlag = patternRule.regexps.every(function(pattern) { // すべてのパターンが
				return tagsExist.some(function(tag) { return (matchData = tag.match(pattern)); }); // いずれかの作品タグに一致するか？
			});
			if (foundMatchFlag) { tagsAdded.push(replaceWithMatch(patternRule.tag, matchData)); }
		});

		// タグを消去する
		tagsFound = tagsFound.filter(function(foundTag) { return tagsAdded.indexOf('-'+foundTag) === -1; });
		tagsAdded = tagsAdded.filter(function(tag) { return !tag.match(/^-/); });

		// 重複の削除
		var uniqueAry = tagsFound.concat(tagsAdded).filter(function(elem, i, ary) { return ary.indexOf(elem) === i; }).join(' ');

		// ブックマークタグを設定する
		input.value = uniqueAry;

		// タグのハイライトを表示させる
		var keyupEvent = document.createEvent('HTMLEvents');
		keyupEvent.initEvent('keyup', true, true);
		input.dispatchEvent(keyupEvent);

		// タグ付けが終わったら、背景を緑色にして補完がされたことを示す
		input.parentNode.style.backgroundColor = '#76B6E0';
		// それと入力欄にフォーカスする
		input.focus();
	}
};

(function() {
	// 自動タグ付けの実行
	if (window.location.href.match(/member_illust/)) {
		var ul = document.querySelector('section.list-container.tag-container.work-tags-container > div > ul');
		var checkTagGenerated = function(fn) { (ul.childNodes.length > 0) ? window.setTimeout(autoTag, 750) : window.setTimeout(fn, 750, fn); };
		window.setTimeout(checkTagGenerated, 1250, checkTagGenerated);
	} else {
		window.setTimeout(autoTag, 750);
	}

	// 設定ボタンの生成
	var settingsButton = document.createElement('button');
	settingsButton.className = '_button';
	settingsButton.style.marginLeft = '1em';
	settingsButton.id = 'autotag-settings-button';
	settingsButton.textContent = 'タグ自動化設定';
	settingsButton.addEventListener('click', toggleSettingsView, false);

	var target = document.querySelector('section.list-container.tag-container.work-tags-container > div > h1');
	target.parentElement.insertBefore(settingsButton, target.nextSibling);

	// タグ付けボタンの生成
	var autoTagButton = document.createElement('button');
	autoTagButton.className = '_button';
	autoTagButton.style.marginLeft = '0.25em';
	autoTagButton.id = 'autotag-button';
	autoTagButton.textContent = '上書きタグ付け';
	autoTagButton.addEventListener('click', function() { input.value = ''; autoTag(); }, false);
	target.parentElement.insertBefore(autoTagButton, settingsButton.nextSibling);
})();
<|endoftext|>


<commit_before>
var argscheck = require('cordova/argscheck'),
    exec = require('cordova/exec');

var admobExport = {};

admobExport.AD_SIZE = {
  SMART_BANNER: 'SMART_BANNER',
  BANNER: 'BANNER',
  MEDIUM_RECTANGLE: 'MEDIUM_RECTANGLE',
  FULL_BANNER: 'FULL_BANNER',
  LEADERBOARD: 'LEADERBOARD',
  SKYSCRAPER: 'SKYSCRAPER'
};

admobExport.AD_POSITION = {
  POS_XY: 0,
  TOP_LEFT: 1,
  TOP_CENTER: 2,
  TOP_RIGHT: 3,
  LEFT: 4,
  CENTER: 5,
  RIGHT: 6,
  BOTTOM_LEFT: 7,
  BOTTOM_CENTER: 8,
  BOTTOM_RIGHT: 9
};

/*
 * set options:
 *  {
 *    adSize: string,	// banner type size
 *    width: integer,	// banner width, if set adSize to 'CUSTOM'
 *    height: integer,	// banner height, if set adSize to 'CUSTOM'
 *    position: integer, // default position
 *    x: integer,	// default X of banner
 *    y: integer,	// default Y of banner
 *    isTesting: boolean,	// if set to true, to receive test ads
 *    autoShow: boolean,	// if set to true, no need call showBanner or showInterstitial
 *    adExtra: {
 *    }
 *   }
 */
admobExport.setOptions = function(options, successCallback, failureCallback) {
	  if(typeof options === 'object') {
		  cordova.exec( successCallback, failureCallback, 'AdMob', 'setOptions', [options] );
	  } else {
		  if(typeof failureCallback === 'function') {
			  failureCallback('options should be specified.');
		  }
	  }
	};

admobExport.createBanner = function(args, successCallback, failureCallback) {
	var options = {};
	if(typeof args === 'object') {
		for(var k in args) {
			if(k === 'success') { if(args[k] === 'function') successCallback = args[k]; }
			else if(k === 'fail') { if(args[k] === 'function') failureCallback = args[k]; }
			else {
				options[k] = args[k];
			}
		}
	} else if(typeof args === 'string') {
		options = { adId: args };
	}
	cordova.exec( successCallback, failureCallback, 'AdMob', 'createBanner', [ options ] );
};

admobExport.removeBanner = function(successCallback, failureCallback) {
	cordova.exec( successCallback, failureCallback, 'AdMob', 'removeBanner', [] );
};

admobExport.hideBanner = function(successCallback, failureCallback) {
	cordova.exec( successCallback, failureCallback, 'AdMob', 'hideBanner', [] );
};

admobExport.showBanner = function(position, successCallback, failureCallback) {
	cordova.exec( successCallback, failureCallback, 'AdMob', 'showBanner', [ position ] );
};

admobExport.showBannerAtXY = function(x, y, successCallback, failureCallback) {
	cordova.exec( successCallback, failureCallback, 'AdMob', 'showBannerAtXY', [{x:x, y:y}] );
};

admobExport.prepareInterstitial = function(args, successCallback, failureCallback) {
	var options = {};
	if(typeof args === 'object') {
		for(var k in args) {
			if(k === 'success') { if(args[k] === 'function') successCallback = args[k]; }
			else if(k === 'fail') { if(args[k] === 'function') failureCallback = args[k]; }
			else {
				options[k] = args[k];
			}
		}
	} else if(typeof args === 'string') {
		options = { adId: args };
	}
	cordova.exec( successCallback, failureCallback, 'AdMob', 'prepareInterstitial', [ args ] );
};

admobExport.showInterstitial = function(successCallback, failureCallback) {
	cordova.exec( successCallback, failureCallback, 'AdMob', 'showInterstitial', [] );
};

admobExport.isInterstitialReady = function(successCallback, failureCallback) {
	cordova.exec( successCallback, failureCallback, 'AdMob', 'isInterstitialReady', [] );
};

module.exports = admobExport;

<commit_msg>change success/fail in options to done/error<commit_after>
var argscheck = require('cordova/argscheck'),
    exec = require('cordova/exec');

var admobExport = {};

admobExport.AD_SIZE = {
  SMART_BANNER: 'SMART_BANNER',
  BANNER: 'BANNER',
  MEDIUM_RECTANGLE: 'MEDIUM_RECTANGLE',
  FULL_BANNER: 'FULL_BANNER',
  LEADERBOARD: 'LEADERBOARD',
  SKYSCRAPER: 'SKYSCRAPER'
};

admobExport.AD_POSITION = {
  POS_XY: 0,
  TOP_LEFT: 1,
  TOP_CENTER: 2,
  TOP_RIGHT: 3,
  LEFT: 4,
  CENTER: 5,
  RIGHT: 6,
  BOTTOM_LEFT: 7,
  BOTTOM_CENTER: 8,
  BOTTOM_RIGHT: 9
};

/*
 * set options:
 *  {
 *    adSize: string,	// banner type size
 *    width: integer,	// banner width, if set adSize to 'CUSTOM'
 *    height: integer,	// banner height, if set adSize to 'CUSTOM'
 *    position: integer, // default position
 *    x: integer,	// default X of banner
 *    y: integer,	// default Y of banner
 *    isTesting: boolean,	// if set to true, to receive test ads
 *    autoShow: boolean,	// if set to true, no need call showBanner or showInterstitial
 *    adExtra: {
 *    }
 *   }
 */
admobExport.setOptions = function(options, successCallback, failureCallback) {
	  if(typeof options === 'object') {
		  cordova.exec( successCallback, failureCallback, 'AdMob', 'setOptions', [options] );
	  } else {
		  if(typeof failureCallback === 'function') {
			  failureCallback('options should be specified.');
		  }
	  }
	};

admobExport.createBanner = function(args, successCallback, failureCallback) {
	var options = {};
	if(typeof args === 'object') {
		for(var k in args) {
			if(k === 'done') { if(args[k] === 'function') successCallback = args[k]; }
			else if(k === 'error') { if(args[k] === 'function') failureCallback = args[k]; }
			else {
				options[k] = args[k];
			}
		}
	} else if(typeof args === 'string') {
		options = { adId: args };
	}
	cordova.exec( successCallback, failureCallback, 'AdMob', 'createBanner', [ options ] );
};

admobExport.removeBanner = function(successCallback, failureCallback) {
	cordova.exec( successCallback, failureCallback, 'AdMob', 'removeBanner', [] );
};

admobExport.hideBanner = function(successCallback, failureCallback) {
	cordova.exec( successCallback, failureCallback, 'AdMob', 'hideBanner', [] );
};

admobExport.showBanner = function(position, successCallback, failureCallback) {
	cordova.exec( successCallback, failureCallback, 'AdMob', 'showBanner', [ position ] );
};

admobExport.showBannerAtXY = function(x, y, successCallback, failureCallback) {
	cordova.exec( successCallback, failureCallback, 'AdMob', 'showBannerAtXY', [{x:x, y:y}] );
};

admobExport.prepareInterstitial = function(args, successCallback, failureCallback) {
	var options = {};
	if(typeof args === 'object') {
		for(var k in args) {
			if(k === 'done') { if(args[k] === 'function') successCallback = args[k]; }
			else if(k === 'error') { if(args[k] === 'function') failureCallback = args[k]; }
			else {
				options[k] = args[k];
			}
		}
	} else if(typeof args === 'string') {
		options = { adId: args };
	}
	cordova.exec( successCallback, failureCallback, 'AdMob', 'prepareInterstitial', [ args ] );
};

admobExport.showInterstitial = function(successCallback, failureCallback) {
	cordova.exec( successCallback, failureCallback, 'AdMob', 'showInterstitial', [] );
};

admobExport.isInterstitialReady = function(successCallback, failureCallback) {
	cordova.exec( successCallback, failureCallback, 'AdMob', 'isInterstitialReady', [] );
};

module.exports = admobExport;

<|endoftext|>


<commit_before>/* eslint-disable react/prop-types */
import React from 'react';
import finallyShim from 'promise.prototype.finally';
import { combineReducers } from 'redux';
import { Provider } from 'react-redux';
import useStore from 'redux/store';
import { rootReducer } from 'fast-redux';
import isEmpty from 'lodash/isEmpty';
import useDeepCompareEffect from 'use-deep-compare-effect';

import reducerRegistry from 'redux/registry';

import 'styles/styles.scss';

finallyShim.shim();

const App = ({ Component, pageProps }) => {
  const store = useStore();
  const reducers = reducerRegistry.getReducers();

  useDeepCompareEffect(() => {
    store.replaceReducer(
      isEmpty(reducers)
        ? rootReducer
        : combineReducers(reducerRegistry.getReducers())
    );
  }, [reducers]);

  return (
    <Provider store={store}>
      <Component {...pageProps} />
    </Provider>
  );
};

export default App;
<commit_msg>fixes loading of css modules between route changes in dev mode<commit_after>/* eslint-disable react/prop-types */
import React from 'react';
import finallyShim from 'promise.prototype.finally';
import { combineReducers } from 'redux';
import { Provider } from 'react-redux';
import useStore from 'redux/store';
import { rootReducer } from 'fast-redux';
import isEmpty from 'lodash/isEmpty';
import useDeepCompareEffect from 'use-deep-compare-effect';

import reducerRegistry from 'redux/registry';

import 'styles/styles.scss';

finallyShim.shim();

// fixes dev mode css modules not being added to the document correctly between
// route changes due to a conflict between mini-css-extract-plugin and HMR
// https://github.com/sheerun/extracted-loader/issues/11#issue-453094382
if (process.env.NODE_ENV !== 'production' && module.hot) {
  module.hot.addStatusHandler((status) => {
    if (typeof window !== 'undefined' && status === 'ready') {
      window.__webpack_reload_css__ = true;
    }
  });
}

const App = ({ Component, pageProps }) => {
  const store = useStore();
  const reducers = reducerRegistry.getReducers();

  useDeepCompareEffect(() => {
    store.replaceReducer(
      isEmpty(reducers)
        ? rootReducer
        : combineReducers(reducerRegistry.getReducers())
    );
  }, [reducers]);

  return (
    <Provider store={store}>
      <Component {...pageProps} />
    </Provider>
  );
};

export default App;
<|endoftext|>


<commit_before>module.exports = function(grunt) {
	grunt.initConfig({
		docbase: {
			def: {
				options: {
					generatePath: "dist/",
					baseUrl: "/",
					'urlToAccess': 'http://localhost:8081/'
				}
			}
		},
		connect: {
			server: {
				options: {
					port: 9001,
					base: './'
				}
			}
		},
		'gh-pages': {
			def: {
				options: {
					base: 'dist',
					user: {
						name: 'Travis',
						email: 'mateusfreira@gmail.com'
					},
					repo: 'https://' + process.env.GH_TOKEN + '@github.com/mateusfreira/Docs.git',
					message: 'publish gh-pages (auto)',
					silent: false,
				},
				src: ['**']
			}
		}
	});

	grunt.loadNpmTasks('grunt-contrib-connect');
	grunt.loadNpmTasks('grunt-docbase');
	grunt.loadNpmTasks('grunt-gh-pages');
	// Default task.
	grunt.registerTask('default', ['connect', 'docbase']);
	grunt.registerTask('publish', ['connect', 'docbase', 'gh-pages']);

};<commit_msg>Improves to publish<commit_after>module.exports = function(grunt) {
	grunt.initConfig({
		docbase: {
			def: {
				options: {
					generatePath: "dist/",
					baseUrl: "/"
				}
			}
		},
		connect: {
			server: {
				options: {
					port: 9001,
					base: './'
				}
			}
		},
		'gh-pages': {
			def: {
				options: {
					base: 'dist',
					user: {
						name: 'Travis',
						email: 'mateusfreira@gmail.com'
					},
					repo: 'https://' + process.env.GH_TOKEN + '@github.com/mateusfreira/Docs.git',
					message: 'publish gh-pages (auto)',
					silent: false,
				},
				src: ['**']
			}
		}
	});

	grunt.loadNpmTasks('grunt-contrib-connect');
	grunt.loadNpmTasks('grunt-docbase');
	grunt.loadNpmTasks('grunt-gh-pages');
	// Default task.
	grunt.registerTask('default', ['connect', 'docbase']);
	grunt.registerTask('publish', ['connect', 'docbase', 'gh-pages']);

};<|endoftext|>