<commit_before>function PerformanceDashboard(executionId, measurementType, entity) {

	var widgetsArray = [];
	var entityName = '';
	if(measurementType && measurementType === 'keyword'){
		entityName = 'Keyword';
	}else{
		entityName = 'Custom Transaction';
	}

	//addLastMeasurements(widgetsArray);
	addAggregatesOverTimeTpl(widgetsArray, entityName);
	addLastMeasurementsTpl(widgetsArray, entityName);
	addAggregatesSummaryTpl(widgetsArray, entityName);
	//TODO:addMeasurementExplorer(widgetsArray) //with paging
	//TODO:addAggregatesSummaryOptzTpl(widgetsArray);
	var dashboardObject = new Dashboard(
			entityName + ' Performance',
			new DashboardState(
					new GlobalSettings(
							[new Placeholder("__eId__", executionId, false), new Placeholder("__measurementType__", measurementType, false)],
							false,
							false,
							'Global Settings',
							3000
					),
					widgetsArray,
					entityName + ' Dashboard',
					'aggregated',
					new DefaultDashboardGui()
			)
	);

	dashboardObject.oid = "perfDashboardId";
	return dashboardObject;
};

function RTMAggBaseQueryTmpl(metric, transform){
	return new AsyncQuery(
			null,
			new Service(//service
					"/rtm/rest/aggregate/get", "Post",
					"",//templated
					new Preproc("function(requestFragment, workData){var newRequestFragment = requestFragment;for(i=0;i<workData.length;i++){newRequestFragment = newRequestFragment.replace(workData[i].key, workData[i].value);}return newRequestFragment;}"),
					new Postproc("", "",[], "function(response){if(!response.data.payload){console.log('No payload ->' + JSON.stringify(response)); return null;}return [{ placeholder : '__streamedSessionId__', value : response.data.payload.streamedSessionId, isDynamic : false }];}", "")
			),
			new Service(//callback
					"/rtm/rest/aggregate/refresh", "Post",
					"{\"streamedSessionId\": \"__streamedSessionId__\"}",
					new Preproc("function(requestFragment, workData){var newRequestFragment = requestFragment;for(i=0;i<workData.length;i++){newRequestFragment = newRequestFragment.replace(workData[i].placeholder, workData[i].value);}return newRequestFragment;}"),
					new Postproc("function(response){return response.data.payload.stream.complete;}", transform ,[{"key" : "metric", "value" : metric, "isDynamic" : false}], {}, ""))
	);
};

function RTMAggBaseTemplatedQueryTmpl(metric, pGranularity, transform){
	return new TemplatedQuery(
			"Template",
			new RTMAggBaseQueryTmpl(metric, transform),
			new DefaultPaging(),
			new Controls(
					new Template(
							"{ \"selectors1\": [{ \"textFilters\": [{ \"key\": \"eId\", \"value\": \"__eId__\", \"regex\": \"false\" }, { \"key\": \"type\", \"value\": \"__measurementType__\", \"regex\": \"false\" }], \"numericalFilters\": [] }], \"serviceParams\": { \"measurementService.nextFactor\": \"0\", \"aggregateService.sessionId\": \"defaultSid\", \"aggregateService.granularity\": \"__granularity__\", \"aggregateService.groupby\": \"name\", \"aggregateService.cpu\": \"1\", \"aggregateService.partition\": \"8\", \"aggregateService.timeout\": \"600\" } }",
							"",
							[new Placeholder("__granularity__", pGranularity, false)]
					)
			)
	);
};

var addAggregatesSummaryTpl = function(widgetsArray, entityName){
	var summaryTransform = "function (response) {\r\n    //var metrics = response.data.payload.metricList;\r\n    var metrics = [\"cnt\",\"avg\", \"min\", \"max\", \"tpm\", \"tps\", \"90th pcl\"];\r\n    var retData = [], series = {};\r\n\r\n    var payload = response.data.payload.stream.streamData;\r\n    var payloadKeys = Object.keys(payload);\r\n\r\n    if (payload && payloadKeys.length > 0) {\r\n        var serieskeys = Object.keys(payload[payloadKeys[0]])\r\n        for (j = 0; j < serieskeys.length; j++) {\r\n            for (i = 0; i < metrics.length; i++) {\r\n                var metric = metrics[i];\r\n                if (payload[payloadKeys[0]][serieskeys[j]][metric]) {\r\n                    retData.push({\r\n                        x: metric,\r\n                        y: Math.round(payload[payloadKeys[0]][serieskeys[j]][metric]),\r\n                        z: serieskeys[j]\r\n                    });\r\n                }\r\n            }\r\n        }\r\n    }\r\n    return retData;\r\n}";
	var standalone = new Widget(getUniqueId(), new DefaultWidgetState(), new DashletState(entityName + " stats summary", false, 0, {}, new ChartOptions('seriesTable'), new Config('Off', false, false, ''), new RTMAggBaseTemplatedQueryTmpl("sum", "max", summaryTransform), new DefaultGuiClosed(), new DefaultInfo()));
	widgetsArray.push(standalone);
};

var addAggregatesOverTimeTpl = function(widgetsArray, entityName){
	var overtimeTransform = "function (response, args) {\r\n    var metric = args.metric;\r\n    var retData = [], series = {};\r\n\r\n    var payload = response.data.payload.stream.streamData;\r\n    var payloadKeys = Object.keys(payload);\r\n\r\n    for (i = 0; i < payloadKeys.length; i++) {\r\n        var serieskeys = Object.keys(payload[payloadKeys[i]])\r\n        for (j = 0; j < serieskeys.length; j++) {\r\n            retData.push({\r\n                x: payloadKeys[i],\r\n                y: payload[payloadKeys[i]][serieskeys[j]][metric],\r\n                z: serieskeys[j]\r\n            });\r\n        }\r\n    }\r\n    return retData;\r\n}";
	var overtimeFillBlanksTransform = "function (response, args) {\r\n    var metric = args.metric;\r\n    var retData = [], series = [];\r\n\r\n    var payload = response.data.payload.stream.streamData;\r\n    var payloadKeys = Object.keys(payload);\r\n\r\n    for (i = 0; i < payloadKeys.length; i++) {\r\n        var serieskeys = Object.keys(payload[payloadKeys[i]])\r\n        for (j = 0; j < serieskeys.length; j++) {\r\n            if(!series.includes(serieskeys[j])){\r\n                series.push(serieskeys[j]);\r\n            }\r\n        }\r\n    }\r\n\r\n    for (i = 0; i < payloadKeys.length; i++) {\r\n        var serieskeys = Object.keys(payload[payloadKeys[i]])\r\n        for (j = 0; j < series.length; j++) {\r\n            var yval;\r\n            if(payload[payloadKeys[i]][serieskeys[j]] && payload[payloadKeys[i]][serieskeys[j]][metric]){\r\n              yval = payload[payloadKeys[i]][serieskeys[j]][metric];\r\n            }else{\r\n              //console.log('missing dot: x=' + payloadKeys[i] + '; series=' + series[j]);\r\n              yval = 0;\r\n            }\r\n            retData.push({\r\n                x: payloadKeys[i],\r\n                y: yval,\r\n                z: series[j]\r\n            });\r\n        }\r\n    }\r\n    return retData;\r\n}";
	var config = getMasterSlaveConfig("raw", "Average "+entityName+" Duration (ms)", "Nb " + entityName + " per minute");

	var master = new Widget(config.masterid, new DefaultWidgetState(), new DashletState(config.mastertitle, false, 0, {}, new ChartOptions('lineChart'), config.masterconfig, new RTMAggBaseTemplatedQueryTmpl("avg", "auto", overtimeTransform), new DefaultGuiClosed(), new DefaultInfo()));
	//var slave = new Widget(config.slaveid, new DefaultWidgetState(), new DashletState(config.slavetitle, false, 0, {}, new ChartOptions('lineChart'), config.slaveconfig, new RTMAggBaseTemplatedQueryTmpl("cnt", "auto", overtimeTransform), new DefaultGuiClosed(), new DefaultInfo()));
	var slave = new Widget(config.slaveid, new DefaultWidgetState(), new DashletState(config.slavetitle, false, 0, {}, new ChartOptions('stackedAreaChart', false, true), config.slaveconfig, new RTMAggBaseTemplatedQueryTmpl("cnt", "auto", overtimeFillBlanksTransform), new DefaultGuiClosed(), new DefaultInfo()));

	widgetsArray.push(master);
	widgetsArray.push(slave);
};

//No paging: FACTOR 100 via template
var addLastMeasurementsTpl = function(widgetsArray, entityName){
	function RTMLatestMeasurementBaseQueryTmpl(){
		return new SimpleQuery(
				"Raw", new Service(
						"/rtm/rest/measurement/latest", "Post",
						"",
						new Preproc("function(requestFragment, workData){var newRequestFragment = requestFragment;for(i=0;i<workData.length;i++){newRequestFragment = newRequestFragment.replace(workData[i].key, workData[i].value);}return newRequestFragment;}"),
						new Postproc("", "function (response, args) {\r\n    var x = 'begin', y = 'value', z = 'name';\r\n    var retData = [], index = {};\r\n    var payload = response.data.payload;\r\n    for (var i = 0; i < payload.length; i++) {\r\n        retData.push({\r\n            x: payload[i][x],\r\n            y: payload[i][y],\r\n            z: payload[i][z]\r\n        });\r\n    }\r\n    return retData;\r\n}",
								[], {}, "")
				)
		);
	};

	function RTMLatestMeasurementTemplatedQuery(){
		return new TemplatedQuery(
				"Template",
				new RTMLatestMeasurementBaseQueryTmpl(),
				new DefaultPaging(),
				//new Paging("On", new Offset("__FACTOR__", "return 0;", "return value + 1;", "if(value > 0){return value - 1;} else{return 0;}"), null),
				new Controls(
						new Template(
								"{ \"selectors1\": [{ \"textFilters\": [{ \"key\": \"eId\", \"value\": \"__eId__\", \"regex\": \"false\" }, { \"key\": \"type\", \"value\": \"__measurementType__\", \"regex\": \"false\" }], \"numericalFilters\": [] }], \"serviceParams\": { \"measurementService.nextFactor\": \"__FACTOR__\", \"aggregateService.sessionId\": \"defaultSid\", \"aggregateService.granularity\": \"auto\", \"aggregateService.groupby\": \"name\", \"aggregateService.cpu\": \"1\", \"aggregateService.partition\": \"8\", \"aggregateService.timeout\": \"600\" } }",
								"",
								[new Placeholder("__FACTOR__", "100", false)]
						)
				)
		);
	};

	var config = getMasterSlaveConfig("transformed", "Last 100 " + entityName +"s - Individual duration (ms)", "Last 100 "+entityName+"s - Value table (ms)");

	var master = new Widget(config.masterid, new DefaultWidgetState(), new DashletState(config.mastertitle, false, 0, {}, new ChartOptions('scatterChart'), config.masterconfig, new RTMLatestMeasurementTemplatedQuery(), new DefaultGuiClosed(), new DefaultInfo()) );
	var slave = new Widget(config.slaveid, new DefaultWidgetState(), new DashletState(config.slavetitle, false, 0, {}, new ChartOptions('seriesTable'), config.slaveconfig, new RTMLatestMeasurementTemplatedQuery(), new DefaultGuiClosed(), new DefaultInfo()) );

	widgetsArray.push(master);
	//widgetsArray.push(slave);
};

