<commit_before>const Constants = require('./constants');
const CoreConstants = require('kolibri.coreVue.vuex.constants');
const ContentNodeKinds = CoreConstants.ContentNodeKinds;
const logging = require('kolibri.lib.logging');

/* given an array of objects sum the keys on those that pass the filter */
function sumOfKeys(array, key, filter = () => true) {
  return array
    .filter(filter)
    .reduce((prev, item) => prev + item[key], 0);
}

function countNodes(progressArray, filter) {
  return sumOfKeys(progressArray, 'node_count', filter);
}

function calcProgress(progressArray, filter, count) {
  const totalProgress = sumOfKeys(progressArray, 'total_progress', filter);
  if (count) {
    return totalProgress / count;
  }
  return undefined;
}

function onlyExercises(item) {
  return item.kind === ContentNodeKinds.EXERCISE;
}

function onlyContent(item) {
  return item.kind !== ContentNodeKinds.EXERCISE;
}

function genCompareFunc(sortColumn, sortOrder) {
  const columnToKey = {};
  columnToKey[Constants.TableColumns.NAME] = 'title';
  columnToKey[Constants.TableColumns.EXERCISE] = 'exerciseProgress';
  columnToKey[Constants.TableColumns.CONTENT] = 'contentProgress';
  columnToKey[Constants.TableColumns.DATE] = 'lastActive';
  const key = columnToKey[sortColumn];

  // take into account sort order
  const flipOrder = sortOrder === Constants.SortOrders.DESCENDING ? 1 : -1;
  // default order of names is A-Z; everything else goes high-low
  const flipNameCol = sortColumn !== Constants.TableColumns.NAME ? -1 : 1;
  return (a, b) => {
    if (a[key] !== undefined && b[key] === undefined) { return 1 * flipOrder * flipNameCol; }
    if (a[key] === undefined && b[key] !== undefined) { return -1 * flipOrder * flipNameCol; }
    if (a[key] > b[key]) { return 1 * flipOrder * flipNameCol; }
    if (a[key] < b[key]) { return -1 * flipOrder * flipNameCol; }
    return 0;
  };
}

const getters = {
  usersCompleted(state) {
    return state.pageState.content_scope_summary.progress[0].log_count_complete;
  },
  exerciseCount(state) {
    const summary = state.pageState.content_scope_summary;
    if (summary.kind === ContentNodeKinds.TOPIC) {
      return countNodes(summary.progress, onlyExercises);
    } else if (summary.kind === ContentNodeKinds.EXERCISE) {
      return 1;
    }
    return 0;
  },
  exerciseProgress(state) {
    return calcProgress(
      state.pageState.content_scope_summary.progress,
      onlyExercises,
      getters.exerciseCount(state)
    );
  },
  contentCount(state) {
    const summary = state.pageState.content_scope_summary;
    if (summary.kind === ContentNodeKinds.TOPIC) {
      return countNodes(summary.progress, onlyContent);
    } else if (summary.kind !== ContentNodeKinds.EXERCISE) {
      return 1;
    }
    return 0;
  },
  contentProgress(state) {
    return calcProgress(
      state.pageState.content_scope_summary.progress,
      onlyContent,
      getters.contentCount(state)
    );
  },
  dataTable(state) {
    const data = state.pageState.table_data.map(item => {
      const row = {};

      // CONTENT NODES
      if (state.pageState.view_by_content_or_learners === Constants.ViewBy.CONTENT) {
        row.kind = item.kind;
        row.id = item.pk;
        row.title = item.title;
        row.parent = { id: item.parent.pk, title: item.parent.title };

        // for content items, set exercise counts appropriately
        if (item.kind === ContentNodeKinds.TOPIC) {
          row.exerciseCount = countNodes(item.progress, onlyExercises);
          row.contentCount = countNodes(item.progress, onlyContent);
        } else if (onlyExercises(item)) {
          row.exerciseCount = 1;
          row.contentCount = 0;
        } else if (onlyContent(item)) {
          row.exerciseCount = 0;
          row.contentCount = 1;
        } else {
          logging.error(`Unhandled item kind: ${item.kind}`);
        }
      // LEARNERS
      } else if (state.pageState.view_by_content_or_learners === Constants.ViewBy.LEARNERS) {
        row.kind = CoreConstants.USER;
        row.id = item.pk.toString(); // see https://github.com/learningequality/kolibri/issues/65;
        row.title = item.full_name;
        row.parent = undefined; // not currently used. Eventually, maybe classes/groups?

        // for learners, the exerise counts are the global values
        row.exerciseProgress
          = calcProgress(item.progress, onlyExercises, getters.exerciseCount(state));
        row.contentProgress
          = calcProgress(item.progress, onlyContent, getters.contentCount(state));
      } else {
        logging.error('Unknown view-by state', state.pageState.view_by_content_or_learners);
      }

      row.exerciseProgress = calcProgress(item.progress, onlyExercises, row.exerciseCount);
      row.contentProgress = calcProgress(item.progress, onlyContent, row.contentCount);
      row.lastActive = item.last_active ? new Date(item.last_active) : null;

      return row;
    });

    if (state.pageState.sort_order !== Constants.SortOrders.NONE) {
      data.sort(genCompareFunc(state.pageState.sort_column, state.pageState.sort_order));
    }

    return data;
  },
};

module.exports = getters;
<commit_msg>proper calculation of progress for single content items<commit_after>const Constants = require('./constants');
const CoreConstants = require('kolibri.coreVue.vuex.constants');
const ContentNodeKinds = CoreConstants.ContentNodeKinds;
const logging = require('kolibri.lib.logging');

/* given an array of objects sum the keys on those that pass the filter */
function sumOfKeys(array, key, filter = () => true) {
  return array
    .filter(filter)
    .reduce((prev, item) => prev + item[key], 0);
}

function countNodes(progressArray, filter) {
  return sumOfKeys(progressArray, 'node_count', filter);
}

function calcProgress(progressArray, filter, count) {
  const totalProgress = sumOfKeys(progressArray, 'total_progress', filter);
  if (count) {
    return totalProgress / count;
  }
  return undefined;
}

function onlyExercises(item) {
  return item.kind === ContentNodeKinds.EXERCISE;
}

function onlyContent(item) {
  return item.kind !== ContentNodeKinds.EXERCISE;
}

function genCompareFunc(sortColumn, sortOrder) {
  const columnToKey = {};
  columnToKey[Constants.TableColumns.NAME] = 'title';
  columnToKey[Constants.TableColumns.EXERCISE] = 'exerciseProgress';
  columnToKey[Constants.TableColumns.CONTENT] = 'contentProgress';
  columnToKey[Constants.TableColumns.DATE] = 'lastActive';
  const key = columnToKey[sortColumn];

  // take into account sort order
  const flipOrder = sortOrder === Constants.SortOrders.DESCENDING ? 1 : -1;
  // default order of names is A-Z; everything else goes high-low
  const flipNameCol = sortColumn !== Constants.TableColumns.NAME ? -1 : 1;
  return (a, b) => {
    if (a[key] !== undefined && b[key] === undefined) { return 1 * flipOrder * flipNameCol; }
    if (a[key] === undefined && b[key] !== undefined) { return -1 * flipOrder * flipNameCol; }
    if (a[key] > b[key]) { return 1 * flipOrder * flipNameCol; }
    if (a[key] < b[key]) { return -1 * flipOrder * flipNameCol; }
    return 0;
  };
}

const getters = {
  usersCompleted(state) {
    return state.pageState.content_scope_summary.progress[0].log_count_complete;
  },
  exerciseCount(state) {
    const summary = state.pageState.content_scope_summary;
    if (summary.kind === ContentNodeKinds.TOPIC) {
      return countNodes(summary.progress, onlyExercises);
    } else if (summary.kind === ContentNodeKinds.EXERCISE) {
      return 1;
    }
    return 0;
  },
  exerciseProgress(state) {
    return calcProgress(
      state.pageState.content_scope_summary.progress,
      onlyExercises,
      getters.exerciseCount(state)
    );
  },
  contentCount(state) {
    const summary = state.pageState.content_scope_summary;
    if (summary.kind === ContentNodeKinds.TOPIC) {
      return countNodes(summary.progress, onlyContent);
    } else if (summary.kind !== ContentNodeKinds.EXERCISE) {
      return 1;
    }
    return 0;
  },
  contentProgress(state) {
    return calcProgress(
      state.pageState.content_scope_summary.progress,
      onlyContent,
      getters.contentCount(state)
    );
  },
  dataTable(state) {
    const data = state.pageState.table_data.map(item => {
      const row = {};

      // CONTENT NODES
      if (state.pageState.view_by_content_or_learners === Constants.ViewBy.CONTENT) {
        row.kind = item.kind;
        row.id = item.pk;
        row.title = item.title;
        row.parent = { id: item.parent.pk, title: item.parent.title };

        // for content items, set exercise counts and progress appropriately
        if (item.kind === ContentNodeKinds.TOPIC) {
          row.exerciseCount = countNodes(item.progress, onlyExercises);
          row.exerciseProgress = calcProgress(item.progress, onlyExercises, row.exerciseCount);
          row.contentCount = countNodes(item.progress, onlyContent);
          row.contentProgress = calcProgress(item.progress, onlyContent, row.contentCount);
        } else if (onlyExercises(item)) {
          row.exerciseCount = 1;
          row.exerciseProgress = item.progress[0].total_progress;
          row.contentCount = 0;
          row.contentProgress = undefined;
        } else if (onlyContent(item)) {
          row.exerciseCount = 0;
          row.exerciseProgress = undefined;
          row.contentCount = 1;
          row.contentProgress = item.progress[0].total_progress;
        } else {
          logging.error(`Unhandled item kind: ${item.kind}`);
        }
      // LEARNERS
      } else if (state.pageState.view_by_content_or_learners === Constants.ViewBy.LEARNERS) {
        row.kind = CoreConstants.USER;
        row.id = item.pk.toString(); // see https://github.com/learningequality/kolibri/issues/65;
        row.title = item.full_name;
        row.parent = undefined; // not currently used. Eventually, maybe classes/groups?

        // for learners, the exerise counts are the global values
        row.exerciseProgress
          = calcProgress(item.progress, onlyExercises, getters.exerciseCount(state));
        row.contentProgress
          = calcProgress(item.progress, onlyContent, getters.contentCount(state));
      } else {
        logging.error('Unknown view-by state', state.pageState.view_by_content_or_learners);
      }

      row.lastActive = item.last_active ? new Date(item.last_active) : null;

      return row;
    });

    if (state.pageState.sort_order !== Constants.SortOrders.NONE) {
      data.sort(genCompareFunc(state.pageState.sort_column, state.pageState.sort_order));
    }

    return data;
  },
};

module.exports = getters;
<|endoftext|>


<commit_before>var slimQuery = function(selector) {
	return sqElem.prototype.init(selector);
};

slimQuery.data = {};
slimQuery.event = {
	special: {}
};
slimQuery.eventMap = {
	click: "click",
	ready: "DOMContentLoaded"
};
slimQuery.support = {};

slimQuery.Event = function(src, props) {
	if (!(this instanceof slimQuery.Event)) {
		return new slimQuery.Event( src, props );
	}
	if (props) {
		slimQuery.extend(this, props);
	}
	this.src = src;
};

