<commit_before>function random(){
	var allvids = ["https://www.youtube.com/embed/3TSD9TJ5sVM",
					"https://www.youtube.com/embed/3DgWv7EH1sI",
					"https://www.youtube.com/embed/cUSvbaBDhGw?list=PLSCcAGyv98icWAjrUD29TYLhJtRAGABp2",
					"https://www.youtube.com/embed/qCrGCSMYiSY",
					"https://www.youtube.com/embed/2zoZXKIuqk8",
					"https://www.youtube.com/embed/UUuY-Zy9jZY"
					"https://www.youtube.com/embed/5yBRRiePOIg",
					"https://www.youtube.com/embed/Nj6kgsxaUGg"] //add new videos HERE

	var numbervid = allvids.length; //how many videos
	var numberfeatured = 4; //number of videos displayed
	var	randomold = []; //new array with nothing, length of 0

	for (i = 0; i < numberfeatured; i++){ //loop through to fill the displayed videos
		var random = Math.floor(Math.random() * numbervid); //choose random number within 0-amount of videos
		var postvid = document.getElementById("Video" + i); //get content of video0...video1...video2...
		var used = randomold.length; //how many videos used
		var r = 0; //counter
		while (r < used){ //loop through all of the used
			if (random == randomold[r]){ //check if number is in the used
				random = Math.floor(Math.random() * numbervid); //changes to a random number
				r = 0; //restart loop
			}else{ //continue
				r++;
			}
		}
		var link = allvids[random]; //get the link
		postvid.src = link; //change the
		randomold.push(random); //stores numbers (index number)
	}
}<commit_msg>glitch2<commit_after>function random(){
	var allvids = ["https://www.youtube.com/embed/3TSD9TJ5sVM",
					"https://www.youtube.com/embed/3DgWv7EH1sI",
					"https://www.youtube.com/embed/cUSvbaBDhGw?list=PLSCcAGyv98icWAjrUD29TYLhJtRAGABp2",
					"https://www.youtube.com/embed/qCrGCSMYiSY",
					"https://www.youtube.com/embed/2zoZXKIuqk8",
					"https://www.youtube.com/embed/UUuY-Zy9jZY",
					"https://www.youtube.com/embed/5yBRRiePOIg",
					"https://www.youtube.com/embed/Nj6kgsxaUGg"] //add new videos HERE

	var numbervid = allvids.length; //how many videos
	var numberfeatured = 4; //number of videos displayed
	var	randomold = []; //new array with nothing, length of 0

	for (i = 0; i < numberfeatured; i++){ //loop through to fill the displayed videos
		var random = Math.floor(Math.random() * numbervid); //choose random number within 0-amount of videos
		var postvid = document.getElementById("Video" + i); //get content of video0...video1...video2...
		var used = randomold.length; //how many videos used
		var r = 0; //counter
		while (r < used){ //loop through all of the used
			if (random == randomold[r]){ //check if number is in the used
				random = Math.floor(Math.random() * numbervid); //changes to a random number
				r = 0; //restart loop
			}else{ //continue
				r++;
			}
		}
		var link = allvids[random]; //get the link
		postvid.src = link; //change the
		randomold.push(random); //stores numbers (index number)
	}
}<|endoftext|>


<commit_before>/**
 * JS implementation of an undirected Graph.
 * TODOs: 1. Add weights for the edges.
 *	  2. Add support for loops.
 */
function Graph(vertex) {
	var graph = {};
	_this = this;
	_this.graph = graph;
	_this.graph[vertex] = {};
	_this.getGraph = getGraph;
	_this.addVertex = addVertex;
	_this.numberOfVertices = numberOfVertices;
	_this.numberOfEdges = numberOfEdges;
	_this.addEdge = addEdge;
	_this.adjacentVertices = adjacentVertices;
	_this.getDegree = getDegree;
	_this.maxDegree = maxDegree;
	_this.averageDegree = averageDegree;
	_this.removeEdge = removeEdge;
	_this.isEdge = isEdge;
	_this.depthFirstSearch = depthFirstSearch;

	/* Returns current graph */
	function getGraph() {
		return _this.graph;
	}

	/* Add a vertex to graph */
	function addVertex(vertex, connectedVerticesArr) {
		_this.graph[vertex] = {};
		if(connectedVerticesArr) {
			connectedVerticesArr.forEach(function(newVertex) {
				if(!_this.graph[newVertex]) {
					_this.graph[newVertex] = {};
				}
				_this.graph[newVertex][vertex] = '';
				_this.graph[vertex][newVertex] = '';
			});
		}
	}

	/* Returns the number of vertices in the graph */
	function numberOfVertices() {
		return Object.keys(_this.graph).length;
	}

	/* Returns the number of edges in the graph */
	function numberOfEdges() {
		var keys = Object.keys(_this.graph);
		var edges = 0;
		keys.forEach(function(key) {
			edges += Object.keys(_this.graph[key]).length;
		});

		return edges/2;
	}

	/* Adds an edge in the graph */
	function addEdge(fromVertex, toVertex) {
		if(!_this.graph[fromVertex] || !_this.graph[toVertex]) {
			console.log('One of the vertices, ' + fromVertex + ' or ' + toVertex + ' does not exist in graph. Please add that vertex first using addVertex method.');
		}
		else {
			_this.graph[fromVertex][toVertex] = '';
			_this.graph[toVertex][fromVertex] = '';
		}
	}

	/* Removes an edge from the graph */
	function removeEdge(fromVertex, toVertex) {
		if(!_this.graph[fromVertex] || !_this.graph[toVertex]) {
			console.log('One of the vertices, ' + fromVertex + ' or ' + toVertex + ' does not exist in graph. Please add that vertex first using addVertex method.');
		}
		else {
			delete _this.graph[fromVertex][toVertex];
			delete _this.graph[toVertex][fromVertex];
		}
	}

	/* Returns an array of edges adjacent to a vertex */
	function adjacentVertices(vertex) {
		return Object.keys(_this.graph[vertex]);
	}

	/* Returns degree of a vertex */
	function getDegree(vertex) {
		return Object.keys(_this.adjacentVertices(vertex)).length;
	}

	/* Returns maximum degree of a graph */
	function maxDegree() {
		var maxDeg = 0;
		var vertices = Object.keys(_this.graph);
		vertices.forEach(function(vertex) {
			var degOfVertex = _this.getDegree(vertex);
			if(degOfVertex > maxDeg) {
				maxDeg = degOfVertex;
			}
		});

		return maxDeg;
	}

	/* Returns average degree of the graph */
	function averageDegree() {
		return _this.numberOfEdges() / _this.numberOfVertices();
	}

	/* Function to check if there is an edge between 2 vertices */
	function isEdge(fromVertex, toVertex) {
		var isPresent = false;
		var adjacent = _this.adjacentVertices(fromVertex);
		Object.keys(adjacent).forEach(function(vertex) {
			if(Number(adjacent[vertex]) === toVertex) {
				isPresent = true;
			}
		});

		return isPresent;
	}

	/* Implementation of depth first search. Returns the order in which elements are traversed */
	function depthFirstSearch(vertex) {
		var _isVisited = {};
		var order = [];
		return _dfs(vertex, _isVisited, order);
	}

	function _dfs(vertex, _isVisited, order) {
		_isVisited[vertex] = true;
		order.push(vertex);
		var adjacentNodes = _this.adjacentVertices(vertex);
		Object.keys(adjacentNodes).forEach(function(adjVertex) {
			if(!_isVisited[adjacentNodes[adjVertex]] === true) {
				_dfs(adjacentNodes[adjVertex], _isVisited, order);
			}
		});
		return order;
	}
}
<commit_msg>add method to find path between 2 vertices<commit_after>/**
 * JS implementation of an undirected Graph.
 * TODOs: 1. Add weights for the edges.
 *		  2. Add support for loops.
 */
function Graph(vertex) {
	var graph = {};
	_this = this;
	_this.graph = graph;
	_this.graph[vertex] = {};
	_this.getGraph = getGraph;
	_this.addVertex = addVertex;
	_this.numberOfVertices = numberOfVertices;
	_this.numberOfEdges = numberOfEdges;
	_this.addEdge = addEdge;
	_this.adjacentVertices = adjacentVertices;
	_this.getDegree = getDegree;
	_this.maxDegree = maxDegree;
	_this.averageDegree = averageDegree;
	_this.removeEdge = removeEdge;
	_this.areConnected = areConnected;
	_this.depthFirstSearch = depthFirstSearch;
	_this.pathTo = pathTo;

	/* Returns current graph */
	function getGraph() {
		return _this.graph;
	}

	/* Add a vertex to graph */
	function addVertex(vertex, connectedVerticesArr) {
		_this.graph[vertex] = {};
		if(connectedVerticesArr) {
			connectedVerticesArr.forEach(function(newVertex) {
				if(!_this.graph[newVertex]) {
					_this.graph[newVertex] = {};
				}
				_this.graph[newVertex][vertex] = '';
				_this.graph[vertex][newVertex] = '';
			});
		}
	}

	/* Returns the number of vertices in the graph */
	function numberOfVertices() {
		return Object.keys(_this.graph).length;
	}

	/* Returns the number of edges in the graph */
	function numberOfEdges() {
		var keys = Object.keys(_this.graph);
		var edges = 0;
		keys.forEach(function(key) {
			edges += Object.keys(_this.graph[key]).length;
		});

		return edges/2;
	}

	/* Adds an edge in the graph */
	function addEdge(fromVertex, toVertex) {
		if(!_this.graph[fromVertex] || !_this.graph[toVertex]) {
			console.log('One of the vertices, ' + fromVertex + ' or ' + toVertex + ' does not exist in graph. Please add that vertex first using addVertex method.');
		}
		else {
			_this.graph[fromVertex][toVertex] = '';
			_this.graph[toVertex][fromVertex] = '';
		}
	}

	/* Removes an edge from the graph */
	function removeEdge(fromVertex, toVertex) {
		if(!_this.graph[fromVertex] || !_this.graph[toVertex]) {
			console.log('One of the vertices, ' + fromVertex + ' or ' + toVertex + ' does not exist in graph. Please add that vertex first using addVertex method.');
		}
		else {
			delete _this.graph[fromVertex][toVertex];
			delete _this.graph[toVertex][fromVertex];
		}
	}

	/* Returns an array of edges adjacent to a vertex */
	function adjacentVertices(vertex) {
		return Object.keys(_this.graph[vertex]);
	}

	/* Returns degree of a vertex */
	function getDegree(vertex) {
		return Object.keys(_this.adjacentVertices(vertex)).length;
	}

	/* Returns maximum degree of a graph */
	function maxDegree() {
		var maxDeg = 0;
		var vertices = Object.keys(_this.graph);
		vertices.forEach(function(vertex) {
			var degOfVertex = _this.getDegree(vertex);
			if(degOfVertex > maxDeg) {
				maxDeg = degOfVertex;
			}
		});

		return maxDeg;
	}

	/* Returns average degree of the graph */
	function averageDegree() {
		return _this.numberOfEdges() / _this.numberOfVertices();
	}

	/* Function to check if there is an edge between 2 vertices */
	function areConnected(fromVertex, toVertex) {
		var isPresent = false;
		var adjacent = _this.adjacentVertices(fromVertex);
		Object.keys(adjacent).forEach(function(vertex) {
			if(Number(adjacent[vertex]) === toVertex) {
				isPresent = true;
			}
		});

		return isPresent;
	}

	/* Implementation of depth first search. Returns the order in which elements are traversed */
	function depthFirstSearch(vertex) {
		var _isVisited = {};
		var order = [];
		return _dfs(vertex, _isVisited, order);
	}

	function _dfs(vertex, _isVisited, order, _edgeTo) {
		_isVisited[vertex] = true;
		if(order) {
			order.push(vertex);
		}
		var adjacentNodes = _this.adjacentVertices(vertex);
		Object.keys(adjacentNodes).forEach(function(adjVertex) {
			if(!_isVisited[adjacentNodes[adjVertex]] === true) {
				if(_edgeTo) {
					_edgeTo[adjacentNodes[adjVertex]] = vertex;
				}
				_dfs(adjacentNodes[adjVertex], _isVisited, order, _edgeTo);
			}
		});
		return _edgeTo ? _edgeTo : order;
	}

	/* Returns the path between 2 vertices in the graph. If path does not exists, then returns undefined.
	 * Uses DFS to find the path
	 */
	function pathTo(fromVertex, toVertex) {
		var _edgeTo = {};
		var _isVisited = {};
		var path = [];
		_edgeTo = _dfs(fromVertex, _isVisited, undefined, _edgeTo);
		if(!_edgeTo[toVertex]) {
			return;
		}
		while(_edgeTo[toVertex] !== fromVertex) {
			path.push(toVertex);
			toVertex = _edgeTo[toVertex];
		}
		path.push(toVertex);
		path.push(fromVertex);
		return path.reverse();
	}
}
<|endoftext|>


