<commit_before>/********************************************************
 * Copyright (c) 2013 Azavea, Inc.
 * See LICENSE in the project root for copying permission
 * Requires: google-maps-api-v3; jquery-1.7.2
 ********************************************************/

var ecepAdmin = ((typeof ecepAdmin === 'undefined') ? {} : ecepAdmin);

ecepAdmin.marker_array = [];
ecepAdmin.map;

ecepAdmin.clearMarkers = function() {
    for (var i = 0; i < ecepAdmin.marker_array.length; i++){
        ecepAdmin.marker_array[i].setMap(null);
    }
    ecepAdmin.marker_array = [];
}

ecepAdmin.addMarker = function(location) {
    var marker = new google.maps.Marker({
        map: ecepAdmin.map,
        position: location
    });
    google.maps.event.addListener(marker, 'click', function() {
        ecepAdmin.addGeocodedPoint(marker.getPosition());
    });

    ecepAdmin.marker_array.push(marker);
};

ecepAdmin.loadMap = function(){
    var latlng = new google.maps.LatLng(latSettings, lngSettings);
    var mapOptions = {
        zoom: 12,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    ecepAdmin.map = new google.maps.Map($('#map')[0], mapOptions);

    google.maps.event.addListener(ecepAdmin.map, "rightclick", function(event) {
        ecepAdmin.clearMarkers();
        ecepAdmin.addMarker(event.latLng);
        ecepAdmin.addGeocodedPoint(event.latLng);
    });

    if ($('#id_geom').val() && $('#id_geom').val() !== 'None') {
        // If point already found, center and add marker there
        var regexPoints = /([-.\d]+) ([-.\d]+)/;
        var results = regexPoints.exec($('#id_geom').val());
        var latlng = new google.maps.LatLng(results[2], results[1]);
        ecepAdmin.map.setZoom(15);
        ecepAdmin.map.setCenter(latlng);
        ecepAdmin.addMarker(latlng);
    }

};

// Function to add geocoded location to admin form
ecepAdmin.addGeocodedPoint = function(location) {
    $('#id_geom').val("POINT (" + location.lng() + " " + location.lat() + ")");
};

// Function to filter results that are not rooftop results
ecepAdmin.rooftopResults = function(geocode_results) {
    for (var i = 0; i < geocode_results.length; i++) {
        if (geocode_results[i].geometry.location_type !== 'ROOFTOP') {
            geocode_results.splice(i, 1);
        }
    }
};

/** Function to geocode address and insert value into the location
 *  input of the admin form.
 *
 *  Provides user feedback if geocoding is unsuccessful and describes
 *  how to manually set the geolocation by right-clicking
 */
ecepAdmin.geocodeAddress = function() {
    var geocoder = new google.maps.Geocoder();
    var $mapHelp = $('#map-help');
    var streetnum = $("#id_address").val(),
        city = $("#id_city").val(),
        state = $("#id_state").val(),
        zip = $("#id_zip").val();
    var address = [streetnum, city, state, zip].join(', ');
    ecepAdmin.clearMarkers();

    geocoder.geocode( {'address': address}, function(results, status) {
        // Filter results (only rooftop)
        ecepAdmin.rooftopResults(results);

        for (var i = 0; i < results.length; i++) {
            // Add markers for all results
            ecepAdmin.addMarker(results[i].geometry.location);
        }

        if (results.length === 1) {
        // If only one marker, set the form value to that location
        // and zoom into that location
            $mapHelp.hide();
            ecepAdmin.addGeocodedPoint(results[0].geometry.location);
            ecepAdmin.map.setZoom(15);
            ecepAdmin.map.setCenter(results[0].geometry.location);
        }

        else if (results.length > 1) {
        // If more than 2 results, let user know they can choose one
        // by clicking on the correct marker or they can set their
        // own marker with a right-click
            $mapHelp.text("There are multiple locations that match that address, please select the correct location by clicking on a marker. You can also set the location manually by right-clicking on a position.");
            $mapHelp.show();

            // Zoom in on multiple markers
            var bounds = new google.maps.LatLngBounds();
            for (var j = 0; j < results.length; j++) {
                bounds.extend(results[j].geometry.location);
            };
            ecepAdmin.map.fitBounds(bounds);
        }
        else if (results.length === 0 || status !== google.maps.GeocoderStatus.OK) {
            // If there aren't any results, let user know they can manually set
            // the location by right clicking on the map
            $mapHelp.text("We could not match that address to a location. You can manually set the location by right-clicking on any location on the map.");
            $mapHelp.show();
        }

    });
};

ecepAdmin.mapHelp = function() {
    $('#map-help').text("Please fill in the address of the location then click the 'Geocode Address' button to find its latitude and longitude. You can also select a location manually by right-clicking anywhere on the map.");
    $('#map-help').show();
};

google.maps.event.addDomListener(window, 'load', ecepAdmin.loadMap);
<commit_msg>Remove filter for geocoding<commit_after>/********************************************************
 * Copyright (c) 2013 Azavea, Inc.
 * See LICENSE in the project root for copying permission
 * Requires: google-maps-api-v3; jquery-1.7.2
 ********************************************************/

var ecepAdmin = ((typeof ecepAdmin === 'undefined') ? {} : ecepAdmin);

ecepAdmin.marker_array = [];
ecepAdmin.map;

ecepAdmin.clearMarkers = function() {
    for (var i = 0; i < ecepAdmin.marker_array.length; i++){
        ecepAdmin.marker_array[i].setMap(null);
    }
    ecepAdmin.marker_array = [];
}

ecepAdmin.addMarker = function(location) {
    var marker = new google.maps.Marker({
        map: ecepAdmin.map,
        position: location
    });
    google.maps.event.addListener(marker, 'click', function() {
        ecepAdmin.addGeocodedPoint(marker.getPosition());
    });

    ecepAdmin.marker_array.push(marker);
};

ecepAdmin.loadMap = function(){
    var latlng = new google.maps.LatLng(latSettings, lngSettings);
    var mapOptions = {
        zoom: 12,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    ecepAdmin.map = new google.maps.Map($('#map')[0], mapOptions);

    google.maps.event.addListener(ecepAdmin.map, "rightclick", function(event) {
        ecepAdmin.clearMarkers();
        ecepAdmin.addMarker(event.latLng);
        ecepAdmin.addGeocodedPoint(event.latLng);
    });

    if ($('#id_geom').val() && $('#id_geom').val() !== 'None') {
        // If point already found, center and add marker there
        var regexPoints = /([-.\d]+) ([-.\d]+)/;
        var results = regexPoints.exec($('#id_geom').val());
        var latlng = new google.maps.LatLng(results[2], results[1]);
        ecepAdmin.map.setZoom(15);
        ecepAdmin.map.setCenter(latlng);
        ecepAdmin.addMarker(latlng);
    }

};

// Function to add geocoded location to admin form
ecepAdmin.addGeocodedPoint = function(location) {
    $('#id_geom').val("POINT (" + location.lng() + " " + location.lat() + ")");
};

/** Function to geocode address and insert value into the location
 *  input of the admin form.
 *
 *  Provides user feedback if geocoding is unsuccessful and describes
 *  how to manually set the geolocation by right-clicking
 */
ecepAdmin.geocodeAddress = function() {
    var geocoder = new google.maps.Geocoder();
    var $mapHelp = $('#map-help');
    var streetnum = $("#id_address").val(),
        city = $("#id_city").val(),
        state = $("#id_state").val(),
        zip = $("#id_zip").val();
    var address = [streetnum, city, state, zip].join(', ');
    ecepAdmin.clearMarkers();

    geocoder.geocode( {'address': address}, function(results, status) {

        for (var i = 0; i < results.length; i++) {
            // Add markers for all results
            ecepAdmin.addMarker(results[i].geometry.location);
        }

        if (results.length === 1) {
        // If only one marker, set the form value to that location
        // and zoom into that location
            $mapHelp.hide();
            ecepAdmin.addGeocodedPoint(results[0].geometry.location);
            ecepAdmin.map.setZoom(15);
            ecepAdmin.map.setCenter(results[0].geometry.location);
        }

        else if (results.length > 1) {
        // If more than 2 results, let user know they can choose one
        // by clicking on the correct marker or they can set their
        // own marker with a right-click
            $mapHelp.text("There are multiple locations that match that address, please select the correct location by clicking on a marker. You can also set the location manually by right-clicking on a position.");
            $mapHelp.show();

            // Zoom in on multiple markers
            var bounds = new google.maps.LatLngBounds();
            for (var j = 0; j < results.length; j++) {
                bounds.extend(results[j].geometry.location);
            };
            ecepAdmin.map.fitBounds(bounds);
        }
        else if (results.length === 0 || status !== google.maps.GeocoderStatus.OK) {
            // If there aren't any results, let user know they can manually set
            // the location by right clicking on the map
            $mapHelp.text("We could not match that address to a location. You can manually set the location by right-clicking on any location on the map.");
            $mapHelp.show();
        }

    });
};

ecepAdmin.mapHelp = function() {
    $('#map-help').text("Please fill in the address of the location then click the 'Geocode Address' button to find its latitude and longitude. You can also select a location manually by right-clicking anywhere on the map.");
    $('#map-help').show();
};

google.maps.event.addDomListener(window, 'load', ecepAdmin.loadMap);
<|endoftext|>


<commit_before>let floatQueue = [];
let floatData = {};
let floatTimer;
let steamListingInfo = {};

// retrieve g_rgListingInfo from page script
window.addEventListener('message', (e) => {
    steamListingInfo = e.data.listingInfo;
});

let retrieveListingInfoFromPage = function(listingId) {
    if (listingId != null && (listingId in steamListingInfo)) {
        return Promise.resolve(steamListingInfo[listingId]);
    }

    let script = document.createElement('script');
    script.innerText = `
        window.postMessage({
            listingInfo: g_rgListingInfo
        }, '*');
    `;
    document.head.appendChild(script);

    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve((listingId != null) ? steamListingInfo[listingId] : steamListingInfo);
        }, 0);
    });
};

