<commit_before>function setFavourite(name, type, image){
    AjaxServices.setFavourite(name, type);
    image.src='images/star_active.gif';
    image.onclick='';
    image.style.cursor='';
    image.title='This is a favourite';
}

function precomputeTemplate(templateName){
    document.getElementById('precompute_'+templateName).innerHTML="Precomputing..";
    AjaxServices.preCompute(templateName,function(str) {
        document.getElementById('precompute_'+templateName).style.color="#777";
        document.getElementById('precompute_'+templateName).innerHTML="Precomputed";
     });
}

function summariseTemplate(templateName){
    document.getElementById('summarise_'+templateName).innerHTML="Summarising..";
    AjaxServices.summarise(templateName,function(str) {
        document.getElementById('summarise_'+templateName).style.color="#777";
        document.getElementById('summarise_'+templateName).innerHTML="Summarised";
    });
}

function editName(name){
  document.getElementById('form_'+name).style.display="block";
  document.getElementById('name_'+name).style.display="none";
}

function renameElement(name, type, index){
    document.getElementById('form_'+name).style.display="none";
    document.getElementById('name_'+name).innerHTML="saving...";
    document.getElementById('name_'+name).style.display="block";
    AjaxServices.rename(name,type, (document.getElementById('newName_'+name).value).replace(/^\s*|\s*$/g,""), function(str){
        document.getElementById('name_'+name).innerHTML=str;
        document.getElementById('selected_user_' + type + '_' + index).value=str;
    });
}

function changeViewPathDescription(pathName){
    var pathString = pathName.replace(/\@sep\@/g,".");
    var pathEnd = pathString.substring(pathString.lastIndexOf('.') + 1);
    document.getElementById('form_'+pathName).style.display = "none";
    document.getElementById('name_'+pathName+'_inner').innerHTML = "saving...";
    document.getElementById('name_'+pathName).style.display = "block";
    var newDescription = document.getElementById('newName_' + pathName).value;
    var callBack = function(prefixDescription){
        if (prefixDescription == null) {
            prefixDescription = '(no description)';
        }
        document.getElementById('name_' + pathName + '_inner').innerHTML =
          '' + prefixDescription +
          ' > ' + pathEnd;
    }
    AjaxServices.changeViewPathDescription(pathString, newDescription, callBack);
}