slimQuery.Event.prototype.isDefaultPrevented = function() {
	return (this.defaultPrevented||false);
};

slimQuery.Event.prototype.preventDefault = function() {
	this.defaultPrevented = true;
};

function sqElem(selector) {
	if (typeof selector === "function") {
		// apparently this is a thing
		$(document).ready(selector);
	} else if (selector instanceof sqElem) {
		return selector;
	} else if (selector instanceof HTMLElement) {
		this[0] = selector;
		this.length++;
	} else if (selector instanceof Array) {
		this.addArray(selector);
	} else if (selector instanceof NodeList) {
		this.addArray(slimQuery.nodeListToArray(selector));
	} else if (selector !== document && selector !== window) {
		this.addArray(document.querySelectorAll(selector));
	} else {
		this[0] = selector;
		this.length++;
	}
	return this;
}

sqElem.prototype = sqElem.fn = slimQuery.fn = {
	jquery: "1.11.3", // this is for compatibility,
	length: 0,
	noConflictFlag: false,
	slimquery: "0.1"
};

sqElem.prototype.init = function(selector) {
	return new sqElem(selector);
};

sqElem.prototype.addArray = function(array) {
	var obj = this;
	var lenStart = this.length;
	slimQuery.each(array, function(i) {
		obj[lenStart + i] = this;
		obj.length++;
	});
	return this;
};

sqElem.prototype.addClass = function(newClass) {
	slimQuery.eachElem(this, function() {
		var curClass = $(this).attr("class");
		if (curClass === undefined) {
			curClass = "";
		}
		curClass = curClass + " " + newClass;
		$(this).attr("class", curClass);
	});
	return this;
};

sqElem.prototype.attr = function(propertyName, value) {
	if (value === undefined) {
		return (this[0].getAttribute(propertyName)||undefined);
	}
	slimQuery.eachElem(this, function() {
		this.setAttribute(propertyName, value);
	});
	return this;
};

sqElem.prototype.append = function(thing) {
	var elem;
	if (thing instanceof HTMLElement) {
		elem = [ thing ];
	} else if (thing instanceof sqElem) {
		elem = thing;
	} else {
		elem = $(thing);
	}
	slimQuery.eachElem(this, function() {
		var to = this;
		slimQuery.each(elem, function() {
			to.appendChild(this);
		});
	});
	return this;
};

sqElem.prototype.appendTo = function(thing) {
	thing.append(this);
	return this;
};

sqElem.prototype.css = function(propertyName, value) {
	if (value === undefined) {
		return window.getComputedStyle(this[0], propertyName);
	}
	slimQuery.eachElem(this, function() {
		this.setAttribute("style", (this.getAttribute("style")||"") + propertyName + ":" + value + ";");
	});
	return this;
};

sqElem.prototype.data = function(propertyName, value) {
	if (value === undefined) {
		if (this.attr("data-sq-private-id") === undefined) {
			return undefined;
		}
		return slimQuery.data[this.attr("data-sq-private-id")][propertyName];
	}
	var id = $(this[0]).attr("data-sq-private-id");
	if (id === undefined) {
		id = slimQuery.uniqueId();
		$(this[0]).attr("data-sq-private-id", id);
		slimQuery.data[id] = {};
	}
	slimQuery.data[id][propertyName] = value;
	return this;
};

sqElem.prototype.each = function(callback) {
	return slimQuery.eachElem(this, callback);
};

sqElem.prototype.find = function(selector) {
	return slimQuery.find(selector, this);
};

sqElem.prototype.splice = function() {
	/*return this..splice.apply(this.dom, arguments);*/
	return false; // TODO: implement splice. This is just a stub to get it to show up as an array.
};

sqElem.prototype.text = function(newValue) {
	if (newValue === undefined) {
		return this[0].innerText;
	}
	slimQuery.eachElem(this, function() {
		this.innerText = newValue;
	});
	return this;
};

sqElem.prototype.hasClass = function(newValue) {
	return (this.attr("class").indexOf(newValue) > -1); // TODO: make this better
};

sqElem.prototype.html = function(newValue) {
	if (newValue === undefined) {
		return this[0].innerHTML;
	}
	slimQuery.eachElem(this, function() {
		this.innerHTML = newValue;
	});
	return this;
};

sqElem.prototype.on = function(event, callback) {
	slimQuery.eachElem(this, function() {
		this.addEventListener(slimQuery.eventJsName(event), function(e) {
			callback.call(e);
		});
	});
	return this;
};

sqElem.prototype.one = function(event, callback) {
	this.on(event, function() {
		callback.call(this);
		// TODO: stop allowing event to happen
		// TODO: this will happen with the event system
	});
	return this;
};

sqElem.prototype.parent = function() {
	return $(this[0].parentNode);
};

sqElem.prototype.show = function() {
	slimQuery.eachElem(this, function() {
		$(this).css("display", "inherit");
	});
	return this;
};

sqElem.prototype.trigger = function(eventStr) {
	// TODO: trigger all of them
	var evt = new Event(slimQuery.eventJsName(eventStr));
	slimQuery.eachElem(this, function() {
		this.dispatchEvent(evt);
	});
	return this;
};

slimQuery.each = function(items, callback) {
	for (var i = 0; i < items.length; i++) {
		callback.call(items[i], i, items[i]);
	}
};

slimQuery.eachElem = function(items, callback) {
	return slimQuery.each(items, function(i) {
		if (typeof i === "number") {
			callback.call(this, i, items[i]);
		}
	});
};

slimQuery.extend = function() {
	// based off of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill
	var retVal = Object(arguments[0]);
	for (var i = 1; i < arguments.length; i++) { // yes, start at one
		var src = arguments[i];
		for (var key in src) {
			if (src.hasOwnProperty(key)) {
				retVal[key] = src[key];
			}
		}
	}
	return retVal;
};

slimQuery.eventJsName = function(name) {
	return (slimQuery.eventMap[name] || "sQ-" + name);
};

slimQuery.find = function(search, start) {
	if (start === undefined) {
		start = $("html");
	}
	return $(start[0].querySelectorAll(search));
};

slimQuery.noConflict = function() {
	slimQuery.noConflictFlag = true;
};

slimQuery.nodeListToArray = function() {
    var a = [];

    for (var i = 0, len = this.length; i < len; i++) {
        a[i] = this[i];
    }

    return a;
}

slimQuery.proxy = function(fn, context) {
	var newFunc  = function() {
		return fn.apply( context || this, arguments);
	};
	return newFunc;
};

slimQuery.uniqueId = function() {
	return "slimQuery-" + Math.random().toString(36).substr(2, 10) + Math.random().toString(36).substr(2, 10);
};

// this is from jQuery
slimQuery.each(("blur focus focusin focusout load resize scroll unload click dblclick " +
	"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
	"change select submit keydown keypress keyup error contextmenu ready").split(" "), function( i, name ) {
	// Handle event binding
	sqElem.prototype[name] = function(fn) {
		return arguments.length > 0 ?
			this.on(name, fn) :
			this.trigger(name);
	};
});

window.sQ = window.slimQuery;
if (!slimQuery.noConflictFlag) {
	window.$ = window.sQ;
	window.jQuery = window.sQ;
}
<commit_msg>more stuff<commit_after>var slimQuery = function(selector) {
	return sqElem.prototype.init(selector);
};

slimQuery.data = {};
slimQuery.event = {
	special: {}
};
slimQuery.eventMap = {
	click: "click",
	ready: "DOMContentLoaded"
};
slimQuery.eventTracker = {};
slimQuery.support = {};

slimQuery.Event = function(src, props) {
	if (!(this instanceof slimQuery.Event)) {
		return new slimQuery.Event( src, props );
	}
	if (props) {
		slimQuery.extend(this, props);
	}
	this.src = src;
};

slimQuery.Event.prototype.isDefaultPrevented = function() {
	return (this.defaultPrevented||false);
};

slimQuery.Event.prototype.preventDefault = function() {
	this.defaultPrevented = true;
};

function sqElem(selector) {
	if (typeof selector === "function") {
		// apparently this is a thing
		$(document).ready(selector);
	} else if (selector instanceof sqElem) {
		return selector;
	} else if (selector instanceof HTMLElement) {
		this[0] = selector;
		this.length++;
	} else if (selector instanceof Array) {
		this.addArray(selector);
	} else if (selector instanceof NodeList) {
		this.addArray(slimQuery.nodeListToArray(selector));
	} else if (selector !== document && selector !== window) {
		this.addArray(document.querySelectorAll(selector));
	} else {
		this[0] = selector;
		this.length++;
	}
	return this;
}

sqElem.prototype = sqElem.fn = slimQuery.fn = {
	jquery: "1.11.3", // this is for compatibility,
	length: 0,
	noConflictFlag: false,
	slimquery: "0.1"
};

sqElem.prototype.init = function(selector) {
	return new sqElem(selector);
};

sqElem.prototype.addArray = function(array) {
	var obj = this;
	var lenStart = this.length;
	slimQuery.each(array, function(i) {
		obj[lenStart + i] = this;
		obj.length++;
	});
	return this;
};

sqElem.prototype.addClass = function(newClass) {
	slimQuery.eachElem(this, function() {
		var curClass = $(this).attr("class");
		if (curClass === undefined) {
			curClass = "";
		}
		curClass = curClass + " " + newClass;
		$(this).attr("class", curClass);
	});
	return this;
};

sqElem.prototype.attr = function(propertyName, value) {
	if (value === undefined) {
		return (this[0].getAttribute(propertyName)||undefined);
	}
	slimQuery.eachElem(this, function() {
		this.setAttribute(propertyName, value);
	});
	return this;
};

sqElem.prototype.append = function(thing) {
	var elem;
	if (thing instanceof HTMLElement) {
		elem = [ thing ];
	} else if (thing instanceof sqElem) {
		elem = thing;
	} else {
		elem = $(thing);
	}
	slimQuery.eachElem(this, function() {
		var to = this;
		slimQuery.each(elem, function() {
			to.appendChild(this);
		});
	});
	return this;
};

sqElem.prototype.appendTo = function(thing) {
	thing.append(this);
	return this;
};

sqElem.prototype.css = function(propertyName, value) {
	if (value === undefined) {
		return window.getComputedStyle(this[0], propertyName);
	}
	slimQuery.eachElem(this, function() {
		this.setAttribute("style", (this.getAttribute("style")||"") + propertyName + ":" + value + ";");
	});
	return this;
};

sqElem.prototype.data = function(propertyName, value) {
	if (value === undefined) {
		if (this.attr("data-sq-private-id") === undefined) {
			return undefined;
		}
		return slimQuery.data[this.attr("data-sq-private-id")][propertyName];
	}
	var id = $(this[0]).attr("data-sq-private-id");
	if (id === undefined) {
		id = slimQuery.uniqueId();
		$(this[0]).attr("data-sq-private-id", id);
		slimQuery.data[id] = {};
	}
	slimQuery.data[id][propertyName] = value;
	return this;
};

sqElem.prototype.each = function(callback) {
	return slimQuery.eachElem(this, callback);
};

sqElem.prototype.find = function(selector) {
	return slimQuery.find(selector, this);
};

sqElem.prototype.splice = function() {
	/*return this..splice.apply(this.dom, arguments);*/
	return false; // TODO: implement splice. This is just a stub to get it to show up as an array.
};