let getFloatData = function(listingId, inspectLink) {
    if (listingId in floatData) {
        return Promise.resolve({ iteminfo: floatData[listingId] });
    }

    return fetch(`https://api.csgofloat.com:1738/?url=${inspectLink}`)
    .then((response) => {
        if (response.ok) { return response.json(); }
        return response.json().then((err) => { throw err; });
    });
};

let showFloatText = function(listingId) {
    let floatDiv = document.querySelector(`#item_${listingId}_floatdiv`);

    if (floatDiv) {
        // Remove the "get float" button
        let floatButton = floatDiv.querySelector('.floatbutton');
        if (floatButton) { floatDiv.removeChild(floatButton); }

        let itemInfo = floatData[listingId];

        // Show the float and paint seed to the user
        let msgdiv = floatDiv.querySelector('.floatmessage');
        msgdiv.innerHTML = `Float: ${itemInfo.floatvalue}<br>Paint Seed: ${itemInfo.paintseed}`;
    }
};

let processFloatQueue = function() {
    if (floatQueue.length === 0) { return setTimeout(processFloatQueue, 500); }

    let lastItem = floatQueue.shift();

    let floatDiv = document.querySelector(`#item_${lastItem.listingId}_floatdiv`);
    let buttonText = floatDiv.querySelector('span');

    if (buttonText) { buttonText.innerText = 'Fetching'; }

    getFloatData(lastItem.listingId, lastItem.inspectLink)
    .then((data) => {
        let itemInfo = data.iteminfo;

        floatData[lastItem.listingId] = itemInfo;

        showFloatText(lastItem.listingId);

        processFloatQueue();
    })
    .catch((err) => {
        // Reset the button text for this itemid
        if (buttonText) { buttonText.innerText = 'Get Float'; }

        // Change the message div for this item to the error
        if (floatDiv) {
            floatDiv.querySelector('.floatmessage').innerHTML = err.error || 'Unknown Error';
        }

        processFloatQueue();
    });
};

// Adds the "Get all floats" button
function addAllFloatButton() {
    let parentDiv = document.createElement('div');
    parentDiv.style.padding = '10px';
    parentDiv.style.marginTop = '10px';
    parentDiv.style.backgroundColor = 'rgba(0, 0, 0, 0.2)';

    let allFloatButton = document.createElement('a');
    allFloatButton.id = 'allfloatbutton';
    allFloatButton.classList.add('btn_green_white_innerfade');
    allFloatButton.classList.add('btn_small');
    allFloatButton.addEventListener('click', GetAllFloats);
    parentDiv.appendChild(allFloatButton);

    let allFloatSpan = document.createElement('span');
    allFloatSpan.innerText = 'Get All Floats';
    allFloatButton.appendChild(allFloatSpan);

    let githubLink = document.createElement('a');
    githubLink.style.marginLeft = '10px';
    githubLink.style.textDecoration = 'underline';
    githubLink.style.fontFamily = `'Motiva Sans', sans-serif`;
    githubLink.href = 'https://github.com/Step7750/CSGOFloat';
    githubLink.innerText = 'Powered by CSGOFloat';
    parentDiv.appendChild(githubLink);

    document.querySelector('#searchResultsTable').insertBefore(parentDiv, document.querySelector('#searchResultsRows'));
}

// Puts all of the available items on the page into a queue for float retrieval
function GetAllFloats() {
    retrieveListingInfoFromPage()
    .then((steamListingData) => {
        // Get all current items on the page (in proper order)
        let listingRows = document.querySelectorAll('.market_listing_row.market_recent_listing_row');

        for (let row of listingRows) {
            let id = row.id.replace('listing_', '');

            let listingData = steamListingData[id];

            let inspectLink = listingData.asset.market_actions[0].link
            .replace('%listingid%', id)
            .replace('%assetid%', listingData.asset.id);

            floatQueue.push({ listingId: id, inspectLink: inspectLink });
        }
    });
}

let getFloatButtonClicked = function(e) {
    let row = e.currentTarget.parentElement.parentElement.parentElement;
    let id = row.id.replace('listing_', '');

    retrieveListingInfoFromPage(id)
    .then((listingData) => {
        let inspectLink = listingData.asset.market_actions[0].link
        .replace('%listingid%', id)
        .replace('%assetid%', listingData.asset.id);

        floatQueue.push({ listingId: id, inspectLink: inspectLink });
    });
};

// If an item on the current page doesn't have the float div/buttons, this function adds it
function addButtons() {
    // Iterate through each item on the page
    let listingRows = document.querySelectorAll('.market_listing_row.market_recent_listing_row');

    for (let row of listingRows) {
        let id = row.id.replace('listing_', '');

        if (row.querySelector(`#item_${id}_floatdiv`)) { continue; }

        let listingNameElement = row.querySelector(`#listing_${id}_name`);

        let buttonDiv = document.createElement('div');
        buttonDiv.style.display = 'inline';
        buttonDiv.style.textAlign = 'left';
        buttonDiv.id = `item_${id}_floatdiv`;
        listingNameElement.parentElement.appendChild(buttonDiv);

        let getFloatButton = document.createElement('a');
        getFloatButton.classList.add('btn_green_white_innerfade');
        getFloatButton.classList.add('btn_small');
        getFloatButton.classList.add('floatbutton');
        getFloatButton.addEventListener('click', getFloatButtonClicked);
        buttonDiv.appendChild(getFloatButton);

        let buttonText = document.createElement('span');
        buttonText.innerText = 'Get Float';
        getFloatButton.appendChild(buttonText);

        let messageDiv = document.createElement('div');
        messageDiv.classList.add('floatmessage');
        buttonDiv.appendChild(messageDiv);

        // check if we already have the float for this item
        if (id in floatData) {
            showFloatText(id);
        }
    }

    // Add show all button if it doesn't exist and we have valid items
    if (!document.querySelector('#allfloatbutton') && listingRows.length > 0) {
        addAllFloatButton();
    }
}

floatTimer = setInterval(() => { addButtons(); }, 500);

// start the queue processing loop
processFloatQueue();

console.log('%c CSGOFloat Market Checker (v1.0.2) by Step7750 ', 'background: #222; color: #fff;');
console.log('%c Changelog can be found here: https://github.com/Step7750/CSGOFloat ', 'background: #222; color: #fff;');
<commit_msg>Consistently define functions<commit_after>let floatQueue = [];
let floatData = {};
let floatTimer;
let steamListingInfo = {};

// retrieve g_rgListingInfo from page script
window.addEventListener('message', (e) => {
    steamListingInfo = e.data.listingInfo;
});

let retrieveListingInfoFromPage = function(listingId) {
    if (listingId != null && (listingId in steamListingInfo)) {
        return Promise.resolve(steamListingInfo[listingId]);
    }

    let script = document.createElement('script');
    script.innerText = `
        window.postMessage({
            listingInfo: g_rgListingInfo
        }, '*');
    `;
    document.head.appendChild(script);

    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve((listingId != null) ? steamListingInfo[listingId] : steamListingInfo);
        }, 0);
    });
};

let getFloatData = function(listingId, inspectLink) {
    if (listingId in floatData) {
        return Promise.resolve({ iteminfo: floatData[listingId] });
    }

    return fetch(`https://api.csgofloat.com:1738/?url=${inspectLink}`)
    .then((response) => {
        if (response.ok) { return response.json(); }
        return response.json().then((err) => { throw err; });
    });
};

let showFloatText = function(listingId) {
    let floatDiv = document.querySelector(`#item_${listingId}_floatdiv`);

    if (floatDiv) {
        // Remove the "get float" button
        let floatButton = floatDiv.querySelector('.floatbutton');
        if (floatButton) { floatDiv.removeChild(floatButton); }

        let itemInfo = floatData[listingId];

        // Show the float and paint seed to the user
        let msgdiv = floatDiv.querySelector('.floatmessage');
        msgdiv.innerHTML = `Float: ${itemInfo.floatvalue}<br>Paint Seed: ${itemInfo.paintseed}`;
    }
};

let processFloatQueue = function() {
    if (floatQueue.length === 0) { return setTimeout(processFloatQueue, 500); }

    let lastItem = floatQueue.shift();

    let floatDiv = document.querySelector(`#item_${lastItem.listingId}_floatdiv`);
    let buttonText = floatDiv.querySelector('span');

    if (buttonText) { buttonText.innerText = 'Fetching'; }

    getFloatData(lastItem.listingId, lastItem.inspectLink)
    .then((data) => {
        let itemInfo = data.iteminfo;

        floatData[lastItem.listingId] = itemInfo;

        showFloatText(lastItem.listingId);

        processFloatQueue();
    })
    .catch((err) => {
        // Reset the button text for this itemid
        if (buttonText) { buttonText.innerText = 'Get Float'; }

        // Change the message div for this item to the error
        if (floatDiv) {
            floatDiv.querySelector('.floatmessage').innerHTML = err.error || 'Unknown Error';
        }

        processFloatQueue();
    });
};

// Puts all of the available items on the page into the queue for float retrieval
let getAllFloats = function() {
    retrieveListingInfoFromPage()
    .then((steamListingData) => {
        // Get all current items on the page (in proper order)
        let listingRows = document.querySelectorAll('.market_listing_row.market_recent_listing_row');

        for (let row of listingRows) {
            let id = row.id.replace('listing_', '');

            let listingData = steamListingData[id];

            let inspectLink = listingData.asset.market_actions[0].link
            .replace('%listingid%', id)
            .replace('%assetid%', listingData.asset.id);

            floatQueue.push({ listingId: id, inspectLink: inspectLink });
        }
    });
};

// Adds the "Get all floats" button
let addAllFloatButton = function() {
    let parentDiv = document.createElement('div');
    parentDiv.style.padding = '10px';
    parentDiv.style.marginTop = '10px';
    parentDiv.style.backgroundColor = 'rgba(0, 0, 0, 0.2)';

    let allFloatButton = document.createElement('a');
    allFloatButton.id = 'allfloatbutton';
    allFloatButton.classList.add('btn_green_white_innerfade');
    allFloatButton.classList.add('btn_small');
    allFloatButton.addEventListener('click', getAllFloats);
    parentDiv.appendChild(allFloatButton);

    let allFloatSpan = document.createElement('span');
    allFloatSpan.innerText = 'Get All Floats';
    allFloatButton.appendChild(allFloatSpan);

    let githubLink = document.createElement('a');
    githubLink.style.marginLeft = '10px';
    githubLink.style.textDecoration = 'underline';
    githubLink.style.fontFamily = `'Motiva Sans', sans-serif`;
    githubLink.href = 'https://github.com/Step7750/CSGOFloat';
    githubLink.innerText = 'Powered by CSGOFloat';
    parentDiv.appendChild(githubLink);

    document.querySelector('#searchResultsTable').insertBefore(parentDiv, document.querySelector('#searchResultsRows'));
};

