<commit_before>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * 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.
 */

CLASS({
  package: 'foam.core',
  name: 'Enum',
  requires: [
    'foam.core.EnumValue'
  ],
  properties: [
    {
      name: 'name',
      defaultValueFn: function() {
        return this.id.split('.').pop();
      }
    },
    {
      name: 'package',
      defaultValueFn: function() {
        return this.id.split('.').slice(0, -1).join('.');
      }
    },
    {
      name: 'startIndex',
      defaultValue: 0,
      type: 'Int'
    },
    {
      name: 'step',
      defaultValue: 1,
      type: 'Int'
    },
    {
      name: 'id',
    },
    {
      name: 'values',
      adapt: function(_, a) {
        // TODO: this should be a custom Property.fromJson implementation
        var index = this.startIndex;
        var used = {};
        for ( var i = 0 ; i < a.length ; i++ ) {
          if ( typeof a[i] == 'string' ) {
            a[i] = this.EnumValue.create({
              label: a[i],
              index: index
            });
          }

          if ( ! a[i].index ) {
            a[i].index = index;
          } else {
            index = a[i].index;
          }
          index += this.step;

          if ( used[index] ) {
            throw "Duplicate Enum index.";
          }
          used[index] = true;

          if ( ! this.EnumValue.isInstance(a[i]) ) {
            a[i] = this.EnumValue.create(a[i]);
          }
        }

        return a;
      }
    }
  ],
  methods: [
    {
      name: 'init',
      labels: ['javascript'],
      code: function init() {
        for ( var i = 0 ; i < this.values.length ; i++ ) {
          var value = this.values[i];
          this[value.name] = value.value;
        }
      }
    }
  ],
  templates: [
    {
      name: 'swiftSource',
      labels: ['swift'],
      template: function() {/*
// Generated by foam.core.Enum.  DO NOT MODIFY BY HAND
import Foundation
class <%= this.name %>: FoamEnum {
<% for (var i = 0, value; value = this.values[i]; i++) { %>
  static let <%= value.name %> = <%= value.index %>
<% } %>
  static let choices: [[AnyObject]] = [
<% for (var i = 0, value; value = this.values[i]; i++) { %>
    [
      <%= this.name %>.<%= value.name %>,
  <% if (value.label) { %>
      NSLocalizedString("<%= value.label %>", comment: "<%= value.description %>"),
  <% } else { %>
      "<%= value.name %>",
  <% } %>
    ],
<% } %>
  ]
  static func valueToLabel(value: AnyObject) -> String {
    for e in <%= this.name %>.choices {
      if equals(e[0], b: value) { return e[1] as! String }
    }
    return ""
  }
}
      */}
    },
    {
      name: 'javaSource',
      labels: ['java'],
      template: function() {/*
// Generated by FOAM, do not modify.
package <%= this.package %>;

public enum <%= this.name %> {
<%
  for ( var i = 0 ; i < this.values.length ; i++ ) {
    var value = this.values[i];
    if ( value.javaSource ) { value.javaSource(out); }
    else {
%>  <%= value.name %>(<%= value.index %>)<%
    }
    if ( i == this.values.length - 1 ) {%>;<%}
    else {%>,<%}
  }
%>

  private final int index_;
  <%= this.name %>(int index) {
    index_ = index;
  }

  public int getIndex() {
    return index_;
  }
}
*/}
    }
  ]
});
<commit_msg>Enums: Bring back getValue() in Javascript<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * 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.
 */

CLASS({
  package: 'foam.core',
  name: 'Enum',
  requires: [
    'foam.core.EnumValue'
  ],
  properties: [
    {
      name: 'name',
      defaultValueFn: function() {
        return this.id.split('.').pop();
      }
    },
    {
      name: 'package',
      defaultValueFn: function() {
        return this.id.split('.').slice(0, -1).join('.');
      }
    },
    {
      name: 'startIndex',
      defaultValue: 0,
      type: 'Int'
    },
    {
      name: 'step',
      defaultValue: 1,
      type: 'Int'
    },
    {
      name: 'id',
    },
    {
      name: 'values',
      adapt: function(_, a) {
        // TODO: this should be a custom Property.fromJson implementation
        var index = this.startIndex;
        var used = {};
        for ( var i = 0 ; i < a.length ; i++ ) {
          if ( typeof a[i] == 'string' ) {
            a[i] = this.EnumValue.create({
              label: a[i],
              index: index
            });
          }

          if ( ! a[i].index ) {
            a[i].index = index;
          } else {
            index = a[i].index;
          }
          index += this.step;

          if ( used[index] ) {
            throw "Duplicate Enum index.";
          }
          used[index] = true;

          if ( ! this.EnumValue.isInstance(a[i]) ) {
            a[i] = this.EnumValue.create(a[i]);
          }
        }

        return a;
      }
    }
  ],
  methods: [
    {
      name: 'init',
      labels: ['javascript'],
      code: function init() {
        for ( var i = 0 ; i < this.values.length ; i++ ) {
          var value = this.values[i];
          this[value.name] = value.value;
        }
      }
    },
    {
      name: 'getValue',
      labels: ['javascript'],
      code: function getValue(index) {
        for (var i = 0; i < this.values.length; i++) {
          if (this.values[i].index === index) return this.values[i];
        }
      }
    }
  ],
  templates: [
    {
      name: 'swiftSource',
      labels: ['swift'],
      template: function() {/*
// Generated by foam.core.Enum.  DO NOT MODIFY BY HAND
import Foundation
class <%= this.name %>: FoamEnum {
<% for (var i = 0, value; value = this.values[i]; i++) { %>
  static let <%= value.name %> = <%= value.index %>
<% } %>
  static let choices: [[AnyObject]] = [
<% for (var i = 0, value; value = this.values[i]; i++) { %>
    [
      <%= this.name %>.<%= value.name %>,
  <% if (value.label) { %>
      NSLocalizedString("<%= value.label %>", comment: "<%= value.description %>"),
  <% } else { %>
      "<%= value.name %>",
  <% } %>
    ],
<% } %>
  ]
  static func valueToLabel(value: AnyObject) -> String {
    for e in <%= this.name %>.choices {
      if equals(e[0], b: value) { return e[1] as! String }
    }
    return ""
  }
}
      */}
    },
    {
      name: 'javaSource',
      labels: ['java'],
      template: function() {/*
// Generated by FOAM, do not modify.
package <%= this.package %>;

public enum <%= this.name %> {
<%
  for ( var i = 0 ; i < this.values.length ; i++ ) {
    var value = this.values[i];
    if ( value.javaSource ) { value.javaSource(out); }
    else {
%>  <%= value.name %>(<%= value.index %>)<%
    }
    if ( i == this.values.length - 1 ) {%>;<%}
    else {%>,<%}
  }
%>

  private final int index_;
  <%= this.name %>(int index) {
    index_ = index;
  }

  public int getIndex() {
    return index_;
  }
}
*/}
    }
  ]
});
<|endoftext|>


<commit_before>const moduleExports = require('./index');

const _global = typeof window === 'undefined' ? global : window;
// @ts-ignore
_global.luma = _global.luma || {};

// @ts-ignore
module.exports = Object.assign(_global.luma, moduleExports);
<commit_msg>Fix constants bundle namespace (#1469)<commit_after>const GLConstants = require('./index').default;

const _global = typeof window === 'undefined' ? global : window;
// @ts-ignore
_global.luma = _global.luma || {};

// @ts-ignore
module.exports = Object.assign(_global.luma, {GL: GLConstants});
<|endoftext|>


<commit_before>import WebMiddle, { PropTypes } from 'webmiddle';
import phantom from 'phantom';

// promise-based implementation of http://stackoverflow.com/a/19070446
function waitForFn(config) {
  config._start = config._start || new Date();

  if (config.timeout && new Date - config._start > config.timeout) {
    const errorMessage = 'waitForFn timedout ' + (new Date - config._start) + 'ms';
    if (config.debug) console.log(errorMessage);
    return Promise.reject(errorMessage);
  }

  return config.check().then(result => {
    if (result) {
      if (config.debug) console.log('waitForFn success ' + (new Date - config._start) + 'ms');
      return result;
    }

    return new Promise((resolve, reject) => {
      setTimeout(() => {
        waitForFn(config).then(resolve, reject);
      }, config.interval || 0);
    });
  });
}

const Browser =
({ name, contentType, url, method = 'GET', body = {}, httpHeaders = {}, cookies = {}, waitFor }) => {
  // TODO: cookies
  return new Promise((resolve, reject) => {
    let sitepage = null;
    let phInstance = null;
    const pageResponses = {};
    let finalUrl = url;

    if (typeof body === 'object' && body !== null) {
      // body as string
      if (httpHeaders && httpHeaders['Content-Type'] === 'application/json') {
        body = JSON.stringify(body);
      } else {
        // default: convert to form data
        body = Object.keys(body).reduce((list, prop) => {
          const value = body[prop];
          list.push(`${encodeURIComponent(prop)}=${encodeURIComponent(value)}`);
          return list;
        }, []).join('&');
      }
    }

    phantom.create()
    .then(instance => {
      phInstance = instance;
      return instance.createPage();
    })
    .then(page => {
      sitepage = page;

      //page.customHeaders = httpHeaders; // TODO: doesn't seem to work

      // track final response (after redirects)
      // https://github.com/ariya/phantomjs/issues/10185#issuecomment-38856203
      page.on('onResourceReceived', (response) => {
        pageResponses[response.url] = response;
      });
      page.on('onUrlChanged', (targetUrl) => {
        finalUrl = targetUrl;
      });

      // TODO: are httpHeaders still sent in case of redirect?
      const settings = {
        operation: method,
        headers: httpHeaders,
        data: body,
      };

      return page.open(url, settings);
    })
    .then(status => {
      const pageResponse = pageResponses[finalUrl];

      if (status !== 'success' || pageResponse.status !== 200) {
        throw pageResponse;
      }

      if (waitFor) {
        return waitForFn({
          debug: true,  // optional
          interval: 0,  // optional
          timeout: 10000,  // optional
          check: () => sitepage.evaluate((waitFor) =>
            document.querySelector(waitFor) !== null
          , waitFor),
        });
      }
    })
    .then(() => sitepage.property('content'))
    .then(content => {
      sitepage.close();
      phInstance.exit();

      resolve({ name, contentType, content });
    })
    .catch(error => {
      phInstance.exit();
      reject(error);
    });
  });
};

Browser.propTypes = {
  name: PropTypes.string.isRequired,
  contentType: PropTypes.string.isRequired,
  url: PropTypes.string.isRequired,
  method: PropTypes.string,
  body: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.string,
  ]),
  httpHeaders: PropTypes.object,
  cookies: PropTypes.object,
  waitFor: PropTypes.string,
};