sqElem.prototype.text = function(newValue) {
	if (newValue === undefined) {
		return this[0].innerText;
	}
	slimQuery.eachElem(this, function() {
		this.innerText = newValue;
	});
	return this;
};

sqElem.prototype.hasClass = function(newValue) {
	return (this.attr("class").indexOf(newValue) > -1); // TODO: make this better
};

sqElem.prototype.html = function(newValue) {
	if (newValue === undefined) {
		return this[0].innerHTML;
	}
	slimQuery.eachElem(this, function() {
		this.innerHTML = newValue;
	});
	return this;
};

sqElem.prototype.on = function(event, callback) {
	slimQuery.eachElem(this, function() {
		this.addEventListener(slimQuery.eventJsName(event), function(e) {
			callback.call(e);
		});
	});
	return this;
};

sqElem.prototype.one = function(event, callback) {
	this.on(event, function() {
		callback.call(this);
		// TODO: stop allowing event to happen
		// TODO: this will happen with the event system
	});
	return this;
};

sqElem.prototype.off = function(event, callback) {
	this.on(event, function() {
		callback.call(this);
		// TODO: stop allowing event to happen
		// TODO: this will happen with the event system
	});
	return this;
};

sqElem.prototype.parent = function() {
	return $(this[0].parentNode);
};

sqElem.prototype.scrollTop = function(val) {
	if (val === undefined) {
		return $(this)[0].scrollTop;
	}
	window.scrollTo(0, val); // TODO: don't reset scrollLeft
	return this;
};

sqElem.prototype.show = function() {
	slimQuery.eachElem(this, function() {
		$(this).css("display", "inherit");
	});
	return this;
};

sqElem.prototype.trigger = function(eventStr) {
	// TODO: trigger all of them
	var evt = new Event(slimQuery.eventJsName(eventStr));
	slimQuery.eachElem(this, function() {
		this.dispatchEvent(evt);
	});
	return this;
};

slimQuery.each = function(items, callback) {
	for (var i = 0; i < items.length; i++) {
		callback.call(items[i], i, items[i]);
	}
};

slimQuery.eachElem = function(items, callback) {
	return slimQuery.each(items, function(i) {
		if (typeof i === "number") {
			callback.call(this, i, items[i]);
		}
	});
};

slimQuery.extend = function() {
	// based off of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign#Polyfill
	var retVal = Object(arguments[0]);
	for (var i = 1; i < arguments.length; i++) { // yes, start at one
		var src = arguments[i];
		for (var key in src) {
			if (src.hasOwnProperty(key)) {
				retVal[key] = src[key];
			}
		}
	}
	return retVal;
};

slimQuery.eventJsName = function(name) {
	return (slimQuery.eventMap[name] || "sQ-" + name);
};

slimQuery.find = function(search, start) {
	if (start === undefined) {
		start = $("html");
	}
	return $(start[0].querySelectorAll(search));
};

slimQuery.noConflict = function() {
	slimQuery.noConflictFlag = true;
};

slimQuery.nodeListToArray = function() {
    var a = [];

    for (var i = 0, len = this.length; i < len; i++) {
        a[i] = this[i];
    }

    return a;
}

slimQuery.proxy = function(fn, context) {
	var newFunc  = function() {
		return fn.apply( context || this, arguments);
	};
	return newFunc;
};

slimQuery.uniqueId = function() {
	return "slimQuery-" + Math.random().toString(36).substr(2, 10) + Math.random().toString(36).substr(2, 10);
};

// this is from jQuery
slimQuery.each(("blur focus focusin focusout load resize scroll unload click dblclick " +
	"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
	"change select submit keydown keypress keyup error contextmenu ready").split(" "), function( i, name ) {
	// Handle event binding
	sqElem.prototype[name] = function(fn) {
		return arguments.length > 0 ?
			this.on(name, fn) :
			this.trigger(name);
	};
});

window.sQ = window.slimQuery;
if (!slimQuery.noConflictFlag) {
	window.$ = window.sQ;
	window.jQuery = window.sQ;
}
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const path = require('path');
const remark = require('remark');
const shjs = require('shelljs');

const utils = require('./utils');
const tmpDir = '/tmp';
const eslint = './node_modules/.bin/eslint --fix';

module.exports = function tinker(filePath, eslintrc) {
  let file = fs.readFileSync(filePath).toString();

  const codes = [];
  const ast = remark.parse(file);
  utils.traverse(ast, {
    code: function(node) {
      if (!!node.lang && utils.isES(node.lang)) {
        codes.push(node.value);
      }
    },
  });

  codes.forEach(function(code) {
    const tmpFile = tmpDir + path.sep + 'eslint-tinker-tmp-' + Date.now();
    fs.writeFileSync(tmpFile, code);

    const cmd = eslint + ' -c ' + eslintrc + ' ' + tmpFile + ' > /dev/null';
    shjs.exec(cmd);

    const fixedCode = fs.readFileSync(tmpFile).toString();

    file = file.replace(code, fixedCode);
    shjs.rm(tmpFile);
  });

  fs.writeFileSync(filePath, file);
  console.log('Errors in ' + filePath + ' had been fixed! XD');
};
<commit_msg>fix: suppress eol-last for it is unstable<commit_after>'use strict';

const fs = require('fs');
const path = require('path');
const remark = require('remark');
const shjs = require('shelljs');

const utils = require('./utils');
const tmpDir = '/tmp';
const eslint = './node_modules/.bin/eslint --fix';

module.exports = function tinker(filePath, eslintrc) {
  let file = fs.readFileSync(filePath).toString();

  const codes = [];
  const ast = remark.parse(file);
  utils.traverse(ast, {
    code: function(node) {
      if (!!node.lang && utils.isES(node.lang)) {
        codes.push(node.value);
      }
    },
  });

  codes.forEach(function(code) {
    const tmpFile = tmpDir + path.sep + 'eslint-tinker-tmp-' + Date.now();
    fs.writeFileSync(tmpFile, code);

    const cmd = eslint + ' -c ' + eslintrc + ' ' + tmpFile + ' --rule \'eol-last: 0\' > /dev/null';
    shjs.exec(cmd);

    const fixedCode = fs.readFileSync(tmpFile).toString();

    file = file.replace(code, fixedCode);
    shjs.rm(tmpFile);
  });

  fs.writeFileSync(filePath, file);
  console.log('Errors in ' + filePath + ' had been fixed! XD');
};
<|endoftext|>


<commit_before>/**
 * This is the setup module.
 * It is supposed to help you create the correct environment to start the app.
 * For more information on how to use this script or on how to start the application,
 * please read README.md.
 * */

var exec = require('child_process').exec;
var fs = require('fs');

function copyFileSync(src, dest) {
  var data = fs.readFileSync(src);
  fs.writeFileSync(dest, data);
}
function isInstalled(app, callback) {
  var cmd = "which " + app;
  exec(cmd, function(err, stdout, stderr) {
    var isInstalled = !err;
    callback(isInstalled);
  });
}

function npmInstall(callback) {
  exec("npm install", function(err, stdout, stderr) {
    callback(err);
  });
}
function bowerInstall(callback) {
  exec("bower install", function(err, stdout, stderr) {
    callback(err);
  });
}

function ensureGrunt(callback) {
  callback = callback || function() {};
  isInstalled("grunt", function(isInstalled) {
    if ( !isInstalled ) {
      exec("npm install -g grunt-cli", function(err, stdout, stderr) {
        callback(err);
      });
    } else {
      callback();
    }
  });
}
function ensureBower(callback) {
  callback = callback || function() {};
  isInstalled("bower", function(isInstalled) {
    if ( !isInstalled ) {
      exec("npm install -g bower", function(err, stdout, stderr) {
        callback(err);
      });
    } else {
      callback();
    }
  });
}

// First, check if there is a config.json
if ( !fs.existsSync('config.json') ) {
  console.log("You need to create a config.json file that tells the application your preferences.");
  console.log("Copying file for you...");
  copyFileSync('config.example.json', 'config.json');
  console.log("Done.");
} else {
  console.log("Good. You already have a config file for the application.");
}

console.log("We are installing dependencies, just to be sure...");
console.log("You need npm and bower installed.");
console.log("----- npm install -----");
npmInstall(function(err) {

  console.log("Installing grunt...");
  ensureGrunt(function(err2) {
    console.log("Installing bower...");
    ensureBower(function(err3) {

      console.log("----- bower install -----");
      bowerInstall(function(err4) {
        console.log("All done.");
      });

    });
  });

});
<commit_msg>Added some comments to setup.<commit_after>/**
 * This is the setup module.
 * It is supposed to help you create the correct environment to start the app.
 * For more information on how to use this script or on how to start the application,
 * please read README.md.
 *
 * @mdoule setup
 * @author Sören Gade
 * */

/* Our requirements */
var exec = require('child_process').exec;
var fs = require('fs');

/** ========== ========== ==========
 * Helpers
 *  ========== ========== ==========
 * */

/**
 * Copies a file synchronioulsy.
 * @param {String} src - The source path of the file that should be copied.
 * @param {String} dest - The destiation path of the copy.
 * */
function copyFileSync(src, dest) {
  var data = fs.readFileSync(src); // read all the data from the file
  fs.writeFileSync(dest, data); // write the data into the new file
}
/**
 * Checks if the given command line application is installed.
 * @param {String} app - The command that should be installed.
 * @param {SuccessCallback} callback - A callback that defines whether the tool is installed.
 * */
function isInstalled(app, callback) {
  var cmd = "which " + app; // use 'which' to determine path => it then is installed
  exec(cmd, function(err, stdout, stderr) {
    var isInstalled = !err;
    callback(isInstalled);
  });
}

/** ========== ========== ==========
 * Executed commands
 *  ========== ========== ==========
 * */
/**
 * Executes 'npm install'.
 * @param {ErrorCallback} callback - A callback that is called once the operation finished.
 * */
function npmInstall(callback) {
  exec("npm install", function(err, stdout, stderr) {
    callback(err);
  });
}
/**
 * Executes 'bower install'.
 * @param {ErrorCallback} callback - A callback that is called once the operation finished.
 * */
function bowerInstall(callback) {
  exec("bower install", function(err, stdout, stderr) {
    callback(err);
  });
}

function ensureGrunt(callback) {
  callback = callback || function() {};
  isInstalled("grunt", function(isInstalled) {
    if ( !isInstalled ) {
      exec("npm install -g grunt-cli", function(err, stdout, stderr) {
        callback(err);
      });
    } else {
      callback();
    }
  });
}
function ensureBower(callback) {
  callback = callback || function() {};
  isInstalled("bower", function(isInstalled) {
    if ( !isInstalled ) {
      exec("npm install -g bower", function(err, stdout, stderr) {
        callback(err);
      });
    } else {
      callback();
    }
  });
}

// First, check if there is a config.json
if ( !fs.existsSync('config.json') ) {
  console.log("You need to create a config.json file that tells the application your preferences.");
  console.log("Copying file for you...");
  copyFileSync('config.example.json', 'config.json');
  console.log("Done.");
} else {
  console.log("Good. You already have a config file for the application.");
}

console.log("We are installing dependencies, just to be sure...");
console.log("You need npm and bower installed.");
console.log("----- npm install -----");
npmInstall(function(err) {

  console.log("Installing grunt...");
  ensureGrunt(function(err2) {
    console.log("Installing bower...");
    ensureBower(function(err3) {

      console.log("----- bower install -----");
      bowerInstall(function(err4) {
        console.log("All done.");
      });

    });
  });

});
<|endoftext|>