let getFloatButtonClicked = function(e) {
    let row = e.currentTarget.parentElement.parentElement.parentElement;
    let id = row.id.replace('listing_', '');

    retrieveListingInfoFromPage(id)
    .then((listingData) => {
        let inspectLink = listingData.asset.market_actions[0].link
        .replace('%listingid%', id)
        .replace('%assetid%', listingData.asset.id);

        floatQueue.push({ listingId: id, inspectLink: inspectLink });
    });
};

// If an item on the current page doesn't have the float div/buttons, this function adds it
let addButtons = function() {
    // Iterate through each item on the page
    let listingRows = document.querySelectorAll('.market_listing_row.market_recent_listing_row');

    for (let row of listingRows) {
        let id = row.id.replace('listing_', '');

        if (row.querySelector(`#item_${id}_floatdiv`)) { continue; }

        let listingNameElement = row.querySelector(`#listing_${id}_name`);

        let buttonDiv = document.createElement('div');
        buttonDiv.style.display = 'inline';
        buttonDiv.style.textAlign = 'left';
        buttonDiv.id = `item_${id}_floatdiv`;
        listingNameElement.parentElement.appendChild(buttonDiv);

        let getFloatButton = document.createElement('a');
        getFloatButton.classList.add('btn_green_white_innerfade');
        getFloatButton.classList.add('btn_small');
        getFloatButton.classList.add('floatbutton');
        getFloatButton.addEventListener('click', getFloatButtonClicked);
        buttonDiv.appendChild(getFloatButton);

        let buttonText = document.createElement('span');
        buttonText.innerText = 'Get Float';
        getFloatButton.appendChild(buttonText);

        let messageDiv = document.createElement('div');
        messageDiv.classList.add('floatmessage');
        buttonDiv.appendChild(messageDiv);

        // check if we already have the float for this item
        if (id in floatData) {
            showFloatText(id);
        }
    }

    // Add show all button if it doesn't exist and we have valid items
    if (!document.querySelector('#allfloatbutton') && listingRows.length > 0) {
        addAllFloatButton();
    }
};

floatTimer = setInterval(() => { addButtons(); }, 500);

// start the queue processing loop
processFloatQueue();

console.log('%c CSGOFloat Market Checker (v1.0.2) by Step7750 ', 'background: #222; color: #fff;');
console.log('%c Changelog can be found here: https://github.com/Step7750/CSGOFloat ', 'background: #222; color: #fff;');
<|endoftext|>


<commit_before>/**
 * @typedef {object} luga.router.options
 *
 * @property {string} rootPath                 Default to empty string
 * @property {function} handlerConstructor     Constructor of routeHandler class. Must implement IRouteHandler. Default to luga.router.RouteHandler
 * @property {boolean} greedy                  Set it to true to allow multiple routes matching. Default to false
 * @property {boolean} pushState               Set it to true if you want to list to window.popstate. Default to false and listen to window.hashchange instead
 */
(function(){
	"use strict";

	/**
	 * Router class
	 * @param options {luga.router.options}
	 * @constructor
	 * @extends luga.Notifier
	 * @fires routeEntered
	 * @fires routeExited
	 */
	luga.router.Router = function(options){

		var CONST = {
			ERROR_MESSAGES: {
				INVALID_ROUTE: "luga.router.Router: Invalid route passed to .add() method",
				INVALID_ADD_ARGUMENTS: "luga.router.Router: Invalid arguments passed to .add() method",
				DUPLICATE_ROUTE: "luga.router.Router: Duplicate route, path {0} already specified"
			},
			EVENTS: {
				ENTER: "routeEntered",
				EXIT: "routeExited"
			}
		};

		luga.extend(luga.Notifier, this);

		/**
		 * @type {luga.router.options}
		 */
		var config = {
			rootPath: "",
			handlerConstructor: luga.router.RouteHandler,
			greedy: false,
			pushState: false
		};

		luga.merge(config, options);

		/** @type {luga.router.Router} */
		var self = this;

		/** @type {array.<luga.router.IRouteHandler>} */
		var routeHandlers = [];

		/** @type {string|undefined} */
		var currentFragment = undefined;

		/** @type {array.<luga.router.IRouteHandler>} */
		var currentHandlers = [];

		/**
		 * Add a route. It can be invoked with two different sets of arguments:
		 * 1) A path expressed as a string, plus additional optional arguments
		 *
		 * 2) One routeHandler object:
		 * ex: Router.add({luga.router.IRouteHandler})
		 *
		 *
		 * @param {string|luga.router.IRouteHandler} path     Either a routeHandler object or a path expressed as string. Required
		 * @param {function|array.<function>} enterCallBack   Either a single callBack function or an array of functions to be invoked before entering the route. Optional
		 * @param {function|array.<function>} exitCallBack    Either a single callBack function or an array of functions to be invoked before leaving the route. Optional
		 * @param {object} payload                            A payload object to be passed to the callBacks. Optional
		 */
		this.add = function(path, enterCallBack, exitCallBack, payload){
			if(arguments.length === 1){
				/* istanbul ignore else */
				if((luga.type(arguments[0]) !== "string") && (luga.type(arguments[0]) !== "object")){
					throw(CONST.ERROR_MESSAGES.INVALID_ADD_ARGUMENTS);
				}
				/* istanbul ignore else */
				if(luga.type(arguments[0]) === "object"){
					if(luga.router.isValidRouteHandler(arguments[0]) !== true){
						throw(CONST.ERROR_MESSAGES.INVALID_ROUTE);
					}
					addHandler(arguments[0]);
				}
			}
			if((arguments.length > 1) && (luga.router.isValidRouteHandler(arguments[0]) === true)){
				throw(CONST.ERROR_MESSAGES.INVALID_ADD_ARGUMENTS);
			}
			if((arguments.length > 0) && (luga.type(arguments[0]) === "string")){
				var options = {
					path: path,
					enterCallBacks: [],
					exitCallBacks: [],
					payload: payload
				};
				if(luga.isArray(enterCallBack) === true){
					options.enterCallBacks = enterCallBack;
				}
				if(luga.type(enterCallBack) === "function"){
					options.enterCallBacks = [enterCallBack];
				}
				if(luga.isArray(exitCallBack) === true){
					options.exitCallBacks = exitCallBack;
				}
				if(luga.type(exitCallBack) === "function"){
					options.exitCallBacks = [exitCallBack];
				}
				var handler = new config.handlerConstructor(options);
				addHandler(handler);
			}
		};

		/**
		 *
		 * @param {luga.router.IRouteHandler} route
		 */
		var addHandler = function(route){
			if(self.getByPath(route.path) !== undefined){
				throw(luga.string.format(CONST.ERROR_MESSAGES.DUPLICATE_ROUTE, [route.path]));
			}
			routeHandlers.push(route);
		};

		/**
		 * Return all the available route objects
		 * @returns {array.<luga.router.IRouteHandler>}
		 */
		this.getAll = function(){
			return routeHandlers;
		};

		/**
		 * Return a registered route object associated with the given path
		 * Return undefined if none is fund
		 * @param {string} path
		 * @returns {luga.router.IRouteHandler|undefined}
		 */
		this.getByPath = function(path){
			for(var i = 0; i < routeHandlers.length; i++){
				if(routeHandlers[i].path === path){
					return routeHandlers[i];
				}
			}
		};

		/**
		 * If options.greedy is false either:
		 * 1) Return a registered routeHandler object matching the given fragment
		 * 2) Return undefined if none is fund
		 *
		 * If options.greedy is true either:
		 * 1) Return an array of matching routeHandler objects
		 * 2) Return an empty array if none is fund
		 *
		 * @param {string} fragment
		 * @returns {luga.router.IRouteHandler|undefined|array.<luga.router.IRouteHandler>}
		 */
		this.getMatch = function(fragment){
			if(config.greedy === false){
				for(var i = 0; i < routeHandlers.length; i++){
					if(routeHandlers[i].match(fragment) === true){
						return routeHandlers[i];
					}
				}
			}
			else{
				return routeHandlers.filter(function(element, index, array){
					return element.match(fragment) === true;
				});
			}
		};

		/**
		 * Remove the rootPath in front of the given string
		 * Also remove the querystring, if any
		 * @param {string} inputString
		 * @returns {string}
		 */
		this.normalizeFragment = function(inputString){
			if(inputString.indexOf("?") !== -1){
				inputString = inputString.substring(0, inputString.indexOf("?"));
			}
			var pattern = new RegExp("^\/?" + config.rootPath);
			return inputString.replace(pattern, "");
		};

		/**
		 * Remove any '#' and/or '!' in front of the given string
		 * Then remove the rootPath too
		 * @param {string} inputString
		 * @returns {string}
		 */
		this.normalizeHash = function(inputString){
			if(inputString[0] === "#"){
				inputString = inputString.substring(1);
			}
			if(inputString[0] === "!"){
				inputString = inputString.substring(1);
			}
			return self.normalizeFragment(inputString);
		};

		/**
		 * Remove the routeHandler matching the given path
		 * Fails silently if the given path does not match any routeHandler
		 * @param {string} path
		 */
		this.remove = function(path){
			var index = routeHandlers.indexOf(self.getByPath(path));
			if(index !== -1){
				routeHandlers.splice(index, 1);
			}
		};

		/**
		 * Remove all routeHandlers
		 */
		this.removeAll = function(){
			routeHandlers = [];
		};

		/**
		 * If options.greedy is false either fails silently if no match is fund or:
		 * 1) Call the exit() method of the previously matched routeHandler
		 * 2) Call the enter() method of the first registered routeHandler matching the given fragment
		 *
		 * If options.greedy is true either fails silently if no match is fund or:
		 * 1) Call the exit() method of the previously matched routeHandlers
		 * 2) Call the enter() method of all the registered routeHandlers matching the given fragment
		 *
		 * @param {string} fragment
		 * @param {object} options.state
		 * @returns {boolean} True if at least one routeHandler was resolved, false otherwise
		 */
		this.resolve = function(fragment, options){
			var matches = self.getMatch(fragment);
			if(matches === undefined){
				return false;
			}
			// Single match
			if(luga.isArray(matches) === false){
				matches = [matches];
			}
			exit(options);
			enter(matches, fragment, options);
			return matches.length > 0;
		};

		/**
		 * Overwrite the current handlers with the given ones
		 * Then execute the enter() method on each of them
		 * Finally: triggers a 'routeEntered' notification
		 * @param {array.<luga.router.IRouteHandler>} handlers
		 * @param {string} fragment
		 * @param {object} options.state
		 */
		var enter = function(handlers, fragment, options){
			currentHandlers = handlers;
			currentFragment = fragment;
			currentHandlers.forEach(function(element, i, collection){
				var context = assembleContext(element, fragment, options);
				element.enter(context);
				self.notifyObservers(CONST.EVENTS.ENTER, context);
			});
		};

		/**
		 * Execute the exit() method on all the current handlers
		 * @param {object} options.state
		 */
		var exit = function(){
			currentHandlers.forEach(function(element, i, collection){
				var context = assembleContext(element, currentFragment, options);
				element.exit(context);
				self.notifyObservers(CONST.EVENTS.EXIT, {});
			});
		};

		/**
		 * Assemble a route context
		 * @param {luga.router.IRouteHandler} handler
		 * @param {string} fragment
		 * @param {object} options
		 * @returns {luga.router.routeContext}
		 */
		var assembleContext = function(handler, fragment, options){
			/** @type {luga.router.routeContext} */
			var context = {
				fragment: fragment,
				path: handler.path,
				payload: handler.getPayload(),
				params: handler.getParams(fragment),
				historyState: undefined
			};

			luga.merge(context, options);
			return context;
		};

		/**
		 * Change current configuration
		 * @param {luga.router.options} options
		 * @returns {luga.router.options}
		 */
		this.setup = function(options){
			luga.merge(config, options);
			return config;
		};

		/**
		 * Bootstrap the Router
		 * If inside a browser, start listening to the "hashchange" and "popstate" events
		 */
		this.start = function(){
			/* istanbul ignore else */
			if(window !== undefined){
				if(config.pushState === false){
					window.addEventListener("hashchange", self.onHashChange, false);
				}
				else{
					window.addEventListener("popstate", self.onPopstate, false);
				}
			}
		};

		/**
		 * Stop the Router
		 * If inside a browser, stop listening to the "hashchange" and "popstate" events
		 */
		this.stop = function(){
			/* istanbul ignore else */
			if(window !== undefined){
				if(config.pushState === false){
					window.removeEventListener("hashchange", self.onHashChange, false);
				}
				else{
					window.removeEventListener("popstate", self.onPopstate, false);
				}
			}
		};

		/**
		 * Handle a hashchange event
		 * https://developer.mozilla.org/en-US/docs/Web/API/HashChangeEvent
		 */
		this.onHashChange = function(){
			self.resolve(self.normalizeHash(location.hash));
		};

		/**
		 * Handle a popstate event
		 * https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate
		 * @param {event} event
		 */
		this.onPopstate = function(event){
			var fragment = self.normalizeFragment(document.location.pathname);
			self.resolve(fragment, {historyState: event.state});
		};

	};

}());<commit_msg>Fixed JSHint warning<commit_after>/**
 * @typedef {object} luga.router.options
 *
 * @property {string} rootPath                 Default to empty string
 * @property {function} handlerConstructor     Constructor of routeHandler class. Must implement IRouteHandler. Default to luga.router.RouteHandler
 * @property {boolean} greedy                  Set it to true to allow multiple routes matching. Default to false
 * @property {boolean} pushState               Set it to true if you want to list to window.popstate. Default to false and listen to window.hashchange instead
 */