export default Browser;
<commit_msg>Keep json & virtual resource content as javascript object<commit_after>import WebMiddle, { PropTypes } from 'webmiddle';
import phantom from 'phantom';

// promise-based implementation of http://stackoverflow.com/a/19070446
function waitForFn(config) {
  config._start = config._start || new Date();

  if (config.timeout && new Date - config._start > config.timeout) {
    const errorMessage = 'waitForFn timedout ' + (new Date - config._start) + 'ms';
    if (config.debug) console.log(errorMessage);
    return Promise.reject(errorMessage);
  }

  return config.check().then(result => {
    if (result) {
      if (config.debug) console.log('waitForFn success ' + (new Date - config._start) + 'ms');
      return result;
    }

    return new Promise((resolve, reject) => {
      setTimeout(() => {
        waitForFn(config).then(resolve, reject);
      }, config.interval || 0);
    });
  });
}

const Browser =
({ name, contentType, url, method = 'GET', body = {}, httpHeaders = {}, cookies = {}, waitFor }) => {
  // TODO: cookies
  return new Promise((resolve, reject) => {
    let sitepage = null;
    let phInstance = null;
    const pageResponses = {};
    let finalUrl = url;

    if (typeof body === 'object' && body !== null) {
      // body as string
      if (httpHeaders && httpHeaders['Content-Type'] === 'application/json') {
        body = JSON.stringify(body);
      } else {
        // default: convert to form data
        body = Object.keys(body).reduce((list, prop) => {
          const value = body[prop];
          list.push(`${encodeURIComponent(prop)}=${encodeURIComponent(value)}`);
          return list;
        }, []).join('&');
      }
    }

    phantom.create()
    .then(instance => {
      phInstance = instance;
      return instance.createPage();
    })
    .then(page => {
      sitepage = page;

      //page.customHeaders = httpHeaders; // TODO: doesn't seem to work

      // track final response (after redirects)
      // https://github.com/ariya/phantomjs/issues/10185#issuecomment-38856203
      page.on('onResourceReceived', (response) => {
        pageResponses[response.url] = response;
      });
      page.on('onUrlChanged', (targetUrl) => {
        finalUrl = targetUrl;
      });

      // TODO: are httpHeaders still sent in case of redirect?
      const settings = {
        operation: method,
        headers: httpHeaders,
        data: body,
      };

      return page.open(url, settings);
    })
    .then(status => {
      const pageResponse = pageResponses[finalUrl];

      if (status !== 'success' || pageResponse.status !== 200) {
        throw pageResponse;
      }

      if (waitFor) {
        return waitForFn({
          debug: true,  // optional
          interval: 0,  // optional
          timeout: 10000,  // optional
          check: () => sitepage.evaluate((waitFor) =>
            document.querySelector(waitFor) !== null
          , waitFor),
        });
      }
    })
    .then(() => sitepage.property('content'))
    .then(content => {
      sitepage.close();
      phInstance.exit();

      resolve({
        name,
        contentType,
        content: (contentType === 'application/json') ? JSON.parse(content) : content,
      });
    })
    .catch(error => {
      phInstance.exit();
      reject(error);
    });
  });
};

Browser.propTypes = {
  name: PropTypes.string.isRequired,
  contentType: PropTypes.string.isRequired,
  url: PropTypes.string.isRequired,
  method: PropTypes.string,
  body: PropTypes.oneOfType([
    PropTypes.object,
    PropTypes.string,
  ]),
  httpHeaders: PropTypes.object,
  cookies: PropTypes.object,
  waitFor: PropTypes.string,
};

export default Browser;
<|endoftext|>