<commit_before>import loconfig from '../utils/config.js';
import message from '../utils/message.js';
import resolve from '../utils/template.js';
import {
    mkdir,
    readFile,
    writeFile,
} from 'node:fs/promises';
import {
    basename,
    dirname,
} from 'node:path';

/**
 * @typedef  {object} VersionOptions
 * @property {string} versionKey - The JSON field to add or update.
 */

/**
 * @const {VersionOptions} defaultVersionOptions     - The default shared version options.
 * @const {VersionOptions} developmentVersionOptions - The predefined version options for development.
 * @const {VersionOptions} productionVersionOptions  - The predefined version options for production.
 */
export const defaultVersionOptions = {
    versionKey: 'version',
};
export const developmentVersionOptions = Object.assign({}, defaultVersionOptions);
export const productionVersionOptions  = Object.assign({}, defaultVersionOptions);

/**
 * @const {object} developmentVersionFilesArgs - The predefined `bumpVersion()` options for development.
 * @const {object} productionVersionFilesArgs  - The predefined `bumpVersion()` options for production.
 */
export const developmentVersionFilesArgs = [
    developmentVersionOptions,
];
export const productionVersionFilesArgs  = [
    productionVersionOptions,
];

/**
 * Bumps version numbers in file.
 *
 * @async
 * @param  {object} [versionOptions=null] - Customize the version options.
 *     If `null`, default production options are used.
 * @return {Promise}
 */
export default async function bumpVersion(versionOptions = null) {
    if (versionOptions == null) {
        versionOptions = productionVersionOptions;
    } else if (
        versionOptions !== developmentVersionOptions &&
        versionOptions !== productionVersionOptions
    ) {
        versionOptions = Object.assign({}, defaultVersionOptions, versionOptions);
    }

    loconfig.tasks.versions.forEach(async ({
        outfile,
        key = null,
        label = null
    }) => {
        if (!label) {
            label = basename(outfile || 'undefined');
        }

        const timeLabel = `${label} bumped in`;
        console.time(timeLabel);

        try {
            outfile  = resolve(outfile);

            let json

            try {
                json = JSON.parse(await readFile(outfile));
            } catch (err) {
                message(`${label} is a new file`, 'notice');

                await mkdir(dirname(outfile), {recursive: true });

                json = {};
            }

            json[key || versionOptions.versionKey] = (new Date()).valueOf();

            await writeFile(outfile, JSON.stringify(json, null, 4))

            message(`${label} bumped`, 'success', timeLabel);
        } catch (err) {
            message(`Error bumping ${label}`, 'error');
            message(err);

            notification({
                title:   `${label} bumping failed 🚨`,
                message: `${err.name}: ${err.message}`
            });
        }
    });
};
<commit_msg>Improve asset versioning task<commit_after>import loconfig from '../utils/config.js';
import message from '../utils/message.js';
import resolve from '../utils/template.js';
import { randomBytes } from 'node:crypto';
import {
    mkdir,
    readFile,
    writeFile,
} from 'node:fs/promises';
import {
    basename,
    dirname,
} from 'node:path';

/**
 * @typedef  {object} VersionOptions
 * @property {string|number|null} prettyPrint   - A string or number to insert
 *     white space into the output JSON string for readability purposes.
 * @property {string}             versionFormat - The version number format.
 * @property {string}             versionKey    - The JSON field name assign
 *     the version number to.
 */

/**
 * @const {VersionOptions} defaultVersionOptions     - The default shared version options.
 * @const {VersionOptions} developmentVersionOptions - The predefined version options for development.
 * @const {VersionOptions} productionVersionOptions  - The predefined version options for production.
 */
export const defaultVersionOptions = {
    prettyPrint:   4,
    versionFormat: 'timestamp',
    versionKey:    'version',
};
export const developmentVersionOptions = Object.assign({}, defaultVersionOptions);
export const productionVersionOptions  = Object.assign({}, defaultVersionOptions);

/**
 * @const {object} developmentVersionFilesArgs - The predefined `bumpVersion()` options for development.
 * @const {object} productionVersionFilesArgs  - The predefined `bumpVersion()` options for production.
 */
export const developmentVersionFilesArgs = [
    developmentVersionOptions,
];
export const productionVersionFilesArgs  = [
    productionVersionOptions,
];

/**
 * Bumps version numbers in file.
 *
 * @async
 * @param  {object} [versionOptions=null] - Customize the version options.
 *     If `null`, default production options are used.
 * @return {Promise}
 */
export default async function bumpVersion(versionOptions = null) {
    if (versionOptions == null) {
        versionOptions = productionVersionOptions;
    } else if (
        versionOptions !== developmentVersionOptions &&
        versionOptions !== productionVersionOptions
    ) {
        versionOptions = Object.assign({}, defaultVersionOptions, versionOptions);
    }

    const queue = new Map();

    loconfig.tasks.versions.forEach(({
        outfile,
        label = null,
        ...options
    }) => {
        if (!label) {
            label = basename(outfile || 'undefined');
        }

        options.pretty = (options.pretty ?? versionOptions.prettyPrint);
        options.format = (options.format ?? versionOptions.versionFormat);
        options.key    = (options.key ?? versionOptions.versionKey);

        if (queue.has(outfile)) {
            queue.get(outfile).then(() => handleBumpVersion(outfile, label, options));
        } else {
            queue.set(outfile, handleBumpVersion(outfile, label, options));
        }
    });
};

/**
 * Creates a formatted version number or string.
 *
 * @param  {string} format - The version format.
 * @return {string|number}
 */
function createVersionNumber(format) {
    let [ type, modifier ] = format.split(':');

    switch (type) {
        case 'hex':
        case 'hexadecimal':
            modifier = Number.parseInt(modifier);

            if (Number.isNaN(modifier)) {
                modifier = 6;
            }

            return randomBytes(modifier).toString('hex');

        case 'timestamp':
            return Date.now().valueOf();
    }

    throw new TypeError(
        'Expected \'format\' to be either "timestamp" or "hexadecimal"'
    );
}

/**
 * @async
 * @param  {string} outfile
 * @param  {string} label
 * @param  {object} options
 * @return {Promise}
 */
