<commit_before>/**
* Principal component analysis and scores plotting
* using d3js
* Isaak Y Tecle <iyt2@cornell.edu>
*
*/

JSAN.use("CXGN.List");
JSAN.use("jquery.blockUI");

jQuery(document).ready( function() {

    var url = window.location.pathname;

    if (url.match(/pca\/analysis/) != null) {

        var list = new CXGN.List();

        var listMenu = list.listSelect("pca_genotypes", ['accessions', 'trials']);

	if (listMenu.match(/option/) != null) {

            jQuery("#pca_genotypes_list").append(listMenu);

        } else {
            jQuery("#pca_genotypes_list").append("<select><option>no lists found - Log in</option></select>");
        }
    }

});

jQuery(document).ready( function() {

    var url = window.location.pathname;

    if (url.match(/[solgs\/trait|breeders_toolbox\/trial]/)) {
       checkPcaResult();
    }

});

function checkPcaResult () {

    var popId = getPopulationId();

    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        url: '/pca/check/result/' + popId,
        success: function(response) {
            if (response.result === 'yes') {
		pcaResult();
            } else {
		jQuery("#run_pca").show();
            }
	}
    });

}

jQuery(document).ready( function() {

    jQuery("#run_pca").click(function() {
        pcaResult();
    });

});

jQuery(document).ready( function() {

    var url = window.location.pathname;

    if (url.match(/pca\/analysis/) != null) {
        var listId;

        jQuery("<option>", {value: '', selected: true}).prependTo("#pca_genotypes_list_select");

        jQuery("#pca_genotypes_list_select").change(function() {
            listId = jQuery(this).find("option:selected").val();

            if (listId) {
                jQuery("#pca_genotypes_list_upload").click(function() {
                    loadPcaGenotypesList(listId);
                });
            }
        });
    }
});

function loadPcaGenotypesList(listId) {

    var genoList = getPcaGenotypesListData(listId);
    var listName = genoList.name;
    var listType = genoList.listType;

    if ( listId.length === 0) {
        alert('The list is empty. Please select a list with content.' );
    } else {
	jQuery.blockUI.defaults.applyPlatformOpacityRules = false;
        jQuery.blockUI({message: 'Please wait..'});

        var pcaGenotypes = jQuery("#uploaded_pca_populations_table").doesExist();

        if (pcaGenotypes == false) {
            pcaGenotypes = getPcaPopsList(listId);
            jQuery("#uploaded_pca_populations").append(pcaGenotypes).show();
        }
        else {
            var addRow = '
'
                + ''
                + listName + ''
                + '	'
		+ '' + listType + '	'
                + ''
                + ''
                + '[ Run PCA ]' + ''
                + '
';

            var tdId = '#list_pca_page_' + listId;
            var addedRow = jQuery(tdId).doesExist();

            if (addedRow == false) {
                jQuery("#uploaded_pca_populations_table tr:last").after(addRow);
            }
        }
	jQuery.unblockUI();
    }

}

function pcaResult () {

    var popId  = getPopulationId();
    var listId = getListId();

    var listName;
    var listType;

    if (listId) {
    var genoList = getPcaGenotypesListData(listId);
	listName = genoList.name;
	listType = genoList.listType;
    }

    if ( popId == null) {
	popId = listId;
    }

    if (listId || popId) {
	jQuery("#pca_message").html("Running PCA... please wait...");
    }

    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        data: {'population_id': popId,
	       'list_id': listId,
	       'list_name': listName,
	       'list_type': listType,
	      },
        url: '/pca/result/' + popId,
        success: function(response) {
            if (response.status === 'success') {

		var scores = response.pca_scores;
		var variances = response.pca_variances;

		if (response.pop_id) {
		    popId = response.pop_id;
		}

		var plotData = { 'scores': scores,
				 'variances': variances,
				 'pop_id': popId,
				 'list_id': listId,
				 'list_name': listName
			       };

                plotPca(plotData);
		jQuery("#pca_message").empty();
		jQuery("#run_pca").hide();

            } else {
		jQuery("#pca_message").html(response.status);
            }
	},
        error: function(response) {
            jQuery("#pca_message").html('Error occured running population structure analysis (PCA).');
        }
    });

}

function getPcaPopsList (listId) {

    var genoList       = getPcaGenotypesListData(listId);
    var listName       = genoList.name;
    var listType       = genoList.listType;

    var pcaPopsList ='

'
                                + 'Population	'
                                + 'List type	'
                                + 'Run PCA	'
                                +'
'
                                + '
'
                                + ''
                                + ''
                                + listName + ''
                                + '	'
    	                        + '' + listType + '	'
                                + ''
                                + ''
                                + '[ Run PCA ]'+ ''
                                + '

';

    return pcaPopsList;
}

jQuery.fn.doesExist = function(){

        return jQuery(this).length > 0;

 };

function getPcaGenotypesListData(listId) {

    var list = new CXGN.List();

    if (! listId == "") {
	var listName = list.listNameById(listId);
        var listType = list.getListType(listId);

	return {'name'     : listName,
		'listType' : listType,
               };
    } else {
	return;
    }

}

function getPopulationId () {

    var populationId = jQuery("#population_id").val();

    if (!populationId) {
        populationId = jQuery("#model_id").val();
    }

    if (!populationId) {
        populationId = jQuery("#combo_pops_id").val();
    }

    return populationId;

}

function setListId (listId) {

    var existingListId = jQuery("#list_id").doesExist();

    if (existingListId) {
	jQuery("#list_id").remove();
    }

    jQuery("#pca_canvas").append("<input type=\"hidden\" id=\"list_id\" value=\"" + listId + "\"></input>");

}

function getListId () {

    var listId = jQuery("#list_id").val();
    return listId;

}

function plotPca(plotData){

    var scores = plotData.scores;
    var variances = plotData.variances;

    var pc12 = [];
    var pc1  = [];
    var pc2  = [];

    jQuery.each(scores, function(i, pc) {

	pc12.push( [{'name' : pc[0], 'pc1' : parseFloat(pc[1]), 'pc2': parseFloat(pc[2])}] );
	pc1.push(parseFloat(pc[1]));
	pc2.push(parseFloat(pc[2]));

    });

    var height = 300;
    var width  = 500;
    var pad    = {left:20, top:20, right:20, bottom: 100};
    var totalH = height + pad.top + pad.bottom;
    var totalW = width + pad.left + pad.right;

    var svg = d3.select("#pca_canvas")
        .append("svg")
        .attr("width", totalW)
        .attr("height", totalH);

    var pcaPlot = svg.append("g")
        .attr("id", "#pca_plot")
        .attr("transform", "translate(" + (pad.left) + "," + (pad.top) + ")");

    var pc1Min = d3.min(pc1);
    var pc1Max = d3.max(pc1);

    var pc1Limits = d3.max([Math.abs(d3.min(pc1)), d3.max(pc1)]);
    var pc2Limits = d3.max([Math.abs(d3.min(pc2)), d3.max(pc2)]);

    var pc1AxisScale = d3.scale.linear()
        .domain([0, pc1Limits])
        .range([0, width/2]);

    var pc1AxisLabel = d3.scale.linear()
        .domain([(-1 * pc1Limits), pc1Limits])
        .range([0, width]);

    var pc2AxisScale = d3.scale.linear()
        .domain([0, pc2Limits])
        .range([0, (height/2)]);

    var pc1Axis = d3.svg.axis()
        .scale(pc1AxisLabel)
        .tickSize(3)
        .orient("bottom");

    var pc2AxisLabel = d3.scale.linear()
        .domain([(-1 * pc2Limits), pc2Limits])
        .range([height, 0]);

   var pc2Axis = d3.svg.axis()
        .scale(pc2AxisLabel)
        .tickSize(3)
        .orient("left");

    var pc1AxisMid = 0.5 * (totalH);
    var pc2AxisMid = 0.5 * (totalW);

    var yMidLineData = [
	{"x": pc2AxisMid, "y": pad.top},
	{"x": pc2AxisMid, "y": pad.top + height}
    ];

    var xMidLineData = [
	{"x": pad.left, "y": pad.top + height/2},
	{"x": pad.left + width, "y": pad.top + height/2}
    ];

    var lineFunction = d3.svg.line()
        .x(function(d) { return d.x; })
        .y(function(d) { return d.y; })
        .interpolate("linear");

    pcaPlot.append("path")
        .attr("d", lineFunction(yMidLineData))
        .attr("stroke", "red")
        .attr("stroke-width", 1)
        .attr("fill", "none");

    pcaPlot.append("path")
        .attr("d", lineFunction(xMidLineData))
        .attr("stroke", "green")
        .attr("stroke-width", 1)
        .attr("fill", "none");

    pcaPlot.append("g")
        .attr("class", "PC1 axis")
        .attr("transform", "translate(" + pad.left + "," + (pad.top + height) +")")
        .call(pc1Axis)
        .selectAll("text")
        .attr("y", 0)
        .attr("x", 10)
        .attr("dy", ".1em")
        .attr("transform", "rotate(90)")
        .attr("fill", "green")
        .style({"text-anchor":"start", "fill": "#86B404"});

    pcaPlot.append("g")
        .attr("class", "PC2 axis")
        .attr("transform", "translate(" + pad.left +  "," + pad.top  + ")")
        .call(pc2Axis)
        .selectAll("text")
        .attr("y", 0)
        .attr("x", -10)
        .attr("fill", "green")
        .style("fill", "#86B404");

    pcaPlot.append("g")
        .attr("id", "pc1_axis_label")
        .append("text")
        .text("PC1 -- " + variances[0][1] + "%" )
        .attr("y", pad.top + height + 30)
        .attr("x", width/2)
        .attr("font-size", 12)
        .style("fill", "green")

    pcaPlot.append("g")
        .attr("id", "pc2_axis_label")
        .append("text")
        .text("PC2 -- " + variances[1][1] + "%" )
	.attr("transform", "rotate(-90)")
	.attr("y", -5)
        .attr("x", -((pad.top + height/2) + 10))
        .attr("font-size", 12)
        .style("fill", "red")

    pcaPlot.append("g")
        .selectAll("circle")
        .data(pc12)
        .enter()
        .append("circle")
        .attr("fill", "#9A2EFE")
        .attr("r", 3)
        .attr("cx", function(d) {
            var xVal = d[0].pc1;
	    if (xVal >= 0) {
                return  (pad.left + (width/2)) + pc1AxisScale(xVal);
            } else {
                return (pad.left + (width/2)) - (-1 * pc1AxisScale(xVal));
           }
        })
        .attr("cy", function(d) {
            var yVal = d[0].pc2;

            if (yVal >= 0) {
                return ( pad.top + (height/2)) - pc2AxisScale(yVal);
            } else {
                return (pad.top + (height/2)) +  (-1 * pc2AxisScale(yVal));
            }
        })
        .on("mouseover", function(d) {
            d3.select(this)
                .attr("r", 5)
                .style("fill", "#86B404")
            pcaPlot.append("text")
                .attr("id", "dLabel")
                .style("fill", "#86B404")
                .text( d[0].name + "(" + d[0].pc1 + "," + d[0].pc2 + ")")
                .attr("x", pad.left + 1)
                .attr("y", pad.top + 80);
        })
        .on("mouseout", function(d) {
            d3.select(this)
                .attr("r", 3)
                .style("fill", "#9A2EFE")
            d3.selectAll("text#dLabel").remove();
        });

    pcaPlot.append("rect")
	.attr("transform", "translate(" + pad.left + "," + pad.top + ")")
        .attr("height", height)
        .attr("width", width)
        .attr("fill", "none")
        .attr("stroke", "#523CB5")
        .attr("stroke-width", 1)
        .attr("pointer-events", "none");

    var id;
    if ( plotData.pop_id) {
    	id = plotData.pop_id;
    } else {
	id = plotData.list_id;
    }

    var popName = "";
    if (plotData.list_name) {
	popName = ' -- ' + plotData.list_name;
    }

    var pcaDownload;
    if (plotData.pop_id)  {
	pcaDownload = "/download/pca/scores/population/" + id;
    }

     pcaPlot.append("a")
	.attr("xlink:href", pcaDownload)
	.append("text")
	.text("[ Download PCA scores ]" + popName)
	.attr("y", pad.top + height + 60)
        .attr("x", pad.left)
        .attr("font-size", 14)
        .style("fill", "#954A09")

}

