<commit_before>/**
   @module ember-data
 */

import DS from 'ember-data';
import Ember from 'ember';
var Adapter = DS.Adapter;
var InvalidError = DS.InvalidError;
var BuildURLMixin = DS.BuildURLMixin;

var get = Ember.get;
var forEach = Ember.ArrayPolyfills.forEach;

/**
   @class JSONAPIAdapter
   @constructor
   @namespace DS
   @extends DS.Adapter
 */
export default Adapter.extend(BuildURLMixin, {
  defaultSerializer: '-json-api',

  coalesceFindRequests: false,

    /**
         @property host
         @type {String}
     */

    /**
         @property namespace
         @type {String}
     */

  find: function(store, type, id, snapshot) {
    return this.ajax(this.buildURL(type.typeKey, id, snapshot), 'GET');
  },

  findAll: function(store, type) {
    return this.ajax(this.buildURL(type.typeKey), 'GET');
  },

  findMany: function(store, type, ids, snapshots) {
    var data = {
      filter: {
        id: ids.join(',')
      }
    };
    return this.ajax(this.buildURL(type.typeKey, ids, snapshots), 'GET', { data: data });
  },

  findQuery: function(store, type, query) {
    return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query });
  },

  findBelongsTo: function(store, snapshot, link, relationship) {
    var url, id, type;

    if (link.related) {
      url = link.related;
    } else {
      id = snapshot.id;
      type = snapshot.typeKey;
      url = this.buildURL(type, id);
    }

    return this.ajax(url, 'GET');
  },

  findHasMany: function(store, snapshot, link, relationship) {
    var url; //, id, type, host;

    if (link.related) {
      url = link.related;
    } else {
      // TODO
      return;
    }

    return this.ajax(url, 'GET');
  },

  createRecord: function(store, type, snapshot) {
    var serializer = store.serializerFor(type.typeKey);
    var data = serializer.serialize(snapshot);

    return this.ajax(this.buildURL(type.typeKey, null, snapshot), 'POST', { data: data });
  },

  updateRecord: function(store, type, snapshot) {
    var serializer = store.serializerFor(type.typeKey);
    var data = serializer.serialize(snapshot, { includeId: true });

    var id = snapshot.id;

    return this.ajax(this.buildURL(type.typeKey, id, snapshot), 'PATCH', { data: data });
  },

  deleteRecord: function(store, type, snapshot) {
    var id = snapshot.id;

    return this.ajax(this.buildURL(type.typeKey, id, snapshot), 'DELETE');
  },

  pathForType: function(typeKey) {
    return Ember.String.dasherize(typeKey);
  },

  ajax: function(url, type, options) {
    var adapter = this;

    return new Ember.RSVP.Promise(function(resolve, reject) {
      var hash = adapter.ajaxOptions(url, type, options);

      hash.success = function(json, textStatus, jqXHR) {
        json = adapter.ajaxSuccess(jqXHR, json);
        if (json instanceof InvalidError) {
          Ember.run(null, reject, json);
        } else {
          Ember.run(null, resolve, json);
        }
      };

      hash.error = function(jqXHR, textStatus, errorThrown) {
        Ember.run(null, reject, adapter.ajaxError(jqXHR, jqXHR.responseText, errorThrown));
      };

      Ember.$.ajax(hash);
    }, 'DS: JSONAPIAdapter#ajax ' + type + ' to ' + url);
  },

  ajaxOptions: function(url, type, options) {
    var hash = options || {};
    hash.url = url;
    hash.type = type;
    hash.dataType = 'json';
    hash.context = this;

    if (hash.data && type !== 'GET') {
      hash.contentType = 'application/json; charset=utf-8';
      hash.data = JSON.stringify(hash.data);
    }

    var headers = get(this, 'headers');
    if (headers !== undefined) {
      hash.beforeSend = function (xhr) {
        forEach.call(Ember.keys(headers), function(key) {
          xhr.setRequestHeader(key, headers[key]);
        });
      };
    }

    return hash;
  },

  ajaxError: function(jqXHR, responseText, errorThrown) {
    var isObject = jqXHR !== null && typeof jqXHR === 'object';

    if (isObject) {
      jqXHR.then = null;
      if (!jqXHR.errorThrown) {
        if (typeof errorThrown === 'string') {
          jqXHR.errorThrown = new Error(errorThrown);
        } else {
          jqXHR.errorThrown = errorThrown;
        }
      }
    }

    return jqXHR;
  },

  ajaxSuccess: function(jqXHR, jsonPayload) {
    return jsonPayload;
  }

});
<commit_msg>pluralize type urls<commit_after>/**
   @module ember-data
 */

import DS from 'ember-data';
import Ember from 'ember';
var Adapter = DS.Adapter;
var InvalidError = DS.InvalidError;
var BuildURLMixin = DS.BuildURLMixin;

var get = Ember.get;
var forEach = Ember.ArrayPolyfills.forEach;

/**
   @class JSONAPIAdapter
   @constructor
   @namespace DS
   @extends DS.Adapter
 */
export default Adapter.extend(BuildURLMixin, {
  defaultSerializer: '-json-api',

  coalesceFindRequests: false,

    /**
         @property host
         @type {String}
     */

    /**
         @property namespace
         @type {String}
     */

  find: function(store, type, id, snapshot) {
    return this.ajax(this.buildURL(type.typeKey, id, snapshot), 'GET');
  },

  findAll: function(store, type) {
    return this.ajax(this.buildURL(type.typeKey), 'GET');
  },

  findMany: function(store, type, ids, snapshots) {
    var data = {
      filter: {
        id: ids.join(',')
      }
    };
    return this.ajax(this.buildURL(type.typeKey, ids, snapshots), 'GET', { data: data });
  },

  findQuery: function(store, type, query) {
    return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query });
  },

  findBelongsTo: function(store, snapshot, link, relationship) {
    var url, id, type;

    if (link.related) {
      url = link.related;
    } else {
      id = snapshot.id;
      type = snapshot.typeKey;
      url = this.buildURL(type, id);
    }

    return this.ajax(url, 'GET');
  },

  findHasMany: function(store, snapshot, link, relationship) {
    var url; //, id, type, host;

    if (link.related) {
      url = link.related;
    } else {
      // TODO
      return;
    }

    return this.ajax(url, 'GET');
  },

  createRecord: function(store, type, snapshot) {
    var serializer = store.serializerFor(type.typeKey);
    var data = serializer.serialize(snapshot);

    return this.ajax(this.buildURL(type.typeKey, null, snapshot), 'POST', { data: data });
  },

  updateRecord: function(store, type, snapshot) {
    var serializer = store.serializerFor(type.typeKey);
    var data = serializer.serialize(snapshot, { includeId: true });

    var id = snapshot.id;

    return this.ajax(this.buildURL(type.typeKey, id, snapshot), 'PATCH', { data: data });
  },

  deleteRecord: function(store, type, snapshot) {
    var id = snapshot.id;

    return this.ajax(this.buildURL(type.typeKey, id, snapshot), 'DELETE');
  },

  pathForType: function(typeKey) {
    return Ember.String.pluralize(Ember.String.dasherize(typeKey));
  },

  ajax: function(url, type, options) {
    var adapter = this;

    return new Ember.RSVP.Promise(function(resolve, reject) {
      var hash = adapter.ajaxOptions(url, type, options);

      hash.success = function(json, textStatus, jqXHR) {
        json = adapter.ajaxSuccess(jqXHR, json);
        if (json instanceof InvalidError) {
          Ember.run(null, reject, json);
        } else {
          Ember.run(null, resolve, json);
        }
      };

      hash.error = function(jqXHR, textStatus, errorThrown) {
        Ember.run(null, reject, adapter.ajaxError(jqXHR, jqXHR.responseText, errorThrown));
      };

      Ember.$.ajax(hash);
    }, 'DS: JSONAPIAdapter#ajax ' + type + ' to ' + url);
  },

  ajaxOptions: function(url, type, options) {
    var hash = options || {};
    hash.url = url;
    hash.type = type;
    hash.dataType = 'json';
    hash.context = this;

    if (hash.data && type !== 'GET') {
      hash.contentType = 'application/json; charset=utf-8';
      hash.data = JSON.stringify(hash.data);
    }

    var headers = get(this, 'headers');
    if (headers !== undefined) {
      hash.beforeSend = function (xhr) {
        forEach.call(Ember.keys(headers), function(key) {
          xhr.setRequestHeader(key, headers[key]);
        });
      };
    }

    return hash;
  },

  ajaxError: function(jqXHR, responseText, errorThrown) {
    var isObject = jqXHR !== null && typeof jqXHR === 'object';

    if (isObject) {
      jqXHR.then = null;
      if (!jqXHR.errorThrown) {
        if (typeof errorThrown === 'string') {
          jqXHR.errorThrown = new Error(errorThrown);
        } else {
          jqXHR.errorThrown = errorThrown;
        }
      }
    }

    return jqXHR;
  },

  ajaxSuccess: function(jqXHR, jsonPayload) {
    return jsonPayload;
  }

});
<|endoftext|>


<commit_before>import Ember from 'ember';
import EmptyObject from './util/empty-object';
import { isClass_ } from './util/assert';

const {
  computed,
  copy,
  get,
  A
} = Ember;

export function create() {
  return computed(function() {
    return new Definition(this);
  }).readOnly();
}

const sofaKey = '__sofa';

function lookupProperties(modelClass) {
  let all = A();
  let byName = new EmptyObject();

  let store = get(modelClass, 'store');
  modelClass.eachComputedProperty((name, meta) => {
    if(!meta || meta[sofaKey] !== true) {
      return;
    }

    let property = meta.property;
    property.prepareModelClass(name, modelClass, store);

    all.push(property);
    byName[name] = property;
  });

  all.reverse();

  return { all, byName };
}

export default class Definition {

  constructor(modelClass) {
    this.modelClass = modelClass;
    this.properties = lookupProperties(modelClass);
  }

  get modelName() {
    let modelName = this._modelName;
    if(!modelName) {
      modelName = get(this.modelClass, 'modelName');
      this._modelName = modelName;
    }
    return modelName;
  }

  get type() {
    let property = this.property('type');
    return property.getDocumentKeyValue(this.modelClass);
  }

  eachProperty(fn) {
    this.properties.all.forEach(fn);
  }

  prepareInternalModel(internalModel, opts) {
    opts = copy(opts || {});
    internalModel.withPropertyChanges(changed => {
      this.eachProperty(property => {
        let key = property.prepareInternalModel(internalModel, opts, changed);
        if(key) {
          delete opts[key];
        }
      });
    }, false);
    return opts;
  }

  property(name) {
    return this.properties.byName[name];
  }

  matchesDocument(doc) {
    return this.property('type').matchesDocument(this.modelClass, doc);
  }

  serialize(internal, preview=false) {
    let doc = copy(internal.raw || {});
    this.eachProperty(property => {
      property.serialize(internal, doc, preview);
    });
    return doc;
  }

  deserialize(internal, doc, changed) {
    let raw = copy(doc);
    this.eachProperty(property => {
      let key = property.deserialize(internal, doc, changed);
      if(key) {
        delete raw[key];
      }
    });
    internal.raw = raw;
  }

  deserializeProperty(internal, name, value, changed) {
    let property = this.property(name);
    let key = property.opts.key;
    let doc = { [key]: value };
    property.deserialize(internal, doc, changed);
  }

  deserializeSaveOrUpdate(internal, json, changed) {
    this.deserializeProperty(internal, 'id', json.id, changed);
    this.deserializeProperty(internal, 'rev', json.rev, changed);
  }

  deserializeDelete(internal, json, changed) {
    if(!json) {
      return;
    }
    this.deserializeProperty(internal, 'id', json.id, changed);
    this.deserializeProperty(internal, 'rev', null, changed);
  }

  deserializeAttachments(internal, doc, changed) {
    this.property('attachments').deserialize(internal, doc, changed);
  }

  docId(modelId) {
    return this.property('id').docId(this.modelClass, modelId);
  }

  modelId(docId) {
    return this.property('id').modelId(this.modelClass, docId);
  }

  is(parent) {
    isClass_(`parent must be class not ${parent}`, parent);
    let arg = parent.superclass.superclass;
    let self = this.modelClass.superclass.superclass;
    while(self) {
      if(arg === self) {
        return true;
      }
      self = self.superclass;
      if(self === Ember.Object) {
        return false;
      }
    }
    return false;
  }

  onLoaded(internal, doc, changed) {
    this.deserialize(internal, doc, changed);
    internal.onLoaded(changed);
  }

  onSaved(internal, json, changed) {
    this.deserializeSaveOrUpdate(internal, json, changed);
    internal.onSaved(changed);
  }

  onDeleted(internal, json, changed) {
    this.deserializeDelete(internal, json, changed);
    internal.onDeleted(changed);
  }

}
<commit_msg>definition.is update to reflect factoryFor changes in Ember<commit_after>import Ember from 'ember';
import EmptyObject from './util/empty-object';
import { isClass_ } from './util/assert';