(function(){
	"use strict";

	/**
	 * Router class
	 * @param options {luga.router.options}
	 * @constructor
	 * @extends luga.Notifier
	 * @fires routeEntered
	 * @fires routeExited
	 */
	luga.router.Router = function(options){

		var CONST = {
			ERROR_MESSAGES: {
				INVALID_ROUTE: "luga.router.Router: Invalid route passed to .add() method",
				INVALID_ADD_ARGUMENTS: "luga.router.Router: Invalid arguments passed to .add() method",
				DUPLICATE_ROUTE: "luga.router.Router: Duplicate route, path {0} already specified"
			},
			EVENTS: {
				ENTER: "routeEntered",
				EXIT: "routeExited"
			}
		};

		luga.extend(luga.Notifier, this);

		/**
		 * @type {luga.router.options}
		 */
		var config = {
			rootPath: "",
			handlerConstructor: luga.router.RouteHandler,
			greedy: false,
			pushState: false
		};

		luga.merge(config, options);

		/** @type {luga.router.Router} */
		var self = this;

		/** @type {array.<luga.router.IRouteHandler>} */
		var routeHandlers = [];

		/** @type {string|undefined} */
		var currentFragment;

		/** @type {array.<luga.router.IRouteHandler>} */
		var currentHandlers = [];

		/**
		 * Add a route. It can be invoked with two different sets of arguments:
		 * 1) A path expressed as a string, plus additional optional arguments
		 *
		 * 2) One routeHandler object:
		 * ex: Router.add({luga.router.IRouteHandler})
		 *
		 *
		 * @param {string|luga.router.IRouteHandler} path     Either a routeHandler object or a path expressed as string. Required
		 * @param {function|array.<function>} enterCallBack   Either a single callBack function or an array of functions to be invoked before entering the route. Optional
		 * @param {function|array.<function>} exitCallBack    Either a single callBack function or an array of functions to be invoked before leaving the route. Optional
		 * @param {object} payload                            A payload object to be passed to the callBacks. Optional
		 */
		this.add = function(path, enterCallBack, exitCallBack, payload){
			if(arguments.length === 1){
				/* istanbul ignore else */
				if((luga.type(arguments[0]) !== "string") && (luga.type(arguments[0]) !== "object")){
					throw(CONST.ERROR_MESSAGES.INVALID_ADD_ARGUMENTS);
				}
				/* istanbul ignore else */
				if(luga.type(arguments[0]) === "object"){
					if(luga.router.isValidRouteHandler(arguments[0]) !== true){
						throw(CONST.ERROR_MESSAGES.INVALID_ROUTE);
					}
					addHandler(arguments[0]);
				}
			}
			if((arguments.length > 1) && (luga.router.isValidRouteHandler(arguments[0]) === true)){
				throw(CONST.ERROR_MESSAGES.INVALID_ADD_ARGUMENTS);
			}
			if((arguments.length > 0) && (luga.type(arguments[0]) === "string")){
				var options = {
					path: path,
					enterCallBacks: [],
					exitCallBacks: [],
					payload: payload
				};
				if(luga.isArray(enterCallBack) === true){
					options.enterCallBacks = enterCallBack;
				}
				if(luga.type(enterCallBack) === "function"){
					options.enterCallBacks = [enterCallBack];
				}
				if(luga.isArray(exitCallBack) === true){
					options.exitCallBacks = exitCallBack;
				}
				if(luga.type(exitCallBack) === "function"){
					options.exitCallBacks = [exitCallBack];
				}
				var handler = new config.handlerConstructor(options);
				addHandler(handler);
			}
		};

		/**
		 *
		 * @param {luga.router.IRouteHandler} route
		 */
		var addHandler = function(route){
			if(self.getByPath(route.path) !== undefined){
				throw(luga.string.format(CONST.ERROR_MESSAGES.DUPLICATE_ROUTE, [route.path]));
			}
			routeHandlers.push(route);
		};

		/**
		 * Return all the available route objects
		 * @returns {array.<luga.router.IRouteHandler>}
		 */
		this.getAll = function(){
			return routeHandlers;
		};

		/**
		 * Return a registered route object associated with the given path
		 * Return undefined if none is fund
		 * @param {string} path
		 * @returns {luga.router.IRouteHandler|undefined}
		 */
		this.getByPath = function(path){
			for(var i = 0; i < routeHandlers.length; i++){
				if(routeHandlers[i].path === path){
					return routeHandlers[i];
				}
			}
		};

		/**
		 * If options.greedy is false either:
		 * 1) Return a registered routeHandler object matching the given fragment
		 * 2) Return undefined if none is fund
		 *
		 * If options.greedy is true either:
		 * 1) Return an array of matching routeHandler objects
		 * 2) Return an empty array if none is fund
		 *
		 * @param {string} fragment
		 * @returns {luga.router.IRouteHandler|undefined|array.<luga.router.IRouteHandler>}
		 */
		this.getMatch = function(fragment){
			if(config.greedy === false){
				for(var i = 0; i < routeHandlers.length; i++){
					if(routeHandlers[i].match(fragment) === true){
						return routeHandlers[i];
					}
				}
			}
			else{
				return routeHandlers.filter(function(element, index, array){
					return element.match(fragment) === true;
				});
			}
		};

		/**
		 * Remove the rootPath in front of the given string
		 * Also remove the querystring, if any
		 * @param {string} inputString
		 * @returns {string}
		 */
		this.normalizeFragment = function(inputString){
			if(inputString.indexOf("?") !== -1){
				inputString = inputString.substring(0, inputString.indexOf("?"));
			}
			var pattern = new RegExp("^\/?" + config.rootPath);
			return inputString.replace(pattern, "");
		};

		/**
		 * Remove any '#' and/or '!' in front of the given string
		 * Then remove the rootPath too
		 * @param {string} inputString
		 * @returns {string}
		 */
		this.normalizeHash = function(inputString){
			if(inputString[0] === "#"){
				inputString = inputString.substring(1);
			}
			if(inputString[0] === "!"){
				inputString = inputString.substring(1);
			}
			return self.normalizeFragment(inputString);
		};

		/**
		 * Remove the routeHandler matching the given path
		 * Fails silently if the given path does not match any routeHandler
		 * @param {string} path
		 */
		this.remove = function(path){
			var index = routeHandlers.indexOf(self.getByPath(path));
			if(index !== -1){
				routeHandlers.splice(index, 1);
			}
		};

		/**
		 * Remove all routeHandlers
		 */
		this.removeAll = function(){
			routeHandlers = [];
		};

		/**
		 * If options.greedy is false either fails silently if no match is fund or:
		 * 1) Call the exit() method of the previously matched routeHandler
		 * 2) Call the enter() method of the first registered routeHandler matching the given fragment
		 *
		 * If options.greedy is true either fails silently if no match is fund or:
		 * 1) Call the exit() method of the previously matched routeHandlers
		 * 2) Call the enter() method of all the registered routeHandlers matching the given fragment
		 *
		 * @param {string} fragment
		 * @param {object} options.state
		 * @returns {boolean} True if at least one routeHandler was resolved, false otherwise
		 */
		this.resolve = function(fragment, options){
			var matches = self.getMatch(fragment);
			if(matches === undefined){
				return false;
			}
			// Single match
			if(luga.isArray(matches) === false){
				matches = [matches];
			}
			exit(options);
			enter(matches, fragment, options);
			return matches.length > 0;
		};

		/**
		 * Overwrite the current handlers with the given ones
		 * Then execute the enter() method on each of them
		 * Finally: triggers a 'routeEntered' notification
		 * @param {array.<luga.router.IRouteHandler>} handlers
		 * @param {string} fragment
		 * @param {object} options.state
		 */
		var enter = function(handlers, fragment, options){
			currentHandlers = handlers;
			currentFragment = fragment;
			currentHandlers.forEach(function(element, i, collection){
				var context = assembleContext(element, fragment, options);
				element.enter(context);
				self.notifyObservers(CONST.EVENTS.ENTER, context);
			});
		};

		/**
		 * Execute the exit() method on all the current handlers
		 * @param {object} options.state
		 */
		var exit = function(){
			currentHandlers.forEach(function(element, i, collection){
				var context = assembleContext(element, currentFragment, options);
				element.exit(context);
				self.notifyObservers(CONST.EVENTS.EXIT, {});
			});
		};

		/**
		 * Assemble a route context
		 * @param {luga.router.IRouteHandler} handler
		 * @param {string} fragment
		 * @param {object} options
		 * @returns {luga.router.routeContext}
		 */
		var assembleContext = function(handler, fragment, options){
			/** @type {luga.router.routeContext} */
			var context = {
				fragment: fragment,
				path: handler.path,
				payload: handler.getPayload(),
				params: handler.getParams(fragment),
				historyState: undefined
			};

			luga.merge(context, options);
			return context;
		};

		/**
		 * Change current configuration
		 * @param {luga.router.options} options
		 * @returns {luga.router.options}
		 */
		this.setup = function(options){
			luga.merge(config, options);
			return config;
		};

		/**
		 * Bootstrap the Router
		 * If inside a browser, start listening to the "hashchange" and "popstate" events
		 */
		this.start = function(){
			/* istanbul ignore else */
			if(window !== undefined){
				if(config.pushState === false){
					window.addEventListener("hashchange", self.onHashChange, false);
				}
				else{
					window.addEventListener("popstate", self.onPopstate, false);
				}
			}
		};

		/**
		 * Stop the Router
		 * If inside a browser, stop listening to the "hashchange" and "popstate" events
		 */
		this.stop = function(){
			/* istanbul ignore else */
			if(window !== undefined){
				if(config.pushState === false){
					window.removeEventListener("hashchange", self.onHashChange, false);
				}
				else{
					window.removeEventListener("popstate", self.onPopstate, false);
				}
			}
		};

		/**
		 * Handle a hashchange event
		 * https://developer.mozilla.org/en-US/docs/Web/API/HashChangeEvent
		 */
		this.onHashChange = function(){
			self.resolve(self.normalizeHash(location.hash));
		};

		/**
		 * Handle a popstate event
		 * https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate
		 * @param {event} event
		 */
		this.onPopstate = function(event){
			var fragment = self.normalizeFragment(document.location.pathname);
			self.resolve(fragment, {historyState: event.state});
		};

	};

}());<|endoftext|>