<commit_msg>add selection population page to PCA analysis pages..<commit_after>/**
* Principal component analysis and scores plotting
* using d3js
* Isaak Y Tecle <iyt2@cornell.edu>
*
*/

JSAN.use("CXGN.List");
JSAN.use("jquery.blockUI");

jQuery(document).ready( function() {

    var url = window.location.pathname;

    if (url.match(/pca\/analysis/) != null) {

        var list = new CXGN.List();

        var listMenu = list.listSelect("pca_genotypes", ['accessions', 'trials']);

	if (listMenu.match(/option/) != null) {

            jQuery("#pca_genotypes_list").append(listMenu);

        } else {
            jQuery("#pca_genotypes_list").append("<select><option>no lists found - Log in</option></select>");
        }
    }

});

jQuery(document).ready( function() {

    var url = window.location.pathname;

    if (url.match(/solgs\/trait|breeders_toolbox\/trial|breeders\/trial\/|solgs\/selection\//)) {
       checkPcaResult();
    }

});

function checkPcaResult () {

    var popId = getPopulationId();

    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        url: '/pca/check/result/' + popId,
        success: function(response) {
            if (response.result === 'yes') {
		pcaResult();
            } else {
		jQuery("#run_pca").show();
            }
	}
    });

}

jQuery(document).ready( function() {

    jQuery("#run_pca").click(function() {
        pcaResult();
    });

});

jQuery(document).ready( function() {

    var url = window.location.pathname;

    if (url.match(/pca\/analysis/) != null) {
        var listId;

        jQuery("<option>", {value: '', selected: true}).prependTo("#pca_genotypes_list_select");

        jQuery("#pca_genotypes_list_select").change(function() {
            listId = jQuery(this).find("option:selected").val();

            if (listId) {
                jQuery("#pca_genotypes_list_upload").click(function() {
                    loadPcaGenotypesList(listId);
                });
            }
        });
    }
});

function loadPcaGenotypesList(listId) {

    var genoList = getPcaGenotypesListData(listId);
    var listName = genoList.name;
    var listType = genoList.listType;

    if ( listId.length === 0) {
        alert('The list is empty. Please select a list with content.' );
    } else {
	jQuery.blockUI.defaults.applyPlatformOpacityRules = false;
        jQuery.blockUI({message: 'Please wait..'});

        var pcaGenotypes = jQuery("#uploaded_pca_populations_table").doesExist();

        if (pcaGenotypes == false) {
            pcaGenotypes = getPcaPopsList(listId);
            jQuery("#uploaded_pca_populations").append(pcaGenotypes).show();
        }
        else {
            var addRow = '
'
                + ''
                + listName + ''
                + '	'
		+ '' + listType + '	'
                + ''
                + ''
                + '[ Run PCA ]' + ''
                + '
';

            var tdId = '#list_pca_page_' + listId;
            var addedRow = jQuery(tdId).doesExist();

            if (addedRow == false) {
                jQuery("#uploaded_pca_populations_table tr:last").after(addRow);
            }
        }
	jQuery.unblockUI();
    }

}

function pcaResult () {

    var popId  = getPopulationId();
    var listId = getListId();

    if (popId.match(/uploaded_/)) {
	listId = popId.replace("uploaded_", "");
    }

    var listName;
    var listType;

    if (listId) {
    var genoList = getPcaGenotypesListData(listId);
	listName = genoList.name;
	listType = genoList.listType;
    }

    if ( popId == null) {
	popId = listId;
    }

    if (listId || popId) {
	jQuery("#pca_message").html("Running PCA... please wait...");
    }

    jQuery.ajax({
        type: 'POST',
        dataType: 'json',
        data: {'population_id': popId,
	       'list_id': listId,
	       'list_name': listName,
	       'list_type': listType,
	      },
        url: '/pca/result/' + popId,
        success: function(response) {
            if (response.status === 'success') {

		var scores = response.pca_scores;
		var variances = response.pca_variances;

		if (response.pop_id) {
		    popId = response.pop_id;
		}

		var plotData = { 'scores': scores,
				 'variances': variances,
				 'pop_id': popId,
				 'list_id': listId,
				 'list_name': listName
			       };

                plotPca(plotData);
		jQuery("#pca_message").empty();
		jQuery("#run_pca").hide();

            } else {
		jQuery("#pca_message").html(response.status);
            }
	},
        error: function(response) {
            jQuery("#pca_message").html('Error occured running population structure analysis (PCA).');
        }
    });

}

function getPcaPopsList (listId) {

    var genoList       = getPcaGenotypesListData(listId);
    var listName       = genoList.name;
    var listType       = genoList.listType;

    var pcaPopsList ='

'
                                + 'Population	'
                                + 'List type	'
                                + 'Run PCA	'
                                +'
'
                                + '
'
                                + ''
                                + ''
                                + listName + ''
                                + '	'
    	                        + '' + listType + '	'
                                + ''
                                + ''
                                + '[ Run PCA ]'+ ''
                                + '

';

    return pcaPopsList;
}

jQuery.fn.doesExist = function(){

        return jQuery(this).length > 0;

 };

function getPcaGenotypesListData(listId) {

    var list = new CXGN.List();

    if (! listId == "") {
	var listName = list.listNameById(listId);
        var listType = list.getListType(listId);

	return {'name'     : listName,
		'listType' : listType,
               };
    } else {
	return;
    }

}

function getPopulationId () {

    var populationId = jQuery("#population_id").val();

    if (!populationId) {
        populationId = jQuery("#model_id").val();
    }

    if (!populationId) {
        populationId = jQuery("#combo_pops_id").val();
    }

    var page = window.location.pathname;

    if (page.match(/solgs\/selection/)) {
	populationId = jQuery("#selection_pop_id").val();
    }

    return populationId;

}

function setListId (listId) {

    var existingListId = jQuery("#list_id").doesExist();

    if (existingListId) {
	jQuery("#list_id").remove();
    }

    jQuery("#pca_canvas").append("<input type=\"hidden\" id=\"list_id\" value=\"" + listId + "\"></input>");

}

function getListId () {

    var listId = jQuery("#list_id").val();
    return listId;

}

function plotPca(plotData){

    var scores = plotData.scores;
    var variances = plotData.variances;

    var pc12 = [];
    var pc1  = [];
    var pc2  = [];

    jQuery.each(scores, function(i, pc) {

	pc12.push( [{'name' : pc[0], 'pc1' : parseFloat(pc[1]), 'pc2': parseFloat(pc[2])}] );
	pc1.push(parseFloat(pc[1]));
	pc2.push(parseFloat(pc[2]));

    });

    var height = 300;
    var width  = 500;
    var pad    = {left:20, top:20, right:20, bottom: 100};
    var totalH = height + pad.top + pad.bottom;
    var totalW = width + pad.left + pad.right;

    var svg = d3.select("#pca_canvas")
        .append("svg")
        .attr("width", totalW)
        .attr("height", totalH);

    var pcaPlot = svg.append("g")
        .attr("id", "#pca_plot")
        .attr("transform", "translate(" + (pad.left) + "," + (pad.top) + ")");

    var pc1Min = d3.min(pc1);
    var pc1Max = d3.max(pc1);

    var pc1Limits = d3.max([Math.abs(d3.min(pc1)), d3.max(pc1)]);
    var pc2Limits = d3.max([Math.abs(d3.min(pc2)), d3.max(pc2)]);

    var pc1AxisScale = d3.scale.linear()
        .domain([0, pc1Limits])
        .range([0, width/2]);

    var pc1AxisLabel = d3.scale.linear()
        .domain([(-1 * pc1Limits), pc1Limits])
        .range([0, width]);

    var pc2AxisScale = d3.scale.linear()
        .domain([0, pc2Limits])
        .range([0, (height/2)]);

    var pc1Axis = d3.svg.axis()
        .scale(pc1AxisLabel)
        .tickSize(3)
        .orient("bottom");

    var pc2AxisLabel = d3.scale.linear()
        .domain([(-1 * pc2Limits), pc2Limits])
        .range([height, 0]);

   var pc2Axis = d3.svg.axis()
        .scale(pc2AxisLabel)
        .tickSize(3)
        .orient("left");

    var pc1AxisMid = 0.5 * (totalH);
    var pc2AxisMid = 0.5 * (totalW);

    var yMidLineData = [
	{"x": pc2AxisMid, "y": pad.top},
	{"x": pc2AxisMid, "y": pad.top + height}
    ];

    var xMidLineData = [
	{"x": pad.left, "y": pad.top + height/2},
	{"x": pad.left + width, "y": pad.top + height/2}
    ];

    var lineFunction = d3.svg.line()
        .x(function(d) { return d.x; })
        .y(function(d) { return d.y; })
        .interpolate("linear");

    pcaPlot.append("path")
        .attr("d", lineFunction(yMidLineData))
        .attr("stroke", "red")
        .attr("stroke-width", 1)
        .attr("fill", "none");

    pcaPlot.append("path")
        .attr("d", lineFunction(xMidLineData))
        .attr("stroke", "green")
        .attr("stroke-width", 1)
        .attr("fill", "none");

    pcaPlot.append("g")
        .attr("class", "PC1 axis")
        .attr("transform", "translate(" + pad.left + "," + (pad.top + height) +")")
        .call(pc1Axis)
        .selectAll("text")
        .attr("y", 0)
        .attr("x", 10)
        .attr("dy", ".1em")
        .attr("transform", "rotate(90)")
        .attr("fill", "green")
        .style({"text-anchor":"start", "fill": "#86B404"});

    pcaPlot.append("g")
        .attr("class", "PC2 axis")
        .attr("transform", "translate(" + pad.left +  "," + pad.top  + ")")
        .call(pc2Axis)
        .selectAll("text")
        .attr("y", 0)
        .attr("x", -10)
        .attr("fill", "green")
        .style("fill", "#86B404");

    pcaPlot.append("g")
        .attr("id", "pc1_axis_label")
        .append("text")
        .text("PC1 -- " + variances[0][1] + "%" )
        .attr("y", pad.top + height + 30)
        .attr("x", width/2)
        .attr("font-size", 12)
        .style("fill", "green")

    pcaPlot.append("g")
        .attr("id", "pc2_axis_label")
        .append("text")
        .text("PC2 -- " + variances[1][1] + "%" )
	.attr("transform", "rotate(-90)")
	.attr("y", -5)
        .attr("x", -((pad.top + height/2) + 10))
        .attr("font-size", 12)
        .style("fill", "red")

    pcaPlot.append("g")
        .selectAll("circle")
        .data(pc12)
        .enter()
        .append("circle")
        .attr("fill", "#9A2EFE")
        .attr("r", 3)
        .attr("cx", function(d) {
            var xVal = d[0].pc1;
	    if (xVal >= 0) {
                return  (pad.left + (width/2)) + pc1AxisScale(xVal);
            } else {
                return (pad.left + (width/2)) - (-1 * pc1AxisScale(xVal));
           }
        })
        .attr("cy", function(d) {
            var yVal = d[0].pc2;

            if (yVal >= 0) {
                return ( pad.top + (height/2)) - pc2AxisScale(yVal);
            } else {
                return (pad.top + (height/2)) +  (-1 * pc2AxisScale(yVal));
            }
        })
        .on("mouseover", function(d) {
            d3.select(this)
                .attr("r", 5)
                .style("fill", "#86B404")
            pcaPlot.append("text")
                .attr("id", "dLabel")
                .style("fill", "#86B404")
                .text( d[0].name + "(" + d[0].pc1 + "," + d[0].pc2 + ")")
                .attr("x", pad.left + 1)
                .attr("y", pad.top + 80);
        })
        .on("mouseout", function(d) {
            d3.select(this)
                .attr("r", 3)
                .style("fill", "#9A2EFE")
            d3.selectAll("text#dLabel").remove();
        });

    pcaPlot.append("rect")
	.attr("transform", "translate(" + pad.left + "," + pad.top + ")")
        .attr("height", height)
        .attr("width", width)
        .attr("fill", "none")
        .attr("stroke", "#523CB5")
        .attr("stroke-width", 1)
        .attr("pointer-events", "none");

    var id;
    if ( plotData.pop_id) {
    	id = plotData.pop_id;
    } else {
	id = plotData.list_id;
    }

    var popName = "";
    if (plotData.list_name) {
	popName = ' -- ' + plotData.list_name;
    }

    var pcaDownload;
    if (plotData.pop_id)  {
	pcaDownload = "/download/pca/scores/population/" + id;
    }

     pcaPlot.append("a")
	.attr("xlink:href", pcaDownload)
	.append("text")
	.text("[ Download PCA scores ]" + popName)
	.attr("y", pad.top + height + 60)
        .attr("x", pad.left)
        .attr("font-size", 14)
        .style("fill", "#954A09")

}