<commit_before>(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){

window.Genetic = require('./genetic');

},{"./genetic":2}],2:[function(require,module,exports){

var Genetic = Genetic || (function(){

	'use strict';

	// facilitates communcation between web workers
	var Serialization = {
		"stringify": function (obj) {
			return JSON.stringify(obj, function (key, value) {
				if (value instanceof Function || typeof value == "function") return "__func__:" + value.toString();
				if (value instanceof RegExp) return "__regex__:" + value;
				return value;
			});
		}, "parse": function (str) {
			return JSON.parse(str, function (key, value) {
				if (typeof value != "string") return value;
				if (value.lastIndexOf("__func__:", 0) === 0) return eval('(' + value.slice(9) + ')');
				if (value.lastIndexOf("__regex__:", 0) === 0) return eval('(' + value.slice(10) + ')');
				return value;
			});
		}
	};

	var Clone = function(obj) {
		if (obj == null || typeof obj != "object")
			return obj;

		return JSON.parse(JSON.stringify(obj));
	};

	var Optimize = {
		"Maximize": function (a, b) { return a >= b; }
		, "Minimize": function (a, b) { return a < b; }
	};

	var Select1 = {
		"Tournament2": function(pop) {
			var n = pop.length;
			var a = pop[Math.floor(Math.random()*n)];
			var b = pop[Math.floor(Math.random()*n)];
			return this.optimize(a.fitness, b.fitness) ? a.entity : b.entity;
		}, "Tournament3": function(pop) {
			var n = pop.length;
			var a = pop[Math.floor(Math.random()*n)];
			var b = pop[Math.floor(Math.random()*n)];
			var c = pop[Math.floor(Math.random()*n)];
			var best = this.optimize(a.fitness, b.fitness) ? a : b;
			best = this.optimize(best.fitness, c.fitness) ? best : c;
			return best.entity;
		}, "Fittest": function (pop) {
			return pop[0].entity;
		}, "Random": function (pop) {
			return pop[Math.floor(Math.random()*pop.length)].entity;
		}, "RandomLinearRank": function (pop) {
			this.internalGenState["rlr"] = this.internalGenState["rlr"]||0;
			return pop[Math.floor(Math.random()*Math.min(pop.length,(this.internalGenState["rlr"]++)))].entity;
		}, "Sequential": function (pop) {
			this.internalGenState["seq"] = this.internalGenState["seq"]||0;
			return pop[(this.internalGenState["seq"]++)%pop.length].entity;
		}
	};

	var Select2 = {
		"Tournament2": function(pop) {
			return [Select1.Tournament2.call(this, pop), Select1.Tournament2.call(this, pop)];
		}, "Tournament3": function(pop) {
			return [Select1.Tournament3.call(this, pop), Select1.Tournament3.call(this, pop)];
		}, "Random": function (pop) {
			return [Select1.Random.call(this, pop), Select1.Random.call(this, pop)];
		}, "RandomLinearRank": function (pop) {
			return [Select1.RandomLinearRank.call(this, pop), Select1.RandomLinearRank.call(this, pop)];
		}, "Sequential": function (pop) {
			return [Select1.Sequential.call(this, pop), Select1.Sequential.call(this, pop)];
		}, "FittestRandom": function (pop) {
			return [Select1.Fittest.call(this, pop), Select1.Random.call(this, pop)];
		}
	};

	function Genetic() {

		// population
		this.fitness = null;
		this.seed = null;
		this.mutate = null;
		this.crossover = null;
		this.select1 = null;
		this.select2 = null;
		this.optimize = null;
		this.generation = null;
		this.notification = null;

		this.configuration = {
			"size": 250
			, "crossover": 0.9
			, "mutation": 0.2
			, "iterations": 100
			, "fittestAlwaysSurvives": true
			, "maxResults": 100
			, "webWorkers": true
			, "skip": 0
		};

		this.userData = {};
		this.internalGenState = {};

		this.entities = [];

		this.usingWebWorker = false;

		this.start = function() {

			var i;
			var self = this;

			function mutateOrNot(entity) {
				// applies mutation based on mutation probability
				return Math.random() <= self.configuration.mutation && self.mutate ? self.mutate(Clone(entity)) : entity;
			}

			// seed the population
			for (i=0;i<this.configuration.size;++i)  {
				this.entities.push(Clone(this.seed()));
			}

			for (i=0;i<this.configuration.iterations;++i) {
				// reset for each generation
				this.internalGenState = {};

				// score and sort
				var pop = this.entities
					.map(function (entity) {
						return {"fitness": self.fitness(entity), "entity": entity };
					})
					.sort(function (a, b) {
						return self.optimize(a.fitness, b.fitness) ? -1 : 1;
					});

				// generation notification
				var mean = pop.reduce(function (a, b) { return a + b.fitness; }, 0)/pop.length;
				var stdev = Math.sqrt(pop
					.map(function (a) { return (a.fitness - mean) * (a.fitness - mean); })
					.reduce(function (a, b) { return a+b; }, 0)/pop.length);

				var stats = {
					"maximum": pop[0].fitness
					, "minimum": pop[pop.length-1].fitness
					, "mean": mean
					, "stdev": stdev
				};

				var r = this.generation ? this.generation(pop, i, stats) : true;
				var isFinished = (typeof r != "undefined" && !r) || (i == this.configuration.iterations-1);

				if (
					this.notification
					&& (isFinished || this.configuration["skip"] == 0 || i%this.configuration["skip"] == 0)
				) {
					this.sendNotification(pop.slice(0, this.maxResults), i, stats, isFinished);
				}

				if (isFinished)
					break;

				// crossover and mutate
				var newPop = [];

				if (this.configuration.fittestAlwaysSurvives) // lets the best solution fall through
					newPop.push(pop[0].entity);

				while (newPop.length < self.configuration.size) {
					if (
						this.crossover // if there is a crossover function
						&& Math.random() <= this.configuration.crossover // base crossover on specified probability
						&& newPop.length+1 < self.configuration.size // keeps us from going 1 over the max population size
					) {
						var parents = this.select2(pop);
						var children = this.crossover(Clone(parents[0]), Clone(parents[1])).map(mutateOrNot);
						newPop.push(children[0], children[1]);
					} else {
						newPop.push(mutateOrNot(self.select1(pop)));
					}
				}

				this.entities = newPop;
			}
		}

		this.sendNotification = function(pop, generation, stats, isFinished) {
			var response = {
				"pop": pop.map(Serialization.stringify)
				, "generation": generation
				, "stats": stats
				, "isFinished": isFinished
			};

			if (this.usingWebWorker) {
				postMessage(response);
			} else {
				// self declared outside of scope
				self.notification(response.pop.map(Serialization.parse), response.generation, response.stats, response.isFinished);
			}

		};
	}

	Genetic.prototype.evolve = function(config, userData) {

		var k;
		for (k in config) {
			this.configuration[k] = config[k];
		}

		for (k in userData) {
			this.userData[k] = userData[k];
		}

		// determine if we can use webworkers
		this.usingWebWorker = this.configuration.webWorkers
			&& typeof Blob != "undefined"
			&& typeof Worker != "undefined"
			&& typeof window.URL != "undefined"
			&& typeof window.URL.createObjectURL != "undefined";

		function addslashes(str) {
			return str.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
		}

		// bootstrap webworker script
		var blobScript = "'use strict'\n";
		blobScript += "var Serialization = {'stringify': " + Serialization.stringify.toString() + ", 'parse': " + Serialization.parse.toString() + "};\n";
		blobScript += "var Clone = " + Clone.toString() + ";\n";

		// make available in webworker
		blobScript += "var Optimize = Serialization.parse(\"" + addslashes(Serialization.stringify(Optimize)) + "\");\n";
		blobScript += "var Select1 = Serialization.parse(\"" + addslashes(Serialization.stringify(Select1)) + "\");\n";
		blobScript += "var Select2 = Serialization.parse(\"" + addslashes(Serialization.stringify(Select2)) + "\");\n";

		// materialize our ga instance in the worker
		blobScript += "var genetic = Serialization.parse(\"" + addslashes(Serialization.stringify(this)) + "\");\n";
		blobScript += "onmessage = function(e) { genetic.start(); }\n";

		var self = this;

		if (this.usingWebWorker) {
			// webworker
			var blob = new Blob([blobScript]);
			var worker = new Worker(window.URL.createObjectURL(blob));
			worker.onmessage = function(e) {
			  var response = e.data;
			  self.notification(response.pop.map(Serialization.parse), response.generation, response.stats, response.isFinished);
			};
			worker.onerror = function(e) {
				alert('ERROR: Line ' + e.lineno + ' in ' + e.filename + ': ' + e.message);
			};
			worker.postMessage("");
		} else {
			// simulate webworker
			(function(){
				var onmessage;
				eval(blobScript);
				onmessage(null);
			})();
		}
	}

	return {
		"create": function() {
			return new Genetic();
		}, "Select1": Select1
		, "Select2": Select2
		, "Optimize": Optimize
		, "Clone": Clone
	};

})();

// so we don't have to build to run in the browser
if (typeof module != "undefined") {
	module.exports = Genetic;
}

},{}]},{},[1]);
<commit_msg>Fix maxResults<commit_after>(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){

window.Genetic = require('./genetic');

},{"./genetic":2}],2:[function(require,module,exports){

var Genetic = Genetic || (function(){

	'use strict';

	// facilitates communcation between web workers
	var Serialization = {
		"stringify": function (obj) {
			return JSON.stringify(obj, function (key, value) {
				if (value instanceof Function || typeof value == "function") return "__func__:" + value.toString();
				if (value instanceof RegExp) return "__regex__:" + value;
				return value;
			});
		}, "parse": function (str) {
			return JSON.parse(str, function (key, value) {
				if (typeof value != "string") return value;
				if (value.lastIndexOf("__func__:", 0) === 0) return eval('(' + value.slice(9) + ')');
				if (value.lastIndexOf("__regex__:", 0) === 0) return eval('(' + value.slice(10) + ')');
				return value;
			});
		}
	};

	var Clone = function(obj) {
		if (obj == null || typeof obj != "object")
			return obj;

		return JSON.parse(JSON.stringify(obj));
	};

	var Optimize = {
		"Maximize": function (a, b) { return a >= b; }
		, "Minimize": function (a, b) { return a < b; }
	};

	var Select1 = {
		"Tournament2": function(pop) {
			var n = pop.length;
			var a = pop[Math.floor(Math.random()*n)];
			var b = pop[Math.floor(Math.random()*n)];
			return this.optimize(a.fitness, b.fitness) ? a.entity : b.entity;
		}, "Tournament3": function(pop) {
			var n = pop.length;
			var a = pop[Math.floor(Math.random()*n)];
			var b = pop[Math.floor(Math.random()*n)];
			var c = pop[Math.floor(Math.random()*n)];
			var best = this.optimize(a.fitness, b.fitness) ? a : b;
			best = this.optimize(best.fitness, c.fitness) ? best : c;
			return best.entity;
		}, "Fittest": function (pop) {
			return pop[0].entity;
		}, "Random": function (pop) {
			return pop[Math.floor(Math.random()*pop.length)].entity;
		}, "RandomLinearRank": function (pop) {
			this.internalGenState["rlr"] = this.internalGenState["rlr"]||0;
			return pop[Math.floor(Math.random()*Math.min(pop.length,(this.internalGenState["rlr"]++)))].entity;
		}, "Sequential": function (pop) {
			this.internalGenState["seq"] = this.internalGenState["seq"]||0;
			return pop[(this.internalGenState["seq"]++)%pop.length].entity;
		}
	};

	var Select2 = {
		"Tournament2": function(pop) {
			return [Select1.Tournament2.call(this, pop), Select1.Tournament2.call(this, pop)];
		}, "Tournament3": function(pop) {
			return [Select1.Tournament3.call(this, pop), Select1.Tournament3.call(this, pop)];
		}, "Random": function (pop) {
			return [Select1.Random.call(this, pop), Select1.Random.call(this, pop)];
		}, "RandomLinearRank": function (pop) {
			return [Select1.RandomLinearRank.call(this, pop), Select1.RandomLinearRank.call(this, pop)];
		}, "Sequential": function (pop) {
			return [Select1.Sequential.call(this, pop), Select1.Sequential.call(this, pop)];
		}, "FittestRandom": function (pop) {
			return [Select1.Fittest.call(this, pop), Select1.Random.call(this, pop)];
		}
	};

	function Genetic() {

		// population
		this.fitness = null;
		this.seed = null;
		this.mutate = null;
		this.crossover = null;
		this.select1 = null;
		this.select2 = null;
		this.optimize = null;
		this.generation = null;
		this.notification = null;

		this.configuration = {
			"size": 250
			, "crossover": 0.9
			, "mutation": 0.2
			, "iterations": 100
			, "fittestAlwaysSurvives": true
			, "maxResults": 100
			, "webWorkers": true
			, "skip": 0
		};

		this.userData = {};
		this.internalGenState = {};

		this.entities = [];

		this.usingWebWorker = false;

		this.start = function() {

			var i;
			var self = this;

			function mutateOrNot(entity) {
				// applies mutation based on mutation probability
				return Math.random() <= self.configuration.mutation && self.mutate ? self.mutate(Clone(entity)) : entity;
			}

			// seed the population
			for (i=0;i<this.configuration.size;++i)  {
				this.entities.push(Clone(this.seed()));
			}

			for (i=0;i<this.configuration.iterations;++i) {
				// reset for each generation
				this.internalGenState = {};

				// score and sort
				var pop = this.entities
					.map(function (entity) {
						return {"fitness": self.fitness(entity), "entity": entity };
					})
					.sort(function (a, b) {
						return self.optimize(a.fitness, b.fitness) ? -1 : 1;
					});

				// generation notification
				var mean = pop.reduce(function (a, b) { return a + b.fitness; }, 0)/pop.length;
				var stdev = Math.sqrt(pop
					.map(function (a) { return (a.fitness - mean) * (a.fitness - mean); })
					.reduce(function (a, b) { return a+b; }, 0)/pop.length);

				var stats = {
					"maximum": pop[0].fitness
					, "minimum": pop[pop.length-1].fitness
					, "mean": mean
					, "stdev": stdev
				};

				var r = this.generation ? this.generation(pop.slice(0, this.configuration["maxResults"]), i, stats) : true;
				var isFinished = (typeof r != "undefined" && !r) || (i == this.configuration.iterations-1);

				if (
					this.notification
					&& (isFinished || this.configuration["skip"] == 0 || i%this.configuration["skip"] == 0)
				) {
					this.sendNotification(pop.slice(0, this.configuration["maxResults"]), i, stats, isFinished);
				}

				if (isFinished)
					break;

				// crossover and mutate
				var newPop = [];

				if (this.configuration.fittestAlwaysSurvives) // lets the best solution fall through
					newPop.push(pop[0].entity);

				while (newPop.length < self.configuration.size) {
					if (
						this.crossover // if there is a crossover function
						&& Math.random() <= this.configuration.crossover // base crossover on specified probability
						&& newPop.length+1 < self.configuration.size // keeps us from going 1 over the max population size
					) {
						var parents = this.select2(pop);
						var children = this.crossover(Clone(parents[0]), Clone(parents[1])).map(mutateOrNot);
						newPop.push(children[0], children[1]);
					} else {
						newPop.push(mutateOrNot(self.select1(pop)));
					}
				}

				this.entities = newPop;
			}
		}

		this.sendNotification = function(pop, generation, stats, isFinished) {
			var response = {
				"pop": pop.map(Serialization.stringify)
				, "generation": generation
				, "stats": stats
				, "isFinished": isFinished
			};

			if (this.usingWebWorker) {
				postMessage(response);
			} else {
				// self declared outside of scope
				self.notification(response.pop.map(Serialization.parse), response.generation, response.stats, response.isFinished);
			}

		};
	}

	Genetic.prototype.evolve = function(config, userData) {

		var k;
		for (k in config) {
			this.configuration[k] = config[k];
		}

		for (k in userData) {
			this.userData[k] = userData[k];
		}

		// determine if we can use webworkers
		this.usingWebWorker = this.configuration.webWorkers
			&& typeof Blob != "undefined"
			&& typeof Worker != "undefined"
			&& typeof window.URL != "undefined"
			&& typeof window.URL.createObjectURL != "undefined";

		function addslashes(str) {
			return str.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
		}

		// bootstrap webworker script
		var blobScript = "'use strict'\n";
		blobScript += "var Serialization = {'stringify': " + Serialization.stringify.toString() + ", 'parse': " + Serialization.parse.toString() + "};\n";
		blobScript += "var Clone = " + Clone.toString() + ";\n";

		// make available in webworker
		blobScript += "var Optimize = Serialization.parse(\"" + addslashes(Serialization.stringify(Optimize)) + "\");\n";
		blobScript += "var Select1 = Serialization.parse(\"" + addslashes(Serialization.stringify(Select1)) + "\");\n";
		blobScript += "var Select2 = Serialization.parse(\"" + addslashes(Serialization.stringify(Select2)) + "\");\n";

		// materialize our ga instance in the worker
		blobScript += "var genetic = Serialization.parse(\"" + addslashes(Serialization.stringify(this)) + "\");\n";
		blobScript += "onmessage = function(e) { genetic.start(); }\n";

		var self = this;

		if (this.usingWebWorker) {
			// webworker
			var blob = new Blob([blobScript]);
			var worker = new Worker(window.URL.createObjectURL(blob));
			worker.onmessage = function(e) {
			  var response = e.data;
			  self.notification(response.pop.map(Serialization.parse), response.generation, response.stats, response.isFinished);
			};
			worker.onerror = function(e) {
				alert('ERROR: Line ' + e.lineno + ' in ' + e.filename + ': ' + e.message);
			};
			worker.postMessage("");
		} else {
			// simulate webworker
			(function(){
				var onmessage;
				eval(blobScript);
				onmessage(null);
			})();
		}
	}

	return {
		"create": function() {
			return new Genetic();
		}, "Select1": Select1
		, "Select2": Select2
		, "Optimize": Optimize
		, "Clone": Clone
	};

})();

// so we don't have to build to run in the browser
if (typeof module != "undefined") {
	module.exports = Genetic;
}

},{}]},{},[1]);
<|endoftext|>