<commit_before>/**
 * Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
 * All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var linePlot;

$(document).ready(function() {

    $("#lineplot-canvas-id").hide();

    $("#text-input-type-rb").prop("checked", true);

    $("input[name='text']").change(function() {
        $("#speech-input-type-rb").prop("checked", false);
    });

    $("input[name='speech']").change(function() {
        $("#text-input-type-rb").prop("checked", false);
    });

    $("#start-button").click(function() {
        if ($("#text-input-type-rb").is(':checked')) {
            sendPost($("#question-input-id").val());
        } else if ($("#speech-input-type-rb").is(':checked')) {
            runSpeechToText();
        }
    });

});

function sendPost(question) {

    $("#lineplot-canvas-id").hide();

    $.ajax({
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        type: "POST",
        url: "api/request",
        data: JSON.stringify({
            "text": question
        }),
        dataType: 'json',
        success: function(response) {

            $('#question-input-id').val(question);

            if (response.type == "error") {

                $('#answer-output-id').val(response.error.message);

                if ($("#speech-input-type-rb").is(':checked')) {
                    var msg = new SpeechSynthesisUtterance(response.error.message);
                    msg.lang = 'en-US';
                    window.speechSynthesis.speak(msg);
                }

            } else {

                $('#answer-output-id').val(response.text);

                if ($("#speech-input-type-rb").is(':checked')) {
                    var msg = new SpeechSynthesisUtterance(response.text);
                    msg.lang = 'en-US';
                    window.speechSynthesis.speak(msg);
                }

                if (response.type == "json") {
                    payloadObj = (JSON.parse(response.payload));
                    if (payloadObj.plotType == "lineplot") {
                        plotLineplot(payloadObj);
                    }
                }

            }

        },
        error: function(e) {

        }
    });
}

function plotLineplot(payloadObj) {

    if (linePlot != null) {
        linePlot.destroy();
    }

    dataObject = JSON.parse(payloadObj.data);

    datasetsObjectFormatted = [];

    //create color array to rotate through
    rgbColorFormatter = ["rgba(0,225,204,0.3)",
        "rgba(153,194,255,0.3)",
        "rgba(51,133,255,0.3)",
        "rgba(128,255,170,0.3)",
        "rgba(0,38,153,0.3)",
        "rgba(0,102,0,0.3)",
        "rgba(255,0,0,0.2)",
        "rgba(255,51,204,0.3)",
        "rgba(255,136,77,0.3)",
        "rgba(153, 51, 255,0.2)"
    ];

    counter = 0;
    for (var key in dataObject) {

        if (dataObject.hasOwnProperty(key)) {

            datasetsObjectFormatted.push({
                label: key,
                fillColor: rgbColorFormatter[counter % 10],
                strokeColor: rgbColorFormatter[counter % 10],
                pointColor: rgbColorFormatter[counter % 10],
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: rgbColorFormatter[counter % 10],
                data: dataObject[key]
            });

        }

        counter++;
    }

    var labels = [];
    if (payloadObj.labels == null) {
        for (var i = 0; i < JSON.parse(payloadObj.data).length; i++) {
            labels.push("");
        }
    } else {
        labels = JSON.parse(payloadObj.labels);
    }

    $("#lineplot-canvas-title-id").html(payloadObj.title);
    $("#xaxis-lineplot-canvas-id").html(payloadObj.xaxis);
    $("#yaxis-lineplot-canvas-id").html(payloadObj.yaxis);

    var lineChartData = {
        labels: labels,
        datasets: datasetsObjectFormatted
    }

    $("#lineplot-canvas-id").show();

    var ctx = document.getElementById("lineplot-canvas-graph-id").getContext("2d");
    linePlot = new Chart(ctx).Line(lineChartData, {
        responsive: true,
        onAnimationComplete: lineplotDoneDrawing
    });

    function lineplotDoneDrawing() {
        $("#export-canvas-button").html("<button type=\"button\" class=\"pull-right btn btn-default\" id=\"export-canvas-button\">Export</button>");
    }
}<commit_msg>Added comments regarding color array<commit_after>/**
 * Copyright 2016 The Johns Hopkins University Applied Physics Laboratory LLC
 * All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var linePlot;

$(document).ready(function() {

    $("#lineplot-canvas-id").hide();

    $("#text-input-type-rb").prop("checked", true);

    $("input[name='text']").change(function() {
        $("#speech-input-type-rb").prop("checked", false);
    });

    $("input[name='speech']").change(function() {
        $("#text-input-type-rb").prop("checked", false);
    });

    $("#start-button").click(function() {
        if ($("#text-input-type-rb").is(':checked')) {
            sendPost($("#question-input-id").val());
        } else if ($("#speech-input-type-rb").is(':checked')) {
            runSpeechToText();
        }
    });

});

function sendPost(question) {

    $("#lineplot-canvas-id").hide();

    $.ajax({
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        type: "POST",
        url: "api/request",
        data: JSON.stringify({
            "text": question
        }),
        dataType: 'json',
        success: function(response) {

            $('#question-input-id').val(question);

            if (response.type == "error") {

                $('#answer-output-id').val(response.error.message);

                if ($("#speech-input-type-rb").is(':checked')) {
                    var msg = new SpeechSynthesisUtterance(response.error.message);
                    msg.lang = 'en-US';
                    window.speechSynthesis.speak(msg);
                }

            } else {

                $('#answer-output-id').val(response.text);

                if ($("#speech-input-type-rb").is(':checked')) {
                    var msg = new SpeechSynthesisUtterance(response.text);
                    msg.lang = 'en-US';
                    window.speechSynthesis.speak(msg);
                }

                if (response.type == "json") {
                    payloadObj = (JSON.parse(response.payload));
                    if (payloadObj.plotType == "lineplot") {
                        plotLineplot(payloadObj);
                    }
                }

            }

        },
        error: function(e) {

        }
    });
}

function plotLineplot(payloadObj) {

    if (linePlot != null) {
        linePlot.destroy();
    }

    dataObject = JSON.parse(payloadObj.data);

    datasetsObjectFormatted = [];

    //create color array to rotate through (color of line in line plot)
    rgbColorFormatter = ["rgba(0,225,204,0.3)", //teal
        "rgba(153,194,255,0.3)", //light blue
        "rgba(51,133,255,0.3)", //royal blue
        "rgba(128,255,170,0.3)", //light green
        "rgba(0,38,153,0.3)", //dark blue
        "rgba(0,102,0,0.3)", //dark green
        "rgba(255,0,0,0.2)", //red
        "rgba(255,51,204,0.3)", //pink
        "rgba(255,136,77,0.3)", //orange
        "rgba(153, 51, 255,0.2)" //purple
    ];

    counter = 0;
    for (var key in dataObject) {

        if (dataObject.hasOwnProperty(key)) {

            datasetsObjectFormatted.push({
                label: key,
                fillColor: rgbColorFormatter[counter % 10],
                strokeColor: rgbColorFormatter[counter % 10],
                pointColor: rgbColorFormatter[counter % 10],
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: rgbColorFormatter[counter % 10],
                data: dataObject[key]
            });

        }

        counter++;
    }

    var labels = [];
    if (payloadObj.labels == null) {
        for (var i = 0; i < JSON.parse(payloadObj.data).length; i++) {
            labels.push("");
        }
    } else {
        labels = JSON.parse(payloadObj.labels);
    }

    $("#lineplot-canvas-title-id").html(payloadObj.title);
    $("#xaxis-lineplot-canvas-id").html(payloadObj.xaxis);
    $("#yaxis-lineplot-canvas-id").html(payloadObj.yaxis);

    var lineChartData = {
        labels: labels,
        datasets: datasetsObjectFormatted
    }

    $("#lineplot-canvas-id").show();

    var ctx = document.getElementById("lineplot-canvas-graph-id").getContext("2d");
    linePlot = new Chart(ctx).Line(lineChartData, {
        responsive: true,
        onAnimationComplete: lineplotDoneDrawing
    });

    function lineplotDoneDrawing() {
        $("#export-canvas-button").html("<button type=\"button\" class=\"pull-right btn btn-default\" id=\"export-canvas-button\">Export</button>");
    }
}<|endoftext|>


<commit_before>#!/usr/bin/env node
var path = require('path');

var express = require('express');

var config = require('./config');

main();

function main() {
    var app = express();

    var apiPrefix = 'v1';
    var halfDay = 43200000;

    var port = config.port;

    app.configure(function() {
        app.set('port', port);

        app.use(express.favicon('public/images/favicon.ico'));
        app.use(express.logger('dev'));
        app.use(express.compress());
        app.use(express['static'](path.join(__dirname, 'public'), {
            maxAge: halfDay
        }));

        app.use(app.router);
    });

    app.configure('development', function() {
        app.use(express.errorHandler());
    });

    app.listen(port, function() {
        console.log('%s: Node (version: %s) %s started on %d ...', Date(Date.now() ), process.version, process.argv[1], port);
    });

    var api = require('./api');
    var routes = require('./routes');

    app.get('/', routes('index'));
    app.get('/about', routes('about'));
    app.get('/resources', routes('resources'));
    app.get('/resources/how-cdns-work', routes('howCdnsWork'));
    app.get('/resources/how-to-use-cdns', routes('howToUseCdns'));
    app.get('/api', routes('api'));

    app.get('/api/' + apiPrefix + '/cdns', api.cdns.getNames);
    app.get('/api/' + apiPrefix + '/cdns/:name', api.cdns.get);

    require('taskist')(config.tasks, require('./tasks'), {
        instant: function(err) {
            if(err) {
                return console.error(err);
            }

            console.log('Tasks initialized!');

            api.cdns.updateData(require('./public/data'));
        }
    });

    process.on('exit', terminator);

    ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT', 'SIGBUS',
    'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGPIPE', 'SIGTERM'
    ].forEach(function(element) {
        process.on(element, function() { terminator(element); });
    });
}

function terminator(sig) {
    if(typeof sig === 'string') {
        console.log('%s: Received %s - terminating Node server ...',
            Date(Date.now()), sig);

        process.exit(1);
    }

    console.log('%s: Node server stopped.', Date(Date.now()) );
}
<commit_msg>Make `app.listen` even lighter<commit_after>#!/usr/bin/env node
var path = require('path');

var express = require('express');

var config = require('./config');

main();

function main() {
    var port = config.port;

    var app = express();

    app.configure(function() {
        var halfDay = 43200000;

        app.set('port', port);

        app.use(express.favicon('public/images/favicon.ico'));
        app.use(express.logger('dev'));
        app.use(express.compress());
        app.use(express['static'](path.join(__dirname, 'public'), {
            maxAge: halfDay
        }));

        app.use(app.router);
    });

    app.configure('development', function() {
        app.use(express.errorHandler());
    });

    app.listen(port, function() {
        console.log('%s: Node (version: %s) %s started on %d ...', Date(Date.now() ), process.version, process.argv[1], port);

        init(app);
    });
}

function init(app) {
    var apiPrefix = 'v1';

    var api = require('./api');
    var routes = require('./routes');

    app.get('/', routes('index'));
    app.get('/about', routes('about'));
    app.get('/resources', routes('resources'));
    app.get('/resources/how-cdns-work', routes('howCdnsWork'));
    app.get('/resources/how-to-use-cdns', routes('howToUseCdns'));
    app.get('/api', routes('api'));

    app.get('/api/' + apiPrefix + '/cdns', api.cdns.getNames);
    app.get('/api/' + apiPrefix + '/cdns/:name', api.cdns.get);

    require('taskist')(config.tasks, require('./tasks'), {
        instant: function(err) {
            if(err) {
                return console.error(err);
            }

            console.log('Tasks initialized!');

            api.cdns.updateData(require('./public/data'));
        }
    });

    process.on('exit', terminator);

    ['SIGHUP', 'SIGINT', 'SIGQUIT', 'SIGILL', 'SIGTRAP', 'SIGABRT', 'SIGBUS',
    'SIGFPE', 'SIGUSR1', 'SIGSEGV', 'SIGUSR2', 'SIGPIPE', 'SIGTERM'
    ].forEach(function(element) {
        process.on(element, function() { terminator(element); });
    });
}

function terminator(sig) {
    if(typeof sig === 'string') {
        console.log('%s: Received %s - terminating Node server ...',
            Date(Date.now()), sig);

        process.exit(1);
    }

    console.log('%s: Node server stopped.', Date(Date.now()) );
}
<|endoftext|>


<commit_before>/*
 * biojs-io-biom
 * https://github.com/iimog/biojs-io-biom
 *
 * Copyright (c) 2016 Markus J. Ankenbrand
 * Licensed under the MIT license.
 */