const {
  computed,
  copy,
  get,
  A
} = Ember;

export function create() {
  return computed(function() {
    return new Definition(this);
  }).readOnly();
}

const sofaKey = '__sofa';

function lookupProperties(modelClass) {
  let all = A();
  let byName = new EmptyObject();

  let store = get(modelClass, 'store');
  modelClass.eachComputedProperty((name, meta) => {
    if(!meta || meta[sofaKey] !== true) {
      return;
    }

    let property = meta.property;
    property.prepareModelClass(name, modelClass, store);

    all.push(property);
    byName[name] = property;
  });

  all.reverse();

  return { all, byName };
}

export default class Definition {

  constructor(modelClass) {
    this.modelClass = modelClass;
    this.properties = lookupProperties(modelClass);
  }

  get modelName() {
    let modelName = this._modelName;
    if(!modelName) {
      modelName = get(this.modelClass, 'modelName');
      this._modelName = modelName;
    }
    return modelName;
  }

  get type() {
    let property = this.property('type');
    return property.getDocumentKeyValue(this.modelClass);
  }

  eachProperty(fn) {
    this.properties.all.forEach(fn);
  }

  prepareInternalModel(internalModel, opts) {
    opts = copy(opts || {});
    internalModel.withPropertyChanges(changed => {
      this.eachProperty(property => {
        let key = property.prepareInternalModel(internalModel, opts, changed);
        if(key) {
          delete opts[key];
        }
      });
    }, false);
    return opts;
  }

  property(name) {
    return this.properties.byName[name];
  }

  matchesDocument(doc) {
    return this.property('type').matchesDocument(this.modelClass, doc);
  }

  serialize(internal, preview=false) {
    let doc = copy(internal.raw || {});
    this.eachProperty(property => {
      property.serialize(internal, doc, preview);
    });
    return doc;
  }

  deserialize(internal, doc, changed) {
    let raw = copy(doc);
    this.eachProperty(property => {
      let key = property.deserialize(internal, doc, changed);
      if(key) {
        delete raw[key];
      }
    });
    internal.raw = raw;
  }

  deserializeProperty(internal, name, value, changed) {
    let property = this.property(name);
    let key = property.opts.key;
    let doc = { [key]: value };
    property.deserialize(internal, doc, changed);
  }

  deserializeSaveOrUpdate(internal, json, changed) {
    this.deserializeProperty(internal, 'id', json.id, changed);
    this.deserializeProperty(internal, 'rev', json.rev, changed);
  }

  deserializeDelete(internal, json, changed) {
    if(!json) {
      return;
    }
    this.deserializeProperty(internal, 'id', json.id, changed);
    this.deserializeProperty(internal, 'rev', null, changed);
  }

  deserializeAttachments(internal, doc, changed) {
    this.property('attachments').deserialize(internal, doc, changed);
  }

  docId(modelId) {
    return this.property('id').docId(this.modelClass, modelId);
  }

  modelId(docId) {
    return this.property('id').modelId(this.modelClass, docId);
  }

  is(parent) {
    isClass_(`parent must be class not ${parent}`, parent);
    let arg = parent.superclass;
    let self = this.modelClass.superclass;
    while(self) {
      if(arg === self) {
        return true;
      }
      self = self.superclass;
      if(self === Ember.Object) {
        return false;
      }
    }
    return false;
  }

  onLoaded(internal, doc, changed) {
    this.deserialize(internal, doc, changed);
    internal.onLoaded(changed);
  }

  onSaved(internal, json, changed) {
    this.deserializeSaveOrUpdate(internal, json, changed);
    internal.onSaved(changed);
  }

  onDeleted(internal, json, changed) {
    this.deserializeDelete(internal, json, changed);
    internal.onDeleted(changed);
  }

}
<|endoftext|>


<commit_before>// when $routeProvider.whenAuthenticated() is called, the path is stored in this list
// to be used by authRequired() in the services below
var securedRoutes = [];

/**
* Adds a special `whenAuthenticated` method onto $routeProvider. This special method,
* when called, waits for auth status to be resolved asynchronously, and then fails/redirects
* if the user is not properly authenticated.
*
* The promise either resolves to the authenticated user object and makes it available to
* dependency injection (see AuthCtrl), or rejects the promise if user is not logged in,
* forcing a redirect to the /login page
*/
app.config(['$routeProvider', function ($routeProvider) {
  // credits for this idea: https://groups.google.com/forum/#!msg/angular/dPr9BpIZID0/MgWVluo_Tg8J
  // unfortunately, a decorator cannot be use here because they are not applied until after
  // the .config calls resolve, so they can't be used during route configuration, so we have
  // to hack it directly onto the $routeProvider object
  $routeProvider.whenAuthenticated = function (path, route) {
    securedRoutes.push(path); // store all secured routes for use with authRequired() below
    route.resolve = route.resolve || {};
    route.resolve.user = ['Auth', function (Auth) {
      return Auth.$requireAuth();
    }];

    $routeProvider.when(path, route);
    return this;
  }
}])

.config(['$httpProvider', 'API_USER', 'API_KEY', function($httpProvider, API_USER, API_KEY) {
  $httpProvider.defaults.headers.common['Authorization'] = "ApiKey " + API_USER + ":" + API_KEY;
}])

/**
* Apply some route security. Any route's resolve method can reject the promise with
* { authRequired: true } to force a redirect. This method enforces that and also watches
* for changes in auth status which might require us to navigate away from a path
* that we can no longer view.
*/
.run(['$rootScope', '$location', 'Auth', 'loginRedirectPath', '$localStorage', '$sessionStorage',
  function ($rootScope, $location, Auth, loginRedirectPath, $localStorage, $sessionStorage) {
    // watch for login status changes and redirect if appropriate
    // Auth.$onAuth(check);
    $rootScope.user = $localStorage.user;
    $rootScope.logout = Auth.$logout;
    // some of our routes may reject resolve promises with the special {authRequired: true} error
    // this redirects to the login page whenever that is encountered
    $rootScope.$on("$routeChangeError", function (e, next, prev, err) {
      if (err === "AUTH_REQUIRED") {
        $location.path(loginRedirectPath);
      }
    });

    $rootScope.$on("$routeChangeStart", function(e, next, current){

      if (!!next) {
        if (next.originalPath.toLowerCase() === '/login' || next.originalPath.toLowerCase() === '/signup') {
          if (!!$sessionStorage.auth || !!$localStorage.auth) {
            $location.path('/dashboard');
          };
        };
      } else {
        if (current.originalPath.toLowerCase() === '/login' || current.originalPath.toLowerCase() === '/signup') {
          if (!!$sessionStorage.auth || !!$localStorage.auth) {
            $location.path('/dashboard');
          };
        };
      }
    });

    function check(user) {
      if (!$localStorage.user && authRequired($location.path())) {
        $location.path(loginRedirectPath);
      }
    }

    function authRequired(path) {
      console.log('authRequired?', path, securedRoutes.indexOf(path)); //debug
      return securedRoutes.indexOf(path) !== -1;
    }
  }
]);

<commit_msg>update frontend configurations<commit_after>// when $routeProvider.whenAuthenticated() is called, the path is stored in this list
// to be used by authRequired() in the services below
var securedRoutes = [];

/**
* Adds a special `whenAuthenticated` method onto $routeProvider. This special method,
* when called, waits for auth status to be resolved asynchronously, and then fails/redirects
* if the user is not properly authenticated.
*
* The promise either resolves to the authenticated user object and makes it available to
* dependency injection (see AuthCtrl), or rejects the promise if user is not logged in,
* forcing a redirect to the /login page
*/
app.config(['$routeProvider', function ($routeProvider) {
  // credits for this idea: https://groups.google.com/forum/#!msg/angular/dPr9BpIZID0/MgWVluo_Tg8J
  // unfortunately, a decorator cannot be use here because they are not applied until after
  // the .config calls resolve, so they can't be used during route configuration, so we have
  // to hack it directly onto the $routeProvider object
  $routeProvider.whenAuthenticated = function (path, route) {
    securedRoutes.push(path); // store all secured routes for use with authRequired() below
    route.resolve = route.resolve || {};
    route.resolve.user = ['Auth', function (Auth) {
      return Auth.$requireAuth();
    }];

    $routeProvider.when(path, route);
    return this;
  }
}])

.config(['$httpProvider', 'API_USER', 'API_KEY', function($httpProvider, API_USER, API_KEY) {
  $httpProvider.defaults.headers.common['Authorization'] = "ApiKey " + API_USER + ":" + API_KEY;
}])

.config(['cfpLoadingBarProvider', function(cfpLoadingBarProvider) {
    cfpLoadingBarProvider.includeSpinner = false;
  }])

/**
* Apply some route security. Any route's resolve method can reject the promise with
* { authRequired: true } to force a redirect. This method enforces that and also watches
* for changes in auth status which might require us to navigate away from a path
* that we can no longer view.
*/
.run(['$rootScope', '$location', 'Auth', 'loginRedirectPath', '$localStorage', '$sessionStorage',
  function ($rootScope, $location, Auth, loginRedirectPath, $localStorage, $sessionStorage) {
    // watch for login status changes and redirect if appropriate
    // Auth.$onAuth(check);
    $rootScope.user = $localStorage.user;
    $rootScope.logout = Auth.$logout;
    // some of our routes may reject resolve promises with the special {authRequired: true} error
    // this redirects to the login page whenever that is encountered
    $rootScope.$on("$routeChangeError", function (e, next, prev, err) {
      if (err === "AUTH_REQUIRED") {
        $location.path(loginRedirectPath);
      }
    });

    $rootScope.$on("$routeChangeStart", function(e, next, current){

      if (!!next) {
        if (next.originalPath.toLowerCase() === '/login' || next.originalPath.toLowerCase() === '/signup') {
          if (!!$sessionStorage.auth || !!$localStorage.auth) {
            $location.path('/dashboard');
          };
        };
      } else {
        if (current.originalPath.toLowerCase() === '/login' || current.originalPath.toLowerCase() === '/signup') {
          if (!!$sessionStorage.auth || !!$localStorage.auth) {
            $location.path('/dashboard');
          };
        };
      }
    });

    function check(user) {
      if (!$localStorage.user && authRequired($location.path())) {
        $location.path(loginRedirectPath);
      }
    }

    function authRequired(path) {
      console.log('authRequired?', path, securedRoutes.indexOf(path)); //debug
      return securedRoutes.indexOf(path) !== -1;
    }
  }
]);

<|endoftext|>


<commit_before>//todo list to return:
//color
//play these notes
//play these chords

var coords = [];
var outputNotes = [];

//sort ascending x
function sortX(a, b) {
	return a.x - b.x;
}

//sort ascending y
function sortY(a, b) {
	return a.y - b.y;
}

function getMeanInRange(low, high) {
	var sum = 0;
	var count = 1;

	for(var i = 0; i < coords.length; i++){
		if(coords[i].x > low && coords[i].x < high){
			sum += coords[i].y;
			count++;
		}
	}
	var mean = sum/count;
	//console.log(Math.floor(mean))
	return Math.floor(mean);
}

function getMaxInRange(low, high) {
	var curMax = 0;

	for(var i = 0; i < coords.length; i++){
		if(coords[i].x > low && coords[i].x < high){
			if(coords[i].y > curMax){
				curMax = coords[i].y;
			}
		}
	}
	return curMax;
}

function getMinInRange(low, high) {
	var curMin = 9999;

	for(var i = 0; i < coords.length; i++){
		if(coords[i].x > low && coords[i].x < high){
			if(coords[i].y < curMin){
				curMin = coords[i].y;
			}
		}
	}
	return curMin;
}

function convertMeanToNum(minY, maxY, mean){
	//divide into n sections
	var n = 10;
	var sectionsize = (maxY-minY)/n;
	var num = 1;
	for(var i = minY; i < maxY; i+=sectionsize){

		if(mean > i && mean < (i + sectionsize)){
			//console.log(num);
			return num;
		}
		num++;
	}
	return num;
}

function parseCanvas() {
	coords.sort(sortX);

	var minX = coords[0].x;
	var maxX = coords[coords.length-1].x;
	var range = maxX - minX;

	coords.sort(sortY);
	var minY = coords[0].y;
	var maxY = coords[coords.length-1].y;

	outputNotes = [];

	//split signature range into n parts for n notes
	var sectionsize = range/16;
	for(var i = minX; i < maxX; i += sectionsize){
		var curmean = getMeanInRange(i, i+sectionsize);
	}

	for(var j = minX; j < maxX; j += sectionsize){
		var notecurmean = getMeanInRange(j, j+sectionsize);
		outputNotes.push(convertMeanToNum(getMinInRange(j, j+sectionsize), getMaxInRange(j, j+sectionsize), notecurmean));
	}

	console.log(outputNotes);
}