var getMasterSlaveConfig = function(rawOrTransformed, masterTitle, slaveTitle){
	var masterId, slaveId, masterTitle, slaveTitle, masterConfig, slaveConfig, datatype;

	if(rawOrTransformed === 'raw'){
		datatype = 'state.data.rawresponse';
	}else{
		datatype = 'state.data.transformed';
	}

	var random = getUniqueId();
	masterId = random + "-master";
	slaveId = random + "-slave";

	masterConfig = new Config('Off', true, false, 'unnecessaryAsMaster');
	slaveConfig = new Config('Off', false, true, datatype);
	slaveConfig.currentmaster = {
			oid: masterId,
			title: masterTitle
	};

	return {masterid: masterId, slaveid: slaveId, mastertitle: masterTitle, slavetitle: slaveTitle, masterconfig : masterConfig, slaveconfig: slaveConfig};
};

function StaticPresets() {
	return {
		queries: [],
		controls: {
			templates: []
		},
		configs: []
	};
}<commit_msg>Switching perf dashboard throughput to tps<commit_after>function PerformanceDashboard(executionId, measurementType, entity) {

	var widgetsArray = [];
	var entityName = '';
	if(measurementType && measurementType === 'keyword'){
		entityName = 'Keyword';
	}else{
		entityName = 'Custom Transaction';
	}

	//addLastMeasurements(widgetsArray);
	addAggregatesOverTimeTpl(widgetsArray, entityName);
	addLastMeasurementsTpl(widgetsArray, entityName);
	addAggregatesSummaryTpl(widgetsArray, entityName);
	//TODO:addMeasurementExplorer(widgetsArray) //with paging
	//TODO:addAggregatesSummaryOptzTpl(widgetsArray);
	var dashboardObject = new Dashboard(
			entityName + ' Performance',
			new DashboardState(
					new GlobalSettings(
							[new Placeholder("__eId__", executionId, false), new Placeholder("__measurementType__", measurementType, false)],
							false,
							false,
							'Global Settings',
							3000
					),
					widgetsArray,
					entityName + ' Dashboard',
					'aggregated',
					new DefaultDashboardGui()
			)
	);

	dashboardObject.oid = "perfDashboardId";
	return dashboardObject;
};

function RTMAggBaseQueryTmpl(metric, transform){
	return new AsyncQuery(
			null,
			new Service(//service
					"/rtm/rest/aggregate/get", "Post",
					"",//templated
					new Preproc("function(requestFragment, workData){var newRequestFragment = requestFragment;for(i=0;i<workData.length;i++){newRequestFragment = newRequestFragment.replace(workData[i].key, workData[i].value);}return newRequestFragment;}"),
					new Postproc("", "",[], "function(response){if(!response.data.payload){console.log('No payload ->' + JSON.stringify(response)); return null;}return [{ placeholder : '__streamedSessionId__', value : response.data.payload.streamedSessionId, isDynamic : false }];}", "")
			),
			new Service(//callback
					"/rtm/rest/aggregate/refresh", "Post",
					"{\"streamedSessionId\": \"__streamedSessionId__\"}",
					new Preproc("function(requestFragment, workData){var newRequestFragment = requestFragment;for(i=0;i<workData.length;i++){newRequestFragment = newRequestFragment.replace(workData[i].placeholder, workData[i].value);}return newRequestFragment;}"),
					new Postproc("function(response){return response.data.payload.stream.complete;}", transform ,[{"key" : "metric", "value" : metric, "isDynamic" : false}], {}, ""))
	);
};

function RTMAggBaseTemplatedQueryTmpl(metric, pGranularity, transform){
	return new TemplatedQuery(
			"Template",
			new RTMAggBaseQueryTmpl(metric, transform),
			new DefaultPaging(),
			new Controls(
					new Template(
							"{ \"selectors1\": [{ \"textFilters\": [{ \"key\": \"eId\", \"value\": \"__eId__\", \"regex\": \"false\" }, { \"key\": \"type\", \"value\": \"__measurementType__\", \"regex\": \"false\" }], \"numericalFilters\": [] }], \"serviceParams\": { \"measurementService.nextFactor\": \"0\", \"aggregateService.sessionId\": \"defaultSid\", \"aggregateService.granularity\": \"__granularity__\", \"aggregateService.groupby\": \"name\", \"aggregateService.cpu\": \"1\", \"aggregateService.partition\": \"8\", \"aggregateService.timeout\": \"600\" } }",
							"",
							[new Placeholder("__granularity__", pGranularity, false)]
					)
			)
	);
};

var addAggregatesSummaryTpl = function(widgetsArray, entityName){
	var summaryTransform = "function (response) {\r\n    //var metrics = response.data.payload.metricList;\r\n    var metrics = [\"cnt\",\"avg\", \"min\", \"max\", \"tpm\", \"tps\", \"90th pcl\"];\r\n    var retData = [], series = {};\r\n\r\n    var payload = response.data.payload.stream.streamData;\r\n    var payloadKeys = Object.keys(payload);\r\n\r\n    if (payload && payloadKeys.length > 0) {\r\n        var serieskeys = Object.keys(payload[payloadKeys[0]])\r\n        for (j = 0; j < serieskeys.length; j++) {\r\n            for (i = 0; i < metrics.length; i++) {\r\n                var metric = metrics[i];\r\n                if (payload[payloadKeys[0]][serieskeys[j]][metric]) {\r\n                    retData.push({\r\n                        x: metric,\r\n                        y: Math.round(payload[payloadKeys[0]][serieskeys[j]][metric]),\r\n                        z: serieskeys[j]\r\n                    });\r\n                }\r\n            }\r\n        }\r\n    }\r\n    return retData;\r\n}";
	var standalone = new Widget(getUniqueId(), new DefaultWidgetState(), new DashletState(entityName + " stats summary", false, 0, {}, new ChartOptions('seriesTable'), new Config('Off', false, false, ''), new RTMAggBaseTemplatedQueryTmpl("sum", "max", summaryTransform), new DefaultGuiClosed(), new DefaultInfo()));
	widgetsArray.push(standalone);
};

var addAggregatesOverTimeTpl = function(widgetsArray, entityName){
	var overtimeTransform = "function (response, args) {\r\n    var metric = args.metric;\r\n    var retData = [], series = {};\r\n\r\n    var payload = response.data.payload.stream.streamData;\r\n    var payloadKeys = Object.keys(payload);\r\n\r\n    for (i = 0; i < payloadKeys.length; i++) {\r\n        var serieskeys = Object.keys(payload[payloadKeys[i]])\r\n        for (j = 0; j < serieskeys.length; j++) {\r\n            retData.push({\r\n                x: payloadKeys[i],\r\n                y: payload[payloadKeys[i]][serieskeys[j]][metric],\r\n                z: serieskeys[j]\r\n            });\r\n        }\r\n    }\r\n    return retData;\r\n}";
	var overtimeFillBlanksTransform = "function (response, args) {\r\n    var metric = args.metric;\r\n    var retData = [], series = [];\r\n\r\n    var payload = response.data.payload.stream.streamData;\r\n    var payloadKeys = Object.keys(payload);\r\n\r\n    for (i = 0; i < payloadKeys.length; i++) {\r\n        var serieskeys = Object.keys(payload[payloadKeys[i]])\r\n        for (j = 0; j < serieskeys.length; j++) {\r\n            if(!series.includes(serieskeys[j])){\r\n                series.push(serieskeys[j]);\r\n            }\r\n        }\r\n    }\r\n\r\n    for (i = 0; i < payloadKeys.length; i++) {\r\n        var serieskeys = Object.keys(payload[payloadKeys[i]])\r\n        for (j = 0; j < series.length; j++) {\r\n            var yval;\r\n            if(payload[payloadKeys[i]][serieskeys[j]] && payload[payloadKeys[i]][serieskeys[j]][metric]){\r\n              yval = payload[payloadKeys[i]][serieskeys[j]][metric];\r\n            }else{\r\n              //console.log('missing dot: x=' + payloadKeys[i] + '; series=' + series[j]);\r\n              yval = 0;\r\n            }\r\n            retData.push({\r\n                x: payloadKeys[i],\r\n                y: yval,\r\n                z: series[j]\r\n            });\r\n        }\r\n    }\r\n    return retData;\r\n}";
	var config = getMasterSlaveConfig("raw", "Average "+entityName+" Duration (ms)", "Nb " + entityName + " per second");

	var master = new Widget(config.masterid, new DefaultWidgetState(), new DashletState(config.mastertitle, false, 0, {}, new ChartOptions('lineChart'), config.masterconfig, new RTMAggBaseTemplatedQueryTmpl("avg", "auto", overtimeTransform), new DefaultGuiClosed(), new DefaultInfo()));
	//var slave = new Widget(config.slaveid, new DefaultWidgetState(), new DashletState(config.slavetitle, false, 0, {}, new ChartOptions('lineChart'), config.slaveconfig, new RTMAggBaseTemplatedQueryTmpl("cnt", "auto", overtimeTransform), new DefaultGuiClosed(), new DefaultInfo()));
	var slave = new Widget(config.slaveid, new DefaultWidgetState(), new DashletState(config.slavetitle, false, 0, {}, new ChartOptions('stackedAreaChart', false, true), config.slaveconfig, new RTMAggBaseTemplatedQueryTmpl("tps", "auto", overtimeFillBlanksTransform), new DefaultGuiClosed(), new DefaultInfo()));

	widgetsArray.push(master);
	widgetsArray.push(slave);
};