/**
 * Version
 * @type {string} version of this module
 */
export const VERSION = '0.1.0';

/**
 * Default Biom Object for empty initialization
 * @type {{
 * id: null,
 * format: string,
 * format_url: string,
 * type: string,
 * generated_by: string,
 * date: Date,
 * rows: Array,
 * columns: Array,
 * matrix_type: string,
 * matrix_element_type: string,
 * shape: number[],
 * data: Array
 * }}
 */
export const DEFAULT_BIOM = {
    id: null,
    format: 'Biological Observation Matrix 1.0.0',
    format_url: 'http://biom-format.org',
    type: 'OTU table',
    generated_by: `biojs-io-biom v${VERSION}`,
    date: null, // will be set to Date.now() in the constructor
    rows: [],
    columns: [],
    matrix_type: 'sparse',
    matrix_element_type: 'float',
    shape: [0,0],
    data: []
};

/**
 * @class Biom
 */
export class Biom {
    /**
     * constructor
     * @param _id
     * @param _format
     * @param _format_url
     * @param _type
     * @param _generated_by
     * @param _date
     * @param _rows
     * @param _columns
     * @param _matrix_type
     * @param _matrix_element_type
     * @param _shape
     * @param _data
     */
    constructor({
        id: _id = null,
        format: _format = DEFAULT_BIOM.format,
        format_url: _format_url = DEFAULT_BIOM.format_url,
        type: _type = DEFAULT_BIOM.type,
        generated_by: _generated_by = DEFAULT_BIOM.generated_by,
        date: _date = Date.now(),
        rows: _rows = DEFAULT_BIOM.rows,
        columns: _columns = DEFAULT_BIOM.columns,
        matrix_type: _matrix_type = DEFAULT_BIOM.matrix_type,
        matrix_element_type:
            _matrix_element_type = DEFAULT_BIOM.matrix_element_type,
        shape: _shape = DEFAULT_BIOM.shape,
        data: _data = DEFAULT_BIOM.data
    } = {}){
        this._id = _id;
        this._format = _format;
        this._format_url = _format_url;
        this._type = _type;
        this._generated_by = _generated_by;
        this._date = _date;
        this._rows = _rows;
        this._columns = _columns;
        this._matrix_type = _matrix_type;
        this._matrix_element_type = _matrix_element_type;
        this._shape = _shape;
        this._data = _data;
    }

    /**
     * Getter for id
     * @returns {string} - a field that can be used to id a table (or null)
     */
    get id(){
        return this._id;
    }

    get format(){
        return this._format;
    }

    get format_url(){
        return this._format_url;
    }

    get type(){
        return this._type;
    }

    get generated_by(){
        return this._generated_by;
    }

    get date(){
        return this._date;
    }

    get rows(){
        return this._rows;
    }

    get columns(){
        return this._columns;
    }

    get matrix_type(){
        return this._matrix_type;
    }

    get matrix_element_type(){
        return this._matrix_element_type;
    }

    get shape(){
        return this._shape;
    }

    get data(){
        return this._data;
    }
}
<commit_msg>Add doc strings for getter<commit_after>/*
 * biojs-io-biom
 * https://github.com/iimog/biojs-io-biom
 *
 * Copyright (c) 2016 Markus J. Ankenbrand
 * Licensed under the MIT license.
 */

/**
 * Version
 * @type {string} version of this module
 */
export const VERSION = '0.1.0';