<commit_before>// ==UserScript==
// @id             iitc-plugin-show-linked-portals@fstopienski
// @name           IITC plugin: Show linked portals
// @category       Portal Info
// @version        0.3.1.@@DATETIMEVERSION@@
// @description    [@@BUILDNAME@@-@@BUILDDATE@@] Try to show the linked portals (image, name and link direction) in portal detail view and jump to linked portal on click.  Some details may not be available if the linked portal is not in the current view.
@@METAINFO@@
// ==/UserScript==

@@PLUGINSTART@@

// PLUGIN START ////////////////////////////////////////////////////////

// use own namespace for plugin
window.plugin.showLinkedPortal = function () {
};

plugin.showLinkedPortal.previewOptions = {
  color: "#C33",
  opacity: 1,
  weight: 5,
  fill: false,
  dashArray: "1,6",
  radius: 18,
};

window.plugin.showLinkedPortal.portalDetail = function (data) {
  plugin.showLinkedPortal.removePreview();

  var portalLinks = getPortalLinks(data.guid);
  var length = portalLinks.in.length + portalLinks.out.length

  var c = 1;

  $('
',{id:'showLinkedPortalContainer'}).appendTo('#portaldetails');

  function renderLinkedPortal(linkGuid) {
    if(c > 16) return;

    var key = this; // passed by Array.prototype.forEach
    var link = window.links[linkGuid].options.data;
    var guid = link[key + 'Guid'];
    var lat = link[key + 'LatE6']/1E6;
    var lng = link[key + 'LngE6']/1E6;

    var length = L.latLng(link.oLatE6/1E6, link.oLngE6/1E6).distanceTo([link.dLatE6/1E6, link.dLngE6/1E6]);
    var lengthFull = digits(Math.round(length)) + 'm';
    var lengthShort = length < 100000 ? lengthFull : digits(Math.round(length/1000)) + 'km'

    var div = $('
').addClass('showLinkedPortalLink showLinkedPortalLink' + c + (key=='d' ? ' outgoing' : ' incoming'));

    var title;

    var data = (portals[guid] && portals[guid].options.data) || portalDetail.get(guid) || null;
    if(data && data.title) {
      title = data.title;
      div.append($('').attr({
        'src': fixPortalImageUrl(data.image),
        'class': 'minImg',
        'alt': title,
      }));
    } else {
      title = 'Go to portal';
      div
        .addClass('outOfRange')
        .append($('')
          .html('Portal not loaded.
' + lengthShort));
    }

    div
      .attr({
        'data-guid': guid,
        'data-lat': lat,
        'data-lng': lng,
        'title': $('
')
          .append($('').text(title))
          .append($('
'))
          .append($('').text(key=='d' ? '↴ outgoing link' : '↳ incoming link'))
          .append($('
'))
          .append($('').html(lengthFull))
          .html(),
      })
      .appendTo('#showLinkedPortalContainer');

    c++;
  }

  portalLinks.out.forEach(renderLinkedPortal, 'd');
  portalLinks.in.forEach(renderLinkedPortal, 'o');

  if(length > 16) {
    $('
')
      .addClass('showLinkedPortalLink showLinkedPortalOverflow')
      .text(length-16 + ' more')
      .appendTo('#showLinkedPortalContainer');
  }

  $('#showLinkedPortalContainer')
    .on('click', '.showLinkedPortalLink', plugin.showLinkedPortal.onLinkedPortalClick)
    .on('mouseover', '.showLinkedPortalLink', plugin.showLinkedPortal.onLinkedPortalMouseOver)
    .on('mouseout', '.showLinkedPortalLink', plugin.showLinkedPortal.onLinkedPortalMouseOut);
}

plugin.showLinkedPortal.onLinkedPortalClick = function() {
  plugin.showLinkedPortal.removePreview();

  var element = $(this);
  var guid = element.attr('data-guid');
  var lat = element.attr('data-lat');
  var lng = element.attr('data-lng');

  if(!guid) return; // overflow

  var position = L.latLng(lat, lng);
  if(!map.getBounds().contains(position)) map.setView(position);
  if(portals[guid])
    renderPortalDetails(guid);
  else
    zoomToAndShowPortal(guid, position);
};

plugin.showLinkedPortal.onLinkedPortalMouseOver = function() {
  plugin.showLinkedPortal.removePreview();

  var element = $(this);
  var lat = element.attr('data-lat');
  var lng = element.attr('data-lng');

  if(!(lat && lng)) return; // overflow

  var remote = L.latLng(lat, lng);
  var local = portals[selectedPortal].getLatLng();

  plugin.showLinkedPortal.preview = L.layerGroup().addTo(map);

  L.circleMarker(remote, plugin.showLinkedPortal.previewOptions)
    .addTo(plugin.showLinkedPortal.preview);

  L.geodesicPolyline([local, remote], plugin.showLinkedPortal.previewOptions)
    .addTo(plugin.showLinkedPortal.preview);
};

plugin.showLinkedPortal.onLinkedPortalMouseOut = function() {
  plugin.showLinkedPortal.removePreview();
};

plugin.showLinkedPortal.removePreview = function() {
  if(plugin.showLinkedPortal.preview)
    map.removeLayer(plugin.showLinkedPortal.preview);
  plugin.showLinkedPortal.preview = null;
};

var setup = function () {
  window.addHook('portalDetailsUpdated', window.plugin.showLinkedPortal.portalDetail);
  $('


<commit_before>'use strict';

var fs = require('fs'),
  lfmt = require('lfmt');

var saveFile = process.cwd() + '/saved.macros';

var macros = {};

var errMsgs = {
  incorrectUsage: '`macro`: you did something wrong.',
  noMacro: 'Can\'t find that!'
};

var loadMacros = function loadMacros() {
  if (Object.keys(macros) > 0) return;

  try {
    // this scheme does not account for duplicate keys. later records with
    // the same key will simply overwrite the template.
    var rawMacros = fs.readFileSync(saveFile).toString()
      .split('\n')
      .forEach(function(record) {
        if (!record) return;

        // TODO: catch errors for records with no space
        var spaceIndex = record.indexOf(' '),
          name = record.slice(0, spaceIndex),
          template = record.slice(spaceIndex + 1);
        macros[name] = template;

        console.log(lfmt.format('loading macro {{name}} `{{template}}`', {
          name: name,
          template: template
        }));
      });
  } catch (err) {
    // log the error and clean the macros.
    console.error(err);
    macros = {};
  }
};

var addMacro = function addMacro(name, template, cb) {
  macros[name] = template;
  fs.appendFile(saveFile, lfmt.format('{{name}} {{template}}\n', {
    name: name,
    template: template
  }), function(err) {
    if (err) console.error(err);
    cb && cb();
  });
};

var applyMacro = function loadMacros(name, args, cb) {
  var template = macros[name];
  if (!template) {
    cb && cb(new Error('Macro not found'));
    return;
  }

  var result = template
    .replace('$@', args.join(' '))
    .replace(/\$(\d+)/g, function(match, p1) {
      return (args[Number(p1)] || '');
    });

  cb && cb(null, result);
};

var macro = function macro(argv, response, logger) {
  loadMacros();

  if (argv.length < 2) {
    logger.error('`macro` called incorrectly: ', argv);
    response.end(errMsgs.incorrectUsage);
    return;
  }

  var subcmd = argv[1];

  if (subcmd === 'set') {
    var name = argv[2];
    var template = argv.slice(3).join(' ');
    addMacro(name, template, function(err) {
      if (!err) {
        response.end(lfmt.format('Successfully macroed {{name}} to `{{template}}`', {
          name: name,
          template: template
        }));
      }
    });
  }
  else {
    var name = subcmd;
    applyMacro(name, argv.slice(2), function(err, result) {
      response.end(result || errMsgs.noMacro);
    });
  }
};

macro.metadata = {
  name: 'macro',
  command: 'macro',
  info: {
    description: 'Set a string template macro',
    usage: 'macro [set {template}|{name} {variables...}]'
  }
};

module.exports = macro;
<commit_msg>Proper $@ replacement<commit_after>'use strict';

var fs = require('fs'),
  lfmt = require('lfmt');

var saveFile = process.cwd() + '/saved.macros';

var macros = {};

var errMsgs = {
  incorrectUsage: '`macro`: you did something wrong.',
  noMacro: 'Can\'t find that!'
};

var loadMacros = function loadMacros() {
  if (Object.keys(macros) > 0) return;

  try {
    // this scheme does not account for duplicate keys. later records with
    // the same key will simply overwrite the template.
    var rawMacros = fs.readFileSync(saveFile).toString()
      .split('\n')
      .forEach(function(record) {
        if (!record) return;

        // TODO: catch errors for records with no space
        var spaceIndex = record.indexOf(' '),
          name = record.slice(0, spaceIndex),
          template = record.slice(spaceIndex + 1);
        macros[name] = template;

        console.log(lfmt.format('loading macro {{name}} `{{template}}`', {
          name: name,
          template: template
        }));
      });
  } catch (err) {
    // log the error and clean the macros.
    console.error(err);
    macros = {};
  }
};

var addMacro = function addMacro(name, template, cb) {
  macros[name] = template;
  fs.appendFile(saveFile, lfmt.format('{{name}} {{template}}\n', {
    name: name,
    template: template
  }), function(err) {
    if (err) console.error(err);
    cb && cb();
  });
};

var applyMacro = function loadMacros(name, args, cb) {
  var template = macros[name];
  if (!template) {
    cb && cb(new Error('Macro not found'));
    return;
  }

  var result = template
    .replace(/\$@/g, args.join(' '))
    .replace(/\$(\d+)/g, function(match, p1) {
      return (args[Number(p1)] || '');
    });

  cb && cb(null, result);
};

var macro = function macro(argv, response, logger) {
  loadMacros();

  if (argv.length < 2) {
    logger.error('`macro` called incorrectly: ', argv);
    response.end(errMsgs.incorrectUsage);
    return;
  }

  var subcmd = argv[1];

  if (subcmd === 'set') {
    var name = argv[2];
    var template = argv.slice(3).join(' ');
    addMacro(name, template, function(err) {
      if (!err) {
        response.end(lfmt.format('Successfully macroed {{name}} to `{{template}}`', {
          name: name,
          template: template
        }));
      }
    });
  }
  else {
    var name = subcmd;
    applyMacro(name, argv.slice(2), function(err, result) {
      response.end(result || errMsgs.noMacro);
    });
  }
};

macro.metadata = {
  name: 'macro',
  command: 'macro',
  info: {
    description: 'Set a string template macro',
    usage: 'macro [set {template}|{name} {variables...}]'
  }
};

module.exports = macro;
<|endoftext|>


<commit_before>// Copyright 2022, University of Colorado Boulder

/**
 * Produces an assignment list of responsible devs. Run from lint.js
 *
 * The Chip Away option provides a quick and easy method to assign devs to their respective repositories
 * for ease in adopting and applying new typescript linting rules.
 * Chip Away will return a markdown formatted checklist with the repository name, responsible dev,
 * and number of errors.
 * Response  format:
 * - [ ] {{REPO}}: @{{GITHUB_USERNAME}} {{NUMBER}} errors in {{NUMBER}} files.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Marla Schulz (PhET Interactive Simulations)
 */

const fs = require( 'fs' );
const _ = require( 'lodash' ); // eslint-disable-line require-statement-match
const path = require( 'path' );

module.exports = results => {

  // NOTE: This should never be run in a maintenance mode since this loads a file from phet-info which
  // does not have its SHA tracked as a dependency.
  let responsibleDevs = null;
  try {
    responsibleDevs = JSON.parse( fs.readFileSync( '../phet-info/sim-info/responsible_dev.json' ) );
  }
  catch( e ) {

    // return gracefully if that file was not found or not parseable.
    return 'Could not output chip-away information, due to: ' + e.message;
  }

  const repos = results.map( result => path.relative( '../', result.filePath ).split( path.sep )[ 0 ] );
  const uniqueRepos = _.uniq( repos ).filter( repo => repo !== 'perennial-alias' );

  // We only want a list of repos that report lint errors
  const reposWithErrors = uniqueRepos.filter( repo => {
    return errorReport( results, repo ).errorCount > 0;
  } );

  // Format chip away assignments. '{{REPO}} @github # errors in # files'
  const assignments = reposWithErrors.map( repo => {
    const fileCount = errorReport( results, repo ).fileCount;
    const errorCount = errorReport( results, repo ).errorCount;

    return ` - [ ] ${repo}: ${responsibleDevs[ repo ].responsibleDevs.join( ', ' )} ${errorCount} errors in ${fileCount} files.`;
  } );

  return assignments.join( '\n' );
};

function errorReport( results, repo ) {
  const filteredResults = results.filter( result => path.relative( '../', result.filePath ).split( path.sep )[ 0 ] === repo );
  const fileCount = filteredResults.filter( result => result.errorCount + result.warningCount > 0 ).length;
  const errorCount = _.sum( filteredResults.map( file => file.errorCount + file.warningCount ) );

  return { errorCount: errorCount, fileCount: fileCount };
}
<commit_msg>Add JSDoc, see https://github.com/phetsims/chipper/issues/1262<commit_after>// Copyright 2022, University of Colorado Boulder

/**
 * Produces an assignment list of responsible devs. Run from lint.js
 *
 * The Chip Away option provides a quick and easy method to assign devs to their respective repositories
 * for ease in adopting and applying new typescript linting rules.
 * Chip Away will return a markdown formatted checklist with the repository name, responsible dev,
 * and number of errors.
 * Response  format:
 * - [ ] {{REPO}}: @{{GITHUB_USERNAME}} {{NUMBER}} errors in {{NUMBER}} files.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Marla Schulz (PhET Interactive Simulations)
 */

const fs = require( 'fs' );
const _ = require( 'lodash' ); // eslint-disable-line require-statement-match
const path = require( 'path' );

/**
 * @param {ESLint.LintResult[]} results - the results from eslint.lintFiles( patterns )
 *                                      - { filePath: string, errorCount: number, warningCount: number }
 *                                      - see https://eslint.org/docs/latest/developer-guide/nodejs-api#-lintresult-type
 * @returns {string} - a message with the chip-away checkboxes in GitHub markdown format, or a message describing why it
 *                   - could not be accomplished
 */
module.exports = results => {

  // NOTE: This should never be run in a maintenance mode since this loads a file from phet-info which
  // does not have its SHA tracked as a dependency.
  let responsibleDevs = null;
  try {
    responsibleDevs = JSON.parse( fs.readFileSync( '../phet-info/sim-info/responsible_dev.json' ) );
  }
  catch( e ) {

    // return gracefully if that file was not found or not parseable.
    return 'Could not output chip-away information, due to: ' + e.message;
  }

  const repos = results.map( result => path.relative( '../', result.filePath ).split( path.sep )[ 0 ] );
  const uniqueRepos = _.uniq( repos ).filter( repo => repo !== 'perennial-alias' );

  // We only want a list of repos that report lint errors
  const reposWithErrors = uniqueRepos.filter( repo => {
    return errorReport( results, repo ).errorCount > 0;
  } );

  // Format chip away assignments. '{{REPO}} @github # errors in # files'
  const assignments = reposWithErrors.map( repo => {
    const fileCount = errorReport( results, repo ).fileCount;
    const errorCount = errorReport( results, repo ).errorCount;

    return ` - [ ] ${repo}: ${responsibleDevs[ repo ].responsibleDevs.join( ', ' )} ${errorCount} errors in ${fileCount} files.`;
  } );

  return assignments.join( '\n' );
};

function errorReport( results, repo ) {
  const filteredResults = results.filter( result => path.relative( '../', result.filePath ).split( path.sep )[ 0 ] === repo );
  const fileCount = filteredResults.filter( result => result.errorCount + result.warningCount > 0 ).length;
  const errorCount = _.sum( filteredResults.map( file => file.errorCount + file.warningCount ) );

  return { errorCount: errorCount, fileCount: fileCount };
}
<|endoftext|>


<commit_before>/*
 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
 */

var url = Usergrid.overrideUrl + '/status';

var getStatus = function(){
    var http = new XMLHttpRequest();

    http.onload= function(){
        if (http.readyState==4 || http.readyState=="complete")
        {
            console.log('response: \n'+http.responseText);
            document.getElementById("statusResponse")
                .innerHTML=http.responseText;
        }
    };

    http.open("GET",url, true);
    http.send();

};
<commit_msg>removing unnecessary logging<commit_after>/*
 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
 */

var url = Usergrid.overrideUrl + '/status';

var getStatus = function(){
    var http = new XMLHttpRequest();

    http.onload= function(){
        if (http.readyState==4 || http.readyState=="complete")
        {
            document.getElementById("statusResponse")
                .innerHTML=http.responseText;
        }
    };

    http.open("GET",url, true);
    http.send();

};
<|endoftext|>


<commit_before>describe("builder", function () {

    var builder = require('cordova/builder');

    it("includes the module into the target", function () {

        var target = {},
            objects = {
                foo: {
                    path: "cordova/plugin/compass"
                }
            };

        builder.build(objects).intoAndClobberTheFOutOf(target);
        expect(target.foo).toBeDefined();
        expect(target.foo).toBe(require("cordova/plugin/compass"));
    });

    it("returns an empty object literal if no path", function () {
        var target = {},
            objects = {cat: {}};

        builder.build(objects).intoButDontClobber(target);

        expect(target.cat).toBeDefined();
    });

    it("builds out the children", function () {

        var target = {},
            objects = {
               homer: {
                   children: {
                       bart: {},
                       lisa: {},
                       maggie: {
                           path: "cordova/plugin/compass"
                       }
                   }
               }
            };

        builder.build(objects).intoButDontClobber(target);

        expect(target.homer.bart).toBeDefined();
        expect(target.homer.maggie).toBe(require('cordova/plugin/compass'));
        expect(target.homer.lisa).toBeDefined();
    });
});
<commit_msg>updating tests following Drews changes...<commit_after>describe("builder", function () {

    var builder = require('cordova/builder');

    it("includes the module into the target", function () {

        var target = {},
            objects = {
                foo: {
                    path: "cordova/plugin/compass"
                }
            };

        builder.build(objects).intoAndClobber(target);
        expect(target.foo).toBeDefined();
        expect(target.foo).toBe(require("cordova/plugin/compass"));
    });

    it("returns an empty object literal if no path", function () {
        var target = {},
            objects = {cat: {}};

        builder.build(objects).intoButDontClobber(target);

        expect(target.cat).toBeDefined();
    });

    it("builds out the children", function () {

        var target = {},
            objects = {
               homer: {
                   children: {
                       bart: {},
                       lisa: {},
                       maggie: {
                           path: "cordova/plugin/compass"
                       }
                   }
               }
            };

        builder.build(objects).intoButDontClobber(target);

        expect(target.homer.bart).toBeDefined();
        expect(target.homer.maggie).toBe(require('cordova/plugin/compass'));
        expect(target.homer.lisa).toBeDefined();
    });
});
<|endoftext|>


<commit_before>/**
 * The UI Element for importing pedigrees from text representationin various formats
 *
 * @class ImportSelector
 */
var ImportSelector = Class.create({

	initialize: function () {
		if (editor.isReadOnlyMode()) return;

		var _this = this;

		var mainDiv = new Element('div', {'class': 'import-selector'});

		var promptImport = new Element('div', {'class': 'import-section'}).update("Import data:");
		this.importValue = new Element("textarea", {"id": "import", "value": "", "class": "import-textarea"});
		mainDiv.insert(promptImport).insert(this.importValue);

		if (!!window.FileReader && !!window.FileList) {
			// only show the upload link if browser supports FileReader/DOM File API
			// Of the browsers suported by pedigree editor, IE9 and Safari 4 & 5 do not support file API
			var uploadFileSelector = new Element('input', {"type": "file", "id": 'pedigreeInputFile', "style": 'display:none'});
			uploadFileSelector.observe('change', function (event) {
				_this.handleFileUpload(this.files);
				try {
					this.value = "";  // clear file selector
				} catch (err) {
					// some older browsers do not allow setting value of a file input element and may generate a security error
				}
			})
			var uploadButton = new Element('input', {type: 'button', 'value': 'Select a local file to be imported', 'class': 'button'}).wrap('span', {'class': 'buttonwrapper'});
			uploadButton.observe('click', function (event) {
				var fileElem = document.getElementById("pedigreeInputFile");
				fileElem.click();
			})
			mainDiv.insert(uploadFileSelector).insert(uploadButton);
		}

		var _addTypeOption = function (checked, labelText, value) {
			var optionWrapper = new Element('tr');
			var input = new Element('input', {"type": "radio", "value": value, "name": "select-type"});
			input.observe('click', _this.disableEnableOptions);
			if (checked) {
				input.checked = true;
			}
			var label = new Element('label', {'class': 'import-type-label'}).insert(input).insert(labelText);
			optionWrapper.insert(label.wrap('td'));
			return optionWrapper;
		};
		var typeListElement = new Element('table');
		//TODO: typeListElement.insert(_addTypeOption(true,  "Autodetect", "auto"));
		//Commented for GEK(GenomicsEngland)......................................................................
		//typeListElement.insert(_addTypeOption(true, "PED or LINKAGE (pre- or post- makeped)", "ped"));
		//typeListElement.insert(_addTypeOption(false, "GEDCOM", "gedcom"));
		//typeListElement.insert(_addTypeOption(false, "BOADICEA", "BOADICEA"));
		//........................................................................................................
		typeListElement.insert(_addTypeOption(true, "Simple JSON", "simpleJSON"));
		//TODO: typeListElement.insert(_addTypeOption(false, "Phenotips Pedigree JSON", "phenotipsJSON"));

		var promptType = new Element('div', {'class': 'import-section'}).update("Data format:");
		var dataSection2 = new Element('div', {'class': 'import-block'});
		dataSection2.insert(promptType).insert(typeListElement);
		mainDiv.insert(dataSection2);

		var _addConfigOption = function (checked, labelText, value) {
			var optionWrapper = new Element('tr');
			var input = new Element('input', {"type": "radio", "value": value, "name": "select-options" });
			if (checked) {
				input.checked = true;
			}
			var label = new Element('label', {'class': 'import-config-label'}).insert(input).insert(labelText);
			optionWrapper.insert(label.wrap('td'));
			return optionWrapper;
		};
		var configListElement = new Element('table', {id: 'import-type'});
		configListElement.insert(_addConfigOption(true, "Treat non-standard phenotype values as new disorders", "accept"));
		configListElement.insert(_addConfigOption(false, "Treat non-standard phenotype values as \"no information\"", "dontaccept"));

		var markEvaluated = new Element('input', {"type": "checkbox", "value": "1", "name": "mark-evaluated"});
		var markLabel1 = new Element('label', {'class': 'import-mark-label1'}).insert(markEvaluated).insert("Mark all patients with known disorder status with 'documented evaluation' mark").wrap('td').wrap('tr');
		configListElement.insert(markLabel1);
		var markExternal = new Element('input', {"type": "checkbox", "value": "1", "name": "mark-external"});
		markExternal.checked = true;
		var markLabel2 = new Element('label', {'class': 'import-mark-label2'}).insert(markExternal).insert("Save individual IDs as given in the input data as 'external ID'").wrap('td').wrap('tr');
		configListElement.insert(markLabel2);
		//Commented for GEK(GenomicsEngland)
		//var promptConfig = new Element('div', {'class': 'import-section'}).update("Options:");
		var dataSection3 = new Element('div', {'class': 'import-block'});
		//Commented for GEK(GenomicsEngland)
		//dataSection3.insert(promptConfig).insert(configListElement);
		mainDiv.insert(dataSection3);

		//TODO: [x] auto-combine multiple unaffected children when the number of children is greater than [5]

		var buttons = new Element('div', {'class': 'buttons import-block-bottom'});
		buttons.insert(new Element('input', {type: 'button', name: 'import', 'value': 'Import', 'class': 'button', 'id': 'import_button'}).wrap('span', {'class': 'buttonwrapper'}));
		buttons.insert(new Element('input', {type: 'button', name: 'cancel', 'value': 'Cancel', 'class': 'button secondary'}).wrap('span', {'class': 'buttonwrapper'}));
		mainDiv.insert(buttons);

		var cancelButton = buttons.down('input[name="cancel"]');
		cancelButton.observe('click', function (event) {
			_this.hide();
		})
		var importButton = buttons.down('input[name="import"]');
		importButton.observe('click', function (event) {
			_this._onImportStarted();
		})

		var closeShortcut = ['Esc'];
		this.dialog = new PhenoTips.widgets.ModalPopup(mainDiv, {close: {method: this.hide.bind(this), keys: closeShortcut}}, {extraClassName: "pedigree-import-chooser", title: "Pedigree import", displayCloseButton: true});
	},

	/*
	 * Populates the text input box with the selected file content (asynchronously)
	 */
	handleFileUpload: function (files) {
		for (var i = 0, numFiles = files.length; i < numFiles; i++) {
			var nextFile = files[i];
			console.log("loading file: " + nextFile.name + ", size: " + nextFile.size);

			var _this = this;
			var fr = new FileReader();
			fr.onload = function (e) {
				_this.importValue.value = e.target.result;  // e.target.result should contain the text
			};
			fr.readAsText(nextFile);
		}
	},

	/*
	 * Disables unapplicable options on input type selection
	 */
	disableEnableOptions: function () {
		var importType = $$('input:checked[type=radio][name="select-type"]')[0].value;
		//console.log("Import type: " + importType);
		var pedOnlyOptions = $$('input[type=radio][name="select-options"]');
		for (var i = 0; i < pedOnlyOptions.length; i++) {
			if (importType != "ped") {
				pedOnlyOptions[i].disabled = true;
			} else {
				pedOnlyOptions[i].disabled = false;
			}
		}
		var pedAndGedcomOption = $$('input[type=checkbox][name="mark-evaluated"]')[0];
		if (importType != "ped" && importType != "gedcom") {
			pedAndGedcomOption.disabled = true;
		} else {
			pedAndGedcomOption.disabled = false;
		}

		var saveExternalID = $$('input[type=checkbox][name="mark-external"]')[0];
		if (importType == "simpleJSON") {
			saveExternalID.disabled = true;
		} else {
			saveExternalID.disabled = false;
		}
	},

	/**
	 * Loads the template once it has been selected
	 *
	 * @param event
	 * @param pictureBox
	 * @private
	 */
	_onImportStarted: function () {
		var importValue = this.importValue.value;
		console.log("Importing:\n" + importValue);

		this.hide();

		if (!importValue || importValue == "") {
			alert("Nothing to import!");
			return;
		}

		var importType = $$('input:checked[type=radio][name="select-type"]')[0].value;
		console.log("Import type: " + importType);

		var importMark = $$('input[type=checkbox][name="mark-evaluated"]')[0].checked;

		var externalIdMark = $$('input[type=checkbox][name="mark-external"]')[0].checked;

		var optionSelected = $$('input:checked[type=radio][name="select-options"]')[0].value;
		var acceptUnknownPhenotypes = (optionSelected == "accept");

		var importOptions = { "markEvaluated": importMark, "externalIdMark": externalIdMark, "acceptUnknownPhenotypes": acceptUnknownPhenotypes };

		editor.getSaveLoadEngine().createGraphFromImportData(importValue, importType, importOptions,
			false /* add to undo stack */, true /*center around 0*/);
	},

	/**
	 * Displays the template selector
	 *
	 * @method show
	 */
	show: function () {
		this.dialog.show();
	},

	/**
	 * Removes the the template selector
	 *
	 * @method hide
	 */
	hide: function () {
		this.importValue.value = "";
		this.dialog.closeDialog();
	}
});<commit_msg>Remove options from Import selector (as we just support JSON import)<commit_after>/**
 * The UI Element for importing pedigrees from text representationin various formats
 *
 * @class ImportSelector
 */
var ImportSelector = Class.create({

	initialize: function () {
		if (editor.isReadOnlyMode()) return;

		var _this = this;

		var mainDiv = new Element('div', {'class': 'import-selector'});

		var promptImport = new Element('div', {'class': 'import-section'}).update("Import data:");
		this.importValue = new Element("textarea", {"id": "import", "value": "", "class": "import-textarea"});
		mainDiv.insert(promptImport).insert(this.importValue);

		if (!!window.FileReader && !!window.FileList) {
			// only show the upload link if browser supports FileReader/DOM File API
			// Of the browsers suported by pedigree editor, IE9 and Safari 4 & 5 do not support file API
			var uploadFileSelector = new Element('input', {"type": "file", "id": 'pedigreeInputFile', "style": 'display:none'});
			uploadFileSelector.observe('change', function (event) {
				_this.handleFileUpload(this.files);
				try {
					this.value = "";  // clear file selector
				} catch (err) {
					// some older browsers do not allow setting value of a file input element and may generate a security error
				}
			})
			var uploadButton = new Element('input', {type: 'button', 'value': 'Select a local file to be imported', 'class': 'button'}).wrap('span', {'class': 'buttonwrapper'});
			uploadButton.observe('click', function (event) {
				var fileElem = document.getElementById("pedigreeInputFile");
				fileElem.click();
			})
			mainDiv.insert(uploadFileSelector).insert(uploadButton);
		}

		var _addTypeOption = function (checked, labelText, value) {
			var optionWrapper = new Element('tr');
			var input = new Element('input', {"type": "radio", "value": value, "name": "select-type"});
			input.observe('click', _this.disableEnableOptions);
			if (checked) {
				input.checked = true;
			}
			var label = new Element('label', {'class': 'import-type-label'}).insert(input).insert(labelText);
			optionWrapper.insert(label.wrap('td'));
			return optionWrapper;
		};
		var typeListElement = new Element('table');
		//TODO: typeListElement.insert(_addTypeOption(true,  "Autodetect", "auto"));
		//Commented for GEK(GenomicsEngland)......................................................................
		//typeListElement.insert(_addTypeOption(true, "PED or LINKAGE (pre- or post- makeped)", "ped"));
		//typeListElement.insert(_addTypeOption(false, "GEDCOM", "gedcom"));
		//typeListElement.insert(_addTypeOption(false, "BOADICEA", "BOADICEA"));
		//........................................................................................................
		typeListElement.insert(_addTypeOption(true, "Simple JSON", "simpleJSON"));
		//TODO: typeListElement.insert(_addTypeOption(false, "Phenotips Pedigree JSON", "phenotipsJSON"));

		var promptType = new Element('div', {'class': 'import-section'}).update("Data format:");
		var dataSection2 = new Element('div', {'class': 'import-block'});
		dataSection2.insert(promptType).insert(typeListElement);
		mainDiv.insert(dataSection2);

		var _addConfigOption = function (checked, labelText, value) {
			var optionWrapper = new Element('tr');
			var input = new Element('input', {"type": "radio", "value": value, "name": "select-options" });
			if (checked) {
				input.checked = true;
			}
			var label = new Element('label', {'class': 'import-config-label'}).insert(input).insert(labelText);
			optionWrapper.insert(label.wrap('td'));
			return optionWrapper;
		};
		var configListElement = new Element('table', {id: 'import-type'});
		configListElement.insert(_addConfigOption(true, "Treat non-standard phenotype values as new disorders", "accept"));
		configListElement.insert(_addConfigOption(false, "Treat non-standard phenotype values as \"no information\"", "dontaccept"));

		var markEvaluated = new Element('input', {"type": "checkbox", "value": "1", "name": "mark-evaluated"});
		var markLabel1 = new Element('label', {'class': 'import-mark-label1'}).insert(markEvaluated).insert("Mark all patients with known disorder status with 'documented evaluation' mark").wrap('td').wrap('tr');
		configListElement.insert(markLabel1);
		var markExternal = new Element('input', {"type": "checkbox", "value": "1", "name": "mark-external"});
		markExternal.checked = true;
		var markLabel2 = new Element('label', {'class': 'import-mark-label2'}).insert(markExternal).insert("Save individual IDs as given in the input data as 'external ID'").wrap('td').wrap('tr');
		configListElement.insert(markLabel2);
		//Commented for GEK(GenomicsEngland)
		//var promptConfig = new Element('div', {'class': 'import-section'}).update("Options:");
		var dataSection3 = new Element('div', {'class': 'import-block'});
		//Commented for GEK(GenomicsEngland)
		//dataSection3.insert(promptConfig).insert(configListElement);
		mainDiv.insert(dataSection3);

		//TODO: [x] auto-combine multiple unaffected children when the number of children is greater than [5]

		var buttons = new Element('div', {'class': 'buttons import-block-bottom'});
		buttons.insert(new Element('input', {type: 'button', name: 'import', 'value': 'Import', 'class': 'button', 'id': 'import_button'}).wrap('span', {'class': 'buttonwrapper'}));
		buttons.insert(new Element('input', {type: 'button', name: 'cancel', 'value': 'Cancel', 'class': 'button secondary'}).wrap('span', {'class': 'buttonwrapper'}));
		mainDiv.insert(buttons);

		var cancelButton = buttons.down('input[name="cancel"]');
		cancelButton.observe('click', function (event) {
			_this.hide();
		})
		var importButton = buttons.down('input[name="import"]');
		importButton.observe('click', function (event) {
			_this._onImportStarted();
		})

		var closeShortcut = ['Esc'];
		this.dialog = new PhenoTips.widgets.ModalPopup(mainDiv, {close: {method: this.hide.bind(this), keys: closeShortcut}}, {extraClassName: "pedigree-import-chooser", title: "Pedigree import", displayCloseButton: true});
	},

	/*
	 * Populates the text input box with the selected file content (asynchronously)
	 */
	handleFileUpload: function (files) {
		for (var i = 0, numFiles = files.length; i < numFiles; i++) {
			var nextFile = files[i];
			console.log("loading file: " + nextFile.name + ", size: " + nextFile.size);

			var _this = this;
			var fr = new FileReader();
			fr.onload = function (e) {
				_this.importValue.value = e.target.result;  // e.target.result should contain the text
			};
			fr.readAsText(nextFile);
		}
	},

	/*
	 * Disables unapplicable options on input type selection
	 */
	disableEnableOptions: function () {
		var importType = $$('input:checked[type=radio][name="select-type"]')[0].value;
		//console.log("Import type: " + importType);
		var pedOnlyOptions = $$('input[type=radio][name="select-options"]');
		for (var i = 0; i < pedOnlyOptions.length; i++) {
			if (importType != "ped") {
				pedOnlyOptions[i].disabled = true;
			} else {
				pedOnlyOptions[i].disabled = false;
			}
		}
		var pedAndGedcomOption = $$('input[type=checkbox][name="mark-evaluated"]')[0];
		if (importType != "ped" && importType != "gedcom") {
			pedAndGedcomOption.disabled = true;
		} else {
			pedAndGedcomOption.disabled = false;
		}

		var saveExternalID = $$('input[type=checkbox][name="mark-external"]')[0];
		if (importType == "simpleJSON") {
			saveExternalID.disabled = true;
		} else {
			saveExternalID.disabled = false;
		}
	},

	/**
	 * Loads the template once it has been selected
	 *
	 * @param event
	 * @param pictureBox
	 * @private
	 */
	_onImportStarted: function () {
		var importValue = this.importValue.value;
		console.log("Importing:\n" + importValue);

		this.hide();

		if (!importValue || importValue == "") {
			alert("Nothing to import!");
			return;
		}

		var importType = $$('input:checked[type=radio][name="select-type"]')[0].value;
		console.log("Import type: " + importType);

		//commented for GEL(GenomicsEngland), as options are removed form UI and we just support JSON import
		var importMark = [];//$$('input[type=checkbox][name="mark-evaluated"]')[0].checked;

		//commented for GEL(GenomicsEngland), as options are removed form UI and we just support JSON import
		var externalIdMark = [];//$$('input[type=checkbox][name="mark-external"]')[0].checked;

		//commented for GEL(GenomicsEngland), as options are removed form UI and we just support JSON import
		//var optionSelected = $$('input:checked[type=radio][name="select-options"]')[0].value;

		//commented for GEL(GenomicsEngland), as options are removed form UI and we just support JSON import
		var acceptUnknownPhenotypes =[];// (optionSelected == "accept");

		var importOptions = { "markEvaluated": importMark, "externalIdMark": externalIdMark, "acceptUnknownPhenotypes": acceptUnknownPhenotypes };

		editor.getSaveLoadEngine().createGraphFromImportData(importValue, importType, importOptions,
			false /* add to undo stack */, true /*center around 0*/);
	},

	/**
	 * Displays the template selector
	 *
	 * @method show
	 */
	show: function () {
		this.dialog.show();
	},

	/**
	 * Removes the the template selector
	 *
	 * @method hide
	 */
	hide: function () {
		this.importValue.value = "";
		this.dialog.closeDialog();
	}
});<|endoftext|>


<commit_before>(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD
        define(['jquery'], factory);
    } else if (typeof exports === 'object') {
        // CommonJS
        factory(require('jquery'));
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {
  var CountTo = function (element, options) {
    this.$element = $(element);
    this.options  = $.extend({}, CountTo.DEFAULTS, this.dataOptions(), options);
    this.init();
  };

  CountTo.DEFAULTS = {
    from: 0,               // the number the element should start at
    to: 0,                 // the number the element should end at
    speed: 1000,           // how long it should take to count between the target numbers
    refreshInterval: 100,  // how often the element should be updated
    decimals: 0,           // the number of decimal places to show
    formatter: formatter,  // handler for formatting the value before rendering
    onUpdate: null,        // callback method for every time the element is updated
    onComplete: null       // callback method for when the element finishes updating
  };

  CountTo.prototype.init = function () {
    this.value     = this.options.from;
    this.loops     = Math.ceil(this.options.speed / this.options.refreshInterval);
    this.loopCount = 0;
    this.increment = (this.options.to - this.options.from) / this.loops;
  };

  CountTo.prototype.dataOptions = function () {
    var options = {
      from:            this.$element.data('from'),
      to:              this.$element.data('to'),
      speed:           this.$element.data('speed'),
      refreshInterval: this.$element.data('refresh-interval'),
      decimals:        this.$element.data('decimals')
    };

    var keys = Object.keys(options);

    for (var i in keys) {
      var key = keys[i];

      if (typeof(options[key]) === 'undefined') {
        delete options[key];
      }
    }

    return options;
  };

  CountTo.prototype.update = function () {
    this.value += this.increment;
    this.loopCount++;

    this.render();

    if (typeof(this.options.onUpdate) == 'function') {
      this.options.onUpdate.call(this.$element, this.value);
    }

    if (this.loopCount >= this.loops) {
      clearInterval(this.interval);
      this.value = this.options.to;

      if (typeof(this.options.onComplete) == 'function') {
        this.options.onComplete.call(this.$element, this.value);
      }
    }
  };

  CountTo.prototype.render = function () {
    var formattedValue = this.options.formatter.call(this.$element, this.value, this.options);
    this.$element.text(formattedValue);
  };

  CountTo.prototype.restart = function () {
    this.stop();
    this.init();
    this.start();
  };

  CountTo.prototype.start = function () {
    this.stop();
    this.render();
    this.interval = setInterval(this.update.bind(this), this.options.refreshInterval);
  };

  CountTo.prototype.stop = function () {
    if (this.interval) {
      clearInterval(this.interval);
    }
  };

  CountTo.prototype.toggle = function () {
    if (this.interval) {
      this.stop();
    } else {
      this.start();
    }
  };

  function formatter(value, options) {
    return value.toFixed(options.decimals);
  }

  $.fn.countTo = function (option) {
    return this.each(function () {
      var $this   = $(this);
      var data    = $this.data('countTo');
      var init    = !data || typeof(option) === 'object';
      var options = typeof(option) === 'object' ? option : {};
      var method  = typeof(option) === 'string' ? option : 'start';

      if (init) {
        if (data) data.stop();
        $this.data('countTo', data = new CountTo(this, options));
      }

      data[method].call(data);
    });
  };
}));
<commit_msg>Remove unused scripts<commit_after><|endoftext|>


<commit_before><commit_msg>Resolved a bug.<commit_after><|endoftext|>