function saveBagDescription(bagName){
    var textarea = document.getElementById('textarea').value;
    textarea = textarea.replace(/[\n\r]+/g, "\n\r
");
    document.getElementById('bagDescriptionDiv').innerHTML = 'Saving...';
    AjaxServices.saveBagDescription(bagName,textarea, function(str){
        document.getElementById('bagDescriptionDiv').innerHTML = str;
    });
    swapDivs('bagDescriptionTextarea','bagDescriptionDiv');
}

function swapDivs(div1,div2){
    document.getElementById(div1).style.display = 'none';
    document.getElementById(div2).style.display = 'block';
}

function roundToSignificantDecimal(n) {
    var log10n = Math.log(Math.abs(n)) / Math.log(10);
    if(log10n<1 && n!=0) {
        var rf = 100*Math.pow(10,-Math.round(log10n));
        return rf;
    } else return 100;
}

function updateCountInColumnSummary() {
    var countString = document.resultsCountText;
    if (countString == null) {
        setTimeout("updateCountInColumnSummary()", 1000);
        return;
    }

    document.getElementById('summary_row_count').innerHTML = "
" + countString + "
";

    var est = document.getElementById('resultsCountEstimate');
    if (est == null || est.style.display != 'none') {
        setTimeout("updateCountInColumnSummary()", 500);
        return;
    }
}

function updateUniqueCountInColumnSummary(uniqueCountQid) {
    getResults(uniqueCountQid, 1000, resultsCountCallback, null);
}

function resultsCountCallback(results) {
    var size = results[0][0];

    if (size > 1) {
        var summaryUniqueCountElement = document.getElementById('summary_unique_count');
        summaryUniqueCountElement.style.display='inline';
        summaryUniqueCountElement.innerHTML='Total unique values: ' + size;
    }
    return true;
}

function getColumnSummary(tableName, columnName, columnDisplayName) {
    document.getElementById('summary_loaded').style.display = "none";
    document.getElementById('summary_loading').style.display = "block";
    Effect.Appear('summary', { duration: 0.30 });
    AjaxServices.getColumnSummary(tableName, columnName, function(str){
        var rows = str[0];
        function rounder(cell) {
            if (cell==null) {
                return "[no value]" ;
            } if (! isNaN(cell)) {
                var rf = roundToSignificantDecimal(cell+0);
                return Math.round(cell*rf)/rf;
            } else {
                return cell;
            }
        }
        var headerText;
        if(rows[0].length == 2){
            headerText = '
Value	Count
';
        } else {
            headerText = '
Min	Max	Sample Mean	Standard Deviation
';
        }

        document.getElementById('summary_loading').style.display = "none";
        document.getElementById('summary_loaded').style.display = "block";

        var bodyText = '';

        for (rowIndex = 0; rowIndex < rows.length; rowIndex++) {
            var row = rows[rowIndex];
            bodyText += '
';
            for (colIndex = 0; colIndex < row.length; colIndex++) {
                var cellValue = rounder(row[colIndex]);
                bodyText += '' + cellValue + '	';
            }
            bodyText += '
';
        }

        var html = '
                                         \

                                     \
                        Column Summary for ' + columnDisplayName + '          \

                                                  \

                      \

                   \

                                                   \

 \

' + headerText +'
    \

' + bodyText + '
    \

                                                \

';

        var summaryLoadedElement = document.getElementById('summary_loaded');
        summaryLoadedElement.innerHTML = html;
        var uniqueCountQid = str[1];
        setTimeout("updateCountInColumnSummary()", 200);
        setTimeout("updateUniqueCountInColumnSummary(" + uniqueCountQid + ")", 300);
    });
}

function getResultsPoller(qid, timeout, userCallback, userData) {
    var callback = function(results) {
        if (results == null) {
            // try again
            getResults(qid, timeout, userCallback, userData);
        } else {
            if (!userCallback(results, userData)) {
                getResults(qid, timeout, userCallback, userData);
            }
        }
    }

    AjaxServices.getResults(qid, callback);
}

function getResults(qid, timeout, userCallback, userData) {
    setTimeout("getResultsPoller(" + qid + ", " + timeout + ", " + userCallback + ","
               + userData + ")", timeout);
}

// delete all the child nodes of the node given by parentElement and create a child
// element of type childTag, setting the text in the new child element to be
// childText
function setChild(parentElement, childText, childTag) {
    var newChild = document.createElement(childTag);
    newChild.innerHTML = childText;
    if (parentElement.firstChild != null) {
        while (parentElement.hasChildNodes()) {
            parentElement.removeChild(parentElement.firstChild);
        }
    }
    parentElement.appendChild(newChild);
    return newChild;
}

var callId = 1;

// Give each ajax call an id and remember what our current pending id is
var currentFilterCallbacks = new Array();

// Give each setTimeout call an id and remember what our current pending id is
var futureFilterCalls = new Array();

function filterWebSearchablesHandler(event, object, scope, type, tags) {
    if (window.event) {
        event = window.event;
    }
    if (event) {
	    if (event.keyCode == 27) {
	        object.value = '';
	        return;
	    }
	    if (event.keyCode == 13) {
	        return;
	    }
	}

    futureFilterCalls[scope + "_" + type] = callId;
    setTimeout('filterWebSearchables("' + object.id + '", "' + scope + '","' + type + '",' +
               callId + ",'" + tags + "')", 500);
    callId++;
}

// given a list of WebSearchables names,scores and descriptions, filter the
// wsFilterList given by the scope and type parameters
function do_filtering(filteredList, scope, type) {
    if (filteredList.length == 0) {
        showAll(scope, type);
    } else {
        var scoreHash = new Array();
        var descHash = new Array();
        var hitHash = new Array();

        for (var el in filteredList) {
            var wsName = filteredList[el][0];
            var wsDesc = filteredList[el][1];
            descHash[scope + '_' + type + '_item_line_' + wsName] = wsDesc;
            var wsScore = filteredList[el][2];
            scoreHash[scope + '_' + type + '_item_line_' + wsName] = wsScore;
            hitHash[scope + '_' + type + '_item_line_' + wsName] = 1;
        }

        var pattern = new RegExp('^' + scope + '_' + type + '_item_line_(.*)');
        var inputArray = document.getElementsByTagName("div");
        for(var i=0; i<inputArray.length; i++) {
            if ((result = pattern.exec(inputArray[i].id)) != null) {
                if (hitHash[inputArray[i].id]) {
                    inputArray[i].style.display='block';
                    var highlightText = descHash[inputArray[i].id];

                    if (highlightText) {
                        var descId = scope + '_' + type + '_item_description_' + result[1];
                        var desc = $(descId);

                        var descChild = setChild(desc, highlightText, 'p');
                        descChild.className = 'description';
                    }

                    if (scoreHash[inputArray[i].id]) {
                        var scoreWsName = result[1];
                        var score = scoreHash[inputArray[i].id];
                        var intScore = parseInt(score * 10);
                        var scoreId = scope + '_' + type + '_item_score_' + scoreWsName;
                        var scoreSpan = $(scoreId);
                        // we do this instead of scoreSpan.innerHTML = "stuff"
                        // because it's buggy in Internet Explorer
                        var heatImage = 'heat' + intScore + '.gif';
                        var heatText = '';
                        setChild(scoreSpan, heatText, 'span');
                    }
                } else {
                    inputArray[i].style.display='none';
                }
            }
        }

        function sortWsFilter(el1, el2) {
            var el1score = scoreHash[el1.id];
            var el2score = scoreHash[el2.id]
                if (el1score > el2score) {
                    return -1;
                } else {
                    if (el1score < el2score) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
        }

        var parent = $(scope + '_' + type + '_ws_list');
        var divs = new Array();

        for (var i in parent.childNodes) {
            var child = parent.childNodes[i];
            if (child.tagName == 'DIV' && scoreHash[child.id]) {
                divs.push(child);
            }
        }

        divs.sort(sortWsFilter);

        for (var i = 0; i < divs.length; i++) {
            parent.appendChild(divs[i]);
        }

        $(scope + '_' + type + '_spinner').style.visibility = 'hidden';
    }
}

// un-hide all the rows in the webSearchableList
function showAll(scope, type) {
    var pattern = new RegExp('^' + scope + '_' + type + '_item_line_(.*)');
    var inputArray = document.getElementsByTagName("div");
    for(var i=0; i<inputArray.length; i++) {
        var result;
        if ((result = pattern.exec(inputArray[i].id)) != null) {
            inputArray[i].style.display='block';
        }
    }
    $(scope + '_' + type + '_spinner').style.visibility = 'hidden';
}

// call AjaxServices.filterWebSearchables() then hide those WebSearchables in
// the webSearchableList that don't match
function filterWebSearchables(objectId, scope, type, callId, tags) {

    if (futureFilterCalls[scope + "_" + type] != callId) {
        // filterWebSearchablesHandler() has been called again since this
        // timeout was set, so ignore as another timeout will be along
        // shortly
        return;
    }

    var object = document.getElementById(objectId);
    var value = object.value;
    var filterAction = document.getElementById('filterAction' + '_' + scope + '_' + type).value;

    if ((value != null && value.length > 1) || (tags != null && tags.length > 1)) {
        function filterCallBack(cbResult) {
            var callId = cbResult[0];
            var filteredList = cbResult.slice(1);

            if (currentFilterCallbacks[scope + "_" + type] != callId) {
                // we've started another call since this one started, so
                // ignore this one
                return;
            }

            do_filtering(filteredList, scope, type);
        }

        $(scope + '_' + type + '_spinner').style.visibility = 'visible';
        currentFilterCallbacks[scope + "_" + type] = callId;
        var tagList = null;

        /*  can only be one of these options:
        1. favourite
        2. aspect:<aspect>
        3. aspect:<aspect>|favourite
        4. null
         */

        if(tags != null && tags.length > 1) {
	        tagList = new Array();
			if (tags.match("|")) {
	        	var a = new Array();

    	    	a = tags.split('|');
        		for (var i=0, l=a.length; i<l; ++i) {
        			tagList[i] = a[i];
        		}
        	} else {
        		tagList[0] = tags;
        	}
        }

        /*  filterAction toggles favourites off and on */
        AjaxServices.filterWebSearchables(scope, type, tagList, object.value, filterAction, callId++,
                                          filterCallBack);
    } else {
        showAll(scope, type);
    }

    futureFilterCalls[scope + "_" + type] = 0;
}

function filterFavourites(scope,type) {
    var id = 'filterAction_'+scope+'_'+type;
    var tags = '';

    // aspect selected
    if (document.getElementById(scope+'_'+type+'_filter_aspect').value != '') {
    	tags = 'aspect:'+document.getElementById(scope+'_'+type+'_filter_aspect').value;
    }
    // favourites OFF
    if(document.getElementById(id).value == "favourites") {
        document.getElementById(id).value = "";
        document.getElementById('filter_favourites_'+scope+'_'+type).src = 'images/filter_favourites_ico.gif';
    // favourites ON
    } else {
        document.getElementById(id).value = "favourites";
        document.getElementById('filter_favourites_'+scope+'_'+type).src = 'images/filter_favourites_act_ico.gif';
        tags = (tags == '' ? 'favourite' : tags + '|favourite');
    }
    return filterWebSearchablesHandler(null,document.getElementById(scope+'_'+type+'_filter_text'), scope, type, tags);
}

function filterAspect(scope,type) {
	var tags = null;
	var id = 'filterAction_'+scope+'_'+type;
	var aspect = document.getElementById(scope+'_'+type+'_filter_aspect').value;

	// filter by favourites
    if(document.getElementById(id).value == "favourites") {
    	tags = 'favourite';
    }

    // aspects ON
    if(aspect != null && aspect.length > 1) {
        aspect = 'aspect:'+ aspect;
        tags = (tags == 'favourite' ? tags + '|' + aspect : aspect);
    }

    return filterWebSearchablesHandler(null,document.getElementById(scope+'_'+type+'_filter_text'), scope, type, tags);
}

<commit_msg>Fixed empty lists in the megatile.<commit_after>function setFavourite(name, type, image){
    AjaxServices.setFavourite(name, type);
    image.src='images/star_active.gif';
    image.onclick='';
    image.style.cursor='';
    image.title='This is a favourite';
}

function precomputeTemplate(templateName){
    document.getElementById('precompute_'+templateName).innerHTML="Precomputing..";
    AjaxServices.preCompute(templateName,function(str) {
        document.getElementById('precompute_'+templateName).style.color="#777";
        document.getElementById('precompute_'+templateName).innerHTML="Precomputed";
     });
}

function summariseTemplate(templateName){
    document.getElementById('summarise_'+templateName).innerHTML="Summarising..";
    AjaxServices.summarise(templateName,function(str) {
        document.getElementById('summarise_'+templateName).style.color="#777";
        document.getElementById('summarise_'+templateName).innerHTML="Summarised";
    });
}

function editName(name){
  document.getElementById('form_'+name).style.display="block";
  document.getElementById('name_'+name).style.display="none";
}

function renameElement(name, type, index){
    document.getElementById('form_'+name).style.display="none";
    document.getElementById('name_'+name).innerHTML="saving...";
    document.getElementById('name_'+name).style.display="block";
    AjaxServices.rename(name,type, (document.getElementById('newName_'+name).value).replace(/^\s*|\s*$/g,""), function(str){
        document.getElementById('name_'+name).innerHTML=str;
        document.getElementById('selected_user_' + type + '_' + index).value=str;
    });
}

function changeViewPathDescription(pathName){
    var pathString = pathName.replace(/\@sep\@/g,".");
    var pathEnd = pathString.substring(pathString.lastIndexOf('.') + 1);
    document.getElementById('form_'+pathName).style.display = "none";
    document.getElementById('name_'+pathName+'_inner').innerHTML = "saving...";
    document.getElementById('name_'+pathName).style.display = "block";
    var newDescription = document.getElementById('newName_' + pathName).value;
    var callBack = function(prefixDescription){
        if (prefixDescription == null) {
            prefixDescription = '(no description)';
        }
        document.getElementById('name_' + pathName + '_inner').innerHTML =
          '' + prefixDescription +
          ' > ' + pathEnd;
    }
    AjaxServices.changeViewPathDescription(pathString, newDescription, callBack);
}

function saveBagDescription(bagName){
    var textarea = document.getElementById('textarea').value;
    textarea = textarea.replace(/[\n\r]+/g, "\n\r
");
    document.getElementById('bagDescriptionDiv').innerHTML = 'Saving...';
    AjaxServices.saveBagDescription(bagName,textarea, function(str){
        document.getElementById('bagDescriptionDiv').innerHTML = str;
    });
    swapDivs('bagDescriptionTextarea','bagDescriptionDiv');
}

function swapDivs(div1,div2){
    document.getElementById(div1).style.display = 'none';
    document.getElementById(div2).style.display = 'block';
}

function roundToSignificantDecimal(n) {
    var log10n = Math.log(Math.abs(n)) / Math.log(10);
    if(log10n<1 && n!=0) {
        var rf = 100*Math.pow(10,-Math.round(log10n));
        return rf;
    } else return 100;
}

function updateCountInColumnSummary() {
    var countString = document.resultsCountText;
    if (countString == null) {
        setTimeout("updateCountInColumnSummary()", 1000);
        return;
    }

    document.getElementById('summary_row_count').innerHTML = "
" + countString + "
";

    var est = document.getElementById('resultsCountEstimate');
    if (est == null || est.style.display != 'none') {
        setTimeout("updateCountInColumnSummary()", 500);
        return;
    }
}

function updateUniqueCountInColumnSummary(uniqueCountQid) {
    getResults(uniqueCountQid, 1000, resultsCountCallback, null);
}

function resultsCountCallback(results) {
    var size = results[0][0];

    if (size > 1) {
        var summaryUniqueCountElement = document.getElementById('summary_unique_count');
        summaryUniqueCountElement.style.display='inline';
        summaryUniqueCountElement.innerHTML='Total unique values: ' + size;
    }
    return true;
}

function getColumnSummary(tableName, columnName, columnDisplayName) {
    document.getElementById('summary_loaded').style.display = "none";
    document.getElementById('summary_loading').style.display = "block";
    Effect.Appear('summary', { duration: 0.30 });
    AjaxServices.getColumnSummary(tableName, columnName, function(str){
        var rows = str[0];
        function rounder(cell) {
            if (cell==null) {
                return "[no value]" ;
            } if (! isNaN(cell)) {
                var rf = roundToSignificantDecimal(cell+0);
                return Math.round(cell*rf)/rf;
            } else {
                return cell;
            }
        }
        var headerText;
        if(rows[0].length == 2){
            headerText = '
Value	Count
';
        } else {
            headerText = '
Min	Max	Sample Mean	Standard Deviation
';
        }

        document.getElementById('summary_loading').style.display = "none";
        document.getElementById('summary_loaded').style.display = "block";

        var bodyText = '';

        for (rowIndex = 0; rowIndex < rows.length; rowIndex++) {
            var row = rows[rowIndex];
            bodyText += '
';
            for (colIndex = 0; colIndex < row.length; colIndex++) {
                var cellValue = rounder(row[colIndex]);
                bodyText += '' + cellValue + '	';
            }
            bodyText += '
';
        }

        var html = '
                                         \

                                     \
                        Column Summary for ' + columnDisplayName + '          \

                                                  \

                      \

                   \

                                                   \

 \

' + headerText +'
    \

' + bodyText + '
    \

                                                \

';

        var summaryLoadedElement = document.getElementById('summary_loaded');
        summaryLoadedElement.innerHTML = html;
        var uniqueCountQid = str[1];
        setTimeout("updateCountInColumnSummary()", 200);
        setTimeout("updateUniqueCountInColumnSummary(" + uniqueCountQid + ")", 300);
    });
}

function getResultsPoller(qid, timeout, userCallback, userData) {
    var callback = function(results) {
        if (results == null) {
            // try again
            getResults(qid, timeout, userCallback, userData);
        } else {
            if (!userCallback(results, userData)) {
                getResults(qid, timeout, userCallback, userData);
            }
        }
    }

    AjaxServices.getResults(qid, callback);
}

function getResults(qid, timeout, userCallback, userData) {
    setTimeout("getResultsPoller(" + qid + ", " + timeout + ", " + userCallback + ","
               + userData + ")", timeout);
}

// delete all the child nodes of the node given by parentElement and create a child
// element of type childTag, setting the text in the new child element to be
// childText
function setChild(parentElement, childText, childTag) {
    var newChild = document.createElement(childTag);
    newChild.innerHTML = childText;
    if (parentElement.firstChild != null) {
        while (parentElement.hasChildNodes()) {
            parentElement.removeChild(parentElement.firstChild);
        }
    }
    parentElement.appendChild(newChild);
    return newChild;
}

var callId = 1;

// Give each ajax call an id and remember what our current pending id is
var currentFilterCallbacks = new Array();

// Give each setTimeout call an id and remember what our current pending id is
var futureFilterCalls = new Array();

function filterWebSearchablesHandler(event, object, scope, type, tags) {
    if (window.event) {
        event = window.event;
    }
    if (event) {
	    if (event.keyCode == 27) {
	        object.value = '';
	        return;
	    }
	    if (event.keyCode == 13) {
	        return;
	    }
	}

    futureFilterCalls[scope + "_" + type] = callId;

    if (tags == null) {
        tags = [];
    }

    setTimeout('filterWebSearchables("' + object.id + '", "' + scope + '","' + type + '",' +
               callId + ",'" + tags + "')", 500);
    callId++;
}

// given a list of WebSearchables names,scores and descriptions, filter the
// wsFilterList given by the scope and type parameters
function do_filtering(filteredList, scope, type) {
    if (filteredList.length == 0) {
        showAll(scope, type);
    } else {
        var scoreHash = new Array();
        var descHash = new Array();
        var hitHash = new Array();

        for (var el in filteredList) {
            var wsName = filteredList[el][0];
            var wsDesc = filteredList[el][1];
            descHash[scope + '_' + type + '_item_line_' + wsName] = wsDesc;
            var wsScore = filteredList[el][2];
            scoreHash[scope + '_' + type + '_item_line_' + wsName] = wsScore;
            hitHash[scope + '_' + type + '_item_line_' + wsName] = 1;
        }

        var pattern = new RegExp('^' + scope + '_' + type + '_item_line_(.*)');
        var inputArray = document.getElementsByTagName("div");
        for(var i=0; i<inputArray.length; i++) {
            if ((result = pattern.exec(inputArray[i].id)) != null) {
                if (hitHash[inputArray[i].id]) {
                    inputArray[i].style.display='block';
                    var highlightText = descHash[inputArray[i].id];

                    if (highlightText) {
                        var descId = scope + '_' + type + '_item_description_' + result[1];
                        var desc = $(descId);

                        var descChild = setChild(desc, highlightText, 'p');
                        descChild.className = 'description';
                    }

                    if (scoreHash[inputArray[i].id]) {
                        var scoreWsName = result[1];
                        var score = scoreHash[inputArray[i].id];
                        var intScore = parseInt(score * 10);
                        var scoreId = scope + '_' + type + '_item_score_' + scoreWsName;
                        var scoreSpan = $(scoreId);
                        // we do this instead of scoreSpan.innerHTML = "stuff"
                        // because it's buggy in Internet Explorer
                        var heatImage = 'heat' + intScore + '.gif';
                        var heatText = '';
                        setChild(scoreSpan, heatText, 'span');
                    }
                } else {
                    inputArray[i].style.display='none';
                }
            }
        }

        function sortWsFilter(el1, el2) {
            var el1score = scoreHash[el1.id];
            var el2score = scoreHash[el2.id]
                if (el1score > el2score) {
                    return -1;
                } else {
                    if (el1score < el2score) {
                        return 1;
                    } else {
                        return 0;
                    }
                }
        }

        var parent = $(scope + '_' + type + '_ws_list');
        var divs = new Array();

        for (var i in parent.childNodes) {
            var child = parent.childNodes[i];
            if (child.tagName == 'DIV' && scoreHash[child.id]) {
                divs.push(child);
            }
        }

        divs.sort(sortWsFilter);

        for (var i = 0; i < divs.length; i++) {
            parent.appendChild(divs[i]);
        }

        $(scope + '_' + type + '_spinner').style.visibility = 'hidden';
    }
}

// un-hide all the rows in the webSearchableList
function showAll(scope, type) {
    var pattern = new RegExp('^' + scope + '_' + type + '_item_line_(.*)');
    var inputArray = document.getElementsByTagName("div");
    for(var i=0; i<inputArray.length; i++) {
        var result;
        if ((result = pattern.exec(inputArray[i].id)) != null) {
            inputArray[i].style.display='block';
        }
    }
    $(scope + '_' + type + '_spinner').style.visibility = 'hidden';
}

// call AjaxServices.filterWebSearchables() then hide those WebSearchables in
// the webSearchableList that don't match
function filterWebSearchables(objectId, scope, type, callId, tags) {

        // filterWebSearchablesHandler() has been called again since this
        // timeout was set, so ignore as another timeout will be along
        // shortly
        return;
    }

    var object = document.getElementById(objectId);
    var value = object.value;
    var filterAction = document.getElementById('filterAction' + '_' + scope + '_' + type).value;

    if ((value != null && value.length > 1) || (tags != null && tags.length > 1)) {
        function filterCallBack(cbResult) {
            var callId = cbResult[0];
            var filteredList = cbResult.slice(1);

            if (currentFilterCallbacks[scope + "_" + type] != callId) {
                // we've started another call since this one started, so
                // ignore this one
                return;
            }

            do_filtering(filteredList, scope, type);
        }

        $(scope + '_' + type + '_spinner').style.visibility = 'visible';
        currentFilterCallbacks[scope + "_" + type] = callId;
        var tagList = null;

        /*  can only be one of these options:
        1. favourite
        2. aspect:<aspect>
        3. aspect:<aspect>|favourite
        4. null
         */

        if(tags != null && tags.length > 1) {
	        tagList = new Array();
			if (tags.match("|")) {
	        	var a = new Array();

    	    	a = tags.split('|');
        		for (var i=0, l=a.length; i<l; ++i) {
        			tagList[i] = a[i];
        		}
        	} else {
        		tagList[0] = tags;
        	}
        }

        /*  filterAction toggles favourites off and on */
        AjaxServices.filterWebSearchables(scope, type, tagList, object.value, filterAction,
                                          callId++, filterCallBack);
    } else {
        showAll(scope, type);
    }

    futureFilterCalls[scope + "_" + type] = 0;
}

function filterFavourites(scope,type) {
    var id = 'filterAction_'+scope+'_'+type;
    var tags = '';

    // aspect selected
    if (document.getElementById(scope+'_'+type+'_filter_aspect').value != '') {
    	tags = 'aspect:'+document.getElementById(scope+'_'+type+'_filter_aspect').value;
    }
    // favourites OFF
    if(document.getElementById(id).value == "favourites") {
        document.getElementById(id).value = "";
        document.getElementById('filter_favourites_'+scope+'_'+type).src = 'images/filter_favourites_ico.gif';
    // favourites ON
    } else {
        document.getElementById(id).value = "favourites";
        document.getElementById('filter_favourites_'+scope+'_'+type).src = 'images/filter_favourites_act_ico.gif';
        tags = (tags == '' ? 'favourite' : tags + '|favourite');
    }
    return filterWebSearchablesHandler(null,document.getElementById(scope+'_'+type+'_filter_text'),
    								   scope, type, tags);
}

function filterAspect(scope,type) {
	var tags = null;
	var id = 'filterAction_'+scope+'_'+type;
	var aspect = document.getElementById(scope+'_'+type+'_filter_aspect').value;

	// filter by favourites
    if(document.getElementById(id).value == "favourites") {
    	tags = 'favourite';
    }

    // aspects ON
    if(aspect != null && aspect.length > 1) {
        aspect = 'aspect:'+ aspect;
        tags = (tags == 'favourite' ? tags + '|' + aspect : aspect);
    }

    return filterWebSearchablesHandler(null,document.getElementById(scope+'_'+type+'_filter_text'),
                                       scope, type, tags);
}

<|endoftext|>


<commit_before>/**
 * @fileoverview Misc type
 *
 * @externs
 */

/**
 * Encryption option.
 * @constructor
 */
function EncryptionOption() {}

/**
 * @type {number|undefined}
 */
EncryptionOption.prototype.expiration;

/**
 * @type {boolean|undefined}
 */
EncryptionOption.prototype.encryptKey;

/**
 * @type {boolean|undefined}
 */
EncryptionOption.prototype.unsafe_parse;

/**
 * @type {string|undefined}
 */
EncryptionOption.prototype.method;

/**
 * Encryption option.
 * @constructor
 */
function EncryptionOptionSecret() {}

/**
 * @type {string}
 */
EncryptionOptionSecret.prototype.name;

/**
 * @type {string}
 */
EncryptionOptionSecret.prototype.key;

/**
 * @type {Array<EncryptionOptionSecret>}
 */
EncryptionOption.prototype.secrets;

/**
 * @constructor
 */
function StorageOptions() {}

/**
 * Estimated database size for WebSQL.
 * @type {number|undefined}
 */
StorageOptions.prototype.size;

/**
 * Preferential ordering of storage mechanisms.
 * @type {!Array.<string>|undefined}
 */
StorageOptions.prototype.mechanisms;

/**
 * @type {boolean}
 */
StorageOptions.prototype.autoSchema;

/**
 * @type {string|undefined}
 */
StorageOptions.prototype.policy;

/**
 * @type {boolean|undefined}
 */
StorageOptions.prototype.isSerial;

/**
 * @type {number|undefined}
 */
StorageOptions.prototype.connectionTimeout;

/**
 * @type {EncryptionOption}
 */
StorageOptions.prototype.Encryption;

/**
 * @constructor
 */
function KeyRangeJson() {}

/**
 * @type {number|string|!Date|!Array.<number|string|!Date>|undefined}
 */
KeyRangeJson.prototype.lower;

/**
 * @type {boolean}
 */
KeyRangeJson.prototype.lowerOpen;

/**
 * @type {number|string|!Date|!Array.<number|string|!Date>|undefined}
 */
KeyRangeJson.prototype.upper;

/**
 * @type {boolean}
 */
KeyRangeJson.prototype.upperOpen;

/**
 * @const
 * @type {Object}
 */
var DataSourceOption = {};

/**
 * @constructor
 */
var GDataSourceOption = function() {};

/**
 * @type {string}
 */
GDataSourceOption.prototype.kind;

/**
 * @type {string}
 */
GDataSourceOption.prototype.id;

/**
 * @constructor
 * @extends {GDataSourceOption}
 */
var ContactDataSourceOption = function() {};

/**
 * Record format for {@see ydn.debug.DbLogger}.
 * @interface.
 */
var DbLoggerRecord = function() {};

/** @type {string} */
DbLoggerRecord.prototype.exception;

/** @type {number} */
DbLoggerRecord.prototype.level;

/** @type {string} */
DbLoggerRecord.prototype.logger;

/** @type {string} */
DbLoggerRecord.prototype.name;

/** @type {number} */
DbLoggerRecord.prototype.time;

/** @type {string} */
DbLoggerRecord.prototype.message;

/** @type {number} */
DbLoggerRecord.prototype.seq;

/**
 * JSON format in result of db.search() query.
 * Stringify out put of ydn.db.schema.fulltext.Entry.
 * @constructor
 */
var DbFullTextSearchResult = function() {};

/**
 * @constructor
 */
DbFullTextSearchResult.Token = function() {};

/**
 * Keypath of token.
 * @type {string}
 */
DbFullTextSearchResult.Token.prototype.keyPath;

/**
 * Index of location of matching keyword in the document.
 * @type {!Array.<number>}
 */
DbFullTextSearchResult.Token.prototype.loc;

/**
 * Keyword from the document.
 * @type {string}
 */
DbFullTextSearchResult.Token.prototype.value;

/**
 * Primary key of the document, in which it was found.
 * @type {number|string|!Date|!Array.<number|string|!Date>}
 */
DbFullTextSearchResult.prototype.primaryKey;

/**
 * Matching score.
 * @type {number}
 */
DbFullTextSearchResult.prototype.score;

/**
 * Target store name.
 * @type {string}
 */
DbFullTextSearchResult.prototype.storeName;

/**
 * Search result.
 * @type {!Array.<DbFullTextSearchResult.Token>}
 */
DbFullTextSearchResult.prototype.tokens;

/**
 * Search value.
 * @type {string}
 */
DbFullTextSearchResult.prototype.value;

/**
 * Record value of given primaryKey from storeName object store. This value
 * is not set by search return result.
 * @type {*}
 */
DbFullTextSearchResult.prototype.record;

<commit_msg>add unsafeparse option on cryto<commit_after>/**
 * @fileoverview Misc type
 *
 * @externs
 */

/**
 * Encryption option.
 * @constructor
 */
function EncryptionOption() {}

/**
 * @type {number|undefined}
 */
EncryptionOption.prototype.expiration;

/**
 * @type {boolean|undefined}
 */
EncryptionOption.prototype.encryptKey;

/**
 * @type {boolean|undefined}
 */
EncryptionOption.prototype.unsafeParse;

/**
 * @type {string|undefined}
 */
EncryptionOption.prototype.method;

/**
 * Encryption option.
 * @constructor
 */
function EncryptionOptionSecret() {}

/**
 * @type {string}
 */
EncryptionOptionSecret.prototype.name;

/**
 * @type {string}
 */
EncryptionOptionSecret.prototype.key;

/**
 * @type {Array<EncryptionOptionSecret>}
 */
EncryptionOption.prototype.secrets;

/**
 * @constructor
 */
function StorageOptions() {}

/**
 * Estimated database size for WebSQL.
 * @type {number|undefined}
 */
StorageOptions.prototype.size;

/**
 * Preferential ordering of storage mechanisms.
 * @type {!Array.<string>|undefined}
 */
StorageOptions.prototype.mechanisms;

/**
 * @type {boolean}
 */
StorageOptions.prototype.autoSchema;

/**
 * @type {string|undefined}
 */
StorageOptions.prototype.policy;

/**
 * @type {boolean|undefined}
 */
StorageOptions.prototype.isSerial;

/**
 * @type {number|undefined}
 */
StorageOptions.prototype.connectionTimeout;

/**
 * @type {EncryptionOption}
 */
StorageOptions.prototype.Encryption;

/**
 * @constructor
 */
function KeyRangeJson() {}

/**
 * @type {number|string|!Date|!Array.<number|string|!Date>|undefined}
 */
KeyRangeJson.prototype.lower;

/**
 * @type {boolean}
 */
KeyRangeJson.prototype.lowerOpen;

/**
 * @type {number|string|!Date|!Array.<number|string|!Date>|undefined}
 */
KeyRangeJson.prototype.upper;

/**
 * @type {boolean}
 */
KeyRangeJson.prototype.upperOpen;

/**
 * @const
 * @type {Object}
 */
var DataSourceOption = {};

/**
 * @constructor
 */
var GDataSourceOption = function() {};

/**
 * @type {string}
 */
GDataSourceOption.prototype.kind;

/**
 * @type {string}
 */
GDataSourceOption.prototype.id;

/**
 * @constructor
 * @extends {GDataSourceOption}
 */
var ContactDataSourceOption = function() {};

/**
 * Record format for {@see ydn.debug.DbLogger}.
 * @interface.
 */
var DbLoggerRecord = function() {};

/** @type {string} */
DbLoggerRecord.prototype.exception;

/** @type {number} */
DbLoggerRecord.prototype.level;

/** @type {string} */
DbLoggerRecord.prototype.logger;

/** @type {string} */
DbLoggerRecord.prototype.name;

/** @type {number} */
DbLoggerRecord.prototype.time;

/** @type {string} */
DbLoggerRecord.prototype.message;

/** @type {number} */
DbLoggerRecord.prototype.seq;

/**
 * JSON format in result of db.search() query.
 * Stringify out put of ydn.db.schema.fulltext.Entry.
 * @constructor
 */
var DbFullTextSearchResult = function() {};

/**
 * @constructor
 */
DbFullTextSearchResult.Token = function() {};

/**
 * Keypath of token.
 * @type {string}
 */
DbFullTextSearchResult.Token.prototype.keyPath;

/**
 * Index of location of matching keyword in the document.
 * @type {!Array.<number>}
 */
DbFullTextSearchResult.Token.prototype.loc;

/**
 * Keyword from the document.
 * @type {string}
 */
DbFullTextSearchResult.Token.prototype.value;

/**
 * Primary key of the document, in which it was found.
 * @type {number|string|!Date|!Array.<number|string|!Date>}
 */
DbFullTextSearchResult.prototype.primaryKey;

/**
 * Matching score.
 * @type {number}
 */
DbFullTextSearchResult.prototype.score;

/**
 * Target store name.
 * @type {string}
 */
DbFullTextSearchResult.prototype.storeName;

/**
 * Search result.
 * @type {!Array.<DbFullTextSearchResult.Token>}
 */
DbFullTextSearchResult.prototype.tokens;

/**
 * Search value.
 * @type {string}
 */
DbFullTextSearchResult.prototype.value;

/**
 * Record value of given primaryKey from storeName object store. This value
 * is not set by search return result.
 * @type {*}
 */
DbFullTextSearchResult.prototype.record;

<|endoftext|>


<commit_before>/*
`tsv` is a string of tab-separated url and title.
`raw` is an ordered array with JSON of {url: url, title: title}.
*/

function zip(x, y) {
	return x.map(function (element, i) {
    	return [element, y[i]];
	});
}

/*
 using items array of urls and titles,
 create a TSV string of url, title format
*/
function toTSV(items) {
	var tsv = "";
	for (item of items) {
		tsv += item.url+"\t"+item.title+"\n"
	}
	return tsv;
}

function extractTabsOther() {
	var historyApp = document.getElementById("history-app").shadowRoot;
	var mainContainer = historyApp.getElementById("main-container");
	var content = mainContainer.getElementsByTagName("iron-pages")[0];
	var syncedDevices = content.getElementsByTagName("history-synced-device-manager")[0].shadowRoot;
	var syncedDeviceList = syncedDevices.getElementById("synced-device-list");
	var historySyncedDeviceCard = syncedDeviceList.getElementsByTagName("history-synced-device-card")[0].shadowRoot;
	var historyItemContainer = historySyncedDeviceCard.getElementById("history-item-container");
	var ironCollapse = historyItemContainer.getElementsByTagName("iron-collapse")[0];
	var tabItemList = ironCollapse.getElementsByTagName("div")[0];
	var tabItems = tabItemList.getElementsByClassName("item-container");
	var items = [];
	for (tabItem of tabItems) {
		item = tabItem.getElementsByClassName("website-title")[0];
		var page = {};
		page["title"] = item.title;
		page["url"] = item.href;
		items.push(page);
	}
	return {"tsv": toTSV(items), "raw": items}
}

function extractTabsMe() {
	var names = [].slice.call(document.getElementsByClassName("name"));
	var urls = [].slice.call(document.getElementsByClassName("url"));
	var items = [];
	for (item of zip(names, urls)) {
		var page = {};
		page["title"] = item[0].innerHTML;
		page["url"] = item[1].innerHTML;
		items.push(page);
	}
	return {"tsv": toTSV(items), "raw": items}
}
<commit_msg>Fix tab size from 8 to 4 spaces<commit_after>/*
`tsv` is a string of tab-separated url and title.
`raw` is an ordered array with JSON of {url: url, title: title}.
*/

function zip(x, y) {
	return x.map(function (element, i) {
    	return [element, y[i]];
	});
}

/*
using items array of urls and titles,
create a TSV string of url, title format
*/
function toTSV(items) {
	var tsv = "";
	for (item of items) {
		tsv += item.url+"\t"+item.title+"\n"
	}
	return tsv;
}

function extractTabsOther() {
	var historyApp = document.getElementById("history-app").shadowRoot;
	var mainContainer = historyApp.getElementById("main-container");
	var content = mainContainer.getElementsByTagName("iron-pages")[0];
	var syncedDevices = content.getElementsByTagName("history-synced-device-manager")[0].shadowRoot;
	var syncedDeviceList = syncedDevices.getElementById("synced-device-list");
	var historySyncedDeviceCard = syncedDeviceList.getElementsByTagName("history-synced-device-card")[0].shadowRoot;
	var historyItemContainer = historySyncedDeviceCard.getElementById("history-item-container");
	var ironCollapse = historyItemContainer.getElementsByTagName("iron-collapse")[0];
	var tabItemList = ironCollapse.getElementsByTagName("div")[0];
	var tabItems = tabItemList.getElementsByClassName("item-container");
	var items = [];
	for (tabItem of tabItems) {
		item = tabItem.getElementsByClassName("website-title")[0];
		var page = {};
		page["title"] = item.title;
		page["url"] = item.href;
		items.push(page);
	}
	return {"tsv": toTSV(items), "raw": items}
}

function extractTabsMe() {
	var names = [].slice.call(document.getElementsByClassName("name"));
	var urls = [].slice.call(document.getElementsByClassName("url"));
	var items = [];
	for (item of zip(names, urls)) {
		var page = {};
		page["title"] = item[0].innerHTML;
		page["url"] = item[1].innerHTML;
		items.push(page);
	}
	return {"tsv": toTSV(items), "raw": items}
}
<|endoftext|>


<commit_before>var mongoose = require('mongoose');
exports.mongoose = mongoose;
// --------------------------------------------------------------------------------------
var logs_schema = mongoose.Schema({
  timestamp : Date,
  realm : String,
  viscountry : String,
  visinst : String,
  csi : String,
  pn : String,
  result : String
});
// --------------------------------------------------------------------------------------
exports.logs_schema = logs_schema;
var logs = mongoose.model('logs', logs_schema, 'logs');
exports.logs = logs;
// --------------------------------------------------------------------------------------
var users_mac_schema = mongoose.Schema({
  username : String,
  addrs : Array
});
// --------------------------------------------------------------------------------------
exports.users_mac_schema = users_mac_schema;
var users_mac = mongoose.model('users_mac', users_mac_schema, 'users_mac');
exports.users_mac = users_mac;
// --------------------------------------------------------------------------------------
var privileged_ips_schema = mongoose.Schema({
  ip : String
});
// --------------------------------------------------------------------------------------
exports.privileged_ips = privileged_ips;
var privileged_ips = mongoose.model('privileged_ips', privileged_ips_schema, 'privileged_ips');
exports.privileged_ips = privileged_ips;
// --------------------------------------------------------------------------------------
var invalid_records_schema = mongoose.Schema({
  date : string,
  records : Array
});
// --------------------------------------------------------------------------------------
exports.invalid_records = invalid_records;
var invalid_records = mongoose.model('invalid_records', invalid_records_schema, 'invalid_records');
exports.invalid_records = invalid_records;
// --------------------------------------------------------------------------------------
mongoose.connect('mongodb://localhost/etlog');
mongoose.connection.on('error', console.error.bind(console, 'connection error:'));
mongoose.connection.once('open', function (callback) {
  console.log("sucesfully connected do mongodb database on localhost");
});
// --------------------------------------------------------------------------------------
<commit_msg>fix string to String<commit_after>var mongoose = require('mongoose');
exports.mongoose = mongoose;
// --------------------------------------------------------------------------------------
var logs_schema = mongoose.Schema({
  timestamp : Date,
  realm : String,
  viscountry : String,
  visinst : String,
  csi : String,
  pn : String,
  result : String
});
// --------------------------------------------------------------------------------------
exports.logs_schema = logs_schema;
var logs = mongoose.model('logs', logs_schema, 'logs');
exports.logs = logs;
// --------------------------------------------------------------------------------------
var users_mac_schema = mongoose.Schema({
  username : String,
  addrs : Array
});
// --------------------------------------------------------------------------------------
exports.users_mac_schema = users_mac_schema;
var users_mac = mongoose.model('users_mac', users_mac_schema, 'users_mac');
exports.users_mac = users_mac;
// --------------------------------------------------------------------------------------
var privileged_ips_schema = mongoose.Schema({
  ip : String
});
// --------------------------------------------------------------------------------------
exports.privileged_ips = privileged_ips;
var privileged_ips = mongoose.model('privileged_ips', privileged_ips_schema, 'privileged_ips');
exports.privileged_ips = privileged_ips;
// --------------------------------------------------------------------------------------
var invalid_records_schema = mongoose.Schema({
  date : String,
  records : Array
});
// --------------------------------------------------------------------------------------
exports.invalid_records = invalid_records;
var invalid_records = mongoose.model('invalid_records', invalid_records_schema, 'invalid_records');
exports.invalid_records = invalid_records;
// --------------------------------------------------------------------------------------
mongoose.connect('mongodb://localhost/etlog');
mongoose.connection.on('error', console.error.bind(console, 'connection error:'));
mongoose.connection.once('open', function (callback) {
  console.log("sucesfully connected do mongodb database on localhost");
});
// --------------------------------------------------------------------------------------
<|endoftext|>


<commit_before>(function(){
  function indexOf(which, searchElement) {
    for(var ix = which.length - 1;
        ix > -1 ;
        ix--
      ) {
      if (searchElement == which[ix]) {
        break;
      }
    }

    return ix;
  }

  // The first parameter, if exists, is assumed to be the value in the database,
  // which has a content of arrays, to search.
  // The second parameter is the index to search
  function has(param1, param2) {
    var
      callback,
      comparator,
      obj = {};

    if(arguments.length == 1) {
      comparator = param1;
    } else if(arguments.length == 2){
      comparator = param2;
    }

    if(comparator.constructor == Array) {
      var len = comparator.length;

      // This becomes O(N * M)
      callback = function(key) {
        for(ix = 0; ix < len; ix++) {
          if (indexOf(key, comparator[ix]) > -1) {
            return true;
          }
        }
        return false;
      }
    } else {
      // This is O(N)
      callback = function(key) {
        return indexOf(key, comparator) > -1;
      }
    }

    if(arguments.length == 2) {
      obj = {};
      obj[param1] = callback;
      return obj;
    } else {
      return callback;
    }
  }

  function isin(param1, param2) {
    var
      comparator,
      obj = {};

    if(arguments.length == 1) {
      comparator = param1;
    } else if(arguments.length == 2){
      comparator = param2;
    }

    // If the second argument is an array then we assume that we are looking
    // to see if the value in the database is part of the user supplied funciton
    if(comparator.constructor == Array) {
      comparator = function(x) { return indexOf(x, comparator) > -1; };
    } else if (comparator instanceof Function) {
      comparator = function(x) { return indexOf(x, comparator()) > -1; };
    }

    if(arguments.length == 2) {
      obj = {};
      obj[param1] = comparator;
      return obj;
    } else {
      return comparator;
    }
  }

  function like(param1, param2) {
    var
      comparator,
      query,
      obj = {};

    if(arguments.length == 1) {
      query = param1;
    } else if(arguments.length == 2){
      query = param2;
    }

    query = query.toString().toLowerCase();

    comparator = function(x) { return x.toString().toLowerCase().search(query) > -1; };

    if(arguments.length == 2) {
      obj = {};
      obj[param1] = comparator;
      return obj;
    } else {
      return comparator;
    }
  }

  window.DB = function(){
    var
      constraints = {},
      ixlast = 0,
      raw = {};

    function expression(){
      if(typeof arguments[0] == 'string') {
        if(arguments.length == 1) {
          return new Function("$$x$$", "return $$x$$ " + arguments[0]);
        }

        if(arguments.length == 2 && typeof arguments[1] == 'string') {
          var obj = {};
          obj[arguments[0]] = new Function("$$x$$", "return $$x$$ " + arguments[1]);
          return obj;
        }
      }
    }

    // Jacked from Resig's jquery 1.5.2
    // The code has been modified to not rely on jquery
    function extend() {
      var
        options, name, src, copy, copyIsArray, clone,
        target = arguments[0] || {},
        i = 1,
        length = arguments.length,
        deep = false;

      // Handle a deep copy situation
      if ( typeof target === "boolean" ) {
        deep = target;
        target = arguments[1] || {};
        // skip the boolean and the target
        i = 2;
      }

      // Handle case when target is a string or something (possible in deep copy)
      if ( typeof target !== "object" && typeof target !== 'function') {
        target = {};
      }

      // extend jQuery itself if only one argument is passed
      if ( length === i ) {
        target = this;
        --i;
      }

      for ( ; i < length; i++ ) {
        // Only deal with non-null/undefined values
        if ( (options = arguments[ i ]) != null ) {
          // Extend the base object
          for ( name in options ) {
            src = target[ name ];
            copy = options[ name ];

            // Prevent never-ending loop
            if ( target === copy ) {
               continue;
            }

            // Recurse if we're merging plain objects or arrays
            if ( deep && copy && ( copy.constructor == Object || (copyIsArray = (copy.constructor == Array)) ) ) {
              if ( copyIsArray ) {
                copyIsArray = false;
                clone = src && (src.constructor == Array) ? src : [];
              } else {
                clone = src && (src.constructor == Object) ? src : {};
              }

              // Never move original objects, clone them
              target[ name ] = extend( deep, clone, copy );

            // Don't bring in undefined values
            } else if ( copy !== undefined ) {
              target[ name ] = copy;
            }
          }
        }
      }

      // Return the modified object
      return target;
    };

    function deepcopy(from) {
      //@http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-a-javascript-object
      return extend(true, {}, from);
    }

    function list2obj(list) {
      var ret = {};
      each(list, function(which) {
        ret[which] = true;
      });

      return ret;
    }

    function values(obj) {
      var ret = [];

      for(var key in obj) {
        ret.push(obj[key]);
      }

      return ret;
    }

    function keys(obj) {
      var ret = [];

      for(var key in obj) {
        ret.push(key);
      }

      return ret;
    }

    var obj2list = keys;

    function each(obj, cb) {
      if (obj instanceof Array) {
        var
          ix = 0,
          len = obj.length;

        for(; ix < len; ix++) {
          cb(obj[ix], ix);
        }
      } else {
        for(var key in obj) {
          cb(key, obj[key]);
        }
      }
    }

    function res2list(res) {
      var list = [];

      each(res, function(which) {
        list.push(which.constructor('ix'));
      });

      return list;
    }

    function setdiff(larger, subset) {
      larger = list2obj(larger);
      subset = list2obj(subset);

      for(var key in subset) {
        if(larger[key]) {
          delete larger[key];
        }
      }

      return keys(larger);
    }

    function list2data(list) {
      var
        ix = 0,
        len = list.length,
        ret = new Array(len);

      for(; ix < len; ix++) {
        ret[ix] = raw[list[ix]];
      }

      return ret;
    }

    function kvarg(which){
      var ret = {};

      if(which.length == 2) {
        ret[which[0]] = which[1];
        return ret;
      }
      if(which.length == 1) {
        return which[0];
      }
    }

    // An encapsulator for hiding internal variables
    function secret() {
      var cache = {};
      return function(){
        if (arguments.length == 1) { return cache[arguments[0]];}
        if (arguments.length == 2) { cache[arguments[0]] = arguments[1]; }
      };
    }

    ret = expression;
    ret.expr = expression;
    ret.isin = isin;
    ret.has = has;
    ret.ilike = ret.like = like;

    function chain(list) {
      for(var func in ret) {
        list[func] = ret[func];
      }

      return list;
    }

    function find() {
      var
        filterList = Array.prototype.slice.call(arguments),
        iy,
        ix,
        len,
        key,
        which,
        filtered,
        nextRound = [],
        value;

      // This permits a subfind
      if(this instanceof Array) {
        filtered = keys(this);
      } else {
        filtered = keys(raw);
      }

      if(filterList.length == 0) {
        filterList = [{}];
      }

      // This permits find(key, value)
      if( filterList.length == 2 &&
          typeof filterList[0] == 'string'
        ) {
          which = {};
          which[filterList[0]] = filterList[1];
          filterList = [deepcopy(which)];
      }

      // We can either do find({}) or find({},{},{})
      for(iy = 0; iy < filterList.length; iy++) {
        var obj = filterList[iy];

        each(obj, function(key, value) {

          // If the directive is not, then we find everything
          // that satisfies the query after the not
          if(key == 'not' && typeof value == 'object') {
            nextRound = setdiff(filtered, find(value));
          } else {
            len = filtered.length;

            for(ix = 0; ix < len; ix++) {
              which = filtered[ix];

              if(
                // Check for existence
                key in raw[which] && (

                  // This is an expression based callback
                  (
                    typeof value == 'function' &&
                    value(raw[which][key])
                  ) ||

                  // Trivial value comparison
                  (raw[which][key] == value)  ||

                  // Less trivial value comparison
                  ( (
                      value.toString &&
                      raw[which][key].toString
                    ) && (
                      value.toString() ==
                      raw[which][key].toString()
                    )
                  )
                )
              ) {
                nextRound.push(which);
              }
            }
          }

          filtered = nextRound;
          nextRound = [];
        });
      }

      return chain(filtered);
    }

    ret.constrain = function() {
      constraints = extend(true, constraints, kvarg(arguments));
    }

    ret.each = function(callback) {
      var
	      ret = [],
	      filter;

      if(arguments.length == 2) {
	      filter = arguments[0];
	      callback = arguments[1];
	    } else {
        filter = this;
      }

      each(filter, function(){
        ret.push(callback.apply(this, arguments));
      });

      return ret;
    }

    ret.inverse = function(list) {
      if(arguments.length == 0 && this instanceof Array) {
        list = this;
      }

      return chain(setdiff(keys(raw), list));
    }

    ret.where = ret.find = function() {
      return chain(list2data(find.apply(this, arguments)));
    }

    ret.select = function(field) {
      var
        result,
        filter,
        resultList = [];

      if(arguments.length > 1) {
        field = Array.prototype.slice.call(arguments);
      } else if (typeof field == 'string') {
        field = [field];
      }

      if(this instanceof Array) {
        filter = this;
      } else {
        filter = ret.find();
      }

      each(filter, function (row) {
        result = [];

        each(field, function (column) {
          if(column == '*') {
            result = result.concat(values(row));
          } else {
            result.push(row[column]);
          }
        });

        resultList.push(result);
      });

      // select doesn't change data
      //ret.sync(raw);

      return chain(resultList);
    }

    ret.insert = function(param) {
      var
        block = [],
        toInsert = [],
        ixList = [];

      if(arguments.length > 1) {
        toInsert = Array.prototype.slice.call(arguments);
      } else if (param.constructor == Array) {
        toInsert = param;
      } else if (param.constructor == Object) {
        toInsert = [param];
      }

      // If the user had opted for a certain field to be unique,
      // then we find all the matches to that field and create
      // a block list from them.
      if(constraints.unique) {
        block = db.find().select(constraints.unique);
      }

      each(toInsert, function(which) {
        // If the unique field has been set then we do
        // a linear search through the constraints to
        // see if it's there.
        if(constraints.unique) {
          if(indexOf(block, which[constraints.unique]) != -1){
            return;
          }
        }

        var ix = ixlast++;
        raw[ix] = new (secret())();
        extend(true, raw[ix], which);
        raw[ix].constructor('ix', ix);

        ixList.push(ix);
      });

      ret.sync(raw);
      return chain(list2data(ixList));
    }

    // Update allows you to set newvalue to all
    // parameters matching constraint where constraint
    // is either a set of K/V pairs or a result
    // of find so that you can do something like
    //
    //   var result = db.find(constraint);
    //   result.update({a: b});
    //
    ret.update = function(newvalue, param) {
      var
        list,
        key;

      if(this instanceof Array) {
        list = res2list(this);
      } else {
        list = find();
      }

      // This permits update(key, value) on a chained find
      if( arguments.length == 2 &&
          typeof arguments[0] == 'string'
        ) {

        // Store the key string
        key = newvalue;

        // The constraint is actually the new value to be
        // assigned.
        newvalue = {};
        newvalue[key] = param;
      }

      each(newvalue, function(key, value) {
        if(typeof value == 'function') {
          each(list, function(index) {
            raw[index][key] = value(raw[index]);
          });
        } else {
          each(list, function(index) {
            raw[index][key] = value;
          });
        }
      });

      ret.sync(raw);
      return chain(list2data(list));
    }

    ret.order = function() {
      var
        key,
        fnSort,
        order,
        filter;

      if(typeof arguments[0] == 'function') {
        fnSort = arguments[0];
      } else if(typeof arguments[0] == 'string') {
        key = arguments[0];

        if(arguments.length == 1) {
          order = 'x - y';
        } else if(arguments.length == 2) {

          if(typeof arguments[1] == 'string') {
            if(arguments[1].toLowerCase() == 'asc') {
              order = 'x - y';
            } else if(arguments[1].toLowerCase() == 'desc') {
              order = 'y - x';
            }
          }

          if (typeof order == 'undefined') {
            order = arguments[1];
          }
        }

        if(typeof order == 'string') {
          order = new Function('x,y', 'return ' + order);
        }

        fnSort = function(a, b) {
          return order(a[key], b[key]);
        }
      }

      if(this instanceof Array) {
        filter = this;
      } else {
        filter = ret.find();
      }

      // Order doesn't change data
      //ret.sync(raw);

      return filter.sort(fnSort);
    }

    ret.remove = function(constraint) {
      var
        list,
        save = [];

      if(this instanceof Array) {
        list = res2list(this);
      } else if(constraint instanceof Array) {
        list = res2list(constraint);
      } else {
        list = find(constraint);
      }

      each(list, function(index) {
        save.push(deepcopy(raw[index]));
        delete raw[index];
      });

      ret.sync(raw);
      return chain(save);
    }

    ret.sync = function() {}

    // The ability to import a database from somewhere
    if (arguments.length == 1) {
      if (arguments[0].constructor == Array) {
        ret.insert(arguments[0]);
      } else if (arguments[0].constructor == Function) {
        ret.insert(arguments[0]());
      } else if (arguments[0].constructor == Object) {
        ret.insert(arguments[0]);
      } else if (arguments[0].constructor == String) {
        return expr.apply(this, arguments);
      }
    } else if(arguments.length > 1) {
      ret.insert(Array.prototype.slice.call(arguments));
    }

    return ret;
  }

  window.DB.isin = isin;
  window.DB.has = has;
  window.DB.ilike = window.DB.like = like;

})();
<commit_msg>~scoping problem fixed<commit_after>(function(){
  function indexOf(which, searchElement) {
    for(var ix = which.length - 1;
        ix > -1 ;
        ix--
      ) {
      if (searchElement == which[ix]) {
        break;
      }
    }

    return ix;
  }

  // The first parameter, if exists, is assumed to be the value in the database,
  // which has a content of arrays, to search.
  // The second parameter is the index to search
  function has(param1, param2) {
    var
      callback,
      comparator,
      obj = {};

    if(arguments.length == 1) {
      comparator = param1;
    } else if(arguments.length == 2){
      comparator = param2;
    }

    if(comparator.constructor == Array) {
      var len = comparator.length;

      // This becomes O(N * M)
      callback = function(key) {
        for(ix = 0; ix < len; ix++) {
          if (indexOf(key, comparator[ix]) > -1) {
            return true;
          }
        }
        return false;
      }
    } else {
      // This is O(N)
      callback = function(key) {
        return indexOf(key, comparator) > -1;
      }
    }

    if(arguments.length == 2) {
      obj = {};
      obj[param1] = callback;
      return obj;
    } else {
      return callback;
    }
  }

  function isin(param1, param2) {
    var
      comparator,
      obj = {};

    if(arguments.length == 1) {
      comparator = param1;
    } else if(arguments.length == 2){
      comparator = param2;
    }

    // If the second argument is an array then we assume that we are looking
    // to see if the value in the database is part of the user supplied funciton
    if(comparator.constructor == Array) {
      comparator = function(x) { return indexOf(x, comparator) > -1; };
    } else if (comparator instanceof Function) {
      comparator = function(x) { return indexOf(x, comparator()) > -1; };
    }

    if(arguments.length == 2) {
      obj = {};
      obj[param1] = comparator;
      return obj;
    } else {
      return comparator;
    }
  }

  function like(param1, param2) {
    var
      comparator,
      query,
      obj = {};

    if(arguments.length == 1) {
      query = param1;
    } else if(arguments.length == 2){
      query = param2;
    }

    query = query.toString().toLowerCase();

    comparator = function(x) { return x.toString().toLowerCase().search(query) > -1; };

    if(arguments.length == 2) {
      obj = {};
      obj[param1] = comparator;
      return obj;
    } else {
      return comparator;
    }
  }

  window.DB = function(){
    var
      constraints = {},
      ixlast = 0,
      raw = {};

    function expression(){
      if(typeof arguments[0] == 'string') {
        if(arguments.length == 1) {
          return new Function("$$x$$", "return $$x$$ " + arguments[0]);
        }

        if(arguments.length == 2 && typeof arguments[1] == 'string') {
          var obj = {};
          obj[arguments[0]] = new Function("$$x$$", "return $$x$$ " + arguments[1]);
          return obj;
        }
      }
    }

    // Jacked from Resig's jquery 1.5.2
    // The code has been modified to not rely on jquery
    function extend() {
      var
        options, name, src, copy, copyIsArray, clone,
        target = arguments[0] || {},
        i = 1,
        length = arguments.length,
        deep = false;

      // Handle a deep copy situation
      if ( typeof target === "boolean" ) {
        deep = target;
        target = arguments[1] || {};
        // skip the boolean and the target
        i = 2;
      }

      // Handle case when target is a string or something (possible in deep copy)
      if ( typeof target !== "object" && typeof target !== 'function') {
        target = {};
      }

      // extend jQuery itself if only one argument is passed
      if ( length === i ) {
        target = this;
        --i;
      }

      for ( ; i < length; i++ ) {
        // Only deal with non-null/undefined values
        if ( (options = arguments[ i ]) != null ) {
          // Extend the base object
          for ( name in options ) {
            src = target[ name ];
            copy = options[ name ];

            // Prevent never-ending loop
            if ( target === copy ) {
               continue;
            }

            // Recurse if we're merging plain objects or arrays
            if ( deep && copy && ( copy.constructor == Object || (copyIsArray = (copy.constructor == Array)) ) ) {
              if ( copyIsArray ) {
                copyIsArray = false;
                clone = src && (src.constructor == Array) ? src : [];
              } else {
                clone = src && (src.constructor == Object) ? src : {};
              }

              // Never move original objects, clone them
              target[ name ] = extend( deep, clone, copy );

            // Don't bring in undefined values
            } else if ( copy !== undefined ) {
              target[ name ] = copy;
            }
          }
        }
      }

      // Return the modified object
      return target;
    };

    function deepcopy(from) {
      //@http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-a-javascript-object
      return extend(true, {}, from);
    }

    function list2obj(list) {
      var ret = {};
      each(list, function(which) {
        ret[which] = true;
      });

      return ret;
    }

    function values(obj) {
      var ret = [];

      for(var key in obj) {
        ret.push(obj[key]);
      }

      return ret;
    }

    function keys(obj) {
      var ret = [];

      for(var key in obj) {
        ret.push(key);
      }

      return ret;
    }

    var obj2list = keys;

    function each(obj, cb) {
      if (obj instanceof Array) {
        var
          ix = 0,
          len = obj.length;

        for(; ix < len; ix++) {
          cb(obj[ix], ix);
        }
      } else {
        for(var key in obj) {
          cb(key, obj[key]);
        }
      }
    }

    function res2list(res) {
      var list = [];

      each(res, function(which) {
        list.push(which.constructor('ix'));
      });

      return list;
    }

    function setdiff(larger, subset) {
      larger = list2obj(larger);
      subset = list2obj(subset);

      for(var key in subset) {
        if(larger[key]) {
          delete larger[key];
        }
      }

      return keys(larger);
    }

    function list2data(list) {
      var
        ix = 0,
        len = list.length,
        ret = new Array(len);

      for(; ix < len; ix++) {
        ret[ix] = raw[list[ix]];
      }

      return ret;
    }

    function kvarg(which){
      var ret = {};

      if(which.length == 2) {
        ret[which[0]] = which[1];
        return ret;
      }
      if(which.length == 1) {
        return which[0];
      }
    }

    // An encapsulator for hiding internal variables
    function secret() {
      var cache = {};
      return function(){
        if (arguments.length == 1) { return cache[arguments[0]];}
        if (arguments.length == 2) { cache[arguments[0]] = arguments[1]; }
      };
    }

    var ret = expression;
    ret.expr = expression;
    ret.isin = isin;
    ret.has = has;
    ret.ilike = ret.like = like;

    function chain(list) {
      for(var func in ret) {
        list[func] = ret[func];
      }

      return list;
    }

    function find() {
      var
        filterList = Array.prototype.slice.call(arguments),
        iy,
        ix,
        len,
        key,
        which,
        filtered,
        nextRound = [],
        value;

      // This permits a subfind
      if(this instanceof Array) {
        filtered = keys(this);
      } else {
        filtered = keys(raw);
      }

      if(filterList.length == 0) {
        filterList = [{}];
      }

      // This permits find(key, value)
      if( filterList.length == 2 &&
          typeof filterList[0] == 'string'
        ) {
          which = {};
          which[filterList[0]] = filterList[1];
          filterList = [deepcopy(which)];
      }

      // We can either do find({}) or find({},{},{})
      for(iy = 0; iy < filterList.length; iy++) {
        var obj = filterList[iy];

        each(obj, function(key, value) {

          // If the directive is not, then we find everything
          // that satisfies the query after the not
          if(key == 'not' && typeof value == 'object') {
            nextRound = setdiff(filtered, find(value));
          } else {
            len = filtered.length;

            for(ix = 0; ix < len; ix++) {
              which = filtered[ix];

              if(
                // Check for existence
                key in raw[which] && (

                  // This is an expression based callback
                  (
                    typeof value == 'function' &&
                    value(raw[which][key])
                  ) ||

                  // Trivial value comparison
                  (raw[which][key] == value)  ||

                  // Less trivial value comparison
                  ( (
                      value.toString &&
                      raw[which][key].toString
                    ) && (
                      value.toString() ==
                      raw[which][key].toString()
                    )
                  )
                )
              ) {
                nextRound.push(which);
              }
            }
          }

          filtered = nextRound;
          nextRound = [];
        });
      }

      return chain(filtered);
    }

    ret.constrain = function() {
      constraints = extend(true, constraints, kvarg(arguments));
    }

    ret.each = function(callback) {
      var
	      ret = [],
	      filter;

      if(arguments.length == 2) {
	      filter = arguments[0];
	      callback = arguments[1];
	    } else {
        filter = this;
      }

      each(filter, function(){
        ret.push(callback.apply(this, arguments));
      });

      return ret;
    }

    ret.inverse = function(list) {
      if(arguments.length == 0 && this instanceof Array) {
        list = this;
      }

      return chain(setdiff(keys(raw), list));
    }

    ret.where = ret.find = function() {
      return chain(list2data(find.apply(this, arguments)));
    }

    ret.select = function(field) {
      var
        result,
        filter,
        resultList = [];

      if(arguments.length > 1) {
        field = Array.prototype.slice.call(arguments);
      } else if (typeof field == 'string') {
        field = [field];
      }

      if(this instanceof Array) {
        filter = this;
      } else {
        filter = ret.find();
      }

      each(filter, function (row) {
        result = [];

        each(field, function (column) {
          if(column == '*') {
            result = result.concat(values(row));
          } else {
            result.push(row[column]);
          }
        });

        resultList.push(result);
      });

      // select doesn't change data
      //ret.sync(raw);

      return chain(resultList);
    }

    ret.insert = function(param) {
      var
        block = [],
        toInsert = [],
        ixList = [];

      if(arguments.length > 1) {
        toInsert = Array.prototype.slice.call(arguments);
      } else if (param.constructor == Array) {
        toInsert = param;
      } else if (param.constructor == Object) {
        toInsert = [param];
      }

      // If the user had opted for a certain field to be unique,
      // then we find all the matches to that field and create
      // a block list from them.
      if(constraints.unique) {
        block = db.find().select(constraints.unique);
      }

      each(toInsert, function(which) {
        // If the unique field has been set then we do
        // a linear search through the constraints to
        // see if it's there.
        if(constraints.unique) {
          if(indexOf(block, which[constraints.unique]) != -1){
            return;
          }
        }

        var ix = ixlast++;
        raw[ix] = new (secret())();
        extend(true, raw[ix], which);
        raw[ix].constructor('ix', ix);

        ixList.push(ix);
      });

      ret.sync(raw);
      return chain(list2data(ixList));
    }

    // Update allows you to set newvalue to all
    // parameters matching constraint where constraint
    // is either a set of K/V pairs or a result
    // of find so that you can do something like
    //
    //   var result = db.find(constraint);
    //   result.update({a: b});
    //
    ret.update = function(newvalue, param) {
      var
        list,
        key;

      if(this instanceof Array) {
        list = res2list(this);
      } else {
        list = find();
      }

      // This permits update(key, value) on a chained find
      if( arguments.length == 2 &&
          typeof arguments[0] == 'string'
        ) {

        // Store the key string
        key = newvalue;

        // The constraint is actually the new value to be
        // assigned.
        newvalue = {};
        newvalue[key] = param;
      }

      each(newvalue, function(key, value) {
        if(typeof value == 'function') {
          each(list, function(index) {
            raw[index][key] = value(raw[index]);
          });
        } else {
          each(list, function(index) {
            raw[index][key] = value;
          });
        }
      });

      ret.sync(raw);
      return chain(list2data(list));
    }

    ret.order = function() {
      var
        key,
        fnSort,
        order,
        filter;

      if(typeof arguments[0] == 'function') {
        fnSort = arguments[0];
      } else if(typeof arguments[0] == 'string') {
        key = arguments[0];

        if(arguments.length == 1) {
          order = 'x - y';
        } else if(arguments.length == 2) {

          if(typeof arguments[1] == 'string') {
            if(arguments[1].toLowerCase() == 'asc') {
              order = 'x - y';
            } else if(arguments[1].toLowerCase() == 'desc') {
              order = 'y - x';
            }
          }

          if (typeof order == 'undefined') {
            order = arguments[1];
          }
        }

        if(typeof order == 'string') {
          order = new Function('x,y', 'return ' + order);
        }

        fnSort = function(a, b) {
          return order(a[key], b[key]);
        }
      }

      if(this instanceof Array) {
        filter = this;
      } else {
        filter = ret.find();
      }

      // Order doesn't change data
      //ret.sync(raw);

      return filter.sort(fnSort);
    }

    ret.remove = function(constraint) {
      var
        list,
        save = [];

      if(this instanceof Array) {
        list = res2list(this);
      } else if(constraint instanceof Array) {
        list = res2list(constraint);
      } else {
        list = find(constraint);
      }

      each(list, function(index) {
        save.push(deepcopy(raw[index]));
        delete raw[index];
      });

      ret.sync(raw);
      return chain(save);
    }

    ret.sync = function() {}

    // The ability to import a database from somewhere
    if (arguments.length == 1) {
      if (arguments[0].constructor == Array) {
        ret.insert(arguments[0]);
      } else if (arguments[0].constructor == Function) {
        ret.insert(arguments[0]());
      } else if (arguments[0].constructor == Object) {
        ret.insert(arguments[0]);
      } else if (arguments[0].constructor == String) {
        return expr.apply(this, arguments);
      }
    } else if(arguments.length > 1) {
      ret.insert(Array.prototype.slice.call(arguments));
    }

    return ret;
  }

  window.DB.isin = isin;
  window.DB.has = has;
  window.DB.ilike = window.DB.like = like;

})();
<|endoftext|>


<commit_before>// var person = new Object();
// person.name = "Nicholas";
// person.age = 29;

// var person = {
// 	name:"Nicholas",
// 	age:29
// };

// var person = {};
// person.name = "Nicholas";
// person.age = 29;
// console.log(person["name"]);
// console.log(person.age);
// var propertyName = "name";
// console.log(person[propertyName]);

// var colors = new Array();
// var colors = new Array(20);
// var colors = new Array("red", "blue", "green");
// var colors = Array(3);
// var names = Array("Greg");
// var colors = ["red", "blue", "green"];

// var colors = ["red", "blue", "green"];
// colors.length = 2;
// console.log(colors[2]);

// var colors =["red", "blue", "green"];
// colors.length = 4;
// console.log(colors[3]);

// var colors = ["red", "blue", "green"];
// colors[99] = "black";
// console.log(colors.length);
// if (colors instanceof Array) {
// 	console.log("是数组");
// }
// if (Array.isArray(colors)) {
// 	console.log("也是数组");
// }

// var colors = ["red", "blue", "green"];
// console.log(colors.toString());
// console.log(colors.valueOf());
// console.log(colors);

var person1 = {
	toLocaleString:function(){
		return "Nikolaos";
	},
	toString:function(){
		return "Nicholas";
	}
};
var person2 = {
	toLocaleString:function(){
		return "Grigorios";
	},
	toString:function(){
		return "Greg";
	}
};
var person = [person1, person2];
console.log(person);
console.log(person.toString());
console.log(person.toLocaleString());

<commit_msg>update<commit_after>// var person = new Object();
// person.name = "Nicholas";
// person.age = 29;

// var person = {
// 	name:"Nicholas",
// 	age:29
// };

// var person = {};
// person.name = "Nicholas";
// person.age = 29;
// console.log(person["name"]);
// console.log(person.age);
// var propertyName = "name";
// console.log(person[propertyName]);

// var colors = new Array();
// var colors = new Array(20);
// var colors = new Array("red", "blue", "green");
// var colors = Array(3);
// var names = Array("Greg");
// var colors = ["red", "blue", "green"];

// var colors = ["red", "blue", "green"];
// colors.length = 2;
// console.log(colors[2]);

// var colors =["red", "blue", "green"];
// colors.length = 4;
// console.log(colors[3]);

// var colors = ["red", "blue", "green"];
// colors[99] = "black";
// console.log(colors.length);
// if (colors instanceof Array) {
// 	console.log("是数组");
// }
// if (Array.isArray(colors)) {
// 	console.log("也是数组");
// }

// var colors = ["red", "blue", "green"];
// console.log(colors.toString());
// console.log(colors.valueOf());
// console.log(colors);

// var person1 = {
// 	toLocaleString:function(){
// 		return "Nikolaos";
// 	},
// 	toString:function(){
// 		return "Nicholas";
// 	}
// };
// var person2 = {
// 	toLocaleString:function(){
// 		return "Grigorios";
// 	},
// 	toString:function(){
// 		return "Greg";
// 	}
// };
// var person = [person1, person2];
// console.log(person);
// console.log(person.toString());
// console.log(person.toLocaleString());

// var colors = ["red", "green", "blue"];
// console.log(colors.join(","));
// console.log(colors.join("||"));

// var colors = new Array();
// var count = colors.push("red","green");
// console.log(count);
// count = colors.push("black");
// console.log(count);
// var item = colors.pop();
// console.log(item);
// console.log(colors.length);
// colors[3] = "brown";
// item = colors.pop();
// console.log(item);

// var colors = new Array();
// var count = colors.unshift("red", "green");
// console.log(count);
// count = colors.unshift("black");
// console.log(count);
// var item = colors.pop();
// console.log(item);
// console.log(colors.length);

// var values = [1, 2, 3, 4, 5];
// values.reverse();
// console.log(values);
// values = [0, 1, 5, 10, 15];
// values.sort();
// console.log(values);
// function compare(value1, value2){
// 	if (value1 < value2) {
// 		return -1;
// 	}else if(value1 > value2){
// 		return 1;
// 	}else{
// 		return 0;
// 	}
// }
// values.sort(compare);
// console.log(values);

// var colors = ["red", "green", "blue"];
// var colors2 = colors.concat("yellow", ["black", "brown"]);
// console.log(colors);
// console.log(colors2);

// var colors = ["red", "green", "blue", "yellow", "purple"];
// var colors2 = colors.slice(1);
// var colors3 = colors.slice(1,4);
// console.log(colors);
// console.log(colors2);
// console.log(colors3);

// var colors = ["red", "green", "blue"];
// var removed = colors.splice(0, 1);
// console.log(colors);
// console.log(removed);
// removed =colors.splice(1, 0, "yellow", "orange");
// console.log(colors);
// console.log(removed);
// removed = colors.splice(1, 1, "red", "purple");
// console.log(colors);
// console.log(removed);

// var numbers = [1,2,3,4,5,4,3,2,1];
// console.log(numbers.indexOf(4));
// console.log(numbers.lastIndexOf(4));
// console.log(numbers.indexOf(4,4));
// console.log(numbers.lastIndexOf(4,4));
// var person = {name: "Nicholas"};
// var people = [{name: "Nicholas"}];
// var morePeople = [person];
// console.log(people.indexOf(person));
// console.log(morePeople.indexOf(person));

// var numbers = [1,2,3,4,5,4,3,2,1];
// var everyResult = numbers.every(function(item, index, array){
// 	return (item > 2);
// });
// console.log(everyResult);
// var someResult = numbers.some(function(item, index, array){
// 	return (item > 2);
// });
// console.log(someResult);
// var filterResult = numbers.filter(function(item, index, array){
// 	return (item > 2);
// });
// console.log(filterResult);
// var mapResult = numbers.map(function(item, index, array){
// 	return item	* 2;
// });
// console.log(mapResult);

// var values = [1,2,3,4,5];
// var sum = values.reduce(function(prev,cur,index,array){
// 	return prev + cur;
// });
// console.log(sum);
// sum = values.reduceRight(function(prev, cur, index,array){
// 	return prev + cur;
// });
// console.log(sum);

// var now = new Date();
// //GMT时间2000年1月1日 午夜零时
// var y2k = new Date(Date.UTC(2000, 0));
// //GMT时间2005年5月5日 下午5：55：55
// var allFives = new Date(Date.UTC(2005,4,5,17,55,55));
// //本地时间2000年 1月1日 午夜零时
// y2k = new Date(2000,0);
// //本地时间2005年5月5日 下午5：55：55
// allFives = new Date(2005, 4, 5, 17, 55, 55);
// //现在
// var start = Date.now();
// var date1 = new Date(2007, 0, 1);
// var date2 = new Date(2007, 1, 1);
// console.log(date1 < date2);

// //匹配字符串中的所有at的实例
// var pattern1 = /at/g;
// //匹配第一个bat或者cat，不区分大小写
// var pattern2 = /[bc]at/i;
// //匹配所有以at结尾的3哥字符的组合，不区分大小写
// var pattern3 = /.at/gi;
// //匹配第一个bat或者cat，不区分大小写
// var pattern1 = /[bc]at/i;
// //匹配第一个[bc]at，不区分大小写。
// var pattern2 = /\[bc\]at/i;
// //匹配所有以at结尾的3个字符的组合，不区分大小写。
// var patter3 = /.at/gi;
// //匹配所有的“.at”,不区分大小写
// var pattern4 = /\.at/gi;
// var pattern2 = new RegExp("[bc]at", "i");

// var pattern1 = /\[bc\]at/i;
// console.log(pattern1.global);
// console.log(pattern1.ignoreCase);
// console.log(pattern1.multiline);
// console.log(pattern1.lastIndex);
// console.log(pattern1.source);
// var pattern2 = new RegExp("\\[bc\\]at", "i");
// console.log(pattern2.global);
// console.log(pattern2.ignoreCase);
// console.log(pattern2.multiline);
// console.log(pattern2.lastIndex);
// console.log(pattern2.source);

// var text = "cat, bat, sat, fat";
// var pattern1 = /.at/;
// var matches = pattern1.exec(text);
// console.log(matches.index);
// console.log(matches[0]);
// console.log(matches.lastIndex);

// var text = "000-00-0000";
// var pattern = /\d{3}-\d{2}-\d{4}/;
// if (pattern.test(text)) {
// 	console.log("The pattern was matched.");
// }

// var text = "this has been a short summer";
// var pattern = /(.)hort/g;
// if (pattern.test(text)) {
//     console.log(RegExp.input);
//     console.log(RegExp.leftContext);
//     console.log(RegExp.rightContext);
//     console.log(RegExp.lastMatch);
//     console.log(RegExp.lastParen);
//     console.log(RegExp.multiline);
// }

// function sum(num1, num2){
// 	return num1 + num2;
// }
// console.log(sum(10,10));
// var anotherSum = sum;
// console.log(anotherSum(10,10));
// sum = null;
// console.log(anotherSum(10,10));

// function callSomeFunction(someFuction, someArgument) {
// 	return someFuction(someArgument);
// }
// function add10(num) {
// 	return num + 10;
// }
// var result1 = callSomeFunction(add10, 10);
// console.log(result1);
// function getGreeting(name) {
// 	return "hello" + name;
// }
// var result2 = callSomeFunction(getGreeting, "Nicholas");
// console.log(result2);

// function createComparisonFunciton(propertyName){
// 	return function(object1, object2){
// 		var value1 = object1[propertyName];
// 		var value2 = object2[propertyName];
// 		if (value1 < value2) {
// 			return -1;
// 		}else if(value1 > value2){
// 			return 1;
// 		}else{
// 			return 0;
// 		}
// 	}
// }
// var data = [{name:"Zachary", age:28}, {name:"Nicholas", age:29}];
// data.sort(createComparisonFunciton("name"));
// console.log(data[0].name);
// data.sort(createComparisonFunciton("age"));
// console.log(data[0].name);

// function factorial(num){
// 	if (num <= 1) {
// 		return 1;
// 	}else {
// 		return num * arguments.callee(num - 1);
// 	}
// }
// var trueFactorial = factorial;
// factorial = function(){
// 	return 0;
// }
// console.log(trueFactorial(5));
// console.log(factorial(5));

// function outer(){
// 	inner();
// }
// function inner(){
// 	console.log(arguments.callee.caller);
// }
// outer();
// function sayName(name){
// 	console.log("name");
// }
// function sum(num1,num2){
// 	return num1 + num2;
// }
// function sayHi(){
// 	console.log("hi");
// }
// console.log(sayName.length);
// console.log(sum.length);
// console.log(sayHi.length);

// function sum(num1,num2){
// 	return num1 + num2;
// }
// function callSum1(num1, num2){
// 	return sum.apply(this, arguments);
// }
// function callSum2(num1, num2){
// 	return sum.call(this, [num1, num2]);
// }
// console.log(callSum1(10, 10));
// console.log(callSum2(10, 10));

window.color = "red";
var o = {color:"blue"};
function sayColor(){
	console.log(this.color);
}
sayColor();
sayColor.call(this);
sayColor.call(window);
sayColor.call(o);
var objectSayColor = sayColor.bind(o);
objectSayColor();

<|endoftext|>


<commit_before>function UpdateCbioData(job_id) {
  console.log('run UpdateCbioData', this, 'job', job_id)
  Job.call(this, job_id);
  // UpdateCbioData
  // args
  //  sample_group_id - samples with expression and clinical data for upload into cbio
}
UpdateCbioData.prototype = Object.create(Job.prototype);
UpdateCbioData.prototype.constructor = UpdateCbioData;

UpdateCbioData.prototype.run = function () {
  // create paths for files on the disk
  // Use temporary folders at /tmp/UpdateCbioData[job_id]

  var workDir = "/tmp/" + "UpdateCbioData_" + this.job._id;
  console.log('workdir',workDir)

  try {
    fs.mkdirSync(workDir);
  } catch (e) {
    console.log("Pretty sure you reran the job: {$set: { status: 'waiting' }}");
    console.log("error:", e);
    throw e;
  }

  console.log("workDir: ", workDir);

  // create a sample group which is the combination of the two sample groups
  // so that we can easily write out a file

  var self = this;
  var deferred = Q.defer();

  // define up here so as to be available throughout promise chain (so that
  // we can skip a .then block)
  var geneSetGroupPath;
  var expressionDataPath = path.join(workDir, "data_expression.txt");
  var logPath = path.join(workDir, "*.log");
  var associated_object = {
    collection_name: "SampleGroups",
    mongo_id: group._id,
  };
  var form_id = this.job.args.form_id;

  Q.all([
      // write mongo data to files

      // expression data to a file for use in Limma
      spawnCommand(getSetting("genomic_expression_export"), [
        "--sample_group_id", group._id,
        "--cbio",
        "--uq-sample-labels",
      ], workDir, { stdoutPath: expressionDataPath }),
      // phenotype file for cbio importer
      spawnCommand(getSetting("clinical_export"), [
        "--sample_group_id",
        this.job.args.sample_group_id,
        "--form_id",
        this.job.args.form_id,
        "--work-dir",

        workDir,
      ], workDir),
    ])
    .then(function (spawnResults)           {
      console.log("done writing files");

      _.each(spawnResults, function (result) {
        if (result.exitCode !== 0) {
          throw "Problem writing files to disk.";
        }
      });

      // save the file paths... order maters for spawnResults
      // (the order depends on the order of `spawnCommand`s in `Q.all`)
      var clinicalPath = spawnResults[1].stdoutPath;

      // run CbioImporter
      return spawnCommand(getSetting("cbio_importer_path"), [
        "-c import-study",
        "-jar",
        getSetting("cbio_core_jar_path"),
        "-s",
        workDir,
      ], workDir );
    })
    .then(Meteor.bindEnvironment(function (cbioImportResult) {
      if (cbioImportResult.exitCode !== 0) {
        throw "Problem running cbio importer";
      }
      function printError (err) {
         if (err) {
           console.log("error creating blob:", err);
         }
       }
      var meta = { form_id: form_id, cbio_import: dataSetName};
      console.log('importing into cbio form', form_id, dataSetName, associated_object)
      Blobs2.create(cbioImportResult.stdoutPath, associated_object, meta, printError);

     deferred.resolve(cbioImportResult);
   }, deferred.reject))
    .catch(Meteor.bindEnvironment(function (reason) {

      deferred.reject(reason);
    }, deferred.reject));
  return deferred.promise;
};

JobClasses.UpdateCbioData = UpdateCbioData;
<commit_msg>fix bug introduced by removing code<commit_after>function UpdateCbioData(job_id) {
  console.log('run UpdateCbioData', this, 'job', job_id)
  Job.call(this, job_id);
  // UpdateCbioData
  // args
  //  sample_group_id - samples with expression and clinical data for upload into cbio
}
UpdateCbioData.prototype = Object.create(Job.prototype);
UpdateCbioData.prototype.constructor = UpdateCbioData;

UpdateCbioData.prototype.run = function () {
  // create paths for files on the disk
  // Use temporary folders at /tmp/UpdateCbioData[job_id]

  var workDir = "/tmp/" + "UpdateCbioData_" + this.job._id;
  console.log('workdir',workDir)

  try {
    fs.mkdirSync(workDir);
  } catch (e) {
    console.log("Pretty sure you reran the job: {$set: { status: 'waiting' }}");
    console.log("error:", e);
    throw e;
  }

  console.log("workDir: ", workDir);

  // create a sample group which is the combination of the two sample groups
  // so that we can easily write out a file

  var self = this;
  var deferred = Q.defer();

  // define up here so as to be available throughout promise chain (so that
  // we can skip a .then block)
  var expressionDataPath = path.join(workDir, "data_expression.txt");
  var logPath = path.join(workDir, "*.log");
  var associated_object = {
    collection_name: "SampleGroups",
    mongo_id: this.job.args.sample_group_id,
  };
  var form_id = this.job.args.form_id;

  Q.all([
      // write mongo data to files

      // expression data to a file for use in Limma
      spawnCommand(getSetting("genomic_expression_export"), [
        "--sample_group_id", this.job.args.sample_group_id,
        "--cbio",
        "--uq-sample-labels",
      ], workDir, { stdoutPath: expressionDataPath }),
      // phenotype file for cbio importer
      spawnCommand(getSetting("clinical_export"), [
        "--sample_group_id",
        this.job.args.sample_group_id,
        "--form_id",
        this.job.args.form_id,
        "--work-dir",

        workDir,
      ], workDir),
    ])
    .then(function (spawnResults)           {
      console.log("done writing files");

      _.each(spawnResults, function (result) {
        if (result.exitCode !== 0) {
          throw "Problem writing files to disk.";
        }
      });

      // save the file paths... order maters for spawnResults
      // (the order depends on the order of `spawnCommand`s in `Q.all`)
      var clinicalPath = spawnResults[1].stdoutPath;

      // run CbioImporter
      return spawnCommand(getSetting("cbio_importer_path"), [
        "-c import-study",
        "-jar",
        getSetting("cbio_core_jar_path"),
        "-s",
        workDir,
      ], workDir );
    })
    .then(Meteor.bindEnvironment(function (cbioImportResult) {
      if (cbioImportResult.exitCode !== 0) {
        throw "Problem running cbio importer";
      }
      function printError (err) {
         if (err) {
           console.log("error creating blob:", err);
         }
       }
      var meta = { form_id: form_id, cbio_import: dataSetName};
      console.log('importing into cbio form', form_id, dataSetName, associated_object)
      Blobs2.create(cbioImportResult.stdoutPath, associated_object, meta, printError);

     deferred.resolve(cbioImportResult);
   }, deferred.reject))
    .catch(Meteor.bindEnvironment(function (reason) {

      deferred.reject(reason);
    }, deferred.reject));
  return deferred.promise;
};

JobClasses.UpdateCbioData = UpdateCbioData;
<|endoftext|>