<commit_before>function createTracker() {
  $('.dup-warn').hide();

  dname = $('#devicename').val();
  var dmac = '';
  $( ".devicemac" ).find('input').each(function(i,o){
    dmac = dmac + $(this).val().toUpperCase();
  });

  // Check whether MAC already exists in the db if not create a new Tracker
  if (validateMAC() === true) {
    $.get('/api/tracker/findmac/' + dmac).done(function(res){
      if (res.length === 0) {
        $.post('/api/tracker/create', { name: dname, device: {mac: dmac} });
      } else {
        $('.dup-warn').show();}
    });
  }
}

function validateMAC() {
  var regex = /^[0-9A-Fa-f]{2}$/;
  var valid = true;

  $( ".devicemac" ).find('input').each(function(i,o){
    var validmac = regex.test($(this).val());
    if (!validmac){
      $(this).addClass("incorrect-mac");
      valid = valid && false;
    } else {
      $(this).removeClass("incorrect-mac");
    }
  });
  return valid;
}

//function to create new resource

function createResource(){

	var resName = $('#resourceid').val();
	var resCat = $('#resource_cat').val();

	$.post('/api/resources/create', {name : resName, icon : resCat, marker : '', attributes : []});
}

function initialize() {

  map = initializeMap();

  var header = $('.content-header > h1').text();

  if(/Dashboard/.test(header)){
    drawLocations(map);
  }
  else if(/Path Analyzer/.test(header)){
    var id = $('.content-header').attr('trackerid');
    drawTrails(map, id);

  }

}

function setMarker(res, map){
  getNameFromId(res._id, function(name){
    var latLng = markerCoords(res);
    var marker = new google.maps.Marker({
      position: latLng,
      map: map,
      title: name
    });
  });
}

function setPath(res, map){
	getNameFromId(res.id, function(name){
	var latLng = new google.maps.LatLng(res.data[0], res.data[1]);
    var marker = new google.maps.Marker({
      position: latLng,
      map: map,
      title: name
    });
  });
}

function getNameFromId(id, cb){
  $.get('/api/tracker/'+id).done(function(res){
  	cb(res[0].name);
  });
}

function initializeMap(){

  var mylatlng = new google.maps.LatLng(6.9344, 79.8428); // Should find a way to automatically set the focus
  var mapProp = {
    center: mylatlng,
    zoom:7,
    mapTypeId:google.maps.MapTypeId.ROADMAP
  };

  var map = new google.maps.Map($("#googleMap")[0], mapProp);

  return map;
}

function drawTrails(map, id){

	var pathCoords = [];

	requestStr = '/api/tracker/' + id + '/location/data';

	$.get(requestStr).done(function(res){
		for(var i = 0; i < res.length; i++){
			setPath(res[i], map);
			pathCoords.push(new google.maps.LatLng(res[i].data[0], res[i].data[1]));
		}

		var path = new google.maps.Polyline({
			path : pathCoords,
			geodesic : true,
			strokeColor: '#0000FF',
			strokeOpacity: 1.0,
			strokeWeight: 2
	  	});

		path.setMap(map);

	});
}

function markerCoords(res) {
  return new google.maps.LatLng(res.path[res.path.length - 1].latitude, res.path[res.path.length - 1].longitude);
}

function drawLocations(map){

  $.get('/api/tracker/locations').done(function(res){
    var bounds = new google.maps.LatLngBounds();
    console.log("Got locations: ", res);
    for(var i=0; i<res.length; i++){
      setMarker(res[i], map);
      bounds.extend(markerCoords(res[i]));
    }
    console.log("Fitting map to bounds: ", bounds);
    map.fitBounds(bounds);
  });

}

function listTrackers(){

    $.get('/api/trackers').done(function(res){

        var list = '';

        for(var i = 0; i < res.length; i++){
        	list += '
 ' + res[i].name + '
';
        }

    	$('#trackers').html(list);

    });

}

$('document').ready(function(){

	$('.col-xs-2').keyup(function(){
		if ($(this).children().val().length == 2){
    			$(this).next('.col-xs-2').children().focus();
    		}
	 });

});

listTrackers();

google.maps.event.addDomListener(window, 'load', initialize);

<commit_msg>Show information about tracker when clicked on<commit_after>function createTracker() {
  $('.dup-warn').hide();

  dname = $('#devicename').val();
  var dmac = '';
  $( ".devicemac" ).find('input').each(function(i,o){
    dmac = dmac + $(this).val().toUpperCase();
  });

  // Check whether MAC already exists in the db if not create a new Tracker
  if (validateMAC() === true) {
    $.get('/api/tracker/findmac/' + dmac).done(function(res){
      if (res.length === 0) {
        $.post('/api/tracker/create', { name: dname, device: {mac: dmac} });
      } else {
        $('.dup-warn').show();}
    });
  }
}

function validateMAC() {
  var regex = /^[0-9A-Fa-f]{2}$/;
  var valid = true;

  $( ".devicemac" ).find('input').each(function(i,o){
    var validmac = regex.test($(this).val());
    if (!validmac){
      $(this).addClass("incorrect-mac");
      valid = valid && false;
    } else {
      $(this).removeClass("incorrect-mac");
    }
  });
  return valid;
}

//function to create new resource

function createResource(){

	var resName = $('#resourceid').val();
	var resCat = $('#resource_cat').val();

	$.post('/api/resources/create', {name : resName, icon : resCat, marker : '', attributes : []});
}

function initialize() {

  map = initializeMap();

  var header = $('.content-header > h1').text();

  if(/Dashboard/.test(header)){
    drawLocations(map);
  }
  else if(/Path Analyzer/.test(header)){
    var id = $('.content-header').attr('trackerid');
    drawTrails(map, id);

  }

}

function setMarker(res, map){
  getTrackerFromId(res._id, function(tracker){
    var name = tracker.name;
    var latLng = markerCoords(res);
    var marker = new google.maps.Marker({
      position: latLng,
      map: map,
      title: name
    });
    var content = '
' + name + '
' +
        '
Last seen: ' + new Date(res.timestamp).toLocaleString() + '
' +
        '
Device ID: ' + tracker._id + '
';
    if (tracker.device && tracker.device.mac) {
      content += '
MAC: ' + tracker.device.mac + '
';
    }
    var infoWindow = new google.maps.InfoWindow({
      content: content
    });
    marker.addListener('click', function() {
      infoWindow.open(map, marker);
    });
  });
}

function setPath(res, map){
  getTrackerFromId(res.id, function(tracker){
    var latLng = new google.maps.LatLng(res.data[0], res.data[1]);
    var marker = new google.maps.Marker({
      position: latLng,
      map: map,
      title: tracker.name
    });
  });
}

function getTrackerFromId(id, cb){
  $.get('/api/tracker/'+id).done(function(res){
    cb(res[0]);
  });
}

function initializeMap(){

  var mylatlng = new google.maps.LatLng(6.9344, 79.8428); // Should find a way to automatically set the focus
  var mapProp = {
    center: mylatlng,
    zoom:7,
    mapTypeId:google.maps.MapTypeId.ROADMAP
  };

  var map = new google.maps.Map($("#googleMap")[0], mapProp);

  return map;
}

function drawTrails(map, id){

	var pathCoords = [];

	requestStr = '/api/tracker/' + id + '/location/data';

	$.get(requestStr).done(function(res){
		for(var i = 0; i < res.length; i++){
			setPath(res[i], map);
			pathCoords.push(new google.maps.LatLng(res[i].data[0], res[i].data[1]));
		}

		var path = new google.maps.Polyline({
			path : pathCoords,
			geodesic : true,
			strokeColor: '#0000FF',
			strokeOpacity: 1.0,
			strokeWeight: 2
	  	});

		path.setMap(map);

	});
}

function markerCoords(res) {
  return new google.maps.LatLng(res.path[res.path.length - 1].latitude, res.path[res.path.length - 1].longitude);
}

function drawLocations(map){

  $.get('/api/tracker/locations').done(function(res){
    var bounds = new google.maps.LatLngBounds();
    for(var i=0; i<res.length; i++){
      setMarker(res[i], map);
      bounds.extend(markerCoords(res[i]));
    }
    map.fitBounds(bounds);
  });

}

function listTrackers(){

    $.get('/api/trackers').done(function(res){

        var list = '';

        for(var i = 0; i < res.length; i++){
        	list += '
 ' + res[i].name + '
';
        }

    	$('#trackers').html(list);

    });

}

$('document').ready(function(){

	$('.col-xs-2').keyup(function(){
		if ($(this).children().val().length == 2){
    			$(this).next('.col-xs-2').children().focus();
    		}
	 });

});

listTrackers();

google.maps.event.addDomListener(window, 'load', initialize);

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 airbug inc. http://airbug.com
 *
 * bugmeta may be freely distributed under the MIT license.
 */