<commit_before>class Queue {
  constructor() {
    this.items = [];
  }

  enqueue(item) {
    this.items.push(item);
  }

  [Symbol.asyncIterator]() {
    return new AsyncQueueIterator(this.items);
  }

  [Symbol.iterator]() {
    return new QueueIterator(this.items);
  }
}

class QueueIterator {
  constructor(queue) {
    this.queue = queue;
  }

  next() {
    const done = this.queue.length === 0;
    const value = this.queue.shift();

    return { value, done };
  }

  [Symbol.iterator]() {
    return this;
  }
}

class AsyncQueueIterator extends QueueIterator {
  async next() {
    // FIXME: https://github.com/babel/babel/issues/3930
    return QueueIterator.prototype.next.call(this);
  }
}

exports.Queue = Queue;
<commit_msg>use super call<commit_after>class Queue {
  constructor() {
    this.items = [];
  }

  enqueue(item) {
    this.items.push(item);
  }

  [Symbol.asyncIterator]() {
    return new AsyncQueueIterator(this.items);
  }

  [Symbol.iterator]() {
    return new QueueIterator(this.items);
  }
}

class QueueIterator {
  constructor(queue) {
    this.queue = queue;
  }

  next() {
    const done = this.queue.length === 0;
    const value = this.queue.shift();

    return { value, done };
  }

  [Symbol.iterator]() {
    return this;
  }
}

class AsyncQueueIterator extends QueueIterator {
  async next() {
    return super.next();
  }
}

exports.Queue = Queue;
<|endoftext|>


<commit_before>console.log("SIBot v0.2");
console.log("Loading...");

var config = {
        channels: ["#sibot-test"],
        server: "chat.freenode.net",
        botName: "SIbot"
};

var irc = require("irc");
var bot = new irc.Client(config.server, config.botName, { channels: config.channels });

bot.addListener('message', function (from, to, message) {
    // List of parser functions
    // (more than one conversion can be output per input message)

    feet_parse(message, to); // ft / feet
    pounds_parse(message, to); // lb / lbs
    //fahrenheit_parse(message, to); // Fahrenheit
});

function feet_parse(message, to) {
    ft_regex="[0-9]*[,]?[0-9]*[.]?[0-9]*[ ]?f[e]{0,2}t";
    if(message.search(ft_regex) != -1) {
        console.log(new Date()+": Detected feet at "+message.search(ft_regex));
        sillyNum=message.substr(message.search(ft_regex),12).match("[0-9]*[,]?[0-9]+");
        realNum=parseInt(String(sillyNum).replace(",",""))*0.3048;
        console.log(" - Got Number as "+sillyNum);
        if(realNum<10) {
            outStr="In real units: "+sillyNum+" ft = "+realNum.toFixed(2)+" m";
        } else if(realNum>5000) {
            outStr="In real units: "+sillyNum+" ft = "+Math.round(realNum/1000)+" km";
        } else {
            outStr="In real units: "+sillyNum+" ft = "+Math.round(realNum)+" m";
        }
        bot.say(to, outStr);
    }
}

function pounds_parse(message, to) {
    lb_regex="[0-9]*[,]?[.]?[0-9]+[ ]*lb";
    if(message.search(lb_regex) != -1) {
        console.log(new Date()+": Detected pounds at "+message.search(lb_regex));
        sillyNum=message.substr(message.search(lb_regex),12).match("[0-9]*[,]?[.]?[0-9]+");
        realNum=parseInt(String(sillyNum).replace(",",""))*0.453592;
        console.log(" - Got Number as "+sillyNum);
        if(realNum<1) {
            outStr="In real units: "+sillyNum+" lbs = "+Math.round(realNum*1000)+" g";
        } else {
            outStr="In real units: "+sillyNum+" lbs = "+realNum.toFixed(1)+" kg";
        }
        bot.say(to, outStr);
    }
}

function fahrenheit_parse(message, to) {
    df_regex="[0-9]*[,]?[.]?[0-9]+([ ]|[°])+F[\W]+";
    if(message.search(df_regex) != -1) {
        console.log(new Date()+": Detected fahrenheit at "+message.search(df_regex));
        sillyNum=message.substr(message.search(df_regex),12).match("[0-9]*[,]?[.]?[0-9]+");
        realNum=(parseInt(String(sillyNum).replace(",",""))-32)*(5/9);
        console.log(" - Got Number as "+sillyNum);
        outStr="In real units: "+sillyNum+" °F = "+realNum.toFixed(1)+" °C";
        bot.say(to, outStr);
    }
}

console.log("Loaded.");
<commit_msg>Swap parseInt for parseFloat<commit_after>console.log("SIBot v0.2");
console.log("Loading...");

var config = {i
        channels: ["#sibot-test"],
        server: "chat.freenode.net",
        botName: "SIbot"
};

var irc = require("irc");
var bot = new irc.Client(config.server, config.botName, { channels: config.channels });

bot.addListener('message', function (from, to, message) {
    // List of parser functions
    // (more than one conversion can be output per input message)

    feet_parse(message, to); // ft / feet
    pounds_parse(message, to); // lb / lbs
    //fahrenheit_parse(message, to); // Fahrenheit
});

function feet_parse(message, to) {
    ft_regex="[0-9]*[,]?[0-9]*[.]?[0-9]*[ ]?f[e]{0,2}t";
    if(message.search(ft_regex) != -1) {
        console.log(new Date()+": Detected feet at "+message.search(ft_regex));
        sillyNum=message.substr(message.search(ft_regex),12).match("[0-9]*[,]?[0-9]+");
        realNum=parseFloat(String(sillyNum).replace(",",""))*0.3048;
        console.log(" - Got Number as "+sillyNum);
        if(realNum<10) {
            outStr="In real units: "+sillyNum+" ft = "+realNum.toFixed(2)+" m";
        } else if(realNum>5000) {
            outStr="In real units: "+sillyNum+" ft = "+Math.round(realNum/1000)+" km";
        } else {
            outStr="In real units: "+sillyNum+" ft = "+Math.round(realNum)+" m";
        }
        bot.say(to, outStr);
    }
}

function pounds_parse(message, to) {
    lb_regex="[0-9]*[,]?[.]?[0-9]+[ ]*lb";
    if(message.search(lb_regex) != -1) {
        console.log(new Date()+": Detected pounds at "+message.search(lb_regex));
        sillyNum=message.substr(message.search(lb_regex),12).match("[0-9]*[,]?[.]?[0-9]+");
        realNum=parseFloat(String(sillyNum).replace(",",""))*0.453592;
        console.log(" - Got Number as "+sillyNum);
        if(realNum<1) {
            outStr="In real units: "+sillyNum+" lbs = "+Math.round(realNum*1000)+" g";
        } else {
            outStr="In real units: "+sillyNum+" lbs = "+realNum.toFixed(1)+" kg";
        }
        bot.say(to, outStr);
    }
}

function fahrenheit_parse(message, to) {
    df_regex="[0-9]*[,]?[.]?[0-9]+([ ]|[°])+F[\W]+";
    if(message.search(df_regex) != -1) {
        console.log(new Date()+": Detected fahrenheit at "+message.search(df_regex));
        sillyNum=message.substr(message.search(df_regex),12).match("[0-9]*[,]?[.]?[0-9]+");
        realNum=(parseFloat(String(sillyNum).replace(",",""))-32)*(5/9);
        console.log(" - Got Number as "+sillyNum);
        outStr="In real units: "+sillyNum+" °F = "+realNum.toFixed(1)+" °C";
        bot.say(to, outStr);
    }
}

console.log("Loaded.");
<|endoftext|>


<commit_before>var isMobile = false;
var snake = [[1, 0], [0, 0]]; // An array of [x, y] pairs. The head is at [0], tail is at [-1].
var board; // top left is 0, 0, bottom right is height-1, width-1
var food = [-10, -10];  // if there is no food, use this to avoid null pointers
var refreshRate = 250; // How quickly the snake moves. (ms)
var intervalId;
var gameIsStopped = true;
if (document.cookie === null) {
  document.cookie = 'speed='+refreshRate+'; highest='+maxLevel;
} else {
  cookies = document.cookie.split(';');
  for (var c=0; c<cookies.length; c++) {
    var cookie = cookies[c].split('=');
    console.log(cookie);
    if (cookie[0] == 'speed') {
      changeSpeed(cookie[1]);
    } else if (cookie[0] == 'highest') {
      maxLevel = cookie[1];
    }
  }
}

// Clears board & stops AI
function stopGame() {
  console.log("Game stopped");
  gameIsStopped = true;
  upLevel();
  board = [];
  board.length = width; // board[x][y]
  console.log("Board reset");
  for (var i = 0; i < width; i++) {
    board[i] = [];
    board[i].length = height;
  }
  food = [-10, -10];
  snake = [];
  for (var i=0; i<level+3; i++) {
    snake.unshift([i, 0]);
  }
  dir = 'right';
  debugSnake();
  updateBoard();
  console.log("Game ready");
}

// Snake collided with self, start next AI level
function startGame() {
  if (!gameIsStopped) {
    return;
  }
  gameIsStopped = false;
  console.log("Game started");
  console.log(level);
  console.log(refreshRate);
  console.log("Round ended! Advancing to AI level", level);
  intervalId = window.setInterval(ai, refreshRate, level); // calls ai(level) at refreshRate
  ai(level);
}

function changeSpeed(rate) {
  refreshRate = rate; // set to new value
  window.clearInterval(intervalId);
  if (!gameIsStopped) { // ensures only one interval going on at once
    intervalId = window.setInterval(ai, refreshRate, level); // calls ai(level) at refreshRate
    ai(level);
  }
}

function debugSnake() {
  for (var s=0; s<snake.length; s++) {
    console.log(snake[s][0], snake[s][1]);
  }
}

function inSnakeTwice(string) {
  var count = 0;
  for (var s=0; s<snake.length; s++) {
    if (string == snake[s][0]+'_'+snake[s][1]) {
      count++;
    }
  }
  return count==2;
}

// String is of form x_y to allow compatibility with Board.js
function inSnake(string) {
  for (var s=0; s<snake.length; s++) {
    if (string == snake[s][0]+'_'+snake[s][1]) {
      return true;
    }
  }
  return false;
}

function moveHead(dir) {
  // move snake's head in given direction
  // 'right', 'left', 'up', and 'down'
  var newHead = snake[0].slice(0); // Clone so we don't move the head by accident.
  if (dir == 'right') {
    if (newHead[0] == width - 1) {
      throw 'cannot move right from ' + newHead[0] + ', ' + newHead[1];
    } else if (inSnake((newHead[0]+1)+'_'+newHead[1])) {
      window.clearInterval(intervalId);
      window.setTimeout(stopGame, 10*refreshRate
);
    }
    newHead[0]++;
  } else if (dir == 'left') {
    if (newHead[0] === 0) {
      throw 'cannot move left from ' + newHead[0] + ', ' + newHead[1];
    } else if (inSnake((newHead[0]-1)+'_'+newHead[1])) {
      window.clearInterval(intervalId);
      window.setTimeout(stopGame, 10*refreshRate
);
    }
    newHead[0]--;
  } else if (dir == 'up') {  // add new head above current one
    if (newHead[1] === 0) {
      throw 'cannot move up from ' + newHead[0] + ', ' + newHead[1];
    } else if (inSnake(newHead[0]+'_'+(newHead[1]-1))) {
      window.clearInterval(intervalId);
      window.setTimeout(stopGame, 10*refreshRate
);
    }
    newHead[1]--;  // changes y-coordinate by -1 (going UP)
  } else if (dir == 'down') {
    if (newHead[1] == height - 1) {
      throw 'cannot move down from ' + newHead[0] + ', ' + newHead[1];
    } else if (inSnake(newHead[0]+'_'+(newHead[1]+1))) {
      window.clearInterval(intervalId);
      window.setTimeout(stopGame, 10*refreshRate
);
    }
    newHead[1]++;
  }
  snake.unshift(newHead); // add newHead to the beginning of the list
  if (snake[0][0] == food[0] && snake[0][1] == food[1]) { // if snake's head is on the food
  food = [-10, -10];
} else {
  delTail();
}
updateBoard();
}

function delTail() {  // simple function to remove the tail
  snake.pop();
}

function placeFood(x, y) {
  startGame();
  if (inSnake(x+'_'+y)) {
    console.log('Invalid food placement: Food collides with snake');
  } else if (x >= width || y >= height || x < 0 || y < 0) { // off of board
    console.log('Invalid food placement: Food is off board');
  } else {
    food = [x, y];
    console.log('Food placed at '+x+' '+y);
    updateBoard();
  }
}
<commit_msg>Still trying to fix cookies.<commit_after>var isMobile = false;
var snake = [[1, 0], [0, 0]]; // An array of [x, y] pairs. The head is at [0], tail is at [-1].
var board; // top left is 0, 0, bottom right is height-1, width-1
var food = [-10, -10];  // if there is no food, use this to avoid null pointers
var refreshRate = 250; // How quickly the snake moves. (ms)
var intervalId;
var gameIsStopped = true;
if (document.cookie === null) {
  document.cookie = 'speed='+refreshRate+'; highest='+maxLevel;
  console.log(document.cookie);
} else {
  console.log(document.cookie);
  cookies = document.cookie.split(';');
  for (var c=0; c<cookies.length; c++) {
    var cookie = cookies[c].split('=');
    console.log(cookie);
    if (cookie[0] == 'speed') {
      changeSpeed(cookie[1]);
    } else if (cookie[0] == 'highest') {
      maxLevel = cookie[1];
    }
  }
}
document.cookie = null;

// Clears board & stops AI
function stopGame() {
  console.log("Game stopped");
  gameIsStopped = true;
  upLevel();
  board = [];
  board.length = width; // board[x][y]
  console.log("Board reset");
  for (var i = 0; i < width; i++) {
    board[i] = [];
    board[i].length = height;
  }
  food = [-10, -10];
  snake = [];
  for (var i=0; i<level+3; i++) {
    snake.unshift([i, 0]);
  }
  dir = 'right';
  debugSnake();
  updateBoard();
  console.log("Game ready");
}

// Snake collided with self, start next AI level
function startGame() {
  if (!gameIsStopped) {
    return;
  }
  gameIsStopped = false;
  console.log("Game started");
  console.log(level);
  console.log(refreshRate);
  console.log("Round ended! Advancing to AI level", level);
  intervalId = window.setInterval(ai, refreshRate, level); // calls ai(level) at refreshRate
  ai(level);
}

function changeSpeed(rate) {
  refreshRate = rate; // set to new value
  window.clearInterval(intervalId);
  if (!gameIsStopped) { // ensures only one interval going on at once
    intervalId = window.setInterval(ai, refreshRate, level); // calls ai(level) at refreshRate
    ai(level);
  }
}

function debugSnake() {
  for (var s=0; s<snake.length; s++) {
    console.log(snake[s][0], snake[s][1]);
  }
}

function inSnakeTwice(string) {
  var count = 0;
  for (var s=0; s<snake.length; s++) {
    if (string == snake[s][0]+'_'+snake[s][1]) {
      count++;
    }
  }
  return count==2;
}

// String is of form x_y to allow compatibility with Board.js
function inSnake(string) {
  for (var s=0; s<snake.length; s++) {
    if (string == snake[s][0]+'_'+snake[s][1]) {
      return true;
    }
  }
  return false;
}

function moveHead(dir) {
  // move snake's head in given direction
  // 'right', 'left', 'up', and 'down'
  var newHead = snake[0].slice(0); // Clone so we don't move the head by accident.
  if (dir == 'right') {
    if (newHead[0] == width - 1) {
      throw 'cannot move right from ' + newHead[0] + ', ' + newHead[1];
    } else if (inSnake((newHead[0]+1)+'_'+newHead[1])) {
      window.clearInterval(intervalId);
      window.setTimeout(stopGame, 10*refreshRate
);
    }
    newHead[0]++;
  } else if (dir == 'left') {
    if (newHead[0] === 0) {
      throw 'cannot move left from ' + newHead[0] + ', ' + newHead[1];
    } else if (inSnake((newHead[0]-1)+'_'+newHead[1])) {
      window.clearInterval(intervalId);
      window.setTimeout(stopGame, 10*refreshRate
);
    }
    newHead[0]--;
  } else if (dir == 'up') {  // add new head above current one
    if (newHead[1] === 0) {
      throw 'cannot move up from ' + newHead[0] + ', ' + newHead[1];
    } else if (inSnake(newHead[0]+'_'+(newHead[1]-1))) {
      window.clearInterval(intervalId);
      window.setTimeout(stopGame, 10*refreshRate
);
    }
    newHead[1]--;  // changes y-coordinate by -1 (going UP)
  } else if (dir == 'down') {
    if (newHead[1] == height - 1) {
      throw 'cannot move down from ' + newHead[0] + ', ' + newHead[1];
    } else if (inSnake(newHead[0]+'_'+(newHead[1]+1))) {
      window.clearInterval(intervalId);
      window.setTimeout(stopGame, 10*refreshRate
);
    }
    newHead[1]++;
  }
  snake.unshift(newHead); // add newHead to the beginning of the list
  if (snake[0][0] == food[0] && snake[0][1] == food[1]) { // if snake's head is on the food
  food = [-10, -10];
} else {
  delTail();
}
updateBoard();
}

function delTail() {  // simple function to remove the tail
  snake.pop();
}

function placeFood(x, y) {
  startGame();
  if (inSnake(x+'_'+y)) {
    console.log('Invalid food placement: Food collides with snake');
  } else if (x >= width || y >= height || x < 0 || y < 0) { // off of board
    console.log('Invalid food placement: Food is off board');
  } else {
    food = [x, y];
    console.log('Food placed at '+x+' '+y);
    updateBoard();
  }
}
<|endoftext|>


<commit_before>Ext.define('Mba.ux.Data.Store', {
    override: 'Ext.data.Store',

    requires: [
        'Ext.ux.Deferred',
        'Ext.device.Connection'
    ],

    applyProxy: function(proxy, currentProxy) {
        if (Ext.isObject(proxy)) {
            if (!proxy.model) {
                proxy.model = this.getModel().$className;
            }
        }
        proxy = Ext.factory(proxy, Ext.data.Proxy, currentProxy, 'proxy');
        if (!proxy && this.getModel()) {
            proxy = this.getModel().getProxy();
        }

        if (!proxy) {
            proxy = new Ext.data.proxy.Memory({
                model: this.getModel()
            });
        }

        if (proxy.isMemoryProxy) {
            this.setSyncRemovedRecords(false);
        }
        return proxy;
    },

    /** Constroi a promise e faz o wrap do callback do usuario
     *  @return {Object} Contexto de execucao
     *  @return {Object} return.dfd: A instancia do deferred com a promessa
     *  @return {Object} return.options: Objeto options alterado para ser passado para callParent
     *  @return {Object} return.scope: Escopo de chamada, o mesmo scope passado para a funcao
     *  @private
     **/
    prepareDeferred: function(options, scope) {
        var dfd = Ext.create('Ext.ux.Deferred'),
            userCallback = Ext.emptyFn,
            me = this,
            argumentsPromise;

        options = options || {};

        if (Ext.isFunction(options)) {
            userCallback = options;
            options = {};
        } else if (Ext.isObject(options)) {
            userCallback = options.callback || Ext.emptyFn;
        }

        options.callback = function() {
            userCallback.apply(me, arguments);
            argumentsPromise = Ext.Array.slice(arguments);
            argumentsPromise.push(me);
            if (arguments[2]) {
                dfd.resolve.apply(dfd, argumentsPromise);
                return;
            }
            if (argumentsPromise[1].error.status === 0 || argumentsPromise[1].error.status === 404) {
                Ext.Msg.alert('Atenção', MbaLocale.get('MSG_ERRO_TIMEOUT'));
                this.removeAll();
                dfd.resolve.apply(dfd, argumentsPromise);
                return;
            }
            dfd.reject.apply(dfd, argumentsPromise);
        };

        return {
            dfd: dfd,
            options: options,
            scope: scope
        };
    },

    /** Executa uma funcao de load deffered. Os parametros sao os mesmos
     *  de uma store normal
     *  @returns {Object} Uma promessa de load */
    load: function(options, scope) {
        var r = this.prepareDeferred(options, scope),
            promise = r.dfd.promise(), remoteProxys = ['Mba.ux.Data.MbaRestProxy', 'Ext.data.proxy.Ajax',
            'Ext.data.proxy.Rest'];
        if (this.getProxy() && remoteProxys.indexOf(this.getProxy().$className) !== -1) {
            if (!Ext.device.Connection.isOnline()) {
                r.dfd.reject([], {
                    error: {
                        statusText: 'Sem conexão de dados.'
                    }
                });
                return promise;
            }
        }

        this.callParent([r.options, r.scope]);
        return promise;
    },

    /** Executa uma funcao de loadPage deffered. Os parametros sao os mesmos
     *  de uma store normal
     *  @returns {Object} Uma promessa de loadPage */
    loadPage: function(page, options, scope) {
        var r = this.prepareDeferred(options, scope),
            promise = r.dfd.promise();
        this.callParent([page, r.options, r.scope]);
        return promise;
    },

    /** Executa uma funcao de nextPage deffered. Os parametros sao os mesmos
     *  de uma store normal
     *  @returns {Object} Uma promessa de nextPage */
    nextPage: function(options) {
        var r = this.prepareDeferred(options),
            promise = r.dfd.promise();
        this.callParent([r.options]);
        return promise;
    },

    /** Executa uma funcao de previousPage deffered. Os parametros sao os mesmos
     *  de uma store normal
     *  @returns {Object} Uma promessa de previousPage */
    previousPage: function(options) {
        var r = this.prepareDeferred(options),
            promise = r.dfd.promise();
        this.callParent([r.options]);
        return promise;
    }
});
<commit_msg>corrigindo condição<commit_after>Ext.define('Mba.ux.Data.Store', {
    override: 'Ext.data.Store',

    requires: [
        'Ext.ux.Deferred',
        'Ext.device.Connection'
    ],

    applyProxy: function(proxy, currentProxy) {
        if (Ext.isObject(proxy)) {
            if (!proxy.model) {
                proxy.model = this.getModel().$className;
            }
        }
        proxy = Ext.factory(proxy, Ext.data.Proxy, currentProxy, 'proxy');
        if (!proxy && this.getModel()) {
            proxy = this.getModel().getProxy();
        }

        if (!proxy) {
            proxy = new Ext.data.proxy.Memory({
                model: this.getModel()
            });
        }

        if (proxy.isMemoryProxy) {
            this.setSyncRemovedRecords(false);
        }
        return proxy;
    },

    /** Constroi a promise e faz o wrap do callback do usuario
     *  @return {Object} Contexto de execucao
     *  @return {Object} return.dfd: A instancia do deferred com a promessa
     *  @return {Object} return.options: Objeto options alterado para ser passado para callParent
     *  @return {Object} return.scope: Escopo de chamada, o mesmo scope passado para a funcao
     *  @private
     **/
    prepareDeferred: function(options, scope) {
        var dfd = Ext.create('Ext.ux.Deferred'),
            userCallback = Ext.emptyFn,
            me = this,
            argumentsPromise;

        options = options || {};

        if (Ext.isFunction(options)) {
            userCallback = options;
            options = {};
        } else if (Ext.isObject(options)) {
            userCallback = options.callback || Ext.emptyFn;
        }

        options.callback = function() {
            userCallback.apply(me, arguments);
            argumentsPromise = Ext.Array.slice(arguments);
            argumentsPromise.push(me);
            if (arguments[2]) {
                dfd.resolve.apply(dfd, argumentsPromise);
                return;
            }
            if (argumentsPromise[1].erro && (argumentsPromise[1].error.status === 0 || argumentsPromise[1].error.status === 404)) {
                Ext.Msg.alert('Atenção', MbaLocale.get('MSG_ERRO_TIMEOUT'));
                this.removeAll();
                dfd.resolve.apply(dfd, argumentsPromise);
                return;
            }
            dfd.reject.apply(dfd, argumentsPromise);
        };

        return {
            dfd: dfd,
            options: options,
            scope: scope
        };
    },

    /** Executa uma funcao de load deffered. Os parametros sao os mesmos
     *  de uma store normal
     *  @returns {Object} Uma promessa de load */
    load: function(options, scope) {
        var r = this.prepareDeferred(options, scope),
            promise = r.dfd.promise(), remoteProxys = ['Mba.ux.Data.MbaRestProxy', 'Ext.data.proxy.Ajax',
            'Ext.data.proxy.Rest'];
        if (this.getProxy() && remoteProxys.indexOf(this.getProxy().$className) !== -1) {
            if (!Ext.device.Connection.isOnline()) {
                r.dfd.reject([], {
                    error: {
                        statusText: 'Sem conexão de dados.'
                    }
                });
                return promise;
            }
        }

        this.callParent([r.options, r.scope]);
        return promise;
    },

    /** Executa uma funcao de loadPage deffered. Os parametros sao os mesmos
     *  de uma store normal
     *  @returns {Object} Uma promessa de loadPage */
    loadPage: function(page, options, scope) {
        var r = this.prepareDeferred(options, scope),
            promise = r.dfd.promise();
        this.callParent([page, r.options, r.scope]);
        return promise;
    },

    /** Executa uma funcao de nextPage deffered. Os parametros sao os mesmos
     *  de uma store normal
     *  @returns {Object} Uma promessa de nextPage */
    nextPage: function(options) {
        var r = this.prepareDeferred(options),
            promise = r.dfd.promise();
        this.callParent([r.options]);
        return promise;
    },

    /** Executa uma funcao de previousPage deffered. Os parametros sao os mesmos
     *  de uma store normal
     *  @returns {Object} Uma promessa de previousPage */
    previousPage: function(options) {
        var r = this.prepareDeferred(options),
            promise = r.dfd.promise();
        this.callParent([r.options]);
        return promise;
    }
});
<|endoftext|>


<commit_before>const WH_TIME = 0;
const ADMINS = ["Dino", "α|CraftSpider|Ω", "HiddenStorys"];

var NumWWs = 0;
var MaxWWs = 10;
var IsSleeping = 0;

var Commands = {
	"seen": function(user) {
	    postMessage("Sorry, this command doesn't work yet.");
// 		searchMessages("{V:" + user[0] + "}");
	},
	"wordWar": function(length) {
		if (length[0] > 60 || length[0] <= 0) {
			postMessage("Choose a number between 1 and 60.");
		} else if (NumWWs >= MaxWWs) {
		    postMessage("Too many word wars, I can't keep up! Wait for one to finish first.");
		} else {
		    NumWWs++;
			postMessage("I'm starting a " + length[0] + " minute word war." + (length[1]? " Keyword: " + length[1]  + "." : "") + " Go!");
			setTimeout(function() {
				NumWWs--;
				if (!IsSleeping) {
					postMessage("Word War " + (length[1]? "'" + length[1] + "' " : "") + "ends. How did you do?");
				}
			}, length[0] * 60000);
		}
	},
	"help": function (args) {
	    if (!args[0]) {
		    var helpList = "Greetings. I'm Talos, chat helper. My commands are:\n";
		    for (var C in Commands) {
		    	helpList += "^" + C + "\n";
		    }
		    helpList += "\nMy Admin Commands are:\n";
		    for (var C in ADMIN_COMMANDS) {
		    	helpList += "^" + C + "\n";
		    }
		    postMessage(helpList);
	    } else {
	        switch (args[0]) {
	            case "help":
	                postMessage("Use: ^help [Command Name]\nDescription: Help command, by default gives general information about Talos and a list of available commands. Adding the name of another command as an argument will give a more detailed description of that command. Though you probably figured that out, you're here after all :P");

	                break;
	            case "seen":
	                postMessage("Use: ^seen <Username>\nDescription:");

	                break;
	            case "toggleSleep":
	                postMessage("Use: ^toggleSleep [time]\nDescription:");

	                break;
	            case "wordWar":
	                postMessage("Use: ^wordWar <time> [keyword]\nDescription:");

	                break;
	            default:
	        }
	    }
	}
};

const ADMIN_COMMANDS = {
    "toggleSleep": function() {
    	if (IsSleeping == 0) {
    		IsSleeping = 1;
    		postMessage("Good night! Going to sleep now. To wake me, type [b]^toggleSleep[/b] again.");
    	} else {
    		IsSleeping = 0;
    		postMessage("I'm awake again, and available for user commands. To have me sleep again, type [b]^toggleSleep[/b].");
    	}
	},
};

function postMessage(message) {
    // X92.value = message;
    // X342();
    X279(message);
}

function privateMessage(name, message) {
	postMessage("/pm \"" + name + "\" " + message);
}

//Note, only sends the message to online users.
function globalMessage(message) {
	var users = X330.split("\n");
	for (var i = 1; i <= users[0]; i++) {
		user = users[i].split("	");
		privateMessage(user[0], message);	//Replace the 0 with other numbers to grab different values. 2 is last leave/exit, 4 is status, 5 is location.
	}
}

function searchMessages(term) {
	postMessage("/find " + term);

}

///requires re-init of JSBot. Automate that?
function changeName(name) {
	X292('X387');

	setTimeout(function() {
		X481.value = name;
		X544.onsubmit();
	}, 1000);
}

function closeChat() {
	X279("/close");
}

function openChat() {
	X279("/open");
}

function toggleChatLock() {
	if(X105.X398) {
		X279("/open");
	} else {
		X279("/close");
	}
}

var WHActive = false;
var WHAlertOne = false;
var WHAlertTwo = false;

function writingHour() {
    d = new Date();

    if (d.getUTCHours() == WH_TIME && d.getUTCMinutes() == 0 && !WHActive) {
        postMessage("[b]Writing Hour has started.[/b] Have fun, and use it productively!");
        WHActive = true;
        setTimeout(function() {closeChat();}, 500);
        setTimeout(function() {
            openChat();
            setTimeout(function() {postMessage("[b]Writing Hour is over.[/b] How did you do?");}, 500);
            WHActive = false;
            WHAlertTwo = false;
            WHAlertOne = false;
        }, 60 * 60000);

    } else if (d.getUTCHours() == (WH_TIME == 0 ? 23 : WH_TIME - 1)  && d.getUTCMinutes() == 50 && !WHAlertOne) {
        postMessage("[b][Alert][/b] Writing Hour starts in 10 minutes!");
        WHAlertOne = true;

    } else if (d.getUTCHours() == (WH_TIME == 0 ? 23 : WH_TIME - 1) && d.getUTCMinutes() == 55 && !WHAlertTwo) {
        postMessage("[b][Alert][/b] Writing Hour starts in 5 minutes!");
        WHAlertTwo = true;
    }
}

function readChat() {
	var Messages = X17("X138").innerHTML.split("\n");
	for (var i = 1; i < Messages.length; i++) {
		var Message = Messages[i];
		if (Message.match(/(.*)<\/b>: \^(\w+)(?:\s(.+))?/)) { //Instead of matching a set list of commands, match the word then check it against a dict?
		    var User = RegExp.$1;
			var Command = RegExp.$2;
			var Args = RegExp.$3.split(/[\s]| <span/);
		    var isAdmin = false;
			for (var U in ADMINS) {
			    if (User == ADMINS[U]) {
			        isAdmin = true;
			        break;
			    }
			}
			if (window["ADMIN_COMMANDS"][Command] && isAdmin) {
			    window["ADMIN_COMMANDS"][Command](Args);
			} else if (IsSleeping == 1) {
				break;
			} else if (window["ADMIN_COMMANDS"][Command] && !isAdmin) {
			    postMessage("Sorry, that command is Admin only, and I don't recognize you!");
			} else if (window["Commands"][Command]) {
				window["Commands"][Command](Args);
			} else {
			    postMessage("Sorry, I don't understand that. May I suggest ^help?");
			}
		}
	}

	X17("X138").innerHTML = '
Previous messages parsed (press ESC to re-parse page)
\n';
	X783 = false;
}

function mainLoop() {
    readChat();
    writingHour();

}

setInterval(function() {mainLoop();}, 1000);
X17("X138").innerHTML = '
Previous messages hidden. (press ESC to re-parse page)
\n';
X783 = false;
<commit_msg>Altered regex to stop args from grabbing things we don't care about<commit_after>const WH_TIME = 0;
const ADMINS = ["Dino", "α|CraftSpider|Ω", "HiddenStorys"];

var NumWWs = 0;
var MaxWWs = 10;
var IsSleeping = 0;

var Commands = {
	"seen": function(user) {
	    postMessage("Sorry, this command doesn't work yet.");
// 		searchMessages("{V:" + user[0] + "}");
	},
	"wordWar": function(length) {
		if (length[0] > 60 || length[0] <= 0) {
			postMessage("Choose a number between 1 and 60.");
		} else if (NumWWs >= MaxWWs) {
		    postMessage("Too many word wars, I can't keep up! Wait for one to finish first.");
		} else {
		    NumWWs++;
			postMessage("I'm starting a " + length[0] + " minute word war." + (length[1]? " Keyword: " + length[1]  + "." : "") + " Go!");
			setTimeout(function() {
				NumWWs--;
				if (!IsSleeping) {
					postMessage("Word War " + (length[1]? "'" + length[1] + "' " : "") + "ends. How did you do?");
				}
			}, length[0] * 60000);
		}
	},
	"help": function (args) {
	    if (!args[0]) {
		    var helpList = "Greetings. I'm Talos, chat helper. My commands are:\n";
		    for (var C in Commands) {
		    	helpList += "^" + C + "\n";
		    }
		    helpList += "\nMy Admin Commands are:\n";
		    for (var C in ADMIN_COMMANDS) {
		    	helpList += "^" + C + "\n";
		    }
		    postMessage(helpList);
	    } else {
	        switch (args[0]) {
	            case "help":
	                postMessage("Use: ^help [Command Name]\nDescription: Help command, by default gives general information about Talos and a list of available commands. Adding the name of another command as an argument will give a more detailed description of that command. Though you probably figured that out, you're here after all :P");

	                break;
	            case "seen":
	                postMessage("Use: ^seen <Username>\nDescription:");

	                break;
	            case "toggleSleep":
	                postMessage("Use: ^toggleSleep [time]\nDescription:");

	                break;
	            case "wordWar":
	                postMessage("Use: ^wordWar <time> [keyword]\nDescription:");

	                break;
	            default:
	        }
	    }
	}
};

const ADMIN_COMMANDS = {
    "toggleSleep": function() {
    	if (IsSleeping == 0) {
    		IsSleeping = 1;
    		postMessage("Good night! Going to sleep now. To wake me, type [b]^toggleSleep[/b] again.");
    	} else {
    		IsSleeping = 0;
    		postMessage("I'm awake again, and available for user commands. To have me sleep again, type [b]^toggleSleep[/b].");
    	}
	},
};

function postMessage(message) {
    // X92.value = message;
    // X342();
    X279(message);
}

function privateMessage(name, message) {
	postMessage("/pm \"" + name + "\" " + message);
}

//Note, only sends the message to online users.
function globalMessage(message) {
	var users = X330.split("\n");
	for (var i = 1; i <= users[0]; i++) {
		user = users[i].split("	");
		privateMessage(user[0], message);	//Replace the 0 with other numbers to grab different values. 2 is last leave/exit, 4 is status, 5 is location.
	}
}

function searchMessages(term) {
	postMessage("/find " + term);

}

///requires re-init of JSBot. Automate that?
function changeName(name) {
	X292('X387');

	setTimeout(function() {
		X481.value = name;
		X544.onsubmit();
	}, 1000);
}

function closeChat() {
	X279("/close");
}

function openChat() {
	X279("/open");
}

function toggleChatLock() {
	if(X105.X398) {
		X279("/open");
	} else {
		X279("/close");
	}
}

var WHActive = false;
var WHAlertOne = false;
var WHAlertTwo = false;

function writingHour() {
    d = new Date();

    if (d.getUTCHours() == WH_TIME && d.getUTCMinutes() == 0 && !WHActive) {
        postMessage("[b]Writing Hour has started.[/b] Have fun, and use it productively!");
        WHActive = true;
        setTimeout(function() {closeChat();}, 500);
        setTimeout(function() {
            openChat();
            setTimeout(function() {postMessage("[b]Writing Hour is over.[/b] How did you do?");}, 500);
            WHActive = false;
            WHAlertTwo = false;
            WHAlertOne = false;
        }, 60 * 60000);

    } else if (d.getUTCHours() == (WH_TIME == 0 ? 23 : WH_TIME - 1)  && d.getUTCMinutes() == 50 && !WHAlertOne) {
        postMessage("[b][Alert][/b] Writing Hour starts in 10 minutes!");
        WHAlertOne = true;

    } else if (d.getUTCHours() == (WH_TIME == 0 ? 23 : WH_TIME - 1) && d.getUTCMinutes() == 55 && !WHAlertTwo) {
        postMessage("[b][Alert][/b] Writing Hour starts in 5 minutes!");
        WHAlertTwo = true;
    }
}

function readChat() {
	var Messages = X17("X138").innerHTML.split("\n");
	for (var i = 1; i < Messages.length; i++) {
		var Message = Messages[i];
		if (Message.match(/(.*)<\/b>: \^(\w+)(?:\s(.+))?(?: )/)) { //Instead of matching a set list of commands, match the word then check it against a dict?
		    var User = RegExp.$1;
			var Command = RegExp.$2;
			var Args = RegExp.$3.split(/\s/);
		    var isAdmin = false;
			for (var U in ADMINS) {
			    if (User == ADMINS[U]) {
			        isAdmin = true;
			        break;
			    }
			}
			if (window["ADMIN_COMMANDS"][Command] && isAdmin) {
			    window["ADMIN_COMMANDS"][Command](Args);
			} else if (IsSleeping == 1) {
				break;
			} else if (window["ADMIN_COMMANDS"][Command] && !isAdmin) {
			    postMessage("Sorry, that command is Admin only, and I don't recognize you!");
			} else if (window["Commands"][Command]) {
				window["Commands"][Command](Args);
			} else {
			    postMessage("Sorry, I don't understand that. May I suggest ^help?");
			}
		}
	}

	X17("X138").innerHTML = '
Previous messages parsed (press ESC to re-parse page)
\n';
	X783 = false;
}

function mainLoop() {
    readChat();
    writingHour();

}

setInterval(function() {mainLoop();}, 1000);
X17("X138").innerHTML = '
Previous messages hidden. (press ESC to re-parse page)
\n';
X783 = false;
<|endoftext|>


<commit_before>import _ from 'lodash';
import fetch from 'isomorphic-fetch';
// We have to remove node_modules/react to avoid having multiple copies loaded.
// eslint-disable-next-line import/no-unresolved
import React, { PropTypes, Component } from 'react';
import Match from 'react-router/Match';

import Pane from '@folio/stripes-components/lib/Pane';
import Paneset from '@folio/stripes-components/lib/Paneset';
import PaneMenu from '@folio/stripes-components/lib/PaneMenu';
import Button from '@folio/stripes-components/lib/Button';
import Icon from '@folio/stripes-components/lib/Icon';
import MultiColumnList from '@folio/stripes-components/lib/MultiColumnList';
import FilterPaneSearch from '@folio/stripes-components/lib/FilterPaneSearch';
import FilterControlGroup from '@folio/stripes-components/lib/FilterControlGroup';
import Layer from '@folio/stripes-components/lib/Layer';

import FilterGroups, { initialFilterState, filters2cql } from '@folio/stripes-components/lib/FilterGroups';

import UserForm from './UserForm';
import ViewUser from './ViewUser';

const filterConfig = [
  {
    label: 'Filters',
    name: 'active',
    cql: 'active',
    values: [
      { name: 'Active', cql: 'true' },
      { name: 'Inactive', cql: 'false' },
    ],
  },
];

class Users extends Component {
  static contextTypes = {
    router: PropTypes.object.isRequired,
    store: PropTypes.object,
  };

  static propTypes = {
    data: PropTypes.object.isRequired,
    pathname: PropTypes.string.isRequired,
    location: PropTypes.shape({
      pathname: PropTypes.string.isRequired,
      query: PropTypes.object, // object of key=value pairs
      search: PropTypes.string, // string combining all parts of query
    }).isRequired,
    mutator: PropTypes.object,
  };

  static manifest = Object.freeze({
    addUserMode: { },
    users: {
      type: 'okapi',
      records: 'users',
      path: (queryParams, _pathComponents, _resourceValues) => {
        // console.log('Users manifest "users" path function, queryParams = ', queryParams);
        const { query, filters, sort } = queryParams || {};

        let cql;
        if (query) {
          cql = `username="${query}*" or personal.first_name="${query}*" or personal.last_name="${query}*"`;
        }

        const filterCql = filters2cql(filterConfig, filters);
        if (filterCql) {
          if (cql) {
            cql = `(${cql}) and ${filterCql}`;
          } else {
            cql = filterCql;
          }
        }

        if (sort) {
          const sortMap = {
            Active: 'active',
            Name: 'personal.last_name personal.first_name',
            Username: 'username',
            Email: 'personal.email',
          };
          const sortIndex = sortMap[sort];
          if (sortIndex) {
            if (cql === undefined) cql = 'username=*';
            cql += ` sortby ${sortIndex}`;
          }
        }

        let path = 'users';
        if (cql) path += `?query=${encodeURIComponent(cql)}`;

        console.log(`query=${query} filters=${filters} sort=${sort} -> ${path}`);
        return path;
      },
      staticFallback: { path: 'users' },
    },
  });

  constructor(props, context) {
    super(props);

    const query = props.location.query || {};
    this.state = {
      filters: initialFilterState(filterConfig, query.filters),
      selectedItem: {},
      searchTerm: query.query || '',
      sortOrder: query.sort || '',
    };
    props.mutator.addUserMode.replace({ mode: false });

    this.okapi = context.store.getState().okapi;

    this.onClickAddNewUser = this.onClickAddNewUser.bind(this);
    this.onClickCloseNewUser = this.onClickCloseNewUser.bind(this);
    this.onChangeFilter = this.onChangeFilter.bind(this);
    // this.performSearch = _.debounce(this.performSearch.bind(this), 250);
    this.performSearch = this.performSearch.bind(this); // For now, prefer instant response
    this.onChangeSearch = this.onChangeSearch.bind(this);
    this.onClearSearch = this.onClearSearch.bind(this);
    this.onSort = this.onSort.bind(this);
    this.onSelectRow = this.onSelectRow.bind(this);
  }

  // search Handlers...
  onChangeFilter(e) {
    const filters = Object.assign({}, this.state.filters);
    filters[e.target.name] = e.target.checked;
    console.log('onChangeFilter setting state', filters);
    this.setState({ filters });
    this.updateSearch(this.state.searchTerm, this.state.sortOrder, filters);
  }

  onClearSearch() {
    console.log('User cleared search');
    this.setState({ searchTerm: '' });
    this.context.router.transitionTo(this.props.location.pathname);
  }

  onSort(e, meta) {
    const sortOrder = meta.name;
    console.log('User sorted by', sortOrder);
    this.setState({ sortOrder });
    this.updateSearch(this.state.searchTerm, sortOrder, this.state.filters);
  }

  onSelectRow(e, meta) {
    const userId = meta.id;
    const username = meta.username;
    console.log('User clicked', userId, 'location = ', this.props.location);
    this.setState({ selectedItem: meta });
    this.context.router.transitionTo(`/users/view/${userId}/${username}${this.props.location.search}`);
  }

  // end search Handlers

  // AddUser Handlers
  onClickAddNewUser(e) {
    if (e) e.preventDefault();
    this.props.mutator.addUserMode.replace({ mode: true });
  }

  onClickCloseNewUser(e) {
    if (e) e.preventDefault();
    this.props.mutator.addUserMode.replace({ mode: false });
  }
  // end AddUser Handlers

  onChangeSearch(e) {
    const term = e.target.value;
    this.setState({ searchTerm: term });
    this.performSearch(term);
  }

  performSearch(term) {
    console.log('User searched:', term, 'at', this.props.location.pathname);
    this.updateSearch(term, this.state.sortOrder, this.state.filters);
  }

  // We need to explicitly pass changed values into this function,
  // as state-change only happens after event is handled.
  updateSearch(query, sortOrder, filters) {
    console.log(`updateSearch('${query}', '${sortOrder}',`, filters, ')');
    let transitionLoc = this.props.location.pathname;
    const params = {};
    if (query) params.query = query;
    if (sortOrder) params.sort = sortOrder;

    const activeFilters = [];
    for (const name in filters) {
      if (filters[name]) activeFilters.push(name);
    }

    if (activeFilters) params.filters = activeFilters.join(',');

    const keys = Object.keys(params);
    if (keys.length) {
      // eslint-disable-next-line prefer-template
      transitionLoc += '?' + keys.map(key => `${key}=${encodeURIComponent(params[key])}`).join('&');
    }
    this.context.router.transitionTo(transitionLoc);
  }

  create(data) {
    // extract creds object from user object
    const creds = Object.assign({}, data.creds, { username: data.username });
    if (data.creds) delete data.creds; // eslint-disable-line no-param-reassign
    // POST user record
    const p = this.props.mutator.users.POST(data);
    console.log('got promise', p);
    p.then((x) => {
      console.log('POST promise was OK:', x);
    }).catch((x) => {
      console.log('POST promise failed:', x);
    });
    // POST credentials, permission-user, permissions;
    this.postCreds(data.username, { credentials: creds });
    this.onClickCloseNewUser();
  }