<|endoftext|>


<commit_before>'use strict';

function clicked(){
    audio_start({
      'id': 'boop',
      'volume-multiplier': settings_settings['audio-volume'],
    });

    document.getElementById('score').innerHTML = parseInt(
      document.getElementById('score').innerHTML,
      10
    ) + 1;
    generate();
}

function clear_links(){
    // Remove all target links from text.
    document.getElementById('text').innerHTML =
      document.getElementById('text').innerHTML.replace('', '').replace('', '');
}

function decisecond(){
    time = (time - .1).toFixed(1);

    document.getElementById('time').innerHTML = time;

    if(time <= 0){
        stop();
    }
}

function generate(){
    clear_links();
    var range = 0;
    var text = document.getElementById('text').innerHTML;

    // Generate a range of link-length that doesn't overwrite any HTML.
    do{
        range = random_integer({
          'max': text.length - settings_settings['link-length'],
        });
    }while(text.substr(range, settings_settings['link-length']).indexOf('<') !== -1
      || text.substr(range, settings_settings['link-length']).indexOf('>') != -1);

    // Replace the text with the new target link in it.
    document.getElementById('text').innerHTML = text.substr(0, range)
      + '' + text.substr(range, settings_settings['link-length']) + ''
      + text.substr(range + settings_settings['link-length'], text.length - range);
}

function settings_toggle(state){
    state = state == void 0
      ? document.getElementById('settings-button').value === '+'
      : state;

    if(state){
        document.getElementById('settings').style.display = 'inline-block';
        document.getElementById('settings-button').value = '-';

    }else{
        document.getElementById('settings').style.display = 'none';
        document.getElementById('settings-button').value = '+';
    }
}

function start(){
    settings_save();

    time = settings_settings['time-max'];

    document.getElementById('score').innerHTML = 0;
    document.getElementById('start-button').onclick = stop;
    document.getElementById('start-button').value = 'End [ESC]';
    document.getElementById('time').innerHTML = time;
    document.getElementById('time-max-span').innerHTML = time;
    generate();

    interval = window.setInterval(
      decisecond,
      100
    );
}

function stop(){
    window.clearInterval(interval);
    clear_links();
    document.getElementById('start-button').onclick = start;
    document.getElementById('start-button').value =
      'Start [' + settings_settings['start-key'] + ']';
}

var interval = 0;
var time = 0;

window.onkeydown = function(e){
    var key = e.keyCode || e.which;

    // ESC: stop current game.
    if(key === 27){
        stop();

    }else if(String.fromCharCode(key) === settings_settings['start-key']){
        stop();
        start();

    // +: show settings.
    }else if(key === 187){
        settings_toggle(true);

    // -: hide settings.
    }else if(key === 189){
        settings_toggle(false);
    }
};

window.onload = function(e){
    settings_init({
      'prefix': 'SpeedText.htm-',
      'settings': {
        'audio-volume': 1,
        'link-length': 5,
        'start-key': 'H',
        'time-max': 30,
      },
    });
    audio_init({
      'volume': settings_settings['audio-volume'],
    });
    audio_create({
      'id': 'boop',
      'properties': {
        'duration': .1,
        'volume': .1,
      },
    });

    document.getElementById('settings').innerHTML =
      '<input id=audio-volume max=1 min=0 step=0.01 type=range>Audio
'
        + '<input id=link-length maxlength=2>Link Length
'
        + '<input id=start-key maxlength=1>Start
'
        + '<input id=time-max>Time
'
        + '<input id=reset-button onclick=settings_reset() type=button value=Reset>';
    settings_update();

    document.getElementById('settings-button').onclick = function(){
        settings_toggle();
    };
    document.getElementById('start-button').onclick = start;
    document.getElementById('text').innerHTML = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur nibh ligula, dictum ut pulvinar sed, fringilla non lectus. Nunc fermentum aliquam condimentum. Aenean iaculis varius massa, vel rutrum nunc dictum eget. Sed sed ante at diam gravida luctus. Mauris tellus sapien, fringilla convallis mollis nec, tempor et velit. Morbi est odio, aliquet non interdum rutrum, facilisis egestas felis. Curabitur quis nisl et lacus congue ultricies. Sed enim justo, varius condimentum egestas quis, sodales condimentum orci. Praesent porttitor consectetur leo, ac consequat magna vulputate et. Donec non sem sem.

Integer quis enim at odio facilisis rhoncus. Nunc id ipsum eu massa eleifend placerat. Duis luctus lacus vel urna consequat scelerisque. Maecenas diam risus, interdum sed gravida in, posuere a ipsum. Nulla in nunc vitae velit tincidunt viverra vitae nec sem. Aliquam quis tellus magna. Donec nisl diam, ornare vehicula mattis nec, hendrerit sed ipsum.

Etiam iaculis vehicula lectus sed fringilla. In ut mauris augue, at facilisis tellus. Maecenas sed eros vitae turpis adipiscing dapibus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Morbi vitae sodales odio. In sit amet magna sit amet erat sodales congue non sit amet justo. Suspendisse lobortis, neque in cursus tincidunt, neque magna sagittis massa, eu adipiscing magna elit et tellus. Nullam tincidunt leo in sem pretium mollis. Nam ac consequat risus.

Donec a porttitor orci. Fusce vestibulum massa velit, at ullamcorper tortor. Donec iaculis, quam non sodales pellentesque, enim mi venenatis ipsum, semper auctor nunc massa et ipsum. Praesent eget nisl lectus, non luctus felis. Aenean euismod lacinia mauris, at lacinia ante cursus id. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam sodales, lorem ultricies molestie cursus, sapien erat congue quam, et vehicula eros massa ac libero. Nunc sit amet magna non turpis facilisis aliquet id sed risus. Mauris quis tellus nibh.

Nulla facilisi. Curabitur scelerisque, lectus ac sodales sollicitudin, justo massa convallis quam, eget tristique sapien eros eget urna. Fusce et neque lorem. Sed enim est, dapibus quis fermentum ac, mollis eget ligula. Aliquam erat volutpat. Aliquam odio erat, accumsan in sollicitudin ac, elementum nec augue. Sed vel tortor sit amet sapien elementum varius. Morbi sollicitudin mauris vitae augue suscipit hendrerit. Morbi nec elementum massa. Praesent condimentum dignissim nibh, eu scelerisque leo sollicitudin rutrum. Cras sit amet nibh eu leo scelerisque laoreet. Aliquam eu mauris at sapien placerat imperdiet vel eget turpis. Etiam posuere sem et justo ultrices suscipit. Vestibulum nibh dolor, lobortis sed eleifend sed, suscipit sit amet diam.';

    stop();
    settings_toggle(false);
};
<commit_msg>moved event bindings to onload<commit_after>'use strict';

function clicked(){
    audio_start({
      'id': 'boop',
      'volume-multiplier': settings_settings['audio-volume'],
    });

    document.getElementById('score').innerHTML = parseInt(
      document.getElementById('score').innerHTML,
      10
    ) + 1;
    generate();
}

function clear_links(){
    // Remove all target links from text.
    document.getElementById('text').innerHTML =
      document.getElementById('text').innerHTML.replace('', '').replace('', '');
}

function decisecond(){
    time = (time - .1).toFixed(1);

    document.getElementById('time').innerHTML = time;

    if(time <= 0){
        stop();
    }
}

function generate(){
    clear_links();
    var range = 0;
    var text = document.getElementById('text').innerHTML;

    // Generate a range of link-length that doesn't overwrite any HTML.
    do{
        range = random_integer({
          'max': text.length - settings_settings['link-length'],
        });
    }while(text.substr(range, settings_settings['link-length']).indexOf('<') !== -1
      || text.substr(range, settings_settings['link-length']).indexOf('>') != -1);

    // Replace the text with the new target link in it.
    document.getElementById('text').innerHTML = text.substr(0, range)
      + '' + text.substr(range, settings_settings['link-length']) + ''
      + text.substr(range + settings_settings['link-length'], text.length - range);
}

function settings_toggle(state){
    state = state == void 0
      ? document.getElementById('settings-button').value === '+'
      : state;

    if(state){
        document.getElementById('settings').style.display = 'inline-block';
        document.getElementById('settings-button').value = '-';

    }else{
        document.getElementById('settings').style.display = 'none';
        document.getElementById('settings-button').value = '+';
    }
}