//-------------------------------------------------------------------------------
// Requires
//-------------------------------------------------------------------------------

var buildbug            = require('buildbug');

//-------------------------------------------------------------------------------
// Simplify References
//-------------------------------------------------------------------------------

var buildProject        = buildbug.buildProject;
var buildProperties     = buildbug.buildProperties;
var buildScript         = buildbug.buildScript;
var buildTarget         = buildbug.buildTarget;
var enableModule        = buildbug.enableModule;
var parallel            = buildbug.parallel;
var series              = buildbug.series;
var targetTask          = buildbug.targetTask;

//-------------------------------------------------------------------------------
// Enable Modules
//-------------------------------------------------------------------------------

var aws                 = enableModule("aws");
var bugpack             = enableModule('bugpack');
var bugunit             = enableModule('bugunit');
var core                = enableModule('core');
var lintbug             = enableModule("lintbug");
var nodejs              = enableModule('nodejs');

//-------------------------------------------------------------------------------
// Values
//-------------------------------------------------------------------------------

var name                = "bugmeta";
var version             = "0.1.2";
var dependencies        = {
    bugpack: "0.1.11"
};

//-------------------------------------------------------------------------------
// BuildProperties
//-------------------------------------------------------------------------------

buildProperties({
    node: {
        packageJson: {
            name: name,
            version: version,
            description: "A JavaScript library for applying and retrieving meta information about a JS function",
            main: "./scripts/bugmeta-node-module.js",
            dependencies: dependencies,
            author: "Brian Neisler <brian@airbug.com>",
            repository: {
                type: "git",
                url: "https://github.com/airbug/bugmeta.git"
            },
            bugs: {
                url: "https://github.com/airbug/bugmeta/issues"
            },
            licenses: [
                {
                    type : "MIT",
                    url : "https://raw.githubusercontent.com/airbug/bugmeta/master/LICENSE"
                }
            ]
        },
        sourcePaths: [
            "../bugcore/projects/bugcore/js/src",
            "./projects/bugmeta/js/src"
        ],
        scriptPaths: [
            "./projects/bugmeta-node/js/scripts"
        ],
        readmePath: "./README.md",
        unitTest: {
            packageJson: {
                name: name + "-test",
                version: version,
                main: "./scripts/bugmeta-node-module.js",
                dependencies: dependencies,
                scripts: {
                    test: "./scripts/bugunit-run.js"
                }
            },
            sourcePaths: [
                "../buganno/projects/buganno/js/src",
                "../bugflow/projects/bugflow/js/src",
                "../bugfs/projects/bugfs/js/src",
                "../bugtrace/projects/bugtrace/js/src",
                "../bugunit/projects/bugdouble/js/src",
                "../bugunit/projects/bugunit/js/src"
            ],
            scriptPaths: [
                "../buganno/projects/buganno/js/scripts",
                "../bugunit/projects/bugunit/js/scripts"
            ],
            testPaths: [
                "../bugcore/projects/bugcore/js/test",
                "./projects/bugmeta/js/test"
            ]
        }
    },
    lint: {
        targetPaths: [
            "."
        ],
        ignorePatterns: [
            ".*\\.buildbug$",
            ".*\\.bugunit$",
            ".*\\.git$",
            ".*node_modules$"
        ]
    }
});

//-------------------------------------------------------------------------------
// BuildTargets
//-------------------------------------------------------------------------------

// Clean BuildTarget
//-------------------------------------------------------------------------------

buildTarget('clean').buildFlow(
    targetTask('clean')
);

// Local BuildTarget
//-------------------------------------------------------------------------------

buildTarget('local').buildFlow(
    series([
        targetTask('clean'),
        targetTask('lint', {
            properties: {
                targetPaths: buildProject.getProperty("lint.targetPaths"),
                ignores: buildProject.getProperty("lint.ignorePatterns"),
                lintTasks: [
                    "ensureNewLineEnding",
                    "updateCopyright",
                    "orderBugpackRequires",
                    "orderRequireAnnotations",
                    "indentEqualSignsForPreClassVars"
                ]
            }
        }),
        series([
            targetTask('createNodePackage', {
                properties: {
                    packageJson: buildProject.getProperty("node.packageJson"),
                    packagePaths: {
                        ".": [buildProject.getProperty("node.readmePath")],
                        "./lib": buildProject.getProperty("node.sourcePaths").concat(
                            buildProject.getProperty("node.unitTest.sourcePaths")
                        ),
                        "./scripts": buildProject.getProperty("node.scriptPaths").concat(
                            buildProject.getProperty("node.unitTest.scriptPaths")
                        ),
                        "./test": buildProject.getProperty("node.unitTest.testPaths")
                    }
                }
            }),
            targetTask('generateBugPackRegistry', {
                init: function(task, buildProject, properties) {
                    var nodePackage = nodejs.findNodePackage(
                        buildProject.getProperty("node.packageJson.name"),
                        buildProject.getProperty("node.packageJson.version")
                    );
                    task.updateProperties({
                        sourceRoot: nodePackage.getBuildPath()
                    });
                }
            }),
            targetTask('packNodePackage', {
                properties: {
                    packageName: "{{node.packageJson.name}}",
                    packageVersion: "{{node.packageJson.version}}"
                }
            }),
            targetTask('startNodeModuleTests', {
                init: function(task, buildProject, properties) {
                    var packedNodePackage = nodejs.findPackedNodePackage(
                        buildProject.getProperty("node.packageJson.name"),
                        buildProject.getProperty("node.packageJson.version")
                    );
                    task.updateProperties({
                        modulePath: packedNodePackage.getFilePath()
                        //checkCoverage: true
                    });
                }
            }),
            targetTask("s3PutFile", {
                init: function(task, buildProject, properties) {
                    var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("node.packageJson.name"),
                        buildProject.getProperty("node.packageJson.version"));
                    task.updateProperties({
                        file: packedNodePackage.getFilePath(),
                        options: {
                            acl: 'public-read',
                            encrypt: true
                        }
                    });
                },
                properties: {
                    bucket: "{{local-bucket}}"
                }
            })
        ])
    ])
).makeDefault();

// Prod BuildTarget
//-------------------------------------------------------------------------------

buildTarget('prod').buildFlow(
    series([
        targetTask('clean'),
        targetTask('lint', {
            properties: {
                targetPaths: buildProject.getProperty("lint.targetPaths"),
                ignores: buildProject.getProperty("lint.ignorePatterns"),
                lintTasks: [
                    "ensureNewLineEnding",
                    "updateCopyright",
                    "orderBugpackRequires",
                    "orderRequireAnnotations",
                    "indentEqualSignsForPreClassVars"
                ]
            }
        }),
        parallel([

            //Create test node bugmeta package

            series([
                targetTask('createNodePackage', {
                    properties: {
                        packageJson: buildProject.getProperty("node.unitTest.packageJson"),
                        packagePaths: {
                            "./lib": buildProject.getProperty("node.sourcePaths").concat(
                                buildProject.getProperty("node.unitTest.sourcePaths")
                            ),
                            "./scripts": buildProject.getProperty("node.scriptPaths").concat(
                                buildProject.getProperty("node.unitTest.scriptPaths")
                            ),
                            "./test": buildProject.getProperty("node.unitTest.testPaths")
                        }
                    }
                }),
                targetTask('generateBugPackRegistry', {
                    init: function(task, buildProject, properties) {
                        var nodePackage = nodejs.findNodePackage(
                            buildProject.getProperty("node.unitTest.packageJson.name"),
                            buildProject.getProperty("node.unitTest.packageJson.version")
                        );
                        task.updateProperties({
                            sourceRoot: nodePackage.getBuildPath()
                        });
                    }
                }),
                targetTask('packNodePackage', {
                    properties: {
                        packageName: "{{node.unitTest.packageJson.name}}",
                        packageVersion: "{{node.unitTest.packageJson.version}}"
                    }
                }),
                targetTask('startNodeModuleTests', {
                    init: function(task, buildProject, properties) {
                        var packedNodePackage = nodejs.findPackedNodePackage(
                            buildProject.getProperty("node.unitTest.packageJson.name"),
                            buildProject.getProperty("node.unitTest.packageJson.version")
                        );
                        task.updateProperties({
                            modulePath: packedNodePackage.getFilePath(),
                            checkCoverage: true
                        });
                    }
                 })
            ]),

            // Create production node bugmeta package

            series([
                targetTask('createNodePackage', {
                    properties: {
                        packageJson: buildProject.getProperty("node.packageJson"),
                        packagePaths: {
                            ".": [buildProject.getProperty("node.readmePath")],
                            "./lib": buildProject.getProperty("node.sourcePaths"),
                            "./scripts": buildProject.getProperty("node.scriptPaths")
                        }
                    }
                }),
                targetTask('generateBugPackRegistry', {
                    init: function(task, buildProject, properties) {
                        var nodePackage = nodejs.findNodePackage(
                            buildProject.getProperty("node.packageJson.name"),
                            buildProject.getProperty("node.packageJson.version")
                        );
                        task.updateProperties({
                            sourceRoot: nodePackage.getBuildPath()
                        });
                    }
                }),
                targetTask('packNodePackage', {
                    properties: {
                        packageName: "{{node.packageJson.name}}",
                        packageVersion: "{{node.packageJson.version}}"
                    }
                }),
                targetTask("s3PutFile", {
                    init: function(task, buildProject, properties) {
                        var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("node.packageJson.name"),
                            buildProject.getProperty("node.packageJson.version"));
                        task.updateProperties({
                            file: packedNodePackage.getFilePath(),
                            options: {
                                acl: 'public-read',
                                encrypt: true
                            }
                        });
                    },
                    properties: {
                        bucket: "{{prod-deploy-bucket}}"
                    }
                }),
                targetTask('npmConfigSet', {
                    properties: {
                        config: buildProject.getProperty("npmConfig")
                    }
                }),
                targetTask('npmAddUser'),
                targetTask('publishNodePackage', {
                    properties: {
                        packageName: "{{node.packageJson.name}}",
                        packageVersion: "{{node.packageJson.version}}"
                    }
                })
            ])
        ])
    ])
);