/**
 * Default Biom Object for empty initialization
 * @type {{
 * id: null,
 * format: string,
 * format_url: string,
 * type: string,
 * generated_by: string,
 * date: Date,
 * rows: Array,
 * columns: Array,
 * matrix_type: string,
 * matrix_element_type: string,
 * shape: number[],
 * data: Array
 * }}
 */
export const DEFAULT_BIOM = {
    id: null,
    format: 'Biological Observation Matrix 1.0.0',
    format_url: 'http://biom-format.org',
    type: 'OTU table',
    generated_by: `biojs-io-biom v${VERSION}`,
    date: null, // will be set to Date.now() in the constructor
    rows: [],
    columns: [],
    matrix_type: 'sparse',
    matrix_element_type: 'float',
    shape: [0,0],
    data: []
};

/**
 * @class Biom
 */
export class Biom {
    /**
     * constructor
     * @param _id
     * @param _format
     * @param _format_url
     * @param _type
     * @param _generated_by
     * @param _date
     * @param _rows
     * @param _columns
     * @param _matrix_type
     * @param _matrix_element_type
     * @param _shape
     * @param _data
     */
    constructor({
        id: _id = null,
        format: _format = DEFAULT_BIOM.format,
        format_url: _format_url = DEFAULT_BIOM.format_url,
        type: _type = DEFAULT_BIOM.type,
        generated_by: _generated_by = DEFAULT_BIOM.generated_by,
        date: _date = Date.now(),
        rows: _rows = DEFAULT_BIOM.rows,
        columns: _columns = DEFAULT_BIOM.columns,
        matrix_type: _matrix_type = DEFAULT_BIOM.matrix_type,
        matrix_element_type:
            _matrix_element_type = DEFAULT_BIOM.matrix_element_type,
        shape: _shape = DEFAULT_BIOM.shape,
        data: _data = DEFAULT_BIOM.data
    } = {}){
        this._id = _id;
        this._format = _format;
        this._format_url = _format_url;
        this._type = _type;
        this._generated_by = _generated_by;
        this._date = _date;
        this._rows = _rows;
        this._columns = _columns;
        this._matrix_type = _matrix_type;
        this._matrix_element_type = _matrix_element_type;
        this._shape = _shape;
        this._data = _data;
    }

    /**
     * Getter for id
     * @returns {string} - A field that can be used to id a table (or null)
     */
    get id(){
        return this._id;
    }

    /**
     * Getter for format
     * @returns {string} - The name and version of the current biom format
     */
    get format(){
        return this._format;
    }

    /**
     * Getter for format_url
     * @returns {string} - A string with a static URL providing format details
     */
    get format_url(){
        return this._format_url;
    }

    /**
     * Getter for type
     * @returns {string} - Table type (a controlled vocabulary)
     *                     Acceptable values:
     *                       "OTU table"
     *                       "Pathway table"
     *                       "Function table"
     *                       "Ortholog table"
     *                       "Gene table"
     *                       "Metabolite table"
     *                       "Taxon table"
     */
    get type(){
        return this._type;
    }

    /**
     * Getter for generated_by
     * @returns {string} - Package and revision that built the table
     */
    get generated_by(){
        return this._generated_by;
    }

    /**
     * Getter for date
     * @returns {Date} - Date the table was built (ISO 8601 format)
     */
    get date(){
        return this._date;
    }

    /**
     * Getter for rows
     * @returns {Array} - An ORDERED list of obj describing the rows
     */
    get rows(){
        return this._rows;
    }

    /**
     * Getter for columns
     * @returns {Array} - An ORDERED list of obj describing the columns
     */
    get columns(){
        return this._columns;
    }

    /**
     * Getter for matrix_type
     * @returns {string} - Type of matrix data representation
     *                     (a controlled vocabulary) Acceptable values:
     *                       "sparse" : only non-zero values are specified
     *                       "dense" : every element must be specified
     */
    get matrix_type(){
        return this._matrix_type;
    }

    /**
     * Getter for matrix_element_type
     * @returns {string} - Value type in matrix (a controlled vocabulary)
     *                     Acceptable values:
     *                       "int" : integer
     *                       "float" : floating point
     *                       "unicode" : unicode string
     */
    get matrix_element_type(){
        return this._matrix_element_type;
    }

    /**
     * Getter for shape
     * @returns {Array} - the number of rows and number of columns in data
     */
    get shape(){
        return this._shape;
    }

    /**
     * Getter for data
     * @returns {Array} - counts of observations by sample
     *                   if matrix_type is "sparse", [[row, column, value],
     *                                                 [row, column, value],
     *                                                                  ...]
     *                   if matrix_type is "dense", [[value, value, value, ...],
     *                                               [value, value, value, ...],
     *                                                                      ...]
     */
    get data(){
        return this._data;
    }
}
<|endoftext|>


<commit_before>import "./examen.html";
import {Selecciones} from "../../api/seleccion.js";
import {Verdaderos} from "../../api/verdadero.js";
import {Estudiantes} from "../../api/estudiante.js";

//import {Random} from 'meteor/'

Template.examen.onCreated(function(){
    this.posSeleccion = 0;
    this.posVerdadero = 0;
    this.answersSeleccion1 = 0;
    this.answersSeleccion2 = 0;
    this.answersSeleccion3 = 0;
    this.answersSeleccion4 = 0;
    this.answersSeleccion5 = 0;
   // seleccionEscogida = [0,0,0,0,0,0,0,0,0,0];
    //verdaderoEscogido = [0,0,0,0,0,0,0,0,0,0];
    this.answersVerdaderos1 = 0;
    this.answersVerdaderos2 = 0;
    this.answersVerdaderos3 = 0;
    this.answersVerdaderos4 = 0;
    this.answersVerdaderos5 = 0;
    this.notaFinal = 0;
    Meteor.subscribe("Verdaderos");
    Meteor.subscribe("Selecciones");
    Meteor.subscribe("Estudiantes");

});

Template.examen.helpers({
    /*
    verdaderos:function(){
        return Verdaderos.find({});
    },
    selecciones:function(){
        return Selecciones.find({});
    },
    */
    /*
    sizeVerdaderos:function(){
        return Verdaderos.count();
    },
    sizeSelecciones:function(){
        return Selecciones.count();
    },
    */
    grade:function(){
        return Template.instance().notaFinal;
    },

    preguntaSeleccion1: function(){
        var random = Math.floor( Math.random() * (Selecciones.find({}).count()+2));
        try {
            var Doc = Selecciones.find().fetch()[random];
            Template.instance().answersSeleccion1=Doc.respuesta;
            console.log(Doc.respuesta);
        } catch (TypeError) {

        }

        return Selecciones.find({index:random});
    },
    preguntaSeleccion2: function(){
        var random = Math.floor( Math.random() * (Selecciones.find({}).count()+2));
        try {
            var Doc = Selecciones.find().fetch()[random];
            Template.instance().answersSeleccion2=Doc.respuesta;
            console.log(Doc.respuesta);
        } catch (TypeError) {

        }

        return Selecciones.find({index:random});
    },
    preguntaSeleccion3: function(){
        var random = Math.floor( Math.random() * (Selecciones.find({}).count()+2));
        try {
            var Doc = Selecciones.find().fetch()[random];
            Template.instance().answersSeleccion3=Doc.respuesta;
            console.log(Doc.respuesta);
        } catch (TypeError) {

        }

        return Selecciones.find({index:random});
    },
    preguntaSeleccion4: function(){
        var random = Math.floor( Math.random() * (Selecciones.find({}).count()+2));
        try {
            var Doc = Selecciones.find().fetch()[random];
            Template.instance().answersSeleccion4=Doc.respuesta;
            console.log(Doc.respuesta);
        } catch (TypeError) {

        }

        return Selecciones.find({index:random});
    },
    preguntaSeleccion5: function(){
        var random = Math.floor( Math.random() * (Selecciones.find({}).count()+2));
        try {
            var Doc = Selecciones.find().fetch()[random];
            Template.instance().answersSeleccion5=Doc.respuesta;
            console.log(Doc.respuesta);
        } catch (TypeError) {

        }

        return Selecciones.find({index:random});
    },

    preguntaVerdadero1: function(){
        var random = Math.floor( Math.random() * (Verdaderos.find({}).count()+2));
        try {
            var Doc = Verdaderos.find().fetch()[random];
            Template.instance().answersVerdaderos1 = Doc.respuesta;

        } catch (TypeError) {

        }
        return Verdaderos.find({index:random});
    },
    preguntaVerdadero2: function(){
        var random = Math.floor( Math.random() * (Verdaderos.find({}).count()+2));
        try {
            var Doc = Verdaderos.find().fetch()[random];
            Template.instance().answersVerdaderos2 = Doc.respuesta;
        } catch (TypeError) {

        }
        return Verdaderos.find({index:random});
    },
    preguntaVerdadero3: function(){
        var random = Math.floor( Math.random() * (Verdaderos.find({}).count()+2));
        try {
            var Doc = Verdaderos.find().fetch()[random];
            Template.instance().answersVerdaderos3 = Doc.respuesta;
        } catch (TypeError) {

        }
        return Verdaderos.find({index:random});
    },
    preguntaVerdadero4: function(){
        var random = Math.floor( Math.random() * (Verdaderos.find({}).count()+2));
        try {
            var Doc = Verdaderos.find().fetch()[random];
            Template.instance().answersVerdaderos4 = Doc.respuesta;
        } catch (TypeError) {

        }
        return Verdaderos.find({index:random});
    },
    preguntaVerdadero5: function(){
        var random = Math.floor( Math.random() * (Verdaderos.find({}).count()+2));
        try {
            var Doc = Verdaderos.find().fetch()[random];
            Template.instance().answersVerdaderos5 = Doc.respuesta;
        } catch (TypeError) {

        }
        return Verdaderos.find({index:random});
    }

    /*,

    opcion:function(numPregunta,numOpcion){
        var realSelectionIndex = Template.instance().seleccionEscogida[numPregunta];
        //var realSelection = Selecciones.findOne({index:realSelectionIndex});
        if(numOpcion === 1){
            return Selecciones.findOne({index:realSelectionIndex}).opcion1;
        }else if (numOpcion ===2 ){
            return Selecciones.findOne({index:realSelectionIndex}).opcion2;
        }else if(numOpcion ===3 ){
            return Selecciones.findOne({index:realSelectionIndex}).opcion3;
        }else if(numOpcion ===4 ){
            return Selecciones.findOne({index:realSelectionIndex}).opcion4;
        }
    }
    */
});