function start(){
    settings_save();

    time = settings_settings['time-max'];

    document.getElementById('score').innerHTML = 0;
    document.getElementById('start-button').onclick = stop;
    document.getElementById('start-button').value = 'End [ESC]';
    document.getElementById('time').innerHTML = time;
    document.getElementById('time-max-span').innerHTML = time;
    generate();

    interval = window.setInterval(
      decisecond,
      100
    );
}

function stop(){
    window.clearInterval(interval);
    clear_links();
    document.getElementById('start-button').onclick = start;
    document.getElementById('start-button').value =
      'Start [' + settings_settings['start-key'] + ']';
}

var interval = 0;
var time = 0;

window.onload = function(e){
    settings_init({
      'prefix': 'SpeedText.htm-',
      'settings': {
        'audio-volume': 1,
        'link-length': 5,
        'start-key': 'H',
        'time-max': 30,
      },
    });
    audio_init({
      'volume': settings_settings['audio-volume'],
    });
    audio_create({
      'id': 'boop',
      'properties': {
        'duration': .1,
        'volume': .1,
      },
    });

    document.getElementById('settings').innerHTML =
      '<input id=audio-volume max=1 min=0 step=0.01 type=range>Audio
'
        + '<input id=link-length maxlength=2>Link Length
'
        + '<input id=start-key maxlength=1>Start
'
        + '<input id=time-max>Time
'
        + '<input id=reset-button onclick=settings_reset() type=button value=Reset>';
    settings_update();

    document.getElementById('settings-button').onclick = function(){
        settings_toggle();
    };
    document.getElementById('start-button').onclick = start;
    document.getElementById('text').innerHTML = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur nibh ligula, dictum ut pulvinar sed, fringilla non lectus. Nunc fermentum aliquam condimentum. Aenean iaculis varius massa, vel rutrum nunc dictum eget. Sed sed ante at diam gravida luctus. Mauris tellus sapien, fringilla convallis mollis nec, tempor et velit. Morbi est odio, aliquet non interdum rutrum, facilisis egestas felis. Curabitur quis nisl et lacus congue ultricies. Sed enim justo, varius condimentum egestas quis, sodales condimentum orci. Praesent porttitor consectetur leo, ac consequat magna vulputate et. Donec non sem sem.

Integer quis enim at odio facilisis rhoncus. Nunc id ipsum eu massa eleifend placerat. Duis luctus lacus vel urna consequat scelerisque. Maecenas diam risus, interdum sed gravida in, posuere a ipsum. Nulla in nunc vitae velit tincidunt viverra vitae nec sem. Aliquam quis tellus magna. Donec nisl diam, ornare vehicula mattis nec, hendrerit sed ipsum.

Etiam iaculis vehicula lectus sed fringilla. In ut mauris augue, at facilisis tellus. Maecenas sed eros vitae turpis adipiscing dapibus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Morbi vitae sodales odio. In sit amet magna sit amet erat sodales congue non sit amet justo. Suspendisse lobortis, neque in cursus tincidunt, neque magna sagittis massa, eu adipiscing magna elit et tellus. Nullam tincidunt leo in sem pretium mollis. Nam ac consequat risus.

Donec a porttitor orci. Fusce vestibulum massa velit, at ullamcorper tortor. Donec iaculis, quam non sodales pellentesque, enim mi venenatis ipsum, semper auctor nunc massa et ipsum. Praesent eget nisl lectus, non luctus felis. Aenean euismod lacinia mauris, at lacinia ante cursus id. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam sodales, lorem ultricies molestie cursus, sapien erat congue quam, et vehicula eros massa ac libero. Nunc sit amet magna non turpis facilisis aliquet id sed risus. Mauris quis tellus nibh.

Nulla facilisi. Curabitur scelerisque, lectus ac sodales sollicitudin, justo massa convallis quam, eget tristique sapien eros eget urna. Fusce et neque lorem. Sed enim est, dapibus quis fermentum ac, mollis eget ligula. Aliquam erat volutpat. Aliquam odio erat, accumsan in sollicitudin ac, elementum nec augue. Sed vel tortor sit amet sapien elementum varius. Morbi sollicitudin mauris vitae augue suscipit hendrerit. Morbi nec elementum massa. Praesent condimentum dignissim nibh, eu scelerisque leo sollicitudin rutrum. Cras sit amet nibh eu leo scelerisque laoreet. Aliquam eu mauris at sapien placerat imperdiet vel eget turpis. Etiam posuere sem et justo ultrices suscipit. Vestibulum nibh dolor, lobortis sed eleifend sed, suscipit sit amet diam.';

    stop();
    settings_toggle(false);

    window.onkeydown = function(e){
        var key = e.keyCode || e.which;

        // ESC: stop current game.
        if(key === 27){
            stop();

        }else if(String.fromCharCode(key) === settings_settings['start-key']){
            stop();
            start();

        // +: show settings.
        }else if(key === 187){
            settings_toggle(true);

        // -: hide settings.
        }else if(key === 189){
            settings_toggle(false);
        }
    };
};
<|endoftext|>


<commit_before>(function($){
  $(function(){
    $('.button-collapse').sideNav({
        closeOnClick: true, // Closes side-nav on  clicks, useful for Angular/Meteor
        draggable: true // Choose whether you can drag to open on touch screens
    });
    // Initialize collapsible (uncomment the line below if you use the dropdown variation)
    $('.collapsible').collapsible();

    $.winSizeSpy();

    $('.scrollspy').scrollSpy({
        scrollOffset: window.innerHeight * 0.3
    });

    $('.dropdown-button').dropdown({
        inDuration: 300,
        outDuration: 225,
        constrain_width: false, // Does not change width of dropdown to that of the activator
        hover: true, // Activate on hover
        gutter: 0, // Spacing from edge
        belowOrigin: false, // Displays dropdown below the button
        alignment: 'left' // Displays dropdown with edge aligned to the left of button
    });

    // hover handler for sidebar
    $('header ul.side-nav li:not(:first-child):not(:last-child)').hover(function() {
        $(this).addClass('light-blue lighten-2');
        $('a', this).removeClass('black-text');
        $('a', this).addClass('white-text');
    }, function() {
        $(this).removeClass('light-blue lighten-2');
        $('a', this).removeClass('white-text');
        $('a', this).addClass('black-text');
    });

    $('header ul.side-nav li a.social-link').hover(function() {
        $(this).addClass('light-blue lighten-2');
        $('i', this).removeClass('black-text');
        $('i', this).addClass('white-text');
    }, function() {
        $(this).removeClass('light-blue lighten-2');
        $('i', this).removeClass('white-text');
        $('i', this).addClass('black-text');
    });

    // window on scroll
    var onScroll = function(event) {
        var scrollHeight = Math.floor($(window).scrollTop());

        var elmHeight = $('#index-banner').offset().top;

        var elmSize = $('#index-banner').outerHeight();

        var navHeight = $('header nav').height();

        // console.log(Math.abs(elmHeight - scrollHeight), elmSize - navHeight);

        if (Math.abs(elmHeight - scrollHeight) > elmSize - navHeight) {
            $('header div.hide').removeClass('hide');
        } else {
            $('header div').addClass('hide');
        }
    };

    $(window).scroll(Materialize.throttle(onScroll, 100));

    /*  initialize skills */

    // get skills from json file
    $.getJSON('js/skills.json', function(json, textStatus) {
        var chips = json.chips;
        // create a chip for each skill
        $.each(chips, function(index, el) {
            // append new chip with given icon
            // and define appropriate handlers
            $('.chips').append(
                $(document.createElement('div'))
                    .addClass('chip')
                    .text(el.tag)
                    .append(
                        $(document.createElement('i'))
                            .addClass('close mdi mdi-' + el.icon)
                            .click(function(event) {
                                $(this).parent().trigger('click')
                                event.preventDefault();
                                event.stopPropagation();
                            })
                    )
                    .click(function(event) {
                        // clear current selected chip
                        $('.chip').removeClass('selected');
                        // select this chip
                        $(this).addClass('selected');
                        // fire selected event and pass in card
                        var card = $(document.createElement('div')).addClass('card-panel').html('

' + el.tag + '

' + el.text + '
');
                        $(this).trigger('chip.select', card);
                    })
            )
        });

        // hide the input box, won't be used here
        $('.chips-initial input').addClass('hide');

        $('.chips').on('chip.select', function(event, card) {
            event.preventDefault();
            /* Act on the event */
            $('.card-container').html(card);
        });
    });

  }); // end of document ready
})(jQuery); // end of jQuery name space<commit_msg>latest changes<commit_after>(function($){
  $(function(){
    $('.button-collapse').sideNav({
        closeOnClick: true, // Closes side-nav on  clicks, useful for Angular/Meteor
        draggable: true // Choose whether you can drag to open on touch screens
    });
    // Initialize collapsible (uncomment the line below if you use the dropdown variation)
    $('.collapsible').collapsible();

    $.winSizeSpy();

    $('.scrollspy').scrollSpy({
        scrollOffset: window.innerHeight * 0.3
    });

    $('.dropdown-button').dropdown({
        inDuration: 300,
        outDuration: 225,
        constrain_width: false, // Does not change width of dropdown to that of the activator
        hover: true, // Activate on hover
        gutter: 0, // Spacing from edge
        belowOrigin: false, // Displays dropdown below the button
        alignment: 'left' // Displays dropdown with edge aligned to the left of button
    });

    // hover handler for sidebar
    $('header ul.side-nav li:not(:first-child):not(:last-child)').hover(function() {
        $(this).addClass('light-blue lighten-2');
        $('a', this).removeClass('black-text');
        $('a', this).addClass('white-text');
    }, function() {
        $(this).removeClass('light-blue lighten-2');
        $('a', this).removeClass('white-text');
        $('a', this).addClass('black-text');
    });

    $('header ul.side-nav li a.social-link').hover(function() {
        $(this).addClass('light-blue lighten-2');
        $('i', this).removeClass('black-text');
        $('i', this).addClass('white-text');
    }, function() {
        $(this).removeClass('light-blue lighten-2');
        $('i', this).removeClass('white-text');
        $('i', this).addClass('black-text');
    });

    // window on scroll
    var onScroll = function(event) {
        var scrollHeight = Math.floor($(window).scrollTop());

        var elmHeight = $('#index-banner').offset().top;

        var elmSize = $('#index-banner').outerHeight();

        var navHeight = $('header nav').height();

        // console.log(Math.abs(elmHeight - scrollHeight), elmSize - navHeight);

        if (Math.abs(elmHeight - scrollHeight) > elmSize - navHeight) {
            $('header div.hide').removeClass('hide');
        } else {
            $('header div').addClass('hide');
        }
    };

    $(window).scroll(Materialize.throttle(onScroll, 100));

    /*  initialize skills */

    // get skills from json file
    $.getJSON('js/skills.json', function(json, textStatus) {
        var chips = json.chips;
        // create a chip for each skill
        $.each(chips, function(index, el) {
            // append new chip with given icon
            // and define appropriate handlers
            $('.chips').append(
                $(document.createElement('div'))
                    .addClass('chip')
                    .text(el.tag)
                    .append(
                        $(document.createElement('i'))
                            .addClass('close mdi mdi-' + el.icon)
                            .click(function(event) {
                                $(this).parent().trigger('click')
                                event.preventDefault();
                                event.stopPropagation();
                            })
                    )
                    .click(function(event) {
                        // clear current selected chip
                        $('.chip').removeClass('selected');
                        // select this chip
                        $(this).addClass('selected');
                        // fire selected event and pass in card
                        var card = $(document.createElement('div')).addClass('card-panel').html('

' + el.tag + '

' + el.text + '
');
                        $(this).trigger('chip.select', card);
                    })
            )
        });

        // hide the input box, won't be used here
        $('.chips-initial input').addClass('hide');

        $('.chips').on('chip.select', function(event, card) {
            event.preventDefault();
            $('.card-container').html(card);
        });

        $('.chips .chip')[0].click();
    });

  }); // end of document ready
})(jQuery); // end of jQuery name space<|endoftext|>