//-------------------------------------------------------------------------------
// Build Scripts
//-------------------------------------------------------------------------------

buildScript({
    dependencies: [
        "bugcore",
        "bugflow",
        "bugfs"
    ],
    script: "./lintbug.js"
});
<commit_msg>Remove old unecessary libraries<commit_after>/*
 * Copyright (c) 2014 airbug inc. http://airbug.com
 *
 * bugmeta may be freely distributed under the MIT license.
 */

//-------------------------------------------------------------------------------
// Requires
//-------------------------------------------------------------------------------

var buildbug            = require('buildbug');

//-------------------------------------------------------------------------------
// Simplify References
//-------------------------------------------------------------------------------

var buildProject        = buildbug.buildProject;
var buildProperties     = buildbug.buildProperties;
var buildScript         = buildbug.buildScript;
var buildTarget         = buildbug.buildTarget;
var enableModule        = buildbug.enableModule;
var parallel            = buildbug.parallel;
var series              = buildbug.series;
var targetTask          = buildbug.targetTask;

//-------------------------------------------------------------------------------
// Enable Modules
//-------------------------------------------------------------------------------

var aws                 = enableModule("aws");
var bugpack             = enableModule('bugpack');
var bugunit             = enableModule('bugunit');
var core                = enableModule('core');
var lintbug             = enableModule("lintbug");
var nodejs              = enableModule('nodejs');

//-------------------------------------------------------------------------------
// Values
//-------------------------------------------------------------------------------

var name                = "bugmeta";
var version             = "0.1.2";
var dependencies        = {
    bugpack: "0.1.11"
};

//-------------------------------------------------------------------------------
// BuildProperties
//-------------------------------------------------------------------------------

buildProperties({
    node: {
        packageJson: {
            name: name,
            version: version,
            description: "A JavaScript library for applying and retrieving meta information about a JS function",
            main: "./scripts/bugmeta-node-module.js",
            dependencies: dependencies,
            author: "Brian Neisler <brian@airbug.com>",
            repository: {
                type: "git",
                url: "https://github.com/airbug/bugmeta.git"
            },
            bugs: {
                url: "https://github.com/airbug/bugmeta/issues"
            },
            licenses: [
                {
                    type : "MIT",
                    url : "https://raw.githubusercontent.com/airbug/bugmeta/master/LICENSE"
                }
            ]
        },
        sourcePaths: [
            "../bugcore/projects/bugcore/js/src",
            "./projects/bugmeta/js/src"
        ],
        scriptPaths: [
            "./projects/bugmeta-node/js/scripts"
        ],
        readmePath: "./README.md",
        unitTest: {
            packageJson: {
                name: name + "-test",
                version: version,
                main: "./scripts/bugmeta-node-module.js",
                dependencies: dependencies,
                scripts: {
                    test: "./scripts/bugunit-run.js"
                }
            },
            sourcePaths: [
                "../buganno/projects/buganno/js/src",
                "../bugfs/projects/bugfs/js/src",
                "../bugunit/projects/bugdouble/js/src",
                "../bugunit/projects/bugunit/js/src"
            ],
            scriptPaths: [
                "../buganno/projects/buganno/js/scripts",
                "../bugunit/projects/bugunit/js/scripts"
            ],
            testPaths: [
                "../bugcore/projects/bugcore/js/test",
                "./projects/bugmeta/js/test"
            ]
        }
    },
    lint: {
        targetPaths: [
            "."
        ],
        ignorePatterns: [
            ".*\\.buildbug$",
            ".*\\.bugunit$",
            ".*\\.git$",
            ".*node_modules$"
        ]
    }
});

//-------------------------------------------------------------------------------
// BuildTargets
//-------------------------------------------------------------------------------

// Clean BuildTarget
//-------------------------------------------------------------------------------

buildTarget('clean').buildFlow(
    targetTask('clean')
);

// Local BuildTarget
//-------------------------------------------------------------------------------

buildTarget('local').buildFlow(
    series([
        targetTask('clean'),
        targetTask('lint', {
            properties: {
                targetPaths: buildProject.getProperty("lint.targetPaths"),
                ignores: buildProject.getProperty("lint.ignorePatterns"),
                lintTasks: [
                    "ensureNewLineEnding",
                    "updateCopyright",
                    "orderBugpackRequires",
                    "orderRequireAnnotations",
                    "indentEqualSignsForPreClassVars"
                ]
            }
        }),
        series([
            targetTask('createNodePackage', {
                properties: {
                    packageJson: buildProject.getProperty("node.packageJson"),
                    packagePaths: {
                        ".": [buildProject.getProperty("node.readmePath")],
                        "./lib": buildProject.getProperty("node.sourcePaths").concat(
                            buildProject.getProperty("node.unitTest.sourcePaths")
                        ),
                        "./scripts": buildProject.getProperty("node.scriptPaths").concat(
                            buildProject.getProperty("node.unitTest.scriptPaths")
                        ),
                        "./test": buildProject.getProperty("node.unitTest.testPaths")
                    }
                }
            }),
            targetTask('generateBugPackRegistry', {
                init: function(task, buildProject, properties) {
                    var nodePackage = nodejs.findNodePackage(
                        buildProject.getProperty("node.packageJson.name"),
                        buildProject.getProperty("node.packageJson.version")
                    );
                    task.updateProperties({
                        sourceRoot: nodePackage.getBuildPath()
                    });
                }
            }),
            targetTask('packNodePackage', {
                properties: {
                    packageName: "{{node.packageJson.name}}",
                    packageVersion: "{{node.packageJson.version}}"
                }
            }),
            targetTask('startNodeModuleTests', {
                init: function(task, buildProject, properties) {
                    var packedNodePackage = nodejs.findPackedNodePackage(
                        buildProject.getProperty("node.packageJson.name"),
                        buildProject.getProperty("node.packageJson.version")
                    );
                    task.updateProperties({
                        modulePath: packedNodePackage.getFilePath()
                        //checkCoverage: true
                    });
                }
            }),
            targetTask("s3PutFile", {
                init: function(task, buildProject, properties) {
                    var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("node.packageJson.name"),
                        buildProject.getProperty("node.packageJson.version"));
                    task.updateProperties({
                        file: packedNodePackage.getFilePath(),
                        options: {
                            acl: 'public-read',
                            encrypt: true
                        }
                    });
                },
                properties: {
                    bucket: "{{local-bucket}}"
                }
            })
        ])
    ])
).makeDefault();

// Prod BuildTarget
//-------------------------------------------------------------------------------