Template.examen.events({
    'click #finalizar'(event){
        var a1 =$('input:radio[name="group1"]:checked').val();
        var a2 =$('input:radio[name="group2"]:checked').val();
        var a3 =$('input:radio[name="group3"]:checked').val();
        var a4 =$('input:radio[name="group4"]:checked').val();
        var a5 =$('input:radio[name="group5"]:checked').val();
        var a6 =$('input:radio[name="group6"]:checked').val();
        var a7 =$('input:radio[name="group7"]:checked').val();
        var a8 =$('input:radio[name="group8"]:checked').val();
        var a9 =$('input:radio[name="group9"]:checked').val();
        var a10 =$('input:radio[name="group10"]:checked').val();

        alert("nota actual" + Template.instance().notaFinal);
        var grades = 0;

        if( parseInt(a1) == Template.instance().answersSeleccion1 ){
            grades = grades + 1;

        }
        if(parseInt(a2) == Template.instance().answersSeleccion2 ){
            grades = grades + 1;

        }
        if(parseInt(a3) == Template.instance().answersSeleccion3 ){
            grades = grades + 1;

        }
        if(parseInt(a4) == Template.instance().answersSeleccion4 ){
            grades = grades + 1;

        }
        if(parseInt(a5) == Template.instance().answersSeleccion5 ){
            grades = grades + 1;

        }
        if(parseInt(a6) == Template.instance().answersVerdaderos1 ){
            grades = grades + 1;

        }
        if(parseInt(a7) == Template.instance().answersVerdaderos2 ){
            grades = grades + 1;

        }
        if(parseInt(a8) == Template.instance().answersVerdaderos3 ){
            grades = grades + 1;

        }
        if(parseInt(a9) == Template.instance().answersVerdaderos4 ){
            grades = grades + 1;

        }
        if(parseInt(a10) == Template.instance().answersVerdaderos5 ){
            grades = grades + 1;

        }
        alert("NOTA"+grades);
        var nombre = $('nombreEstudiante').val();

        Meteor.call("insertEstudiante", {nombre,grades},function(err,res){
            if(err){
                console.log(err);
            }
        });
    }

});

<commit_msg>fixing random range<commit_after>import "./examen.html";
import {Selecciones} from "../../api/seleccion.js";
import {Verdaderos} from "../../api/verdadero.js";
import {Estudiantes} from "../../api/estudiante.js";

//import {Random} from 'meteor/'

Template.examen.onCreated(function(){
    this.posSeleccion = 0;
    this.posVerdadero = 0;
    this.answersSeleccion1 = 0;
    this.answersSeleccion2 = 0;
    this.answersSeleccion3 = 0;
    this.answersSeleccion4 = 0;
    this.answersSeleccion5 = 0;
   // seleccionEscogida = [0,0,0,0,0,0,0,0,0,0];
    //verdaderoEscogido = [0,0,0,0,0,0,0,0,0,0];
    this.answersVerdaderos1 = 0;
    this.answersVerdaderos2 = 0;
    this.answersVerdaderos3 = 0;
    this.answersVerdaderos4 = 0;
    this.answersVerdaderos5 = 0;
    this.notaFinal = 0;
    Meteor.subscribe("Verdaderos");
    Meteor.subscribe("Selecciones");
    Meteor.subscribe("Estudiantes");

});

Template.examen.helpers({
    /*
    verdaderos:function(){
        return Verdaderos.find({});
    },
    selecciones:function(){
        return Selecciones.find({});
    },
    */
    /*
    sizeVerdaderos:function(){
        return Verdaderos.count();
    },
    sizeSelecciones:function(){
        return Selecciones.count();
    },
    */
    grade:function(){
        return Template.instance().notaFinal;
    },

    preguntaSeleccion1: function(){
        var random = Math.floor( Math.random() * (Selecciones.find({}).count()+1));
        try {
            var Doc = Selecciones.find().fetch()[random];
            Template.instance().answersSeleccion1=Doc.respuesta;
            console.log(Doc.respuesta);
        } catch (TypeError) {

        }

        return Selecciones.find({index:random});
    },
    preguntaSeleccion2: function(){
        var random = Math.floor( Math.random() * (Selecciones.find({}).count()+1));
        try {
            var Doc = Selecciones.find().fetch()[random];
            Template.instance().answersSeleccion2=Doc.respuesta;
            console.log(Doc.respuesta);
        } catch (TypeError) {

        }

        return Selecciones.find({index:random});
    },
    preguntaSeleccion3: function(){
        var random = Math.floor( Math.random() * (Selecciones.find({}).count()+1));
        try {
            var Doc = Selecciones.find().fetch()[random];
            Template.instance().answersSeleccion3=Doc.respuesta;
            console.log(Doc.respuesta);
        } catch (TypeError) {

        }

        return Selecciones.find({index:random});
    },
    preguntaSeleccion4: function(){
        var random = Math.floor( Math.random() * (Selecciones.find({}).count()+1));
        try {
            var Doc = Selecciones.find().fetch()[random];
            Template.instance().answersSeleccion4=Doc.respuesta;
            console.log(Doc.respuesta);
        } catch (TypeError) {

        }

        return Selecciones.find({index:random});
    },
    preguntaSeleccion5: function(){
        var random = Math.floor( Math.random() * (Selecciones.find({}).count()+1));
        try {
            var Doc = Selecciones.find().fetch()[random];
            Template.instance().answersSeleccion5=Doc.respuesta;
            console.log(Doc.respuesta);
        } catch (TypeError) {

        }

        return Selecciones.find({index:random});
    },

    preguntaVerdadero1: function(){
        var random = Math.floor( Math.random() * (Verdaderos.find({}).count()+1));
        try {
            var Doc = Verdaderos.find().fetch()[random];
            Template.instance().answersVerdaderos1 = Doc.respuesta;

        } catch (TypeError) {

        }
        return Verdaderos.find({index:random});
    },
    preguntaVerdadero2: function(){
        var random = Math.floor( Math.random() * (Verdaderos.find({}).count()+1));
        try {
            var Doc = Verdaderos.find().fetch()[random];
            Template.instance().answersVerdaderos2 = Doc.respuesta;
        } catch (TypeError) {

        }
        return Verdaderos.find({index:random});
    },
    preguntaVerdadero3: function(){
        var random = Math.floor( Math.random() * (Verdaderos.find({}).count()+1));
        try {
            var Doc = Verdaderos.find().fetch()[random];
            Template.instance().answersVerdaderos3 = Doc.respuesta;
        } catch (TypeError) {

        }
        return Verdaderos.find({index:random});
    },
    preguntaVerdadero4: function(){
        var random = Math.floor( Math.random() * (Verdaderos.find({}).count()+1));
        try {
            var Doc = Verdaderos.find().fetch()[random];
            Template.instance().answersVerdaderos4 = Doc.respuesta;
        } catch (TypeError) {

        }
        return Verdaderos.find({index:random});
    },
    preguntaVerdadero5: function(){
        var random = Math.floor( Math.random() * (Verdaderos.find({}).count()+1));
        try {
            var Doc = Verdaderos.find().fetch()[random];
            Template.instance().answersVerdaderos5 = Doc.respuesta;
        } catch (TypeError) {

        }
        return Verdaderos.find({index:random});
    }

    /*,

    opcion:function(numPregunta,numOpcion){
        var realSelectionIndex = Template.instance().seleccionEscogida[numPregunta];
        //var realSelection = Selecciones.findOne({index:realSelectionIndex});
        if(numOpcion === 1){
            return Selecciones.findOne({index:realSelectionIndex}).opcion1;
        }else if (numOpcion ===2 ){
            return Selecciones.findOne({index:realSelectionIndex}).opcion2;
        }else if(numOpcion ===3 ){
            return Selecciones.findOne({index:realSelectionIndex}).opcion3;
        }else if(numOpcion ===4 ){
            return Selecciones.findOne({index:realSelectionIndex}).opcion4;
        }
    }
    */
});

Template.examen.events({
    'click #finalizar'(event){
        var a1 =$('input:radio[name="group1"]:checked').val();
        var a2 =$('input:radio[name="group2"]:checked').val();
        var a3 =$('input:radio[name="group3"]:checked').val();
        var a4 =$('input:radio[name="group4"]:checked').val();
        var a5 =$('input:radio[name="group5"]:checked').val();
        var a6 =$('input:radio[name="group6"]:checked').val();
        var a7 =$('input:radio[name="group7"]:checked').val();
        var a8 =$('input:radio[name="group8"]:checked').val();
        var a9 =$('input:radio[name="group9"]:checked').val();
        var a10 =$('input:radio[name="group10"]:checked').val();

        var grades = 0;

        if( parseInt(a1) == Template.instance().answersSeleccion1 ){
            grades = grades + 1;

        }
        if(parseInt(a2) == Template.instance().answersSeleccion2 ){
            grades = grades + 1;

        }
        if(parseInt(a3) == Template.instance().answersSeleccion3 ){
            grades = grades + 1;

        }
        if(parseInt(a4) == Template.instance().answersSeleccion4 ){
            grades = grades + 1;

        }
        if(parseInt(a5) == Template.instance().answersSeleccion5 ){
            grades = grades + 1;

        }
        if(parseInt(a6) == Template.instance().answersVerdaderos1 ){
            grades = grades + 1;

        }
        if(parseInt(a7) == Template.instance().answersVerdaderos2 ){
            grades = grades + 1;

        }
        if(parseInt(a8) == Template.instance().answersVerdaderos3 ){
            grades = grades + 1;

        }
        if(parseInt(a9) == Template.instance().answersVerdaderos4 ){
            grades = grades + 1;

        }
        if(parseInt(a10) == Template.instance().answersVerdaderos5 ){
            grades = grades + 1;

        }
        var nombre = $('nombreEstudiante').val();

        Meteor.call("insertEstudiante", {nombre,grades},function(err,res){
            if(err){
                console.log(err);
            }
        });
    }

});

<|endoftext|>