async function handleBumpVersion(outfile, label, options) {
    const timeLabel = `${label} bumped in`;
    console.time(timeLabel);

    try {
        outfile = resolve(outfile);

        let json;

        try {
            json = JSON.parse(await readFile(outfile));
        } catch (err) {
            json = {};

            message(`${label} is a new file`, 'notice');

            await mkdir(dirname(outfile), { recursive: true });
        }

        json[options.key] = createVersionNumber(options.format);

        await writeFile(outfile, JSON.stringify(json, null, options.pretty));

        message(`${label} bumped`, 'success', timeLabel);
    } catch (err) {
        message(`Error bumping ${label}`, 'error');
        message(err);

        notification({
            title:   `${label} bumping failed 🚨`,
            message: `${err.name}: ${err.message}`
        });
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var parallel = require('run-parallel');
var Buffer = require('buffer').Buffer;
var allocCluster = require('./lib/alloc-cluster.js');
var EndpointHandler = require('../endpoint-handler');

allocCluster.test('request().send() to a server', 2, function t(cluster, assert) {
    var one = cluster.channels[0];
    var two = cluster.channels[1];
    var hostOne = cluster.hosts[0];

    one.handler = EndpointHandler();

    one.handler.register('foo', function foo(req, res) {
        assert.ok(Buffer.isBuffer(req.arg2));
        assert.ok(Buffer.isBuffer(req.arg3));
        res.sendOk(req.arg2, req.arg3);
    });

    parallel({
        'bufferOp': sendRes.bind(null, two, {
            host: hostOne
        }, new Buffer('foo'), null, null),
        'stringOp': sendRes.bind(null, two, {
            host: hostOne
        }, 'foo', null, null),
        'bufferHead': sendRes.bind(null, two, {
            host: hostOne
        }, 'foo', new Buffer('abc'), null),
        'stringHead': sendRes.bind(null, two, {
            host: hostOne
        }, 'foo', 'abc', null),
        'objectHead': sendRes.bind(null, two, {
            host: hostOne
        }, 'foo', JSON.stringify({ value: 'abc' }), null),
        'nullHead': sendRes.bind(null, two, {
            host: hostOne
        }, 'foo', null, null),
        'undefinedHead': sendRes.bind(null, two, {
            host: hostOne
        }, 'foo', undefined, null),
        'bufferBody': sendRes.bind(null, two, {
            host: hostOne
        }, 'foo', null, new Buffer('abc')),
        'stringBody': sendRes.bind(null, two, {
            host: hostOne
        }, 'foo', null, 'abc'),
        'objectBody': sendRes.bind(null, two, {
            host: hostOne
        }, 'foo', null, JSON.stringify({ value: 'abc' })),
        'nullBody': sendRes.bind(null, two, {
            host: hostOne
        }, 'foo', null, null),
        'undefinedBody': sendRes.bind(null, two, {
            host: hostOne
        }, 'foo', null, undefined)
    }, function onResults(err, results) {
        assert.ifError(err);

        var peersOne = one.getPeers();
        var peersTwo = two.getPeers();

        assert.equal(peersOne.length, 1, 'one should have 1 peer');
        assert.equal(peersTwo.length, 1, 'two should have 1 peer');

        var inPeer = peersOne[0];
        if (inPeer) {
            assert.equal(inPeer.direction, 'in', 'inPeer should be in');
            assert.equal(Object.keys(inPeer.inOps).length, 0, 'inPeer should have no inOps');
            assert.equal(Object.keys(inPeer.outOps).length, 0, 'inPeer should have no outOps');
        }

        var outPeer = peersTwo[0];
        if (outPeer) {
            assert.equal(outPeer.direction, 'out', 'outPeer should be out');
            assert.equal(Object.keys(outPeer.inOps).length, 0, 'outPeer should have no inOps');
            assert.equal(Object.keys(outPeer.outOps).length, 0, 'outPeer should have no outOps');
        }

        var stringOp = results.stringOp;
        assert.ok(Buffer.isBuffer(stringOp.head));
        assert.equal(stringOp.head.length, 0);
        assert.ok(Buffer.isBuffer(stringOp.body));
        assert.equal(stringOp.body.length, 0);

        var bufferOp = results.bufferOp;
        assert.ok(Buffer.isBuffer(bufferOp.head));
        assert.equal(bufferOp.head.length, 0);
        assert.ok(Buffer.isBuffer(bufferOp.body));
        assert.equal(bufferOp.body.length, 0);

        var bufferHead = results.bufferHead;
        assert.ok(Buffer.isBuffer(bufferHead.head));
        assert.equal(String(bufferHead.head), 'abc');
        assert.ok(Buffer.isBuffer(bufferHead.body));
        assert.equal(bufferHead.body.length, 0);

        var stringHead = results.stringHead;
        assert.ok(Buffer.isBuffer(stringHead.head));
        assert.equal(String(stringHead.head), 'abc');
        assert.ok(Buffer.isBuffer(stringHead.body));
        assert.equal(stringHead.body.length, 0);

        var objectHead = results.objectHead;
        assert.ok(Buffer.isBuffer(objectHead.head));
        assert.equal(String(objectHead.head), '{"value":"abc"}');
        assert.ok(Buffer.isBuffer(objectHead.body));
        assert.equal(objectHead.body.length, 0);

        var nullHead = results.nullHead;
        assert.ok(Buffer.isBuffer(nullHead.head));
        assert.equal(String(nullHead.head), '');
        assert.ok(Buffer.isBuffer(nullHead.body));
        assert.equal(nullHead.body.length, 0);

        var undefinedHead = results.undefinedHead;
        assert.ok(Buffer.isBuffer(undefinedHead.head));
        assert.equal(String(undefinedHead.head), '');
        assert.ok(Buffer.isBuffer(undefinedHead.body));
        assert.equal(undefinedHead.body.length, 0);

        var bufferBody = results.bufferBody;
        assert.ok(Buffer.isBuffer(bufferBody.head));
        assert.equal(String(bufferBody.head), '');
        assert.ok(Buffer.isBuffer(bufferBody.body));
        assert.equal(String(bufferBody.body), 'abc');

        var stringBody = results.stringBody;
        assert.ok(Buffer.isBuffer(stringBody.head));
        assert.equal(String(stringBody.head), '');
        assert.ok(Buffer.isBuffer(stringBody.body));
        assert.equal(String(stringBody.body), 'abc');

        var objectBody = results.objectBody;
        assert.ok(Buffer.isBuffer(objectBody.head));
        assert.equal(String(objectBody.head), '');
        assert.ok(Buffer.isBuffer(objectBody.body));
        assert.equal(String(objectBody.body), '{"value":"abc"}');

        var nullBody = results.nullBody;
        assert.ok(Buffer.isBuffer(nullBody.head));
        assert.equal(String(nullBody.head), '');
        assert.ok(Buffer.isBuffer(nullBody.body));
        assert.equal(String(nullBody.body), '');

        var undefinedBody = results.undefinedBody;
        assert.ok(Buffer.isBuffer(undefinedBody.head));
        assert.equal(String(undefinedBody.head), '');
        assert.ok(Buffer.isBuffer(undefinedBody.body));
        assert.equal(String(undefinedBody.body), '');

        assert.end();
    });
});

/*eslint max-params: [2, 6] */
/*jshint maxparams: 6 */
function sendRes(channel, opts, op, h, b, cb) {
    channel
        .request(opts)
        .send(op, h, b, onResult);

    function onResult(err, res) {
        cb(err, {
            head: res.arg2,
            body: res.arg3
        });
    }
}
<commit_msg>test/send: factor out case structure<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var parallel = require('run-parallel');
var Buffer = require('buffer').Buffer;
var extend = require('xtend');
var allocCluster = require('./lib/alloc-cluster.js');
var EndpointHandler = require('../endpoint-handler');

var Cases = [

    {
        name: 'bufferOp',
        op: Buffer('foo'),
        reqHead: null,
        reqBody: null,
        resHead: '',
        resBody: ''
    },

    {
        name: 'stringOp',
        op: 'foo',
        reqHead: null,
        reqBody: null,
        resHead: '',
        resBody: ''
    },

    {
        name: 'bufferHead',
        op: 'foo',
        reqHead: Buffer('abc'),
        reqBody: null,
        resHead: 'abc',
        resBody: ''
    },

    {
        name: 'stringHead',
        op: 'foo',
        reqHead: 'abc',
        reqBody: null,
        resHead: 'abc',
        resBody: ''
    },

    {
        name: 'objectHead',
        op: 'foo',
        reqHead: JSON.stringify({value: 'abc'}),
        reqBody: null,
        resHead: '{"value":"abc"}',
        resBody: ''
    },

    {
        name: 'nullHead',
        op: 'foo',
        reqHead: null,
        reqBody: null,
        resHead: '',
        resBody: ''
    },

    {
        name: 'undefinedHead',
        op: 'foo',
        reqHead: undefined,
        reqBody: null,
        resHead: '',
        resBody: ''
    },

    {
        name: 'bufferBody',
        op: 'foo',
        reqHead: null,
        reqBody: Buffer('abc'),
        resHead: '',
        resBody: 'abc'
    },

    {
        name: 'stringBody',
        op: 'foo',
        reqHead: null,
        reqBody: 'abc',
        resHead: '',
        resBody: 'abc'
    },

    {
        name: 'objectBody',
        op: 'foo',
        reqHead: null,
        reqBody: JSON.stringify({value: 'abc'}),
        resHead: '',
        resBody: '{"value":"abc"}'
    },

    {
        name: 'nullBody',
        op: 'foo',
        reqHead: null,
        reqBody: null,
        resHead: '',
        resBody: ''
    },

    {
        name: 'undefinedBody',
        op: 'foo',
        reqHead: null,
        reqBody: undefined,
        resHead: '',
        resBody: ''
    },

];

allocCluster.test('request().send() to a server', 2, function t(cluster, assert) {
    var one = cluster.channels[0];
    var two = cluster.channels[1];
    var hostOne = cluster.hosts[0];

    one.handler = EndpointHandler();

    one.handler.register('foo', function foo(req, res) {
        assert.ok(Buffer.isBuffer(req.arg2));
        assert.ok(Buffer.isBuffer(req.arg3));
        res.sendOk(req.arg2, req.arg3);
    });

    parallel(Cases.map(function eachTestCase(testCase) {
        testCase = extend({
            channel: two,
            opts: {host: hostOne},
        }, testCase);
        return sendTest(testCase, assert);
    }), function onResults(err) {
        assert.ifError(err);

        var peersOne = one.getPeers();
        var peersTwo = two.getPeers();

        assert.equal(peersOne.length, 1, 'one should have 1 peer');
        assert.equal(peersTwo.length, 1, 'two should have 1 peer');

        var inPeer = peersOne[0];
        if (inPeer) {
            assert.equal(inPeer.direction, 'in', 'inPeer should be in');
            assert.equal(Object.keys(inPeer.inOps).length, 0, 'inPeer should have no inOps');
            assert.equal(Object.keys(inPeer.outOps).length, 0, 'inPeer should have no outOps');
        }

        var outPeer = peersTwo[0];
        if (outPeer) {
            assert.equal(outPeer.direction, 'out', 'outPeer should be out');
            assert.equal(Object.keys(outPeer.inOps).length, 0, 'outPeer should have no inOps');
            assert.equal(Object.keys(outPeer.outOps).length, 0, 'outPeer should have no outOps');
        }

        assert.end();
    });
});

function sendTest(testCase, assert) {
    return function runSendTest(callback) {
        testCase.channel
            .request(testCase.opts)
            .send(testCase.op, testCase.reqHead, testCase.reqBody, onResult);
        function onResult(err, res) {
            var head = res.arg2;
            var body = res.arg3;
            assert.ifError(err, testCase.name + ': no result error');
            if (!err) {
                assert.ok(Buffer.isBuffer(head));
                assert.ok(Buffer.isBuffer(body));
                assert.equal(head ? String(head) : head, testCase.resHead);
                assert.equal(body ? String(body) : body, testCase.resBody);
            }
            callback();
        }
    };
}
<|endoftext|>


<commit_before>define(["jquery", "d3", "app/torus-array", "app/rle-parser", "app/goodies"], function(
        $, d3, TorusArray, RunLengthEncodedParser) {

    function Life(initialTorus) {
        /*
         * Represents a Life field.
         */

        // overall configuration
        var itemSize = 15,
            cellSize = itemSize - 1,
            margin = {
                top: 0,
                left: 0,
                right: 0,
                bottom: 0
            };

        // instance variables
        this.stepTime = 100;

        if(typeof initialTorus == "undefined") {
            // balance number of cells / width to fill screen
            this.rows = Math.floor(window.height / itemSize);
            this.cols = Math.floor(window.width / itemSize);
            this.torus = new TorusArray(this.rows, this.cols);
            this.markedCells = [];
            this.cellsAlive = 0;
        }
        else {
            this.torus = initialTorus;
            this.rows = this.torus.rows;
            this.cols = this.torus.cols;
            this.markedCells = [];
            for(var i = 0; i < this.torus.rows; i++) {
                for(var j = 0; j < this.torus.cols; j++) {
                    this.markForScan(i, j, 'add');
                    if(this.torus.get(i, j) == 1) {
                        this.cellsAlive++;
                    }
                }
            }
        }

//        this.torusQueue = [
//            new TorusArray(this.rows, this.cols),
//            new TorusArray(this.rows, this.cols)
//        ];
//        this.torus = this.torusQueue[0];

        this.gameTimer = undefined;
        this.generation = 0;
        this.id = Math.random();

        this.initGrid = function() {
            var width = (this.cols * itemSize) + margin.right + margin.left;
            var height = (this.rows * itemSize) + margin.top + margin.bottom;

            var svg = d3.select('[role="fieldmap"]');

            // all cells background
            svg.append('rect')
                .attr('transform',
                    'translate(' + (margin.left - 1) + ',' + (margin.top - 1) + ')')
                .attr('width', width - margin.left - margin.right + 1)
                .attr('height', height - margin.top - margin.bottom + 1)
                .attr('fill', '#ccc');

            var fieldmap = svg
                .attr('width', width)
                .attr('height', height)
                .append('g') // group for all cells
                .attr('role', 'field')
                .attr('transform',
                    'translate(' + (margin.left) + ',' + (margin.top) + ')');

            // add rows
            var rows = fieldmap.selectAll('g')
                .data(this.torus.toArray())
                .enter()
                .append('g')
                // shift each row from top by its number
                .attr('transform', function (d, i) {
                    return 'translate(0, ' + itemSize * i + ')';
                });

            // for each row draw cells
            rows.selectAll()
                .data(function (d) {
                    return d;
                })
                .enter()
                .append('rect')
                .attr('type', 'cell')
                .attr('width', cellSize)
                .attr('height', cellSize)
                .attr('fill', function (d) {
                    return d == 1 ? '#000' : '#fff';
                })
                .attr('x', function (d, i) {
                    return itemSize * i;
                });

            // cell actions
            var cells = svg.selectAll('rect[type="cell"]');

            var instance = this;
            cells.on('click', function(d, i) {
                instance.toggleCell(this, i);
            });

            cells.on('mouseover', function () {
                d3.select(this).attr('opacity', .35);
            });
            cells.on('mouseout', function () {
                d3.select(this).attr('opacity', 1);
            });

            console.log("life.js: grid initialized from",
                        initialTorus || "default torus");
        };

        this.initGrid();
    } // end of life

    Life.fromRLEFile = function(fileData) {
        function getRLEData(parsedData, dataType) {
            for(var i = 0; i < parsedData.length; i++) {
                if(parsedData[i].type == dataType) {
                    var data = parsedData[i];
                    delete data["type"];
                    return data;
                }
            }
        }

        var parsedData = RunLengthEncodedParser.parse(fileData);
        var lines = getRLEData(parsedData, "lines");
        var header = getRLEData(parsedData, "header");
        var torus = TorusArray.fromRLEData(header, lines);
        return new Life(torus);
    };

    Life.prototype.updateGrid = function () {
        /*
         * Updates the grid.
         */
        var startTime = performance.now();
        var grid = this.torus.toArray();
        var gridItems = d3.merge(grid);

        var svg = d3.select('[role="fieldmap"]');
        svg.selectAll('rect[type="cell"]')
            .data(gridItems)
            .transition()
            .duration(this.stepTime / 2)
            .attr('fill', function (d) {
                return d == 1 ? '#000' : '#fff';
            });

        // metrics
        var endTime = performance.now();
        $(this).trigger('updateGridFinished', [endTime - startTime]);
        console.log("updated grid", gridItems);
    };

    Life.prototype.markForScan = function (i, j, operation) {
        /*
         * Adds cell for scan on the next evolution step.
         */
        var candidates = this.torus.neighbors(i, j);
        candidates.push([i, j]);

        var instance = this;
        candidates = candidates.map(function (n) {
            return instance.torus.absoluteIndex(n[0], n[1]);
        });

        for (var k = 0; k < candidates.length; k++) {
            var index = this.markedCells.indexOf(candidates[k]);
            if (index == -1) {
                if (operation == 'add') {
                    this.markedCells.push(candidates[k]);
                }
            }
            else {
                if(operation == 'remove') {
                    this.markedCells.splice(index, 1);
                }
            }
        }
    };

    Life.prototype.toggleCell = function(cell, absoluteIndex) {
        /*
         * Changes single cell state.
         */

        var torusIndex = this.torus.arrayIndex(absoluteIndex);
        var row = torusIndex[0],
            col = torusIndex[1];

        var currentValue = this.torus.get(row, col);
        var newValue = currentValue == 1 ? 0 : 1;
        var operation = newValue == 1 ? 'add' : 'remove';

        d3.select(cell).attr('fill', newValue == 1 ? '#000' : '#fff');
        this.torus.set(row, col, newValue);
        this.markForScan(row, col, operation);
    };

    Life.prototype.evolve = function() {
        /*
         * Performs one step of evolution process.
         * Returns number of cells to scan on the next step.
         */
        if(this.markedCells.length == 0) {
            console.log("life.js: no cells marked for scan");
            return 0;
        }

        var startTime = performance.now();

        var nextTorus = new TorusArray(this.torus.rows, this.torus.cols);

        //var nextTorus = this.torusQueue.shift();

        var cellsSeen = 0,
            cellsAlive = 0;

        function checkCell(instance, i, j) {
            var neighbors = instance.torus.neighbors(i, j);
            var neighborsState = neighbors.map(function (currValue) {
                return instance.torus.get(currValue[0], currValue[1]);
            });

            var population = neighborsState.reduce(function (prevValue, currValue) {
                return prevValue + currValue;
            });

            // new born
            if (instance.torus.get(i, j) == 0 && population == 3) {
                nextTorus.set(i, j, 1);
                instance.markForScan(i, j, 'add');
                cellsAlive++;
            }

            if (instance.torus.get(i, j) == 1) {
                // loneliness or overpopulation
                if (population < 2 || population > 3) {
                    nextTorus.set(i, j, 0);
                }
                else {
                    // lucky cell
                    nextTorus.set(i, j, 1);
                    instance.markForScan(i, j, 'add');
                    cellsAlive++;
                }
            }
            cellsSeen++;
        }

        // scan only marked
        var markedCells = this.markedCells;
        this.markedCells = [];
        for(var k = 0; k < markedCells.length; k++) {
            var cell = this.torus.arrayIndex(markedCells[k]);
            checkCell(this, cell[0], cell[1]);
        }

        // swap torus
        //this.torusQueue.push(this.torus);
        this.torus = nextTorus;
        this.cellsAlive = cellsAlive;
        this.generation++;

        // metrics
        var endTime = performance.now();
        $(this).trigger(
            'evolutionStepFinished', [
            endTime - startTime,
            this.generation,
            this.cellsAlive
        ]);

        this.updateGrid();
        console.log("life.js:",
                    "cells seen", cellsSeen,
                    "cellsAlive", cellsAlive,
                    "cells to see next round", this.markedCells.length);

        return this.markedCells;
    };

    return Life;
});
<commit_msg>understanding d3.js<commit_after>define(["jquery", "d3", "app/torus-array", "app/rle-parser", "app/goodies"], function(
        $, d3, TorusArray, RunLengthEncodedParser) {

    function Life(initialTorus) {
        /*
         * Represents a Life field.
         */

        // overall configuration
        var itemSize = 15,
            cellSize = itemSize - 1,
            margin = {
                top: 0,
                left: 0,
                right: 0,
                bottom: 0
            };

        // instance variables
        this.stepTime = 100;

        if(typeof initialTorus == "undefined") {
            // balance number of cells / width to fill screen
            this.rows = Math.floor(window.height / itemSize);
            this.cols = Math.floor(window.width / itemSize);
            this.torus = new TorusArray(this.rows, this.cols);
            this.markedCells = [];
            this.cellsAlive = 0;
        }
        else {
            this.torus = initialTorus;
            this.rows = this.torus.rows;
            this.cols = this.torus.cols;
            this.markedCells = [];
            for(var i = 0; i < this.torus.rows; i++) {
                for(var j = 0; j < this.torus.cols; j++) {
                    this.markedCells.push(
                        this.torus.absoluteIndex(i, j)
                    );

                    if(this.torus.get(i, j) == 1) {
                        this.cellsAlive++;
                    }
                }
            }
        }

//        this.torusQueue = [
//            new TorusArray(this.rows, this.cols),
//            new TorusArray(this.rows, this.cols)
//        ];
//        this.torus = this.torusQueue[0];

        this.gameTimer = undefined;
        this.generation = 0;
        this.id = Math.random();

        this.initGrid = function() {
            var width = (this.cols * itemSize) + margin.right + margin.left;
            var height = (this.rows * itemSize) + margin.top + margin.bottom;

            var svg = d3.select('[role="fieldmap"]');

            // all cells background
            svg.append('rect')
                .attr('transform',
                    'translate(' + (margin.left - 1) + ',' + (margin.top - 1) + ')')
                .attr('width', width - margin.left - margin.right + 1)
                .attr('height', height - margin.top - margin.bottom + 1)
                .attr('fill', '#ccc');

            var fieldmap = svg
                .attr('width', width)
                .attr('height', height)
                .append('g') // group for all cells
                .attr('role', 'field')
                .attr('transform',
                    'translate(' + (margin.left) + ',' + (margin.top) + ')');

            // add rows
            var rows = fieldmap.selectAll('g')
                .data(this.torus.toArray());

            console.log("rows", rows);

            rows.enter()
                .append('g')
                // shift each row from top by its number
                .attr('transform', function (d, i) {
                    return 'translate(0, ' + itemSize * i + ')';
                });

            rows.exit().remove();

            // for each row draw cells
            var allRows = rows.selectAll()
                .data(function (d) {
                    return d;
                });

            console.log("all rows", allRows);

            allRows.enter()
                .append('rect')
                .attr('type', 'cell')
                .attr('width', cellSize)
                .attr('height', cellSize)
                .attr('fill', function (d) {
                    return d == 1 ? '#000' : '#fff';
                })
                .attr('x', function (d, i) {
                    return itemSize * i;
                });

            allRows.exit().remove();

            // cell actions
            var cells = svg.selectAll('rect[type="cell"]');

            var instance = this;
            cells.on('click', function(d, i) {
                instance.toggleCell(this, i);
            });

            cells.on('mouseover', function () {
                d3.select(this).attr('opacity', .35);
            });
            cells.on('mouseout', function () {
                d3.select(this).attr('opacity', 1);
            });

            console.log("life.js: grid initialized from",
                        initialTorus || "default torus");
        };

        this.initGrid();
    } // end of life

    Life.fromRLEFile = function(fileData) {
        function getRLEData(parsedData, dataType) {
            for(var i = 0; i < parsedData.length; i++) {
                if(parsedData[i].type == dataType) {
                    var data = parsedData[i];
                    delete data["type"];
                    return data;
                }
            }
        }

        var parsedData = RunLengthEncodedParser.parse(fileData);
        var lines = getRLEData(parsedData, "lines");
        var header = getRLEData(parsedData, "header");
        var torus = TorusArray.fromRLEData(header, lines);
        return new Life(torus);
    };

    Life.prototype.updateGrid = function () {
        /*
         * Updates the grid.
         */
        var startTime = performance.now();
        var grid = this.torus.toArray();
        var gridItems = d3.merge(grid);

        var svg = d3.select('[role="fieldmap"]');
        console.log("elements under update",
                    svg.selectAll('rect[type="cell"]'),
                    "torus", gridItems.length);
        svg.selectAll('rect[type="cell"]')
            .data(gridItems)
            .transition()
            .duration(this.stepTime / 2)
            .attr('fill', function (d) {
                return d == 1 ? '#000' : '#fff';
            });

        // metrics
        var endTime = performance.now();
        $(this).trigger('updateGridFinished', [endTime - startTime]);
    };

    Life.prototype.markForScan = function (i, j, operation) {
        /*
         * Adds cell for scan on the next evolution step.
         */
        var candidates = this.torus.neighbors(i, j);
        candidates.push([i, j]);

        var instance = this;
        candidates = candidates.map(function (n) {
            return instance.torus.absoluteIndex(n[0], n[1]);
        });

        for (var k = 0; k < candidates.length; k++) {
            var index = this.markedCells.indexOf(candidates[k]);
            if (index == -1) {
                if (operation == 'add') {
                    this.markedCells.push(candidates[k]);
                }
            }
            else {
                if(operation == 'remove') {
                    this.markedCells.splice(index, 1);
                }
            }
        }
    };

    Life.prototype.toggleCell = function(cell, absoluteIndex) {
        /*
         * Changes single cell state.
         */

        var torusIndex = this.torus.arrayIndex(absoluteIndex);
        var row = torusIndex[0],
            col = torusIndex[1];

        var currentValue = this.torus.get(row, col);
        var newValue = currentValue == 1 ? 0 : 1;
        var operation = newValue == 1 ? 'add' : 'remove';

        d3.select(cell).attr('fill', newValue == 1 ? '#000' : '#fff');
        this.torus.set(row, col, newValue);
        this.markForScan(row, col, operation);
    };

    Life.prototype.evolve = function() {
        /*
         * Performs one step of evolution process.
         * Returns number of cells to scan on the next step.
         */
        if(this.markedCells.length == 0) {
            console.log("life.js: no cells marked for scan");
            return 0;
        }

        var startTime = performance.now();

        var nextTorus = new TorusArray(this.torus.rows, this.torus.cols);

        //var nextTorus = this.torusQueue.shift();

        var cellsSeen = 0,
            cellsAlive = 0;

        function checkCell(instance, i, j) {
            var neighbors = instance.torus.neighbors(i, j);
            var neighborsState = neighbors.map(function (currValue) {
                return instance.torus.get(currValue[0], currValue[1]);
            });

            var population = neighborsState.reduce(function (prevValue, currValue) {
                return prevValue + currValue;
            });

            // new born
            if (instance.torus.get(i, j) == 0 && population == 3) {
                nextTorus.set(i, j, 1);
                instance.markForScan(i, j, 'add');
                cellsAlive++;
            }

            if (instance.torus.get(i, j) == 1) {
                // loneliness or overpopulation
                if (population < 2 || population > 3) {
                    nextTorus.set(i, j, 0);
                }
                else {
                    // lucky cell
                    nextTorus.set(i, j, 1);
                    instance.markForScan(i, j, 'add');
                    cellsAlive++;
                }
            }
            cellsSeen++;
        }

        // scan only marked
        var markedCells = this.markedCells;
        this.markedCells = [];
        for(var k = 0; k < markedCells.length; k++) {
            var cell = this.torus.arrayIndex(markedCells[k]);
            checkCell(this, cell[0], cell[1]);
        }

        // swap torus
        //this.torusQueue.push(this.torus);
        this.torus = nextTorus;
        this.cellsAlive = cellsAlive;
        this.generation++;

        // metrics
        var endTime = performance.now();
        $(this).trigger(
            'evolutionStepFinished', [
            endTime - startTime,
            this.generation,
            this.cellsAlive
        ]);

        this.updateGrid();
        console.log("life.js:",
                    "cells seen", cellsSeen,
                    "cellsAlive", cellsAlive,
                    "cells to see next round", this.markedCells.length);

        return this.markedCells;
    };

    return Life;
});
<|endoftext|>


<commit_before>/* 	Variation Database Javascript methods

    Nikhil Anand <nikhil@mantralay.org>
    Sean Ephraim <sean.ephraim@gmail.com>
*/

function getParameterByName(name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.search);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

function _otoscope_db_set_column_cookie($index,$colcount) {
	var cookieval = '', i = 0;
	for (i=1; i <= $colcount; i++) {
		cookieval += ( i == $index ) ? 0 : 1;
	};
}

// Make each table sortable and show a bubble for the "Variant type" column
function tablesort() {
  $('#mutation-tables table').each(function(){
  	$(this).tablesorter({
  	  widgets: ['zebra'],
  	  headers: { 0: { sorter: false } }
  	 });
  });
}

$(document).ready(function(){

  // If this is a first-time visit, and NOT a gene page, collapse the glossary
  var URL = $(location).attr('href');
  if($.cookie("mdb_visited") == null && (URL.indexOf("letter") == -1)) {
      $("#sidebar-sorters-glossary").hide();
      $.cookie("mdb_visited", "yes", {expires: 7});
  } else {
      $("#sidebar-sorters-glossary").show();
  }

  /* S I D E B A R */

	// Check sidebar collapsed state
	if($.cookie("sidebar-sorters-information")) {$("#sidebar-sorters-information").hide();}
	if($.cookie("sidebar-sorters-glossary"))    {$("#sidebar-sorters-glossary").hide();}

	// Collapse fieldsets and remember their collapsed state
	$('.sidebar-collapsible legend').click(function(){
		var sidebar_id = $(this).closest('fieldset').children('div').attr('id');
		if($.cookie(sidebar_id) == null) {
			$(this).closest('fieldset').children('div').hide();
			$.cookie(sidebar_id, "1");
		} else {
			$(this).closest('fieldset').children('div').show();
			$.cookie(sidebar_id, null);
		}
	});

  /* V I E W */

  tablesort();

  // Load variations when gene name is clicked
  $.ajaxSetup ({
    cache: false
  });
	$('.genename').click(function(){
    var variations_table = $(this).parent().children(".variant-list-container");
    $(this).toggleClass('collapsed');
    if (!$(this).hasClass("loaded")) {
      // Load and display variations table for the first time
      $(this).addClass("loaded");
      $("#table-"+$(this).attr('id')).toggle();
      var loading_modal = '' +
        '
' +
        '
' +
        '        ' +
        '
' +
        '
';

      //Rob Marini Edits here for searchPos functionality....my edits will preserve legacy variant by id look up.
      var parts = window.location.search.substr(1).split("=");
      if(parts[0].localeCompare('searchStr') == 0){
//      var $_GET = {};
//      for (var i = 0; i < parts.length; i++) {
//          var temp = parts[i].split("=");
//          $_GET[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);
//      }

    	  var loadURL = "/geneVariantPos/" + parts[1]; //providing the position searched here
//    	  var loadURL = "../gene/"+parts[1];
//    	  var loadURL = "../gene/" + this.id;
    	  //end of Rob Marini Edits (includes this if-structure. Originally only the else clause existed without the if-structure
      } else {
	      var loadURL = "../gene/"+this.id; //this.id is the gene name
      }

	  alert(loadURL);

      //variations_table.html(loading_modal).load(loadURL);
      variations_table.html(loading_modal).load(loadURL, function(){
        tablesort();
      });
    }
    else if (variations_table.css('display') == 'none') {
      // Show variations table if hidden and already loaded
      variations_table.show();
    }
    else {
      // Hide variations table if already loaded
      variations_table.hide();
    }
	});

	// Modal popup for variant data
	$('.showinfo .showinfo-popup').live('click', function(){
	  var parent_id = $(this).closest("tr").attr("id").substring(9); // 9 = "mutation-"
    var src='../variant/' + parent_id;
    var viewport_height =  $(window).height();
		$.modal('', {
    	containerCss:{
    	  containerId: 'info-container',
    		backgroundColor:"#fff",
    		borderColor:"#fff",
    		height:650,
    		padding:0,
        width:670
    	},
      top:10,
    	opacity:90,
    	overlayClose:true
    });
    return false;
	});

	// Contact popup
	$('.contact-popup').click(function(){
		$("#section-contact").modal({opacity:90,overlayClose:true});
	});
  // Contact CBCB is unchecked by default
  $("#contact-cbcb").prop("checked", false);
  // Automatically Contact CBCB on click
	$('.contact-cbcb').click(function(){
    $("#contact-cbcb").prop("checked", true);
	});

	// Handle contact form submission
	$('#contact-submit').click(function(){
		var hasError = false;
		var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;

		// Check name
		if (!$("#contact-name").val()) {
			hasError = true;
			$("#contact-name-error").text("Please enter your name");
			$("#contact-name-error").slideDown();
		} else if($("#contact-name").val().length < 3){
			hasError = true;
			$("#contact-name-error").text("We really need a longer name...");
			$("#contact-name-error").slideDown();
		} else {
			$("#contact-name-error").slideUp();
		}

		// Check email
		if (!filter.test($("#contact-email").val())) {
			hasError = true;
			$("#contact-email-error").text("Please enter a valid email address");
			$("#contact-email-error").slideDown();
		} else {
			$("#contact-email-error").slideUp();
		}

		// Check comments
		if (!$("#contact-comments").val()) {
			hasError = true;
			$("#contact-comments-error").text("Please enter your questions or comments");
			$("#contact-comments-error").slideDown();
		} else if($("#contact-comments").val().length < 10){
			hasError = true;
			$("#contact-comments-error").text("You surely have something more to add...");
			$("#contact-comments-error").slideDown();
		} else {
			$("#contact-comments-error").slideUp();
		}

		// Submit form
		if (hasError == false) {
      document.getElementById("section-contact").submit();
		}
	});

	/* Help page */
  $('#content-help .float-left' ).shadow('raised');
  $('#content-help .float-right').shadow('raised');

  /* Variant view (small) */
  // Show tooltips
  $("#frequency-small div").each(function(){
      $(this).tipsy({
        fallback: $(this).children('strong').text(),
        gravity:'s'
      });
  });

  // Add description to paragraph above on click
  $("#frequency-small table td div").click(function(){
      $('#frequency-description').text($(this).children('strong').text());
  });

  /* Close dialoge boxes */
  $(".close").click(function(){
    $(".close").parent().hide();
  });

  /* Show email success message */
  if (getParameterByName('success') == 1) {
    $(".success").show();
  }

});
<commit_msg>just gonna hardcode to see if that works<commit_after>/* 	Variation Database Javascript methods

    Nikhil Anand <nikhil@mantralay.org>
    Sean Ephraim <sean.ephraim@gmail.com>
*/

function getParameterByName(name)
{
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.search);
  if(results == null)
    return "";
  else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}

function _otoscope_db_set_column_cookie($index,$colcount) {
	var cookieval = '', i = 0;
	for (i=1; i <= $colcount; i++) {
		cookieval += ( i == $index ) ? 0 : 1;
	};
}

// Make each table sortable and show a bubble for the "Variant type" column
function tablesort() {
  $('#mutation-tables table').each(function(){
  	$(this).tablesorter({
  	  widgets: ['zebra'],
  	  headers: { 0: { sorter: false } }
  	 });
  });
}

$(document).ready(function(){

  // If this is a first-time visit, and NOT a gene page, collapse the glossary
  var URL = $(location).attr('href');
  if($.cookie("mdb_visited") == null && (URL.indexOf("letter") == -1)) {
      $("#sidebar-sorters-glossary").hide();
      $.cookie("mdb_visited", "yes", {expires: 7});
  } else {
      $("#sidebar-sorters-glossary").show();
  }

  /* S I D E B A R */

	// Check sidebar collapsed state
	if($.cookie("sidebar-sorters-information")) {$("#sidebar-sorters-information").hide();}
	if($.cookie("sidebar-sorters-glossary"))    {$("#sidebar-sorters-glossary").hide();}

	// Collapse fieldsets and remember their collapsed state
	$('.sidebar-collapsible legend').click(function(){
		var sidebar_id = $(this).closest('fieldset').children('div').attr('id');
		if($.cookie(sidebar_id) == null) {
			$(this).closest('fieldset').children('div').hide();
			$.cookie(sidebar_id, "1");
		} else {
			$(this).closest('fieldset').children('div').show();
			$.cookie(sidebar_id, null);
		}
	});

  /* V I E W */

  tablesort();

  // Load variations when gene name is clicked
  $.ajaxSetup ({
    cache: false
  });
	$('.genename').click(function(){
    var variations_table = $(this).parent().children(".variant-list-container");
    $(this).toggleClass('collapsed');
    if (!$(this).hasClass("loaded")) {
      // Load and display variations table for the first time
      $(this).addClass("loaded");
      $("#table-"+$(this).attr('id')).toggle();
      var loading_modal = '' +
        '
' +
        '
' +
//        '        ' +
        '        ' +
        '
' +
        '
';

      //Rob Marini Edits here for searchPos functionality....my edits will preserve legacy variant by id look up.
      var parts = window.location.search.substr(1).split("=");
      if(parts[0].localeCompare('searchStr') == 0){
//      var $_GET = {};
//      for (var i = 0; i < parts.length; i++) {
//          var temp = parts[i].split("=");
//          $_GET[decodeURIComponent(temp[0])] = decodeURIComponent(temp[1]);
//      }

    	  var loadURL = "http://cordova-dev.eng.uiowa.edu/cordova_rjm/geneVariantPos/" + parts[1]; //providing the position searched here
//    	  var loadURL = "../gene/"+parts[1];
//    	  var loadURL = "../gene/" + this.id;
    	  //end of Rob Marini Edits (includes this if-structure. Originally only the else clause existed without the if-structure
      } else {
	      var loadURL = "../gene/"+this.id; //this.id is the gene name
      }

	  alert(loadURL);

      //variations_table.html(loading_modal).load(loadURL);
      variations_table.html(loading_modal).load(loadURL, function(){
        tablesort();
      });
    }
    else if (variations_table.css('display') == 'none') {
      // Show variations table if hidden and already loaded
      variations_table.show();
    }
    else {
      // Hide variations table if already loaded
      variations_table.hide();
    }
	});

	// Modal popup for variant data
	$('.showinfo .showinfo-popup').live('click', function(){
	  var parent_id = $(this).closest("tr").attr("id").substring(9); // 9 = "mutation-"
    var src='../variant/' + parent_id;
    var viewport_height =  $(window).height();
		$.modal('', {
    	containerCss:{
    	  containerId: 'info-container',
    		backgroundColor:"#fff",
    		borderColor:"#fff",
    		height:650,
    		padding:0,
        width:670
    	},
      top:10,
    	opacity:90,
    	overlayClose:true
    });
    return false;
	});

	// Contact popup
	$('.contact-popup').click(function(){
		$("#section-contact").modal({opacity:90,overlayClose:true});
	});
  // Contact CBCB is unchecked by default
  $("#contact-cbcb").prop("checked", false);
  // Automatically Contact CBCB on click
	$('.contact-cbcb').click(function(){
    $("#contact-cbcb").prop("checked", true);
	});

	// Handle contact form submission
	$('#contact-submit').click(function(){
		var hasError = false;
		var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;

		// Check name
		if (!$("#contact-name").val()) {
			hasError = true;
			$("#contact-name-error").text("Please enter your name");
			$("#contact-name-error").slideDown();
		} else if($("#contact-name").val().length < 3){
			hasError = true;
			$("#contact-name-error").text("We really need a longer name...");
			$("#contact-name-error").slideDown();
		} else {
			$("#contact-name-error").slideUp();
		}

		// Check email
		if (!filter.test($("#contact-email").val())) {
			hasError = true;
			$("#contact-email-error").text("Please enter a valid email address");
			$("#contact-email-error").slideDown();
		} else {
			$("#contact-email-error").slideUp();
		}

		// Check comments
		if (!$("#contact-comments").val()) {
			hasError = true;
			$("#contact-comments-error").text("Please enter your questions or comments");
			$("#contact-comments-error").slideDown();
		} else if($("#contact-comments").val().length < 10){
			hasError = true;
			$("#contact-comments-error").text("You surely have something more to add...");
			$("#contact-comments-error").slideDown();
		} else {
			$("#contact-comments-error").slideUp();
		}

		// Submit form
		if (hasError == false) {
      document.getElementById("section-contact").submit();
		}
	});

	/* Help page */
  $('#content-help .float-left' ).shadow('raised');
  $('#content-help .float-right').shadow('raised');

  /* Variant view (small) */
  // Show tooltips
  $("#frequency-small div").each(function(){
      $(this).tipsy({
        fallback: $(this).children('strong').text(),
        gravity:'s'
      });
  });

  // Add description to paragraph above on click
  $("#frequency-small table td div").click(function(){
      $('#frequency-description').text($(this).children('strong').text());
  });

  /* Close dialoge boxes */
  $(".close").click(function(){
    $(".close").parent().hide();
  });

  /* Show email success message */
  if (getParameterByName('success') == 1) {
    $(".success").show();
  }

});
<|endoftext|>


<commit_before>import _ from 'lodash';
import Scroll from 'react-scroll';

export const handleMessageUtility = (state, message, socket) => {
    const newState = _.cloneDeep(state);

    if (message.type instanceof Error) {
        newState.submitError = message.type.message;
        return newState;
    }

    // no error -> handle message
    newState.submitError = null;

    if (message.type === 'nick') {
        socket.emit('SET_NAME', message.args.join(' '));
    }
    if (message.type === 'oops') {
        const lastMessageId = newState.messageIds[newState.messageIds.length - 1];
        if (lastMessageId) {
            newState.messages.splice(newState.messages.findIndex((message) => message.id === lastMessageId), 1);
            socket.emit('REMOVE_MESSAGE', lastMessageId);
            newState.messageIds.pop();
        }

    }
    else if (message.type === 'countdown') {
        socket.emit('COUNTDOWN', message.args);
    }
    else if (message.type === 'fadelast') {
        // client-side only
        const lastMessageId = newState.messageIds[newState.messageIds.length - 1];

        if (lastMessageId) {
            const lastMessage = newState.messages.findIndex((message) => message.id === lastMessageId);
            lastMessage.css.fontSize = '1.1em';
            // better than css filters for cross-browser support
            lastMessage.css.color = 'hsl(0, 100%, 10%)'; //
        }
    }
    else if (message.type === 'plain' || message.type === 'think') {
        // normal message (eventually with styling)
        let styles = {};
        let content = message.content;

        if (message.type === 'think') {
            styles.color = '#2f4f4f';
            content = message.args.join(' ');
        }

        const id = new Date().getUTCMilliseconds();
        const newMessage = {
            id,
            content,
            author: 'me',
            css: styles,
            sending: true,
        };
        newState.messageIds.push(id);

        newState.messages.push(newMessage);
        newState.lastMessageSent = false;

        // notify WS
        socket.emit('INCOMING_MESSAGE', newMessage);
    }

    Scroll.animateScroll.scrollToBottom();

    return newState;
};
<commit_msg>fadelast+highlight commands (complete) - session paused<commit_after>import _ from 'lodash';
import Scroll from 'react-scroll';

export const handleMessageUtility = (state, message, socket) => {
    const newState = _.cloneDeep(state);

    if (message.type instanceof Error) {
        newState.submitError = message.type.message;
        return newState;
    }

    // no error -> handle message
    newState.submitError = null;

    if (message.type === 'nick') {
        socket.emit('SET_NAME', message.args.join(' '));
    }
    if (message.type === 'oops') {
        const lastMessageId = newState.messageIds[newState.messageIds.length - 1];
        if (lastMessageId) {
            newState.messages.splice(newState.messages.findIndex((message) => message.id === lastMessageId), 1);
            socket.emit('REMOVE_MESSAGE', lastMessageId);
            newState.messageIds.pop();
        }

    }
    else if (message.type === 'countdown') {
        socket.emit('COUNTDOWN', message.args);
    }
    else if (message.type === 'fadelast') {
        // client-side only
        const lastMessageId = newState.messageIds[newState.messageIds.length - 1];

        if (lastMessageId) {
            const lastMessage = newState.messages.find((message) => message.id === lastMessageId);

            if (lastMessage) {
                lastMessage.css.opacity = '0.1';
            }
        }
    }
    else if (message.type === 'plain' || message.type === 'think' || message.type === 'highlight') {
        // normal message (eventually with styling)
        let styles = {};
        let content = message.content;

        if (message.type === 'think') {
            styles.color = '#2f4f4f';
            content = message.args.join(' ');
        }

        if (message.type === 'highlight') {
            styles.fontSize = '1.1em';
            styles.filter = 'brightness(90%)';
            content = message.args.join(' ');
        }

        const id = new Date().getUTCMilliseconds();
        const newMessage = {
            id,
            content,
            author: 'me',
            css: styles,
            sending: true,
        };
        newState.messageIds.push(id);

        newState.messages.push(newMessage);
        newState.lastMessageSent = false;

        // notify WS
        socket.emit('INCOMING_MESSAGE', newMessage);
    }

    Scroll.animateScroll.scrollToBottom();

    return newState;
};
<|endoftext|>


<commit_before>
var navigationView = new tabris.NavigationView({
  left: 0, top: 0, right: 0, bottom: 0
}).appendTo(tabris.ui.contentView);

var createAction = function(title, imageName, placementPriority) {
  new tabris.Action({
    title: title,
    placementPriority: placementPriority,
    image: 'images/' + imageName
  }).appendTo(navigationView);
};

createAction('Search', 'search.png', 'high');
createAction('Share', 'share.png', 'low');
createAction('Settings', 'settings.png', 'low');
<commit_msg>Improve navigationview-action-placementpriority snippet<commit_after>
var navigationView = new tabris.NavigationView({
  left: 0, top: 0, right: 0, bottom: 0
}).appendTo(tabris.ui.contentView);

var createAction = function(title, imageName, placementPriority) {
  new tabris.Action({
    title: title,
    placementPriority: placementPriority,
    image: 'images/' + imageName
  }).appendTo(navigationView);
};

createAction('Search', 'search.png', 'high');
createAction('Share', 'share.png', 'low');
createAction('Settings', 'settings.png', 'normal');
<|endoftext|>


<commit_before>var brain=require('brain');

function tounao(trainedBrain) {
  if(trainedBrain) {
    this.brain=trainedBrain;
  }
  this.net = new brain.NeuralNetwork();
}

tounao.prototype.train=require('./tounao.train');
tounao.prototype.export=require('./tounao.export');
tounao.prototype.question=require('./tounao.question');

module.exports=tounao;<commit_msg>refactored to use this.trained<commit_after>var brain=require('brain');

function tounao(trainedBrain) {
  this.net = new brain.NeuralNetwork();
  this.trained=false;
  if(trainedBrain) {
    this.net.fromJSON(trainedBrain);
    this.trained=true;
  }
}

tounao.prototype.train=require('./tounao.train');
tounao.prototype.export=require('./tounao.export');
tounao.prototype.question=require('./tounao.question');

module.exports=tounao;<|endoftext|>


<commit_before>var pk = pk || {};
/**
Class used for notification management
@class pk.notify
@constructor
*/

/**
Create a new notification
@method push
@param options {Object}
@param [options.content] {String} Notification content (`HTML` allowed)
@param [options.delay=8000] {Number} Time in `ms` for notificaiton to display for
@returns Object {Object} Returns notification element (item `0`)
*/

/**
Remove a notification
@method close
@param element {Object} Notification element to remove
*/
(function(pk) {
    var nEl = pk.createEl("

");
    document.body.appendChild(nEl);
    pk.notify = {
        push: function(opt) {
            var mEl = pk.createEl("
" + opt.content + "
"),
                delay = opt.delay || 8000;
            nEl.appendChild(mEl);
            setTimeout(function() {
                pk.addClass(mEl, 'pk-show');
            }, 10);
            var scope = this;
            setTimeout(function() {
                scope.dismiss(mEl);
            }, delay);

            pk.bindEvent('click', mEl, function() {
                scope.dismiss(mEl);
            });
			return {
				0:mEl;
			}
        },
        dismiss: function(dEl) {
            if (!pk.hasClass(dEl, 'pk-show')) {
                return;
            }
            pk.removeClass(dEl, 'pk-show');
            setTimeout(function() {
                if (dEl) {
                    nEl.removeChild(dEl);
                }
            }, 1000);
        }
    };
})(pk);
<commit_msg>Update notify.js<commit_after>var pk = pk || {};
/**
Class used for notification management
@class pk.notify
@constructor
*/

/**
Create a new notification
@method push
@param options {Object}
@param [options.content] {String} Notification content (`HTML` allowed)
@param [options.delay=8000] {Number} Time in `ms` for notificaiton to display for
@returns Object {Object} Returns notification element (item `0`)
*/

/**
Remove a notification
@method close
@param element {Object} Notification element to remove
*/
(function(pk) {
    var nEl = pk.createEl("

");
    document.body.appendChild(nEl);
    pk.notify = {
        push: function(opt) {
            var mEl = pk.createEl("
" + opt.content + "
"),
                delay = opt.delay || 8000;
            nEl.appendChild(mEl);
            setTimeout(function() {
                pk.addClass(mEl, 'pk-show');
            }, 10);
            var scope = this;
            setTimeout(function() {
                scope.dismiss(mEl);
            }, delay);

            pk.bindEvent('click', mEl, function() {
                scope.dismiss(mEl);
            });
            return {
                0: mEl
            };
        },
        dismiss: function(dEl) {
            if (!pk.hasClass(dEl, 'pk-show')) {
                return;
            }
            pk.removeClass(dEl, 'pk-show');
            setTimeout(function() {
                if (dEl) {
                    nEl.removeChild(dEl);
                }
            }, 1000);
        }
    };
})(pk);
<|endoftext|>