buildTarget('prod').buildFlow(
    series([
        targetTask('clean'),
        targetTask('lint', {
            properties: {
                targetPaths: buildProject.getProperty("lint.targetPaths"),
                ignores: buildProject.getProperty("lint.ignorePatterns"),
                lintTasks: [
                    "ensureNewLineEnding",
                    "updateCopyright",
                    "orderBugpackRequires",
                    "orderRequireAnnotations",
                    "indentEqualSignsForPreClassVars"
                ]
            }
        }),
        parallel([

            //Create test node bugmeta package

            series([
                targetTask('createNodePackage', {
                    properties: {
                        packageJson: buildProject.getProperty("node.unitTest.packageJson"),
                        packagePaths: {
                            "./lib": buildProject.getProperty("node.sourcePaths").concat(
                                buildProject.getProperty("node.unitTest.sourcePaths")
                            ),
                            "./scripts": buildProject.getProperty("node.scriptPaths").concat(
                                buildProject.getProperty("node.unitTest.scriptPaths")
                            ),
                            "./test": buildProject.getProperty("node.unitTest.testPaths")
                        }
                    }
                }),
                targetTask('generateBugPackRegistry', {
                    init: function(task, buildProject, properties) {
                        var nodePackage = nodejs.findNodePackage(
                            buildProject.getProperty("node.unitTest.packageJson.name"),
                            buildProject.getProperty("node.unitTest.packageJson.version")
                        );
                        task.updateProperties({
                            sourceRoot: nodePackage.getBuildPath()
                        });
                    }
                }),
                targetTask('packNodePackage', {
                    properties: {
                        packageName: "{{node.unitTest.packageJson.name}}",
                        packageVersion: "{{node.unitTest.packageJson.version}}"
                    }
                }),
                targetTask('startNodeModuleTests', {
                    init: function(task, buildProject, properties) {
                        var packedNodePackage = nodejs.findPackedNodePackage(
                            buildProject.getProperty("node.unitTest.packageJson.name"),
                            buildProject.getProperty("node.unitTest.packageJson.version")
                        );
                        task.updateProperties({
                            modulePath: packedNodePackage.getFilePath(),
                            checkCoverage: true
                        });
                    }
                 })
            ]),

            // Create production node bugmeta package

            series([
                targetTask('createNodePackage', {
                    properties: {
                        packageJson: buildProject.getProperty("node.packageJson"),
                        packagePaths: {
                            ".": [buildProject.getProperty("node.readmePath")],
                            "./lib": buildProject.getProperty("node.sourcePaths"),
                            "./scripts": buildProject.getProperty("node.scriptPaths")
                        }
                    }
                }),
                targetTask('generateBugPackRegistry', {
                    init: function(task, buildProject, properties) {
                        var nodePackage = nodejs.findNodePackage(
                            buildProject.getProperty("node.packageJson.name"),
                            buildProject.getProperty("node.packageJson.version")
                        );
                        task.updateProperties({
                            sourceRoot: nodePackage.getBuildPath()
                        });
                    }
                }),
                targetTask('packNodePackage', {
                    properties: {
                        packageName: "{{node.packageJson.name}}",
                        packageVersion: "{{node.packageJson.version}}"
                    }
                }),
                targetTask("s3PutFile", {
                    init: function(task, buildProject, properties) {
                        var packedNodePackage = nodejs.findPackedNodePackage(buildProject.getProperty("node.packageJson.name"),
                            buildProject.getProperty("node.packageJson.version"));
                        task.updateProperties({
                            file: packedNodePackage.getFilePath(),
                            options: {
                                acl: 'public-read',
                                encrypt: true
                            }
                        });
                    },
                    properties: {
                        bucket: "{{prod-deploy-bucket}}"
                    }
                }),
                targetTask('npmConfigSet', {
                    properties: {
                        config: buildProject.getProperty("npmConfig")
                    }
                }),
                targetTask('npmAddUser'),
                targetTask('publishNodePackage', {
                    properties: {
                        packageName: "{{node.packageJson.name}}",
                        packageVersion: "{{node.packageJson.version}}"
                    }
                })
            ])
        ])
    ])
);

//-------------------------------------------------------------------------------
// Build Scripts
//-------------------------------------------------------------------------------

buildScript({
    dependencies: [
        "bugcore",
        "bugflow",
        "bugfs"
    ],
    script: "./lintbug.js"
});
<|endoftext|>


<commit_before>"use strict";

var cslEditor;

// Use FileAPI to read files from local file system
var loadCSL = function () {
	var dialog = $('
' +
			'
Choose a CSL file to load<\/p>' +
			'<input type="file" \/>' +
			'<\/div>');
	dialog.find('input[type=file]').change(function (event) {
		var file = event.target.files[0],
			reader = new FileReader();
		reader.onload = function (event) {
			cslEditor.setCslCode(event.target.result);
			dialog.dialog("destroy");
		};
		reader.readAsText(file);
	});

	dialog.dialog({modal : true});
};