<commit_before>Array.prototype.forEachDone = function(fn, scope, lastfn) {
    for(var i = 0, c = 0, len = this.length; i < len; i++) {
        fn.call(scope, this[i], i, this, function() { // fn should be set up as fn(num, i, arr, done)
            ++c === len && lastfn();
        });
    }
};

function round(num, places) {
    var multiplier = Math.pow(10, places);
    return Math.round(num * multiplier) / multiplier;
}

var searchResultsTemplateSrc = $("#search-results-template").html();
var searchResultsTemplate = Handlebars.compile(searchResultsTemplateSrc);

var renderSearchResults = function (IDs, data) {
    var game = $("input[type=radio][name=game]:checked").val();
    if (IDs.length > 0) {
        var playerObjs = [];
        ref.child(game).child("participants").once("value", function (snapshot) {
            // First get participants
            var participants = snapshot.val();
            var numParticipants = Infinity;
            if (participants) {
                numParticipants = Object.keys(participants).length;
            }
            // Then iterate through Smasher IDs
            IDs.forEachDone(function (key, i, arr, done) {
                var playerObj = data[key];
                if (!playerObj.handle) {
                    // Assign empty player handle to empty string
                    playerObj.handle = "";
                }
                playerObj.id = key;
                // Calculate popularity
                ref.child(game).child("freqs").child(key).once("value", function (snap) {
                    var players = snap.val();
                    if (players) {
                        var numPlayers = Object.keys(players).length;
                        playerObj.popularity = round((numPlayers / numParticipants) * 100, 2);
                    } else {
                        playerObj.popularity = 0;
                    }
                    playerObj.scoreSpread = calculateScoreSpread(playerObj.popularity);
                    playerObjs.push(playerObj);
                    done();
                });
            }, this, function () {
                var context = {players: playerObjs};
                var renderedTemplate = searchResultsTemplate(context);
                $("#search-results-view").html(renderedTemplate);
                attachToggleListeners($("#search-results"), true);
                adjustPageHeight();
            });
        });
    } else {
        var context = {players: []};
        var renderedTemplate = searchResultsTemplate(context);
        $("#search-results-view").html(renderedTemplate);
        attachToggleListeners($("#search-results"), true);
        adjustPageHeight();
    }
};

var adjustPageHeight = function () {
    // Reset height first
    $(".col").css({
        height: ""
    });
    var pageHeight = $(document).height();
    $(".col").css({
        height: pageHeight
    });
};

var attachToggleListeners = function (olElement, isChooseBtn) {
    if (typeof isChooseBtn != "boolean") throw "isChooseBtn must be defined as boolean";
    olElement.find("li").each(function () {
        // Store heights beforehand
        $(this).data("fullHeight", $(this).outerHeight());
        var previewEl = $(this).find(".preview");
        var previewRelTop = previewEl.offset().top - $(this).offset().top;
        var previewHeight = previewEl.outerHeight(true);
        $(this).data("previewHeight", previewRelTop + previewHeight);
        $(this).css({
            height: $(this).data("previewHeight")
        });
        // Attach click listener to expand button
        var playerEl = $(this);
        var toggleBtn = $(this).find(".toggle-button");
        toggleBtn.on("click", function () {
            if (playerEl.hasClass("expanded")) {
                // Already expanded, need to shrink
                playerEl.removeClass("expanded");
                $(this).html("▼");
                playerEl.animate({
                    height: playerEl.data("previewHeight")
                }, 200);
            } else {
                // Was shrunk, need to expand
                playerEl.addClass("expanded");
                $(this).html("▲");
                playerEl.animate({
                    height: playerEl.data("fullHeight")
                }, 200);
            }
        });
        // Attach add/remove listeners
        var game = $("input[type=radio][name=game]:checked").val();
        var userID = getUserID();
        if (isChooseBtn) {
            var chooseBtn = $(this).find(".choose-button");
            chooseBtn.on("click", function () {
                addPlayer($(this).attr("id"), userID, game);
            });
        } else { // else it's remove btn
            var removeBtn = $(this).find(".remove-button");
            removeBtn.on("click", function () {
                removePlayer($(this).attr("id"), userID, game);
            });
        }
    });
};<commit_msg>Edit attachToggleListener<commit_after>Array.prototype.forEachDone = function(fn, scope, lastfn) {
    for(var i = 0, c = 0, len = this.length; i < len; i++) {
        fn.call(scope, this[i], i, this, function() { // fn should be set up as fn(num, i, arr, done)
            ++c === len && lastfn();
        });
    }
};

function round(num, places) {
    var multiplier = Math.pow(10, places);
    return Math.round(num * multiplier) / multiplier;
}

var searchResultsTemplateSrc = $("#search-results-template").html();
var searchResultsTemplate = Handlebars.compile(searchResultsTemplateSrc);

var renderSearchResults = function (IDs, data) {
    var game = $("input[type=radio][name=game]:checked").val();
    if (IDs.length > 0) {
        var playerObjs = [];
        ref.child(game).child("participants").once("value", function (snapshot) {
            // First get participants
            var participants = snapshot.val();
            var numParticipants = Infinity;
            if (participants) {
                numParticipants = Object.keys(participants).length;
            }
            // Then iterate through Smasher IDs
            IDs.forEachDone(function (key, i, arr, done) {
                var playerObj = data[key];
                if (!playerObj.handle) {
                    // Assign empty player handle to empty string
                    playerObj.handle = "";
                }
                playerObj.id = key;
                // Calculate popularity
                ref.child(game).child("freqs").child(key).once("value", function (snap) {
                    var players = snap.val();
                    if (players) {
                        var numPlayers = Object.keys(players).length;
                        playerObj.popularity = round((numPlayers / numParticipants) * 100, 2);
                    } else {
                        playerObj.popularity = 0;
                    }
                    playerObj.scoreSpread = calculateScoreSpread(playerObj.popularity);
                    playerObjs.push(playerObj);
                    done();
                });
            }, this, function () {
                var context = {players: playerObjs};
                var renderedTemplate = searchResultsTemplate(context);
                $("#search-results-view").html(renderedTemplate);
                attachToggleListeners($("#search-results"), true);
                adjustPageHeight();
            });
        });
    } else {
        var context = {players: []};
        var renderedTemplate = searchResultsTemplate(context);
        $("#search-results-view").html(renderedTemplate);
        attachToggleListeners($("#search-results"), true);
        adjustPageHeight();
    }
};

var adjustPageHeight = function () {
    // Reset height first
    $(".col").css({
        height: ""
    });
    var pageHeight = $(document).height();
    $(".col").css({
        height: pageHeight
    });
};

var attachToggleListeners = function (olElement, isChooseBtn) {
    if (typeof isChooseBtn != "boolean") throw "isChooseBtn must be defined as boolean";
    olElement.find("li").each(function () {
        // Store heights beforehand
        $(this).data("fullHeight", $(this).outerHeight());
        var previewEl = $(this).find(".preview");
        var previewRelTop = previewEl.offset().top - $(this).offset().top;
        var previewHeight = previewEl.outerHeight(true);
        $(this).data("previewHeight", previewRelTop + previewHeight);
        $(this).css({
            height: $(this).data("previewHeight")
        });
        // Attach click listener to expand button
        var playerEl = $(this);
        var toggleBtn = $(this).find(".toggle-button");
        toggleBtn.on("click", function () {
            if (playerEl.hasClass("expanded")) {
                // Already expanded, need to shrink
                playerEl.removeClass("expanded");
                $(this).html("▼");
                playerEl.animate({
                    height: playerEl.data("previewHeight")
                }, 200);
            } else {
                // Was shrunk, need to expand
                playerEl.addClass("expanded");
                $(this).html("▲");
                playerEl.animate({
                    height: playerEl.data("fullHeight")
                }, 200);
            }
        });
        // Attach add/remove listeners
        var game = $("input[type=radio][name=game]:checked").val();
        var userID = getUserID();
        if (isChooseBtn) {
            var chooseBtn = $(this).find(".choose-button");
            if (chooseBtn.length != 0) {
                chooseBtn.on("click", function () {
                    addPlayer($(this).attr("id"), userID, game);
                });
            }
        } else { // else it's remove btn
            var removeBtn = $(this).find(".remove-button");
            if (removeBtn.length != 0) {
                removeBtn.on("click", function () {
                    removePlayer($(this).attr("id"), userID, game);
                });
            }
        }
    });
};<|endoftext|>


<commit_before>(function($){
  $(function(){

    $('.button-collapse').sideNav();
    $('.parallax').parallax();

  }); // end of document ready
})(jQuery); // end of jQuery name space

var play_html = '

';
var pause_html = '

';
var download_html = '

';
var bar_html = '

';
var inside_bar_html = '

';

SC.initialize({
  client_id: 'e58500f22069ebf6de412ec63b4939b3'
});

splitOnBar = function(s, d){
  var splitTitle = s.split("|");
  if (splitTitle.length == 2) return splitTitle;
  if (d == null || d == "") d = " ";
  return [s,d];
}