//No paging: FACTOR 100 via template
var addLastMeasurementsTpl = function(widgetsArray, entityName){
	function RTMLatestMeasurementBaseQueryTmpl(){
		return new SimpleQuery(
				"Raw", new Service(
						"/rtm/rest/measurement/latest", "Post",
						"",
						new Preproc("function(requestFragment, workData){var newRequestFragment = requestFragment;for(i=0;i<workData.length;i++){newRequestFragment = newRequestFragment.replace(workData[i].key, workData[i].value);}return newRequestFragment;}"),
						new Postproc("", "function (response, args) {\r\n    var x = 'begin', y = 'value', z = 'name';\r\n    var retData = [], index = {};\r\n    var payload = response.data.payload;\r\n    for (var i = 0; i < payload.length; i++) {\r\n        retData.push({\r\n            x: payload[i][x],\r\n            y: payload[i][y],\r\n            z: payload[i][z]\r\n        });\r\n    }\r\n    return retData;\r\n}",
								[], {}, "")
				)
		);
	};

	function RTMLatestMeasurementTemplatedQuery(){
		return new TemplatedQuery(
				"Template",
				new RTMLatestMeasurementBaseQueryTmpl(),
				new DefaultPaging(),
				//new Paging("On", new Offset("__FACTOR__", "return 0;", "return value + 1;", "if(value > 0){return value - 1;} else{return 0;}"), null),
				new Controls(
						new Template(
								"{ \"selectors1\": [{ \"textFilters\": [{ \"key\": \"eId\", \"value\": \"__eId__\", \"regex\": \"false\" }, { \"key\": \"type\", \"value\": \"__measurementType__\", \"regex\": \"false\" }], \"numericalFilters\": [] }], \"serviceParams\": { \"measurementService.nextFactor\": \"__FACTOR__\", \"aggregateService.sessionId\": \"defaultSid\", \"aggregateService.granularity\": \"auto\", \"aggregateService.groupby\": \"name\", \"aggregateService.cpu\": \"1\", \"aggregateService.partition\": \"8\", \"aggregateService.timeout\": \"600\" } }",
								"",
								[new Placeholder("__FACTOR__", "100", false)]
						)
				)
		);
	};

	var config = getMasterSlaveConfig("transformed", "Last 100 " + entityName +"s - Individual duration (ms)", "Last 100 "+entityName+"s - Value table (ms)");

	var master = new Widget(config.masterid, new DefaultWidgetState(), new DashletState(config.mastertitle, false, 0, {}, new ChartOptions('scatterChart'), config.masterconfig, new RTMLatestMeasurementTemplatedQuery(), new DefaultGuiClosed(), new DefaultInfo()) );
	var slave = new Widget(config.slaveid, new DefaultWidgetState(), new DashletState(config.slavetitle, false, 0, {}, new ChartOptions('seriesTable'), config.slaveconfig, new RTMLatestMeasurementTemplatedQuery(), new DefaultGuiClosed(), new DefaultInfo()) );

	widgetsArray.push(master);
	//widgetsArray.push(slave);
};

var getMasterSlaveConfig = function(rawOrTransformed, masterTitle, slaveTitle){
	var masterId, slaveId, masterTitle, slaveTitle, masterConfig, slaveConfig, datatype;

	if(rawOrTransformed === 'raw'){
		datatype = 'state.data.rawresponse';
	}else{
		datatype = 'state.data.transformed';
	}

	var random = getUniqueId();
	masterId = random + "-master";
	slaveId = random + "-slave";

	masterConfig = new Config('Off', true, false, 'unnecessaryAsMaster');
	slaveConfig = new Config('Off', false, true, datatype);
	slaveConfig.currentmaster = {
			oid: masterId,
			title: masterTitle
	};

	return {masterid: masterId, slaveid: slaveId, mastertitle: masterTitle, slavetitle: slaveTitle, masterconfig : masterConfig, slaveconfig: slaveConfig};
};

function StaticPresets() {
	return {
		queries: [],
		controls: {
			templates: []
		},
		configs: []
	};
}<|endoftext|>


<commit_before>import Vue from 'vue'
import * as arceasy from 'arceasy'

const changeMap = (slide, state) => {
    arceasy.layers.hideAll()

    state.visibility = slide.presentation !== undefined
        ? slide.minimize : true

    // if (slide.light !== undefined) {
    //     // if (slide.light.cameraTracking !== undefined) {
    //     //     arceasy.view.light({
    //     //         cameraTracking: slide.light.cameraTracking
    //     //     })
    //     // }
    //
    //     if (slide.light.date !== undefined) {
    //         arceasy.view.light({
    //             date: slide.light.date
    //         })
    //     }
    // }

    if (slide.coordinates !== undefined ||
        slide.scale !== undefined ||
        slide.camera !== undefined) {
        arceasy.view.newPosition({
            coordinates: slide.coordinates,
            scale: slide.scale,
            camera: slide.camera
        })
    }

    if (slide.basemap !== undefined) {
        arceasy.view.changeBasemap(
            slide.basemap
        )
    }

    if (slide.symbol !== undefined) {
        arceasy.utils.addGraphicLayer(
            slide.symbol,
            slide.point
        )
    }

    if (slide.layer !== undefined) {
        slide.layer.forEach((cur, indx, arr) => {
            arceasy.layers.setVisibility(
                cur,
                true
            )
        })
    }

    if (slide.opacity !== undefined &&
        slide.layer !== undefined) {
        slide.layer.forEach((cur, indx, arr) => {
            arceasy.layers.setOpacity(
                cur,
                slide.opacity
            )
        })
    }

    if (slide.id === 'possibilidades' ||
        slide.id === 'webradar-3') {
        arceasy.utils.hideGraphicLayers()
    }
}

export default {
    start (state) {
        state.actual = 51
    },
    next (state) {
        if (state.actual < state.slides.length - 1) {
            state.actual++
        }
    },
    previous (state) {
        if (state.actual > 0) {
            --state.actual
        }
    },
    visibility (state, status) {
        state.visibility = status
    },
    setSlide (state, slide) {
        Vue.set(state, 'slide', slide)

        if (Object.keys(arceasy.obj.view).length !== 0) {
            changeMap(slide, state)
        }
    }
}
<commit_msg>(acho que é o build final)<commit_after>import Vue from 'vue'
import * as arceasy from 'arceasy'

const changeMap = (slide, state) => {
    arceasy.layers.hideAll()

    state.visibility = slide.presentation !== undefined
        ? slide.minimize : true

    // if (slide.light !== undefined) {
    //     // if (slide.light.cameraTracking !== undefined) {
    //     //     arceasy.view.light({
    //     //         cameraTracking: slide.light.cameraTracking
    //     //     })
    //     // }
    //
    //     if (slide.light.date !== undefined) {
    //         arceasy.view.light({
    //             date: slide.light.date
    //         })
    //     }
    // }

    if (slide.coordinates !== undefined ||
        slide.scale !== undefined ||
        slide.camera !== undefined) {
        arceasy.view.newPosition({
            coordinates: slide.coordinates,
            scale: slide.scale,
            camera: slide.camera
        })
    }

    if (slide.basemap !== undefined) {
        arceasy.view.changeBasemap(
            slide.basemap
        )
    }

    if (slide.symbol !== undefined) {
        arceasy.utils.addGraphicLayer(
            slide.symbol,
            slide.point
        )
    }

    if (slide.layer !== undefined) {
        slide.layer.forEach((cur, indx, arr) => {
            arceasy.layers.setVisibility(
                cur,
                true
            )
        })
    }

    if (slide.opacity !== undefined &&
        slide.layer !== undefined) {
        slide.layer.forEach((cur, indx, arr) => {
            arceasy.layers.setOpacity(
                cur,
                slide.opacity
            )
        })
    }

    if (slide.id === 'possibilidades' ||
        slide.id === 'webradar-3') {
        arceasy.utils.hideGraphicLayers()
    }
}

export default {
    start (state) {
        state.actual = 0
    },
    next (state) {
        if (state.actual < state.slides.length - 1) {
            state.actual++
        }
    },
    previous (state) {
        if (state.actual > 0) {
            --state.actual
        }
    },
    visibility (state, status) {
        state.visibility = status
    },
    setSlide (state, slide) {
        Vue.set(state, 'slide', slide)

        if (Object.keys(arceasy.obj.view).length !== 0) {
            changeMap(slide, state)
        }
    }
}
<|endoftext|>


<commit_before>//  cordova-plugin-spinnerdialog
//  Copyright © 2015 filfat Studios AB
//  Repo: https://github.com/filfat-Studios-AB/cordova-plugin-spinnerdialog
/* global Windows, cordova */
var progressIndicator;

cordova.commandProxy.add("SpinnerDialog", {
  show: function (successCallback, errorCallback, data) {
    if (typeof Windows !== 'undefined' &&
      typeof Windows.UI !== 'undefined' /* Check that we have a UI to work with */ &&
      typeof Windows.UI.ViewManagement.StatusBar !== 'undefined' /* Check that we have the StatusBar to work with*/) {

      progressIndicator = Windows.UI.ViewManagement.StatusBar.ProgressIndicator
        || Windows.UI.ViewManagement.StatusBar.getForCurrentView().progressIndicator;

      if (typeof(data[0]) !== 'undefined' && data[0] !== null) {
        progressIndicator.text = data[0];
	    }
      progressIndicator.showAsync();
      Windows.UI.ViewManagement.StatusBar.getForCurrentView().showAsync();
    } else if (typeof Windows !== 'undefined' &&
      typeof Windows.UI !== 'undefined' /* Check that we have a UI to work with */) {

      //TODO: Support Desktop, Xbox, etc
    }
  },
  hide: function (successCallback, errorCallback, data) {
    if (typeof Windows !== 'undefined' &&
      typeof Windows.UI !== 'undefined' /* Check that we have a UI to work with */ &&
      typeof Windows.UI.ViewManagement.StatusBar !== 'undefined' /* Check that we have the StatusBar to work with*/) {

      progressIndicator.hideAsync();
      /* Hide status bar if data is undefined or false exclusively */
      if(typeof(data[0]) === 'undefined' || data[0] === false) {
        Windows.UI.ViewManagement.StatusBar.getForCurrentView().hideAsync();
      }
    } else if (typeof Windows !== 'undefined' &&
      typeof Windows.UI !== 'undefined' /* Check that we have a UI to work with */) {

      //TODO: Support Desktop, Xbox, etc
    }
  }
});
<commit_msg>Update SpinnerDialogProxy.js<commit_after>//  cordova-plugin-spinnerdialog
//  Copyright © 2015 filfat Studios AB
//  Repo: https://github.com/filfat-Studios-AB/cordova-plugin-spinnerdialog
/* global Windows, cordova */
var progressIndicator;

cordova.commandProxy.add("SpinnerDialog", {
  show: function (successCallback, errorCallback, data) {
    if (typeof Windows !== 'undefined' &&
      typeof Windows.UI !== 'undefined' /* Check that we have a UI to work with */ &&
      typeof Windows.UI.ViewManagement.StatusBar !== 'undefined' /* Check that we have the StatusBar to work with*/) {

      progressIndicator = Windows.UI.ViewManagement.StatusBar.ProgressIndicator
        || Windows.UI.ViewManagement.StatusBar.getForCurrentView().progressIndicator;

      if (typeof(data[0]) !== 'undefined' && data[0] !== null) {
        progressIndicator.text = data[0];
	    }
      progressIndicator.showAsync();
      Windows.UI.ViewManagement.StatusBar.getForCurrentView().showAsync();
    } else if (typeof Windows !== 'undefined' &&
      typeof Windows.UI !== 'undefined' /* Check that we have a UI to work with */) {

      //TODO: Support Desktop, Xbox, etc
    }
  },
  hide: function (successCallback, errorCallback, data) {
    if (typeof Windows !== 'undefined' &&
      typeof Windows.UI !== 'undefined' /* Check that we have a UI to work with */ &&
      typeof Windows.UI.ViewManagement.StatusBar !== 'undefined' /* Check that we have the StatusBar to work with*/) {

      try {
        progressIndicator.hideAsync();
      } catch(e) {
        console.warn(e.message);
      }
      /* Hide status bar if data is undefined or false exclusively */
      if(typeof(data[0]) === 'undefined' || data[0] === false) {
        Windows.UI.ViewManagement.StatusBar.getForCurrentView().hideAsync();
      }
    } else if (typeof Windows !== 'undefined' &&
      typeof Windows.UI !== 'undefined' /* Check that we have a UI to work with */) {

      //TODO: Support Desktop, Xbox, etc
    }
  }
});
<|endoftext|>