<commit_msg>add 0's to the melody for holding out<commit_after>//todo list to return:
//color
//play these notes
//play these chords

var coords = [];
var outputNotes = [];

//sort ascending x
function sortX(a, b) {
	return a.x - b.x;
}

//sort ascending y
function sortY(a, b) {
	return a.y - b.y;
}

function getMeanInRange(low, high) {
	var sum = 0;
	var count = 1;

	for(var i = 0; i < coords.length; i++){
		if(coords[i].x > low && coords[i].x < high){
			sum += coords[i].y;
			count++;
		}
	}
	var mean = sum/count;
	//console.log(Math.floor(mean))
	return Math.floor(mean);
}

function getMaxInRange(low, high) {
	var curMax = 0;

	for(var i = 0; i < coords.length; i++){
		if(coords[i].x > low && coords[i].x < high){
			if(coords[i].y > curMax){
				curMax = coords[i].y;
			}
		}
	}
	return curMax;
}

function getMinInRange(low, high) {
	var curMin = 9999;

	for(var i = 0; i < coords.length; i++){
		if(coords[i].x > low && coords[i].x < high){
			if(coords[i].y < curMin){
				curMin = coords[i].y;
			}
		}
	}
	return curMin;
}

function convertMeanToNum(minY, maxY, mean){
	//divide into n sections
	var n = 10;
	var sectionsize = (maxY-minY)/n;
	var num = 1;
	for(var i = minY; i < maxY; i+=sectionsize){

		if(mean > i && mean < (i + sectionsize)){
			//console.log(num);
			return num;
		}
		num++;
	}
	return num;
}

function parseCanvas() {
	coords.sort(sortX);

	var minX = coords[0].x;
	var maxX = coords[coords.length-1].x;
	var range = maxX - minX;

	coords.sort(sortY);
	var minY = coords[0].y;
	var maxY = coords[coords.length-1].y;

	outputNotes = [];

	//split signature range into n parts for n notes
	var sectionsize = range/16;
	for(var i = minX; i < maxX; i += sectionsize){
		var curmean = getMeanInRange(i, i+sectionsize);
	}

	for(var j = minX; j < maxX; j += sectionsize){
		var notecurmean = getMeanInRange(j, j+sectionsize);
		if(Math.random() > 0.6){
			outputNotes.push(0);
		}
		outputNotes.push(convertMeanToNum(getMinInRange(j, j+sectionsize), getMaxInRange(j, j+sectionsize), notecurmean));
	}

	console.log(outputNotes);
}

<|endoftext|>


<commit_before>var Document = Backbone.Model.extend({
  urlRoot: '/api/documents/',
  initialize: function(){
    this.on("change", function(){

    });
  }
});
var Milestone = Backbone.Model.extend({
});
var Address = Backbone.Model.extend({
});
var Date = Backbone.Model.extend({
});
var Person = Backbone.Model.extend({
  urlRoot: "/api/people/",
  initialize: function(){
    this.on("change:name", function(){
        alert("the name has changed");
    });
  }
});
var Paragraph = Backbone.Model.extend({});
var ParagraphList = Backbone.Collection.extend({
  model: Paragraph,
  url: function(){
    return '/api/documents/' + this.get("document_id");
  },
  initialize: function(){
    this.on("change", function(){
      alert("fasfs");
    });
  },
});
var AnalyzerView = Backbone.View.extend({
  el: $("#sidebar"),
  sidebarTemplate: $("#combTemplate").html(),
  events: {
  },
  initialize: function(){
  }
});
var DocumentContext = Backbone.View.extend({
  el: $("#context"),
  documentTemplate: $("#documentContextTemplate").html(),
  initialize: function(){
    this.model.on('change', this.render, this)
  },
  render: function(){
    var html = Mustache.render(this.documentTemplate, this.model.toJSON());
    this.$el.html(html);
    return this;
  }
});
var ParagraphView = Backbone.View.extend({
  events: {
    "click span": "selectNamedEntity"
  },
  className: "paragraph",
  paragraphTemplate: $("#paragraphTemplate").html(),
  render: function(){
    var html = Mustache.render(this.paragraphTemplate, this.namedEntitiesParse());
    this.$el.html(html);
    return this;
  },
  namedEntitiesParse: function(){
    var content = this.model.get("content");
    var nes = this.model.get("named_entities");
    for(var i=0; i < nes.length; i++){
      regExp = new RegExp("(" + nes[i].text + ")");
      content = content.replace(regExp, "" + "$1" + "");
    }
    return {_id: this.model._id, content: content};
  },
  selectNamedEntity: function(e){
    alert("named!");
  }
});
var ParagraphListView = Backbone.View.extend({
  el: ".paragraphs",
  className: "paragraphs",
  render: function(){
    this.collection.forEach(this.addOne, this);
    return this;
  },
  addOne: function(paragraph){
    var paragraphView = new ParagraphView({model: paragraph});
    this.$el.append(paragraphView.render().el);
  }
});
var analizer = {
  init: function(){
    this.getTemplates();
  },
  getTemplates: function(){
    this.paragraphTemplate = $('#paragraphTemplate').html();
    this.nextPageTemplate = $("#nextPageTemplate").html();
  },
  addParagraph: function(data){
    var url;
    var nextPageValues;
    var nextPage;
    $(".paragraphs").append(Mustache.render(analizer.paragraphTemplate, data));
    $("#loading").hide();
    console.log(data.last_page);
    if(!data.last_page){
      console.log("entro");
      nextPage = parseInt(data.current_page, 10) + 1;
      url = "/documents/" + data.document_id + "/comb?page=" + nextPage;
      nextPageValues = { url: url, id: data.document_id, 'next_page': data.current_page + 1 };
      $(".next_page").html(Mustache.render(analizer.nextPageTemplate, nextPageValues));
      checkScroll();
    }
  }
};
function nearBottomOfPage() {
  return scrollDistanceFromBottom() < 200;
}
function scrollDistanceFromBottom(argument) {
  return pageHeight() - (window.pageYOffset + self.innerHeight);
}
function pageHeight() {
  return Math.max(document.body.scrollHeight, document.body.offsetHeight);
}
function checkScroll() {
  if (nearBottomOfPage()) {
    callNextPage();
  } else {
    window.setTimeout("checkScroll", 250);
  }
}
function callNextPage(){
  var url = "/api/documents/" + $("#next_page").attr("data-document") + "?page=" + $("#next_page").attr("data-next");
  $("#loading").show();
  $("#next_page").remove();
  $.getJSON(url, analizer.addParagraph);
}
namedEntitiesParser = {
  findMatches: function(cad, nes){
    for(var i=0; i < nes.length; i++){
      regExp = new RegExp("(" + nes[i]+ ")");
      cad = cad.replace(regExp, "" + "$1" + "");
    }
    return cad;
  }
}
var AnalizeApp = new (Backbone.Router.extend({
  initialize: function(){
    var document_id = $("#document_heading").attr("data-document-id");

    this.document = new Document({id: document_id});
    this.document.fetch();
    this.paragraphList = new ParagraphList();
    this.paragraphList.url = "/api/documents/" + document_id + "/";
    this.paragraphList.fetch({data:{page:1}});
    this.paragraphListView = new ParagraphListView({collection: this.paragraphList});
  }
}));
$(document).ready(function(){
  analizer.getTemplates();
  /*checkScroll();*/
  $("#next_page").live("click", function(){
    callNextPage();
    return false;
  });
  $(".people").live("click", function(){
    var $this = $(this);
  });
  /*documentContext = new DocumentContext({model: doc});*/
});

<commit_msg>loading text on the startup<commit_after>var Document = Backbone.Model.extend({
  urlRoot: '/api/documents/',
  initialize: function(){
    this.on("change", function(){

    });
  }
});
var Milestone = Backbone.Model.extend({
});
var Address = Backbone.Model.extend({
});
var Date = Backbone.Model.extend({
});
var Person = Backbone.Model.extend({
  urlRoot: "/api/people/",
  initialize: function(){
    this.on("reset", function(){
        alert("the name has changed");
    });
  }
});
var Paragraph = Backbone.Model.extend({});
var ParagraphList = Backbone.Collection.extend({
  model: Paragraph,
  url: function(){
    return '/api/documents/' + this.get("document_id");
  }
});
var AnalyzerView = Backbone.View.extend({
  el: $("#sidebar"),
  sidebarTemplate: $("#combTemplate").html(),
  events: {
  },
  initialize: function(){
  }
});
var DocumentContext = Backbone.View.extend({
  el: $("#context"),
  documentTemplate: $("#documentContextTemplate").html(),
  initialize: function(){
    this.model.on('change', this.render, this)
  },
  render: function(){
    var html = Mustache.render(this.documentTemplate, this.model.toJSON());
    this.$el.html(html);
    return this;
  }
});
var ParagraphView = Backbone.View.extend({
  events: {
    "click span": "selectNamedEntity"
  },
  className: "paragraph",
  paragraphTemplate: $("#paragraphTemplate").html(),
  render: function(){
    var html = Mustache.render(this.paragraphTemplate, this.namedEntitiesParse());
    this.$el.html(html);
    return this;
  },
  namedEntitiesParse: function(){
    var content = this.model.get("content");
    var nes = this.model.get("named_entities");
    for(var i=0; i < nes.length; i++){
      regExp = new RegExp("(" + nes[i].text + ")");
      content = content.replace(regExp, "" + "$1" + "");
    }
    return {_id: this.model._id, content: content};
  },
  selectNamedEntity: function(e){
    alert("named!");
  }
});
var ParagraphListView = Backbone.View.extend({
  el: ".paragraphs",
  className: "paragraphs",
  events: {
    "scroll": "scrolling"
  },
  scrolling: function(e){
    console.log(e);
  },
  render: function(){
    this.addAll();
    return this;
  },
  addOne: function(paragraph){
    var paragraphView = new ParagraphView({model: paragraph});
    this.$el.append(paragraphView.render().el);
  },
  addAll: function(){
    this.collection.forEach(this.addOne, this);
  },
  initialize: function(){
    this.collection.on("add", this.addOne, this);
    this.collection.on("reset", this.addAll, this);
  }
});
var analizer = {
  init: function(){
    this.getTemplates();
  },
  getTemplates: function(){
    this.paragraphTemplate = $('#paragraphTemplate').html();
    this.nextPageTemplate = $("#nextPageTemplate").html();
  },
  addParagraph: function(data){
    var url;
    var nextPageValues;
    var nextPage;
    $(".paragraphs").append(Mustache.render(analizer.paragraphTemplate, data));
    $("#loading").hide();
    console.log(data.last_page);
    if(!data.last_page){
      console.log("entro");
      nextPage = parseInt(data.current_page, 10) + 1;
      url = "/documents/" + data.document_id + "/comb?page=" + nextPage;
      nextPageValues = { url: url, id: data.document_id, 'next_page': data.current_page + 1 };
      $(".next_page").html(Mustache.render(analizer.nextPageTemplate, nextPageValues));
      checkScroll();
    }
  }
};
function nearBottomOfPage() {
  return scrollDistanceFromBottom() < 200;
}
function scrollDistanceFromBottom(argument) {
  return pageHeight() - (window.pageYOffset + self.innerHeight);
}
function pageHeight() {
  return Math.max(document.body.scrollHeight, document.body.offsetHeight);
}
function checkScroll() {
  if (nearBottomOfPage()) {
    callNextPage();
  } else {
    window.setTimeout("checkScroll", 250);
  }
}
function callNextPage(){
  var url = "/api/documents/" + $("#next_page").attr("data-document") + "?page=" + $("#next_page").attr("data-next");
  $("#loading").show();
  $("#next_page").remove();
  $.getJSON(url, analizer.addParagraph);
}
namedEntitiesParser = {
  findMatches: function(cad, nes){
    for(var i=0; i < nes.length; i++){
      regExp = new RegExp("(" + nes[i]+ ")");
      cad = cad.replace(regExp, "" + "$1" + "");
    }
    return cad;
  }
}
var AnalizeApp = new (Backbone.Router.extend({
  initialize: function(){
    var document_id = $("#document_heading").attr("data-document-id");

    this.document = new Document({id: document_id});
    this.document.fetch();
    this.paragraphList = new ParagraphList();
    this.paragraphList.url = "/api/documents/" + document_id + "/";
    this.paragraphListView = new ParagraphListView({collection: this.paragraphList});
    this.paragraphList.fetch({data:{page:1}});
  }
}));
$(document).ready(function(){
  analizer.getTemplates();
  /*checkScroll();*/
  $("#next_page").live("click", function(){
    callNextPage();
    return false;
  });
  $(".people").live("click", function(){
    var $this = $(this);
  });
  /*documentContext = new DocumentContext({model: doc});*/
});

<|endoftext|>