// stream track id 293
$(document).ready(function(){

  SC.get('/playlists/51633482', function(playlist) {
    if (playlist.tracks.length < 6){
      $('#tracks1').parent().addClass("col-sm-offset-3")
                   .removeClass("sm-50px-padding-right")
                   .removeClass("sm-right-border");
      $('#tracks2').parent().hide();
    }
    $(playlist.tracks.slice(0,10)).each(function(i,e){
      var trackDiv = $('

')
        .appendTo(i < 5 ? '#tracks1' : '#tracks2');
      $("
" + splitOnBar(e.title, e.description)[0] + "
").appendTo(trackDiv);
      $('
' + splitOnBar(e.title, e.description)[1] + "
").appendTo(trackDiv);
      var play = $(play_html).appendTo(trackDiv);
      var pause = $(pause_html).appendTo(trackDiv);
      pause.hide();
      var download = $(download_html).appendTo(trackDiv);
      var bar = $(bar_html).appendTo(trackDiv);
      var inside_bar = $(inside_bar_html).appendTo(bar);
      SC.stream("/tracks/" + e.id, function(sound){
        var intrvl;
        play.click(function(){
            sound.play();
            play.hide();
            pause.show();
            intrvl = setInterval(function () {
                var end = parseFloat(e.duration);
                var howMuchSoFar = parseFloat(sound.position);
                var fraction = howMuchSoFar / end;
                var percent = (fraction * parseFloat(100)) + "%";
                $(inside_bar).css("width", percent);
            }, 500);
        });
        pause.click(function(){
            clearInterval(intrvl);
            sound.pause();
            pause.hide();
            play.show();
        });
        download.click(function(){
          window.location = e.download_url + "?client_id=e58500f22069ebf6de412ec63b4939b3";
        });
      });
    });
  });
});<commit_msg>sdfsdf<commit_after>(function($){
  $(function(){

    $('.button-collapse').sideNav();
    $('.parallax').parallax();

  }); // end of document ready
})(jQuery); // end of jQuery name space

var play_html = '

';
var pause_html = '

';
var download_html = '

';
var bar_html = '

';
var inside_bar_html = '

';

SC.initialize({
  client_id: 'e58500f22069ebf6de412ec63b4939b3'
});

splitOnBar = function(s, d){
  var splitTitle = s.split("|");
  if (splitTitle.length == 2) return splitTitle;
  if (d == null || d == "") d = " ";
  return [s,d];
}

// stream track id 293
$(document).ready(function(){

  SC.get('/playlists/51633482', function(playlist) {
    if (playlist.tracks.length < 6){
      $('#tracks1').parent().addClass("col-sm-offset-3")
                   .removeClass("sm-50px-padding-right")
                   .removeClass("sm-right-border");
      $('#tracks2').parent().hide();
    }
    $(playlist.tracks.slice(0,10)).each(function(i,e){
      var trackDiv = $('

')
        .appendTo(i < 5 ? '#tracks1' : '#tracks2');
      $("
" + splitOnBar(e.title, e.description)[0] + "
").appendTo(trackDiv);
      $('
' + splitOnBar(e.title, e.description)[1] + "
").appendTo(trackDiv);
      var play = $(play_html).appendTo(trackDiv);
      var pause = $(pause_html).appendTo(trackDiv);
      pause.hide();
      var download = $(download_html).appendTo(trackDiv);
      var bar = $(bar_html).appendTo(trackDiv);
      var inside_bar = $(inside_bar_html).appendTo(bar);
      SC.stream("/tracks/" + e.id, function(sound){
        var intrvl;
        play.click(function(){
            sound.play();
            play.hide();
            pause.show();
            intrvl = setInterval(function () {
                var end = parseFloat(e.duration);
                var howMuchSoFar = parseFloat(sound.position);
                var fraction = howMuchSoFar / end;
                var percent = (fraction * parseFloat(100)) + "%";
                $(inside_bar).css("width", percent);
            }, 500);
        });
        pause.click(function(){
            clearInterval(intrvl);
            sound.pause();
            pause.hide();
            play.show();
        });
        download.click(function(){
          window.location = e.download_url + "?client_id=e58500f22069ebf6de412ec63b4939b3";
        });
      });
    });
  });
});<|endoftext|>


<commit_before>'use strict';

const fs = require ('fs')
    , log = require ('ololog').handleNodeErrors ()
    // eslint-disable-next-line import/no-dynamic-require
    , ccxtpro = require (__dirname + '/../../ccxt.pro.js')

const [processPath, , exchangeId, exchangeSymbol] = process.argv.filter (x => !x.startsWith ('--'))
const verbose = process.argv.includes ('--verbose') || false

// ----------------------------------------------------------------------------

if (!exchangeId) {
    console.log ('Exchange id not specified')
    process.exit ()
}

log.bright ('\nTESTING', { exchangeId, symbol: exchangeSymbol || 'all' }, '\n')

// ----------------------------------------------------------------------------

const enableRateLimit = true

const { Agent } = require ('https')

const ecdhCurve = 'auto'
const agent = new Agent ({ ecdhCurve })

const timeout = 20000
const print = function printToFile (... args) {
    args = args.map ((x) => {
        if (typeof x === 'string') {
            return x
        } else if (x instanceof Date) {
            return x.toISOString ()
        } else {
            return JSON.stringify (x)
        }
    })
    fs.appendFileSync ('js.' + exchangeId + '.log', args.join (' ') + "\n")
}

const exchangeOptions = { agent, verbose, enableRateLimit, timeout, print }
const exchange = new (ccxtpro)[exchangeId] (exchangeOptions)

// ----------------------------------------------------------------------------

const tests = {}

const pathToExchangeTests = __dirname + '/Exchange/'
fs.readdirSync (pathToExchangeTests)
    .filter ((file) => file.match (/test.[a-zA-Z0-9_-]+.js$/))
    .forEach ((file) => {
        const key = file.slice (5, -3)
        // eslint-disable-next-line import/no-dynamic-require
        tests[key] = require (pathToExchangeTests + file)
    })

//-----------------------------------------------------------------------------

const keysGlobal = 'keys.json'
    , keysLocal = 'keys.local.json'
    , keysFile = fs.existsSync (keysLocal) ? keysLocal : keysGlobal
    // eslint-disable-next-line import/no-dynamic-require
    , settings = require (__dirname + '/../../' + keysFile)[exchangeId]

if (settings) {
    for (const key in settings) {
        if (settings[key]) {
            settings[key] = ccxtpro.deepExtend (exchange[key] || {}, settings[key])
        }
    }
}

Object.assign (exchange, settings)

if (settings && settings.skip) {
    log.error.bright ('[Skipped]', { exchange: exchangeId, symbol: exchangeSymbol || 'all' })
    process.exit ()
}

//-----------------------------------------------------------------------------

async function testPublic (exchange, symbol) {
    await tests['watchOrderBook']   (exchange, symbol)
    await tests['watchTicker']      (exchange, symbol)
    await tests['watchTrades']      (exchange, symbol)
    await tests['watchOHLCV']       (exchange, symbol)
    // await tests['watchStatus']      (exchange)
    // await tests['watchHeartbeat']   (exchange)
    // await tests['watchL2OrderBook'] (exchange, symbol)
    // await tests['watchOrderBooks']  (exchange, symbol)
    // await tests['watchTickers']     (exchange, [ symbol ])
}

async function testPrivate (exchange, symbol, code) {
    if (exchange.checkRequiredCredentials (false)) {
        await tests['watchBalance']      (exchange)
        // await tests['watchOrders']       (exchange, symbol)
        // await tests['watchOpenOrders']   (exchange, symbol)
        // await tests['watchClosedOrders'] (exchange, symbol)
        // await tests['watchMyTrades']     (exchange, symbol)
        // const code = exchange.markets[symbol]['quote']
        // await tests['watchLedger']       (exchange, code)
        // await tests['watchTransactions'] (exchange, code)
        // await tests['watchDeposits']     (exchange, code)
        // await tests['watchWithdrawals']  (exchange, code)
    }
}

//-----------------------------------------------------------------------------

async function testExchange (exchange) {

    const codes = [
        'BTC',
        'ETH',
        'XRP',
        'LTC',
        'BCH',
        'EOS',
        'BNB',
        'BSV',
        'USDT',
        'ATOM',
        'BAT',
        'BTG',
        'DASH',
        'DOGE',
        'ETC',
        'IOTA',
        'LSK',
        'MKR',
        'NEO',
        'PAX',
        'QTUM',
        'TRX',
        'TUSD',
        'USD',
        'USDC',
        'WAVES',
        'XEM',
        'XMR',
        'ZEC',
        'ZRX',
    ]
    let code = codes[0]
    for (let c in codes) {
        if (c in exchange.currencies) {
            code = c
        }
    }

    let symbol = exchange.symbols[0]
    const symbols = [
        'BTC/KRW',
        'BTC/USD',
        'BTC/USDT',
        'BTC/CNY',
        'BTC/EUR',
        'BTC/ETH',
        'ETH/BTC',
        'BTC/JPY',
        'LTC/BTC',
        'ZRX/WETH',
    ]
    for (let s in symbols) {
        if (exchange.symbols.includes (symbols[s]) &&
            (('active' in exchange.markets[symbols[s]]) ? exchange.markets[symbols[s]]['active'] : true)) {
            symbol = symbols[s]
            break
        }
    }

    log.green ('CODE:', code)
    log.green ('SYMBOL:', symbol)

    if ((symbol.indexOf ('.d') < 0)) {
        await testPublic  (exchange, symbol)
        await testPrivate (exchange, symbol, code)
    }
}

//-----------------------------------------------------------------------------

(async () => {

    await exchange.loadMarkets ()
    await testExchange (exchange, exchangeSymbol)
    console.log (new Date (), 'Done.')
    process.exit ()

}) ()
<commit_msg>debug binanceje<commit_after>'use strict';

const fs = require ('fs')
    , log = require ('ololog').handleNodeErrors ()
    // eslint-disable-next-line import/no-dynamic-require
    , ccxtpro = require (__dirname + '/../../ccxt.pro.js')

const [processPath, , exchangeId, exchangeSymbol] = process.argv.filter (x => !x.startsWith ('--'))
let verbose = process.argv.includes ('--verbose') || false

// ----------------------------------------------------------------------------

if (!exchangeId) {
    console.log ('Exchange id not specified')
    process.exit ()
}

log.bright ('\nTESTING', { exchangeId, symbol: exchangeSymbol || 'all' }, '\n')

// ----------------------------------------------------------------------------

const enableRateLimit = true

const { Agent } = require ('https')

const ecdhCurve = 'auto'
const agent = new Agent ({ ecdhCurve })

const timeout = 20000
const print = function printToFile (... args) {
    args = args.map ((x) => {
        if (typeof x === 'string') {
            return x
        } else if (x instanceof Date) {
            return x.toISOString ()
        } else {
            return JSON.stringify (x)
        }
    })
    fs.appendFileSync ('js.' + exchangeId + '.log', args.join (' ') + "\n")
}

if (exchangeId === 'binanceje') {
    verbose = true
}

const exchangeOptions = {
    agent,
    verbose,
    enableRateLimit,
    timeout,
    print,
}
const exchange = new (ccxtpro)[exchangeId] (exchangeOptions)

// ----------------------------------------------------------------------------

const tests = {}

const pathToExchangeTests = __dirname + '/Exchange/'
fs.readdirSync (pathToExchangeTests)
    .filter ((file) => file.match (/test.[a-zA-Z0-9_-]+.js$/))
    .forEach ((file) => {
        const key = file.slice (5, -3)
        // eslint-disable-next-line import/no-dynamic-require
        tests[key] = require (pathToExchangeTests + file)
    })

//-----------------------------------------------------------------------------

const keysGlobal = 'keys.json'
    , keysLocal = 'keys.local.json'
    , keysFile = fs.existsSync (keysLocal) ? keysLocal : keysGlobal
    // eslint-disable-next-line import/no-dynamic-require
    , settings = require (__dirname + '/../../' + keysFile)[exchangeId]

if (settings) {
    for (const key in settings) {
        if (settings[key]) {
            settings[key] = ccxtpro.deepExtend (exchange[key] || {}, settings[key])
        }
    }
}

Object.assign (exchange, settings)

if (settings && settings.skip) {
    log.error.bright ('[Skipped]', { exchange: exchangeId, symbol: exchangeSymbol || 'all' })
    process.exit ()
}

//-----------------------------------------------------------------------------

async function testPublic (exchange, symbol) {
    await tests['watchOrderBook']   (exchange, symbol)
    await tests['watchTicker']      (exchange, symbol)
    await tests['watchTrades']      (exchange, symbol)
    await tests['watchOHLCV']       (exchange, symbol)
    // await tests['watchStatus']      (exchange)
    // await tests['watchHeartbeat']   (exchange)
    // await tests['watchL2OrderBook'] (exchange, symbol)
    // await tests['watchOrderBooks']  (exchange, symbol)
    // await tests['watchTickers']     (exchange, [ symbol ])
}

async function testPrivate (exchange, symbol, code) {
    if (exchange.checkRequiredCredentials (false)) {
        await tests['watchBalance']      (exchange)
        // await tests['watchOrders']       (exchange, symbol)
        // await tests['watchOpenOrders']   (exchange, symbol)
        // await tests['watchClosedOrders'] (exchange, symbol)
        // await tests['watchMyTrades']     (exchange, symbol)
        // const code = exchange.markets[symbol]['quote']
        // await tests['watchLedger']       (exchange, code)
        // await tests['watchTransactions'] (exchange, code)
        // await tests['watchDeposits']     (exchange, code)
        // await tests['watchWithdrawals']  (exchange, code)
    }
}

//-----------------------------------------------------------------------------

async function testExchange (exchange) {

    const codes = [
        'BTC',
        'ETH',
        'XRP',
        'LTC',
        'BCH',
        'EOS',
        'BNB',
        'BSV',
        'USDT',
        'ATOM',
        'BAT',
        'BTG',
        'DASH',
        'DOGE',
        'ETC',
        'IOTA',
        'LSK',
        'MKR',
        'NEO',
        'PAX',
        'QTUM',
        'TRX',
        'TUSD',
        'USD',
        'USDC',
        'WAVES',
        'XEM',
        'XMR',
        'ZEC',
        'ZRX',
    ]
    let code = codes[0]
    for (let c in codes) {
        if (c in exchange.currencies) {
            code = c
        }
    }

    let symbol = exchange.symbols[0]
    const symbols = [
        'BTC/KRW',
        'BTC/USD',
        'BTC/USDT',
        'BTC/CNY',
        'BTC/EUR',
        'BTC/ETH',
        'ETH/BTC',
        'BTC/JPY',
        'LTC/BTC',
        'ZRX/WETH',
    ]
    for (let s in symbols) {
        if (exchange.symbols.includes (symbols[s]) &&
            (('active' in exchange.markets[symbols[s]]) ? exchange.markets[symbols[s]]['active'] : true)) {
            symbol = symbols[s]
            break
        }
    }

    log.green ('CODE:', code)
    log.green ('SYMBOL:', symbol)

    if ((symbol.indexOf ('.d') < 0)) {
        await testPublic  (exchange, symbol)
        await testPrivate (exchange, symbol, code)
    }
}

//-----------------------------------------------------------------------------

(async () => {

    await exchange.loadMarkets ()
    await testExchange (exchange, exchangeSymbol)
    console.log (new Date (), 'Done.')
    process.exit ()

}) ()
<|endoftext|>


<commit_before>(function($){
  $(function(){

    $('.button-collapse').sideNav();
    $('.parallax').parallax();

  }); // end of document ready
})(jQuery); // end of jQuery name space

var play_html = '

';
var pause_html = '

';
var download_html = '

';
var bar_html = '

';
var inside_bar_html = '

';

SC.initialize({
  client_id: 'e58500f22069ebf6de412ec63b4939b3'
});

splitOnBar = function(s, d){
  var splitTitle = s.split("|");
  if (splitTitle.length == 2) return splitTitle;
  if (d == null || d == "") d = " ";
  return [s,d];
}

// stream track id 293
$(document).ready(function(){

  SC.get('/playlists/51633482', function(playlist) {
    if (playlist.tracks.length < 6){
      $('#tracks1').parent().addClass("col-sm-offset-3")
                   .removeClass("sm-50px-padding-right")
                   .removeClass("sm-right-border");
      $('#tracks2').parent().hide();
    }
    $(playlist.tracks.slice(0,10)).each(function(i,e){
      var trackDiv = $('

')
        .appendTo(i < 5 ? '#tracks1' : '#tracks2');
      $("
" + splitOnBar(e.title, e.description)[0] + "
").appendTo(trackDiv);
      $('
' + splitOnBar(e.title, e.description)[1] + "
").appendTo(trackDiv);
      var play = $(play_html).appendTo(trackDiv);
      var pause = $(pause_html).appendTo(trackDiv);
      pause.hide();
      var download = $(download_html).appendTo(trackDiv);
      var bar = $(bar_html).appendTo(trackDiv);
      var inside_bar = $(inside_bar_html).appendTo(bar);
      SC.stream("/tracks/" + e.id, function(sound){
        var intrvl;
        play.click(function(){
            sound.play();
            play.hide();
            pause.show();
            intrvl = setInterval(function () {
                var end = parseFloat(e.duration);
                var howMuchSoFar = parseFloat(sound.position);
                var fraction = howMuchSoFar / end;
                var percent = (fraction * parseFloat(100)) + "%";
                $(inside_bar).css("width", percent);
            }, 500);
        });
        pause.click(function(){
            clearInterval(intrvl);
            sound.pause();
            pause.hide();
            play.show();
        });
        download.click(function(){
          window.location = e.download_url + "?client_id=e58500f22069ebf6de412ec63b4939b3";
        });
      });
    });
  });
});<commit_msg>margin top<commit_after>(function($){
  $(function(){

    $('.button-collapse').sideNav();
    $('.parallax').parallax();

  }); // end of document ready
})(jQuery); // end of jQuery name space

var play_html = '

';
var pause_html = '

';
var download_html = '

';
var bar_html = '

';
var inside_bar_html = '

';

SC.initialize({
  client_id: 'e58500f22069ebf6de412ec63b4939b3'
});

splitOnBar = function(s, d){
  var splitTitle = s.split("|");
  if (splitTitle.length == 2) return splitTitle;
  if (d == null || d == "") d = " ";
  return [s,d];
}

// stream track id 293
$(document).ready(function(){

  SC.get('/playlists/51633482', function(playlist) {
    if (playlist.tracks.length < 6){
      $('#tracks1').parent().addClass("col-sm-offset-3")
                   .removeClass("sm-50px-padding-right")
                   .removeClass("sm-right-border");
      $('#tracks2').parent().hide();
    }
    $(playlist.tracks.slice(0,10)).each(function(i,e){
      var trackDiv = $('

')
        .appendTo(i < 5 ? '#tracks1' : '#tracks2');
      $("
" + splitOnBar(e.title, e.description)[0] + "
").appendTo(trackDiv);
      $('
' + splitOnBar(e.title, e.description)[1] + "
").appendTo(trackDiv);
      var play = $(play_html).appendTo(trackDiv);
      var pause = $(pause_html).appendTo(trackDiv);
      pause.hide();
      var download = $(download_html).appendTo(trackDiv);
      var bar = $(bar_html).appendTo(trackDiv);
      var inside_bar = $(inside_bar_html).appendTo(bar);
      SC.stream("/tracks/" + e.id, function(sound){
        var intrvl;
        play.click(function(){
            sound.play();
            play.hide();
            pause.show();
            intrvl = setInterval(function () {
                var end = parseFloat(e.duration);
                var howMuchSoFar = parseFloat(sound.position);
                var fraction = howMuchSoFar / end;
                var percent = (fraction * parseFloat(100)) + "%";
                $(inside_bar).css("width", percent);
            }, 500);
        });
        pause.click(function(){
            clearInterval(intrvl);
            sound.pause();
            pause.hide();
            play.show();
        });
        download.click(function(){
          window.location = e.download_url + "?client_id=e58500f22069ebf6de412ec63b4939b3";
        });
      });
    });
  });
});<|endoftext|>


<commit_before>/* global $, Gallery */
/**
 * A thumbnail is the actual image attached to the GalleryImage object
 *
 * @param {number} fileId
 * @param {bool} square
 * @constructor
 */
function Thumbnail (fileId, square) {
	this.square = square;
	this.fileId = fileId;
	this.image = null;
	this.loadingDeferred = new $.Deferred();
	this.height = 200;
	this.width = 400;
	this.ratio = null;
	this.valid = true;
	this.status = 200;
}

var Thumbnails = {};
Thumbnails.map = {};
Thumbnails.squareMap = {};

/**
 * Retrieves the thumbnail linked to the given fileID
 *
 * @param {number} fileId
 * @param {bool} square
 *
 * @returns {Thumbnail}
 */
Thumbnails.get = function (fileId, square) {
	var map = {};
	if (square === true) {
		map = Thumbnails.squareMap;
		square = true;
	} else {
		map = Thumbnails.map;
		square = false;
	}
	if (!map[fileId]) {
		map[fileId] = new Thumbnail(fileId, square);
	}

	return map[fileId];
};

/**
 * Returns an icon of a specific type
 *
 * -1 is for a folder
 * -404 is for a broken file icon
 * -500 is for a media type icon
 *
 * @param {number} type
 *
 * @returns {Thumbnail}
 */
Thumbnails.getStandardIcon = function (type) {
	if (!Thumbnails.squareMap[type]) {
		var icon = '';
		// true means square
		var thumb = new Thumbnail(type, true);
		thumb.image = new Image();
		thumb.image.onload = function () {
			thumb.loadingDeferred.resolve(thumb.image);
		};

		if (type === -1) {
			icon = 'folder.svg';
		}
		thumb.image.src = OC.imagePath(Gallery.appName, icon);

		Thumbnails.squareMap[type] = thumb;

		// FIXME console.log
		console.log('Folder Thumbnail created', Thumbnails.squareMap[type]);

	}

	return Thumbnails.squareMap[type];
};

/**
 * Loads thumbnails in batch, using EventSource
 *
 * @param {array} ids
 * @param {bool} square
 *
 * @returns {{}}
 */
Thumbnails.loadBatch = function (ids, square) {
	var map = (square) ? Thumbnails.squareMap : Thumbnails.map;
	// Purely here as a precaution
	ids = ids.filter(function (id) {
		return !map[id];
	});
	var batch = {};
	var i, idsLength = ids.length;
	if (idsLength) {
		for (i = 0; i < idsLength; i++) {
			var thumb = new Thumbnail(ids[i], square);
			thumb.image = new Image();
			map[ids[i]] = batch[ids[i]] = thumb;

		}
		var params = {
			ids: ids.join(';'),
			scale: window.devicePixelRatio,
			square: (square) ? 1 : 0
		};
		var url = Gallery.utility.buildGalleryUrl('thumbnails', '', params);

		var eventSource = new Gallery.EventSource(url);
		eventSource.listen('preview', function (/**{path, status, mimetype, preview}*/ preview) {
			var id = preview.fileid;
			var thumb = batch[id];
			thumb.status = preview.status;
			if (thumb.status === 404) {
				thumb.valid = false;
				thumb.loadingDeferred.resolve(null);
			} else {
				thumb.image.onload = function () {
					// Fix for SVG files which can come in all sizes
					if (square) {
						thumb.image.width = 200;
						thumb.image.height = 200;
					}
					thumb.image.ratio = thumb.image.width / thumb.image.height;
					thumb.image.originalWidth = 200 * thumb.image.ratio;
					thumb.loadingDeferred.resolve(thumb.image);
				};
				thumb.image.onerror = function () {
					thumb.valid = false;
					thumb.loadingDeferred.resolve(null);
				};

				if (thumb.status === 200) {
					thumb.image.src = 'data:' + preview.mimetype + ';base64,' + preview.preview;
				} else {
					thumb.valid = false;
					thumb.image.src = Gallery.mediaTypes[preview.mimetype];

				}
			}
		});
	}

	return batch;
};
<commit_msg>Use the new mediaTypes location<commit_after>/* global $, Gallery */
/**
 * A thumbnail is the actual image attached to the GalleryImage object
 *
 * @param {number} fileId
 * @param {bool} square
 * @constructor
 */
function Thumbnail (fileId, square) {
	this.square = square;
	this.fileId = fileId;
	this.image = null;
	this.loadingDeferred = new $.Deferred();
	this.height = 200;
	this.width = 400;
	this.ratio = null;
	this.valid = true;
	this.status = 200;
}

var Thumbnails = {};
Thumbnails.map = {};
Thumbnails.squareMap = {};

/**
 * Retrieves the thumbnail linked to the given fileID
 *
 * @param {number} fileId
 * @param {bool} square
 *
 * @returns {Thumbnail}
 */
Thumbnails.get = function (fileId, square) {
	var map = {};
	if (square === true) {
		map = Thumbnails.squareMap;
		square = true;
	} else {
		map = Thumbnails.map;
		square = false;
	}
	if (!map[fileId]) {
		map[fileId] = new Thumbnail(fileId, square);
	}

	return map[fileId];
};

/**
 * Returns an icon of a specific type
 *
 * -1 is for a folder
 * -404 is for a broken file icon
 * -500 is for a media type icon
 *
 * @param {number} type
 *
 * @returns {Thumbnail}
 */
Thumbnails.getStandardIcon = function (type) {
	if (!Thumbnails.squareMap[type]) {
		var icon = '';
		// true means square
		var thumb = new Thumbnail(type, true);
		thumb.image = new Image();
		thumb.image.onload = function () {
			thumb.loadingDeferred.resolve(thumb.image);
		};

		if (type === -1) {
			icon = 'folder.svg';
		}
		thumb.image.src = OC.imagePath(Gallery.appName, icon);

		Thumbnails.squareMap[type] = thumb;
	}

	return Thumbnails.squareMap[type];
};

/**
 * Loads thumbnails in batch, using EventSource
 *
 * @param {array} ids
 * @param {bool} square
 *
 * @returns {{}}
 */
Thumbnails.loadBatch = function (ids, square) {
	var map = (square) ? Thumbnails.squareMap : Thumbnails.map;
	// Purely here as a precaution
	ids = ids.filter(function (id) {
		return !map[id];
	});
	var batch = {};
	var i, idsLength = ids.length;
	if (idsLength) {
		for (i = 0; i < idsLength; i++) {
			var thumb = new Thumbnail(ids[i], square);
			thumb.image = new Image();
			map[ids[i]] = batch[ids[i]] = thumb;

		}
		var params = {
			ids: ids.join(';'),
			scale: window.devicePixelRatio,
			square: (square) ? 1 : 0
		};
		var url = Gallery.utility.buildGalleryUrl('thumbnails', '', params);

		var eventSource = new Gallery.EventSource(url);
		eventSource.listen('preview', function (/**{path, status, mimetype, preview}*/ preview) {
			var id = preview.fileid;
			var thumb = batch[id];
			thumb.status = preview.status;
			if (thumb.status === 404) {
				thumb.valid = false;
				thumb.loadingDeferred.resolve(null);
			} else {
				thumb.image.onload = function () {
					// Fix for SVG files which can come in all sizes
					if (square) {
						thumb.image.width = 200;
						thumb.image.height = 200;
					}
					thumb.image.ratio = thumb.image.width / thumb.image.height;
					thumb.image.originalWidth = 200 * thumb.image.ratio;
					thumb.loadingDeferred.resolve(thumb.image);
				};
				thumb.image.onerror = function () {
					thumb.valid = false;
					thumb.loadingDeferred.resolve(null);
				};

				if (thumb.status === 200) {
					thumb.image.src = 'data:' + preview.mimetype + ';base64,' + preview.preview;
				} else {
					thumb.valid = false;
					thumb.image.src = Gallery.config.mediaTypes[preview.mimetype];

				}
			}
		});
	}

	return batch;
};
<|endoftext|>


<commit_before>var videoURL = 'notset';
var photoURL = 'notset';
var matchItem = [
    'snap it',
    'click it'
];
(function ($) {
    $(function () {

        $('.button-collapse').sideNav();
        $('.modal').modal();
        $('#camIP').val('172.16.10.83');
        $('#camPort').val('8080');
        //setVideo();
        $('#IPCamAddress').modal('open');

        var recognition = new webkitSpeechRecognition();
        recognition.continuous = true;
        recognition.interimResults = false;
        recognition.lang = "en-US";
        recognition.start();

        recognition.onresult = function (event) {
            var text = "";
            for (var i = event.resultIndex; i < event.results.length; ++i) {
                text += event.results[i][0].transcript;
            }
            console.log(text + matchItem.indexOf(text));
            if (matchItem.indexOf(text) != -1) {
                console.log('IN');
                Materialize.toast('Snapping the Pic', 3000, 'rounded');
                snapit();
            }

        };
        $(window).keydown(function (event) {
            if (event.ctrlKey && (event.which == 83 || event.which == 115)) {
                console.log('IN');
                Materialize.toast('Snapping the Pic', 3000, 'rounded');
                snapit();
                event.preventDefault();
            }
        });
        $.ajaxSetup({
            cache: true
        });
        $.getScript('//connect.facebook.net/en_US/sdk.js', function () {
            FB.init({
                appId: getAppId(),
                version: 'v2.7' // or v2.1, v2.2, v2.3, ...
            });

            FB.login(function () {
                console.log('Log in Done');
            }, {
                scope: 'publish_actions'
            });

        });

        startTime();
        getTemp();
        getNews();

    }); // end of document ready
})(jQuery); // end of jQuery name space

function setVideo() {
    var ip = $('#camIP').val();
    var port = $('#camPort').val();
    videoURL = "http://" + ip + ":" + port + "/video";
    photoURL = "http://" + ip + ":" + port + "/photoaf.jpg";

    $('#videoImg').attr("src", videoURL);
}
<commit_msg>ip changed<commit_after>var videoURL = 'notset';
var photoURL = 'notset';
var matchItem = [
    'snap it',
    'click it'
];
(function ($) {
    $(function () {

        $('.button-collapse').sideNav();
        $('.modal').modal();
        $('#camIP').val('172.16.10.110');
        $('#camPort').val('8080');
        //setVideo();
        $('#IPCamAddress').modal('open');

        var recognition = new webkitSpeechRecognition();
        recognition.continuous = true;
        recognition.interimResults = false;
        recognition.lang = "en-US";
        recognition.start();

        recognition.onresult = function (event) {
            var text = "";
            for (var i = event.resultIndex; i < event.results.length; ++i) {
                text += event.results[i][0].transcript;
            }
            console.log(text + matchItem.indexOf(text));
            if (matchItem.indexOf(text) != -1) {
                console.log('IN');
                Materialize.toast('Snapping the Pic', 3000, 'rounded');
                snapit();
            }

        };
        $(window).keydown(function (event) {
            if (event.ctrlKey && (event.which == 83 || event.which == 115)) {
                console.log('IN');
                Materialize.toast('Snapping the Pic', 3000, 'rounded');
                snapit();
                event.preventDefault();
            }
        });
        $.ajaxSetup({
            cache: true
        });
        $.getScript('//connect.facebook.net/en_US/sdk.js', function () {
            FB.init({
                appId: getAppId(),
                version: 'v2.7' // or v2.1, v2.2, v2.3, ...
            });

            FB.login(function () {
                console.log('Log in Done');
            }, {
                scope: 'publish_actions'
            });

        });

        startTime();
        getTemp();
        getNews();

    }); // end of document ready
})(jQuery); // end of jQuery name space

function setVideo() {
    var ip = $('#camIP').val();
    var port = $('#camPort').val();
    videoURL = "http://" + ip + ":" + port + "/video";
    photoURL = "http://" + ip + ":" + port + "/photoaf.jpg";

    $('#videoImg').attr("src", videoURL);
}
<|endoftext|>


<commit_before>Reveal.addEventListener("ready", function() {
  var Ap = Array.prototype;
  var each = Ap.forEach;
  var slice = Ap.slice;

  var codes = document.querySelectorAll("code.javascript,code.xml");
  each.call(codes, function (block) {
    console.log(block);
    hljs.highlightBlock(block);
  });

  var blinkers = slice.call(document.querySelectorAll(".blink"));
  if (blinkers.length > 0) {
    var visible = true;
    function setVisibility(blinker) {
      blinker.style.visibility = visible ? "visible" : "hidden";
    }

    function go() {
      blinkers.forEach(setVisibility);
      setTimeout(go, visible ? 1000 : 500);
      visible = ! visible;
    }

    go();
  }
});

// Full list of configuration options available at:
// https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
  controls: true,
  progress: true,
  history: true,
  center: true,

  transition: 'none', // none/fade/slide/convex/concave/zoom

  // Optional reveal.js plugins
  dependencies: [{
    src: 'lib/js/classList.js',
    condition: function() {
      return !document.body.classList;
    }
  }, {
    src: 'plugin/markdown/marked.js',
    condition: function() {
      return !!document.querySelector( '[data-markdown]' );
    }
  }, {
    src: 'plugin/markdown/markdown.js',
    condition: function() {
      return !!document.querySelector( '[data-markdown]' );
    }
  }, {
    src: 'plugin/zoom-js/zoom.js',
    async: true
  }, {
    src: 'plugin/notes/notes.js',
    async: true
  }]
});
<commit_msg>Remove stray console.log.<commit_after>Reveal.addEventListener("ready", function() {
  var Ap = Array.prototype;
  var each = Ap.forEach;
  var slice = Ap.slice;

  var codes = document.querySelectorAll("code.javascript,code.xml");
  each.call(codes, function (block) {
    hljs.highlightBlock(block);
  });

  var blinkers = slice.call(document.querySelectorAll(".blink"));
  if (blinkers.length > 0) {
    var visible = true;
    function setVisibility(blinker) {
      blinker.style.visibility = visible ? "visible" : "hidden";
    }

    function go() {
      blinkers.forEach(setVisibility);
      setTimeout(go, visible ? 1000 : 500);
      visible = ! visible;
    }

    go();
  }
});

// Full list of configuration options available at:
// https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
  controls: true,
  progress: true,
  history: true,
  center: true,

  transition: 'none', // none/fade/slide/convex/concave/zoom

  // Optional reveal.js plugins
  dependencies: [{
    src: 'lib/js/classList.js',
    condition: function() {
      return !document.body.classList;
    }
  }, {
    src: 'plugin/markdown/marked.js',
    condition: function() {
      return !!document.querySelector( '[data-markdown]' );
    }
  }, {
    src: 'plugin/markdown/markdown.js',
    condition: function() {
      return !!document.querySelector( '[data-markdown]' );
    }
  }, {
    src: 'plugin/zoom-js/zoom.js',
    async: true
  }, {
    src: 'plugin/notes/notes.js',
    async: true
  }]
});
<|endoftext|>