Commit 996af225 authored by Joshua Gould's avatar Joshua Gould

moved getDataType to util

parent 613448df
morpheus.VectorUtil = function() {
morpheus.VectorUtil = function () {
};
morpheus.VectorUtil.createValueToIndicesMap = function(vector) {
morpheus.VectorUtil.createValueToIndicesMap = function (vector) {
if (!vector) {
throw 'vector is null';
}
......@@ -16,7 +16,7 @@ morpheus.VectorUtil.createValueToIndicesMap = function(vector) {
}
return map;
};
morpheus.VectorUtil.createValueToCountMap = function(vector) {
morpheus.VectorUtil.createValueToCountMap = function (vector) {
if (!vector) {
throw 'vector is null';
}
......@@ -39,7 +39,7 @@ morpheus.VectorUtil.createValueToCountMap = function(vector) {
}
return map;
};
morpheus.VectorUtil.maybeConvertToStringArray = function(vector, delim) {
morpheus.VectorUtil.maybeConvertToStringArray = function (vector, delim) {
var newValues = [];
var regex = new RegExp(delim);
var found = false;
......@@ -63,7 +63,7 @@ morpheus.VectorUtil.maybeConvertToStringArray = function(vector, delim) {
return found;
};
morpheus.VectorUtil.maybeConvertStringToNumber = function(vector) {
morpheus.VectorUtil.maybeConvertStringToNumber = function (vector) {
var newValues = [];
for (var i = 0, nrows = vector.size(); i < nrows; i++) {
......@@ -81,7 +81,7 @@ morpheus.VectorUtil.maybeConvertStringToNumber = function(vector) {
vector.getProperties().set(morpheus.VectorKeys.DATA_TYPE, 'number');
return true;
};
morpheus.VectorUtil.createValuesToIndicesMap = function(vectors) {
morpheus.VectorUtil.createValuesToIndicesMap = function (vectors) {
var map = new morpheus.Map();
var nvectors = vectors.length;
if (vectors[0] == null) {
......@@ -104,7 +104,7 @@ morpheus.VectorUtil.createValuesToIndicesMap = function(vectors) {
}
return map;
};
morpheus.VectorUtil.createValuesToIndexMap = function(vectors) {
morpheus.VectorUtil.createValuesToIndexMap = function (vectors) {
var map = new morpheus.Map();
var nvectors = vectors.length;
if (vectors[0] == null) {
......@@ -122,10 +122,10 @@ morpheus.VectorUtil.createValuesToIndexMap = function(vectors) {
}
return map;
};
morpheus.VectorUtil.containsMoreThanOneValue = function(vector) {
morpheus.VectorUtil.containsMoreThanOneValue = function (vector) {
return morpheus.VectorUtil.containsMoreThanNValues(vector, 1);
};
morpheus.VectorUtil.containsMoreThanNValues = function(vector, n) {
morpheus.VectorUtil.containsMoreThanNValues = function (vector, n) {
var s = new morpheus.Set();
for (var j = 0, size = vector.size(); j < size; j++) {
var val = vector.getValue(j);
......@@ -136,7 +136,7 @@ morpheus.VectorUtil.containsMoreThanNValues = function(vector, n) {
}
return false;
};
morpheus.VectorUtil.createValueToIndexMap = function(vector) {
morpheus.VectorUtil.createValueToIndexMap = function (vector) {
var map = new morpheus.Map();
for (var j = 0, size = vector.size(); j < size; j++) {
var val = vector.getValue(j);
......@@ -144,7 +144,7 @@ morpheus.VectorUtil.createValueToIndexMap = function(vector) {
}
return map;
};
morpheus.VectorUtil.getValues = function(vector, excludeNull) {
morpheus.VectorUtil.getValues = function (vector, excludeNull) {
var set = new morpheus.Set();
for (var j = 0, size = vector.size(); j < size; j++) {
var val = vector.getValue(j);
......@@ -157,14 +157,14 @@ morpheus.VectorUtil.getValues = function(vector, excludeNull) {
array.sort(morpheus.SortKey.ASCENDING_COMPARATOR);
return array;
};
morpheus.VectorUtil.getSet = function(vector) {
morpheus.VectorUtil.getSet = function (vector) {
var set = new morpheus.Set();
for (var j = 0, size = vector.size(); j < size; j++) {
set.add(vector.getValue(j));
}
return set;
};
morpheus.VectorUtil.createSpanMap = function(vector) {
morpheus.VectorUtil.createSpanMap = function (vector) {
var previous = vector.getValue(0);
// find 1st row with different value
var startIndexToEndIndex = new morpheus.Map();
......@@ -181,7 +181,7 @@ morpheus.VectorUtil.createSpanMap = function(vector) {
startIndexToEndIndex.set(start, vector.size());
return startIndexToEndIndex;
};
morpheus.VectorUtil.toArray = function(vector) {
morpheus.VectorUtil.toArray = function (vector) {
var array = [];
for (var i = 0, length = vector.size(); i < length; i++) {
var val = vector.getValue(i);
......@@ -190,12 +190,12 @@ morpheus.VectorUtil.toArray = function(vector) {
return array;
};
morpheus.VectorUtil.arrayAsVector = function(array, name) {
morpheus.VectorUtil.arrayAsVector = function (array, name) {
var v = new morpheus.Vector(name, array.length);
v.array = array;
return v;
};
morpheus.VectorUtil.toString = function(vector) {
morpheus.VectorUtil.toString = function (vector) {
var array = [];
for (var i = 0, length = vector.size(); i < length; i++) {
var val = vector.getValue(i);
......@@ -204,31 +204,18 @@ morpheus.VectorUtil.toString = function(vector) {
return array.join(', ');
};
morpheus.VectorUtil.getDataType = function(vector) {
morpheus.VectorUtil.getDataType = function (vector) {
var dataType = vector.getProperties().get(morpheus.VectorKeys.DATA_TYPE);
if (dataType === undefined) {
var firstNonNull = morpheus.VectorUtil.getFirstNonNull(vector);
var isArray = morpheus.Util.isArray(firstNonNull);
if (isArray && firstNonNull.length > 0) {
firstNonNull = firstNonNull[0];
}
if (_.isString(firstNonNull)) {
dataType = 'string';
} else if (_.isNumber(firstNonNull)) {
dataType = 'number';
} else {
dataType = 'object';
}
if (isArray) {
dataType = '[' + dataType + ']';
}
dataType = morpheus.Util.getDataType(firstNonNull);
vector.getProperties().set(morpheus.VectorKeys.DATA_TYPE, dataType);
}
return dataType;
};
morpheus.VectorUtil.getMinMax = function(vector) {
morpheus.VectorUtil.getMinMax = function (vector) {
var min = Number.MAX_VALUE;
var max = -Number.MAX_VALUE;
var fields = vector.getProperties().get(morpheus.VectorKeys.FIELDS);
......@@ -256,11 +243,11 @@ morpheus.VectorUtil.getMinMax = function(vector) {
}
}
return {
min : min,
max : max
min: min,
max: max
};
};
morpheus.VectorUtil.getFirstNonNull = function(vector) {
morpheus.VectorUtil.getFirstNonNull = function (vector) {
for (var i = 0, length = vector.size(); i < length; i++) {
var val = vector.getValue(i);
if (val != null) {
......@@ -269,6 +256,6 @@ morpheus.VectorUtil.getFirstNonNull = function(vector) {
}
return null;
};
morpheus.VectorUtil.isNumber = function(vector) {
morpheus.VectorUtil.isNumber = function (vector) {
return morpheus.VectorUtil.getDataType(vector) === 'number';
};
if (typeof morpheus === 'undefined') {
morpheus = {};
}
morpheus.Util = function() {
morpheus.Util = function () {
};
morpheus.Util.URL = 'https://www.broadinstitute.org/cancer/software/morpheus/';
......@@ -14,21 +14,21 @@ morpheus.Util.RIGHT_ARROW = String.fromCharCode(8594);
* @param {Object}
* c2 The object that obj1 inherits from
*/
morpheus.Util.extend = function(c1, c2) {
for ( var key in c2.prototype) {
morpheus.Util.extend = function (c1, c2) {
for (var key in c2.prototype) {
if (!(key in c1.prototype)) {
c1.prototype[key] = c2.prototype[key];
}
}
};
morpheus.Util.viewPortSize = function() {
morpheus.Util.viewPortSize = function () {
return window.getComputedStyle(document.body, ':before').content.replace(
/"/g, '');
};
morpheus.Util.TRACKING_CODE_LOADED = false;
morpheus.Util.loadTrackingCode = function() {
morpheus.Util.loadTrackingCode = function () {
if (typeof window !== 'undefined') {
if (morpheus.Util.TRACKING_CODE_LOADED) {
return;
......@@ -37,9 +37,9 @@ morpheus.Util.loadTrackingCode = function() {
return;
}
(function(i, s, o, g, r, a, m) {
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
i[r] = i[r] || function() {
i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments);
}, i[r].l = 1 * new Date();
a = s.createElement(o), m = s.getElementsByTagName(o)[0];
......@@ -57,27 +57,45 @@ morpheus.Util.loadTrackingCode = function() {
};
morpheus.Util.trackEvent = function(options) {
morpheus.Util.trackEvent = function (options) {
if (typeof window !== 'undefined') {
if (!morpheus.Util.TRACKING_CODE_LOADED) {
morpheus.Util.loadTrackingCode();
}
if (morpheus.Util.TRACKING_CODE_LOADED) {
ga('morpheus.send', {
hitType : 'event',
eventCategory : options.eventCategory,
eventAction : options.eventAction,
eventLabel : options.eventLabel
hitType: 'event',
eventCategory: options.eventCategory,
eventAction: options.eventAction,
eventLabel: options.eventLabel
});
}
}
};
morpheus.Util.getDataType = function (firstNonNull) {
var dataType;
var isArray = morpheus.Util.isArray(firstNonNull);
if (isArray && firstNonNull.length > 0) {
firstNonNull = firstNonNull[0];
}
if (_.isString(firstNonNull)) {
dataType = 'string';
} else if (_.isNumber(firstNonNull)) {
dataType = 'number';
} else {
dataType = 'object';
}
if (isArray) {
dataType = '[' + dataType + ']';
}
return dataType;
};
/**
* Trims leading and trailing whitespace from a string.
*/
morpheus.Util.trim = function(val) {
morpheus.Util.trim = function (val) {
var len = val.length;
var st = 0;
......@@ -93,9 +111,9 @@ morpheus.Util.trim = function(val) {
/**
* Checks whether supplied argument is an array
*/
morpheus.Util.isArray = function(array) {
var types = [ Array, Int8Array, Uint8Array, Uint8ClampedArray, Int16Array,
Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array, ];
morpheus.Util.isArray = function (array) {
var types = [Array, Int8Array, Uint8Array, Uint8ClampedArray, Int16Array,
Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array,];
// handle native arrays
for (var i = 0, length = types.length; i < length; i++) {
if (array instanceof types[i]) {
......@@ -104,7 +122,7 @@ morpheus.Util.isArray = function(array) {
}
return false;
};
morpheus.Util.getWindowSearchObject = function() {
morpheus.Util.getWindowSearchObject = function () {
var searchObject = {};
var hashObject = {};
if (window.location.search.length > 0) {
......@@ -118,7 +136,7 @@ morpheus.Util.getWindowSearchObject = function() {
return _.extend(hashObject, searchObject);
};
morpheus.Util.getQueryParams = function(s) {
morpheus.Util.getQueryParams = function (s) {
var params = {};
if (!s) {
return params;
......@@ -127,6 +145,7 @@ morpheus.Util.getQueryParams = function(s) {
var keyValuePairs = search.split('&');
for (var i = 0; i < keyValuePairs.length; i++) {
var pair = keyValuePairs[i].split('=');
if (pair[1] !== '') {
var array = params[pair[0]];
if (array === undefined) {
array = [];
......@@ -134,9 +153,10 @@ morpheus.Util.getQueryParams = function(s) {
}
array.push(pair[1]);
}
}
return params;
};
morpheus.Util.getScriptPath = function() {
morpheus.Util.getScriptPath = function () {
var scripts = document.getElementsByTagName('script');
for (var i = scripts.length - 1; i >= 0; i--) {
var src = scripts[i].src;
......@@ -151,23 +171,23 @@ morpheus.Util.getScriptPath = function() {
return scripts.length > 0 ? scripts[0].src : '';
};
morpheus.Util.forceDelete = function(obj) {
morpheus.Util.forceDelete = function (obj) {
try {
var _garbageCollector = (function() {
var ef = URL.createObjectURL(new Blob([ '' ], {
type : 'text/javascript'
var _garbageCollector = (function () {
var ef = URL.createObjectURL(new Blob([''], {
type: 'text/javascript'
})), w = new Worker(ef);
URL.revokeObjectURL(ef);
return w;
})();
_garbageCollector.postMessage(obj, [ obj ]);
_garbageCollector.postMessage(obj, [obj]);
} catch (x) {
console.log('Unable to delete');
}
};
morpheus.Util.getFileName = function(fileOrUrl) {
morpheus.Util.getFileName = function (fileOrUrl) {
var name = fileOrUrl instanceof File ? fileOrUrl.name : fileOrUrl;
name = '' + name;
var slash = name.lastIndexOf('/');
......@@ -191,10 +211,10 @@ morpheus.Util.getFileName = function(fileOrUrl) {
}
return name;
};
morpheus.Util.prefixWithZero = function(value) {
morpheus.Util.prefixWithZero = function (value) {
return value < 10 ? '0' + value : value;
};
morpheus.Util.getExtension = function(name) {
morpheus.Util.getExtension = function (name) {
var dotIndex = name.lastIndexOf('.');
if (dotIndex > 0) {
var suffix = name.substring(dotIndex + 1).toLowerCase();
......@@ -226,7 +246,7 @@ morpheus.Util.getExtension = function(name) {
* The file name.
* @return The base file name.
*/
morpheus.Util.getBaseFileName = function(name) {
morpheus.Util.getBaseFileName = function (name) {
var dotIndex = name.lastIndexOf('.');
if (dotIndex > 0) {
var suffix = name.substring(dotIndex + 1, name.length);
......@@ -237,7 +257,7 @@ morpheus.Util.getBaseFileName = function(name) {
}
return name;
};
morpheus.Util.seq = function(length) {
morpheus.Util.seq = function (length) {
var array = [];
for (var i = 0; i < length; i++) {
array.push(i);
......@@ -245,7 +265,7 @@ morpheus.Util.seq = function(length) {
return array;
};
morpheus.Util.sequ32 = function(length) {
morpheus.Util.sequ32 = function (length) {
var array = new Uint32Array(length);
for (var i = 0; i < length; i++) {
array[i] = i;
......@@ -257,7 +277,7 @@ morpheus.Util.sequ32 = function(length) {
* Converts window hash or search to an object that maps keys to an array of
* values. For example ?foo=bar returns {foo:[bar]}
*/
morpheus.Util.paramsToObject = function(hash) {
morpheus.Util.paramsToObject = function (hash) {
var search = hash ? window.location.hash : window.location.search;
if (search.length <= 1) {
return {};
......@@ -276,29 +296,29 @@ morpheus.Util.paramsToObject = function(hash) {
}
return result;
};
morpheus.Util.endsWith = function(string, suffix) {
morpheus.Util.endsWith = function (string, suffix) {
return string.length >= suffix.length
&& string.substr(string.length - suffix.length) === suffix;
};
morpheus.Util.measureSvgText = function(text, classname) {
morpheus.Util.measureSvgText = function (text, classname) {
if (!text || text.length === 0)
return {
height : 0,
width : 0
height: 0,
width: 0
};
var container = d3.select('body').append('svg');
if (classname) {
container.attr('class', classname);
}
container.append('text').attr({
x : -1000,
y : -1000
x: -1000,
y: -1000
}).text(text);
var bbox = container.node().getBBox();
container.remove();
return {
height : bbox.height,
width : bbox.width
height: bbox.height,
width: bbox.width
};
};
morpheus.Util.IS_MAC = false;
......@@ -308,25 +328,25 @@ if (typeof navigator !== 'undefined') {
}
morpheus.Util.COMMAND_KEY = morpheus.Util.IS_MAC ? '&#8984;' : 'Ctrl+';
morpheus.Util.hammer = function(el, recognizers) {
morpheus.Util.hammer = function (el, recognizers) {
var hammer = new Hammer(el, {
recognizers : []
recognizers: []
});
if (_.indexOf(recognizers, 'pan') !== -1) {
hammer.add(new Hammer.Pan({
threshold : 1,
direction : Hammer.DIRECTION_ALL
threshold: 1,
direction: Hammer.DIRECTION_ALL
}));
} else if (_.indexOf(recognizers, 'panh') !== -1) {
hammer.add(new Hammer.Pan({
threshold : 1,
direction : Hammer.DIRECTION_HORIZONTAL
threshold: 1,
direction: Hammer.DIRECTION_HORIZONTAL
}));
} else if (_.indexOf(recognizers, 'panv') !== -1) {
hammer.add(new Hammer.Pan({
threshold : 1,
direction : Hammer.DIRECTION_VERTICAL
threshold: 1,
direction: Hammer.DIRECTION_VERTICAL
}));
}
if (_.indexOf(recognizers, 'tap') !== -1) {
......@@ -348,8 +368,8 @@ morpheus.Util.hammer = function(el, recognizers) {
}
if (_.indexOf(recognizers, 'longpress') !== -1) {
hammer.add(new Hammer.Press({
event : 'longpress',
time : 1000
event: 'longpress',
time: 1000
}));
}
if (_.indexOf(recognizers, 'press') !== -1) {
......@@ -362,7 +382,7 @@ morpheus.Util.hammer = function(el, recognizers) {
// });
return hammer;
};
morpheus.Util.autocompleteArrayMatcher = function(q, cb, array, fields, max) {
morpheus.Util.autocompleteArrayMatcher = function (q, cb, array, fields, max) {
var filteredSet = new morpheus.Set();
// an array that will be populated with substring matches
// regex used to determine if a string starts with substring `q`
......@@ -417,18 +437,18 @@ morpheus.Util.autocompleteArrayMatcher = function(q, cb, array, fields, max) {
* when text field is empty.
*
*/
morpheus.Util.autosuggest = function(options) {
morpheus.Util.autosuggest = function (options) {
var fieldRegExp = /:/g;
options = $.extend({}, {
multi : true,
delay : 500,
suggestWhenEmpty : true,
multi: true,
delay: 500,
suggestWhenEmpty: true,
}, options);
options.$el
// don't navigate away from the field on tab when selecting an item
.on(
'keydown',
function(event) {
function (event) {
if ((event.keyCode === $.ui.keyCode.TAB)
&& $(this).data('ui-autocomplete').menu.active) {
event.preventDefault();
......@@ -436,17 +456,17 @@ morpheus.Util.autosuggest = function(options) {
})
.autocomplete(
{
minLength : 0,
delay : options.delay,
source : function(request, response) {
minLength: 0,
delay: options.delay,
source: function (request, response) {
// delegate back to autocomplete, but extract the
// autocomplete term
var terms = morpheus.Util
.getAutocompleteTokens(
request.term,
{
trim : false,
selectionStart : options.$el[0].selectionStart
trim: false,
selectionStart: options.$el[0].selectionStart
});
if (terms.selectionStartIndex === undefined
......@@ -457,11 +477,11 @@ morpheus.Util.autosuggest = function(options) {
options.filter(terms, response);
}
},
focus : function() {
focus: function () {
// prevent value inserted on focus
return false;
},
select : function(event, ui) {
select: function (event, ui) {
if (ui.item.skip) {
return false;
}
......@@ -470,8 +490,8 @@ morpheus.Util.autosuggest = function(options) {
.getAutocompleteTokens(
this.value,
{
trim : false,
selectionStart : options.$el[0].selectionStart
trim: false,
selectionStart: options.$el[0].selectionStart
});
// quote value if needed
var value = (ui.item.value[0] !== '"'
......@@ -498,7 +518,7 @@ morpheus.Util.autosuggest = function(options) {
// select
// just a
// field name?
setTimeout(function() {
setTimeout(function () {
options.$el.autocomplete('search',
options.$el.val());
}, 20);
......@@ -520,18 +540,18 @@ morpheus.Util.autosuggest = function(options) {
// use html for label instead of default text
var instance = options.$el.autocomplete('instance');
instance._renderItem = function(ul, item) {
instance._renderItem = function (ul, item) {
return $('<li class="ui-menu-item">').html(
item.render ? item.render() : item.label).appendTo(ul);
};
if (options.suggestWhenEmpty) {
options.$el.on('focus', function() {
options.$el.on('focus', function () {
options.$el.autocomplete('search', options.$el.val());
});
}
options.$el.on('keyup', function(e) {
options.$el.on('keyup', function (e) {
if (e.which === 13) {
options.$el.autocomplete('close');
} else if (options.suggestWhenEmpty) {
......@@ -544,9 +564,9 @@ morpheus.Util.autosuggest = function(options) {
};
morpheus.Util.getAutocompleteTokens = function(text, options) {
morpheus.Util.getAutocompleteTokens = function (text, options) {
options = $.extend({}, {
trim : true
trim: true
}, options);
if (options.trim) {
text = $.trim(text);
......@@ -567,8 +587,8 @@ morpheus.Util.getAutocompleteTokens = function(text, options) {
} else {
if ((c === ' ' || c === '\t') && !inQuote) {
tokens.push({
s : currentToken.join(''),
inSelectionStart : currentToken.inSelectionStart
s: currentToken.join(''),
inSelectionStart: currentToken.inSelectionStart
});
currentToken = []; // start new token
} else { // add to current token
......@@ -581,14 +601,14 @@ morpheus.Util.getAutocompleteTokens = function(text, options) {
}
tokens.push({
s : currentToken.join(''),
inSelectionStart : currentToken.inSelectionStart
s: currentToken.join(''),
inSelectionStart: currentToken.inSelectionStart
});
// add trailing token
if (!options.trim && !inQuote && text[text.length - 1] === ' ') {
tokens.push({
s : ' ',
inSelectionStart : false
s: ' ',
inSelectionStart: false
});
}
// remove empty tokens
......@@ -615,33 +635,33 @@ morpheus.Util.getAutocompleteTokens = function(text, options) {
/**
* @deprecated
*/
morpheus.Util.autocomplete = function($el, filterFunction, selectCb,
morpheus.Util.autocomplete = function ($el, filterFunction, selectCb,
singleTerm, autoclose) {
var fieldRegExp = /:/g;
$el
// don't navigate away from the field on tab when selecting an item
.on(
'keydown',
function(event) {
function (event) {
if ((event.keyCode === $.ui.keyCode.TAB)
&& $(this).data('ui-autocomplete').menu.active) {
event.preventDefault();
}
}).autocomplete({
minLength : 1,
delay : 1200,
source : function(request, response) {
minLength: 1,
delay: 1200,
source: function (request, response) {
// delegate back to autocomplete, but extract the last term
var terms = morpheus.Util.getAutocompleteTokens(request.term);
if (terms.length > 0) {
filterFunction(terms.pop(), response);
}
},
focus : function() {
focus: function () {
// prevent value inserted on focus
return false;
},
select : function(event, ui) {
select: function (event, ui) {
if (!singleTerm) {
var terms = morpheus.Util.getAutocompleteTokens(this.value);
// remove the current input
......@@ -669,19 +689,19 @@ morpheus.Util.autocomplete = function($el, filterFunction, selectCb,
});
// use html for label instead of default text
$el.autocomplete('instance')._renderItem = function(ul, item) {
$el.autocomplete('instance')._renderItem = function (ul, item) {
return $('<li>').html(item.label).appendTo(ul);
};
if (autoclose) {
$el.on('keyup', function(e) {
$el.on('keyup', function (e) {
if (e.which === 13) {
$el.autocomplete('close');
}
});
}
};
morpheus.Util.showDialog = function($el, title, options) {
morpheus.Util.showDialog = function ($el, title, options) {
var $dialog = $('<div></div>');
$el.appendTo($dialog);
$dialog.appendTo($(document.body));
......@@ -689,9 +709,9 @@ morpheus.Util.showDialog = function($el, title, options) {
options = {};
}
$dialog.dialog({
width : 670,
height : 590,
title : title,
width: 670,
height: 590,
title: title,
// resizeStop : function(event, ui) {
// var w = parseInt($dialog.width());
// var h = parseInt($dialog.height());
......@@ -700,7 +720,7 @@ morpheus.Util.showDialog = function($el, title, options) {
// svg.attr("height", h - 50);
// chart.update();
// },
close : function(event, ui) {
close: function (event, ui) {
$dialog.remove();
if (options.close) {
options.close();
......@@ -715,15 +735,15 @@ morpheus.Util.showDialog = function($el, title, options) {
* If a delim is specified each row, will contain a string separated
* by delim. Otherwise each row will contain an array.
*/
morpheus.Util.sheetToArray = function(sheet, delim) {
morpheus.Util.sheetToArray = function (sheet, delim) {
var r = XLSX.utils.decode_range(sheet['!ref']);
var rows = [];
for (var R = r.s.r; R <= r.e.r; ++R) {
var row = [];
for (var C = r.s.c; C <= r.e.c; ++C) {
var val = sheet[XLSX.utils.encode_cell({
c : C,
r : R
c: C,
r: R
})];
if (!val) {
row.push('');
......@@ -736,7 +756,7 @@ morpheus.Util.sheetToArray = function(sheet, delim) {
}
return rows;
};
morpheus.Util.linesToObjects = function(lines) {
morpheus.Util.linesToObjects = function (lines) {
var header = lines[0];
var array = [];
var nfields = header.length;
......@@ -752,29 +772,29 @@ morpheus.Util.linesToObjects = function(lines) {
}
return array;
};
morpheus.Util.xlsxTo2dArray = function(data) {
morpheus.Util.xlsxTo2dArray = function (data) {
var workbook = XLSX.read(data, {
type : 'binary',
cellFormula : false,
cellHTML : false
type: 'binary',
cellFormula: false,
cellHTML: false
});
var sheetNames = workbook.SheetNames;
var worksheet = workbook.Sheets[sheetNames[0]];
var lines = morpheus.Util.sheetToArray(worksheet);
return lines;
};
morpheus.Util.xlsxTo1dArray = function(data) {
morpheus.Util.xlsxTo1dArray = function (data) {
var workbook = XLSX.read(data, {
type : 'binary',
cellFormula : false,
cellHTML : false
type: 'binary',
cellFormula: false,
cellHTML: false
});
var sheetNames = workbook.SheetNames;
var worksheet = workbook.Sheets[sheetNames[0]];
var lines = morpheus.Util.sheetToArray(worksheet, '\t');
return lines;
};
morpheus.Util.hashCode = function(val) {
morpheus.Util.hashCode = function (val) {
var h = 0;
if (val.length > 0) {
for (var i = 0; i < val.length; i++) {
......@@ -786,19 +806,19 @@ morpheus.Util.hashCode = function(val) {
/**
* Returns a promise that resolves to a string
*/
morpheus.Util.getText = function(urlOrFile) {
morpheus.Util.getText = function (urlOrFile) {
var deferred = $.Deferred();
if (_.isString(urlOrFile)) {
$.ajax({
contentType : 'text/plain',
url : urlOrFile,
}).done(function(text, status, xhr) {
contentType: 'text/plain',
url: urlOrFile,
}).done(function (text, status, xhr) {
// var type = xhr.getResponseHeader('Content-Type');
deferred.resolve(text);
});
} else if (urlOrFile instanceof File) {
var reader = new FileReader();
reader.onload = function(event) {
reader.onload = function (event) {
deferred.resolve(event.target.result);
};
reader.readAsText(urlOrFile);
......@@ -808,12 +828,12 @@ morpheus.Util.getText = function(urlOrFile) {
}
return deferred.promise();
};
morpheus.Util.createOptions = function(values, none) {
morpheus.Util.createOptions = function (values, none) {
var html = [];
if (none) {
html.push('<option value="">(None)</option>');
}
_.each(values, function(val) {
_.each(values, function (val) {
html.push('<option value="');
html.push(val);
html.push('">');
......@@ -830,7 +850,7 @@ morpheus.Util.createOptions = function(values, none) {
* @param index
* @return The ranks.
*/
morpheus.Util.rankIndexArray = function(index) {
morpheus.Util.rankIndexArray = function (index) {
var rank = [];
var n = index.length;
for (var j = 0; j < n; j++) {
......@@ -839,40 +859,40 @@ morpheus.Util.rankIndexArray = function(index) {
return rank;
};
morpheus.Util.indexSort = function(array, ascending) {
morpheus.Util.indexSort = function (array, ascending) {
var pairs = [];
array.forEach(function(value, index) {
array.forEach(function (value, index) {
pairs.push({
value : value,
index : index
value: value,
index: index
});
});
return morpheus.Util.indexSortPairs(pairs, ascending);
};
morpheus.Util.indexSortPairs = function(array, ascending) {
morpheus.Util.indexSortPairs = function (array, ascending) {
if (ascending) {
array.sort(function(a, b) {
array.sort(function (a, b) {
return (a.value < b.value ? -1 : (a.value === b.value ? 0 : 1));
});
} else {
array.sort(function(a, b) {
array.sort(function (a, b) {
return (a.value < b.value ? 1 : (a.value === b.value ? 0 : -1));
});
}
var indices = [];
array.forEach(function(item) {
array.forEach(function (item) {
indices.push(item.index);
});
return indices;
};
morpheus.Util.arrayEquals = function(array1, array2, comparator) {
morpheus.Util.arrayEquals = function (array1, array2, comparator) {
if (array1 == array2)
return true;
if (array1 == null || array2 == null) {
return false;
}
if (!comparator) {
comparator = function(a, b) {
comparator = function (a, b) {
return a === b;
};
}
......@@ -888,35 +908,35 @@ morpheus.Util.arrayEquals = function(array1, array2, comparator) {
return true;
};
morpheus.Util._intFormat = typeof d3 !== 'undefined' ? d3.format(',i')
: function(d) {
: function (d) {
return '' + Math.round(d);
};
morpheus.Util.intFormat = function(n) {
};
morpheus.Util.intFormat = function (n) {
return morpheus.Util._intFormat(n);
};
morpheus.Util._nf = typeof d3 !== 'undefined' ? d3.format('.4f') : function(d) {
morpheus.Util._nf = typeof d3 !== 'undefined' ? d3.format('.4f') : function (d) {
return '' + d;
};
morpheus.Util.nf = function(n) {
morpheus.Util.nf = function (n) {
var str = (n < 1 && n > -1 && n.toPrecision !== undefined) ? n
.toPrecision(4) : morpheus.Util._nf(n);
return morpheus.Util.removeTrailingZerosInFraction(str);
};
morpheus.Util.createNumberFormat = function(nfractionDigits) {
morpheus.Util.createNumberFormat = function (nfractionDigits) {
var d3Formatter = d3.format('.' + nfractionDigits + 'f');
var f = function(value) {
var f = function (value) {
var str = d3Formatter(value);
return morpheus.Util.removeTrailingZerosInFraction(str);
};
return f;
};
morpheus.Util.formatObject = function(value) {
morpheus.Util.formatObject = function (value) {
if (_.isNumber(value)) {
return morpheus.Util.nf(value);
}
return value;
};
morpheus.Util.arrayToString = function(array, sep) {
morpheus.Util.arrayToString = function (array, sep) {
var s = [];
for (var i = 0, length = array.length; i < length; i++) {
s.push(morpheus.Util.formatObject(array[i]));
......@@ -925,14 +945,14 @@ morpheus.Util.arrayToString = function(array, sep) {
};
morpheus.Util.wrapNumber = function(value, object) {
morpheus.Util.wrapNumber = function (value, object) {
var n = new Number(value);
n.toObject = function() {
n.toObject = function () {
return object;
};
return n;
};
morpheus.Util.toString = function(value) {
morpheus.Util.toString = function (value) {
if (value == null) {
return '';
} else if (_.isNumber(value)) {
......@@ -946,7 +966,7 @@ morpheus.Util.toString = function(value) {
}
return '' + value;
};
morpheus.Util.removeTrailingZerosInFraction = function(str) {
morpheus.Util.removeTrailingZerosInFraction = function (str) {
var index = str.lastIndexOf('.');
if (index !== -1) {
var len = str.length;
......@@ -965,10 +985,10 @@ morpheus.Util.removeTrailingZerosInFraction = function(str) {
}
return str;
};
morpheus.Util.s = function(n) {
morpheus.Util.s = function (n) {
return n === 1 ? '' : 's';
};
morpheus.Util.create2dArray = function(rows, columns) {
morpheus.Util.create2dArray = function (rows, columns) {
var array2d = [];
for (var i = 0; i < rows; i++) {
var array = [];
......@@ -979,14 +999,14 @@ morpheus.Util.create2dArray = function(rows, columns) {
}
return array2d;
};
morpheus.Util.escapeRegex = function(value) {
morpheus.Util.escapeRegex = function (value) {
return value.replace(/[*]/g, '.*')
.replace(/[-[\]{}()+?,\\^$|#\s]/g, '\\$&');
};
morpheus.Util.createSearchPredicates = function(options) {
morpheus.Util.createSearchPredicates = function (options) {
options = $.extend({}, {
validateFieldNames : true
validateFieldNames: true
}, options);
var tokens = options.tokens;
if (tokens == null) {
......@@ -1002,7 +1022,7 @@ morpheus.Util.createSearchPredicates = function(options) {
var defaultIsExactMatch = options.defaultMatchMode === 'exact';
tokens
.forEach(function(token) {
.forEach(function (token) {
var isNot = false;
if (token[0] === '-') { // not predicate
token = token.substring(1);
......@@ -1045,7 +1065,7 @@ morpheus.Util.createSearchPredicates = function(options) {
var predicate;
var rangeIndex = -1;
var rangeToken = null;
var rangeIndicators = [ '..', '>=', '>', '<=', '<', '=' ];
var rangeIndicators = ['..', '>=', '>', '<=', '<', '='];
for (var i = 0; i < rangeIndicators.length; i++) {
rangeIndex = token.indexOf(rangeIndicators[i]);
if (rangeIndex !== -1) {
......@@ -1119,13 +1139,13 @@ morpheus.Util.createSearchPredicates = function(options) {
return predicates;
};
morpheus.Util.createRegExpStringToMatchText = function(text) {
morpheus.Util.createRegExpStringToMatchText = function (text) {
var tokens = morpheus.Util.getAutocompleteTokens(text);
if (tokens.length === 0) {
return null;
}
var regex = [];
_.each(tokens, function(token) {
_.each(tokens, function (token) {
if (token[0] === '"' && token[token.length - 1] === '"') {
token = token.substring(1, token.length - 1);
regex.push('^' + morpheus.Util.escapeRegex(token) + '$'); // exact
......@@ -1136,18 +1156,18 @@ morpheus.Util.createRegExpStringToMatchText = function(text) {
});
return '(' + regex.join('|') + ')';
};
morpheus.Util.createRegExpToMatchText = function(text) {
morpheus.Util.createRegExpToMatchText = function (text) {
var s = morpheus.Util.createRegExpStringToMatchText(text);
return s == null ? null : new RegExp(s, 'i');
};
morpheus.Util.reorderArray = function(array, index) {
morpheus.Util.reorderArray = function (array, index) {
var newArray = [];
for (var i = 0; i < index.length; i++) {
newArray.push(array[index[i]]);
}
return newArray;
};
morpheus.Util.getSearchString = function() {
morpheus.Util.getSearchString = function () {
var s = window.location.search;
return s.length > 1 ? s.substring(1) : '';
};
......@@ -1156,7 +1176,7 @@ morpheus.Util.getSearchString = function() {
*
* @return An array of arrays
*/
morpheus.Util.splitLines = function(lines) {
morpheus.Util.splitLines = function (lines) {
var tab = new RegExp('\t');
var tokens = [];
for (var i = 0, nlines = lines.length; i < nlines; i++) {
......@@ -1174,7 +1194,7 @@ morpheus.Util.splitLines = function(lines) {
* a File or url
* @return A deferred object that resolves to an array of arrays
*/
morpheus.Util.readLines = function(fileOrUrl) {
morpheus.Util.readLines = function (fileOrUrl) {
var isFile = fileOrUrl instanceof File;
var isString = typeof fileOrUrl === 'string' || fileOrUrl instanceof String;
var name = morpheus.Util.getFileName(fileOrUrl);
......@@ -1185,7 +1205,7 @@ morpheus.Util.readLines = function(fileOrUrl) {
var oReq = new XMLHttpRequest();
oReq.open('GET', fileOrUrl, true);
oReq.responseType = 'arraybuffer';
oReq.onload = function(oEvent) {
oReq.onload = function (oEvent) {
var arrayBuffer = oReq.response; // Note: not
// oReq.responseText
if (arrayBuffer) {
......@@ -1204,14 +1224,14 @@ morpheus.Util.readLines = function(fileOrUrl) {
oReq.send(null);
} else {
$.ajax({
url : fileOrUrl,
}).done(function(text, status, xhr) {
url: fileOrUrl,
}).done(function (text, status, xhr) {
deferred.resolve(morpheus.Util.splitOnNewLine(text));
});
}
} else if (isFile) {
var reader = new FileReader();
reader.onload = function(event) {
reader.onload = function (event) {
deferred.resolve(ext === 'xlsx' ? morpheus.Util
.xlsxTo1dArray(event.target.result) : morpheus.Util
.splitOnNewLine(event.target.result));
......@@ -1226,9 +1246,9 @@ morpheus.Util.readLines = function(fileOrUrl) {
}
return deferred;
};
morpheus.Util.createValueToIndices = function(array, field) {
morpheus.Util.createValueToIndices = function (array, field) {
var map = new morpheus.Map();
_.each(array, function(item) {
_.each(array, function (item) {
var key = item[field];
var values = map.get(key);
if (values === undefined) {
......@@ -1243,7 +1263,7 @@ morpheus.Util.createValueToIndices = function(array, field) {
/**
* Splits a string by the new line character, trimming whitespace
*/
morpheus.Util.splitOnNewLine = function(text, commentChar) {
morpheus.Util.splitOnNewLine = function (text, commentChar) {
var commentCharCode = commentChar !== undefined ? commentChar.charCodeAt(0)
: undefined;
......@@ -1271,175 +1291,175 @@ morpheus.Util.splitOnNewLine = function(text, commentChar) {
return rows;
};
morpheus.Util.ContainsPredicate = function(field, text) {
morpheus.Util.ContainsPredicate = function (field, text) {
this.field = field;
text = text.toLowerCase();
this.text = text;
};
morpheus.Util.ContainsPredicate.prototype = {
accept : function(value) {
accept: function (value) {
return value.toLowerCase
&& value.toLowerCase().indexOf(this.text) !== -1;
},
getField : function() {
getField: function () {
return this.field;
},
isNumber : function() {
isNumber: function () {
return false;
},
toString : function() {
toString: function () {
return 'ContainsPredicate ' + this.field + ':' + this.text;
}
};
morpheus.Util.ExactTermPredicate = function(field, term) {
morpheus.Util.ExactTermPredicate = function (field, term) {
this.field = field;
term = term.toLowerCase();
this.text = term;
};
morpheus.Util.ExactTermPredicate.prototype = {
accept : function(value) {
accept: function (value) {
return value.toLowerCase && value.toLowerCase() === this.text;
},
getField : function() {
getField: function () {
return this.field;
},
isNumber : function() {
isNumber: function () {
return false;
},
toString : function() {
toString: function () {
return 'ExactTermPredicate ' + this.field + ':' + this.text;
}
};
morpheus.Util.RegexPredicate = function(field, text) {
morpheus.Util.RegexPredicate = function (field, text) {
this.field = field;
this.text = text;
this.regex = new RegExp(morpheus.Util.escapeRegex(text), 'i');
};
morpheus.Util.RegexPredicate.prototype = {
accept : function(value) {
accept: function (value) {
return this.regex.test(value);
},
getField : function() {
getField: function () {
return this.field;
},
isNumber : function() {
isNumber: function () {
return false;
},
toString : function() {
toString: function () {
return 'RegexPredicate ' + this.field + ':' + this.regex;
}
};
morpheus.Util.NumberRangePredicate = function(field, min, max) {
morpheus.Util.NumberRangePredicate = function (field, min, max) {
this.field = field;
this.min = min;
this.max = max;
};
morpheus.Util.NumberRangePredicate.prototype = {
accept : function(value) {
accept: function (value) {
return value >= this.min && value <= this.max;
},
getField : function() {
getField: function () {
return this.field;
},
isNumber : function() {
isNumber: function () {
return true;
},
toString : function() {
toString: function () {
return 'NumberRangePredicate ' + this.field + ':' + this.min + '...'
+ this.max;
}
};
morpheus.Util.GreaterThanPredicate = function(field, val) {
morpheus.Util.GreaterThanPredicate = function (field, val) {
this.field = field;
this.val = val;
};
morpheus.Util.GreaterThanPredicate.prototype = {
accept : function(value) {
accept: function (value) {
return value > this.val;
},
getField : function() {
getField: function () {
return this.field;
},
isNumber : function() {
isNumber: function () {
return true;
}
};
morpheus.Util.GreaterThanOrEqualPredicate = function(field, val) {
morpheus.Util.GreaterThanOrEqualPredicate = function (field, val) {
this.field = field;
this.val = val;
};
morpheus.Util.GreaterThanOrEqualPredicate.prototype = {
accept : function(value) {
accept: function (value) {
return value >= this.val;
},
getField : function() {
getField: function () {
return this.field;
},
isNumber : function() {
isNumber: function () {
return true;
}
};
morpheus.Util.LessThanPredicate = function(field, val) {
morpheus.Util.LessThanPredicate = function (field, val) {
this.field = field;
this.val = val;
};
morpheus.Util.LessThanPredicate.prototype = {
accept : function(value) {
accept: function (value) {
return value < this.val;
},
getField : function() {
getField: function () {
return this.field;
},
isNumber : function() {
isNumber: function () {
return true;
}
};
morpheus.Util.LessThanOrEqualPredicate = function(field, val) {
morpheus.Util.LessThanOrEqualPredicate = function (field, val) {
this.field = field;
this.val = val;
};
morpheus.Util.LessThanOrEqualPredicate.prototype = {
accept : function(value) {
accept: function (value) {
return value <= this.val;
},
getField : function() {
getField: function () {
return this.field;
},
isNumber : function() {
isNumber: function () {
return true;
}
};
morpheus.Util.EqualsPredicate = function(field, val) {
morpheus.Util.EqualsPredicate = function (field, val) {
this.field = field;
this.val = val;
};
morpheus.Util.EqualsPredicate.prototype = {
accept : function(value) {
accept: function (value) {
return value === this.val;
},
getField : function() {
getField: function () {
return this.field;
},
isNumber : function() {
isNumber: function () {
return true;
}
};
morpheus.Util.NotPredicate = function(p) {
morpheus.Util.NotPredicate = function (p) {
this.p = p;
};
morpheus.Util.NotPredicate.prototype = {
accept : function(value) {
accept: function (value) {
return !this.p.accept(value);
},
getField : function() {
getField: function () {
return this.p.getField();
},
isNumber : function() {
isNumber: function () {
return this.p.isNumber();
},
toString : function() {
toString: function () {
return 'NotPredicate ' + this.p;
}
};
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment