<commit_before>/* eslint-disable */
'use strict';

(function init() {
    // clean stale data in local storage
    localStorage.removeItem('assets');
    localStorage.removeItem('settings');

    var defaultConfig = {
        language: 'EN',
        theme: 'light',
        apiUrl: 'wss://frontend.binaryws.com/websockets/v3',
        oAuthUrl: 'https://oauth.binary.com/oauth2/authorize',
        accounts: []
    };

    const getDefaultAppId = () => {
      let defaultAppID;
      if(window.cordova) {
        defaultAppID = 1006;
      } else if(window.electron) {
        defaultAppID = 1306;
      } else if (/localhost:/g.test(window.location.href)) {
        defaultAppID = 3588;
      } else if (/arnabk.github.io:/g.test(window.location.href)) {
        defaultAppID = 3604;
      } else if (/beta/g.test(window.location.href)) {
        defaultAppID = 4343; //This is for BETA release
      }
      localStorage.setItem('config.default_app_id', defaultAppID);
      return defaultAppID;
    };

  const getAppId = () =>
    window.localStorage.getItem('config.app_id') || getDefaultAppId() || 1001;

  const getSocketURL = () => {
    let server_url = window.localStorage.getItem('config.server_url');
    if (!server_url) {
      let server = 'frontend';
      server_url = `${server}.binaryws.com`;
    }
    return `wss://${server_url}/websockets/v3`;
  };

    function parseOAuthResponse(responseUrl) {
        var urlParts = responseUrl.split('?');
        if (urlParts.length !== 2) {
            throw new Error('Not a valid url');
        }

        var objURL = {};
        responseUrl.replace(
            new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
            function( $0, $1, $2, $3 ){
                objURL[ $1 ] = $3;
            }
        );

        var accounts = [];
        for(var i = 1;; i++) {
            var account = objURL['acct' + i],
                token = objURL['token' + i],
                currency = objURL['cur' + i];
            if (!account || !token) break;
            accounts.push({ account: account, token: token, currency : currency || '', });
        }

        return accounts;
    }

    function readConfig() {
        try {
            window.BinaryBoot = JSON.parse(localStorage.getItem('boot')) || defaultConfig;
        } catch (e) {
            window.BinaryBoot = defaultConfig;
            window.console.log('Error while initializing', e);
        }
    }

    function parseUrlAndStoreAccountInfo(url) {
        if (~url.indexOf('acct1')) {
            var accounts = parseOAuthResponse(url);
            window.BinaryBoot.accounts = accounts;
            try {
                localStorage.setItem('boot', JSON.stringify(window.BinaryBoot));
                localStorage.setItem('account', JSON.stringify({ token: accounts[0].token }));
            } catch (e) {
                window.console.log('Error while saving boot config', e);
            }
        }
    }

    readConfig();
    parseUrlAndStoreAccountInfo(window.location.href);
    window.BinaryBoot.parseUrl = parseOAuthResponse;
    window.BinaryBoot.isBeta = /beta/g.test(window.location.href);
    window.BinaryBoot.baseUrl = window.BinaryBoot.isBeta ? '/beta' : '/';
    var lang = window.BinaryBoot.language;

    var redirectIndex = window.location.href.indexOf('?');
    if (~redirectIndex) {
        window.location.href = window.BinaryBoot.baseUrl;
    }

    window.BinaryBoot.oAuthUrl = defaultConfig.oAuthUrl;
    window.BinaryBoot.apiUrl = defaultConfig.apiUrl;

      try {
        // var config = JSON.parse(testConfig) || { };
        const serverURL = localStorage.getItem('config.server_url');
        window.BinaryBoot.appId = getAppId();
        window.BinaryBoot.apiUrl = serverURL ? `wss://${serverURL}/websockets/v3` : getSocketURL();
        window.BinaryBoot.oAuthUrl = config.oAuthUrl || window.BinaryBoot.oAuthUrl;
      } catch (e) { }

    window.BinaryBoot.connection = new WebSocket(window.BinaryBoot.apiUrl + '?app_id=' + window.BinaryBoot.appId + '&l=' + lang);
})();
<commit_msg>convert es6 to es5 in boot.js<commit_after>/* eslint-disable */
'use strict';

(function init() {
    // clean stale data in local storage
    localStorage.removeItem('assets');
    localStorage.removeItem('settings');

    var defaultConfig = {
        language: 'EN',
        theme: 'light',
        apiUrl: 'wss://frontend.binaryws.com/websockets/v3',
        oAuthUrl: 'https://oauth.binary.com/oauth2/authorize',
        accounts: []
    };

    function getDefaultAppId() {
        var defaultAppID;
        if(window.cordova) {
          defaultAppID = 1006;
        } else if(window.electron) {
          defaultAppID = 1306;
        } else if (/localhost:/g.test(window.location.href)) {
          defaultAppID = 3588;
        } else if (/arnabk.github.io:/g.test(window.location.href)) {
          defaultAppID = 3604;
        } else if (/beta/g.test(window.location.href)) {
          defaultAppID = 4343; //This is for BETA release
        } else {
          defaultAppID = 1001; //This is for PROD release
        }
        localStorage.setItem('config.default_app_id', defaultAppID);
        return defaultAppID;
    };

    function getAppId() {
      return window.localStorage.getItem('config.app_id') || getDefaultAppId();
    }

    function getSocketURL () {
        var server_url = window.localStorage.getItem('config.server_url');
        if (!server_url) {
            var server = 'frontend';
            server_url = server + '.binaryws.com';
        }
        return 'wss://' + server_url + '/websockets/v3';
    };

    function parseOAuthResponse(responseUrl) {
        var urlParts = responseUrl.split('?');
        if (urlParts.length !== 2) {
            throw new Error('Not a valid url');
        }

        var objURL = {};
        responseUrl.replace(
            new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
            function( $0, $1, $2, $3 ){
                objURL[ $1 ] = $3;
            }
        );

        var accounts = [];
        for(var i = 1;; i++) {
            var account = objURL['acct' + i],
                token = objURL['token' + i],
                currency = objURL['cur' + i];
            if (!account || !token) break;
            accounts.push({ account: account, token: token, currency : currency || '', });
        }

        return accounts;
    }

    function readConfig() {
        try {
            window.BinaryBoot = JSON.parse(localStorage.getItem('boot')) || defaultConfig;
        } catch (e) {
            window.BinaryBoot = defaultConfig;
            window.console.log('Error while initializing', e);
        }
    }

    function parseUrlAndStoreAccountInfo(url) {
        if (~url.indexOf('acct1')) {
            var accounts = parseOAuthResponse(url);
            window.BinaryBoot.accounts = accounts;
            try {
                localStorage.setItem('boot', JSON.stringify(window.BinaryBoot));
                localStorage.setItem('account', JSON.stringify({ token: accounts[0].token }));
            } catch (e) {
                window.console.log('Error while saving boot config', e);
            }
        }
    }

    readConfig();
    parseUrlAndStoreAccountInfo(window.location.href);
    window.BinaryBoot.parseUrl = parseOAuthResponse;
    window.BinaryBoot.isBeta = /beta/g.test(window.location.href);
    window.BinaryBoot.baseUrl = window.BinaryBoot.isBeta ? '/beta' : '/';
    var lang = window.BinaryBoot.language;

    var redirectIndex = window.location.href.indexOf('?');
    if (~redirectIndex) {
        window.location.href = window.BinaryBoot.baseUrl;
    }

    window.BinaryBoot.oAuthUrl = defaultConfig.oAuthUrl;
    window.BinaryBoot.apiUrl = defaultConfig.apiUrl;

    try {
        // var config = JSON.parse(testConfig) || { };
        window.BinaryBoot.appId = getAppId();
        window.BinaryBoot.apiUrl = getSocketURL();
        window.BinaryBoot.oAuthUrl = config.oAuthUrl || window.BinaryBoot.oAuthUrl;
    } catch (e) { }

    window.BinaryBoot.connection = new WebSocket(window.BinaryBoot.apiUrl + '?app_id=' + window.BinaryBoot.appId + '&l=' + lang);
})();
<|endoftext|>


<commit_before>'use strict';

// Declare app level module which depends on views, and components
angular.module('schedulerApp', [
  'ngRoute',
  'ngResource'
])
.factory('db', [ '$resource', '$q', '$rootScope', function($resource, $q, $rootScope) {

	var
		Things = $resource("http://10.0.1.168:8000/rest/v1/things", {}),
		Rooms = $resource("http://10.0.1.168:8000/rest/v1/rooms", {}),
		Tasks = $resource("http://10.0.1.168:8100/rest/v1/tasks", {}),
		Task = $resource("http://10.0.1.168:8100/rest/v1/tasks/:id", {}),
		refreshThings = function() {
			return Things.get({}).$promise.then(
				function(things) {
					service.things = {}
					angular.forEach(things.data,
						function(thing) {
							var found = false
							if (!thing.promoted || !thing.name || !thing.location) {
								console.debug("skipping thing because not promoted, described or assigned to room", thing)
								return
							}
							angular.forEach(thing.device.channels, function(channel) {
								if (channel.supportedMethods && channel.supportedMethods.indexOf("turnOff") > 0) {
									found = true
								}
							})
							if (found) {
								service.things[thing["id"]] = thing
							}
						}
					)
					return service
				}
			)
		},
		refreshRooms = function() {
			return Rooms.get({}).$promise.then(
				function(rooms) {
					service.rooms = {}
					angular.forEach(rooms.data, function(room) {
						service.rooms[room["id"]] = room
					})
					return service
				}
			)
		},
		refreshTasks = function() {
			return Tasks.get({}).$promise.then(
				function(tasks) {
					service.tasks = {}
					angular.forEach(tasks.schedule, function(task) {
						if (task.description && task.description != '') {
							service.tasks[task["id"]] = task
						}
					})
					return service
				}
			)
		},
		service = {
			things: { } ,
			rooms: { } ,
			tasks: { } ,
			save: function(task) {
				var deferred = $q.defer()
				Tasks.save(
					{},
					task,
					function(r) {
						refreshTasks().then(
							function() { deferred.resolve(r) },
							deferred.reject
						)},
					deferred.reject)
				return deferred.promise
			},
			delete: function(id) {
				var deferred = $q.defer()
				Task.delete({"id": id},
					function(r) {
						refreshTasks().then(function() { deferred.resolve(r)}, deferred.reject)
					},
					deferred.reject
				)
				return deferred.promise
			},
			refresh: function() {
				return $q.all([ refreshRooms(),	refreshThings(), refreshTasks() ]).then(
					function() {
						return service
					}
				)
			}
		}
	return service
}])
.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/list', {templateUrl: 'task-list.html', controller: 'TaskList'});
  $routeProvider.when('/edit/:id', {templateUrl: 'task-edit.html', controller: 'TaskEdit'});
  $routeProvider.when('/create', {templateUrl: 'task-edit.html', controller: 'TaskEdit'});
  $routeProvider.otherwise({redirectTo: '/list'});
}])
.controller('ModelRefresh', ['$scope', 'db', function($scope, db) {
	db.refresh().then(
		function(things) {
			return things
		},
		function(err) {
			$scope.message = err
		}
	)
}])
.controller('TaskEdit', ['$scope', '$location', 'db', '$routeParams', function($scope, $location, db, $routeParams) {

	$scope.thingToModel = function(thing) {
		var result = {}
		result.id = thing.id
		result.description = thing.name
		var room = db.rooms[thing.location]
		if (!room) {
			return null
		}
		result.room = room.name
		result.on = "true"
		return result
	}

	$scope.actionToModel = function(action) {
	    // {
        //    "action" : "turnOn",
        //    "thingID" : "94dc7d1a-aa67-11e4-803a-7c669d02a706",
        //     "type" : "thing-action"
        // }
        //
        // ==>
        //
	    // {
	    //	  "id": thing-id
        //    "description" : "thing description",
        //	  "room": "room description"
        //	  "on": true
        // }
        //

		var result = {}
		switch (action["action"]) {
		case "turnOn":
			result.on = "true"
			break
		case "turnOff":
			result.on = "false"
			break
		default:
			console.debug("bad action ", action)
			return null
		}

		if (action.type != "thing-action") {
			console.debug("bad type ", action.type)
			return null
		}

		if (!action.thingID) {
			console.debug("missing thing id")
			return null
		}

		result.id = action.thingID
		var thing = db.things[result.id]
		if (!thing) {
			console.debug("invalid thing id", result.id)
			return null
		}
		result.description = thing.name
		var room = db.rooms[thing.location]
		if (!room) {
			console.debug("invalid room id", thing.location)
			return null
		}
		result.room = room.name

		return result
	}

	$scope.selectedThings = {}
	$scope.availableThings = {}

	$scope.task = function() {
		return db.tasks[$routeParams["id"]]
	}

	$scope.$watch('task()', function(task) {
		$scope.availableThings = {}
		angular.forEach(db.things, function(t) {
			var m = $scope.thingToModel(t)
			if (m) {
				$scope.availableThings[t["id"]] = m
				$scope.selected = t["id"]
			}
		})
		if (!task) {
			return
		}
		$scope.description = task.description
		$scope.timeOfDay = task.window.after.param
		angular.forEach(task.open, function(action) {
			var thing = $scope.actionToModel(action)
			if (thing) {
				$scope.selectedThings[thing.id] = thing
				delete $scope.availableThings[thing.id]
			} else {
				console.debug(action)
			}
		})
		$scope.updateSelected()
	})

	$scope.selected = null

	$scope.save = function() {
		$scope.message = ""

		var task = {
			"id": $routeParams["id"],
			"description": $scope.description,
			"open":
				(function() {
					var results = []
					angular.forEach($scope.selectedThings, function(m) {
						results.push(
							{
								"type": "thing-action",
								"action": (m.on == "true" ? "turnOn" : "turnOff"),
								"thingID": m.id
							}
						)
					})
					return results
				}())
			,
			"window": {
				"after": {
					"rule": "time-of-day",
					"param": $scope.timeOfDay
				},
				"before": {
					"rule": "delay",
					"param": "00:01:00"
				}
			}
		}

		db.save(task).then(
			function() {
				$location.path('/list')
			}, function(m) {
				$scope.message = m
			})
	}

	$scope.delete = function() {
		db.delete($routeParams["id"]).then(
			function() {
				$location.path('/list')
			}, function(m) {
				$scope.message = m
			})
	}

	$scope.updateSelected = function() {
		$scope.selected = null
		angular.forEach($scope.availableThings, function(m) {
			$scope.selected = m.id
		})
	}
	$scope.add = function() {
		if ($scope.selected) {
			$scope.selectedThings[$scope.selected] = $scope.availableThings[$scope.selected]
			delete $scope.availableThings[$scope.selected]
			$scope.updateSelected()
		}

	}

	$scope.remove = function() {
		var tmp = []
		angular.forEach($scope.selectedThings, function (m) {
			if (m.selected) {
				tmp.push(m.id)
			}
		})
		angular.forEach(tmp, function(id) {
			var m = $scope.selectedThings[id]
			delete $scope.selectedThings[id]
			$scope.availableThings[id] = m
		})
		$scope.updateSelected()
	}

	$scope.cancel = function() {
		$location.path('/list')
	}
}])
.controller('TaskList', ['$scope', 'db', '$rootScope', function($scope, db, $rootScope) {
	$scope.tasks = {}
	$scope.db = db
	$scope.$watch("db.tasks", function(tasks) {
		$scope.tasks = db.tasks
	})
}])

<commit_msg>fix: >0 -> >=0<commit_after>'use strict';

// Declare app level module which depends on views, and components
angular.module('schedulerApp', [
  'ngRoute',
  'ngResource'
])
.factory('db', [ '$resource', '$q', '$rootScope', function($resource, $q, $rootScope) {

	var
		Things = $resource("http://10.0.1.168:8000/rest/v1/things", {}),
		Rooms = $resource("http://10.0.1.168:8000/rest/v1/rooms", {}),
		Tasks = $resource("http://10.0.1.168:8100/rest/v1/tasks", {}),
		Task = $resource("http://10.0.1.168:8100/rest/v1/tasks/:id", {}),
		refreshThings = function() {
			return Things.get({}).$promise.then(
				function(things) {
					service.things = {}
					angular.forEach(things.data,
						function(thing) {
							var found = false
							if (!thing.promoted || !thing.name || !thing.location) {
								console.debug("skipping thing because not promoted, described or assigned to room", thing)
								return
							}
							angular.forEach(thing.device.channels, function(channel) {
								if (channel.supportedMethods && channel.supportedMethods.indexOf("turnOff") >= 0) {
									found = true
								}
							})
							if (found) {
								service.things[thing["id"]] = thing
							}
						}
					)
					return service
				}
			)
		},
		refreshRooms = function() {
			return Rooms.get({}).$promise.then(
				function(rooms) {
					service.rooms = {}
					angular.forEach(rooms.data, function(room) {
						service.rooms[room["id"]] = room
					})
					return service
				}
			)
		},
		refreshTasks = function() {
			return Tasks.get({}).$promise.then(
				function(tasks) {
					service.tasks = {}
					angular.forEach(tasks.schedule, function(task) {
						if (task.description && task.description != '') {
							service.tasks[task["id"]] = task
						}
					})
					return service
				}
			)
		},
		service = {
			things: { } ,
			rooms: { } ,
			tasks: { } ,
			save: function(task) {
				var deferred = $q.defer()
				Tasks.save(
					{},
					task,
					function(r) {
						refreshTasks().then(
							function() { deferred.resolve(r) },
							deferred.reject
						)},
					deferred.reject)
				return deferred.promise
			},
			delete: function(id) {
				var deferred = $q.defer()
				Task.delete({"id": id},
					function(r) {
						refreshTasks().then(function() { deferred.resolve(r)}, deferred.reject)
					},
					deferred.reject
				)
				return deferred.promise
			},
			refresh: function() {
				return $q.all([ refreshRooms(),	refreshThings(), refreshTasks() ]).then(
					function() {
						return service
					}
				)
			}
		}
	return service
}])
.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/list', {templateUrl: 'task-list.html', controller: 'TaskList'});
  $routeProvider.when('/edit/:id', {templateUrl: 'task-edit.html', controller: 'TaskEdit'});
  $routeProvider.when('/create', {templateUrl: 'task-edit.html', controller: 'TaskEdit'});
  $routeProvider.otherwise({redirectTo: '/list'});
}])
.controller('ModelRefresh', ['$scope', 'db', function($scope, db) {
	db.refresh().then(
		function(things) {
			return things
		},
		function(err) {
			$scope.message = err
		}
	)
}])
.controller('TaskEdit', ['$scope', '$location', 'db', '$routeParams', function($scope, $location, db, $routeParams) {

	$scope.thingToModel = function(thing) {
		var result = {}
		result.id = thing.id
		result.description = thing.name
		var room = db.rooms[thing.location]
		if (!room) {
			return null
		}
		result.room = room.name
		result.on = "true"
		return result
	}

	$scope.actionToModel = function(action) {
	    // {
        //    "action" : "turnOn",
        //    "thingID" : "94dc7d1a-aa67-11e4-803a-7c669d02a706",
        //     "type" : "thing-action"
        // }
        //
        // ==>
        //
	    // {
	    //	  "id": thing-id
        //    "description" : "thing description",
        //	  "room": "room description"
        //	  "on": true
        // }
        //

		var result = {}
		switch (action["action"]) {
		case "turnOn":
			result.on = "true"
			break
		case "turnOff":
			result.on = "false"
			break
		default:
			console.debug("bad action ", action)
			return null
		}

		if (action.type != "thing-action") {
			console.debug("bad type ", action.type)
			return null
		}

		if (!action.thingID) {
			console.debug("missing thing id")
			return null
		}

		result.id = action.thingID
		var thing = db.things[result.id]
		if (!thing) {
			console.debug("invalid thing id", result.id)
			return null
		}
		result.description = thing.name
		var room = db.rooms[thing.location]
		if (!room) {
			console.debug("invalid room id", thing.location)
			return null
		}
		result.room = room.name

		return result
	}

	$scope.selectedThings = {}
	$scope.availableThings = {}

	$scope.task = function() {
		return db.tasks[$routeParams["id"]]
	}

	$scope.$watch('task()', function(task) {
		$scope.availableThings = {}
		angular.forEach(db.things, function(t) {
			var m = $scope.thingToModel(t)
			if (m) {
				$scope.availableThings[t["id"]] = m
				$scope.selected = t["id"]
			}
		})
		if (!task) {
			return
		}
		$scope.description = task.description
		$scope.timeOfDay = task.window.after.param
		angular.forEach(task.open, function(action) {
			var thing = $scope.actionToModel(action)
			if (thing) {
				$scope.selectedThings[thing.id] = thing
				delete $scope.availableThings[thing.id]
			} else {
				console.debug(action)
			}
		})
		$scope.updateSelected()
	})

	$scope.selected = null

	$scope.save = function() {
		$scope.message = ""

		var task = {
			"id": $routeParams["id"],
			"description": $scope.description,
			"open":
				(function() {
					var results = []
					angular.forEach($scope.selectedThings, function(m) {
						results.push(
							{
								"type": "thing-action",
								"action": (m.on == "true" ? "turnOn" : "turnOff"),
								"thingID": m.id
							}
						)
					})
					return results
				}())
			,
			"window": {
				"after": {
					"rule": "time-of-day",
					"param": $scope.timeOfDay
				},
				"before": {
					"rule": "delay",
					"param": "00:01:00"
				}
			}
		}

		db.save(task).then(
			function() {
				$location.path('/list')
			}, function(m) {
				$scope.message = m
			})
	}

	$scope.delete = function() {
		db.delete($routeParams["id"]).then(
			function() {
				$location.path('/list')
			}, function(m) {
				$scope.message = m
			})
	}

	$scope.updateSelected = function() {
		$scope.selected = null
		angular.forEach($scope.availableThings, function(m) {
			$scope.selected = m.id
		})
	}
	$scope.add = function() {
		if ($scope.selected) {
			$scope.selectedThings[$scope.selected] = $scope.availableThings[$scope.selected]
			delete $scope.availableThings[$scope.selected]
			$scope.updateSelected()
		}

	}

	$scope.remove = function() {
		var tmp = []
		angular.forEach($scope.selectedThings, function (m) {
			if (m.selected) {
				tmp.push(m.id)
			}
		})
		angular.forEach(tmp, function(id) {
			var m = $scope.selectedThings[id]
			delete $scope.selectedThings[id]
			$scope.availableThings[id] = m
		})
		$scope.updateSelected()
	}

	$scope.cancel = function() {
		$location.path('/list')
	}
}])
.controller('TaskList', ['$scope', 'db', '$rootScope', function($scope, db, $rootScope) {
	$scope.tasks = {}
	$scope.db = db
	$scope.$watch("db.tasks", function(tasks) {
		$scope.tasks = db.tasks
	})
}])

<|endoftext|>


<commit_before>/* jslint browser: true */
var createDivs = function ( data ) {
	var body = document.querySelector( '.counter');
	var queues = [
		[ 'best' ],
		[ 'good', 'decent', 'music' ],
		[ 'pending' ],
		[ 'bad' ],
		['trash' ]
	];

	var prog = document.createElement( 'progress' );
	prog.className = 'progress';
	prog.id = 'progress';
	body.appendChild(prog);

	var delta = document.createElement( 'div' );
	delta.className = 'delta';
	delta.id = 'delta';
	delta.innerHTML = 'Δ0';
	body.appendChild(delta);

	for ( var i = 0; i < queues.length; i++  ) {
		for ( var j = 0; j < queues[i].length; j++ ) {
			var queue = queues[i][j];
			var div = document.createElement( 'div' );
			if ( queue === 'total' ) {
				continue;
			}

			div.className = 'queue ' + queue;
			div.id = queue;

			body.appendChild( div );

			if ( j < queues[i].length - 1) {
				var sep = document.createElement( 'span' );
				sep.class = 'sep';
				sep.innerHTML = '&#x21c6'; //'↔';
				body.appendChild( sep );
			}

			if ( queue === 'trash' ) {
				continue;
			}
		}
		var span = document.createElement( 'span' );
		span.className = 'sep';
		if ( i === queue.length ) {
			span.innerHTML = '↓'; // downwards
		} else if ( i === queue.length - 1) {
			continue;
		} else if ( i === 0 ) {
			span.innerHTML = '↑'; // upwards
		} else {
			span.innerHTML = '&#x21f5'; //'↕'; //  updown
		}
		body.appendChild( span );
	}
};
var updateCounts = function ( data ) {
	var div;
	var total = 0 - data.counts.pending - data.counts.total;
	data.counts.good = data.counts.held;
	delete data.counts.held; // deletes property from object

	for ( var queue in data.counts ) {
		if ( data.counts.hasOwnProperty( queue ) ) {
			total += data.counts[queue];
			div = document.getElementById( queue );
			if ( !div ) { continue; }
			var text = data.counts[queue] + ' ' + queue;
			div.innerHTML = '' + text + '';
			var size = 0.5 * Math.sqrt(data.counts[queue]) + 'em';
			div.style.height = size;
			div.style.width = size;
			div.style['line-height'] = size;
		}
	}

	var prog = document.getElementById( 'progress' );
	prog.max = data.counts.total;
	prog.value = total;

	div = document.getElementById( 'delta' );
	div.innerHTML = 'Δ' + data.delta + ' ' + Math.round( 100 * total / data.counts.total ) + '%';
	if ( data.delta < 0 ) {
		div.className = 'delta negative';
	} else if ( data.delta === 0 ) {
		div.className = 'delta zero';
	} else {
		div.className = 'delta';
	}
	setTimeout(poll, 3000);
};

var getJSON = function(url, callback) {
	// http://stackoverflow.com/a/35970894
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status === 200) {
        callback(null, xhr.response);
      } else {
        callback(status);
      }
    };
    xhr.send();
};

function poll() {
	getJSON('//api.webm.website/stats.json', function ( e, r ) {
		updateCounts( r );
	} );
}

window.onload = function () {
	getJSON('//api.webm.website/stats.json', function ( e, r ) {
		createDivs( r );
		updateCounts( r );
	} );
};
<commit_msg>Don't hardcode webm.website in stats<commit_after>/* jslint browser: true */
var hostname = location.hostname.split('.').slice(1).join('.');
var createDivs = function ( data ) {
	var body = document.querySelector( '.counter');
	var queues = [
		[ 'best' ],
		[ 'good', 'decent', 'music' ],
		[ 'pending' ],
		[ 'bad' ],
		['trash' ]
	];

	var prog = document.createElement( 'progress' );
	prog.className = 'progress';
	prog.id = 'progress';
	body.appendChild(prog);

	var delta = document.createElement( 'div' );
	delta.className = 'delta';
	delta.id = 'delta';
	delta.innerHTML = 'Δ0';
	body.appendChild(delta);

	for ( var i = 0; i < queues.length; i++  ) {
		for ( var j = 0; j < queues[i].length; j++ ) {
			var queue = queues[i][j];
			var div = document.createElement( 'div' );
			if ( queue === 'total' ) {
				continue;
			}

			div.className = 'queue ' + queue;
			div.id = queue;

			body.appendChild( div );

			if ( j < queues[i].length - 1) {
				var sep = document.createElement( 'span' );
				sep.class = 'sep';
				sep.innerHTML = '&#x21c6'; //'↔';
				body.appendChild( sep );
			}

			if ( queue === 'trash' ) {
				continue;
			}
		}
		var span = document.createElement( 'span' );
		span.className = 'sep';
		if ( i === queue.length ) {
			span.innerHTML = '↓'; // downwards
		} else if ( i === queue.length - 1) {
			continue;
		} else if ( i === 0 ) {
			span.innerHTML = '↑'; // upwards
		} else {
			span.innerHTML = '&#x21f5'; //'↕'; //  updown
		}
		body.appendChild( span );
	}
};
var updateCounts = function ( data ) {
	var div;
	var total = 0 - data.counts.pending - data.counts.total;
	data.counts.good = data.counts.held;
	delete data.counts.held; // deletes property from object

	for ( var queue in data.counts ) {
		if ( data.counts.hasOwnProperty( queue ) ) {
			total += data.counts[queue];
			div = document.getElementById( queue );
			if ( !div ) { continue; }
			var text = data.counts[queue] + ' ' + queue;
			div.innerHTML = '' + text + '';
			var size = 0.5 * Math.sqrt(data.counts[queue]) + 'em';
			div.style.height = size;
			div.style.width = size;
			div.style['line-height'] = size;
		}
	}

	var prog = document.getElementById( 'progress' );
	prog.max = data.counts.total;
	prog.value = total;

	div = document.getElementById( 'delta' );
	div.innerHTML = 'Δ' + data.delta + ' ' + Math.round( 100 * total / data.counts.total ) + '%';
	if ( data.delta < 0 ) {
		div.className = 'delta negative';
	} else if ( data.delta === 0 ) {
		div.className = 'delta zero';
	} else {
		div.className = 'delta';
	}
	setTimeout(poll, 3000);
};

var getJSON = function(url, callback) {
	// http://stackoverflow.com/a/35970894
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'json';
    xhr.onload = function() {
      var status = xhr.status;
      if (status === 200) {
        callback(null, xhr.response);
      } else {
        callback(status);
      }
    };
    xhr.send();
};

function poll() {
	getJSON('//api.' + hostname + '/stats.json', function ( e, r ) {
		updateCounts( r );
	} );
}

window.onload = function () {
	getJSON('//api.' + hostname + '/stats.json', function ( e, r ) {
		createDivs( r );
		updateCounts( r );
	} );
};
<|endoftext|>


<commit_before>/**
 * The adapter for totoro-test tool
 */
(function(global) {

  var report = top.report
  var id = location.href.match(/runner\/([^/]+)\//)[1]
  var stats = {
    suites: 0,
    tests: 0,
    passes: 0,
    pending: 0,
    failures: 0
  }

  var baseResult = {
      pass: {count: 0, suites: []},
      fail: {count: 0, suites: []},
      error: {count: 0, suites: []}
  }

  var start, status

  global.publish = function(type, name, result) {
    if (type === 'testEnd') {
      typeMapping.testEnd(getSuiteResult(result))
      var failSuites = result.fail.suites && result.fail.suites.slice(0)
      var errorSuites = result.error.suites && result.error.suites.slice(0)

      baseResult = {
        pass: {count: result.pass.count, suites: result.pass.suites},
        fail: {count: result.fail.count, suites: failSuites},
        error: {count: result.error.count, suites: errorSuites}
      }
      return
    }

    if (type === 'test') {
      baseResult.suiteName = name
      return
    }

    typeMapping[type](baseResult)
  }

  function sendMessage(action, info) {
    report({
      orderId: id,
      action: action,
      info: info
    })
  }

  function getSuiteResult(result) {
    var pass = result.pass
    var fail = result.fail
    var error = result.error
    var failSuites = fail.suites && fail.suites.slice(0)
    var errorSuites = error.suites && error.suites.slice(0)
    return {
      suiteName: baseResult.suiteName,
      pass: {count: (pass.count - baseResult.pass.count), suites: pass.suites},
      fail: {count: (fail.count - baseResult.fail.count), suites: failSuites},
      error: {count: (error.count - baseResult.error.count), suites: error.suites}
    }
  }

  function each(arr, iterator) {
    for (var i = 0, l = arr.length; i < l; i++) {
      iterator.call(null, arr[i], i, arr)
    }
  }

  function subtractSuites(suites1, suites2) {
    var suite2Obj = {}
    var subSuite = []

    each(suites2, function(suite) {
      suite2Obj[suite.title] = suite
    })

    each(suites1, function(suite) {
      if (!suite2Obj[suite.title]) {
        subSuite.push(suite)
      }
    })

    return subSuite
  }

  var typeMapping = {
    'start': function() {
      start = new Date().getTime()
    },

    'test': function() {
    },

    'testEnd': function(result) {
      stats.tests++
      var passed = result.fail.count === 0

      var info = {
        parent: result.suiteName,
        title: result.suiteName,
        speed: 'fast',
        duration: '100ms'
      }

      if (passed) {
        stats.passes += result.pass.count
        status = 'pass'
      } else {
        stats.failures += result.fail.count
        status = 'fail'
        var msg = []
        var suites = subtractSuites(result.fail.suites, baseResult.fail.suites)
        for (var i = 0, len = suites.length; i < len; i++) {
            msg.push(suites[i].title)
        }

        info.message = msg.join(',')
      }

      sendMessage(status, info)
    },

    'end': function() {
      stats.duration = new Date().getTime() - start
      report({
        orderId: id,
        action: 'end',
        info: stats
      })
    }
  }

})(this)

<commit_msg>Add total passed count to report<commit_after>/**
 * The adapter for totoro-test tool
 */
(function(global) {

  var report = top.report
  var id = location.href.match(/runner\/([^/]+)\//)[1]
  var stats = {
    suites: 0,
    tests: 0,
    passes: 0,
    pending: 0,
    failures: 0
  }

  var baseResult = {
      pass: {count: 0, suites: []},
      fail: {count: 0, suites: []},
      error: {count: 0, suites: []}
  }

  var start, status

  global.publish = function(type, name, result) {
    if (type === 'testEnd') {
      typeMapping.testEnd(getSuiteResult(result))
      var failSuites = result.fail.suites && result.fail.suites.slice(0)
      var errorSuites = result.error.suites && result.error.suites.slice(0)

      baseResult = {
        pass: {count: result.pass.count, suites: result.pass.suites},
        fail: {count: result.fail.count, suites: failSuites},
        error: {count: result.error.count, suites: errorSuites}
      }
      return
    }

    if (type === 'test') {
      baseResult.suiteName = name
      return
    }

    typeMapping[type](baseResult)
  }

  function sendMessage(action, info) {
    report({
      orderId: id,
      action: action,
      info: info
    })
  }

  function getSuiteResult(result) {
    var pass = result.pass
    var fail = result.fail
    var error = result.error
    var failSuites = fail.suites && fail.suites.slice(0)
    var errorSuites = error.suites && error.suites.slice(0)
    return {
      suiteName: baseResult.suiteName,
      pass: {count: (pass.count - baseResult.pass.count), suites: pass.suites},
      fail: {count: (fail.count - baseResult.fail.count), suites: failSuites},
      error: {count: (error.count - baseResult.error.count), suites: error.suites}
    }
  }

  function each(arr, iterator) {
    for (var i = 0, l = arr.length; i < l; i++) {
      iterator.call(null, arr[i], i, arr)
    }
  }

  function subtractSuites(suites1, suites2) {
    var suite2Obj = {}
    var subSuite = []

    each(suites2, function(suite) {
      suite2Obj[suite.title] = suite
    })

    each(suites1, function(suite) {
      if (!suite2Obj[suite.title]) {
        subSuite.push(suite)
      }
    })

    return subSuite
  }

  var typeMapping = {
    'start': function() {
      start = new Date().getTime()
    },

    'test': function() {
    },

    'testEnd': function(result) {
      stats.tests++
      var passed = result.fail.count === 0

      var info = {
        parent: result.suiteName,
        title: result.suiteName,
        speed: 'fast',
        duration: '100ms'
      }

      if (passed) {
        stats.passes += result.pass.count
        status = 'pass'
      } else {
        stats.failures += result.fail.count
        status = 'fail'
        var msg = []
        var suites = subtractSuites(result.fail.suites, baseResult.fail.suites)
        for (var i = 0, len = suites.length; i < len; i++) {
            msg.push(suites[i].title)
        }

        info.message = msg.join(',')
      }

      sendMessage(status, info)
    },

    'end': function() {
      stats.duration = new Date().getTime() - start
      stats.tests = stats.passes
      report({
        orderId: id,
        action: 'end',
        info: stats
      })
    }
  }

})(this)

<|endoftext|>


<commit_before>const db           = require('./data.json');
const firebase     = require('./firebase');
const slackMessage = require('./slackMessage');
const templates    = require('./templates');

const SLOT_REGEX = /\((\w)+\)/g;
const ID_REGEX     = /(#\w+)/g;

const ALLOWED_FLAGS = [
	'id',
	'quiet'
];

function matchCardByName(query, card) {
	let isMatch = card.key.includes(query.term);

	if(isMatch && query.slot) {
		isMatch = query.slot.includes(card.slot);
	}

	return isMatch;
}

function searchForCardById(cardId) {
	return firebase.refs.cards.child(cardId)
		.once('value')
		.then((snapshot) => snapshot.val())
		.then((card) => typeof card === 'object' ? [card] : []);
}

function searchCards(query) {
	if(query.isId) {
		query.term = parseInt(query.term, 10);
		return searchForCardById(query.term);
		// return [db.find((card) => matchCardById(query, card))];
	}
	return new Promise(function(resolve) {
		resolve(db.filter((card) => matchCardByName(query, card)));
	});
}

function convertCardToResponse(card, isPrivate) {
	let responseData = {
		text:      templates.card(card),
		image:     card.image,
		isPrivate
	};

	return slackMessage(responseData);
}

function handleMultipleCards(foundCards, query) {
	return slackMessage({
		text:      templates.multiple(foundCards, query),
		isPrivate: true
	});
}

function formatSlots(slot) {
	slot = slot.replace(/\(|\)/g, '')
		.trim()
		.toLowerCase();

	if(!firebase.slots().includes(slot)) {
		slot = '';
	}

	return slot;
}

function parseSlots(queryText) {
	// Get any requested slots
	let slots   = queryText.match(SLOT_REGEX);

	if(slots) {
		slots = slots
			.map(formatSlots)
			.filter((slot) => slot.length > 0);
		// Store if we have any after filtering
		return (slots.length > 0 ? slots : false);
	}
	return false;
}

function parseFags(queryText) {
	// Get any requested filters
	let flags   = queryText.match(ID_REGEX);
	if(flags) {
		flags = flags
			.map((flag) => flag.replace('#', ''))
			.map((flag) => ALLOWED_FLAGS.includes(flag) ? flag : '')
			.filter((flag) => flag.length > 0);
		// Store if we have any after filtering
		return (flags.length > 0 ? flags : false);
	}
	return false;
}

function formatSearch(term) {
	// Make sure we only compare in lowercase
	term      = term.toLowerCase();
	let slot  = parseSlots(term);
	let flags = parseFags(term)
	// Strip the command string from the search text
	term      = term
		.replace(SLOT_REGEX, '')
		.replace(ID_REGEX, '')
		.trim();

	return {
		term,
		slot,
		isPrivate: Array.isArray(flags) && flags.includes('quiet'),
		isId:      Array.isArray(flags) && flags.includes('id')
	};
}

function handleNotFound(query) {
	return slackMessage({
		text:      templates.notFound(query),
		isPrivate: true
	});
}

function handleSearchResponse(cards, query, search) {
	const resultCount = cards.length;

	if(resultCount === 0) {
		return handleNotFound(query);
	} else if(resultCount === 1) {
		return convertCardToResponse(cards[0], search.isPrivate);
	} else {
		return handleMultipleCards(cards, query);
	}
}

module.exports = function search(query) {
	const search = formatSearch(query.text);

	return searchCards(search)
		.then((cards) => handleSearchResponse(cards, query, search));
};
<commit_msg>chore: Split out the search methods in to different terms<commit_after>const db           = require('./data.json');
const firebase     = require('./firebase');
const slackMessage = require('./slackMessage');
const templates    = require('./templates');

const SLOT_REGEX = /\((\w)+\)/g;
const ID_REGEX     = /(#\w+)/g;

const ALLOWED_FLAGS = [
	'id',
	'quiet'
];

function matchCardByName(query, card) {
	let isMatch = card.key.includes(query.term);

	if(isMatch && query.slot) {
		isMatch = query.slot.includes(card.slot);
	}

	return isMatch;
}

function searchForCardById(cardId) {
	return firebase.refs.cards.child(cardId)
		.once('value')
		.then((snapshot) => snapshot.val())
		.then((card) => typeof card === 'object' ? [card] : []);
}

function searchById(query) {
	const theId = parseInt(query.term, 10);
	return searchForCardById(theId);
}

function searchByText(query) {
	return new Promise((resolve) => {
		resolve(db.filter((card) => matchCardByName(query, card)));
	});
}

function searchCards(query) {
	if(query.isId) {
		return searchById(query);
	}

	return searchByText(query);
}

function convertCardToResponse(card, isPrivate) {
	let responseData = {
		text:      templates.card(card),
		image:     card.image,
		isPrivate
	};

	return slackMessage(responseData);
}

function handleMultipleCards(foundCards, query) {
	return slackMessage({
		text:      templates.multiple(foundCards, query),
		isPrivate: true
	});
}

function formatSlots(slot) {
	slot = slot.replace(/\(|\)/g, '')
		.trim()
		.toLowerCase();

	if(!firebase.slots().includes(slot)) {
		slot = '';
	}

	return slot;
}

function parseSlots(queryText) {
	// Get any requested slots
	let slots   = queryText.match(SLOT_REGEX);

	if(slots) {
		slots = slots
			.map(formatSlots)
			.filter((slot) => slot.length > 0);

		// Return the slots or false if we don't have any
		return (slots.length > 0 ? slots : false);
	}
	return false;
}

function parseFags(queryText) {
	// Get any requested filters
	let flags   = queryText.match(ID_REGEX);
	if(flags) {
		flags = flags
			.map((flag) => flag.replace('#', ''))
			.map((flag) => ALLOWED_FLAGS.includes(flag) ? flag : '')
			.filter((flag) => flag.length > 0);
		// Store if we have any after filtering
		return (flags.length > 0 ? flags : false);
	}
	return false;
}

function formatSearch(term) {
	// Make sure we only compare in lowercase
	term      = term.toLowerCase();
	let slot  = parseSlots(term);
	let flags = parseFags(term)
	// Strip the command string from the search text
	term      = term
		.replace(SLOT_REGEX, '')
		.replace(ID_REGEX, '')
		.trim();

	return {
		term,
		slot,
		isPrivate: Array.isArray(flags) && flags.includes('quiet'),
		isId:      Array.isArray(flags) && flags.includes('id')
	};
}

function handleNotFound(query) {
	return slackMessage({
		text:      templates.notFound(query),
		isPrivate: true
	});
}

function handleSearchResponse(cards, query, search) {
	const resultCount = cards.length;

	if(resultCount === 0) {
		return handleNotFound(query);
	} else if(resultCount === 1) {
		return convertCardToResponse(cards[0], search.isPrivate);
	} else {
		return handleMultipleCards(cards, query);
	}
}

module.exports = function search(query) {
	const search = formatSearch(query.text);

	return searchCards(search)
		.then((cards) => handleSearchResponse(cards, query, search));
};
<|endoftext|>


<commit_before>import './normalize.js';
import { ModLoader } from './ccloader.js';

if (window.process) {
	const envVar = process.env.CCLOADER_OVERRIDE_MAIN_URL;
	if (envVar) {
		window.location.replace(envVar);
	}
}

window.onload = () => {
	const modloader = new ModLoader();
	modloader.startGame()
		.then()
		.catch(err => console.error('Something went wrong while loading the game', err));
};
<commit_msg>Resolve CCLOADER_OVERRIDE_MAIN_URL relative to the game directory<commit_after>import './normalize.js';
import { ModLoader } from './ccloader.js';

if (window.process) {
	const envVar = process.env.CCLOADER_OVERRIDE_MAIN_URL;
	if (envVar) {
		window.location.replace(new URL(envVar, window.location.origin));
	}
}

window.onload = () => {
	const modloader = new ModLoader();
	modloader.startGame()
		.then()
		.catch(err => console.error('Something went wrong while loading the game', err));
};
<|endoftext|>


<commit_before>
var map, pointarray, heatmap, pickupMarkers, markerFlag;
var markerType = -1;
var markerEvent;
var HELP_TRASH = 1;
var TRASH_DROP = 2;
var COMMENT_LOC = 3;
var MOUSEDOWN_TIME;
var MOUSEUP_TIME;
var logging = false;
var centerPoint = null;

pickupMarkers = [];

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

function initialize() {
    var heatmapData = getHeatmapData();
    // initMap(lat, lon, zoom)
    var dataArr = getIpGeo();
    initMap(dataArr[0], dataArr[1], dataArr[2]);
    // initMap(37.774546, -122.433523, 17);
    initHeatMap(heatmapData);
} // end initialize

function initializeGPS(){
    db = Lawnchair({name : 'db'}, function(store) {
        lawnDB = store;
        setInterval(function() {runUpdate(store)},5000);//update user location every 5 seconds
        setInterval(function() {upload(store)},3000);//upload locations to the server every 30 seconds
    });
}

function start(){
    logging = true;
    initializeGPS();
    console.log("starting...");
    document.getElementById('startButton').style.display = 'none';
    document.getElementById('stopButton').style.display = 'block';
    //document.getElementById('panel1').style.backgroundImage = 'url(/client/img/icons/leaf.png)';

    navigator.geolocation.getCurrentPosition(function(p){
        var newcenter = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
        centerPoint = newcenter;
        map.panTo(newcenter);
    });

}

function stop(){
    upload(lawnDB);
    logging = false;
    console.log("stopping...")
    //document.getElementById('panel1').style.backgroundImage = '';
    document.getElementById('startButton').style.display = 'block';
    document.getElementById('stopButton').style.display= 'none';
}

//Runs the update script:

function runUpdate(database){
    //Grab the geolocation data from the local machine
    navigator.geolocation.getCurrentPosition(function(position) {
          updateLocation(database, position.coords.latitude, position.coords.longitude);
    });
}

//Uploads all local database entries to the Server
//Clears the local storage after upload
function upload(database){
    if(logging){
        //server/addgriddata.php

        database.all(function(data){
            console.log(data);
            $.ajax({
                type:'POST',
                url: '../server/addGridData.php',
                dataType:"json",
                data: {data : data},
                failure: function(errMsg){alert(errMsg);}
            });//Ajax

            //Remove all uploaded database records
            for(var i=1;i<data.length;i++){
                database.remove(i);
            }
        });
    }
}

//Updates the local couch DB with the current info
function updateLocation(database, latitude, longitude){
    if(logging){
        var datetime = new Date().getTime();//generate timestamp
        var location = {
                "latitude" : latitude,
                "longitude" : longitude,
                "datetime" : datetime,
        }

        database.save({value:location});//Save the record
    }
};

function findME(){
    var coords = new array();
    lawnDB.all(function(obj){
        coords.push(obj[obj.length - 1].value.latitude);
        coords.push(obj[obj.length - 1].value.longitude);
    });

    return coords;
}

// resolve our ip to a geolocation for initial map setup
function getIpGeo(){
    var heatmapData = [];
    var query = "../server/locationByIp.php";
    Lib.ajax.getJSON({
        url: query,
        type: "json"
        }, function(data){
            // console.log(data);
            var dataArr = eval("("+data+")");
            console.log("working");
            console.log();
        }
    );
    return dataArr;
}

// we should be supplying the 4 lat/lons to frame the map and only download what we need
// gets heatmap data and formats it for initHeatMap()
function getHeatmapData(){
    var heatmapData = [];
    var query = "../server/getHeatmapPoints.php";
    Lib.ajax.getJSON({
        url: query,
        type: "json"
        }, function(data){
            // console.log(data);
            var dataArr = eval("("+data+")");

            for(ii=0; ii<dataArr.length; ii++){
                // var dataA = dataArr[ii].split(",");
                heatmapData.push({location: new google.maps.LatLng(dataArr[ii][0], dataArr[ii][1]), weight: dataArr[ii][2]});
            }
            console.log("working");
            console.log(heatmapData);
        }
    );
    return heatmapData;
} // end getHeatmapData

// @argument heatData = array returned by getHeatMapData()
function initHeatMap(heatData){
  var pointArray = new google.maps.MVCArray(heatData);
  heatmap = new google.maps.visualization.HeatmapLayer({
    data: pointArray,
    dissipating: true,
    radius: 5
  });

  heatmap.setMap(null);
}

// fire up our google map
function initMap(centerpointLat, centerpointLon, zoom){
    // define the initial location of our map
    centerPoint = new google.maps.LatLng(centerpointLat, centerpointLon);
    var mapOptions = {
    zoom: zoom,
    center: centerPoint,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
  google.maps.event.addListener(map, 'mousedown', markerSelectDown);
  google.maps.event.addListener(map, 'mouseup', markerSelectUp);

}

function initIcons(){
    var pickupIcon = "img/icons/greenCircle.png";
    pickupMarkers = [];

  $.getJSON("../server/getPointsOfInterest.php", function(data) {
    // Lib.ajax.getJSON({
        // url:"/server/getPointsOfInterest.php",
        // type: "json"
        // }, function(data){
       for (var i = data.length - 1; i >= 0; i--) {
           var types = [null, "img/icons/blueCircle.png" ,"img/icons/redCircle.png" ,"img/icons/greenCircle.png" ];
           var marker =  new google.maps.Marker({position: new google.maps.LatLng(data[i].lat,data[i].lon),
                                                map: map,
                                                icon: types[data[i].fkType]
                                            });

           pickupMarkers.push(marker);
       };
       for (var i = pickupMarkers.length - 1; i >= 0; i--) {
            pickupMarkers[i].setVisible(false);
            //Add a custom field to the markers so we can have the information that goes in the infobox
            pickupMarkers[i].messageData = data[i].message;

            google.maps.event.addListener(pickupMarkers[i], "click", function () {
                var info = new google.maps.InfoWindow();
                info.setContent(this.messageData);
                info.setPosition(this.position);
                info.open(map);

            });
        }
    });

    markerFlag = false;
}

function toggleHeatmap() {
    heatmap.setMap(heatmap.getMap() ? null : map);
}

function toggleIcons(){
    var newState;
    if(markerFlag){
        newState = false;
        markerFlag = false;
    }else{
        newState = true;
        markerFlag = true;
    }
    for (var i = 0; i < pickupMarkers.length; i++){
        pickupMarkers[i].setVisible(newState);
    }
}

// add an icon for a pickup
function addPickupMarker(){
    var marker = new google.maps.Marker({
        position: markerEvent.latLng,
        map: map,
        icon: "img/icons/greenCircle.png"
    });
    pickupMarkers.push(marker);

    var info = new google.maps.InfoWindow();
    info.setContent('<form id="hook" class="infowindow pickup" method="GET" action="../server/communication.php"><input type="hidden" name="lat" value="'+marker.position.lat()+'"/><input type="hidden" name="lon" value="'+marker.position.lng()+'" /><textarea name="message"/></textarea><input type="hidden" name="topic" value="3" /><input type="hidden" name="add" /><input type="submit"  onmousedown="showToggleContainer" />');
    info.setPosition(marker.position);
    info.open(map);
}

// add an icon for a Comment location
function addCommentMarker(){
    var marker = new google.maps.Marker({
        position: markerEvent.latLng,
        map: map,
        icon: "img/icons/blueCircle.png"
    });
    pickupMarkers.push(marker);

    var info = new google.maps.InfoWindow();
    info.setContent('<form id="hook" class="infowindow comment" method="GET" action="../server/communication.php"><input type="hidden" name="lat" value="'+marker.position.lat()+'"/><input type="hidden" name="lon" value="'+marker.position.lng()+'" /><textarea name="message"/></textarea><input type="hidden" name="topic" value="1" /><input type="hidden" name="add" /><input type="submit"  onmousedown="showToggleContainer" />');
    info.setPosition(marker.position);
    info.open(map);
}

// add an icon to indicate where trash was found
function addTrashMarker(){
    var marker = new google.maps.Marker({
        position: markerEvent.latLng,
        map: map,
        icon: "img/icons/redCircle.png"
    });
    pickupMarkers.push(marker);

    //corresponds to the help needed
    var info = new google.maps.InfoWindow();
    info.setContent('<form id="hook" class="infowindow helpme" method="GET" action="../server/communication.php"><input type="hidden" name="lat" value="'+marker.position.lat()+'"/><input type="hidden" name="lon" value="'+marker.position.lng()+'" /><textarea name="message"/></textarea><input type="hidden" name="topic" value="2" /><input type="hidden" name="add" /><input type="submit"  onmousedown="showToggleContainer" />');
    info.setPosition(marker.position);
    info.open(map);
}

function showToggleContainer(){
    // $('.toggleContainer').show();
    document.getElementById("toggleContainer").className = "showBlock";
}

function markerSelectUp(event){
    markerEvent = event;
    MOUSEUP_TIME = new Date().getTime() / 1000;
    if((MOUSEUP_TIME - MOUSEDOWN_TIME) < 0.3){
        // alert((MOUSEUP_TIME - MOUSEDOWN_TIME));
        $('#markerTypeDialog').toggle();
        MOUSEDOWN_TIME =0;
        MOUSEDOWN_TIME =0;
    }else{
        MOUSEDOWN_TIME =0;
        MOUSEDOWN_TIME =0;
    }
}

// native javascript version of $.getJSON
// http://gabrieleromanato.name/javascript-implementing-getjson-from-scratch/

function markerSelectDown(event){
    markerEvent = event;
    MOUSEDOWN_TIME = new Date().getTime() / 1000;
    // if((MOUSEUP_TIME - MOUSEDOWN_TIME) < 2){
    //     $('#markerTypeDialog').toggle();
    //     MOUSEDOWN_TIME =0;
    //     MOUSEDOWN_TIME =0;
    // }else{
    //     MOUSEDOWN_TIME =0;
    //     MOUSEDOWN_TIME =0;
    // }
}

function changeRadius() {
  heatmap.setOptions({radius: heatmap.get('radius') ? null : 20});
}

function changeOpacity() {
  heatmap.setOptions({opacity: heatmap.get('opacity') ? null : 0.2});
}

// $(document).ready(function(){
document.addEventListener('DOMContentLoaded',function(){

    // our native replacement for jquery.getJSON
    var Lib = {
            ajax: {
                xhr: function() {
                    var instance = new XMLHttpRequest();
                    return instance;
                },

                getJSON: function(options, callback) {
                    var xhttp = this.xhr();
                    options.url = options.url || location.href;
                    options.data = options.data || null;
                    callback = callback ||
                    function() {};
                    options.type = options.type || 'json';
                    var url = options.url;
                    if (options.type == 'jsonp') {
                        window.jsonCallback = callback;
                        var $url = url.replace('callback=?', 'callback=jsonCallback');
                        var script = document.createElement('script');
                        script.src = $url;
                        document.body.appendChild(script);
                    }
                    xhttp.open('GET', options.url, true);
                    xhttp.send(options.data);
                    xhttp.onreadystatechange = function() {
                        if (xhttp.status == 200 && xhttp.readyState == 4) {
                            callback(xhttp.responseText);
                        }
                    };
                }
            }
        };

    window.Lib = Lib;

    document.addEventListener("touchmove", function(e){
        e.preventDefault();
    }, false);

    // var scrollable = document.getElementByClassName('scrollable');
    var toggleHeat = document.getElementById('toggleHeat');
    var toggleIco = document.getElementById('toggleIcons');
    var selectPickup = document.getElementById('selectPickup');
    var selectComment = document.getElementById('selectComment');
    var selectTrash = document.getElementById('selectTrash');

    var mapInit = document.getElementById('mapInit');
    var startButton = document.getElementById('startButton');
    var stopButton = document.getElementById('stopButton');

    toggleHeat.addEventListener('click', function() {
        toggleHeatmap();
    }, false);

    toggleIco.addEventListener('click', function() {
        toggleIcons();
    }, false);

    selectPickup.addEventListener('click', function() {
        $('#markerTypeDialog').toggle();
        // $('.toggleContainer').hide();
        document.getElementById("toggleContainer").className = "hidden";

        addPickupMarker();
    }, false);

    selectComment.addEventListener('click', function() {
        $('#markerTypeDialog').toggle();
        // $('.toggleContainer').hide();
        document.getElementById("toggleContainer").className = "hidden";
        addCommentMarker();
    }, false);

    selectTrash.addEventListener('click', function() {
        $('#markerTypeDialog').toggle();
        // $('.toggleContainer').hide();
        document.getElementById("toggleContainer").className = "hidden";
        addTrashMarker();
    }, false);

    mapInit.addEventListener('mousedown', function() {
         $('.mapDecoyContainer').hide(function(){
            $('.mapContainer').show();
        });
    }, false);

    startButton.addEventListener('mousedown', function() {
        start();
    }, false);

    stopButton.addEventListener('mousedown', function() {
        stop();
    }, false);

    var pr1 = document.getElementById("pr1");
    pr1.addEventListener('mousedown', function() {
        document.getElementById("container").className = "";
        document.getElementById("container").className = "panel2Center";
    }, false);

    var prr1 = document.getElementById("prr1");
    prr1.addEventListener('mousedown', function() {
        document.getElementById("container").className = "";
        document.getElementById("container").className = "panel3Center";
    }, false);

    var pr2 = document.getElementById("pr2");
    pr2.addEventListener('mousedown', function() {
        document.getElementById("container").className = "";
        document.getElementById("container").className = "panel3Center";
    }, false);

    var pl2 = document.getElementById("pl2");
    pl2.addEventListener('mousedown', function() {
        document.getElementById("container").className = "";
        document.getElementById("container").className = "panel1Center";
    }, false);

    var pl3 = document.getElementById("pl3");
    pl3.addEventListener('mousedown', function() {
        document.getElementById("container").className = "";
        document.getElementById("container").className = "panel2Center";
    }, false);

    var pll3 = document.getElementById("pll3");
    pll3.addEventListener('mousedown', function() {
        document.getElementById("container").className = "";
        document.getElementById("container").className = "panel1Center";
    }, false);

    //Get the parameters in the get url and expose them
    var prmstr = window.location.search.substr(1);
    var prmarr = prmstr.split ("&");
    var params = {};

    for ( var i = 0; i < prmarr.length; i++) {
        var tmparr = prmarr[i].split("=");
        params[tmparr[0]] = tmparr[1];
    }

    //Check the param and look for pane
    if(params.pane != "undefined"){
        switch(params.pane){
            case "2":
                document.getElementById("container").className = "";
                document.getElementById("container").className = "panel2Center";
                break;
            case "3":
                document.getElementById("container").className = "";
                document.getElementById("container").className = "panel3Center";
                break;
        }
    }

    // $('#map-canvas').mousedown(function(){
    //     MOUSEDOWN_TIME = new Date().getTime() / 1000;
    // });
    // $('#map-canvas').mouseup(function(){
    //     MOUSEUP_TIME = new Date().getTime() / 1000;
    // });
});
<commit_msg>adding ipGeo<commit_after>
var map, pointarray, heatmap, pickupMarkers, markerFlag;
var markerType = -1;
var markerEvent;
var HELP_TRASH = 1;
var TRASH_DROP = 2;
var COMMENT_LOC = 3;
var MOUSEDOWN_TIME;
var MOUSEUP_TIME;
var logging = false;
var centerPoint = null;

pickupMarkers = [];

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

function initialize() {
    var heatmapData = getHeatmapData();
    // initMap(lat, lon, zoom)
    var dataArr = getIpGeo();
    initMap(dataArr[0], dataArr[1], dataArr[2]);
    // initMap(37.774546, -122.433523, 17);
    initHeatMap(heatmapData);
} // end initialize

function initializeGPS(){
    db = Lawnchair({name : 'db'}, function(store) {
        lawnDB = store;
        setInterval(function() {runUpdate(store)},5000);//update user location every 5 seconds
        setInterval(function() {upload(store)},3000);//upload locations to the server every 30 seconds
    });
}

function start(){
    logging = true;
    initializeGPS();
    console.log("starting...");
    document.getElementById('startButton').style.display = 'none';
    document.getElementById('stopButton').style.display = 'block';
    //document.getElementById('panel1').style.backgroundImage = 'url(/client/img/icons/leaf.png)';

    navigator.geolocation.getCurrentPosition(function(p){
        var newcenter = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
        centerPoint = newcenter;
        map.panTo(newcenter);
    });

}

function stop(){
    upload(lawnDB);
    logging = false;
    console.log("stopping...")
    //document.getElementById('panel1').style.backgroundImage = '';
    document.getElementById('startButton').style.display = 'block';
    document.getElementById('stopButton').style.display= 'none';
}

//Runs the update script:

function runUpdate(database){
    //Grab the geolocation data from the local machine
    navigator.geolocation.getCurrentPosition(function(position) {
          updateLocation(database, position.coords.latitude, position.coords.longitude);
    });
}

//Uploads all local database entries to the Server
//Clears the local storage after upload
function upload(database){
    if(logging){
        //server/addgriddata.php

        database.all(function(data){
            console.log(data);
            $.ajax({
                type:'POST',
                url: '../server/addGridData.php',
                dataType:"json",
                data: {data : data},
                failure: function(errMsg){alert(errMsg);}
            });//Ajax

            //Remove all uploaded database records
            for(var i=1;i<data.length;i++){
                database.remove(i);
            }
        });
    }
}

//Updates the local couch DB with the current info
function updateLocation(database, latitude, longitude){
    if(logging){
        var datetime = new Date().getTime();//generate timestamp
        var location = {
                "latitude" : latitude,
                "longitude" : longitude,
                "datetime" : datetime,
        }

        database.save({value:location});//Save the record
    }
};

function findME(){
    var coords = new array();
    lawnDB.all(function(obj){
        coords.push(obj[obj.length - 1].value.latitude);
        coords.push(obj[obj.length - 1].value.longitude);
    });

    return coords;
}

// resolve our ip to a geolocation for initial map setup
function getIpGeo(){
    var heatmapData = [];
    var query = "../server/locationByIp.php";
    Lib.ajax.getJSON({
        url: query,
        type: "json"
        }, function(data){
            // console.log(data);
            var dataArr = eval("("+data+")");
            console.log("working");
            console.log();
        }
    );
    return dataArr;
}

// we should be supplying the 4 lat/lons to frame the map and only download what we need
// gets heatmap data and formats it for initHeatMap()
function getHeatmapData(){
    var heatmapData = [];
    var query = "../server/getHeatmapPoints.php";
    Lib.ajax.getJSON({
        url: query,
        type: "json"
        }, function(data){
            // console.log(data);
            var dataArr = eval("("+data+")");

            for(ii=0; ii<dataArr.length; ii++){
                // var dataA = dataArr[ii].split(",");
                heatmapData.push({location: new google.maps.LatLng(dataArr[ii][0], dataArr[ii][1]), weight: dataArr[ii][2]});
            }
            console.log("working");
            console.log(heatmapData);
        }
    );
    return heatmapData;
} // end getHeatmapData

// @argument heatData = array returned by getHeatMapData()
function initHeatMap(heatData){
  var pointArray = new google.maps.MVCArray(heatData);
  heatmap = new google.maps.visualization.HeatmapLayer({
    data: pointArray,
    dissipating: true,
    radius: 5
  });

  heatmap.setMap(null);
}

// fire up our google map
function initMap(centerpointLat, centerpointLon, zoom){
    // define the initial location of our map
    centerPoint = new google.maps.LatLng(centerpointLat, centerpointLon);
    var mapOptions = {
    zoom: zoom,
    center: centerPoint,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
  google.maps.event.addListener(map, 'mousedown', markerSelectDown);
  google.maps.event.addListener(map, 'mouseup', markerSelectUp);

}

function initIcons(){
    var pickupIcon = "img/icons/greenCircle.png";
    pickupMarkers = [];

  $.getJSON("../server/getPointsOfInterest.php", function(data) {
    // Lib.ajax.getJSON({
        // url:"/server/getPointsOfInterest.php",
        // type: "json"
        // }, function(data){
       for (var i = data.length - 1; i >= 0; i--) {
           var types = [null, "img/icons/blueCircle.png" ,"img/icons/redCircle.png" ,"img/icons/greenCircle.png" ];
           var marker =  new google.maps.Marker({position: new google.maps.LatLng(data[i].lat,data[i].lon),
                                                map: map,
                                                icon: types[data[i].fkType]
                                            });

           pickupMarkers.push(marker);
       };
       for (var i = pickupMarkers.length - 1; i >= 0; i--) {
            pickupMarkers[i].setVisible(false);
            //Add a custom field to the markers so we can have the information that goes in the infobox
            pickupMarkers[i].messageData = data[i].message;

            google.maps.event.addListener(pickupMarkers[i], "click", function () {
                var info = new google.maps.InfoWindow();
                info.setContent(this.messageData);
                info.setPosition(this.position);
                info.open(map);

            });
        }
    });

    markerFlag = false;
}

function toggleHeatmap() {
    heatmap.setMap(heatmap.getMap() ? null : map);
}

function toggleIcons(){
    var newState;
    if(markerFlag){
        newState = false;
        markerFlag = false;
    }else{
        newState = true;
        markerFlag = true;
    }
    for (var i = 0; i < pickupMarkers.length; i++){
        pickupMarkers[i].setVisible(newState);
    }
}

// add an icon for a pickup
function addPickupMarker(){
    var marker = new google.maps.Marker({
        position: markerEvent.latLng,
        map: map,
        icon: "img/icons/greenCircle.png"
    });
    pickupMarkers.push(marker);

    var info = new google.maps.InfoWindow();
    info.setContent('<form id="hook" class="infowindow pickup" method="GET" action="../server/communication.php"><input type="hidden" name="lat" value="'+marker.position.lat()+'"/><input type="hidden" name="lon" value="'+marker.position.lng()+'" /><textarea name="message"/></textarea><input type="hidden" name="topic" value="3" /><input type="hidden" name="add" /><input type="submit"  onmousedown="showToggleContainer" />');
    info.setPosition(marker.position);
    info.open(map);
}

// add an icon for a Comment location
function addCommentMarker(){
    var marker = new google.maps.Marker({
        position: markerEvent.latLng,
        map: map,
        icon: "img/icons/blueCircle.png"
    });
    pickupMarkers.push(marker);

    var info = new google.maps.InfoWindow();
    info.setContent('<form id="hook" class="infowindow comment" method="GET" action="../server/communication.php"><input type="hidden" name="lat" value="'+marker.position.lat()+'"/><input type="hidden" name="lon" value="'+marker.position.lng()+'" /><textarea name="message"/></textarea><input type="hidden" name="topic" value="1" /><input type="hidden" name="add" /><input type="submit"  onmousedown="showToggleContainer" />');
    info.setPosition(marker.position);
    info.open(map);
}

// add an icon to indicate where trash was found
function addTrashMarker(){
    var marker = new google.maps.Marker({
        position: markerEvent.latLng,
        map: map,
        icon: "img/icons/redCircle.png"
    });
    pickupMarkers.push(marker);

    //corresponds to the help needed
    var info = new google.maps.InfoWindow();
    info.setContent('<form id="hook" class="infowindow helpme" method="GET" action="../server/communication.php"><input type="hidden" name="lat" value="'+marker.position.lat()+'"/><input type="hidden" name="lon" value="'+marker.position.lng()+'" /><textarea name="message"/></textarea><input type="hidden" name="topic" value="2" /><input type="hidden" name="add" /><input type="submit"  onmousedown="showToggleContainer" />');
    info.setPosition(marker.position);
    info.open(map);
}

function showToggleContainer(){
    // $('.toggleContainer').show();
    document.getElementById("toggleContainer").className = "showBlock";
}

function markerSelectUp(event){
    markerEvent = event;
    MOUSEUP_TIME = new Date().getTime() / 1000;
    if((MOUSEUP_TIME - MOUSEDOWN_TIME) < 0.3){
        // alert((MOUSEUP_TIME - MOUSEDOWN_TIME));
        $('#markerTypeDialog').toggle();
        MOUSEDOWN_TIME =0;
        MOUSEDOWN_TIME =0;
    }else{
        MOUSEDOWN_TIME =0;
        MOUSEDOWN_TIME =0;
    }
}

// native javascript version of $.getJSON
// http://gabrieleromanato.name/javascript-implementing-getjson-from-scratch/

function markerSelectDown(event){
    markerEvent = event;
    MOUSEDOWN_TIME = new Date().getTime() / 1000;
    // if((MOUSEUP_TIME - MOUSEDOWN_TIME) < 2){
    //     $('#markerTypeDialog').toggle();
    //     MOUSEDOWN_TIME =0;
    //     MOUSEDOWN_TIME =0;
    // }else{
    //     MOUSEDOWN_TIME =0;
    //     MOUSEDOWN_TIME =0;
    // }
}

function changeRadius() {
  heatmap.setOptions({radius: heatmap.get('radius') ? null : 20});
}

function changeOpacity() {
  heatmap.setOptions({opacity: heatmap.get('opacity') ? null : 0.2});
}

// $(document).ready(function(){
document.addEventListener('DOMContentLoaded',function(){

    // our native replacement for jquery.getJSON
    var Lib = {
            ajax: {
                xhr: function() {
                    var instance = new XMLHttpRequest();
                    return instance;
                },

                getJSON: function(options, callback) {
                    var xhttp = this.xhr();
                    options.url = options.url || location.href;
                    options.data = options.data || null;
                    callback = callback ||
                    function() {};
                    options.type = options.type || 'json';
                    var url = options.url;
                    if (options.type == 'jsonp') {
                        window.jsonCallback = callback;
                        var $url = url.replace('callback=?', 'callback=jsonCallback');
                        var script = document.createElement('script');
                        script.src = $url;
                        document.body.appendChild(script);
                    }
                    xhttp.open('GET', options.url, true);
                    xhttp.send(options.data);
                    xhttp.onreadystatechange = function() {
                        if (xhttp.status == 200 && xhttp.readyState == 4) {
                            callback(xhttp.responseText);
                        }
                    };
                }
            }
        };

    window.Lib = Lib;

    document.addEventListener("touchmove", function(e){
        e.preventDefault();
    }, false);

    // var scrollable = document.getElementByClassName('scrollable');
    var toggleHeat = document.getElementById('toggleHeat');
    var toggleIco = document.getElementById('toggleIcons');
    var selectPickup = document.getElementById('selectPickup');
    var selectComment = document.getElementById('selectComment');
    var selectTrash = document.getElementById('selectTrash');

    var mapInit = document.getElementById('mapInit');
    var startButton = document.getElementById('startButton');
    var stopButton = document.getElementById('stopButton');

    toggleHeat.addEventListener('click', function() {
        toggleHeatmap();
    }, false);

    toggleIco.addEventListener('click', function() {
        toggleIcons();
    }, false);

    selectPickup.addEventListener('click', function() {
        $('#markerTypeDialog').toggle();
        // $('.toggleContainer').hide();
        document.getElementById("toggleContainer").className = "hidden";

        addPickupMarker();
    }, false);

    selectComment.addEventListener('click', function() {
        $('#markerTypeDialog').toggle();
        // $('.toggleContainer').hide();
        document.getElementById("toggleContainer").className = "hidden";
        addCommentMarker();
    }, false);

    selectTrash.addEventListener('click', function() {
        $('#markerTypeDialog').toggle();
        // $('.toggleContainer').hide();
        document.getElementById("toggleContainer").className = "hidden";
        addTrashMarker();
    }, false);

    mapInit.addEventListener('mousedown', function() {
         $('.mapDecoyContainer').hide(function(){
            $('.mapContainer').show();
        });
    }, false);

    startButton.addEventListener('mousedown', function() {
        start();
    }, false);

    stopButton.addEventListener('mousedown', function() {
        stop();
    }, false);

    var pr1 = document.getElementById("pr1");
    pr1.addEventListener('mousedown', function() {
        document.getElementById("container").className = "";
        document.getElementById("container").className = "panel2Center";
    }, false);

    var prr1 = document.getElementById("prr1");
    prr1.addEventListener('mousedown', function() {
        document.getElementById("container").className = "";
        document.getElementById("container").className = "panel3Center";
    }, false);

    var pr2 = document.getElementById("pr2");
    pr2.addEventListener('mousedown', function() {
        document.getElementById("container").className = "";
        document.getElementById("container").className = "panel3Center";
    }, false);

    var pl2 = document.getElementById("pl2");
    pl2.addEventListener('mousedown', function() {
        document.getElementById("container").className = "";
        document.getElementById("container").className = "panel1Center";
    }, false);

    var pl3 = document.getElementById("pl3");
    pl3.addEventListener('mousedown', function() {
        document.getElementById("container").className = "";
        document.getElementById("container").className = "panel2Center";
    }, false);

    var pll3 = document.getElementById("pll3");
    pll3.addEventListener('mousedown', function() {
        document.getElementById("container").className = "";
        document.getElementById("container").className = "panel1Center";
    }, false);

    //Get the parameters in the get url and expose them
    var prmstr = window.location.search.substr(1);
    var prmarr = prmstr.split ("&");
    var params = {};

    for ( var i = 0; i < prmarr.length; i++) {
        var tmparr = prmarr[i].split("=");
        params[tmparr[0]] = tmparr[1];
    }

    //Check the param and look for pane
    if(params.pane != "undefined"){
        switch(params.pane){
            case "2":
                document.getElementById("container").className = "";
                document.getElementById("container").className = "panel2Center";
                break;
            case "3":
                document.getElementById("container").className = "";
                document.getElementById("container").className = "panel3Center";
                break;
        }
    }

    // $('#map-canvas').mousedown(function(){
    //     MOUSEDOWN_TIME = new Date().getTime() / 1000;
    // });
    // $('#map-canvas').mouseup(function(){
    //     MOUSEUP_TIME = new Date().getTime() / 1000;
    // });
});
<|endoftext|>


<commit_before>var _ = require('lodash'),
    util = require("util"),
    Response = require("./response")

function SearchError(err) {
  this.name = "SearchError"
  this.message = err.msg
}

function error(err) {
  return !!err ? new SearchError(err) : null
}

SearchError.prototype = new Error()
SearchError.prototype.constructor = SearchError;

var BaseRequest = function() {
  this.request = {}
  this.bulkRequest = []

  this.in = function(index) {
    var clone = _.cloneDeep(this)
    if(index) clone.request.index = index
    return clone
  }

  this.for = function(type) {
    var clone = _.cloneDeep(this)
    clone.request.type = type
    return clone
  }
}

var Bulk = function(es) {
  this.transactions = []

  this.add = function(transactions) {
    console.log("add");
    console.dir(transactions)
    var clone = _.cloneDeep(this)
    clone.transactions = clone.transactions.concat(transactions)
    return clone
  }

  this.exec = function(cb) {
    var transactions =
      _.transform(this.transactions, function(res, t) {
        var doc = t.request.body.doc ?
          {doc: t.request.body.doc} : null
        var script = t.request.body.script ?
          t.request.body : null
        var update = {update: _.transform(_.omit(t.request, 'body'),
          function(res, val, key) {
            res['_'+key] = val
            return res
        })}
        res.push(update)
        if(doc) res.push(doc)
        else if (script) res.push(script)
        return res
      })
    es.bulk({body: transactions}, cb)
  }
}

var Update = function(es) {
  BaseRequest.call(this)

  this.doc = function(id) {
    var clone = _.cloneDeep(this)
    clone.request.id = id
    return clone
  }

  this.with = function(doc) {
    var clone = _.cloneDeep(this)
    clone.request.body = {doc: doc}
    if(!clone.request.id && doc.id) clone.request.id = doc.id
    return clone
  }

  this.withScript = function(script, params) {
    var clone = _.cloneDeep(this)
    clone.request.body = {
      script: script,
      params: params
    }
    return clone
  }

  this.exec = function(cb) {
    es.update(this.request, cb)
  }
}

var Search = function(es) {
  BaseRequest.call(this)

  this.compile = function(template) {
    var clone = _.cloneDeep(this)
    clone.template = _.template(template)
    return clone
  }

  this.exec = function(query, options, cb) {
    if(_.isFunction(options)){
      cb = options; options = {}
    }

    var clone = _.cloneDeep(this)
    _.extend(clone.request, options)
    clone.request.body = clone.template ?
      JSON.parse(clone.template(query)) : query
    es.search(clone.request, function(err, response) {
      cb(error(err), new Response(response))
    })
  }
}

util.inherits(Search, BaseRequest)
util.inherits(Update, BaseRequest)

exports.Search = Search
exports.Update = Update
exports.Bulk = Bulk
<commit_msg>remove logging<commit_after>var _ = require('lodash'),
    util = require("util"),
    Response = require("./response")

function SearchError(err) {
  this.name = "SearchError"
  this.message = err.msg
}

function error(err) {
  return !!err ? new SearchError(err) : null
}

SearchError.prototype = new Error()
SearchError.prototype.constructor = SearchError;

var BaseRequest = function() {
  this.request = {}
  this.bulkRequest = []

  this.in = function(index) {
    var clone = _.cloneDeep(this)
    if(index) clone.request.index = index
    return clone
  }

  this.for = function(type) {
    var clone = _.cloneDeep(this)
    clone.request.type = type
    return clone
  }
}

var Bulk = function(es) {
  this.transactions = []

  this.add = function(transactions) {
    var clone = _.cloneDeep(this)
    clone.transactions = clone.transactions.concat(transactions)
    return clone
  }

  this.exec = function(cb) {
    var transactions =
      _.transform(this.transactions, function(res, t) {
        var doc = t.request.body.doc ?
          {doc: t.request.body.doc} : null
        var script = t.request.body.script ?
          t.request.body : null
        var update = {update: _.transform(_.omit(t.request, 'body'),
          function(res, val, key) {
            res['_'+key] = val
            return res
        })}
        res.push(update)
        if(doc) res.push(doc)
        else if (script) res.push(script)
        return res
      })
    es.bulk({body: transactions}, cb)
  }
}

var Update = function(es) {
  BaseRequest.call(this)

  this.doc = function(id) {
    var clone = _.cloneDeep(this)
    clone.request.id = id
    return clone
  }

  this.with = function(doc) {
    var clone = _.cloneDeep(this)
    clone.request.body = {doc: doc}
    if(!clone.request.id && doc.id) clone.request.id = doc.id
    return clone
  }

  this.withScript = function(script, params) {
    var clone = _.cloneDeep(this)
    clone.request.body = {
      script: script,
      params: params
    }
    return clone
  }

  this.exec = function(cb) {
    es.update(this.request, cb)
  }
}

var Search = function(es) {
  BaseRequest.call(this)

  this.compile = function(template) {
    var clone = _.cloneDeep(this)
    clone.template = _.template(template)
    return clone
  }

  this.exec = function(query, options, cb) {
    if(_.isFunction(options)){
      cb = options; options = {}
    }

    var clone = _.cloneDeep(this)
    _.extend(clone.request, options)
    clone.request.body = clone.template ?
      JSON.parse(clone.template(query)) : query
    es.search(clone.request, function(err, response) {
      cb(error(err), new Response(response))
    })
  }
}

util.inherits(Search, BaseRequest)
util.inherits(Update, BaseRequest)

exports.Search = Search
exports.Update = Update
exports.Bulk = Bulk
<|endoftext|>


<commit_before>var famous = require('famous');

var FamousEngine    = famous.core.FamousEngine;
var Gravity3D       = famous.physics.Gravity3D;
var Particle        = famous.physics.Particle;
var PhysicsEngine   = famous.physics.PhysicsEngine;
var Spring          = famous.physics.Spring;
var Vec3            = famous.math.Vec3;

var Mesh            = famous.webglRenderables.Mesh;
var Color           = famous.utilities.Color;
var Circle          = famous.webglGeometries.Circle;
var geometry        = new Circle();

var colors          = [ [151, 131, 242], [47, 189, 232] ];
var totalCols       = 12;
var totalRows       = 10;
var world           = new PhysicsEngine();

function createColorStep(step, isDom) {
    step -= (step >= totalCols) ? totalCols : 0;
    var r = colors[0][0] - Math.round(((colors[0][0] - colors[1][0]) / totalCols) * step);
    var g = colors[0][1] - Math.round(((colors[0][1] - colors[1][1]) / totalCols) * step);
    var b = colors[0][2] - Math.round(((colors[0][2] - colors[1][2]) / totalCols) * step);
    if (isDom) return 'rgb(' + r + ',' + g + ',' + b + ')';
    return [r, g, b];
}

function Phys (node, x, y) {
    this.id = node.addComponent(this);
    this.node = node;
    this.body = new Particle({
        mass: 1,
        position: new Vec3(x, y, 0)
    });
    this.force = new Spring(null, this.body, {
        period: 0.9,
        dampingRatio: 0.12,
        anchor: new Vec3(x, y, 0)
    });
    world.add(this.body, this.force);
    node.requestUpdate(this.id);
}

Phys.prototype.onUpdate = function onUpdate () {
    var pos = this.body.position;
    this.node.setPosition(pos.x, pos.y, pos.z);
    this.node.requestUpdateOnNextTick(this.id);
};

function Dot (node, i, sceneSize) {
    node.setProportionalSize(1 / 12, 1 / 18)
        .setDifferentialSize(-4, -4);

    new Mesh(node).setGeometry(geometry)
        .setBaseColor(new Color(createColorStep(i / 18)));

    new Phys(node, sceneSize[0] * (i % totalRows) / totalRows,
        sceneSize[1] * ((((i / totalRows)|0) % totalCols) / totalCols));
}

var grav3d = new Gravity3D(null, world.bodies, {
    strength: -5e7,
    max: 1000,
    anchor: new Vec3()
});

world.add(grav3d);

document.addEventListener('mousemove', function (e) {
    grav3d.anchor.set(e.pageX, e.pageY);
});

document.addEventListener('touchmove', function (e) {
    grav3d.anchor.set(e.changedTouches[0].pageX, e.changedTouches[0].pageY);
    e.preventDefault();
});

// APP CODE
FamousEngine.init();
var scene = FamousEngine.createScene();
var worldUpdater = scene.addComponent({
    onUpdate: function (time) {
        world.update(time);
        scene.requestUpdateOnNextTick(worldUpdater);
    }
});

scene.requestUpdate(worldUpdater);

var root = scene.addChild();
var sized = false;

root.addComponent({
    onSizeChange: function (size) {
        if (!sized) {
            for (var i = 0 ; i < (totalRows * totalCols) ; i++)
                Dot(root.addChild(), i, size);
            sized = true;
        }
    }
});
<commit_msg>Let there be code<commit_after><|endoftext|>


<commit_before>var Stream = require('stream').Stream;

module.exports = function (parser) {
    var stream = new Stream;
    stream.writable = true;
    stream.readable = true;

    var selectors = [];

    stream.select = function (s, fn) {
        var sel = createSelector(s, fn);
        selectors.push(sel);
        return stream;
    };

    stream.update = function (name, t) {
        if (name === 'open') {
            selectors.forEach(function (sel) {
                sel(t, parser)
            });
        }
        else if (name === 'close') {
            selectors.forEach(function (sel) {
                sel.pending = sel.pending.filter(function (p) {
                    var done = p.level >= parser.tags.length;
                    if (done) p.callback(p.buffered);
                    return !done;
                });
            });
        }
    };

    stream.raw = function (s) {
        selectors.forEach(function (sel) {
            sel.pending.forEach(function (p) {
                p.buffered += s;
            });
        });
    };

    return stream;
};

function createSelector (selector, fn) {
    var parts = selector.split(/([\s>+]+)/).map(function (s) {
        if (s.match(/^\s+$/)) return;
        var op = s.trim();
        if (op === '>' || op === '+') return { combinator : op };

        var m = {
            name : s.match(/^([\w-]+|\*)/),
            class : s.match(/\.([\w-]+)/),
            id : s.match(/#([\w-]+)/),
            pseudo : s.match(/:([\w-]+)/),
            attribute : s.match(/\[([^\]]+)\]/),
        };

        return {
            name : m.name && m.name[1].toUpperCase(),
            class : m.class && m.class[1],
            id : m.id && m.id[1],
            pseudo : m.pseudo && m.pseudo[1],
            attribute : m.attribute && m.attribute[1],
        };
    }).filter(Boolean);

    var depth = parts.reduce(function (sum, s) {
        return sum + (s.combinator ? 0 : 1);
    }, 0);

    var sel = function (tag, parser) {
        var tags = parser.tags;
        if (depth > tags.length) return;

        // hypothesis: the selector matches
        var j = parts.length - 1;
        var i = tags.length - 1;

        for (; j >= 0; j--, i--) {
            var t = tags[i];
            var p = parts[j];

            // try to falsify the hypothesis on each tag/part match:
            if (p.name && p.name !== t.name) return;
            if (p.class && p.class !== t.attributes.class) return;
            if (p.id && p.id !== t.attributes.id) return;
        }

        var p = { level : tags.length };
        fn({
            name : tag.name.toLowerCase(),
            attributes : tag.attributes,
            html : function (cb) {
                p.buffered = '';
                p.callback = cb;
                sel.pending.push(p);
            },
        });
    };

    sel.pending = [];

    return sel;
}
<commit_msg>expiry<commit_after>var Stream = require('stream').Stream;

module.exports = function (parser) {
    var stream = new Stream;
    stream.writable = true;
    stream.readable = true;

    var selectors = [];

    stream.select = function (s, fn) {
        var sel = createSelector(s, fn);
        selectors.push(sel);
        return stream;
    };

    stream.update = function (name, t) {
        if (name === 'open') {
            selectors.forEach(function (sel) {
                sel(t, parser)
            });
        }
        else if (name === 'close') {
            selectors.forEach(function (sel) {
                sel.pending = sel.pending.filter(function (p) {
                    var done = p.level >= parser.tags.length;
                    if (done) p.callback(p.buffered);
                    return !done;
                });
            });
        }
    };

    stream.raw = function (s) {
        selectors.forEach(function (sel) {
            sel.pending.forEach(function (p) {
                p.buffered += s;
            });
        });
    };

    return stream;
};

function createSelector (selector, fn) {
    var parts = selector.split(/([\s>+]+)/).map(function (s) {
        if (s.match(/^\s+$/)) return;
        var op = s.trim();
        if (op === '>' || op === '+') return { combinator : op };

        var m = {
            name : s.match(/^([\w-]+|\*)/),
            class : s.match(/\.([\w-]+)/),
            id : s.match(/#([\w-]+)/),
            pseudo : s.match(/:([\w-]+)/),
            attribute : s.match(/\[([^\]]+)\]/),
        };

        return {
            name : m.name && m.name[1].toUpperCase(),
            class : m.class && m.class[1],
            id : m.id && m.id[1],
            pseudo : m.pseudo && m.pseudo[1],
            attribute : m.attribute && m.attribute[1],
        };
    }).filter(Boolean);

    var depth = parts.reduce(function (sum, s) {
        return sum + (s.combinator ? 0 : 1);
    }, 0);

    var sel = function (tag, parser) {
        var tags = parser.tags;
        if (depth > tags.length) return;

        // hypothesis: the selector matches
        var j = parts.length - 1;
        var i = tags.length - 1;

        for (; j >= 0; j--, i--) {
            var t = tags[i];
            var p = parts[j];

            // try to falsify the hypothesis on each tag/part match:
            if (p.name && p.name !== t.name) return;
            if (p.class && p.class !== t.attributes.class) return;
            if (p.id && p.id !== t.attributes.id) return;
        }

        var p = { level : tags.length };
        var expired = false;
        function expire () {
            throw new Error('Parse expired. You had your chance.');
        }

        fn({
            name : tag.name.toLowerCase(),
            attributes : tag.attributes,
            html : function (cb) {
                if (expired) expire();

                p.buffered = '';
                p.callback = cb;
                sel.pending.push(p);
            },
            update : function (arg) {
                if (expired) expire();
            },
            remove : function () {
                if (expired) expire();
            },
        });

        expired = true;
    };

    sel.pending = [];

    return sel;
}
<|endoftext|>