<commit_before>(function() {
  var app = angular.module('tinatasks', ["components", "firebase"]);
  var ref = new Firebase("https://tinacg.firebaseio.com/tinatasks");

  app.controller('TaskController', ['$rootScope', '$scope', '$firebase', function($rootScope, $scope, $firebase) {
    function init(authData) {
      // $scope.loginStatus = "Welcome back " + authData.password.email + "! Your token expires " + (new Date(authData.expires * 1000));
      $scope.loggedIn = true;

      $scope.notification = "Welcome back " + authData.password.email + "! Your token expires " + (new Date(authData.expires * 1000));

      var tabsRef = ref.child(authData.uid).child("tabs");
      var sync = $firebase(tabsRef);
      $scope.tabs = sync.$asArray();

      $scope.addTab = function(tabName) {
        $scope.tabs.$add({ name: tabName })
          .then(function() { $scope.refreshTaskRefs(); })
          .then(function() { $scope.notification = "Added tab " + tabName; });
      };

      var tasksRef = [];
      var tasksSync = [];
      $scope.tasks = [];

      var tasksRootRef = ref.child(authData.uid).child("tasks");
      var tasksRootSync = $firebase(tasksRootRef);
      $scope.tasksRoot = tasksRootSync.$asObject();

      $scope.refreshTaskRefs = function() {
        angular.forEach($scope.tabs, function(tab, tabId) {
          tasksRef[tab.name] = ref.child(authData.uid).child("tasks").child(tab.name);
          tasksSync[tab.name] = $firebase(tasksRef[tab.name]);
          $scope.tasks[tab.name] = tasksSync[tab.name].$asArray();

          $scope.tasks[tab.name].$loaded().then(function() {
            $scope.refreshAllTasks();
          });

        });
      };

      $scope.tabs.$loaded().then(function () {
        $scope.refreshTaskRefs();
        //$rootScope.panes[1].select();
        angular.forEach($scope.tabs, function(tab, tabId) {
          console.log("populate " + tab.name);
          $scope.populateAllTasks(tab.name);
        });
      });

      $scope.updateTask = function(tasks, task) {
        tasks.$save(task)
          .then(function() { $scope.notification = "Changed task " + task.description; });
      }

      $scope.addTask = function(tabName, taskDone, taskDescription, taskCategory, taskDueDate) {
        taskDescription = taskDescription || "My Task";
        taskCategory = taskCategory || "~uncategorized";
        taskDueDate = taskDueDate || "soon";

        $scope.tasks[tabName].$add({ done: taskDone,
                                     description: taskDescription,
                                     category: taskCategory,
                                     createDate: (new Date()).getTime(),
                                     dueDate: taskDueDate,
                                   })
          .then(function() { $scope.notification = "Added " + tabName + "/" + taskDescription; })
          .then(function() { $scope.refreshAllTasks(); });

        $scope.taskDone = false;
        $scope.taskDescription = "";
        $scope.taskCategory = "";
        $scope.taskDueDate = "";

        $scope.$broadcast("newTaskAdded");
      };

      // tasks[tab.name].$remove(task)
      $scope.removeTask = function(tasks, task) {
        tasks.$remove(task)
          .then(function() { $scope.notification = "Removed task " + task.description; })
          .then(function() { $scope.refreshAllTasks(); });
      };

      $scope.deleteTabTasks = function(tabName) {
        tasksRootSync.$remove(tabName)
          .then(function() { $scope.notification = "Deleted tab tasks for " + tabName; })
          .then(function() { $scope.refreshAllTasks(); });
      };

      $scope.removeTab = function(tab) {
        tasksRootSync.$remove(tab.name)
          .then(function() { $scope.tabs.$remove(tab)
                             .then(function() { $scope.notification = "Removed tab " + tab.name; }); })
          .then(function() { $scope.refreshAllTasks(); });
      };

      // ARRAY FOR ALL TASKS

      $scope.allTasks = [];

      $scope.cleanAllTasks = function() {
        $scope.allTasks = [];
      }

      $scope.populateAllTasks = function(tabName) {
        angular.forEach($scope.tasks[tabName], function(task) {
          $scope.allTasks.push(task);
        });
      };

      $scope.refreshAllTasks = function() {
        $scope.cleanAllTasks();
        angular.forEach($scope.tabs, function(tab, tabId) {
          $scope.populateAllTasks(tab.name);
        });
      };

      // TIME AND MOMENT.JS

      $scope.getms = function(s) {
        var m = moment(s, "D/M/YY H:mm:ss");
        var result = m.valueOf();
        if (isNaN(result)) {
          result = 0;
        }
        return result;
      };

      $scope.getFormattedDate = function(ms) {
        var result = moment(ms).locale('pt-BR').format('ddd D-MMM-YY H:mm:ss');
        if (result === 'Invalid date') {
          result = 'data invalida';
        }
        if (ms === undefined) {
          result = "";
        }
        return result;
      };

      $scope.getShortDate = function(ms) {
        // var result = moment(ms).locale('pt-BR').format('D-MMM H:mm:ss');
        var result = moment(ms).locale('pt-BR').format('D-MMM');
        return result;
      };

      $scope.parseDate = function(s) {
        if (s === 'soon') {
          return 9999999999000;
        }
        return moment(s, "D/M/YY H:mm:ss").valueOf();
      };

      $scope.millisToString = function(ms)
      {
        if (ms < 0 || ms > 3159999999000) {
          return "∞";
        }
        var seconds = Math.floor(ms / 1000);
        var numyears = Math.floor(seconds / 31536000);
        var numdays = Math.floor((seconds % 31536000) / 86400);
        var numhours = Math.floor(((seconds % 31536000) % 86400) / 3600);
        var numminutes = Math.floor((((seconds % 31536000) % 86400) % 3600) / 60);
        var numseconds = (((seconds % 31536000) % 86400) % 3600) % 60;

        var result = "";

        if (numyears > 0) {
          result += numyears + "y ";
        }
        if (numdays > 0) {
          result += numdays + "d ";
        }
        if (numhours > 0) {
          result += numhours + "h ";
        }
        if (numminutes > 0) {
          result += numminutes + "m ";
        }
        // if (numseconds > 0) {
        //  result += numseconds + "s";
        // }
        return result;
      }

      $scope.momentNow = function() {
        return moment().valueOf();
      };

      $scope.now = $scope.momentNow();
      $scope.nowFull = moment().locale('pt-BR').format();

      $scope.dueDateOrder = function(task) {
        return $scope.parseDate(task.dueDate);
      }

      function numdays(ms) {
        var seconds = Math.floor(ms / 1000);
        var days = Math.floor(seconds / 86400);

        return days;
      }

      function daysSince01(dmyStr) {
        var dmyParts = dmyStr.split("/");
        var day = Number(dmyParts[0]);
        var month = Number(dmyParts[1]);
        var year = Number(dmyParts[2]);

        var leapYearsPassed = Math.floor(year / 4);

        if (year % 4 === 0 && month > 2) {
          leapYearsPassed -= 1;
        }

        return leapYearsPassed + (year * 365) + moment(dmyStr, "D/M/YY").dayOfYear();
      }

      // pass moment() now to a function that returns D/M/Y

      $scope.daysDiff = function(then, now) {
        // var nineteenseventy = moment("1/1/1970 0:00:00", "D/M/YYYY H:mm:ss");
        // var then_since1970 = numdays(moment(then, "D/M/YY H:mm:ss").valueOf());
        // var now_since1970 = numdays(moment().valueOf());
        // return Math.max(0, then_since1970 - now_since1970);
        // var result = daysSince01(then.split(" ")[0]) - daysSince01(moment().locale('pt-BR').format("D/M/YY"))
        var result = Math.floor((moment(then.split(" ")[0], "D/M/YY").startOf("day") - moment().startOf("day")) / 86400000);

        if (isNaN(result) || result < 0) {
          result = "";
        }

        else {
          if (result === 1) {
            return "in " + result + " day";
          } else if (result === 0) {
            return "today";
          } else {
            return "in " + result + " days";
          }
        }
      };
    }

    function clean() {
      $scope.notification = "Please log in";
      $scope.tabs = [];
      $scope.loggedIn = false;
    }

    $scope.logout = function() {
      ref.unauth();
      document.location.href = "login.html";
    }

    var authData = ref.getAuth();
    if (authData) {
      init(authData);
    } else {
      clean();
    }
  }]);

  app.directive("focusOn", function() {
    return function(scope, elem, attr) {
      scope.$on(attr.focusOn, function(e) {
        elem[0].focus();
      });
    };
  });
})();
<commit_msg>shorten expiry alert<commit_after>(function() {
  var app = angular.module('tinatasks', ["components", "firebase"]);
  var ref = new Firebase("https://tinacg.firebaseio.com/tinatasks");

  app.controller('TaskController', ['$rootScope', '$scope', '$firebase', function($rootScope, $scope, $firebase) {
    function init(authData) {
      // $scope.loginStatus = "Welcome back " + authData.password.email + "! Your token expires " + (new Date(authData.expires * 1000));
      $scope.loggedIn = true;

      $scope.notification = authData.password.email + " token expires " + (new Date(authData.expires * 1000));

      var tabsRef = ref.child(authData.uid).child("tabs");
      var sync = $firebase(tabsRef);
      $scope.tabs = sync.$asArray();

      $scope.addTab = function(tabName) {
        $scope.tabs.$add({ name: tabName })
          .then(function() { $scope.refreshTaskRefs(); })
          .then(function() { $scope.notification = "Added tab " + tabName; });
      };

      var tasksRef = [];
      var tasksSync = [];
      $scope.tasks = [];

      var tasksRootRef = ref.child(authData.uid).child("tasks");
      var tasksRootSync = $firebase(tasksRootRef);
      $scope.tasksRoot = tasksRootSync.$asObject();

      $scope.refreshTaskRefs = function() {
        angular.forEach($scope.tabs, function(tab, tabId) {
          tasksRef[tab.name] = ref.child(authData.uid).child("tasks").child(tab.name);
          tasksSync[tab.name] = $firebase(tasksRef[tab.name]);
          $scope.tasks[tab.name] = tasksSync[tab.name].$asArray();

          $scope.tasks[tab.name].$loaded().then(function() {
            $scope.refreshAllTasks();
          });

        });
      };

      $scope.tabs.$loaded().then(function () {
        $scope.refreshTaskRefs();
        //$rootScope.panes[1].select();
        angular.forEach($scope.tabs, function(tab, tabId) {
          console.log("populate " + tab.name);
          $scope.populateAllTasks(tab.name);
        });
      });

      $scope.updateTask = function(tasks, task) {
        tasks.$save(task)
          .then(function() { $scope.notification = "Changed task " + task.description; });
      }

      $scope.addTask = function(tabName, taskDone, taskDescription, taskCategory, taskDueDate) {
        taskDescription = taskDescription || "My Task";
        taskCategory = taskCategory || "~uncategorized";
        taskDueDate = taskDueDate || "soon";

        $scope.tasks[tabName].$add({ done: taskDone,
                                     description: taskDescription,
                                     category: taskCategory,
                                     createDate: (new Date()).getTime(),
                                     dueDate: taskDueDate,
                                   })
          .then(function() { $scope.notification = "Added " + tabName + "/" + taskDescription; })
          .then(function() { $scope.refreshAllTasks(); });

        $scope.taskDone = false;
        $scope.taskDescription = "";
        $scope.taskCategory = "";
        $scope.taskDueDate = "";

        $scope.$broadcast("newTaskAdded");
      };

      // tasks[tab.name].$remove(task)
      $scope.removeTask = function(tasks, task) {
        tasks.$remove(task)
          .then(function() { $scope.notification = "Removed task " + task.description; })
          .then(function() { $scope.refreshAllTasks(); });
      };

      $scope.deleteTabTasks = function(tabName) {
        tasksRootSync.$remove(tabName)
          .then(function() { $scope.notification = "Deleted tab tasks for " + tabName; })
          .then(function() { $scope.refreshAllTasks(); });
      };

      $scope.removeTab = function(tab) {
        tasksRootSync.$remove(tab.name)
          .then(function() { $scope.tabs.$remove(tab)
                             .then(function() { $scope.notification = "Removed tab " + tab.name; }); })
          .then(function() { $scope.refreshAllTasks(); });
      };

      // ARRAY FOR ALL TASKS

      $scope.allTasks = [];

      $scope.cleanAllTasks = function() {
        $scope.allTasks = [];
      }

      $scope.populateAllTasks = function(tabName) {
        angular.forEach($scope.tasks[tabName], function(task) {
          $scope.allTasks.push(task);
        });
      };

      $scope.refreshAllTasks = function() {
        $scope.cleanAllTasks();
        angular.forEach($scope.tabs, function(tab, tabId) {
          $scope.populateAllTasks(tab.name);
        });
      };

      // TIME AND MOMENT.JS

      $scope.getms = function(s) {
        var m = moment(s, "D/M/YY H:mm:ss");
        var result = m.valueOf();
        if (isNaN(result)) {
          result = 0;
        }
        return result;
      };

      $scope.getFormattedDate = function(ms) {
        var result = moment(ms).locale('pt-BR').format('ddd D-MMM-YY H:mm:ss');
        if (result === 'Invalid date') {
          result = 'data invalida';
        }
        if (ms === undefined) {
          result = "";
        }
        return result;
      };

      $scope.getShortDate = function(ms) {
        // var result = moment(ms).locale('pt-BR').format('D-MMM H:mm:ss');
        var result = moment(ms).locale('pt-BR').format('D-MMM');
        return result;
      };

      $scope.parseDate = function(s) {
        if (s === 'soon') {
          return 9999999999000;
        }
        return moment(s, "D/M/YY H:mm:ss").valueOf();
      };

      $scope.millisToString = function(ms)
      {
        if (ms < 0 || ms > 3159999999000) {
          return "∞";
        }
        var seconds = Math.floor(ms / 1000);
        var numyears = Math.floor(seconds / 31536000);
        var numdays = Math.floor((seconds % 31536000) / 86400);
        var numhours = Math.floor(((seconds % 31536000) % 86400) / 3600);
        var numminutes = Math.floor((((seconds % 31536000) % 86400) % 3600) / 60);
        var numseconds = (((seconds % 31536000) % 86400) % 3600) % 60;

        var result = "";

        if (numyears > 0) {
          result += numyears + "y ";
        }
        if (numdays > 0) {
          result += numdays + "d ";
        }
        if (numhours > 0) {
          result += numhours + "h ";
        }
        if (numminutes > 0) {
          result += numminutes + "m ";
        }
        // if (numseconds > 0) {
        //  result += numseconds + "s";
        // }
        return result;
      }

      $scope.momentNow = function() {
        return moment().valueOf();
      };

      $scope.now = $scope.momentNow();
      $scope.nowFull = moment().locale('pt-BR').format();

      $scope.dueDateOrder = function(task) {
        return $scope.parseDate(task.dueDate);
      }

      function numdays(ms) {
        var seconds = Math.floor(ms / 1000);
        var days = Math.floor(seconds / 86400);

        return days;
      }

      function daysSince01(dmyStr) {
        var dmyParts = dmyStr.split("/");
        var day = Number(dmyParts[0]);
        var month = Number(dmyParts[1]);
        var year = Number(dmyParts[2]);

        var leapYearsPassed = Math.floor(year / 4);

        if (year % 4 === 0 && month > 2) {
          leapYearsPassed -= 1;
        }

        return leapYearsPassed + (year * 365) + moment(dmyStr, "D/M/YY").dayOfYear();
      }

      // pass moment() now to a function that returns D/M/Y

      $scope.daysDiff = function(then, now) {
        // var nineteenseventy = moment("1/1/1970 0:00:00", "D/M/YYYY H:mm:ss");
        // var then_since1970 = numdays(moment(then, "D/M/YY H:mm:ss").valueOf());
        // var now_since1970 = numdays(moment().valueOf());
        // return Math.max(0, then_since1970 - now_since1970);
        // var result = daysSince01(then.split(" ")[0]) - daysSince01(moment().locale('pt-BR').format("D/M/YY"))
        var result = Math.floor((moment(then.split(" ")[0], "D/M/YY").startOf("day") - moment().startOf("day")) / 86400000);

        if (isNaN(result) || result < 0) {
          result = "";
        }

        else {
          if (result === 1) {
            return "in " + result + " day";
          } else if (result === 0) {
            return "today";
          } else {
            return "in " + result + " days";
          }
        }
      };
    }

    function clean() {
      $scope.notification = "Please log in";
      $scope.tabs = [];
      $scope.loggedIn = false;
    }

    $scope.logout = function() {
      ref.unauth();
      document.location.href = "login.html";
    }

    var authData = ref.getAuth();
    if (authData) {
      init(authData);
    } else {
      clean();
    }
  }]);

  app.directive("focusOn", function() {
    return function(scope, elem, attr) {
      scope.$on(attr.focusOn, function(e) {
        elem[0].focus();
      });
    };
  });
})();
<|endoftext|>