  postCreds(username, creds) {
    fetch(`${this.okapi.url}/authn/users`, {
      method: 'POST',
      headers: Object.assign({}, { 'X-Okapi-Tenant': this.okapi.tenant, 'X-Okapi-Token': this.okapi.token }),
      body: JSON.stringify(creds),
    }).then((response) => {
      if (response.status >= 400) {
        console.log('Users. POST of creds failed.');
      } else {
        this.postPerms(username, 'users.super');
      }
    });
  }

  postPerms(username, perms) {
    fetch(`${this.okapi.url}/perms/users`, {
      method: 'POST',
      headers: Object.assign({}, { 'X-Okapi-Tenant': this.okapi.tenant, 'X-Okapi-Token': this.okapi.token }),
      body: username,
    }).then((response) => {
      if (response.status >= 400) {
        console.log('Users. POST of username failed.');
      } else {
        this.postUsersPerms(username, perms);
      }
    });
  }

  postUsersPerms(username, perm) {
    fetch(`${this.okapi.url}/perms/users/${username}/permissions`, {
      method: 'POST',
      headers: Object.assign({}, { 'X-Okapi-Tenant': this.okapi.tenant, 'X-Okapi-Token': this.okapi.token }),
      body: JSON.stringify({ permission_name: perm }),
    }).then((response) => {
      if (response.status >= 400) {
        console.log("Users. POST of user's perms failed.");
      } else {
        // nothing to do
      }
    });
  }

  render() {
    const { data, pathname } = this.props;
    const users = data.users || [];

    /* searchHeader is a 'custom pane header'*/
    const searchHeader = <FilterPaneSearch id="SearchField" onChange={this.onChangeSearch} onClear={this.onClearSearch} value={this.state.searchTerm} />;
    const resultMenu = <PaneMenu><button><Icon icon="bookmark" /></button></PaneMenu>;

    const resultsFormatter = {
      Active: user => user.active,
      Name: user => `${_.get(user, ['personal', 'last_name'], '')}, ${_.get(user, ['personal', 'first_name'], '')}`,
      Username: user => user.username,
      Email: user => _.get(user, ['personal', 'email']),
    };

    return (
      <Paneset>
        {/* Filter Pane */}
        <Pane defaultWidth="16%" header={searchHeader}>
          <FilterGroups config={filterConfig} filters={this.state.filters} onChangeFilter={this.onChangeFilter} />
          <FilterControlGroup label="Actions">
            <Button fullWidth onClick={this.onClickAddNewUser}>New user</Button>
          </FilterControlGroup>
        </Pane>
        {/* Results Pane */}
        <Pane
          defaultWidth="40%"
          paneTitle={

              Results

                {users.length} Result{users.length === 1 ? '' : 's'} Found

          }
          lastMenu={resultMenu}
        >
          <MultiColumnList
            contentData={users}
            selectedRow={this.state.selectedItem}
            rowMetadata={['id', 'username']}
            formatter={resultsFormatter}
            onRowClick={this.onSelectRow}
            onHeaderClick={this.onSort}
            visibleColumns={['Active', 'Name', 'Username', 'Email']}
            fullWidth
            sortOrder={this.state.sortOrder}
            isEmptyMessage={`No results found for "${this.state.searchTerm}". Please check your spelling and filters.`}
          />
        </Pane>

        {/* Details Pane */}
        <Match pattern={`${pathname}/view/:userid/:username`} render={props => <ViewUser placeholder={'placeholder'} {...props} />} />
        <Layer isOpen={data.addUserMode ? data.addUserMode.mode : false} label="Add New User Dialog">
          <UserForm
            onSubmit={(record) => { this.create(record); }}
            onCancel={this.onClickCloseNewUser}
          />
        </Layer>
      </Paneset>
    );
  }
}

export default Users;
<commit_msg>Break onChangeFilter into two functions: long, generic onChangeFilter and short, items-specific updateFilters. Preparatory to moving the former into the FilterGroups library.<commit_after>import _ from 'lodash';
import fetch from 'isomorphic-fetch';
// We have to remove node_modules/react to avoid having multiple copies loaded.
// eslint-disable-next-line import/no-unresolved
import React, { PropTypes, Component } from 'react';
import Match from 'react-router/Match';

import Pane from '@folio/stripes-components/lib/Pane';
import Paneset from '@folio/stripes-components/lib/Paneset';
import PaneMenu from '@folio/stripes-components/lib/PaneMenu';
import Button from '@folio/stripes-components/lib/Button';
import Icon from '@folio/stripes-components/lib/Icon';
import MultiColumnList from '@folio/stripes-components/lib/MultiColumnList';
import FilterPaneSearch from '@folio/stripes-components/lib/FilterPaneSearch';
import FilterControlGroup from '@folio/stripes-components/lib/FilterControlGroup';
import Layer from '@folio/stripes-components/lib/Layer';

import FilterGroups, { initialFilterState, filters2cql } from '@folio/stripes-components/lib/FilterGroups';

import UserForm from './UserForm';
import ViewUser from './ViewUser';

const filterConfig = [
  {
    label: 'Filters',
    name: 'active',
    cql: 'active',
    values: [
      { name: 'Active', cql: 'true' },
      { name: 'Inactive', cql: 'false' },
    ],
  },
];

class Users extends Component {
  static contextTypes = {
    router: PropTypes.object.isRequired,
    store: PropTypes.object,
  };

  static propTypes = {
    data: PropTypes.object.isRequired,
    pathname: PropTypes.string.isRequired,
    location: PropTypes.shape({
      pathname: PropTypes.string.isRequired,
      query: PropTypes.object, // object of key=value pairs
      search: PropTypes.string, // string combining all parts of query
    }).isRequired,
    mutator: PropTypes.object,
  };

  static manifest = Object.freeze({
    addUserMode: { },
    users: {
      type: 'okapi',
      records: 'users',
      path: (queryParams, _pathComponents, _resourceValues) => {
        // console.log('Users manifest "users" path function, queryParams = ', queryParams);
        const { query, filters, sort } = queryParams || {};

        let cql;
        if (query) {
          cql = `username="${query}*" or personal.first_name="${query}*" or personal.last_name="${query}*"`;
        }

        const filterCql = filters2cql(filterConfig, filters);
        if (filterCql) {
          if (cql) {
            cql = `(${cql}) and ${filterCql}`;
          } else {
            cql = filterCql;
          }
        }

        if (sort) {
          const sortMap = {
            Active: 'active',
            Name: 'personal.last_name personal.first_name',
            Username: 'username',
            Email: 'personal.email',
          };
          const sortIndex = sortMap[sort];
          if (sortIndex) {
            if (cql === undefined) cql = 'username=*';
            cql += ` sortby ${sortIndex}`;
          }
        }

        let path = 'users';
        if (cql) path += `?query=${encodeURIComponent(cql)}`;

        console.log(`query=${query} filters=${filters} sort=${sort} -> ${path}`);
        return path;
      },
      staticFallback: { path: 'users' },
    },
  });

  constructor(props, context) {
    super(props);

    const query = props.location.query || {};
    this.state = {
      filters: initialFilterState(filterConfig, query.filters),
      selectedItem: {},
      searchTerm: query.query || '',
      sortOrder: query.sort || '',
    };
    props.mutator.addUserMode.replace({ mode: false });

    this.okapi = context.store.getState().okapi;

    this.onClickAddNewUser = this.onClickAddNewUser.bind(this);
    this.onClickCloseNewUser = this.onClickCloseNewUser.bind(this);
    this.onChangeFilter = this.onChangeFilter.bind(this);
    // this.performSearch = _.debounce(this.performSearch.bind(this), 250);
    this.performSearch = this.performSearch.bind(this); // For now, prefer instant response
    this.onChangeSearch = this.onChangeSearch.bind(this);
    this.onClearSearch = this.onClearSearch.bind(this);
    this.onSort = this.onSort.bind(this);
    this.onSelectRow = this.onSelectRow.bind(this);
  }

  // search Handlers...
  onChangeFilter(e) {
    const filters = Object.assign({}, this.state.filters);
    filters[e.target.name] = e.target.checked;
    console.log('onChangeFilter setting state', filters);
    this.setState({ filters });
    this.updateFilters(filters);
  }

  updateFilters(filters) {
    this.updateSearch(this.state.searchTerm, this.state.sortOrder, filters);
  }

  onClearSearch() {
    console.log('User cleared search');
    this.setState({ searchTerm: '' });
    this.context.router.transitionTo(this.props.location.pathname);
  }

  onSort(e, meta) {
    const sortOrder = meta.name;
    console.log('User sorted by', sortOrder);
    this.setState({ sortOrder });
    this.updateSearch(this.state.searchTerm, sortOrder, this.state.filters);
  }

  onSelectRow(e, meta) {
    const userId = meta.id;
    const username = meta.username;
    console.log('User clicked', userId, 'location = ', this.props.location);
    this.setState({ selectedItem: meta });
    this.context.router.transitionTo(`/users/view/${userId}/${username}${this.props.location.search}`);
  }

  // end search Handlers

  // AddUser Handlers
  onClickAddNewUser(e) {
    if (e) e.preventDefault();
    this.props.mutator.addUserMode.replace({ mode: true });
  }

  onClickCloseNewUser(e) {
    if (e) e.preventDefault();
    this.props.mutator.addUserMode.replace({ mode: false });
  }
  // end AddUser Handlers

  onChangeSearch(e) {
    const term = e.target.value;
    this.setState({ searchTerm: term });
    this.performSearch(term);
  }

  performSearch(term) {
    console.log('User searched:', term, 'at', this.props.location.pathname);
    this.updateSearch(term, this.state.sortOrder, this.state.filters);
  }

  // We need to explicitly pass changed values into this function,
  // as state-change only happens after event is handled.
  updateSearch(query, sortOrder, filters) {
    console.log(`updateSearch('${query}', '${sortOrder}',`, filters, ')');
    let transitionLoc = this.props.location.pathname;
    const params = {};
    if (query) params.query = query;
    if (sortOrder) params.sort = sortOrder;

    const activeFilters = [];
    for (const name in filters) {
      if (filters[name]) activeFilters.push(name);
    }

    if (activeFilters) params.filters = activeFilters.join(',');

    const keys = Object.keys(params);
    if (keys.length) {
      // eslint-disable-next-line prefer-template
      transitionLoc += '?' + keys.map(key => `${key}=${encodeURIComponent(params[key])}`).join('&');
    }
    this.context.router.transitionTo(transitionLoc);
  }

  create(data) {
    // extract creds object from user object
    const creds = Object.assign({}, data.creds, { username: data.username });
    if (data.creds) delete data.creds; // eslint-disable-line no-param-reassign
    // POST user record
    const p = this.props.mutator.users.POST(data);
    console.log('got promise', p);
    p.then((x) => {
      console.log('POST promise was OK:', x);
    }).catch((x) => {
      console.log('POST promise failed:', x);
    });
    // POST credentials, permission-user, permissions;
    this.postCreds(data.username, { credentials: creds });
    this.onClickCloseNewUser();
  }

  postCreds(username, creds) {
    fetch(`${this.okapi.url}/authn/users`, {
      method: 'POST',
      headers: Object.assign({}, { 'X-Okapi-Tenant': this.okapi.tenant, 'X-Okapi-Token': this.okapi.token }),
      body: JSON.stringify(creds),
    }).then((response) => {
      if (response.status >= 400) {
        console.log('Users. POST of creds failed.');
      } else {
        this.postPerms(username, 'users.super');
      }
    });
  }