// Use Flash based downloadify plugin to save files to local file system
var saveCSL = function (cslCode) {
	var dialog = $('
' +
			'

' +
			'

' +
			'
<\/div>' +
			'<\/div>'),
		saveButton = dialog.find('#downloadify'),
		filename,
		styleId = cslEditor.getStyleId();

	dialog.find('#refManagerInstructions').
			load("../html/fileDialog.html", function () {
		filename = cslEditor.getStyleName().replace(/[\\/:"*?<>| ]+/g, "_") + '.csl';

		// prefix styleId with cslEditor/ so it doesn't clash with existing styles
		if (!/^cslEditor\//.test(styleId)) {
			styleId = 'cslEditor/' + styleId;
			cslEditor.setStyleId(styleId);
			assertEqual(cslEditor.getStyleId(), styleId);
			cslCode = CSLEDIT.data.getCslCode();
		}
		dialog.dialog({
			minWidth : 750,
			minHeight : 450,
			modal : true,
			open :  function () {
				dialog.find('#accordion').accordion({});
				saveButton.find('a').css({
					color : "blue",
					"text-decoration" : "underline"
				});

				saveButton.children().remove();

				saveButton.downloadify({
					swf : '../external/downloadify/downloadify.swf',
					downloadImage : '../external/downloadify/download.png',
					width : 100,
					height : 30,
					filename : filename,
					data : cslCode,
					transparent : true,
					onComplete: function(){
						alert('Your CSL Style Has Been Saved!');
						dialog.dialog('destroy');
					},
					onCancel: function(){ },
					onError: function(){ alert('Error saving file.'); }
				});

				// if it failed, show instructions to install flash player
				if (saveButton.find('object').length === 0) {
					dialog.find('#refManagerInstructions').css({display:"none"});
					dialog.find('#installFlash').html(
						'
Flash Player not found

' +
						'
To save to disk, you need to:' +
						'
' +
						'
Install Adobe Flash Player
' +
						'
Reload this page and try again
' +
						'

');
				} else {
					dialog.find('#refManagerInstructions').css({display:"block"});
					dialog.find('#installFlash').html('');
				}
			}
		});
	});
};

var initVisualEditorDemo = function (rootURL) {
	$("document").ready( function () {
		window.onerror = function (err, url, line) {
			var dialog = $('

').css({overflow:"auto"}),
				errLines = err.split("\n"),
				refreshPage = $('<button>Refresh Page</button>'),
				resetButton = $('<button>Reset Everything</button>');

			$.ajax({
				url : "../logError.php",
				type : "POST",
				data : {
						message : err
				},
				success : function (data) {
						console.log("Logged error: " + data);
				},
				error : function () {
						console.log("Failed to log error");
				}
			});

			dialog.append($('
').append(refreshPage).append(" try this first"));
			refreshPage.on("click", function () {
				window.location.reload();
			});

			dialog.append($('
').append(resetButton).append(" unsaved work will be lost"));
			resetButton.on("click", function () {
				CSLEDIT.storage.clear();
				window.location.reload();
			});

			dialog.append("
" + errLines[0] + "
");

			errLines.splice(0, 1);
			if (errLines.length > 0) {
				//dialog.append("

" + errLines.join("

") + "

");
				dialog.append("
" + errLines.join("\n") + "
");
			} else {
				dialog.append("
url: " + url + "
");
				dialog.append("
line: " + line + "
");
			}

			dialog.dialog({
				width: 650,
				height: 400
			});
		};

		cslEditor = new CSLEDIT.VisualEditor('#visualEditorContainer',
			{
				loadCSLName : "Load Style",
				loadCSLFunc : loadCSL,

				saveCSLName : 'Save Style',
				saveCSLFunc : saveCSL,
				rootURL : rootURL
			});
	});
};
<commit_msg>Add URL and line number to error log<commit_after>"use strict";

var cslEditor;

// Use FileAPI to read files from local file system
var loadCSL = function () {
	var dialog = $('
' +
			'
Choose a CSL file to load<\/p>' +
			'<input type="file" \/>' +
			'<\/div>');
	dialog.find('input[type=file]').change(function (event) {
		var file = event.target.files[0],
			reader = new FileReader();
		reader.onload = function (event) {
			cslEditor.setCslCode(event.target.result);
			dialog.dialog("destroy");
		};
		reader.readAsText(file);
	});

	dialog.dialog({modal : true});
};

// Use Flash based downloadify plugin to save files to local file system
var saveCSL = function (cslCode) {
	var dialog = $('
' +
			'

' +
			'

' +
			'
<\/div>' +
			'<\/div>'),
		saveButton = dialog.find('#downloadify'),
		filename,
		styleId = cslEditor.getStyleId();

	dialog.find('#refManagerInstructions').
			load("../html/fileDialog.html", function () {
		filename = cslEditor.getStyleName().replace(/[\\/:"*?<>| ]+/g, "_") + '.csl';

		// prefix styleId with cslEditor/ so it doesn't clash with existing styles
		if (!/^cslEditor\//.test(styleId)) {
			styleId = 'cslEditor/' + styleId;
			cslEditor.setStyleId(styleId);
			assertEqual(cslEditor.getStyleId(), styleId);
			cslCode = CSLEDIT.data.getCslCode();
		}
		dialog.dialog({
			minWidth : 750,
			minHeight : 450,
			modal : true,
			open :  function () {
				dialog.find('#accordion').accordion({});
				saveButton.find('a').css({
					color : "blue",
					"text-decoration" : "underline"
				});

				saveButton.children().remove();

				saveButton.downloadify({
					swf : '../external/downloadify/downloadify.swf',
					downloadImage : '../external/downloadify/download.png',
					width : 100,
					height : 30,
					filename : filename,
					data : cslCode,
					transparent : true,
					onComplete: function(){
						alert('Your CSL Style Has Been Saved!');
						dialog.dialog('destroy');
					},
					onCancel: function(){ },
					onError: function(){ alert('Error saving file.'); }
				});

				// if it failed, show instructions to install flash player
				if (saveButton.find('object').length === 0) {
					dialog.find('#refManagerInstructions').css({display:"none"});
					dialog.find('#installFlash').html(
						'
Flash Player not found

' +
						'
To save to disk, you need to:' +
						'
' +
						'
Install Adobe Flash Player
' +
						'
Reload this page and try again
' +
						'

');
				} else {
					dialog.find('#refManagerInstructions').css({display:"block"});
					dialog.find('#installFlash').html('');
				}
			}
		});
	});
};

var initVisualEditorDemo = function (rootURL) {
	$("document").ready( function () {
		window.onerror = function (err, url, line) {
			var dialog = $('

').css({overflow:"auto"}),
				errLines = err.split("\n"),
				refreshPage = $('<button>Refresh Page</button>'),
				resetButton = $('<button>Reset Everything</button>');

			$.ajax({
				url : "../logError.php",
				type : "POST",
				data : {
					message : err + "\nUrl: " + url + "\nLine: " + line
				},
				success : function (data) {
					console.log("Logged error: " + data);
				},
				error : function () {
					console.log("Failed to log error");
				}
			});

			dialog.append($('
').append(refreshPage).append(" try this first"));
			refreshPage.on("click", function () {
				window.location.reload();
			});

			dialog.append($('
').append(resetButton).append(" unsaved work will be lost"));
			resetButton.on("click", function () {
				CSLEDIT.storage.clear();
				window.location.reload();
			});

			dialog.append("
" + errLines[0] + "
");

			errLines.splice(0, 1);
			if (errLines.length > 0) {
				//dialog.append("

" + errLines.join("

") + "

");
				dialog.append("
" + errLines.join("\n") + "
");
			} else {
				dialog.append("
url: " + url + "
");
				dialog.append("
line: " + line + "
");
			}

			dialog.dialog({
				width: 650,
				height: 400
			});
		};

		cslEditor = new CSLEDIT.VisualEditor('#visualEditorContainer',
			{
				loadCSLName : "Load Style",
				loadCSLFunc : loadCSL,

				saveCSLName : 'Save Style',
				saveCSLFunc : saveCSL,
				rootURL : rootURL
			});
	});
};
<|endoftext|>


<commit_before>'use strict'
const config = require('../server/init/configuration')
const log = require('../server/init/logging')
const EventEmitter = require('events')
const eventEmitter = new EventEmitter()
const history = require('./history')

const {addDescription} = require('message-type')
const handleMessage = require('./handleMessage')
require('colors')
const {Client: AMQPClient, Policy} = require('amqp10')
const urlencode = require('urlencode')
const client = new AMQPClient(Policy.Utils.RenewOnSettle(1, 1, Policy.ServiceBusQueue))
let _onDetached

client.once('connection:closed', msg => log.info('connection:closed event received', msg))
client.on('connection:opened', msg => log.info('connection to azure opened'))
client.once('connection:disconnected', msg => log.info('connection to azure disconnected'))

async function start () {
  const sharedAccessKey = process.env.AZURE_SHARED_ACCESS_KEY || config.secure.azure.SharedAccessKey
  log.info('connecting with the following azure url:', `amqps://${config.full.azure.SharedAccessKeyName}:${(sharedAccessKey || '').replace(/\w/g, 'x')}@${config.full.azure.host}`)
  const queueName = config.secure.azure.queueName || config.full.azure.queueName
  log.info('connecting to the queue with name ', queueName)

  await client.connect(`amqps://${config.full.azure.SharedAccessKeyName}:${urlencode(sharedAccessKey)}@${config.full.azure.host}`)
  const receiver = await client.createReceiver(queueName)

  log.info('receiver created:', receiver.id)

  receiver.on('errorReceived', err => log.warn('An error occured when trying to receive message from queue', err))

  receiver.on('detached', msg => {
    log.info('detached received for receiver ', receiver.id)
    _onDetached && _onDetached(msg)
  })

  receiver.on('message', async message => {
    log.info(`New message from ug queue for receiver ${receiver.id}`, message)
    history.setIdleTimeStart()
    initLogger(message)

    if (message.body) {
      await _processMessage(message)
    } else {
      log.info('Message is empty or undefined, deleting from queue...', message)
      await receiver.accept(message)
    }

    initLogger(message)
  })

  async function _processMessage (MSG) {
    try {
      const body = addDescription(MSG.body)
      const result = await handleMessage(body)
      log.info('result from handleMessage', result)
      eventEmitter.emit('messageProcessed', MSG, result)
      return receiver.accept(MSG)
    } catch (e) {
      log.error(e)
      log.info('Error Occured, releasing message back to queue...', MSG)
      return receiver.modify(MSG, {undeliverableHere: false, deliveryFailed: true})
    }
  }

  // Return receiver, used by the integration tests
  return receiver
}

function initLogger (msg) {
  let config
  if (msg) {
    const {body} = msg
    config = {
      kthid: body && body.kthid,
      ug1Name: body && body.ug1Name,
      ugversion: (msg && msg.applicationProperties && msg.applicationProperties.UGVersion) || undefined,
      messageId: (msg && msg.properties && msg.properties.messageId) || undefined
    }
  } else {
    config = {}
  }

  log.init(config)

  return msg && msg.body
}

module.exports = {
  start,
  eventEmitter,
  set onDetached (cb) {
    _onDetached = cb
  },
  get onDetached () {
    return _onDetached
  }
}
<commit_msg>use .on again since other stuff is changed.<commit_after>'use strict'
const config = require('../server/init/configuration')
const log = require('../server/init/logging')
const EventEmitter = require('events')
const eventEmitter = new EventEmitter()
const history = require('./history')

const {addDescription} = require('message-type')
const handleMessage = require('./handleMessage')
require('colors')
const {Client: AMQPClient, Policy} = require('amqp10')
const urlencode = require('urlencode')
const client = new AMQPClient(Policy.Utils.RenewOnSettle(1, 1, Policy.ServiceBusQueue))
let _onDetached

client.on('connection:closed', msg => log.info('connection:closed event received', msg))
client.on('connection:opened', msg => log.info('connection to azure opened'))
client.on('connection:disconnected', msg => log.info('connection to azure disconnected'))

async function start () {
  const sharedAccessKey = process.env.AZURE_SHARED_ACCESS_KEY || config.secure.azure.SharedAccessKey
  log.info('connecting with the following azure url:', `amqps://${config.full.azure.SharedAccessKeyName}:${(sharedAccessKey || '').replace(/\w/g, 'x')}@${config.full.azure.host}`)
  const queueName = config.secure.azure.queueName || config.full.azure.queueName
  log.info('connecting to the queue with name ', queueName)

  await client.connect(`amqps://${config.full.azure.SharedAccessKeyName}:${urlencode(sharedAccessKey)}@${config.full.azure.host}`)
  const receiver = await client.createReceiver(queueName)

  log.info('receiver created:', receiver.id)

  receiver.on('errorReceived', err => log.warn('An error occured when trying to receive message from queue', err))

  receiver.on('detached', msg => {
    log.info('detached received for receiver ', receiver.id)
    _onDetached && _onDetached(msg)
  })

  receiver.on('message', async message => {
    log.info(`New message from ug queue for receiver ${receiver.id}`, message)
    history.setIdleTimeStart()
    initLogger(message)

    if (message.body) {
      await _processMessage(message)
    } else {
      log.info('Message is empty or undefined, deleting from queue...', message)
      await receiver.accept(message)
    }

    initLogger(message)
  })

  async function _processMessage (MSG) {
    try {
      const body = addDescription(MSG.body)
      const result = await handleMessage(body)
      log.info('result from handleMessage', result)
      eventEmitter.emit('messageProcessed', MSG, result)
      return receiver.accept(MSG)
    } catch (e) {
      log.error(e)
      log.info('Error Occured, releasing message back to queue...', MSG)
      return receiver.modify(MSG, {undeliverableHere: false, deliveryFailed: true})
    }
  }

  // Return receiver, used by the integration tests
  return receiver
}

function initLogger (msg) {
  let config
  if (msg) {
    const {body} = msg
    config = {
      kthid: body && body.kthid,
      ug1Name: body && body.ug1Name,
      ugversion: (msg && msg.applicationProperties && msg.applicationProperties.UGVersion) || undefined,
      messageId: (msg && msg.properties && msg.properties.messageId) || undefined
    }
  } else {
    config = {}
  }

  log.init(config)

  return msg && msg.body
}

module.exports = {
  start,
  eventEmitter,
  set onDetached (cb) {
    _onDetached = cb
  },
  get onDetached () {
    return _onDetached
  }
}
<|endoftext|>


<commit_before>/* Is it hot right now?
   Code for loading in local weather stats (on page load and on location update)
   James Goldie, Steefan Contractor & Mat Lipson 2017 */

/* on page load: choose a location (for now, Sydney Obs Hill), download
    assets and insert */

$(function()
{
  var default_station = "066062";
  var base_path = "output/"
  var location_menu_innerpad = 10;
  var location_request_timeout = 5000;
  var geolocation_timeout = 3000;
  var geolocation_done = false;

  /* request_station: hide the details section, download stats and plots
     for a new station and then display them _when they're ready_
     put up an error message if they don't load quickly enough */
  function request_station(station_id)
  {

    // fn and obj to track downloaded resources. should probably write a
    // self-contained object for this...
    var loaded_resources =
    {
      isit_stats: false,
      isit_ts_plot: false,
      isit_density_plot: false
    }
    function resources_loaded()
    {
      if (
        loaded_resources.isit_stats == false |
        loaded_resources.isit_ts_plot == false |
        loaded_resources.isit_density_plot == false)
      {
        return false;
      }
      else
      {
        return true;
      }
    }

    // hide the details section while we update stuff!
    $("#detail").attr("style", "display: none;");
    $("#digdeeper").attr("style", "color: #eee;");
    $("#digdeeper h3").text("Loading...");
    $("#isit_answer").text(". . .");
    $("#isit_comment").text("");

    // dl stats as json and insert on success.
    // (nb: no error callback available! need to use a timeout below)
    $.getJSON(base_path + station_id + "/stats.json", function(data)
    {
      $("#isit_answer").text(data.isit_answer);
      $("#isit_comment").text(data.isit_comment);
      $("#isit_maximum").text(data.isit_maximum);
      $("#isit_minimum").text(data.isit_minimum);
      $("#isit_current").text(data.isit_current);
      $("#isit_average").text(data.isit_average);
      $("#isit_name").text(data.isit_name);
      $("#isit_span").text(data.isit_span);

      loaded_resources.isit_stats = true;

      // enable page if all resources are loaded
      if (resources_loaded())
      {
        console.log('Isithot: All resources loaded :D');
        $("#detail").attr("style", "display: flex;");
        $("#digdeeper").attr("style", "color: #b22222;");
        $("#digdeeper h3").text("Dig deeper");
      }
    });

    // dl *each* image and insert on success
    plots = ["ts_plot", "density_plot"]
    plots.map(function(content)
    {
      var plot_target = $("#isit_" + content + " img");
      console.log('Isithot: Creating callback to load ' + content);
      var plot_building = $("<img>");
      plot_building.on('load', function()
      {
        console.log('Isithot: Inside onload callback for dummy ' + content);
        // when loading img is ready, set it to the target img
        plot_target.attr("src", $(this).attr("src"));

        // enable page if all resources are loaded
        if (resources_loaded())
        {
          console.log('Isithot: All resources loaded :D');
          $("#detail").attr("style", "display: flex;");
          $("#digdeeper").attr("style", "color: #b22222;");
          $("#digdeeper h3").text("Dig deeper");
        }
      });
      // set loading img src to trigger the download
      plot_building.attr(
        "src", base_path + station_id + "/" + content + ".png");
      console.log('Isithot: Set src attribute for ' + content + '; image ought to be loading now');

      loaded_resources["isit_" + content] = true;
    });

    // apologise if resources aren't all loaded after 10 secs
    setTimeout(function()
    {
      if (!resources_loaded())
      {
        console.log('Isithot: Resources did not load within timeout D:');
        $("#digdeeper h3").text(
          "We're having some trouble downloading the data...");
      }
    }, location_request_timeout);
  }

  /* resize_location_menu: resize the location menu according to the
     current selection */
  function resize_location_menu(new_text)
  {
    // resize the dropdown
    $("#current_location_temp_dummyopt").html(new_text);
    $("#current_location").width(
      $("#current_location_temp").width() + location_menu_innerpad);
  }

  /* geo_failure: requests the nearest station id */
  function geo_success(pos_data)
  {
    if (pos_data.country_code != "AU")
    {
      console.warn("User outside Australia; defaulting to Sydney Obs Hill!");
      $("#current_location").val(default_station).trigger("change");
      geolocation_done = true;
    }
    else {
      switch (pos_data.region_code) {
        case 'ACT':
          $("#current_location").val("070351").trigger("change");
          break;
        case 'NSW':
          $("#current_location").val("066062").trigger("change");
          break;
        case 'VIC':
          $("#current_location").val("087031").trigger("change");
          break;
        case 'TAS':
          $("#current_location").val("094029").trigger("change");
          break;
        case 'QLD':
          $("#current_location").val("040842").trigger("change");
          break;
        case 'SA':
          $("#current_location").val("023090").trigger("change");
          break;
        case 'NT':
          $("#current_location").val("014015").trigger("change");
          break;
        case 'WA':
          $("#current_location").val("009021").trigger("change");
          break;
        default:
          console.warn(
            "User region not recognised; " +
            "defaulting to Sydney Obs Hill!");
          $("#current_location").val(default_station).trigger("change");
      }
      console.log("Geolocation done!");
      geolocation_done = true;
    }
  }

  /* geo_failure: requests the sydney obs hill station id */
  function geo_failure()
  {
    console.warn("Geolocation failed; defaulting to Sydney Obs Hill!");
    $("current_location").val(default_station).trigger("change");
  }

  // = on page load ===========================================================

  // on page load, populate the location menu, then determine default (local)
  // station and request it
  $.getJSON("locations.json", function(data)
  {
    $("#current_location").append(
      '<option value="no_station_selected">-</option>');
    $.each(data, function(index, station) {
      $("#current_location").append(
        '<option value="' + station.id + '">' + station.label + '</option>');
    });

    // now get user location from ip and use to determine a default station
    // (geo_success and geo_failure will update and request the first time)
    if (navigator.geolocation)
    {
      $.get("https://freegeoip.net/json/", geo_success);
    }
    else
    {
      console.warn("No geolocation available!");
    }

    // default to sydney if geolocation hasn't returned
    setTimeout(function()
    {
      if (!geolocation_done)
      {
        geo_failure();
      }
    }, geolocation_timeout);
  });

  // = callbacks ==============================================================

  /* on new location selected:
       - update the dropdown menu
       - request new location data */
  $("#current_location").change(function() {
    console.log(this.value);
    if (this.value != "no_station_selected")
    {
      resize_location_menu($("option:selected", this).text());
      request_station(this.value);
    }
  });

});<commit_msg>Longer "no station" label<commit_after>/* Is it hot right now?
   Code for loading in local weather stats (on page load and on location update)
   James Goldie, Steefan Contractor & Mat Lipson 2017 */

/* on page load: choose a location (for now, Sydney Obs Hill), download
    assets and insert */

$(function()
{
  var default_station = "066062";
  var base_path = "output/"
  var location_menu_innerpad = 10;
  var location_request_timeout = 5000;
  var geolocation_timeout = 3000;
  var geolocation_done = false;

  /* request_station: hide the details section, download stats and plots
     for a new station and then display them _when they're ready_
     put up an error message if they don't load quickly enough */
  function request_station(station_id)
  {

    // fn and obj to track downloaded resources. should probably write a
    // self-contained object for this...
    var loaded_resources =
    {
      isit_stats: false,
      isit_ts_plot: false,
      isit_density_plot: false
    }
    function resources_loaded()
    {
      if (
        loaded_resources.isit_stats == false |
        loaded_resources.isit_ts_plot == false |
        loaded_resources.isit_density_plot == false)
      {
        return false;
      }
      else
      {
        return true;
      }
    }

    // hide the details section while we update stuff!
    $("#detail").attr("style", "display: none;");
    $("#digdeeper").attr("style", "color: #eee;");
    $("#digdeeper h3").text("Loading...");
    $("#isit_answer").text(". . .");
    $("#isit_comment").text("");

    // dl stats as json and insert on success.
    // (nb: no error callback available! need to use a timeout below)
    $.getJSON(base_path + station_id + "/stats.json", function(data)
    {
      $("#isit_answer").text(data.isit_answer);
      $("#isit_comment").text(data.isit_comment);
      $("#isit_maximum").text(data.isit_maximum);
      $("#isit_minimum").text(data.isit_minimum);
      $("#isit_current").text(data.isit_current);
      $("#isit_average").text(data.isit_average);
      $("#isit_name").text(data.isit_name);
      $("#isit_span").text(data.isit_span);

      loaded_resources.isit_stats = true;

      // enable page if all resources are loaded
      if (resources_loaded())
      {
        console.log('Isithot: All resources loaded :D');
        $("#detail").attr("style", "display: flex;");
        $("#digdeeper").attr("style", "color: #b22222;");
        $("#digdeeper h3").text("Dig deeper");
      }
    });

    // dl *each* image and insert on success
    plots = ["ts_plot", "density_plot"]
    plots.map(function(content)
    {
      var plot_target = $("#isit_" + content + " img");
      console.log('Isithot: Creating callback to load ' + content);
      var plot_building = $("<img>");
      plot_building.on('load', function()
      {
        console.log('Isithot: Inside onload callback for dummy ' + content);
        // when loading img is ready, set it to the target img
        plot_target.attr("src", $(this).attr("src"));

        // enable page if all resources are loaded
        if (resources_loaded())
        {
          console.log('Isithot: All resources loaded :D');
          $("#detail").attr("style", "display: flex;");
          $("#digdeeper").attr("style", "color: #b22222;");
          $("#digdeeper h3").text("Dig deeper");
        }
      });
      // set loading img src to trigger the download
      plot_building.attr(
        "src", base_path + station_id + "/" + content + ".png");
      console.log('Isithot: Set src attribute for ' + content + '; image ought to be loading now');

      loaded_resources["isit_" + content] = true;
    });

    // apologise if resources aren't all loaded after 10 secs
    setTimeout(function()
    {
      if (!resources_loaded())
      {
        console.log('Isithot: Resources did not load within timeout D:');
        $("#digdeeper h3").text(
          "We're having some trouble downloading the data...");
      }
    }, location_request_timeout);
  }

  /* resize_location_menu: resize the location menu according to the
     current selection */
  function resize_location_menu(new_text)
  {
    // resize the dropdown
    $("#current_location_temp_dummyopt").html(new_text);
    $("#current_location").width(
      $("#current_location_temp").width() + location_menu_innerpad);
  }

  /* geo_failure: requests the nearest station id */
  function geo_success(pos_data)
  {
    if (pos_data.country_code != "AU")
    {
      console.warn("User outside Australia; defaulting to Sydney Obs Hill!");
      $("#current_location").val(default_station).trigger("change");
      geolocation_done = true;
    }
    else {
      switch (pos_data.region_code) {
        case 'ACT':
          $("#current_location").val("070351").trigger("change");
          break;
        case 'NSW':
          $("#current_location").val("066062").trigger("change");
          break;
        case 'VIC':
          $("#current_location").val("087031").trigger("change");
          break;
        case 'TAS':
          $("#current_location").val("094029").trigger("change");
          break;
        case 'QLD':
          $("#current_location").val("040842").trigger("change");
          break;
        case 'SA':
          $("#current_location").val("023090").trigger("change");
          break;
        case 'NT':
          $("#current_location").val("014015").trigger("change");
          break;
        case 'WA':
          $("#current_location").val("009021").trigger("change");
          break;
        default:
          console.warn(
            "User region not recognised; " +
            "defaulting to Sydney Obs Hill!");
          $("#current_location").val(default_station).trigger("change");
      }
      console.log("Geolocation done!");
      geolocation_done = true;
    }
  }

  /* geo_failure: requests the sydney obs hill station id */
  function geo_failure()
  {
    console.warn("Geolocation failed; defaulting to Sydney Obs Hill!");
    $("current_location").val(default_station).trigger("change");
  }

  // = on page load ===========================================================

  // on page load, populate the location menu, then determine default (local)
  // station and request it
  $.getJSON("locations.json", function(data)
  {
    $("#current_location").append(
      '<option value="no_station_selected">----------</option>');
    $.each(data, function(index, station) {
      $("#current_location").append(
        '<option value="' + station.id + '">' + station.label + '</option>');
    });

    // now get user location from ip and use to determine a default station
    // (geo_success and geo_failure will update and request the first time)
    if (navigator.geolocation)
    {
      $.get("https://freegeoip.net/json/", geo_success);
    }
    else
    {
      console.warn("No geolocation available!");
    }

    // default to sydney if geolocation hasn't returned
    setTimeout(function()
    {
      if (!geolocation_done)
      {
        geo_failure();
      }
    }, geolocation_timeout);
  });

  // = callbacks ==============================================================

  /* on new location selected:
       - update the dropdown menu
       - request new location data */
  $("#current_location").change(function() {
    console.log(this.value);
    if (this.value != "no_station_selected")
    {
      resize_location_menu($("option:selected", this).text());
      request_station(this.value);
    }
  });

});<|endoftext|>


<commit_before>define({
    "root": true,
    "es": true,
    "fr": true
});
<commit_msg>Enable DE l10n<commit_after>define({
    "root": true,
    "es": true,
    "fr": true,
    "de": true
});
<|endoftext|>


<commit_before>var http = require('http');
var google = function(keyword, callback){
	var options = {
		host: 'ajax.googleapis.com',
		path: '/ajax/services/search/web?v=1.0&q=' + keyword
	};
	var data = '';
	http.get(options, function(res){
		res.on('data', function (chunk) {
			data += chunk;
		});
		res.on('end', function(){
			if(res.statusCode !== 404){
				callback(data);
			}else{
				callback();
			}
		});
	});
};
module.exports = function(bot){
	bot.addCommand('google', 'Search for the keyword', '<keyword>', USER_LEVEL_NORMAL, false, function(event){
		var keyword = '', message = '';
		if(event.params && event.params[0]){
			keyword = event.params.join('+');
		}
		google(keyword, function(data){
			try{
				result = JSON.parse(data);
			}catch(e){
				message = 'Google returned an error.';
			}
			if(result && result.responseData && result.responseData.results && result.responseData.results[0]){
				var returned = result.responseData.results[0];
				message = returned.titleNoFormatting + ' - ' + returned.url;
			}else{
				message = 'No search results returned for that keyword.';
			}
			bot.message(event.target, message);
		});
	});
};<commit_msg>Fixed buggy urls in google. @nebkat, now fix your bot... :P<commit_after>var http = require('http');
var google = function(keyword, callback){
	var options = {
		host: 'ajax.googleapis.com',
		path: '/ajax/services/search/web?v=1.0&q=' + keyword
	};
	var data = '';
	http.get(options, function(res){
		res.on('data', function (chunk) {
			data += chunk;
		});
		res.on('end', function(){
			if(res.statusCode !== 404){
				callback(data);
			}else{
				callback();
			}
		});
	});
};
module.exports = function(bot){
	bot.addCommand('google', 'Search for the keyword', '<keyword>', USER_LEVEL_NORMAL, false, function(event){
		var keyword = '', message = '';
		if(event.params && event.params[0]){
			keyword = event.params.join('+');
		}
		google(keyword, function(data){
			try{
				result = JSON.parse(data);
			}catch(e){
				message = 'Google returned an error.';
			}
			if(result && result.responseData && result.responseData.results && result.responseData.results[0]){
				var returned = result.responseData.results[0];
				message = returned.titleNoFormatting + ' - ' + decodeURIComponent(returned.url);
			}else{
				message = 'No search results returned for that keyword.';
			}
			bot.message(event.target, message);
		});
	});
};<|endoftext|>


<commit_before>var FirebugLoadManager = function () {
    try
    {
        // Get ModuleLoader implementation (it's Mozilla JS code module)
        Components.utils["import"]("resource://firebug/moduleLoader.js");
        if (FBTrace.DBG_MODULES)
            FBTrace.sysout("Loaded ModuleLoader");
    }
    catch (exc)
    {
        var msg = exc.toString() +" "+(exc.fileName || exc.sourceName) + "@" + exc.lineNumber;
        if (FBTrace.DBG_MODULES)
        {
            dump("Import moduleLoader.js FAILS: "+msg+"\n");
            FBTrace.sysout("Import moduleLoader.js ERROR "+msg, exc);
        }
        Components.util.reportError(msg);
        throw exc;
    }

    function preLoadInitialization()
    {
        // FIXME, create options.js as dependent of loader. Firebug.architecture = this.getPref(this.prefDomain, "architecture");
    }

    function getModuleLoaderScope()
    {
        var firebugScope = // pump the objects from this scope down into module loader
        {
            window : window,
            Firebug: Firebug,
            fbXPCOMUtils: fbXPCOMUtils,
            FBL: FBL,
            FirebugReps: FirebugReps,
            FBTrace: FBTrace,
            domplate: domplate,
            setTimeout: function(fn, delay) { return window.setTimeout(fn, delay); }, // bind window via closure
            clearTimeout: function(timeout) { return window.clearTimeout(timeout); }, // bind window via closure
            setInterval: function(fn, delay) { return window.setInterval(fn, delay); }, // bind window via closure
            clearInterval: function(timeout) { return window.clearInterval(timeout); }, // bind window via closure
        };
        return firebugScope;
    }

    function getModuleLoaderConfig()
    {
        var uid = Math.random();  // to give each XUL window its own loader (for now)
        var config = {
            context:"Firebug "+uid, // TODO XUL window id on FF4.0+
            baseUrl: "resource://",
            onDebug: function() {
                if (!this.FBTrace)
                {
                    // traceConsoleService is a global of |window| frome trace.js.
                    // on the first call we use it to get a ref to the Cu.import module object
                    this.FBTrace = traceConsoleService.getTracer("extensions.firebug");
                }
                this.FBTrace.sysout.apply(this.FBTrace,arguments);
            },
            onError: function()
            {
                Components.utils.reportError(arguments[0]);
                if (!this.FBTrace)
                {
                    // traceConsoleService is a global of |window| frome trace.js.
                    // on the first call we use it to get a ref to the Cu.import module object
                    this.FBTrace = traceConsoleService.getTracer("extensions.firebug");
                }
                this.FBTrace.sysout.apply(this.FBTrace,arguments);
            },
            waitSeconds: 0,
            debug: true,
            /* edit: function(errorMsg, errorURL, errorLineNumber)
            {
                window.alert(errorMsg+" "+errorURL+"@"+errorLineNumber);
            },
            edit: function(context, url, module)
            {
                FBTrace.sysout("opening window modal on "+url);
                var a = {url: url};
                return window.showModalDialog("chrome://firebug/content/external/editors.xul",{}, "resizable:yes;scroll:yes;dialogheight:480;dialogwidth:600;center:yes");
            }
            */
        };
        return config;
    }

    function createLoader()
    {
        preLoadInitialization();
        var firebugScope = getModuleLoaderScope();// pump the objects from this scope down into module loader
        var config = getModuleLoaderConfig();
        var loader = new ModuleLoader(firebugScope, config);
        return loader;
    }

    function loadCore(coreInitialize)
    {
        var loader = createLoader();

        var coreModules = [];

        if (FirebugLoadManager.arch === 'inProcess')
        {
            coreModules.push("firebugModules/inProcess/tools.js");  // must be first
            coreModules.push("firebugModules/debugger.js");
        }
        else if (FirebugLoadManager.arch == "remoteClient")
        {
            coreModules.push("crossfireModules/tools.js");
            coreModules.push("firebugModules/debugger.js");

        }
        else if (FirebugLoadManager.arch == "remoteServer")
        {

            coreModules.push("firebugModules/inProcess/tools.js");  // must be first
            coreModules.push("firebugModules/debugger.js");

            coreModules.push("crossfireModules/crossfire-server.js");
        }
        else
        {
            throw new Error("ERROR Firebug.LoadManager.loadCore unknown architechture requested: "+Firebug.arch);
        }

        var defaultModules = [
         "firebugModules/tabContext.js",
         "firebugModules/sourceBox.js",
         "firebugModules/script.js",
        ];

        var modules = coreModules.concat(defaultModules);

        loader.define(modules, coreInitialize);
    }

    return {loadCore: loadCore};
}();<commit_msg>[bti] typo in error<commit_after>var FirebugLoadManager = function () {
    try
    {
        // Get ModuleLoader implementation (it's Mozilla JS code module)
        Components.utils["import"]("resource://firebug/moduleLoader.js");
        if (FBTrace.DBG_MODULES)
            FBTrace.sysout("Loaded ModuleLoader");
    }
    catch (exc)
    {
        var msg = exc.toString() +" "+(exc.fileName || exc.sourceName) + "@" + exc.lineNumber;
        if (FBTrace.DBG_MODULES)
        {
            dump("Import moduleLoader.js FAILS: "+msg+"\n");
            FBTrace.sysout("Import moduleLoader.js ERROR "+msg, exc);
        }
        Components.utils.reportError(msg);
        throw exc;
    }

    function preLoadInitialization()
    {
        // FIXME, create options.js as dependent of loader. Firebug.architecture = this.getPref(this.prefDomain, "architecture");
    }

    function getModuleLoaderScope()
    {
        var firebugScope = // pump the objects from this scope down into module loader
        {
            window : window,
            Firebug: Firebug,
            fbXPCOMUtils: fbXPCOMUtils,
            FBL: FBL,
            FirebugReps: FirebugReps,
            FBTrace: FBTrace,
            domplate: domplate,
            setTimeout: function(fn, delay) { return window.setTimeout(fn, delay); }, // bind window via closure
            clearTimeout: function(timeout) { return window.clearTimeout(timeout); }, // bind window via closure
            setInterval: function(fn, delay) { return window.setInterval(fn, delay); }, // bind window via closure
            clearInterval: function(timeout) { return window.clearInterval(timeout); }, // bind window via closure
        };
        return firebugScope;
    }

    function getModuleLoaderConfig()
    {
        var uid = Math.random();  // to give each XUL window its own loader (for now)
        var config = {
            context:"Firebug "+uid, // TODO XUL window id on FF4.0+
            baseUrl: "resource://",
            onDebug: function() {
                if (!this.FBTrace)
                {
                    // traceConsoleService is a global of |window| frome trace.js.
                    // on the first call we use it to get a ref to the Cu.import module object
                    this.FBTrace = traceConsoleService.getTracer("extensions.firebug");
                }
                this.FBTrace.sysout.apply(this.FBTrace,arguments);
            },
            onError: function()
            {
                Components.utils.reportError(arguments[0]);
                if (!this.FBTrace)
                {
                    // traceConsoleService is a global of |window| frome trace.js.
                    // on the first call we use it to get a ref to the Cu.import module object
                    this.FBTrace = traceConsoleService.getTracer("extensions.firebug");
                }
                this.FBTrace.sysout.apply(this.FBTrace,arguments);
            },
            waitSeconds: 0,
            debug: true,
            /* edit: function(errorMsg, errorURL, errorLineNumber)
            {
                window.alert(errorMsg+" "+errorURL+"@"+errorLineNumber);
            },
            edit: function(context, url, module)
            {
                FBTrace.sysout("opening window modal on "+url);
                var a = {url: url};
                return window.showModalDialog("chrome://firebug/content/external/editors.xul",{}, "resizable:yes;scroll:yes;dialogheight:480;dialogwidth:600;center:yes");
            }
            */
        };
        return config;
    }

    function createLoader()
    {
        preLoadInitialization();
        var firebugScope = getModuleLoaderScope();// pump the objects from this scope down into module loader
        var config = getModuleLoaderConfig();
        var loader = new ModuleLoader(firebugScope, config);
        return loader;
    }

    function loadCore(coreInitialize)
    {
        var loader = createLoader();

        var coreModules = [];

        if (FirebugLoadManager.arch === 'inProcess')
        {
            coreModules.push("firebugModules/inProcess/tools.js");  // must be first
            coreModules.push("firebugModules/debugger.js");
        }
        else if (FirebugLoadManager.arch == "remoteClient")
        {
            coreModules.push("crossfireModules/tools.js");
            coreModules.push("firebugModules/debugger.js");

        }
        else if (FirebugLoadManager.arch == "remoteServer")
        {

            coreModules.push("firebugModules/inProcess/tools.js");  // must be first
            coreModules.push("firebugModules/debugger.js");

            coreModules.push("crossfireModules/crossfire-server.js");
        }
        else
        {
            throw new Error("ERROR Firebug.LoadManager.loadCore unknown architechture requested: "+Firebug.arch);
        }

        var defaultModules = [
         "firebugModules/tabContext.js",
         "firebugModules/sourceBox.js",
         "firebugModules/script.js",
        ];

        var modules = coreModules.concat(defaultModules);

        loader.define(modules, coreInitialize);
    }

    return {loadCore: loadCore};
}();<|endoftext|>