<commit_before>/**
 * @brief 履歴処理
 */
var gspecv = gspecv || {};

gspecv.history = (function() {
  var selecters;
  var fileName;
  var diffCheckArray = [];

  function setup(selecterObjects) {
    selecters = selecterObjects;
    diffCheckArray = [];

    // 履歴ダイアログにセットアップメソッドを追加
    selecters.$dialog.setup = function(historyInfoArray, isDiffSupport) {
      selecters.$infoTable.empty();

      // 差分に対応したフォーマットの場合は、差分表示を有効にする
      (function() {
        if(isDiffSupport) {
          selecters.$diffButton.removeAttr('disabled');
        } else {
          selecters.$diffButton.attr('disabled', 'disabled');
        }
      })();

      historyInfoArray.forEach(function(historyInfo) {
        // ファイル名を保存しておく
        fileName = historyInfo.name;

        var $checkBox = $('<input type="checkbox">');

        diffCheckArray.push({ $checkBox: $checkBox, version: historyInfo.version });

        var $tableRow = $('
');
        gspecv.util.appendTableRowCell($tableRow,
                                        $checkBox,
                                        $('').text(historyInfo.name),
                                        historyInfo.version,
                                        historyInfo.comment,
                                        historyInfo.user_name,
                                        historyInfo.commit_time);

        selecters.$infoTable.append($tableRow);
      });

      return selecters.$dialog;
    };

    // 差分確認ボタンが押された
    selecters.$diffButton.on('click', function() {
      // チェックが2つ以上あることを確認

      var checkedVersions = _(diffCheckArray)
        .filter(function(diffCheck) {
          return (diffCheck.$checkBox.prop('checked'));
        })
        .pluck('version')
        .value();

      if(checkedVersions.length < 2) {
        alert('差分を確認する2つのバージョンを選んでください');
        return;
      }

      var oldVersion = _.min(checkedVersions);
      var newVersion = _.max(checkedVersions);

      gspecv.util.post(
        'diff',
        {
          file_name: fileName,
          old_version: oldVersion,
          new_version: newVersion
        },
        function(data) {
          selecters.$diffDialog.setup(oldVersion, newVersion, data.old_diff_html, data.new_diff_html, data.diff_info).modal('show');
        }
      );
    });

    // 差分表示ダイアログのセットアップ処理
    selecters.$diffDialog.setup = function(oldVersion, newVersion, oldDiffHtml, newDiffHtml, diffInfo) {
      var $this = $(this);

      $this.find('#left_title').text(fileName + ' v' + oldVersion);
      $this.find('#right_title').text(fileName + ' v' + newVersion);

      var leftViewInfos = getOldDiffInfo(diffInfo);
      var leftHtml = convertViewHtml(oldDiffHtml, leftViewInfos);

      $this.find('#left_iframe')[0].contentDocument.documentElement.innerHTML = leftHtml;
      $this.find('#right_iframe')[0].contentDocument.documentElement.innerHTML = newDiffHtml;

      return this;
    };
  }

  function splitLines(text) {
    return text.split(/\r\n|\r|\n/);
  }

  /**
   * @brief 差分情報から左側の変更情報と範囲を取得する
   */
  function diffInfoLeftRange(diffInfo, typeChar) {
    var diffInfoList = splitLines(diffInfo);
    var result = [];

    // 削除された行情報
    diffInfoList.forEach(function(info) {
      var rangeInfo = new RegExp('([\\d,]+)' + typeChar).exec(info);
      if(!rangeInfo) {
        return;
      }

      var range = rangeInfo[1];
      var multiLineInfo = /(\d+),(\d+)/.exec(range);

      var lineNubers = [];
      if(multiLineInfo) {
        // カンマで区切られているので、複数行とみなす
        var begin = parseInt(multiLineInfo[1]);
        var end = parseInt(multiLineInfo[2]) + 1;
        lineNubers = _.range(begin, end);
      } else {
        // カンマで区切られていないので、1行とみなす
        lineNubers = [parseInt(range)];
      }

      result.push({
        type: typeChar,
        lineNumbers: lineNubers
      });
    });

    return result;
  }

  /**
   * @brief 比較する古いファイルの差分情報を取得する
   */
  function getOldDiffInfo(diffInfo) {
    var deleteLinesInfo = diffInfoLeftRange(diffInfo, 'd');
    var changeLinesInfo = diffInfoLeftRange(diffInfo, 'c');

    return deleteLinesInfo.concat(changeLinesInfo);
  }

  function convertViewHtml(htmlText, viewInfos) {
    var lines = splitLines(htmlText);

    // ヘッダは無視する

    return htmlText;
  }

  return {
    setup: setup
  };
})();

<commit_msg>差分の変更情報を行番号の配列のみで扱うように変更<commit_after>/**
 * @brief 履歴処理
 */
var gspecv = gspecv || {};

gspecv.history = (function() {
  var selecters;
  var fileName;
  var diffCheckArray = [];

  function setup(selecterObjects) {
    selecters = selecterObjects;
    diffCheckArray = [];

    // 履歴ダイアログにセットアップメソッドを追加
    selecters.$dialog.setup = function(historyInfoArray, isDiffSupport) {
      selecters.$infoTable.empty();

      // 差分に対応したフォーマットの場合は、差分表示を有効にする
      (function() {
        if(isDiffSupport) {
          selecters.$diffButton.removeAttr('disabled');
        } else {
          selecters.$diffButton.attr('disabled', 'disabled');
        }
      })();

      historyInfoArray.forEach(function(historyInfo) {
        // ファイル名を保存しておく
        fileName = historyInfo.name;

        var $checkBox = $('<input type="checkbox">');

        diffCheckArray.push({ $checkBox: $checkBox, version: historyInfo.version });

        var $tableRow = $('
');
        gspecv.util.appendTableRowCell($tableRow,
                                        $checkBox,
                                        $('').text(historyInfo.name),
                                        historyInfo.version,
                                        historyInfo.comment,
                                        historyInfo.user_name,
                                        historyInfo.commit_time);

        selecters.$infoTable.append($tableRow);
      });

      return selecters.$dialog;
    };

    // 差分確認ボタンが押された
    selecters.$diffButton.on('click', function() {
      // チェックが2つ以上あることを確認

      var checkedVersions = _(diffCheckArray)
        .filter(function(diffCheck) {
          return (diffCheck.$checkBox.prop('checked'));
        })
        .pluck('version')
        .value();

      if(checkedVersions.length < 2) {
        alert('差分を確認する2つのバージョンを選んでください');
        return;
      }

      var oldVersion = _.min(checkedVersions);
      var newVersion = _.max(checkedVersions);

      gspecv.util.post(
        'diff',
        {
          file_name: fileName,
          old_version: oldVersion,
          new_version: newVersion
        },
        function(data) {
          selecters.$diffDialog.setup(oldVersion, newVersion, data.old_diff_html, data.new_diff_html, data.diff_info).modal('show');
        }
      );
    });

    // 差分表示ダイアログのセットアップ処理
    selecters.$diffDialog.setup = function(oldVersion, newVersion, oldDiffHtml, newDiffHtml, diffInfo) {
      var $this = $(this);

      $this.find('#left_title').text(fileName + ' v' + oldVersion);
      $this.find('#right_title').text(fileName + ' v' + newVersion);

      var leftHtml = convertViewHtml(oldDiffHtml,
                                      diffInfoLeftLineNumbers(diffInfo, 'd'),
                                      diffInfoLeftLineNumbers(diffInfo, 'c'),
                                      []);

      $this.find('#left_iframe')[0].contentDocument.documentElement.innerHTML = leftHtml;
      $this.find('#right_iframe')[0].contentDocument.documentElement.innerHTML = newDiffHtml;

      return this;
    };
  }

  function splitLines(text) {
    return text.split(/\r\n|\r|\n/);
  }

  /**
   * @brief 差分情報から左側の変更行番号を配列として返す
   */
  function diffInfoLeftLineNumbers(diffInfo, typeChar) {
    var diffInfoList = splitLines(diffInfo);
    var result = [];

    // 削除された行情報
    diffInfoList.forEach(function(info) {
      var rangeInfo = new RegExp('([\\d,]+)' + typeChar).exec(info);
      if(!rangeInfo) {
        return;
      }

      var range = rangeInfo[1];
      var multiLineInfo = /(\d+),(\d+)/.exec(range);

      var lineNumbers = [];
      if(multiLineInfo) {
        // カンマで区切られているので、複数行とみなす
        var begin = parseInt(multiLineInfo[1]);
        var end = parseInt(multiLineInfo[2]) + 1;
        result = result.concat(_.range(begin, end));
      } else {
        // カンマで区切られていないので、1行とみなす
        result.push(parseInt(range));
      }
    });

    return result;
  }

  function convertViewHtml(htmlText, deleteLineNumbers, changeLineNumbers, addLineNumbers) {
    var lines = splitLines(htmlText);

    // ヘッダは無視する
    var bodyLineIndex = _.findIndex(lines, function(line) {
      return //.test(line);
    });

    console.log(deleteLineNumbers);
    console.log(changeLineNumbers);
    console.log(addLineNumbers);

    return htmlText;
  }

  return {
    setup: setup
  };
})();

<|endoftext|>


<commit_before>$(function(){
    var objQuery ={
		company: {
				q:"department=&Vendor=&OS=&CPU=&RAM=&group=company&group=&company=",
				type: drawDonut2D
			},
		os:{
			q:"department=&Vendor=&OS=&CPU=&RAM=&group=OS&group=&company=",
			type: drawBar2D
		},
		ram:{
			q:"department=&Vendor=&OS=&CPU=&RAM=&group=RAM&group=&company=",
			type: drawColumn2D
		},
		model:{
			q:"department=&Vendor=&OS=&CPU=&RAM=&group=Model&group=&group=&company=",
			type: drawMultiColum2D
		},
		cpu:{
			q:"department=&Vendor=&OS=&CPU=&RAM=&group=CPU&group=&group=&company=",
			type: drawBar2DTop
		}
	}
	ajaxData(objQuery.company.q, objQuery.company.type);

	$('#select-chart').change(function(){
		var objQ = objQuery[$(this).val()];
		ajaxData(objQ.q+$('#company-chart').val(), objQ.type);
	})
	$('#company-chart').change(function(){
		var objQ = objQuery[$('#select-chart').val()];
		ajaxData(objQ.q+$(this).val(), objQ.type);
	})

	function ajaxData(req, fnDraw){

		$.post('/statistics/', req, function(res){
			var response = JSON.parse(res);
			var data = [];
			response.forEach(function(item){
				var oitem = {
					name: item._id[Object.keys(item._id)[0]],
					value: item.total,
					color: getColor()
				}
				//console.log(oitem)
				data.push(oitem);
			})
			fnDraw(data);
    	})
	}
	function showModal(req){
		$.post('/statistics/', req, function(res){
			$('#chart-table').html('');
            var data = JSON.parse(res);
            //console.log(data)
            if(Object.keys(data[0]._id).length === 0){
                return;
            }else{
				createTable($('#chart-table')[0], data);
				$('#chart-Modal').modal({keyboard: true});
            }
		})
	}
//company
	function drawDonut2D(data){
		var chart = new iChart.Donut2D({
					render : 'canvasDiv',
					data: data,
					title : {
						text : 'Laptop Distribution of Companies',
						color : '#3e576f',
						offsety: -10
					},
					footnote : {
						text : 'Data from ACBSIT Nanjing',
						color : '#486c8f',
						fontsize : 11,
						padding : '0 38',
						offsetx: -50
					},
					center : {
						text:'100%',
						color:'#3e576f',
						shadow:true,
						shadow_blur : 2,
						shadow_color : '#557797',
						shadow_offsetx : 0,
						shadow_offsety : 0,
						fontsize : 40
					},
					sub_option : {
						label : {
							background_color:null,
							sign:false,//设置禁用label的小图标
							padding:'0 4',
							border:{
								enable:false,
								color:'#666666'
							},
							fontsize:11,
							fontweight:600,
							color : '#4572a7'
						},
						border : {
							width : 2,
							color : '#ffffff'
						}
					},
					shadow : true,
					shadow_blur : 6,
					shadow_color : '#aaaaaa',
					shadow_offsetx : 0,
					shadow_offsety : 0,
					background_color:'#fefefe',
					offset_angle:-120,//逆时针偏移120度
					showpercent:true,
					decimalsnum:2,
					width : 1400,
					height : 400,
					radius:120
				});

				chart.draw();
	}
//os
	function drawBar2D(data){

				new iChart.Bar2D({
						render : 'canvasDiv',
						data: data,
						title : 'Quantity between OSs',
						footnote : 'Data from ACBSIT Nanjing',
						width : 1400,
						height : 400,
						animation : true,//开启过渡动画
						animation_duration:800,//800ms完成动画
						coordinate:{
							width:740,
							height:380,
							scale:[{
									position:'bottom',
									start_scale:0,
									scale_space:40,
									listeners:{
									parseText:function(t,x,y){
										return {text:t+" pcs"}
									}
									}
							}]
						},
						rectangle:{
							listeners:{
								drawText:function(r,t){
									return t+"%";
								}
							}
						},
						sub_option:{
							listeners:{
								/**
								 * r:iChart.Rectangle2D对象
								 * e:eventObject对象
								 * m:额外参数
								 */
								click:function(r,e,m){
									var q = "department=&Vendor=&OS="+r.get('name')+"&CPU=&RAM=&group=department&group=ComputerName&group=displayName&company="
									$('#myModalLabel').text(r.get('name'));
									showModal(q);
									//alert(r.get('name')+' '+r.get('value'));
								}
							}
						}

				}).draw();

	}
//ram
	function drawColumn2D(data){

		data.sort(function(a,b){return parseInt(a.name) - parseInt(b.name)});
		var chart = new iChart.Column2D({
			render : 'canvasDiv',//渲染的Dom目标,canvasDiv为Dom的ID
			data: data,//绑定数据
			title : 'Quantity between RAMs',//设置标题
			footnote : {
						text : 'Data from ACBSIT Nanjing',
						color : '#486c8f',
						fontsize : 11,
						padding : '0 38',
						offsetx: 50,
					},
			width : 1400,//设置宽度，默认单位为px
			height : 400,//设置高度，默认单位为px
			animation : true,//开启过渡动画
			animation_duration:800,//800ms完成动画
			shadow:true,//激活阴影
			shadow_color:'#c7c7c7',//设置阴影颜色
			column_space: 10,
			column_width : 70,
			coordinate:{//配置自定义坐标轴
				scale:[{//配置自定义值轴
						position:'left',//配置左值轴
						start_scale:0,//设置开始刻度为0
						scale_space:20,//设置刻度间距
						listeners:{//配置事件
						parseText:function(t,x,y){//设置解析值轴文本
							return {text:t+" pcs"}
						}
					}
				}]
			},
			sub_option:{
				listeners:{
					/**
					 * r:iChart.Rectangle2D对象
					 * e:eventObject对象
					 * m:额外参数
					 */
					click:function(r,e,m){
						var q = "department=&Vendor=&OS=&CPU=&RAM="+r.get('name')+"&group=department&group=ComputerName&group=displayName&company="
						$('#myModalLabel').text(r.get('name'));
						showModal(q);
						//alert(r.get('name')+' '+r.get('value'));
					}
				}
			}
		});
		//调用绘图方法开始绘图
		chart.draw();

	}
//model
	function drawMultiColum2D(data){
		data.sort(function(a,b){return b.value - a.value});
		var chart = new iChart.Column2D({
				render : 'canvasDiv',
				data : data,
				title : {
					text : 'Quantity between Models',
					color : '#3e576f'
				},
				footnote : {
					text : 'Data from ACBSIT Nanjing',
					color : '#909090',
					fontsize : 11,
					offsety: -100,
					offsetx: -50
				},
				width : 1400,
				height : 650,
				offsety: -100,
				label : {
					fontsize:11,
					textAlign:'right',
					textBaseline:'middle',
					rotate:-45,
					color : '#666666'
				},
				tip:{
					enable:true,
					listeners:{
						 //tip:提示框对象、name:数据名称、value:数据值、text:当前文本、i:数据点的索引
						parseText:function(tip,name,value,text,i){
							//将数字进行百位格式化
							var f = new String(value);
							f = f.split("").reverse().join("").replace(/(\d{3})/g,"$1,").split("").reverse();
							if(f[0]==','){
								f.shift();
							}
							f = f.join("");

							return name+"
"+f+"pcs
proportion of the total:
"+(value/this.get('total') * 100).toFixed(2)+ '%';
						}
					}
				},
				animation : true,//开启过渡动画
				animation_duration:800,//800ms完成动画
				shadow : true,
				shadow_blur : 2,
				shadow_color : '#aaaaaa',
				shadow_offsetx : 1,
				shadow_offsety : 0,
				column_space: 5,
				column_width : 100,
				sub_option : {
					label : false,
					border : {
						width : 2,
						color : '#ffffff'
					},
					listeners:{
					/**
					 * r:iChart.Rectangle2D对象
					 * e:eventObject对象
					 * m:额外参数
					 */
					click:function(r,e,m){
						var q = "department=&Vendor=&OS=&CPU=&Model="+r.get('name')+"&group=department&group=ComputerName&group=displayName&company="
						$('#myModalLabel').text(r.get('name'));
						showModal(q);
						//alert(r.get('name')+' '+r.get('value'));
					}
				}
				},
				coordinate : {
					background_color : null,
					grid_color : '#c0c0c0',
					width : 960,
					height:300,
					axis : {
						color : '#c0d0e0',
						width : [0, 0, 1, 0]
					},
					scale : [{
						position : 'left',
						start_scale : 0,
						scale_space : 5,
						scale_width: 9,
						scale_enable : false,
						label : {
							fontsize:11,
							color : '#666666'
						},
						listeners:{
							parseText:function(t,x,y){
								return {text:t}
							}
						 }
					}]
				}
			});

			//利用自定义组件构造左侧说明文本
			chart.plugin(new iChart.Custom({
					drawFn:function(){
						//计算位置
						var coo = chart.getCoordinate(),
							x = coo.get('originx'),
							y = coo.get('originy');
						//在左上侧的位置，渲染一个单位的文字
						chart.target.textAlign('start')
						.textBaseline('bottom')
						.textFont('600 11px Verdana')
						.fillText('Quantity(pcs)',x-40,y-10,false,'#6d869f');

					}
			}));

			chart.draw();
	}
//cpu
	function drawBar2DTop(data){
		data.sort(function(a,b){return b.value - a.value});
		data = data.slice(0,10);
		new iChart.Bar2D({
			render : 'canvasDiv',
			background_color : '#EEEEEE',
			data : data,
			title : 'CPU TOP10',
			footnote : 'Data from ACBSIT Nanjing',
			width : 1400,
			height : 450,
			coordinate : {
				width : 840,
				height : 360,
				axis : {
					width : [0, 0, 1, 1]
				},
				scale : [{
					position : 'bottom',
					start_scale : 0,
					scale_space : 2
				}]
			},
			animation : true,
			sub_option : {
				listeners : {
					parseText : function(r, t) {
						return t + " pcs";
					},
					click:function(r,e,m){
						var q = "department=&Vendor=&OS=&CPU="+r.get('name')+"&RAM=&group=department&group=ComputerName&group=displayName&company="
						$('#myModalLabel').text(r.get('name'));
						showModal(q);
						//alert(r.get('name')+' '+r.get('value'));
					}
				},
			},
			legend : {
				enable : false
			}
		}).draw();

	}

    function getColor(){
        var arrColor = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'];
        var sColor = '#';
        [1,1,1].forEach(function(v,k){
            sColor += arrColor[parseInt(Math.random()*15)];
        })
        return sColor;
    }

});<commit_msg>fix show modal when company selected<commit_after>$(function(){
    var objQuery ={
		company: {
				q:"department=&Vendor=&OS=&CPU=&RAM=&group=company&group=&company=",
				type: drawDonut2D
			},
		os:{
			q:"department=&Vendor=&OS=&CPU=&RAM=&group=OS&group=&company=",
			type: drawBar2D
		},
		ram:{
			q:"department=&Vendor=&OS=&CPU=&RAM=&group=RAM&group=&company=",
			type: drawColumn2D
		},
		model:{
			q:"department=&Vendor=&OS=&CPU=&RAM=&group=Model&group=&group=&company=",
			type: drawMultiColum2D
		},
		cpu:{
			q:"department=&Vendor=&OS=&CPU=&RAM=&group=CPU&group=&group=&company=",
			type: drawBar2DTop
		}
	}
	ajaxData(objQuery.company.q, objQuery.company.type);

	$('#select-chart').change(function(){
		var objQ = objQuery[$(this).val()];
		ajaxData(objQ.q+$('#company-chart').val(), objQ.type);
	})
	$('#company-chart').change(function(){
		var objQ = objQuery[$('#select-chart').val()];
		ajaxData(objQ.q+$(this).val(), objQ.type);
	})

	function ajaxData(req, fnDraw){

		$.post('/statistics/', req, function(res){
			var response = JSON.parse(res);
			var data = [];
			response.forEach(function(item){
				var oitem = {
					name: item._id[Object.keys(item._id)[0]],
					value: item.total,
					color: getColor()
				}
				//console.log(oitem)
				data.push(oitem);
			})
			fnDraw(data);
    	})
	}
	function showModal(req){
		$.post('/statistics/', req, function(res){
			$('#chart-table').html('');
            var data = JSON.parse(res);
            //console.log(data)
            if(Object.keys(data[0]._id).length === 0){
                return;
            }else{
				createTable($('#chart-table')[0], data);
				$('#chart-Modal').modal({keyboard: true});
            }
		})
	}
//company
	function drawDonut2D(data){
		var chart = new iChart.Donut2D({
					render : 'canvasDiv',
					data: data,
					title : {
						text : 'Laptop Distribution of Companies',
						color : '#3e576f',
						offsety: -10
					},
					footnote : {
						text : 'Data from ACBSIT Nanjing',
						color : '#486c8f',
						fontsize : 11,
						padding : '0 38',
						offsetx: -50
					},
					center : {
						text:'100%',
						color:'#3e576f',
						shadow:true,
						shadow_blur : 2,
						shadow_color : '#557797',
						shadow_offsetx : 0,
						shadow_offsety : 0,
						fontsize : 40
					},
					sub_option : {
						label : {
							background_color:null,
							sign:false,//设置禁用label的小图标
							padding:'0 4',
							border:{
								enable:false,
								color:'#666666'
							},
							fontsize:11,
							fontweight:600,
							color : '#4572a7'
						},
						border : {
							width : 2,
							color : '#ffffff'
						}
					},
					shadow : true,
					shadow_blur : 6,
					shadow_color : '#aaaaaa',
					shadow_offsetx : 0,
					shadow_offsety : 0,
					background_color:'#fefefe',
					offset_angle:-120,//逆时针偏移120度
					showpercent:true,
					decimalsnum:2,
					width : 1400,
					height : 400,
					radius:120
				});

				chart.draw();
	}
//os
	function drawBar2D(data){

				new iChart.Bar2D({
						render : 'canvasDiv',
						data: data,
						title : 'Quantity between OSs',
						footnote : 'Data from ACBSIT Nanjing',
						width : 1400,
						height : 400,
						animation : true,//开启过渡动画
						animation_duration:800,//800ms完成动画
						coordinate:{
							width:740,
							height:380,
							scale:[{
									position:'bottom',
									start_scale:0,
									scale_space:40,
									listeners:{
									parseText:function(t,x,y){
										return {text:t+" pcs"}
									}
									}
							}]
						},
						rectangle:{
							listeners:{
								drawText:function(r,t){
									return t+"%";
								}
							}
						},
						sub_option:{
							listeners:{
								/**
								 * r:iChart.Rectangle2D对象
								 * e:eventObject对象
								 * m:额外参数
								 */
								click:function(r,e,m){
									var q = "department=&Vendor=&OS="+r.get('name')+"&CPU=&RAM=&group=department&group=ComputerName&group=displayName&company="+$('#company-chart').val();
									$('#myModalLabel').text(r.get('name'));
									showModal(q);
									//alert(r.get('name')+' '+r.get('value'));
								}
							}
						}

				}).draw();

	}
//ram
	function drawColumn2D(data){

		data.sort(function(a,b){return parseInt(a.name) - parseInt(b.name)});
		var chart = new iChart.Column2D({
			render : 'canvasDiv',//渲染的Dom目标,canvasDiv为Dom的ID
			data: data,//绑定数据
			title : 'Quantity between RAMs',//设置标题
			footnote : {
						text : 'Data from ACBSIT Nanjing',
						color : '#486c8f',
						fontsize : 11,
						padding : '0 38',
						offsetx: 50,
					},
			width : 1400,//设置宽度，默认单位为px
			height : 400,//设置高度，默认单位为px
			animation : true,//开启过渡动画
			animation_duration:800,//800ms完成动画
			shadow:true,//激活阴影
			shadow_color:'#c7c7c7',//设置阴影颜色
			column_space: 10,
			column_width : 70,
			coordinate:{//配置自定义坐标轴
				scale:[{//配置自定义值轴
						position:'left',//配置左值轴
						start_scale:0,//设置开始刻度为0
						scale_space:20,//设置刻度间距
						listeners:{//配置事件
						parseText:function(t,x,y){//设置解析值轴文本
							return {text:t+" pcs"}
						}
					}
				}]
			},
			sub_option:{
				listeners:{
					/**
					 * r:iChart.Rectangle2D对象
					 * e:eventObject对象
					 * m:额外参数
					 */
					click:function(r,e,m){
						var q = "department=&Vendor=&OS=&CPU=&RAM="+r.get('name')+"&group=department&group=ComputerName&group=displayName&company="+$('#company-chart').val();
						$('#myModalLabel').text(r.get('name'));
						showModal(q);
						//alert(r.get('name')+' '+r.get('value'));
					}
				}
			}
		});
		//调用绘图方法开始绘图
		chart.draw();

	}
//model
	function drawMultiColum2D(data){
		data.sort(function(a,b){return b.value - a.value});
		var chart = new iChart.Column2D({
				render : 'canvasDiv',
				data : data,
				title : {
					text : 'Quantity between Models',
					color : '#3e576f'
				},
				footnote : {
					text : 'Data from ACBSIT Nanjing',
					color : '#909090',
					fontsize : 11,
					offsety: -100,
					offsetx: -50
				},
				width : 1400,
				height : 650,
				offsety: -100,
				label : {
					fontsize:11,
					textAlign:'right',
					textBaseline:'middle',
					rotate:-45,
					color : '#666666'
				},
				tip:{
					enable:true,
					listeners:{
						 //tip:提示框对象、name:数据名称、value:数据值、text:当前文本、i:数据点的索引
						parseText:function(tip,name,value,text,i){
							//将数字进行百位格式化
							var f = new String(value);
							f = f.split("").reverse().join("").replace(/(\d{3})/g,"$1,").split("").reverse();
							if(f[0]==','){
								f.shift();
							}
							f = f.join("");

							return name+"
"+f+"pcs
proportion of the total:
"+(value/this.get('total') * 100).toFixed(2)+ '%';
						}
					}
				},
				animation : true,//开启过渡动画
				animation_duration:800,//800ms完成动画
				shadow : true,
				shadow_blur : 2,
				shadow_color : '#aaaaaa',
				shadow_offsetx : 1,
				shadow_offsety : 0,
				column_space: 5,
				column_width : 100,
				sub_option : {
					label : false,
					border : {
						width : 2,
						color : '#ffffff'
					},
					listeners:{
					/**
					 * r:iChart.Rectangle2D对象
					 * e:eventObject对象
					 * m:额外参数
					 */
					click:function(r,e,m){
						var q = "department=&Vendor=&OS=&CPU=&Model="+r.get('name')+"&group=department&group=ComputerName&group=displayName&company="+$('#company-chart').val();
						$('#myModalLabel').text(r.get('name'));
						showModal(q);
						//alert(r.get('name')+' '+r.get('value'));
					}
				}
				},
				coordinate : {
					background_color : null,
					grid_color : '#c0c0c0',
					width : 960,
					height:300,
					axis : {
						color : '#c0d0e0',
						width : [0, 0, 1, 0]
					},
					scale : [{
						position : 'left',
						start_scale : 0,
						scale_space : 5,
						scale_width: 9,
						scale_enable : false,
						label : {
							fontsize:11,
							color : '#666666'
						},
						listeners:{
							parseText:function(t,x,y){
								return {text:t}
							}
						 }
					}]
				}
			});

			//利用自定义组件构造左侧说明文本
			chart.plugin(new iChart.Custom({
					drawFn:function(){
						//计算位置
						var coo = chart.getCoordinate(),
							x = coo.get('originx'),
							y = coo.get('originy');
						//在左上侧的位置，渲染一个单位的文字
						chart.target.textAlign('start')
						.textBaseline('bottom')
						.textFont('600 11px Verdana')
						.fillText('Quantity(pcs)',x-40,y-10,false,'#6d869f');

					}
			}));

			chart.draw();
	}
//cpu
	function drawBar2DTop(data){
		data.sort(function(a,b){return b.value - a.value});
		data = data.slice(0,10);
		new iChart.Bar2D({
			render : 'canvasDiv',
			background_color : '#EEEEEE',
			data : data,
			title : 'CPU TOP10',
			footnote : 'Data from ACBSIT Nanjing',
			width : 1400,
			height : 450,
			coordinate : {
				width : 840,
				height : 360,
				axis : {
					width : [0, 0, 1, 1]
				},
				scale : [{
					position : 'bottom',
					start_scale : 0,
					scale_space : 2
				}]
			},
			animation : true,
			sub_option : {
				listeners : {
					parseText : function(r, t) {
						return t + " pcs";
					},
					click:function(r,e,m){
						var q = "department=&Vendor=&OS=&CPU="+r.get('name')+"&RAM=&group=department&group=ComputerName&group=displayName&company="+$('#company-chart').val();
						$('#myModalLabel').text(r.get('name'));
						showModal(q);
						//alert(r.get('name')+' '+r.get('value'));
					}
				},
			},
			legend : {
				enable : false
			}
		}).draw();

	}

    function getColor(){
        var arrColor = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'];
        var sColor = '#';
        [1,1,1].forEach(function(v,k){
            sColor += arrColor[parseInt(Math.random()*15)];
        })
        return sColor;
    }

});<|endoftext|>


<commit_before>function getLTK(){

	var result;
	var table = {};
	table = "LTK";
	processData(table);
	result = LTK(getFDNumber(table),table);
	//$('#output-algo').html(result);
	//document.getElementById('result_output').value = result;
	makeTable(result);

}

function getBCNFDecomposition(){

	var result;
	var table = {};
	table = "Decomposition";
	processData(table);
	result = BCNFDecomposition(getFDNumber(table),table);
	//$('#output-algo').html(result);
	makeTable(result);

	//document.getElementById('result_output').value = result;

}

function processData(table){
	clearCookie();

	var attributeInputArr = getAttributInput();
	console.log(attributeInputArr);
	for(var i = 0 ;i < attributeInputArr.length; i++){
		if(attributeInputArr[i] != ""){
		   addAttribute(table, attributeInputArr[i]);
	    }
	}

	var fdInputArr = getFDInput();
	console.log(fdInputArr);
	for(var i = 0 ;i < fdInputArr.length ; i++){
		if(fdInputArr[i] != ""){
		   var tempFD = fdInputArr[i];
		   tempFD = tempFD.trim();
		   tempFD = tempFD.replace(/^\{|\}$/g,"");

		   console.log(tempFD);
		   var leftbreakIndex = tempFD.indexOf("-");
		   var rightStartIndex = leftbreakIndex + 2;

		   var left = tempFD.substring(0, leftbreakIndex);
		   var right = tempFD.substring(rightStartIndex);
		   console.log(left);
		   console.log(right);
		   insertFD(table, left, right , 0);
		}
	}

}

function getAttributInput(){
	var attributeInput = $('#variable_output').val();
	attributeInput = attributeInput.trim();
	var attributeInputArr = attributeInput.split(",");
	return attributeInputArr;
}
function getFDInput(){
	var fdInput = $('#relation_output').val();
    fdInput = fdInput.trim();
    console.log (fdInput);
    var fdInputArr = fdInput.split(";");
    return fdInputArr;

}
function makeTable(inputData){
	var currentTable = document.createElement("table");

	//
	currentTable.setAttribute("border","2");

	var inputDataArr = inputData.split(";");
	console.log(inputDataArr);
	for(var i = 0; i < inputDataArr.length; i++){
		if(inputDataArr[i] != ""){
			console.log(inputDataArr[i]);
			var currentRow = document.createElement("tr");

			var inputStr = inputDataArr[i];
			var relationLeftBreak = inputStr.indexOf('{');
			var relationRightBreak = inputStr.indexOf('}');
			var fdInput = inputStr.substring(relationLeftBreak+1, relationRightBreak);
			fdInput = fdInput.trim();
			var fdInputArr = fdInput.split(",");
			for( var j = 0; j < fdInputArr.length; j++){
				if(fdInputArr[j] != ""){
				    var currentCol = document.createElement("td");
				    currentCol.innerText = fdInputArr[j];
				    currentRow.appendChild(currentCol);
			    }
			}
		}
		currentTable.appendChild(currentRow);
	}

	// var keyLeftBreak = inputStr.indexOf('(');
	// var keyRightBreak = inputStr.indexOf(')');
	// var keyInput = inputStr.substring(keyLeftBreak+1, keyRightBreak);
	// var realKeyLeftBreak = keyInput.indexOf(':');
	// var realKeyInput = keyInput.substring(realKeyLeftBreak+1);

	var currentOutput = document.getElementById("output-result-div");
	clearChildren(currentOutput);
	currentOutput.appendChild(currentTable);

}

function clearChildren(node){
	while (node.hasChildNodes()) {
          node.removeChild(node.lastChild);
      }
}

function clearCookie(){
	attribute_JSON = {"attribute": [
        {"table":"test1", "name": "test1"}
      ]
    };

    fd_JSON = {"fd": [
        {"table":"test1", "left": "", "right": "", "type": ""}
      ]
    };
}<commit_msg>fixes the bug with bernstein not working with no fds<commit_after>function getLTK(){

	var result;
	var table = {};
	table = "LTK";
	processData(table);
	result = LTK(getFDNumber(table),table);
	//$('#output-algo').html(result);
	//document.getElementById('result_output').value = result;
	makeTable(result);

}

function getBCNFDecomposition(){

	var result;
	var table = {};
	table = "Decomposition";
	processData(table);
	result = BCNFDecomposition(getFDNumber(table),table);
	//$('#output-algo').html(result);
	makeTable(result);

	//document.getElementById('result_output').value = result;

}

function processData(table){
	clearCookie();

	var attributeInputArr = getAttributInput();
	console.log(attributeInputArr);
	for(var i = 0 ;i < attributeInputArr.length; i++){
		if(attributeInputArr[i] != ""){
		   addAttribute(table, attributeInputArr[i]);
	    }
	}

	var fdInputArr = getFDInput();
	console.log(fdInputArr);
	for(var i = 0 ;i < fdInputArr.length ; i++){
		if(fdInputArr[i] != ""){
		   var tempFD = fdInputArr[i];
		   tempFD = tempFD.trim();
		   tempFD = tempFD.replace(/^\{|\}$/g,"");

		   console.log(tempFD);
		   var leftbreakIndex = tempFD.indexOf("-");
		   var rightStartIndex = leftbreakIndex + 2;

		   var left = tempFD.substring(0, leftbreakIndex);
		   var right = tempFD.substring(rightStartIndex);
		   console.log(left);
		   console.log(right);
		   insertFD(table, left, right , 0);
		}
	}

}

function getAttributInput(){
	var attributeInput = $('#variable_output').val();
	attributeInput = attributeInput.trim();
	var attributeInputArr = attributeInput.split(",");
	return attributeInputArr;
}
function getFDInput(){
	var fdInput = $('#relation_output').val();
    fdInput = fdInput.trim();
    console.log (fdInput);
    var fdInputArr = fdInput.split(";");
    return fdInputArr;

}
function makeTable(inputData){
	var currentTable = document.createElement("table");
	var currentRow, inputStr, relationLeftBreak, relationRightBreak, fdInput, fdInputArr;

	currentTable.setAttribute("border","2");
	var inputDataArr = inputData.split(";");
	for(var i = 0; i < inputDataArr.length; i++){
		if(inputDataArr[i] != ""){
			currentRow = document.createElement("tr");
			inputStr = inputDataArr[i];
			relationLeftBreak = inputStr.indexOf('{');
			relationRightBreak = inputStr.indexOf('}');
			fdInput = inputStr.substring(relationLeftBreak+1, relationRightBreak);
			fdInput = fdInput.trim();
			fdInputArr = fdInput.split(",");
			for( var j = 0; j < fdInputArr.length; j++){
				if(fdInputArr[j] != ""){
				    var currentCol = document.createElement("td");
				    currentCol.innerText = fdInputArr[j];
				    currentRow.appendChild(currentCol);
			    }
			}
		}
		if (currentRow) {
			currentTable.appendChild(currentRow);
		}
		currentRow = undefined;
	}

	var currentOutput = document.getElementById("output-result-div");
	clearChildren(currentOutput);
	currentOutput.appendChild(currentTable);
}

function clearChildren(node){
	while (node.hasChildNodes()) {
    node.removeChild(node.lastChild);
  }
}

function clearCookie(){
	attribute_JSON = {"attribute": [
        {"table":"test1", "name": "test1"}
      ]
    };

    fd_JSON = {"fd": [
        {"table":"test1", "left": "", "right": "", "type": ""}
      ]
    };
}
<|endoftext|>


<commit_before>define(["jquery", "backbone"],
    function($, Backbone) {
        // Creates a new Backbone Model class object
        var Model = Backbone.Model.extend({

            // Model Constructor
            initialize: function() {

            },

            // Default values for all of the Model attributes
            defaults: {

            },

            // Get's called automatically by Backbone when the set and/or save methods are called (Add your own logic)
            validate: function(attrs) {

            }

        });

        // Returns the Model class
        return Model;

    }

);<commit_msg>Simplifying<commit_after>define(["jquery", "backbone"],
    function ($, Backbone) {
        // Creates a new Backbone Model class object
        var Model = Backbone.Model.extend({
            initialize:function () {

            },

            // Default values for all of the Model attributes
            defaults:{

            },

            // Get's called automatically by Backbone when the set and/or save methods are called (Add your own logic)
            validate:function (attrs) {

            }
        });

        return Model;
    }
);<|endoftext|>


<commit_before>angular.module('domegis')

.directive('derivedItem', [
  'Server',
  function(Server) {
    return {
      restrict: 'A',
      scope: {
        'layer': '=derivedItem',
      },
      templateUrl: '/views/layer/derived-item.html',
      link: function(scope, element, attrs) {

      }
    }
  }
])

.directive('layerItem', [
  'Server',
  function(Server) {
    return {
      restrict: 'A',
      scope: {
        'layer': '=layerItem'
      },
      templateUrl: '/views/layer/item.html',
      link: function(scope, element, attrs) {

        var layerService = Server.service('layers');
        var viewService = Server.service('views');

        scope.token = Server.app.get('token');

        Server.find(viewService, {
          query: {
            layerId: scope.layer.id
          }
        }).then(function(res) {
          scope.views = res.data;
        });

        Server.on(layerService, 'syncFinish', function(layerId) {
          if(scope.layer.id == layerId) {
            Server.get(layerService, layerId).then(function(data) {
              scope.layer = data;
            })
          }
        });
        Server.on(layerService, 'syncProgress', function(prog) {
          if(scope.layer.id == prog.layerId) {
            if(prog.progress == 1)
              scope.progress = '99%';
            else
              scope.progress = parseInt(prog.progress * 100) + '%';
          }
        });
        Server.on(layerService, 'updated', function(data) {
          if(scope.layer.id == data.id) {
            console.log('updated');
            scope.layer = data;
          }
        });
        Server.on(layerService, 'patched', function(data) {
          if(scope.layer.id == data.id) {
            console.log('patched');
            scope.layer = data;
          }
        });
        Server.on(viewService, 'created', function(data) {
          if(data.layerId == scope.layer.id)
            scope.views.push(data);
        });
        Server.on(viewService, 'removed', function(data) {
          scope.views = _.filter(scope.views, function(item) {
            return item.id !== data.id;
          });
        });

        scope.resync = function() {
          console.log('resyncing');
          Server.patch(layerService, scope.layer.id, {
            resync: true
          }).then(function() {
            console.log('patched', arguments);
          }, function() {
            console.log('path err', arguments);
          });
        };

        scope.remove = function(layer) {
          Server.remove(layerService, layer.id);
        };
      }
    }
  }
]);
<commit_msg>better debug for layer patch<commit_after>angular.module('domegis')

.directive('derivedItem', [
  'Server',
  function(Server) {
    return {
      restrict: 'A',
      scope: {
        'layer': '=derivedItem',
      },
      templateUrl: '/views/layer/derived-item.html',
      link: function(scope, element, attrs) {

      }
    }
  }
])

.directive('layerItem', [
  'Server',
  function(Server) {
    return {
      restrict: 'A',
      scope: {
        'layer': '=layerItem'
      },
      templateUrl: '/views/layer/item.html',
      link: function(scope, element, attrs) {

        var layerService = Server.service('layers');
        var viewService = Server.service('views');

        scope.token = Server.app.get('token');

        Server.find(viewService, {
          query: {
            layerId: scope.layer.id
          }
        }).then(function(res) {
          scope.views = res.data;
        });

        Server.on(layerService, 'syncFinish', function(layerId) {
          if(scope.layer.id == layerId) {
            Server.get(layerService, layerId).then(function(data) {
              scope.layer = data;
            })
          }
        });
        Server.on(layerService, 'syncProgress', function(prog) {
          if(scope.layer.id == prog.layerId) {
            if(prog.progress == 1)
              scope.progress = '99%';
            else
              scope.progress = parseInt(prog.progress * 100) + '%';
          }
        });
        Server.on(layerService, 'updated', function(data) {
          if(scope.layer.id == data.id) {
            console.log('updated');
            scope.layer = data;
          }
        });
        Server.on(layerService, 'patched', function(data) {
          console.log('patched', data.id, data.sync.status);
          if(scope.layer.id == data.id) {
            scope.layer = data;
          }
        });
        Server.on(viewService, 'created', function(data) {
          if(data.layerId == scope.layer.id)
            scope.views.push(data);
        });
        Server.on(viewService, 'removed', function(data) {
          scope.views = _.filter(scope.views, function(item) {
            return item.id !== data.id;
          });
        });

        scope.resync = function() {
          console.log('resyncing');
          Server.patch(layerService, scope.layer.id, {
            resync: true
          }).then(function() {
            console.log('patched', arguments);
          }, function() {
            console.log('path err', arguments);
          });
        };

        scope.remove = function(layer) {
          Server.remove(layerService, layer.id);
        };
      }
    }
  }
]);
<|endoftext|>


<commit_before>// TODO: I've used many ..Sync functions for simplicity, they must go
// TODO: why does .toFixed return a string?

var async = require('async'),
	_ = require('underscore'),
	fs = require('fs-extra')
	path = require('path'),
	argv = require('yargs')
		.demand([ 'oa', 'onspd', 'deviation', 'sample' ])
		// The default max deviation between the course and the surrounding
		// postcode centroids is 50 yards (~46 meters). The smaller this value,
		// the less we are diverting the runner from her course to check an
		// address.
		.default('deviation', 50.) // yards
		// The default course sample is 220 yards. On a ~3 miles run this
		// filters the course from a few thousands down to about 25 points.
		// The combination of 50 yards distance and 220 yards sample identifies
		// 23 candidate postcodes on @giacecco's standard hometown run
		// (e.g. http://dico.im/145XqiJ ).
		.default('sample', 220.) // yards
		.check(function (argv) {
			var ok = !argv.fit || (argv.fit && argv.fitsdk) || false;
			if (!ok) throw new Error('If specifying --fit, the location of the Fit SDK must be specified, too, using --fitsdk.');
		})
		.check(function (argv) {
			var ok = (!argv.lat && !argv.lon && !argv.distance) || (argv.lat && argv.lon && argv.distance) || false;
			if (!ok) throw new Error("The --lat, --lon and --distance parameters must be specified together.");
		})
		.check(function (argv) {
			var ok = argv.fit || argv.lat || false;
			if (!ok) throw new Error("You must either specify the starting position (--lat, --lon and --distance) or the preferred course (--fit).");
		})
		.argv,
	onspdReader = new require('./lib/onspd-reader')(argv.onspd),
	oaReader = new require('./lib/oa-reader')(argv.oa),
	inferenceEngine = new require('./lib/toy-inference.js')();

// This test script identifies the addresses known to Open Addresses that are
// closer to the middle of the course
var generateInvestigationOptions = function (coursePostcodes, callback) {
	// the ideal postcode to be investigated is in the middle of the course; in
	// a way the entire course can be seen as a run to the postcode to be
	// investigated and back
	var idealCoursePostcodeDistance = Math.max.apply(null, coursePostcodes.map(function (p) { return p.closestPoint.distance; })) / 2.;
	async.reduce(coursePostcodes, [ ], function (memo, coursePostcode, callback) {
		// I fetch all addresses OA knows in that postcode
		oaReader.readOaAddressesByPostcode(coursePostcode.pcd, function (err, addresses) {
			if (addresses.length === 0) {
				callback(null, memo);
			} else {
				callback(null, memo.concat({
					'postcode': coursePostcode,
					'relevantOaAddresses': addresses,
				}));
			}
		});
	}, function (err, candidateInvestigations) {
		callback(err, candidateInvestigations.sort(function (a, b) {
			// I sort candidate investigations by how close they are to that ideal
			// distance
			return Math.abs(a.postcode.closestPoint.distance - idealCoursePostcodeDistance) - Math.abs(b.postcode.closestPoint.distance - idealCoursePostcodeDistance);
		}));
	});
};

var stage2 = function (points, latLonFunction, minDistanceKm, maxDistanceKm) {
	onspdReader.fetchNearbyPostcodes(
		points,
		{
			'latLonFunction': latLonFunction,
		  	'minDistanceKm': minDistanceKm,
		  	'maxDistanceKm': maxDistanceKm,
		},
		function (err, coursePostcodes) {
			generateInvestigationOptions(coursePostcodes, function (err, investigationOptions) {
				async.each(investigationOptions, function (o, callback) {
					inferenceEngine.doTheInferenceMagic(o.relevantOaAddresses, function (err, inferredAddresses) {
						o.inferredAddresses = inferredAddresses;
						callback(null);
					});
				}, function (err) {
					console.log(JSON.stringify(investigationOptions));
				});
			});
		});
}

var stage1 = function () {
	if (argv.fit) {
		// the user has requested to find survey options around a.fit course
		var fitReader = new require('./lib/fit-reader')(argv.fitsdk);
		fitReader.fetchCourse(argv.fit, parseFloat(argv.sample) * 0.9144, function (err, points) {
			stage2(
				points,
				function (point) { return point.position; },
				0.,
				parseFloat(argv.deviation) * 0.0009144
			);
		});
	} else if (argv.lat && argv.lon && argv.distance) {
		// the user has requested to find survey options at a given distance
		// from a starting point
		eval(fs.readFileSync(path.join(__dirname, 'lib', 'latlon.js')) + '');
		// Note the calculation below. I need to transform the target return
		// run length into an 'as the crow flies' ray, in order to find the
		// target postcodes. As this is supposed to be an 'urban run', I presume
		// that they ray is the hypotenuse of a right angle and the sum of the
		// two sides is what the runner will actually have to run, twice (to and
		// back).
		var searchAreaRayKm = Math.sqrt((parseFloat(argv.distance) * 1.609344 / 2 / 2) ^ 2 * 2);
		stage2(
			[ new LatLon(parseFloat(argv.lat), parseFloat(argv.lon)) ],
			function (point) { return point; },
			searchAreaRayKm - parseFloat(argv.deviation) * 0.0009144,
			searchAreaRayKm + parseFloat(argv.deviation) * 0.0009144
		);
	} else {
		// you should never get here thanks to the yargs checks
	}
}

// home is LatLon(51.759467, -0.577358);
// Berkhamsted station is LatLon(51.764541, -0.562041);
stage1();
<commit_msg>Drops from the results postcodes for which no addresses were inferred<commit_after>// TODO: I've used many ..Sync functions for simplicity, they must go
// TODO: why does .toFixed return a string?

var async = require('async'),
	_ = require('underscore'),
	fs = require('fs-extra')
	path = require('path'),
	argv = require('yargs')
		.demand([ 'oa', 'onspd', 'deviation', 'sample' ])
		// The default max deviation between the course and the surrounding
		// postcode centroids is 50 yards (~46 meters). The smaller this value,
		// the less we are diverting the runner from her course to check an
		// address.
		.default('deviation', 50.) // yards
		// The default course sample is 220 yards. On a ~3 miles run this
		// filters the course from a few thousands down to about 25 points.
		// The combination of 50 yards distance and 220 yards sample identifies
		// 23 candidate postcodes on @giacecco's standard hometown run
		// (e.g. http://dico.im/145XqiJ ).
		.default('sample', 220.) // yards
		.check(function (argv) {
			var ok = !argv.fit || (argv.fit && argv.fitsdk) || false;
			if (!ok) throw new Error('If specifying --fit, the location of the Fit SDK must be specified, too, using --fitsdk.');
		})
		.check(function (argv) {
			var ok = (!argv.lat && !argv.lon && !argv.distance) || (argv.lat && argv.lon && argv.distance) || false;
			if (!ok) throw new Error("The --lat, --lon and --distance parameters must be specified together.");
		})
		.check(function (argv) {
			var ok = argv.fit || argv.lat || false;
			if (!ok) throw new Error("You must either specify the starting position (--lat, --lon and --distance) or the preferred course (--fit).");
		})
		.argv,
	onspdReader = new require('./lib/onspd-reader')(argv.onspd),
	oaReader = new require('./lib/oa-reader')(argv.oa),
	inferenceEngine = new require('./lib/toy-inference.js')();

// This test script identifies the addresses known to Open Addresses that are
// closer to the middle of the course
var generateInvestigationOptions = function (coursePostcodes, callback) {
	// the ideal postcode to be investigated is in the middle of the course; in
	// a way the entire course can be seen as a run to the postcode to be
	// investigated and back
	var idealCoursePostcodeDistance = Math.max.apply(null, coursePostcodes.map(function (p) { return p.closestPoint.distance; })) / 2.;
	async.reduce(coursePostcodes, [ ], function (memo, coursePostcode, callback) {
		// I fetch all addresses OA knows in that postcode
		oaReader.readOaAddressesByPostcode(coursePostcode.pcd, function (err, addresses) {
			if (addresses.length === 0) {
				callback(null, memo);
			} else {
				callback(null, memo.concat({
					'postcode': coursePostcode,
					'relevantOaAddresses': addresses,
				}));
			}
		});
	}, function (err, candidateInvestigations) {
		callback(err, candidateInvestigations.sort(function (a, b) {
			// I sort candidate investigations by how close they are to that ideal
			// distance
			return Math.abs(a.postcode.closestPoint.distance - idealCoursePostcodeDistance) - Math.abs(b.postcode.closestPoint.distance - idealCoursePostcodeDistance);
		}));
	});
};

var stage2 = function (points, latLonFunction, minDistanceKm, maxDistanceKm) {
	onspdReader.fetchNearbyPostcodes(
		points,
		{
			'latLonFunction': latLonFunction,
		  	'minDistanceKm': minDistanceKm,
		  	'maxDistanceKm': maxDistanceKm,
		},
		function (err, coursePostcodes) {
			generateInvestigationOptions(coursePostcodes, function (err, investigationOptions) {
				async.reduce(investigationOptions, [ ], function (memo, o, callback) {
					inferenceEngine.doTheInferenceMagic(o.relevantOaAddresses, function (err, inferredAddresses) {
						// unless at least one address is inferred, drop the
						// postcode from the investigation options
						if (inferredAddresses.length > 0) {
							o.inferredAddresses = inferredAddresses;
							memo = memo.concat(o);
						}
						callback(null, memo);
					});
				}, function (err, investigationOptions) {
					console.log(JSON.stringify(investigationOptions));
				});
			});
		});
}

var stage1 = function () {
	if (argv.fit) {
		// the user has requested to find survey options around a.fit course
		var fitReader = new require('./lib/fit-reader')(argv.fitsdk);
		fitReader.fetchCourse(argv.fit, parseFloat(argv.sample) * 0.9144, function (err, points) {
			stage2(
				points,
				function (point) { return point.position; },
				0.,
				parseFloat(argv.deviation) * 0.0009144
			);
		});
	} else if (argv.lat && argv.lon && argv.distance) {
		// the user has requested to find survey options at a given distance
		// from a starting point
		eval(fs.readFileSync(path.join(__dirname, 'lib', 'latlon.js')) + '');
		// Note the calculation below. I need to transform the target return
		// run length into an 'as the crow flies' ray, in order to find the
		// target postcodes. As this is supposed to be an 'urban run', I presume
		// that they ray is the hypotenuse of a right angle and the sum of the
		// two sides is what the runner will actually have to run, twice (to and
		// back).
		var searchAreaRayKm = Math.sqrt((parseFloat(argv.distance) * 1.609344 / 2 / 2) ^ 2 * 2);
		stage2(
			[ new LatLon(parseFloat(argv.lat), parseFloat(argv.lon)) ],
			function (point) { return point; },
			searchAreaRayKm - parseFloat(argv.deviation) * 0.0009144,
			searchAreaRayKm + parseFloat(argv.deviation) * 0.0009144
		);
	} else {
		// you should never get here thanks to the yargs checks
	}
}

// home is LatLon(51.759467, -0.577358);
// Berkhamsted station is LatLon(51.764541, -0.562041);
stage1();
<|endoftext|>


<commit_before>'use strict'

const proxy = Symbol('proxy')
const unobserverSet = Symbol('unobserverSet')
const observing = Symbol('observing')

const targets = new WeakMap()
const observerSet = new Set()
let currentObserver

module.exports = {
  observe,
  unobserve,
  observable,
  isObservable
}

function observe (fn) {
  if (typeof fn !== 'function') {
    throw new TypeError('first argument must be a function')
  }
  if (!fn[observing]) {
    fn[observing] = true
    fn[unobserverSet] = new Set()
    queueObserver(fn)
  }
}

function unobserve (fn) {
  if (typeof fn !== 'function') {
    throw new TypeError('first argument must be a function')
  }
  if (fn[observing]) {
    fn[unobserverSet].forEach(runUnobserver)
    fn[unobserverSet] = undefined
  }
  fn[observing] = false
}

function observable (obj) {
  if (obj === undefined) {
    obj = {}
  }
  if (typeof obj !== 'object') {
    throw new TypeError('first argument must be an object or undefined')
  }
  if (isObservable(obj)) {
    return obj
  }
  if (typeof obj[proxy] === 'object') {
    return obj[proxy]
  }
  obj[proxy] = new Proxy(obj, {get, set, deleteProperty})
  targets.set(obj, new Map())
  return obj[proxy]
}

function isObservable (obj) {
  if (typeof obj !== 'object') {
    throw new TypeError('first argument must be an object')
  }
  return (obj[proxy] === true)
}

function get (target, key, receiver) {
  if (key === proxy) {
    return true
  }
  const result = Reflect.get(target, key, receiver)
  if (currentObserver) {
    registerObserver(target, key, currentObserver)
    if (typeof result === 'object') {
      return observable(result)
    }
  }
  if (typeof result === 'object' && typeof result[proxy] === 'object') {
    return result[proxy]
  }
  return result
}

function registerObserver (target, key, observer) {
  let observersForKey = targets.get(target).get(key)
  if (!observersForKey) {
    observersForKey = new Set()
    targets.get(target).set(key, observersForKey)
  }
  if (!observersForKey.has(observer)) {
    observersForKey.add(observer)
    observer[unobserverSet].add(() => observersForKey.delete(observer))
  }
}

function set (target, key, value, receiver) {
  if (targets.get(target).has(key)) {
    targets.get(target).get(key).forEach(queueObserver)
  }
  return Reflect.set(target, key, value, receiver)
}

function deleteProperty (target, key) {
  if (targets.get(target).has(key)) {
    targets.get(target).get(key).forEach(queueObserver)
  }
  return Reflect.deleteProperty(target, key)
}

function queueObserver (observer) {
  if (observerSet.size === 0) {
    setTimeout(runObservers)
  }
  observerSet.add(observer)
}

function runObservers () {
  try {
    observerSet.forEach(runObserver)
  } finally {
    currentObserver = undefined
    observerSet.clear()
  }
}

function runObserver (observer) {
  if (observer[observing]) {
    currentObserver = observer
    observer()
  }
}

function runUnobserver (unobserver) {
  unobserver()
}
<commit_msg>fix(observe): disallow date observation (native bug)<commit_after>'use strict'

const proxy = Symbol('proxy')
const unobserverSet = Symbol('unobserverSet')
const observing = Symbol('observing')

const targets = new WeakMap()
const observerSet = new Set()
let currentObserver

module.exports = {
  observe,
  unobserve,
  observable,
  isObservable
}

function observe (fn) {
  if (typeof fn !== 'function') {
    throw new TypeError('first argument must be a function')
  }
  if (!fn[observing]) {
    fn[observing] = true
    fn[unobserverSet] = new Set()
    queueObserver(fn)
  }
}

function unobserve (fn) {
  if (typeof fn !== 'function') {
    throw new TypeError('first argument must be a function')
  }
  if (fn[observing]) {
    fn[unobserverSet].forEach(runUnobserver)
    fn[unobserverSet] = undefined
  }
  fn[observing] = false
}

function observable (obj) {
  if (obj === undefined) {
    obj = {}
  }
  if (typeof obj !== 'object') {
    throw new TypeError('first argument must be an object or undefined')
  }
  if (isObservable(obj)) {
    return obj
  }
  if (typeof obj[proxy] === 'object') {
    return obj[proxy]
  }
  obj[proxy] = new Proxy(obj, {get, set, deleteProperty})
  targets.set(obj, new Map())
  return obj[proxy]
}

function isObservable (obj) {
  if (typeof obj !== 'object') {
    throw new TypeError('first argument must be an object')
  }
  return (obj[proxy] === true)
}

function get (target, key, receiver) {
  if (key === proxy) {
    return true
  }
  const result = Reflect.get(target, key, receiver)
  if (currentObserver) {
    registerObserver(target, key, currentObserver)
    if (typeof result === 'object' && !(result instanceof Date)) {
      return observable(result)
    }
  }
  if (typeof result === 'object' && typeof result[proxy] === 'object') {
    return result[proxy]
  }
  return result
}

function registerObserver (target, key, observer) {
  let observersForKey = targets.get(target).get(key)
  if (!observersForKey) {
    observersForKey = new Set()
    targets.get(target).set(key, observersForKey)
  }
  if (!observersForKey.has(observer)) {
    observersForKey.add(observer)
    observer[unobserverSet].add(() => observersForKey.delete(observer))
  }
}

function set (target, key, value, receiver) {
  if (targets.get(target).has(key)) {
    targets.get(target).get(key).forEach(queueObserver)
  }
  return Reflect.set(target, key, value, receiver)
}

function deleteProperty (target, key) {
  if (targets.get(target).has(key)) {
    targets.get(target).get(key).forEach(queueObserver)
  }
  return Reflect.deleteProperty(target, key)
}

function queueObserver (observer) {
  if (observerSet.size === 0) {
    setTimeout(runObservers)
  }
  observerSet.add(observer)
}

function runObservers () {
  try {
    observerSet.forEach(runObserver)
  } finally {
    currentObserver = undefined
    observerSet.clear()
  }
}

function runObserver (observer) {
  if (observer[observing]) {
    currentObserver = observer
    observer()
  }
}

function runUnobserver (unobserver) {
  unobserver()
}
<|endoftext|>


<commit_before>var ogreOdds = {
	init : function(target) {
		attack = document.createElement('input');
		attack.id = target+'_atk';
		attack.setAttribute('type', 'text');
		attack.onchange = function(){ogreOdds.calculateOdds(target);};
		attack.onfocus = function(){this.select();};
		attack.onmouseup = function(){return false;};

		defense = document.createElement('input');
		defense.id = target+'_def';
		defense.setAttribute('type', 'text');
		defense.onchange = function(){ogreOdds.calculateOdds(target);};
		defense.onfocus = function(){this.select();};
		defense.onmouseup = function(){return false;};

		odds = document.createElement('input');
		odds.id = target+'_odds';
		odds.setAttribute('type', 'text');
		odds.onfocus = function(){this.blur();attack.focus();};

		obj = document.getElementById(target);
		obj.appendChild(document.createTextNode('Attack: '));
		obj.appendChild(attack);
		obj.appendChild(document.createElement('br'));
		obj.appendChild(document.createTextNode('Defense: '));
		obj.appendChild(defense);
		obj.appendChild(document.createElement('br'));
		obj.appendChild(document.createTextNode('Odds: '));
		obj.appendChild(odds);
	},

	calculateOdds : function(target) {
		atk = document.getElementById(target+'_atk').value;
		def = document.getElementById(target+'_def').value;

		if(atk > 0 && def > 0)
		{
			odds = Math.floor(atk / def);
			if(odds > 4)
			{
				odds = 'X';
			} else if(odds == 0) {
				if(0.5 > atk / def)
				{
					odds = 'NE';
				} else {
					odds = '1-2';
				}
			} else {
				odds = odds+'-1';
			}

			document.getElementById(target+'_odds').value = odds;
		}
	}
}
<commit_msg>Combat Odds Calculator now uses local variables (oops!)<commit_after>var ogreOdds = {
	init : function(target) {
		var attack = document.createElement('input');
		attack.id = target+'_atk';
		attack.setAttribute('type', 'text');
		attack.onchange = function(){ogreOdds.calculateOdds(target);};
		attack.onfocus = function(){this.select();};
		attack.onmouseup = function(){return false;};

		var defense = document.createElement('input');
		defense.id = target+'_def';
		defense.setAttribute('type', 'text');
		defense.onchange = function(){ogreOdds.calculateOdds(target);};
		defense.onfocus = function(){this.select();};
		defense.onmouseup = function(){return false;};

		var odds = document.createElement('input');
		odds.id = target+'_odds';
		odds.setAttribute('type', 'text');
		odds.onfocus = function(){this.blur();attack.focus();};

		var obj = document.getElementById(target);
		obj.appendChild(document.createTextNode('Attack: '));
		obj.appendChild(attack);
		obj.appendChild(document.createElement('br'));
		obj.appendChild(document.createTextNode('Defense: '));
		obj.appendChild(defense);
		obj.appendChild(document.createElement('br'));
		obj.appendChild(document.createTextNode('Odds: '));
		obj.appendChild(odds);
	},

	calculateOdds : function(target) {
		var atk = document.getElementById(target+'_atk').value;
		var def = document.getElementById(target+'_def').value;

		if(atk > 0 && def > 0)
		{
			var odds = Math.floor(atk / def);
			if(odds > 4)
			{
				odds = 'X';
			} else if(odds == 0) {
				if(0.5 > atk / def)
				{
					odds = 'NE';
				} else {
					odds = '1-2';
				}
			} else {
				odds = odds+'-1';
			}

			document.getElementById(target+'_odds').value = odds;
		}
	}
}
<|endoftext|>