  postPerms(username, perms) {
    fetch(`${this.okapi.url}/perms/users`, {
      method: 'POST',
      headers: Object.assign({}, { 'X-Okapi-Tenant': this.okapi.tenant, 'X-Okapi-Token': this.okapi.token }),
      body: username,
    }).then((response) => {
      if (response.status >= 400) {
        console.log('Users. POST of username failed.');
      } else {
        this.postUsersPerms(username, perms);
      }
    });
  }

  postUsersPerms(username, perm) {
    fetch(`${this.okapi.url}/perms/users/${username}/permissions`, {
      method: 'POST',
      headers: Object.assign({}, { 'X-Okapi-Tenant': this.okapi.tenant, 'X-Okapi-Token': this.okapi.token }),
      body: JSON.stringify({ permission_name: perm }),
    }).then((response) => {
      if (response.status >= 400) {
        console.log("Users. POST of user's perms failed.");
      } else {
        // nothing to do
      }
    });
  }

  render() {
    const { data, pathname } = this.props;
    const users = data.users || [];

    /* searchHeader is a 'custom pane header'*/
    const searchHeader = <FilterPaneSearch id="SearchField" onChange={this.onChangeSearch} onClear={this.onClearSearch} value={this.state.searchTerm} />;
    const resultMenu = <PaneMenu><button><Icon icon="bookmark" /></button></PaneMenu>;

    const resultsFormatter = {
      Active: user => user.active,
      Name: user => `${_.get(user, ['personal', 'last_name'], '')}, ${_.get(user, ['personal', 'first_name'], '')}`,
      Username: user => user.username,
      Email: user => _.get(user, ['personal', 'email']),
    };

    return (
      <Paneset>
        {/* Filter Pane */}
        <Pane defaultWidth="16%" header={searchHeader}>
          <FilterGroups config={filterConfig} filters={this.state.filters} onChangeFilter={this.onChangeFilter} />
          <FilterControlGroup label="Actions">
            <Button fullWidth onClick={this.onClickAddNewUser}>New user</Button>
          </FilterControlGroup>
        </Pane>
        {/* Results Pane */}
        <Pane
          defaultWidth="40%"
          paneTitle={

              Results

                {users.length} Result{users.length === 1 ? '' : 's'} Found

          }
          lastMenu={resultMenu}
        >
          <MultiColumnList
            contentData={users}
            selectedRow={this.state.selectedItem}
            rowMetadata={['id', 'username']}
            formatter={resultsFormatter}
            onRowClick={this.onSelectRow}
            onHeaderClick={this.onSort}
            visibleColumns={['Active', 'Name', 'Username', 'Email']}
            fullWidth
            sortOrder={this.state.sortOrder}
            isEmptyMessage={`No results found for "${this.state.searchTerm}". Please check your spelling and filters.`}
          />
        </Pane>

        {/* Details Pane */}
        <Match pattern={`${pathname}/view/:userid/:username`} render={props => <ViewUser placeholder={'placeholder'} {...props} />} />
        <Layer isOpen={data.addUserMode ? data.addUserMode.mode : false} label="Add New User Dialog">
          <UserForm
            onSubmit={(record) => { this.create(record); }}
            onCancel={this.onClickCloseNewUser}
          />
        </Layer>
      </Paneset>
    );
  }
}

export default Users;
<|endoftext|>


<commit_before>'use strict';

var React = require('react-native');
var AppList = require("../Components/AppList");
var NoResults = require('../Components/NoResults');

var {
  StyleSheet,
  Text,
  View,
  ListView,
  TextInput,
} = React;

var Explore = React.createClass({
  getInitialState() {
    return {
      searchText: '',
      showAppList: false
    }
  },

  _handleSearch() {
    this.setState({
      showAppList: false,
      searchUrl: `/apps/search.json?name=${this.state.searchText}`
    });

    if (this.state.searchText !== '') {
      this.setState({ showAppList: true });
    }
  },

  renderList() {
    return(
      <AppList url={this.state.searchUrl} />
    );
  },

  renderNoResults() {
    return(
      <NoResults />
    );
  },

  render(){
    return (
      <View style={styles.mainContainer}>
        <View style={styles.searchRow}>
          <View style={styles.inputContainer}>
            <TextInput
              autoCapitalize="none"
              autoCorrect={false}
              autoFocus={true}
              clearButtonMode="always"
              returnKeyType={'search'}
              placeholder="SEARCH..."
              style={styles.input}
              onChangeText={(text) => this.setState({searchText: text})}
              onSubmitEditing={this._handleSearch}
            />
          </View>
        </View>
        {this.state.showAppList ? this.renderList() : this.renderNoResults()}
      </View>
    )
  }
});

var styles = StyleSheet.create({
  mainContainer: {
    flex: 1,
  },
  searchRow: {
    backgroundColor: '#f3f3f3',
    padding: 10,
  },
  input: {
    height: 40,
    padding: 5,
    fontSize: 14,
    color: 'black',
  },
  inputContainer: {
    borderBottomWidth: 1,
    borderColor: '#ccc',
    margin: 5,
    marginTop: 0,
  },
});

module.exports = Explore;
<commit_msg>Fixes AppList overlap issue on the Search screen<commit_after>'use strict';

var React = require('react-native');
var AppList = require("../Components/AppList");
var NoResults = require('../Components/NoResults');

var {
  StyleSheet,
  Text,
  View,
  ListView,
  TextInput,
} = React;

var Explore = React.createClass({
  getInitialState() {
    return {
      searchText: '',
      showAppList: false
    }
  },

  _handleSearch() {
    this.setState({
      showAppList: false,
      searchUrl: `/apps/search.json?name=${this.state.searchText}`
    });

    if (this.state.searchText !== '') {
      this.setState({ showAppList: true });
    }
  },

  renderList() {
    return(
      <AppList url={this.state.searchUrl} />
    );
  },

  renderNoResults() {
    return(
      <NoResults />
    );
  },

  render(){
    return (
      <View style={styles.mainContainer}>
        <View style={styles.searchRow}>
          <View style={styles.inputContainer}>
            <TextInput
              autoCapitalize="none"
              autoCorrect={false}
              autoFocus={true}
              clearButtonMode="always"
              returnKeyType={'search'}
              placeholder="SEARCH..."
              style={styles.input}
              onChangeText={(text) => this.setState({searchText: text})}
              onSubmitEditing={this._handleSearch}
            />
          </View>
        </View>
        {this.state.showAppList ? this.renderList() : this.renderNoResults()}
      </View>
    )
  }
});

var styles = StyleSheet.create({
  mainContainer: {
    flex: 1,
  },
  searchRow: {
    backgroundColor: '#f3f3f3',
    padding: 10,
    marginBottom: 9,
  },
  input: {
    height: 40,
    padding: 5,
    fontSize: 14,
    color: 'black',
  },
  inputContainer: {
    borderBottomWidth: 1,
    borderColor: '#ccc',
    margin: 5,
    marginTop: 0,
  },
});

module.exports = Explore;
<|endoftext|>


<commit_before>'use strict';

const AWS = require('aws-sdk');
const region = process.env.AWS_REGION || 'us-west-2';
const dynamo = new AWS.DynamoDB({region: region});
const sqs = new AWS.SQS({region: region});

const userCounts = require('./lib/userCounts.js');
const overallCounts = require('./lib/overallCounts.js');

exports.handler = (event, context, callback) => {
    processNext(event, callback);
};

function processNext(context, callback) {
    getJob(context)
        .then(getChildren)
        .then(userCounts.merge)
        .then(userCounts.pack)
        .then(overallCounts.merge)
        .then(overallCounts.pack)
        .then(writeToDynamo)
        .then(markJobDone)
        .then(() => {
            processNext(context, callback);
        }).catch((err) => {
            if (err.no_messages) {
                // retries or concurrency checks here in the future
                return callback(null);
            } else {
                err.context = context;
                console.error(err.stack);
                return callback(err);
            }
        });
}

function getJob(context) {
    return new Promise((resolve, reject) => {
        if (context.source) {
            if (context.source === 'perTenMinTrigger') {
                context.queue = process.env.perTenMinQueue;
            } else {
                context.queue = process.env.perMinQueue;
            }
        } else {
            return reject(new Error('missing source'));
        }

        sqs.receiveMessage({
            QueueUrl: context.queue,
            VisibilityTimeout: 10
        }, (err, data) => {
            if (err) return reject(err);
            if (!data.Messages) return reject({no_messages: true});

            console.log('starting', data.Messages[0].Body);
            context.job = JSON.parse(data.Messages[0].Body);
            context.job.ReceiptHandle = data.Messages[0].ReceiptHandle;

            // validate the key real quick, this should be a lib
            if (context.job.jobType === 'minute') context.job.key = context.job.key.slice(0, 16);
            if (context.job.jobType === 'hour') context.job.key = context.job.key.slice(0, 13);
            if (context.job.jobType === 'day') context.job.key = context.job.key.slice(0, 10);
            if (context.job.jobType === 'month') context.job.key = context.job.key.slice(0, 7);

            resolve(context);
        });
    });
}

function markJobDone(context) {
    return new Promise((resolve, reject) => {
        sqs.deleteMessage({
            QueueUrl: context.queue,
            ReceiptHandle: context.job.ReceiptHandle
        }, (err, data) => {
            if (err) return reject(err);

            delete context.job.data;
            delete context.job.children;

            console.log('finished', JSON.stringify(context.job));

            delete context.job;
            resolve(context);
        });
    });
}

function getChildren(context) {
    // get all the children for the given parent

    return new Promise((resolve, reject) => {
        // all jobs want these things for now, that might change
        const projExpression = ['#SEQUENCE', '#OVERALLCOUNTS'];
        const xprsnAttrNames = {
            '#PARENT': 'parent',
            '#OVERALLCOUNTS': 'overallCounts',
            '#SEQUENCE': 'sequence'
        };

        if (context.job.jobType === 'minute' ||
            context.job.jobType === 'hour') {
            projExpression.push('#USERCOUNTS');
            xprsnAttrNames['#USERCOUNTS'] = 'userCounts';
        }

        dynamo.query({
            TableName: process.env.MainTable,
            Select: 'SPECIFIC_ATTRIBUTES',
            KeyConditionExpression: '#PARENT = :parent',
            ProjectionExpression: projExpression.join(', '),
            ExpressionAttributeNames: xprsnAttrNames,
            ExpressionAttributeValues: {
                ':parent': {S: context.job.key}
            }
        }, (err, data) => {
            if (err) return reject(err);
            context.job.children = data.Items;
            resolve(context);
        });
    });
}

function writeToDynamo(context) {
    // dynamically write all data

    return new Promise((resolve, reject) => {
        const attrs = [];
        for (const attr in context.job.data) {
            attrs.push(attr);
        }

        const attrNames = {};
        const updateExpression = [];
        const attrValues = {};

        attrs.forEach(attr => {
            const subName = '#' + attr.toUpperCase();
            const subValue = ':' + attr;
            attrNames[subName] = attr;
            updateExpression.push(subName + ' = ' + subValue);
            attrValues[subValue] = context.job.data[attr];
        });

        // come up with a better way of modifying parent and sequence length
        // like actually using Date(), negative slices feel sketch
        dynamo.updateItem({
            TableName: process.env.MainTable,
            Key: {
                parent: {S: context.job.key.slice(0, -3)},
                sequence: {N: context.job.key.slice(-2)}
            },
            UpdateExpression: 'SET ' + updateExpression.join(', '),
            ExpressionAttributeNames: attrNames,
            ExpressionAttributeValues: attrValues
        }, (err, data) => {
            if (err) return reject(err);
            resolve(context);
        });
    });
}
<commit_msg>Try and catch straggling error<commit_after>'use strict';

const AWS = require('aws-sdk');
const region = process.env.AWS_REGION || 'us-west-2';
const dynamo = new AWS.DynamoDB({region: region});
const sqs = new AWS.SQS({region: region});