<commit_before>'use strict';

const navigation = require( '../src/js/navigation' );
const interpolate = require( './interpolate' );
const fs = require( 'fs' );
const path = require( 'path' );
const sitemapPath = path.join( process.cwd(), '/public/sitemap.xml' );

let content;
let extractUrls;
let add;
let getUrl;
let toSitemapUrl;
let inDomain;
let urls;

extractUrls = ( obj, urls ) => {
    let key;
    // TODO: in ES6 default can be defined above
    urls = ( typeof urls !== 'undefined' ) ? urls : [];
    for ( key in obj ) {
        if ( typeof obj[ key ] === 'string' ) {
            add( getUrl( obj[ key ] ), urls );
        } else if ( typeof obj[ key ] === 'object' ) {
            if ( obj[ key ]._self ) {
                add( getUrl( obj[ key ]._self ), urls );
            }
            extractUrls( obj[ key ], urls );
        }
    }

    return urls;
}

add = ( item, arr ) => arr.indexOf( item ) === -1 && inDomain( item ) ? arr.push( item ) : arr;

getUrl = ( url ) => interpolate( url );

inDomain = ( url ) => url.indexOf( navigation.sites[ 'enketo-main' ].substring( 8 ) ) !== -1;

toSitemapUrl = ( url ) => `
    <url>
        <loc>${url}</loc>
    </url>`;

urls = extractUrls( navigation.primary ).concat( [ navigation.sites[ 'enketo-api' ] ] );

content = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\
${urls.map( toSitemapUrl ).join( '' )}
</urlset>`;

fs.writeFile( sitemapPath, content, {}, function() {
    console.log( 'done' );
} );
<commit_msg>changed: refactored sitemap generator<commit_after>'use strict';

const navigation = require( '../src/js/navigation' );
const interpolate = require( './interpolate' );
const fs = require( 'fs' );
const path = require( 'path' );
const sitemapPath = path.join( process.cwd(), '/public/sitemap.xml' );

const getUrl = ( url ) => interpolate( url );

const inDomain = ( url ) => url.indexOf( navigation.sites[ 'enketo-main' ].substring( 8 ) ) !== -1;

const add = ( item, arr ) => arr.indexOf( item ) === -1 && inDomain( item ) ? arr.push( item ) : arr;

const extractUrls = ( obj, urls = [] ) => {
    for ( let key in obj ) {
        if ( typeof obj[ key ] === 'string' ) {
            add( getUrl( obj[ key ] ), urls );
        } else if ( typeof obj[ key ] === 'object' ) {
            if ( obj[ key ]._self ) {
                add( getUrl( obj[ key ]._self ), urls );
            }
            extractUrls( obj[ key ], urls );
        }
    }

    return urls;
};

const toSitemapUrl = ( url ) => `
    <url>
        <loc>${url}</loc>
    </url>`;

const urls = extractUrls( navigation.primary ).concat( [ navigation.sites[ 'enketo-api' ] ] );

const content = `<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\
${urls.map( toSitemapUrl ).join( '' )}
</urlset>`;

fs.writeFile( sitemapPath, content, {}, function() {
    console.log( 'done' );
} );<|endoftext|>


<commit_before>var fs = require('fs'),
    path = require('path'),
    unify = require('fayde-unify'),
    renderer = unify.renderer,
    JsonFile = unify.JsonFile,
    Library = unify.Library;

module.exports = function (grunt) {
    function getTypings(basePath, unify, isSelf) {
        grunt.verbose
            .write('Collecting typings from [')
            .write(unify.path)
            .writeln(']...');

        var typings = unify.getValue('typings') || [];
        if (isSelf) {
            typings = typings.concat(unify.getValue('devTypings') || []);
        }
        var unifyDir = path.resolve(path.dirname(unify.path));
        return typings.map(function (typing) {
            return path.relative(basePath, path.join(unifyDir, typing));
        });
    }

    function getAllDependencies(sourceLib, lib) {
        lib = lib || sourceLib;
        return lib.bower.getDependenciesSync()
            .reduce(function (agg, cur) {
                var curlib = sourceLib.createDependent(cur);
                agg.push(curlib);
                return agg
                    .concat([curlib])
                    .concat(getAllDependencies(sourceLib, curlib));
            }, []);
    }

    function verboseTypings(typings) {
        grunt.verbose.write('Typings: ')
            .writeln(grunt.log.wordlist(typings, {separator: ', ', color: 'cyan'}));
    }

    return function (basePath, unifyPath) {
        unifyPath = unifyPath == null ? basePath : unifyPath;
        var unifyDir = unifyPath == null ? process.cwd() : unifyPath;
        var unify = new JsonFile(path.join(unifyDir, 'unify.json'));
        unify.loadSync();

        var typings = getTypings(basePath, unify, true);

        var lib = new Library(unify, new renderer.Standard());
        if (!fs.existsSync(lib.bower.bowerFilepath)) {
            grunt.verbose.write('Could not find bower file [')
                .write(lib.bower.bowerFilepath)
                .writeln('].');
            verboseTypings(typings);
            return typings;
        }

        grunt.verbose.write('Collecting bower dependencies from [')
            .write(lib.bower.bowerFilepath)
            .writeln(']...');
        var allTypings = unique(getAllDependencies(lib))
            .reduce(function (agg, cur) {
                return agg.concat(getTypings(basePath, cur.unify, false));
            }, typings);
        verboseTypings(allTypings);
        return allTypings;
    };
};

function unique(arr) {
    return arr.reduce(function (agg, cur) {
        if (agg.indexOf(cur.name) > -1)
            return agg;
        return agg.concat([cur]);
    }, []);
}
<commit_msg>Adding OK logs and fixing unique.<commit_after>var fs = require('fs'),
    path = require('path'),
    unify = require('fayde-unify'),
    renderer = unify.renderer,
    JsonFile = unify.JsonFile,
    Library = unify.Library;

module.exports = function (grunt) {
    function getTypings(basePath, unify, isSelf) {
        grunt.verbose
            .write('Collecting typings from [')
            .write(unify.path)
            .writeln(']...');

        var typings = unify.getValue('typings') || [];
        if (isSelf) {
            typings = typings.concat(unify.getValue('devTypings') || []);
        }
        var unifyDir = path.resolve(path.dirname(unify.path));
        var rv = typings.map(function (typing) {
            return path.relative(basePath, path.join(unifyDir, typing));
        });
        grunt.verbose.ok();
        return rv;
    }

    function getAllDependencies(sourceLib, lib) {
        lib = lib || sourceLib;
        return lib.bower.getDependenciesSync()
            .reduce(function (agg, cur) {
                var curlib = sourceLib.createDependent(cur);
                agg.push(curlib);
                return agg
                    .concat([curlib])
                    .concat(getAllDependencies(sourceLib, curlib));
            }, []);
    }

    function verboseTypings(typings) {
        grunt.verbose.write('Typings: ')
            .writeln(grunt.log.wordlist(typings, {separator: ', ', color: 'cyan'}));
    }

    return function (basePath, unifyPath) {
        unifyPath = unifyPath == null ? basePath : unifyPath;
        var unifyDir = unifyPath == null ? process.cwd() : unifyPath;
        var unify = new JsonFile(path.join(unifyDir, 'unify.json'));
        unify.loadSync();

        var typings = getTypings(basePath, unify, true);

        var lib = new Library(unify, new renderer.Standard());
        if (!fs.existsSync(lib.bower.bowerFilepath)) {
            grunt.verbose.write('Could not find bower file [')
                .write(lib.bower.bowerFilepath)
                .writeln('].');
            verboseTypings(typings);
            return typings;
        }

        grunt.verbose.write('Collecting bower dependencies from [')
            .write(lib.bower.bowerFilepath)
            .write(']...');
        var allTypings = unique(getAllDependencies(lib))
            .reduce(function (agg, cur) {
                return agg.concat(getTypings(basePath, cur.unify, false));
            }, typings);
        grunt.verbose.ok();
        verboseTypings(allTypings);
        return allTypings;
    };
};

function unique(arr) {
    return arr.reduce(function (agg, cur) {
        return (agg.some(function (check) {
            return check.name === cur.name;
        })) ? agg : agg.concat([cur]);
    }, []);
}
<|endoftext|>


<commit_before>"use strict";

describe('history', function() {
  var mockConfigurator = {
    getConfAndDelegate: function() {},
    configurationFor: function() { return {}; },
    getRetrievers: function() { return {}; },
    provideResource: function() {}
  };

  var mockKC = {
    initCaptures: function() { return {}; },
  };

  beforeEach(module("arethusa.core"));

  beforeEach(module("arethusa.hist", function($provide) {
    $provide.value('configurator', mockConfigurator);
    $provide.value('keyCapture', mockKC);
  }));

  var history, state;
  var undone, redone;
  beforeEach(inject(function(_history_, _state_) {
    history = _history_;
    state   = _state_;
    state.silent = false; // true by default
    history.init();
    undone = 0;
    redone = 0;
  }));

  function MockEvent(type) {
    this.exec = function() { redone++; };
    this.undo = function() { undone++; };
    this.type = type;
  }

  describe('this.canUndo', function() {
    it('is false on init', function() {
      expect(history.canUndo).toBeFalsy();
    });

    it('is true when element to undo is present', function() {
      history.saveEvent(new MockEvent());
      expect(history.canUndo).toBeTruthy();
    });

    it('is false when elements are present but we traversed the whole history', function() {
      history.saveEvent(new MockEvent());
      history.undo();
      expect(history.canUndo).toBeFalsy();
    });

    it('is true when we are on the end of the history and redo a step', function() {
      history.saveEvent(new MockEvent());
      history.undo();
      expect(history.canUndo).toBeFalsy();
      history.redo();
      expect(history.canUndo).toBeTruthy();
    });
  });

  describe('this.canRedo', function() {
    it('is false on init', function() {
      history.init();
      expect(history.canRedo).toBeFalsy();
    });

    it('is true after we have undone an event', function() {
      history.saveEvent(new MockEvent());
      expect(history.canRedo).toBeFalsy();
      history.undo();
      expect(history.canRedo).toBeTruthy();
    });

    it('is false when we are at the beginning of the history chain again', function() {
      history.saveEvent(new MockEvent());
      expect(history.canRedo).toBeFalsy();
      history.undo();
      expect(history.canRedo).toBeTruthy();
      history.redo();
      expect(history.canRedo).toBeFalsy();
    });
  });

  describe('this.undo()', function() {
    it('calls undo function of current event in history', function() {
      history.saveEvent(new MockEvent());
      expect(undone).toEqual(0);
      history.undo();
      expect(undone).toEqual(1);
    });

    it('calls the undo function in state.silent mode', function() {
      var silentMode = true;
      // An undo function usually triggers a tokenChange
      state.on('tokenChange', function() { silentMode = false; });
      history.saveEvent(new MockEvent());
      history.undo();
      expect(silentMode).toBeTruthy();
    });
  });

  describe('this.redo()', function() {
    it('calls exec function of an undone element', function() {
      expect(undone).toEqual(0);
      expect(redone).toEqual(0);
      history.saveEvent(new MockEvent());

      history.undo();
      expect(undone).toEqual(1);
      history.redo();
      expect(redone).toEqual(1);
    });
  });

  describe('this.save()', function() {
    it('saves an event to the history', function() {
      expect(history.events.length).toEqual(0);
      history.saveEvent(new MockEvent());
      expect(history.events.length).toEqual(1);
    });

    it('does not save events in state.silent mode', function() {
      expect(history.events.length).toEqual(0);
      state.silent = true;
      history.saveEvent(new MockEvent());
      expect(history.events.length).toEqual(0);
    });

    it('never saves more items than defined throught history.maxSize', function() {
      history.maxSize = 2;
      history.saveEvent(new MockEvent());
      history.saveEvent(new MockEvent());
      expect(history.events.length).toEqual(2);
      history.saveEvent(new MockEvent());
      expect(history.events.length).toEqual(2);
    });

    it('pops the oldest history event when maxSize is reached', function() {
      var a, b, c;
      a = new MockEvent();
      b = new MockEvent();
      c = new MockEvent();

      history.maxSize = 2;

      history.saveEvent(a);
      history.saveEvent(b);
      expect(history.events).toContain(a);
      expect(history.events).toContain(b);

      history.saveEvent(c);
      expect(history.events).not.toContain(a);
      expect(history.events).toContain(b);
      expect(history.events).toContain(c);
    });

    it('does not act like a tree', function() {
      var a, b, c, d;
      a = new MockEvent();
      b = new MockEvent();
      c = new MockEvent();
      d = new MockEvent();

      history.saveEvent(a);
      history.saveEvent(b);
      history.saveEvent(c);

      history.undo(); // we're now at b again

      history.saveEvent(d);
      expect(history.events).toContain(a);
      expect(history.events).toContain(b);
      expect(history.events).not.toContain(c);
      expect(history.events).toContain(d);
    });
  });

  describe('watches', function() {
    it('all events issued through state.change and saves them', function() {
      var event = { property: 'head.id', newVal: 1, oldVal: 2 };

      expect(history.events.length).toEqual(0);
      state.change({}, 'head.id', 1, 2);
      expect(history.events.length).toEqual(1);
    });

    it('all tokenAdded events', function() {
      expect(history.events.length).toEqual(0);
      state.broadcast('tokenAdded', {});
      expect(history.events.length).toEqual(1);
    });

    it('all tokenRemoved events', function() {
      expect(history.events.length).toEqual(0);
      state.broadcast('tokenRemoved', {});
      expect(history.events.length).toEqual(1);
    });
  });
});

<commit_msg>Start to arethusaMocks for history specs<commit_after>"use strict";

describe('history', function() {
  var mockKC = {
    initCaptures: function() { return {}; },
  };

  beforeEach(module("arethusa.core"));

  beforeEach(module("arethusa.hist", function($provide) {
    $provide.value('configurator', arethusaMocks.configurator());
    $provide.value('keyCapture', mockKC);
  }));

  var history, state;
  var undone, redone;
  beforeEach(inject(function(_history_, _state_) {
    history = _history_;
    state   = _state_;
    state.silent = false; // true by default
    history.init();
    undone = 0;
    redone = 0;
  }));

  function MockEvent(type) {
    this.exec = function() { redone++; };
    this.undo = function() { undone++; };
    this.type = type;
  }

  describe('this.canUndo', function() {
    it('is false on init', function() {
      expect(history.canUndo).toBeFalsy();
    });

    it('is true when element to undo is present', function() {
      history.saveEvent(new MockEvent());
      expect(history.canUndo).toBeTruthy();
    });

    it('is false when elements are present but we traversed the whole history', function() {
      history.saveEvent(new MockEvent());
      history.undo();
      expect(history.canUndo).toBeFalsy();
    });

    it('is true when we are on the end of the history and redo a step', function() {
      history.saveEvent(new MockEvent());
      history.undo();
      expect(history.canUndo).toBeFalsy();
      history.redo();
      expect(history.canUndo).toBeTruthy();
    });
  });

  describe('this.canRedo', function() {
    it('is false on init', function() {
      history.init();
      expect(history.canRedo).toBeFalsy();
    });

    it('is true after we have undone an event', function() {
      history.saveEvent(new MockEvent());
      expect(history.canRedo).toBeFalsy();
      history.undo();
      expect(history.canRedo).toBeTruthy();
    });

    it('is false when we are at the beginning of the history chain again', function() {
      history.saveEvent(new MockEvent());
      expect(history.canRedo).toBeFalsy();
      history.undo();
      expect(history.canRedo).toBeTruthy();
      history.redo();
      expect(history.canRedo).toBeFalsy();
    });
  });

  describe('this.undo()', function() {
    it('calls undo function of current event in history', function() {
      history.saveEvent(new MockEvent());
      expect(undone).toEqual(0);
      history.undo();
      expect(undone).toEqual(1);
    });

    it('calls the undo function in state.silent mode', function() {
      var silentMode = true;
      // An undo function usually triggers a tokenChange
      state.on('tokenChange', function() { silentMode = false; });
      history.saveEvent(new MockEvent());
      history.undo();
      expect(silentMode).toBeTruthy();
    });
  });

  describe('this.redo()', function() {
    it('calls exec function of an undone element', function() {
      expect(undone).toEqual(0);
      expect(redone).toEqual(0);
      history.saveEvent(new MockEvent());

      history.undo();
      expect(undone).toEqual(1);
      history.redo();
      expect(redone).toEqual(1);
    });
  });

  describe('this.save()', function() {
    it('saves an event to the history', function() {
      expect(history.events.length).toEqual(0);
      history.saveEvent(new MockEvent());
      expect(history.events.length).toEqual(1);
    });

    it('does not save events in state.silent mode', function() {
      expect(history.events.length).toEqual(0);
      state.silent = true;
      history.saveEvent(new MockEvent());
      expect(history.events.length).toEqual(0);
    });

    it('never saves more items than defined throught history.maxSize', function() {
      history.maxSize = 2;
      history.saveEvent(new MockEvent());
      history.saveEvent(new MockEvent());
      expect(history.events.length).toEqual(2);
      history.saveEvent(new MockEvent());
      expect(history.events.length).toEqual(2);
    });

    it('pops the oldest history event when maxSize is reached', function() {
      var a, b, c;
      a = new MockEvent();
      b = new MockEvent();
      c = new MockEvent();

      history.maxSize = 2;

      history.saveEvent(a);
      history.saveEvent(b);
      expect(history.events).toContain(a);
      expect(history.events).toContain(b);

      history.saveEvent(c);
      expect(history.events).not.toContain(a);
      expect(history.events).toContain(b);
      expect(history.events).toContain(c);
    });

    it('does not act like a tree', function() {
      var a, b, c, d;
      a = new MockEvent();
      b = new MockEvent();
      c = new MockEvent();
      d = new MockEvent();

      history.saveEvent(a);
      history.saveEvent(b);
      history.saveEvent(c);

      history.undo(); // we're now at b again

      history.saveEvent(d);
      expect(history.events).toContain(a);
      expect(history.events).toContain(b);
      expect(history.events).not.toContain(c);
      expect(history.events).toContain(d);
    });
  });

  describe('watches', function() {
    it('all events issued through state.change and saves them', function() {
      var event = { property: 'head.id', newVal: 1, oldVal: 2 };

      expect(history.events.length).toEqual(0);
      state.change({}, 'head.id', 1, 2);
      expect(history.events.length).toEqual(1);
    });

    it('all tokenAdded events', function() {
      expect(history.events.length).toEqual(0);
      state.broadcast('tokenAdded', {});
      expect(history.events.length).toEqual(1);
    });

    it('all tokenRemoved events', function() {
      expect(history.events.length).toEqual(0);
      state.broadcast('tokenRemoved', {});
      expect(history.events.length).toEqual(1);
    });
  });
});

<|endoftext|>


<commit_before>// ==UserScript==
// @name                SmartyFace
// @description        Text Prediction on facepunch
// @author                benjojo
// @namespace        http://facepunch.com
// @include                http://facepunch.com/*
// @include         http://www.facepunch.com/*
// @include                https://facepunch.com/*
// @include         https://www.facepunch.com/*
// @version         1
// ==/UserScript==
var s=document.createElement('script');
s.setAttribute('type','text/javascript');
s.innerHTML='$(document).ready(function(){function b(a){a=$(".cke_enable_context_menu");if(a[0].parentNode){var e=a[0].parentNode;if(!c){$(e).prepend(\'Type Reply Here\');var d=a[0];$(a[0]).keypress(function(a){a=$(d).val();$.post(f,{post:a},function(a){$("#SmartyFace").html($(d).val()+a)})});c=!0}}else setTimeout(b,1500)}var f="http://text.nsa.me.uk/pose",c=!1;setTimeout(b,1500)});';
var a = document.body.appendChild(s);
console.log(a);

// $( document ).ready(function() {
//         var endPoint = "http://text.nsa.me.uk/pose";
//         var tagged = false;
//         function findTextBoxes (argument) {
//                 var boxes = $('.cke_enable_context_menu');
//                 if(!boxes[0].parentNode) {
//                         setTimeout(findTextBoxes,1500);
//                 } else {
//                         var parent = boxes[0].parentNode;
//                         if(!tagged) {
//                                 $(parent).prepend("Type Reply Here");
//                                 var textarea = boxes[0];
//                                 $(boxes[0]).keypress(function(a) {
//                                         var text = $(textarea).val();
//                                         $.post( endPoint, { post: text }, function( data ) {
//                                                 $('#SmartyFace').html( $(textarea).val()+data );
//                                         });
//                                 });
//                                 tagged = true;
//                         }

//                 }
//         }
//         setTimeout(findTextBoxes,1500);
// });<commit_msg>Oh my god it works<commit_after>// ==UserScript==
// @name                SmartyFace
// @description        Text Prediction on facepunch
// @author                benjojo
// @namespace        http://facepunch.com
// @include                http://facepunch.com/*
// @include         http://www.facepunch.com/*
// @include                https://facepunch.com/*
// @include         https://www.facepunch.com/*
// @version         1.0.1
// ==/UserScript==
var s=document.createElement('script');
s.setAttribute('type','text/javascript');
s.innerHTML='$(document).ready(function(){function b(a){a=$(".cke_enable_context_menu");if(a[0].parentNode){var e=a[0].parentNode;if(!c){$(e).prepend(\'Type Reply Here\');var d=a[0];$(a[0]).keypress(function(a){a=$(d).val();$.post(f,{post:a},function(a){$("#SmartyFace").html($(d).val()+a)})});c=!0}}else setTimeout(b,1500)}var f="http://text.nsa.me.uk/pose",c=!1;setTimeout(b,1500)});';
var a = document.body.appendChild(s);
console.log(a);

// $( document ).ready(function() {
//         var endPoint = "http://text.nsa.me.uk/pose";
//         var tagged = false;
//         function findTextBoxes (argument) {
//                 var boxes = $('.cke_enable_context_menu');
//                 if(!boxes[0].parentNode) {
//                         setTimeout(findTextBoxes,1500);
//                 } else {
//                         var parent = boxes[0].parentNode;
//                         if(!tagged) {
//                                 $(parent).prepend("Type Reply Here");
//                                 var textarea = boxes[0];
//                                 $(boxes[0]).keypress(function(a) {
//                                         var text = $(textarea).val();
//                                         $.post( endPoint, { post: text }, function( data ) {
//                                                 $('#SmartyFace').html( $(textarea).val()+data );
//                                         });
//                                 });
//                                 tagged = true;
//                         }

//                 }
//         }
//         setTimeout(findTextBoxes,1500);
// });<|endoftext|>


<commit_before>if (typeof define !== 'function') {
    var define = require('amdefine')(module);
}

define(["require","../deep", "../deep-unit"], function (require, deep, Unit) {

    //_______________________________________________________________ GENERIC STORE TEST CASES

    var unit = {
        title:"deep/units/context",
        stopOnError:false,
        setup:function(){},
        tests : {
            setvar:function(){
                deep.context = {};
                var p1 = deep(9999)
                .context("test",1)
                .done(function(){
                    return deep.context.test;
                })
                .equal(1)
                .done(function(){
                    return this.context().test;
                })
                .equal(1);
                var p2 = deep(deep.context).equal({});
                return deep.all(p1,p2);
            },
            setvar2:function(){
                deep.context = {};
                var p1 = deep(9999)
                .context("test",1)
                .done(function(){
                    return deep(true)
                    .context("hello","world")
                    .done(function(){
                        return deep.context;
                    })
                    .equal({test:1,hello:"world"});
                })
                .done(function(){
                    return deep.context;
                })
                .equal({test:1});
                var p2 = deep(deep.context).equal({});
                return deep.all(p1,p2);
            },
            delayed:function(){
                deep.context = {};
                var p1 = deep(9999)
                .context("test",1)
                .delay(3)
                .done(function(){
                    return deep.context;
                })
                .equal({test:1});

                var p2 = deep(9999)
                .context("test",2)
                .delay(9)
                .done(function(){
                    return deep.context;
                })
                .equal({test:2});

                var p3 = deep(9999)
                .context("test",3)
                .delay(6)
                .done(function(){
                    return deep.context;
                })
                .equal({test:3});

                var p4 = deep(deep.context).equal({});
                return deep.all(p1,p2,p3,p4);
            }
        }
    };

    return new Unit(unit);
});
<commit_msg>add clean in context testcases<commit_after>if (typeof define !== 'function') {
    var define = require('amdefine')(module);
}

define(["require","../deep", "../deep-unit"], function (require, deep, Unit) {

    //_______________________________________________________________ GENERIC STORE TEST CASES

    var unit = {
        title:"deep/units/context",
        stopOnError:false,
        setup:function(){},
        clean:function(){
            deep.context = {};
        },
        tests : {
            setvar:function(){
                deep.context = {};
                var p1 = deep(9999)
                .context("test",1)
                .done(function(){
                    return deep.context.test;
                })
                .equal(1)
                .done(function(){
                    return this.context().test;
                })
                .equal(1);
                var p2 = deep(deep.context).equal({});
                return deep.all(p1,p2);
            },
            setvar2:function(){
                deep.context = {};
                var p1 = deep(9999)
                .context("test",1)
                .done(function(){
                    return deep(true)
                    .context("hello","world")
                    .done(function(){
                        return deep.context;
                    })
                    .equal({test:1,hello:"world"});
                })
                .done(function(){
                    return deep.context;
                })
                .equal({test:1});
                var p2 = deep(deep.context).equal({});
                return deep.all(p1,p2);
            },
            delayed:function(){
                deep.context = {};
                var p1 = deep(9999)
                .context("test",1)
                .delay(3)
                .done(function(){
                    return deep.context;
                })
                .equal({test:1});

                var p2 = deep(9999)
                .context("test",2)
                .delay(9)
                .done(function(){
                    return deep.context;
                })
                .equal({test:2});

                var p3 = deep(9999)
                .context("test",3)
                .delay(6)
                .done(function(){
                    return deep.context;
                })
                .equal({test:3});

                var p4 = deep(deep.context).equal({});
                return deep.all(p1,p2,p3,p4);
            }
        }
    };

    return new Unit(unit);
});
<|endoftext|>


<commit_before>var utils = require('../utils/functions');
var debug = require('debug')('bookitsimon:flightdata');
var config = require("config");
var request = require('request');
var fs = require("fs");

module.exports = {
	getSample: function(req, res, next){
		var payload = {
			departureFlight: {
				origin: "DCA",
		        destination: "SEA",
		        date: "2015-05-08",
		        permittedDepartureTime: {
		          earliestTime: "10:00",
		          latestTime: "12:00"
		        }
			},
			returnFlight: {
				origin: "SEA",
		        destination: "DCA",
		        date: "2015-05-21",
		        permittedDepartureTime: {
		          earliestTime: "10:00",
		          latestTime: "12:00"
		        }
			},
			passengers: {
				adult: 1
			},
			solutions: 10,
			maxPrice: "USD1000.00",
			refundable: false
		};
		debug("Getting sample");
		res.json(payload);
	},
	search: function(req, res, next){
		var body = utils.trimBody(req.body);
		if(!utils.validateBody(body)){
			debug("Body not valid");
			res.json({
				error: true,
				message: "body is missing required fields. Check http://localhost:3000/sample for a sample payload."
			});
			return;
		}

		var requestData = {
			request: {
				slice: [
					{
						origin: body["departureFlight.origin"] ,
						destination: body["departureFlight.destination"],
						date: body["departureFlight.date"],
						preferredCabin: (body["departureFlight.preferredCabin"]) ? body["departureFlight.preferredCabin"] : "COACH",
						permittedDepartureTime: {
							earliestTime: (body["departureFlight.permittedDepartureTime"] && body["departureFlight.permittedDepartureTime.earliestTime"]) ? body["departureFlight.permittedDepartureTime.earliestTime"] : "10:00",
							latestTime: (body["departureFlight.latestTime"] && body["departureFlight.permittedDepartureTime.latestTime"]) ? body["departureFlight.permittedDepartureTime.latestTime"] : "12:00"
						}
					},
					{
						origin: body["returnFlight.origin"],
						destination: body["returnFlight.destination"],
						date: body["returnFlight.date"],
						preferredCabin: (body["returnFlight.preferredCabin"]) ? body["returnFlight.preferredCabin"] : "COACH",
						permittedDepartureTime: {
							earliestTime: (body["returnFlight.permittedDepartureTime"] && body["returnFlight.permittedDepartureTime.earliestTime"]) ? body["returnFlight.permittedDepartureTime.earliestTime"] : "10:00",
							latestTime: (body["returnFlight.latestTime"] && body["returnFlight.permittedDepartureTime.latestTime"]) ? body["returnFlight.permittedDepartureTime.latestTime"] : "12:00"
						}
					}
				],
			    passengers: {
			      adultCount: (body["passengers.adultCount"]) ? parseInt(body["passengers.adultCount"]) : 1,
			      infantInLapCount: 0,
			      infantInSeatCount: 0,
			      childCount: 0,
			      seniorCount: 0
			    },
			    solutions: (body["passengers.solutions"]) ? parseInt(body["passengers.solutions"]) : 2,
			    maxPrice: (body["passengers.maxPrice"]) ? body["passengers.maxPrice "]: "USD1000.00",
			    refundable: (body["passengers.refundable"]) ? Boolean(body["passengers.refundable"]) : false
			}
		}

		debug("request:", JSON.stringify(requestData));

		var options = {
			url: [config.googleApi.url, "?key=", config.googleApi.apiKey].join(""),
			body: requestData,
			headers: {
				"Content-Type": config.googleApi.contentType
			},
			json: true
		};

		/*request.post(options, function(err, response, body) {
		  	res.json(body);
		});*/

		var theData = JSON.parse(fs.readFileSync('./flightdata/flightdata-2.json'));

		var results = [
			{
				carrier: "US",
				fare: "USD1000",
				origDep: "DCA",
				origFlightime: "11:25 am",
				origDest: "SEA",
				origDepTime: "05:03 pm",
				origDuration: "8h 38m",
				retDep: "DCA",
				retFlightime: "11:25 am",
				retDest: "SEA",
				retDepTime: "05:03 pm",
				retDuration: "8h 38m"
			},
			{
				carrier: "US",
				fare: "USD1000",
				origDep: "DCA",
				origFlightime: "11:25 am",
				origDest: "SEA",
				origDepTime: "05:03 pm",
				origDuration: "8h 38m",
				retDep: "DCA",
				retFlightime: "11:25 am",
				retDest: "SEA",
				retDepTime: "05:03 pm",
				retDuration: "8h 38m"
			}
		];
		res.render('flightdata', {
			flightdata: results
		});
	}

}

<commit_msg>Updated data<commit_after>var utils = require('../utils/functions');
var debug = require('debug')('bookitsimon:flightdata');
var config = require("config");
var request = require('request');
var fs = require("fs");

module.exports = {
	getSample: function(req, res, next){
		var payload = {
			departureFlight: {
				origin: "DCA",
		        destination: "SEA",
		        date: "2015-05-08",
		        permittedDepartureTime: {
		          earliestTime: "10:00",
		          latestTime: "12:00"
		        }
			},
			returnFlight: {
				origin: "SEA",
		        destination: "DCA",
		        date: "2015-05-21",
		        permittedDepartureTime: {
		          earliestTime: "10:00",
		          latestTime: "12:00"
		        }
			},
			passengers: {
				adult: 1
			},
			solutions: 10,
			maxPrice: "USD1000.00",
			refundable: false
		};
		debug("Getting sample");
		res.json(payload);
	},
	search: function(req, res, next){
		var body = utils.trimBody(req.body);
		if(!utils.validateBody(body)){
			debug("Body not valid");
			res.json({
				error: true,
				message: "body is missing required fields. Check http://localhost:3000/sample for a sample payload."
			});
			return;
		}

		var requestData = {
			request: {
				slice: [
					{
						origin: body["departureFlight.origin"] ,
						destination: body["departureFlight.destination"],
						date: body["departureFlight.date"],
						preferredCabin: (body["departureFlight.preferredCabin"]) ? body["departureFlight.preferredCabin"] : "COACH",
						permittedDepartureTime: {
							earliestTime: (body["departureFlight.permittedDepartureTime"] && body["departureFlight.permittedDepartureTime.earliestTime"]) ? body["departureFlight.permittedDepartureTime.earliestTime"] : "10:00",
							latestTime: (body["departureFlight.latestTime"] && body["departureFlight.permittedDepartureTime.latestTime"]) ? body["departureFlight.permittedDepartureTime.latestTime"] : "12:00"
						}
					},
					{
						origin: body["returnFlight.origin"],
						destination: body["returnFlight.destination"],
						date: body["returnFlight.date"],
						preferredCabin: (body["returnFlight.preferredCabin"]) ? body["returnFlight.preferredCabin"] : "COACH",
						permittedDepartureTime: {
							earliestTime: (body["returnFlight.permittedDepartureTime"] && body["returnFlight.permittedDepartureTime.earliestTime"]) ? body["returnFlight.permittedDepartureTime.earliestTime"] : "10:00",
							latestTime: (body["returnFlight.latestTime"] && body["returnFlight.permittedDepartureTime.latestTime"]) ? body["returnFlight.permittedDepartureTime.latestTime"] : "12:00"
						}
					}
				],
			    passengers: {
			      adultCount: (body["passengers.adultCount"]) ? parseInt(body["passengers.adultCount"]) : 1,
			      infantInLapCount: 0,
			      infantInSeatCount: 0,
			      childCount: 0,
			      seniorCount: 0
			    },
			    solutions: (body["passengers.solutions"]) ? parseInt(body["passengers.solutions"]) : 2,
			    maxPrice: (body["passengers.maxPrice"]) ? body["passengers.maxPrice "]: "USD1000.00",
			    refundable: (body["passengers.refundable"]) ? Boolean(body["passengers.refundable"]) : false
			}
		}

		debug("request:", JSON.stringify(requestData));

		var options = {
			url: [config.googleApi.url, "?key=", config.googleApi.apiKey].join(""),
			body: requestData,
			headers: {
				"Content-Type": config.googleApi.contentType
			},
			json: true
		};

		/*request.post(options, function(err, response, body) {
		  	res.json(body);
		});*/

		var theData = JSON.parse(fs.readFileSync('./flightdata/flightdata-2.json'));

		var results = [
			{
				carrier: "US",
				fare: "USD1000.00",
				origDep: "DCA",
				origFlightime: "11:25 am",
				origDest: "SEA",
				origDepTime: "05:03 pm",
				origDuration: "8h 38m",
				retDep: "DCA",
				retFlightime: "11:25 am",
				retDest: "SEA",
				retDepTime: "05:03 pm",
				retDuration: "8h 38m"
			},
			{
				carrier: "ASA",
				fare: "USD764.00",
				origDep: "DCA",
				origFlightime: "08:25 am",
				origDest: "SEA",
				origDepTime: "02:25 pm",
				origDuration: "5h 38m",
				retDep: "DCA",
				retFlightime: "2:27 pm",
				retDest: "SEA",
				retDepTime: "05:03 pm",
				retDuration: "4h 38m"
			}
		];
		res.render('flightdata', {
			flightdata: results
		});
	}

}

<|endoftext|>


<commit_before>/**
 * These rules enforce the Hack Reactor Style Guide
 *
 * Visit this repo for more information:
 *   https://github.com/reactorcore/eslint-config-hackreactor
 */

module.exports = {
  extends: './node_modules/eslint-config-hackreactor/index.js'
};<commit_msg>Newline in .eslintrc.js<commit_after>/**
 * These rules enforce the Hack Reactor Style Guide
 *
 * Visit this repo for more information:
 *   https://github.com/reactorcore/eslint-config-hackreactor
 */

module.exports = {
  extends: './node_modules/eslint-config-hackreactor/index.js'
};
<|endoftext|>


<commit_before>module.exports = {
    "extends": "tui",
    "parserOptions": {
        "ecmaVersion": 3
    },
    "env": {
        "browser": true,
        "jasmine": true,
        "jquery": true,
        "commonjs": true
    },
    "globals": {
        "tui": true,
        "loadFixtures": true
    }
};
<commit_msg>Update eslint Rule<commit_after>module.exports = {
    "extends": "tui",
    "parserOptions": {
        "ecmaVersion": 3
    },
    "env": {
        "browser": true,
        "jasmine": true,
        "jquery": true,
        "commonjs": true
    },
    "globals": {
        "tui": true,
        "loadFixtures": true
    },
    'rules': {
        'indent': [2, 4, {'SwitchCase': 1, 'ignoreComments': false, 'ImportDeclaration': 1, 'flatTernaryExpressions': false}]
    }
};
<|endoftext|>


<commit_before>module.exports = {
    "extends": "elm"
};
<commit_msg>add no-shadow disable<commit_after>module.exports = {
    "extends": "elm",
	rules: {
		"no-shadow": "off"
	}
};
<|endoftext|>


<commit_before>module.exports = {
  env: {
    node: true,
  },
  extends: ['eslint:recommended'],
  parserOptions: {
    ecmaVersion: 10,
    sourceType: 'module',
  },
  plugins: [],
  rules: {},
  settings: {},
  globals: {
    after: false,
    afterEach: false,
    before: false,
    browser: false,
    describe: false,
    beforeEach: false,
    it: false,
  },
}
<commit_msg>Fix eslint warnings<commit_after>module.exports = {
  es6: true,
  env: {
    node: true,
  },
  extends: ['eslint:recommended'],
  parserOptions: {
    ecmaVersion: 10,
    sourceType: 'module',
  },
  plugins: [],
  rules: {},
  settings: {},
  globals: {
    after: false,
    afterEach: false,
    before: false,
    browser: false,
    describe: false,
    beforeEach: false,
    it: false,
  },
}
<|endoftext|>


<commit_before>{
  "extends": ["frost-standard"]
}<commit_msg>Resolve incorrect content/format<commit_after>module.exports = {
  extends: ['frost-standard']
}
<|endoftext|>