const userCounts = require('./lib/userCounts.js');
const overallCounts = require('./lib/overallCounts.js');

exports.handler = (event, context, callback) => {
    processNext(event, callback);
};

function processNext(context, callback) {
    getJob(context)
        .then(getChildren)
        .then(userCounts.merge)
        .then(userCounts.pack)
        .then(overallCounts.merge)
        .then(overallCounts.pack)
        .then(writeToDynamo)
        .then(markJobDone)
        .then(() => {
            processNext(context, callback);
        }).catch((err) => {
            if (err.no_messages) {
                // retries or concurrency checks here in the future
                return callback(null);
            } else {
                console.error(err.stack, context);
                return callback(err);
            }
        });
}

function getJob(context) {
    return new Promise((resolve, reject) => {
        if (context.source) {
            if (context.source === 'perTenMinTrigger') {
                context.queue = process.env.perTenMinQueue;
            } else {
                context.queue = process.env.perMinQueue;
            }
        } else {
            return reject(new Error('missing source'));
        }

        sqs.receiveMessage({
            QueueUrl: context.queue,
            VisibilityTimeout: 10
        }, (err, data) => {
            if (err) return reject(err);
            if (!data.Messages) return reject({no_messages: true});

            console.log('starting', data.Messages[0].Body);
            context.job = JSON.parse(data.Messages[0].Body);
            context.job.ReceiptHandle = data.Messages[0].ReceiptHandle;

            // validate the key real quick, this should be a lib
            if (context.job.jobType === 'minute') context.job.key = context.job.key.slice(0, 16);
            if (context.job.jobType === 'hour') context.job.key = context.job.key.slice(0, 13);
            if (context.job.jobType === 'day') context.job.key = context.job.key.slice(0, 10);
            if (context.job.jobType === 'month') context.job.key = context.job.key.slice(0, 7);

            resolve(context);
        });
    });
}

function markJobDone(context) {
    return new Promise((resolve, reject) => {
        sqs.deleteMessage({
            QueueUrl: context.queue,
            ReceiptHandle: context.job.ReceiptHandle
        }, (err, data) => {
            if (err) return reject(err);

            delete context.job.data;
            delete context.job.children;

            console.log('finished', JSON.stringify(context.job));

            delete context.job;
            resolve(context);
        });
    });
}

function getChildren(context) {
    // get all the children for the given parent

    return new Promise((resolve, reject) => {
        // all jobs want these things for now, that might change
        const projExpression = ['#SEQUENCE', '#OVERALLCOUNTS'];
        const xprsnAttrNames = {
            '#PARENT': 'parent',
            '#OVERALLCOUNTS': 'overallCounts',
            '#SEQUENCE': 'sequence'
        };

        if (context.job.jobType === 'minute' ||
            context.job.jobType === 'hour') {
            projExpression.push('#USERCOUNTS');
            xprsnAttrNames['#USERCOUNTS'] = 'userCounts';
        }

        dynamo.query({
            TableName: process.env.MainTable,
            Select: 'SPECIFIC_ATTRIBUTES',
            KeyConditionExpression: '#PARENT = :parent',
            ProjectionExpression: projExpression.join(', '),
            ExpressionAttributeNames: xprsnAttrNames,
            ExpressionAttributeValues: {
                ':parent': {S: context.job.key}
            }
        }, (err, data) => {
            if (err) return reject(err);
            context.job.children = data.Items;
            resolve(context);
        });
    });
}

function writeToDynamo(context) {
    // dynamically write all data

    return new Promise((resolve, reject) => {
        const attrs = [];
        for (const attr in context.job.data) {
            attrs.push(attr);
        }

        const attrNames = {};
        const updateExpression = [];
        const attrValues = {};

        attrs.forEach(attr => {
            const subName = '#' + attr.toUpperCase();
            const subValue = ':' + attr;
            attrNames[subName] = attr;
            updateExpression.push(subName + ' = ' + subValue);
            attrValues[subValue] = context.job.data[attr];
        });

        // come up with a better way of modifying parent and sequence length
        // like actually using Date(), negative slices feel sketch
        dynamo.updateItem({
            TableName: process.env.MainTable,
            Key: {
                parent: {S: context.job.key.slice(0, -3)},
                sequence: {N: context.job.key.slice(-2)}
            },
            UpdateExpression: 'SET ' + updateExpression.join(', '),
            ExpressionAttributeNames: attrNames,
            ExpressionAttributeValues: attrValues
        }, (err, data) => {
            if (err) return reject(err);
            resolve(context);
        });
    });
}
<|endoftext|>


<commit_before>define(["Tone/core/Tone", "Tone/signal/Signal", "Tone/signal/Scale"], function(Tone){

	"use strict";

	/**
	 * @class  dry/wet knob.
	 *         equal power fading control values:
	 * 	       0 = 100% wet  -    0% dry
	 * 	       1 =   0% wet  -  100% dry
	 *
	 * @constructor
	 * @extends {Tone}
	 * @param {number=} initialDry
	 */
	Tone.DryWet = function(initialDry){
		Tone.call(this);

		/**
		 *  connect this input to the dry signal
		 *  the dry signal is also the default input
		 *
		 *  @type {GainNode}
		 */
		this.dry = this.input;

		/**
		 *  connect this input to the wet signal
		 *
		 *  @type {GainNode}
		 */
		this.wet = this.context.createGain();

		/**
		 *  controls the amount of wet signal
		 *  which is mixed into the dry signal
		 *
		 *  @type {Tone.Signal}
		 */
		this.wetness = new Tone.Signal();

		/**
		 *  invert the incoming signal
		 *  @private
		 *  @type {Tone}
		 */
		this._invert = new Tone.Scale(0, 1, 1, 0);

		//connections
		this.dry.connect(this.output);
		this.wet.connect(this.output);
		//wet control
		this.chain(this.wetness, this.wet.gain);
		//dry control is the inverse of the wet
		this.chain(this.wetness, this._invert, this.dry.gain);
		this.setDry(this.defaultArg(initialDry, 0));
	};

	Tone.extend(Tone.DryWet);

	/**
	 * Set the dry value
	 *
	 * @param {number} val
	 * @param {Tone.Time=} rampTime
	 */
	Tone.DryWet.prototype.setDry = function(val, rampTime){
		this.setWet(1-val, rampTime);
	};

	/**
	 * Set the wet value
	 *
	 * @param {number} val
	 * @param {Tone.Time=} rampTime
	 */
	Tone.DryWet.prototype.setWet = function(val, rampTime){
		if (rampTime){
			this.wetness.linearRampToValueNow(val, rampTime);
		} else {
			this.wetness.setValue(val);
		}
	};

	/**
	 *  clean up
	 */
	Tone.DryWet.prototype.dispose = function(){
		Tone.prototype.dispose.call(this);
		this.dry.disconnect();
		this.wet.disconnect();
		this.wetness.dispose();
		this._invert.dispose();
		this.dry = null;
		this.wet = null;
		this.wetness = null;
		this._invert = null;
	};

	return Tone.DryWet;
});
<commit_msg>small dry/wet optimization<commit_after>define(["Tone/core/Tone", "Tone/signal/Signal", "Tone/signal/Expr"], function(Tone){

	"use strict";

	/**
	 * @class  dry/wet knob.
	 *         equal power fading control values:
	 * 	       0 = 100% wet  -    0% dry
	 * 	       1 =   0% wet  -  100% dry
	 *
	 * @constructor
	 * @extends {Tone}
	 * @param {number=} initialDry
	 */
	Tone.DryWet = function(initialDry){
		Tone.call(this);

		/**
		 *  connect this input to the dry signal
		 *  the dry signal is also the default input
		 *
		 *  @type {GainNode}
		 */
		this.dry = this.input;

		/**
		 *  connect this input to the wet signal
		 *
		 *  @type {GainNode}
		 */
		this.wet = this.context.createGain();

		/**
		 *  controls the amount of wet signal
		 *  which is mixed into the dry signal
		 *
		 *  @type {Tone.Signal}
		 */
		this.wetness = new Tone.Signal();

		/**
		 *  invert the incoming signal
		 *  @private
		 *  @type {Tone}
		 */
		this._invert = new Tone.Expr("1 - $0");

		//connections
		this.dry.connect(this.output);
		this.wet.connect(this.output);
		//wet control
		this.chain(this.wetness, this.wet.gain);
		//dry control is the inverse of the wet
		this.chain(this.wetness, this._invert, this.dry.gain);
		this.setDry(this.defaultArg(initialDry, 0));
	};

	Tone.extend(Tone.DryWet);

	/**
	 * Set the dry value
	 *
	 * @param {number} val
	 * @param {Tone.Time=} rampTime
	 */
	Tone.DryWet.prototype.setDry = function(val, rampTime){
		this.setWet(1-val, rampTime);
	};

	/**
	 * Set the wet value
	 *
	 * @param {number} val
	 * @param {Tone.Time=} rampTime
	 */
	Tone.DryWet.prototype.setWet = function(val, rampTime){
		if (rampTime){
			this.wetness.linearRampToValueNow(val, rampTime);
		} else {
			this.wetness.setValue(val);
		}
	};

	/**
	 *  clean up
	 */
	Tone.DryWet.prototype.dispose = function(){
		Tone.prototype.dispose.call(this);
		this.dry.disconnect();
		this.wet.disconnect();
		this.wetness.dispose();
		this._invert.dispose();
		this.dry = null;
		this.wet = null;
		this.wetness = null;
		this._invert = null;
	};

	return Tone.DryWet;
});
<|endoftext|>


<commit_before>jQuery(document).ready(function() {
    var gif = jQuery('
');
    gif.hide();
    gif.css('position', 'absolute').css('box-shadow', '1px 1px 2px #444');
    jQuery('body').append(gif);

    jQuery('a.agifinline').mouseover(function(event) {});

    jQuery('a.agifinline').mousemove(function(event) {
        jQuery('#agifinline').html('');
        gw = jQuery('#agifinline img').width();
        gh = jQuery('#agifinline img').height();
        var left = event.pageX - (gw / 2);
        var top = event.pageY + 20;
        gif.css('height', gh);
        gif.css('left', left);
        gif.css('top', top);
        gif.show();
    });

    jQuery('a.agifinline').mouseout(function(event) {
        gif.hide();
    });
});
<commit_msg>z-index<commit_after>jQuery(document).ready(function() {
    var gif = jQuery('
');
    gif.hide();
    gif.css('position', 'absolute').css('box-shadow', '1px 1px 2px #444').css('z-index', 1000000);
    jQuery('body').append(gif);

    jQuery('a.agifinline').mouseover(function(event) {});

    jQuery('a.agifinline').mousemove(function(event) {
        jQuery('#agifinline').html('');
        gw = jQuery('#agifinline img').width();
        gh = jQuery('#agifinline img').height();
        var left = event.pageX - (gw / 2);
        var top = event.pageY + 20;
        gif.css('height', gh);
        gif.css('left', left);
        gif.css('top', top);
        gif.show();
    });

    jQuery('a.agifinline').mouseout(function(event) {
        gif.hide();
    });
});
<|endoftext|>


<commit_before>// Export our module as our export
module.exports = module;

// Export other magic globals
module.exports.filename = __filename;
module.exports.dirname = __dirname;

// Add a special identifier for `module.exports` assertions
module.exports.hello = 'world';

// Add property with proper window context
console.log('hi', window.before + '', console.log + '');
module.exports.before = window.before;
<commit_msg>Cleaning up console.log<commit_after>// Export our module as our export
module.exports = module;

// Export other magic globals
module.exports.filename = __filename;
module.exports.dirname = __dirname;

// Add a special identifier for `module.exports` assertions
module.exports.hello = 'world';

// Add property with proper window context
module.exports.before = window.before;
<|endoftext|>