language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function Dice(startNumber) {
//DOM constants
const rollDiceButton = document.querySelector('.rollDiceButton'); //link rollDiceButton to DOM element
const dicePic = document.querySelector('.dicePic'); //link dicePic to DOM element
const sound = document.querySelector('.diceAudio'); //link sound to diceAudio DOM element
const bell = document.querySelector('.bell'); //link sound to diceAudio DOM element
const timer = document.querySelector('.timer'); //link timer to DOM element
this.number = startNumber; //dice number
this.timeleft = client.TIME_TURN;
this.interval = undefined;
dicePic.src = 'images/dice' + this.number + '.png'; //assign dice image
rollDiceButton.disabled = true; //disable dice butotn
rollDiceButton.addEventListener("click", enableCoins); //assign event listener to rollDiceButton
//Getter for the dice number
this.getNumber = function () { return this.number; };
//Just the animation of rolling the dice
this.rollDiceAnimation = function(number) {
if (number==0){ //executed locally, this P determines (and sends) the dice number
this.number = client.DICE_GOD ? 20 : Math.floor(Math.random() * 6) + 1;
let diceMessage = {
type: "DICE",
data: localGame.dice.number
}
socket.send(JSON.stringify(diceMessage));
} else {
this.number = number;
}
let roll = setInterval(function () {
//This "Interval" repeats the 'rolling the dice' function (random dice frame) every 300 miliseconds
sound.play(); //ticking sound for each dice number preview
dicePic.src = 'images/dice' + (Math.floor(Math.random() * 6) + 1) + '.png'; //Update the dice image for this preview number (dice animation is local to reduce the number of messages)
}, 0.3 * client.GAME_SPEED); //0.3 seconds (in total 10 frames if run for 3 seconds)
setTimeout(function () {
clearInterval(roll);
dicePic.src = 'images/dice' + this.number + '.png';
}.bind(this), 3 * client.GAME_SPEED); //3 game seconds
};
//Disables the roll dice button, plays click sound and assigns a new number and dice pic every 0.3 seconds
//Stops after 3 seconds
//Then enables the coins of the player
function enableCoins () {
rollDiceButton.disabled = true; //disable the dice button right after clicking it
localGame.dice.rollDiceAnimation(0);
//There is a delay of 3000 miliseconds (3 sec) until the "Interval" is stopped (cleared)
//the last dice number is chosen
//after the dice number is displayed all coins are enabled, except coins at home cells
setTimeout(function () {
client.DICE_NUMBER = this.number;
/*prob send some sockets here*/ /*and also refresh the dice at the other terminal (or maybe send it each time so the animation is seen live*/
//enable P1 coins
if (localGame.player == 1 && localGame.turn == 1) {
for (let i = 0; i < 4; i++) {
if (localGame.board.coin[i].position != 19) { //using the coin position was simpler than using cell type, make sure to keep track of the cell position for these home cells if you decide to change the layout of the board.
localGame.board.coin[i].enable();
}
}
}
//enable P2 coins
if (localGame.player == 2 && localGame.turn == 2) {
for (let i = 4; i < 8; i++) {
if (localGame.board.coin[i].position != 23) { //P2 home exception
localGame.board.coin[i].enable();
}
}
}
}, 3 * client.GAME_SPEED); //3 game seconds
}
//Starts the countdown to make a move
this.start = function () {
if (!localGame.gameOver) {
if (localGame.turn == localGame.player){
printMessage(1);
} else {
printMessage(2);
}
}
setTimeout(function () {
localGame.turn == localGame.player ? rollDiceButton.disabled = false : rollDiceButton.disabled = true;
}, 1 * client.GAME_SPEED);
this.interval = setInterval(function () {
if (!localGame.gameOver && this.timeleft >= 0) {
timer.innerHTML = "P" + localGame.turn + " Timeout</br>" + this.timeleft;
this.timeleft--;
} else {
//switch players locally
localGame.turn = localGame.turn == 1 ? 2 : 1;
//updates the time for the other player locally
this.timeleft = client.TIME_TURN;
//there is no need to send an update message since the board remains the same
//graphic update
bell.play();
timer.innerHTML = "P" + localGame.turn + " Timeout</br></br>";
if (!localGame.gameOver) {
if (localGame.turn == localGame.player){
printMessage(1);
} else {
printMessage(2);
}
}
//enable after 1 sec depending on the localGame player type
if (localGame.turn == localGame.player && !localGame.gameOver) {
setTimeout(function () { rollDiceButton.disabled = false; }, 1 * client.GAME_SPEED);
} else {
this.disable();
}
}
}.bind(this), 1 * client.GAME_SPEED);
}
//disables the dice clickability and the board clickability
this.disable = function () {
//disable button
rollDiceButton.disabled = true;
//time's run out, so all coins are disabled
for (let i = 0; i < localGame.board.coin.length; i++) {
localGame.board.coin[i].disable();
}
//time's run out, so all cells are disabled
for (let i = 0; i < localGame.board.cell.length; i++) {
localGame.board.cell[i].disable();
}
}
//Changes player turns
this.switch = function () {
localGame.export(); //sends new game state to the other player
this.timeleft = -1; //"resets" dice clock locally (forces time runout and lets the turn switch by itself)
localGame.dice.disable(); //locally turns off the dice clickability and the board clickability
}
//Stops the dice timer (only used at game over!)
this.stop = function () {
clearInterval(this.interval); //freezes the timer loop.
this.disable();
}
} | function Dice(startNumber) {
//DOM constants
const rollDiceButton = document.querySelector('.rollDiceButton'); //link rollDiceButton to DOM element
const dicePic = document.querySelector('.dicePic'); //link dicePic to DOM element
const sound = document.querySelector('.diceAudio'); //link sound to diceAudio DOM element
const bell = document.querySelector('.bell'); //link sound to diceAudio DOM element
const timer = document.querySelector('.timer'); //link timer to DOM element
this.number = startNumber; //dice number
this.timeleft = client.TIME_TURN;
this.interval = undefined;
dicePic.src = 'images/dice' + this.number + '.png'; //assign dice image
rollDiceButton.disabled = true; //disable dice butotn
rollDiceButton.addEventListener("click", enableCoins); //assign event listener to rollDiceButton
//Getter for the dice number
this.getNumber = function () { return this.number; };
//Just the animation of rolling the dice
this.rollDiceAnimation = function(number) {
if (number==0){ //executed locally, this P determines (and sends) the dice number
this.number = client.DICE_GOD ? 20 : Math.floor(Math.random() * 6) + 1;
let diceMessage = {
type: "DICE",
data: localGame.dice.number
}
socket.send(JSON.stringify(diceMessage));
} else {
this.number = number;
}
let roll = setInterval(function () {
//This "Interval" repeats the 'rolling the dice' function (random dice frame) every 300 miliseconds
sound.play(); //ticking sound for each dice number preview
dicePic.src = 'images/dice' + (Math.floor(Math.random() * 6) + 1) + '.png'; //Update the dice image for this preview number (dice animation is local to reduce the number of messages)
}, 0.3 * client.GAME_SPEED); //0.3 seconds (in total 10 frames if run for 3 seconds)
setTimeout(function () {
clearInterval(roll);
dicePic.src = 'images/dice' + this.number + '.png';
}.bind(this), 3 * client.GAME_SPEED); //3 game seconds
};
//Disables the roll dice button, plays click sound and assigns a new number and dice pic every 0.3 seconds
//Stops after 3 seconds
//Then enables the coins of the player
function enableCoins () {
rollDiceButton.disabled = true; //disable the dice button right after clicking it
localGame.dice.rollDiceAnimation(0);
//There is a delay of 3000 miliseconds (3 sec) until the "Interval" is stopped (cleared)
//the last dice number is chosen
//after the dice number is displayed all coins are enabled, except coins at home cells
setTimeout(function () {
client.DICE_NUMBER = this.number;
/*prob send some sockets here*/ /*and also refresh the dice at the other terminal (or maybe send it each time so the animation is seen live*/
//enable P1 coins
if (localGame.player == 1 && localGame.turn == 1) {
for (let i = 0; i < 4; i++) {
if (localGame.board.coin[i].position != 19) { //using the coin position was simpler than using cell type, make sure to keep track of the cell position for these home cells if you decide to change the layout of the board.
localGame.board.coin[i].enable();
}
}
}
//enable P2 coins
if (localGame.player == 2 && localGame.turn == 2) {
for (let i = 4; i < 8; i++) {
if (localGame.board.coin[i].position != 23) { //P2 home exception
localGame.board.coin[i].enable();
}
}
}
}, 3 * client.GAME_SPEED); //3 game seconds
}
//Starts the countdown to make a move
this.start = function () {
if (!localGame.gameOver) {
if (localGame.turn == localGame.player){
printMessage(1);
} else {
printMessage(2);
}
}
setTimeout(function () {
localGame.turn == localGame.player ? rollDiceButton.disabled = false : rollDiceButton.disabled = true;
}, 1 * client.GAME_SPEED);
this.interval = setInterval(function () {
if (!localGame.gameOver && this.timeleft >= 0) {
timer.innerHTML = "P" + localGame.turn + " Timeout</br>" + this.timeleft;
this.timeleft--;
} else {
//switch players locally
localGame.turn = localGame.turn == 1 ? 2 : 1;
//updates the time for the other player locally
this.timeleft = client.TIME_TURN;
//there is no need to send an update message since the board remains the same
//graphic update
bell.play();
timer.innerHTML = "P" + localGame.turn + " Timeout</br></br>";
if (!localGame.gameOver) {
if (localGame.turn == localGame.player){
printMessage(1);
} else {
printMessage(2);
}
}
//enable after 1 sec depending on the localGame player type
if (localGame.turn == localGame.player && !localGame.gameOver) {
setTimeout(function () { rollDiceButton.disabled = false; }, 1 * client.GAME_SPEED);
} else {
this.disable();
}
}
}.bind(this), 1 * client.GAME_SPEED);
}
//disables the dice clickability and the board clickability
this.disable = function () {
//disable button
rollDiceButton.disabled = true;
//time's run out, so all coins are disabled
for (let i = 0; i < localGame.board.coin.length; i++) {
localGame.board.coin[i].disable();
}
//time's run out, so all cells are disabled
for (let i = 0; i < localGame.board.cell.length; i++) {
localGame.board.cell[i].disable();
}
}
//Changes player turns
this.switch = function () {
localGame.export(); //sends new game state to the other player
this.timeleft = -1; //"resets" dice clock locally (forces time runout and lets the turn switch by itself)
localGame.dice.disable(); //locally turns off the dice clickability and the board clickability
}
//Stops the dice timer (only used at game over!)
this.stop = function () {
clearInterval(this.interval); //freezes the timer loop.
this.disable();
}
} |
JavaScript | function enableCoins () {
rollDiceButton.disabled = true; //disable the dice button right after clicking it
localGame.dice.rollDiceAnimation(0);
//There is a delay of 3000 miliseconds (3 sec) until the "Interval" is stopped (cleared)
//the last dice number is chosen
//after the dice number is displayed all coins are enabled, except coins at home cells
setTimeout(function () {
client.DICE_NUMBER = this.number;
/*prob send some sockets here*/ /*and also refresh the dice at the other terminal (or maybe send it each time so the animation is seen live*/
//enable P1 coins
if (localGame.player == 1 && localGame.turn == 1) {
for (let i = 0; i < 4; i++) {
if (localGame.board.coin[i].position != 19) { //using the coin position was simpler than using cell type, make sure to keep track of the cell position for these home cells if you decide to change the layout of the board.
localGame.board.coin[i].enable();
}
}
}
//enable P2 coins
if (localGame.player == 2 && localGame.turn == 2) {
for (let i = 4; i < 8; i++) {
if (localGame.board.coin[i].position != 23) { //P2 home exception
localGame.board.coin[i].enable();
}
}
}
}, 3 * client.GAME_SPEED); //3 game seconds
} | function enableCoins () {
rollDiceButton.disabled = true; //disable the dice button right after clicking it
localGame.dice.rollDiceAnimation(0);
//There is a delay of 3000 miliseconds (3 sec) until the "Interval" is stopped (cleared)
//the last dice number is chosen
//after the dice number is displayed all coins are enabled, except coins at home cells
setTimeout(function () {
client.DICE_NUMBER = this.number;
/*prob send some sockets here*/ /*and also refresh the dice at the other terminal (or maybe send it each time so the animation is seen live*/
//enable P1 coins
if (localGame.player == 1 && localGame.turn == 1) {
for (let i = 0; i < 4; i++) {
if (localGame.board.coin[i].position != 19) { //using the coin position was simpler than using cell type, make sure to keep track of the cell position for these home cells if you decide to change the layout of the board.
localGame.board.coin[i].enable();
}
}
}
//enable P2 coins
if (localGame.player == 2 && localGame.turn == 2) {
for (let i = 4; i < 8; i++) {
if (localGame.board.coin[i].position != 23) { //P2 home exception
localGame.board.coin[i].enable();
}
}
}
}, 3 * client.GAME_SPEED); //3 game seconds
} |
JavaScript | function LocalGame() {
//Managed locally (mostly, dice gets updates via "DICE" and in "TURN" socket onmessage)
this.player = 0; //it gets determined at gamestart by socket messages
this.dice = new Dice(20);
this.gameClock = new GameClock();
this.turn = 1; //by default p1 starts
//Import/Export properties
this.board = new Board();
this.gameOver = false;
this.winner = -1; //-1 DRAW, 0 aborted, 1 P1, 2P2
this.scoreP1 = 0;
this.scoreP2 = 0;
//Starts the game
this.start = function () {
this.dice.start();
this.gameClock.reset();
}
//Exports game state to JSON
this.export = function () {
socket.send(JSON.stringify(this.getGameState()));
}
//Updates the local game state
this.import = function (stateUpdate) {
//Beware! JSON stringify will remove the functions from the objects!
//therefore we can't do a thing such as this.board.coin = stateUpdate.coins;
//that would break our game since we would lose the methods from coin
//we can update the single valued variabels without worry though
this.scoreP1 = stateUpdate.scoreP1;
this.scoreP2 = stateUpdate.scoreP2;
this.gameOver = this.gameOver;
//A method at Board object takes care of a proper import
this.board.importCells(stateUpdate.cells);
this.board.importCoins(stateUpdate.coins);
document.getElementById("SCORE_P1").innerHTML = this.scoreP1;
document.getElementById("SCORE_P2").innerHTML = this.scoreP2;
//P1 wins
if (this.scoreP1 == 4) {
if (localGame.player == 1) {
printMessage(3);
} else {
printMessage(4);
}
localGame.winner = 1;
localGame.gameOver = true;
showP1PathInv(); //p1 win animation
}
//P2 wins
if (this.scoreP2 == 4) {
if (localGame.player == 2) {
printMessage(3);
} else {
printMessage(4);
}
localGame.winner = 2;
localGame.gameOver = true;
showP2PathInv(); //p2 win animation
}
}
//Creates game state JSON friendly object
this.getGameState = function () {
let gameState = {
type: "UPDATE",
data: {
cells: this.board.cell,
coins: this.board.coin,
scoreP1: this.scoreP1,
scoreP2: this.scoreP2,
winner: this.winner,
gameOver: this.gameOver
}
}
return gameState
}
//Notifies server of game over
this.SendGameOverToServer = function () {
let message =
{
type: "GAMEOVER",
data: this.winner
};
socket.send(JSON.stringify(message));
}
//Applies side effects of abortion locally
this.abortReaction = function(){
document.querySelector('.abort').play();
localGame.gameOver = true;
localGame.winner = 0;
printMessage(5);
localGame.dice.stop(); //Stops the dice timer
document.querySelector('.abortButton').disabled = true; //disables abort button
}
} | function LocalGame() {
//Managed locally (mostly, dice gets updates via "DICE" and in "TURN" socket onmessage)
this.player = 0; //it gets determined at gamestart by socket messages
this.dice = new Dice(20);
this.gameClock = new GameClock();
this.turn = 1; //by default p1 starts
//Import/Export properties
this.board = new Board();
this.gameOver = false;
this.winner = -1; //-1 DRAW, 0 aborted, 1 P1, 2P2
this.scoreP1 = 0;
this.scoreP2 = 0;
//Starts the game
this.start = function () {
this.dice.start();
this.gameClock.reset();
}
//Exports game state to JSON
this.export = function () {
socket.send(JSON.stringify(this.getGameState()));
}
//Updates the local game state
this.import = function (stateUpdate) {
//Beware! JSON stringify will remove the functions from the objects!
//therefore we can't do a thing such as this.board.coin = stateUpdate.coins;
//that would break our game since we would lose the methods from coin
//we can update the single valued variabels without worry though
this.scoreP1 = stateUpdate.scoreP1;
this.scoreP2 = stateUpdate.scoreP2;
this.gameOver = this.gameOver;
//A method at Board object takes care of a proper import
this.board.importCells(stateUpdate.cells);
this.board.importCoins(stateUpdate.coins);
document.getElementById("SCORE_P1").innerHTML = this.scoreP1;
document.getElementById("SCORE_P2").innerHTML = this.scoreP2;
//P1 wins
if (this.scoreP1 == 4) {
if (localGame.player == 1) {
printMessage(3);
} else {
printMessage(4);
}
localGame.winner = 1;
localGame.gameOver = true;
showP1PathInv(); //p1 win animation
}
//P2 wins
if (this.scoreP2 == 4) {
if (localGame.player == 2) {
printMessage(3);
} else {
printMessage(4);
}
localGame.winner = 2;
localGame.gameOver = true;
showP2PathInv(); //p2 win animation
}
}
//Creates game state JSON friendly object
this.getGameState = function () {
let gameState = {
type: "UPDATE",
data: {
cells: this.board.cell,
coins: this.board.coin,
scoreP1: this.scoreP1,
scoreP2: this.scoreP2,
winner: this.winner,
gameOver: this.gameOver
}
}
return gameState
}
//Notifies server of game over
this.SendGameOverToServer = function () {
let message =
{
type: "GAMEOVER",
data: this.winner
};
socket.send(JSON.stringify(message));
}
//Applies side effects of abortion locally
this.abortReaction = function(){
document.querySelector('.abort').play();
localGame.gameOver = true;
localGame.winner = 0;
printMessage(5);
localGame.dice.stop(); //Stops the dice timer
document.querySelector('.abortButton').disabled = true; //disables abort button
}
} |
JavaScript | function GameClock() {
//DOM Constants
const seconds = document.querySelector(".seconds");
const minutes = document.querySelector(".minutes");
const abortButton = document.querySelector('.abortButton');
abortButton.addEventListener("click", abort);
//Aborts game
function abort () {
const sound = document.querySelector('.abort');
sound.play();
localGame.gameOver = true;
localGame.winner = 0;
localGame.SendGameOverToServer();
printMessage(5);
localGame.dice.stop(); //Stops the dice timer
abortButton.disabled = true; //disables abort button
}
let elapsedTime = 0; //start counting at 0 seconds
//Only display integers
function formatTime(x) { return x > 9 ? x : "0" + x; }
//Starts the clock
this.start = function () {
if (localGame.turn == localGame.player){
printMessage(1);
} else {
printMessage(2);
}
let startClock = setInterval(function () {
//STOP THE CLOCK AT GAME OVER
if (localGame.gameOver) {
clearInterval(startClock); //stops the game clock
client.GAME_ELAPSED_TIME = elapsedTime; //registers the total played time
localGame.dice.stop(); //Stops the dice timer
abortButton.disabled = true; //disables abort button
if (localGame.winner == -1){
printMessage(6);//print game is a draw
}
} else {
seconds.innerHTML = formatTime(elapsedTime % 60); //parse seconds
minutes.innerHTML = formatTime(parseInt((elapsedTime / 60) % 60, 10)); //parse minutes
if (elapsedTime === client.MAX_GAME_DURATION) { //finish game after 1 hour )(3600s)
localGame.gameOver = true;
client.GAME_ELAPSED_TIME = elapsedTime;
if (localGame.player == 1) {localGame.SendGameOverToServer();}; //enough that 1 sends the gameover
};
}
elapsedTime++;
}.bind(this), 1 * client.GAME_SPEED); //speed of the game time clock 1000ms = 1 sec
}
// Resets the clock
this.reset = function () {
localGame.gameOver = false;
localGame.winner = -1;
elapsedTime = 0;
abortButton.disabled = false; //enables abort button
this.start();
}
//Getter for the game time
this.getElapsedTime = function () { return elapsedTime; };
} | function GameClock() {
//DOM Constants
const seconds = document.querySelector(".seconds");
const minutes = document.querySelector(".minutes");
const abortButton = document.querySelector('.abortButton');
abortButton.addEventListener("click", abort);
//Aborts game
function abort () {
const sound = document.querySelector('.abort');
sound.play();
localGame.gameOver = true;
localGame.winner = 0;
localGame.SendGameOverToServer();
printMessage(5);
localGame.dice.stop(); //Stops the dice timer
abortButton.disabled = true; //disables abort button
}
let elapsedTime = 0; //start counting at 0 seconds
//Only display integers
function formatTime(x) { return x > 9 ? x : "0" + x; }
//Starts the clock
this.start = function () {
if (localGame.turn == localGame.player){
printMessage(1);
} else {
printMessage(2);
}
let startClock = setInterval(function () {
//STOP THE CLOCK AT GAME OVER
if (localGame.gameOver) {
clearInterval(startClock); //stops the game clock
client.GAME_ELAPSED_TIME = elapsedTime; //registers the total played time
localGame.dice.stop(); //Stops the dice timer
abortButton.disabled = true; //disables abort button
if (localGame.winner == -1){
printMessage(6);//print game is a draw
}
} else {
seconds.innerHTML = formatTime(elapsedTime % 60); //parse seconds
minutes.innerHTML = formatTime(parseInt((elapsedTime / 60) % 60, 10)); //parse minutes
if (elapsedTime === client.MAX_GAME_DURATION) { //finish game after 1 hour )(3600s)
localGame.gameOver = true;
client.GAME_ELAPSED_TIME = elapsedTime;
if (localGame.player == 1) {localGame.SendGameOverToServer();}; //enough that 1 sends the gameover
};
}
elapsedTime++;
}.bind(this), 1 * client.GAME_SPEED); //speed of the game time clock 1000ms = 1 sec
}
// Resets the clock
this.reset = function () {
localGame.gameOver = false;
localGame.winner = -1;
elapsedTime = 0;
abortButton.disabled = false; //enables abort button
this.start();
}
//Getter for the game time
this.getElapsedTime = function () { return elapsedTime; };
} |
JavaScript | function Coin(id) {
//constructor
this.id = id; //coin id
this.dom = document.getElementById(id); //HTML dom object
this.player = id.charAt(1); //coin owner
this.dom.src = 'images/coinp' + this.player + '.png'; //con icon
this.dom.disabled = true; //cannot be selected
this.position = -1; //current position
this.prevPosition = -1; //previous position
this.spawn = 's' + id.substring(1,3); //DOM object id for the base
//Getter for coin id
this.getId = function () {
return this.id;
}
//Getter for coin spawn id
this.getSpawn = function () {
return this.spawn;
}
//Getter for coin DOM object
this.getDom = function () {
return this.dom;
}
//Getter for cell coin position
this.getPosition = function (x) {
return this.position;
}
//Setter for cell coin position
this.setPosition = function (x) {
this.position = x;
}
//Getter for previous cell coin position
this.getPrevPosition = function (x) {
return this.prevPosition;
}
//Setter for previous cell coin position
this.setPrevPosition = function (x) {
this.prevPosition = x;
}
//Enables coin selection for moves
this.enable = function () {
if (this.player == localGame.player){
this.dom.disabled = false;
this.dom.addEventListener("click", this.highlight);
}
}
//Disables coin selection for moves
this.disable = function () {
this.dom.src = 'images/coinp' + this.player + '.png'; //unselected icon
this.dom.disabled = true;
}
//(After clicking the coin) Highlights this coin and un-higlights all other coins,
//highlights and enables allowed cell for a move as well
this.highlight = function () {
//un-higlight all other coins (graphically)
for (let i = 0; i < 4; i++) {
document.querySelectorAll(".coinp1")[i].src = 'images/coinp1.png';
document.querySelectorAll(".coinp2")[i].src = 'images/coinp2.png';
}
//highlights this (selected, as this is used in a click event) coin (darkens icon)
document.getElementById(id).src = 'images/coinp' + this.player + 'selected.png';
//updates LAST_COIN value
client.LAST_COIN = this.id;
//Highlights the available cell move and enables it for possible selection (and move execution)
let maxCell = undefined;
//P1 Logic
if (this.player == 1){
maxCell = localGame.board.cell[Math.min(this.position + localGame.dice.number,19)].getId();
}
//P2 Logic
if (this.player == 2){
let pos = (this.position == -1) ? -1 : localGame.board.cellIdtoRouteP2Position[this.position];
maxCell = localGame.board.routeP2[Math.min(pos + localGame.dice.number, 19)].getId();
}
//remove previous coin cell highlights and selectibility
for (let i = 0; i < 24; i++) {
localGame.board.cell[i].disable();
}
//enables the coin's max cell and so highlights it
localGame.board.cell[maxCell].enable();
}.bind(this); //necessary to bind 'this' for proper 'this' functionality. (as it is a callback function?)
} | function Coin(id) {
//constructor
this.id = id; //coin id
this.dom = document.getElementById(id); //HTML dom object
this.player = id.charAt(1); //coin owner
this.dom.src = 'images/coinp' + this.player + '.png'; //con icon
this.dom.disabled = true; //cannot be selected
this.position = -1; //current position
this.prevPosition = -1; //previous position
this.spawn = 's' + id.substring(1,3); //DOM object id for the base
//Getter for coin id
this.getId = function () {
return this.id;
}
//Getter for coin spawn id
this.getSpawn = function () {
return this.spawn;
}
//Getter for coin DOM object
this.getDom = function () {
return this.dom;
}
//Getter for cell coin position
this.getPosition = function (x) {
return this.position;
}
//Setter for cell coin position
this.setPosition = function (x) {
this.position = x;
}
//Getter for previous cell coin position
this.getPrevPosition = function (x) {
return this.prevPosition;
}
//Setter for previous cell coin position
this.setPrevPosition = function (x) {
this.prevPosition = x;
}
//Enables coin selection for moves
this.enable = function () {
if (this.player == localGame.player){
this.dom.disabled = false;
this.dom.addEventListener("click", this.highlight);
}
}
//Disables coin selection for moves
this.disable = function () {
this.dom.src = 'images/coinp' + this.player + '.png'; //unselected icon
this.dom.disabled = true;
}
//(After clicking the coin) Highlights this coin and un-higlights all other coins,
//highlights and enables allowed cell for a move as well
this.highlight = function () {
//un-higlight all other coins (graphically)
for (let i = 0; i < 4; i++) {
document.querySelectorAll(".coinp1")[i].src = 'images/coinp1.png';
document.querySelectorAll(".coinp2")[i].src = 'images/coinp2.png';
}
//highlights this (selected, as this is used in a click event) coin (darkens icon)
document.getElementById(id).src = 'images/coinp' + this.player + 'selected.png';
//updates LAST_COIN value
client.LAST_COIN = this.id;
//Highlights the available cell move and enables it for possible selection (and move execution)
let maxCell = undefined;
//P1 Logic
if (this.player == 1){
maxCell = localGame.board.cell[Math.min(this.position + localGame.dice.number,19)].getId();
}
//P2 Logic
if (this.player == 2){
let pos = (this.position == -1) ? -1 : localGame.board.cellIdtoRouteP2Position[this.position];
maxCell = localGame.board.routeP2[Math.min(pos + localGame.dice.number, 19)].getId();
}
//remove previous coin cell highlights and selectibility
for (let i = 0; i < 24; i++) {
localGame.board.cell[i].disable();
}
//enables the coin's max cell and so highlights it
localGame.board.cell[maxCell].enable();
}.bind(this); //necessary to bind 'this' for proper 'this' functionality. (as it is a callback function?)
} |
JavaScript | function Cell(id, type, color) { //type 0 = empty, 1 = red arrow, 2 = blue arrow, 3 = black arrow (start), 4 = star
//constructor
this.id = id; //cell id
this.type = type; //cell type (used for star graphic and for not "eating" other tokens behaviour)
this.color = color; //needs to match either "white", "blue" or "red"
this.dom = document.getElementById(id); //HTML dom object
this.occupiedBy = -1; //coin sitting at the cell, -1 = empty cell
//cell image
this.dom.style.backgroundImage = "url('images/cell" + this.type + this.color + ".png')";
this.dom.style.backgroundRepeat = "no-repeat";
this.dom.style.backgroundPosition = "center";
//Cell color setter (unused if color assigned properly at object constructor)
this.setColor = function (x) {
this.color = x;
}
//Returns the coin occupying the cell
this.getCoin = function () {
return this.occupiedBy;
}
//"Empties the cell", partially. Will update only the cell "coin occupation" data. Not graphics. Used with other methods.
this.leaveCoin = function () {
let position = localGame.board.coin[client.LAST_COIN.charAt(2)].getPosition();
if (position != -1) {
localGame.board.cell[position].occupiedBy = -1;
}
}
//Moves the coin to this cell (both graphically and "coin occupation data"),
//sends back to the base the coins that were at the cell (if any)
//Updates the score if this cell is home.
this.setCoin = function () {
//if the possible move cell is the same that the coin is occuping you can't make a move to the same cell
//so the whole setCoin method is aborted.
if (this.occupiedBy == client.LAST_COIN) { //without blocks this will never happen. This is useful if blocking the path feature is implemented.
return;
}
//dealing with occupied coins (does not apply at home type cells)
if (this.occupiedBy != -1 && this.type != 4) {
let spawn = localGame.board.coin[this.occupiedBy.charAt(2)].getSpawn(); //base DOM object
let coinDom = localGame.board.coin[this.occupiedBy.charAt(2)].getDom(); //current coin at cell DOM object
//graphically send current occupying coin to base
document.getElementById(spawn).appendChild(coinDom);
//update sent to base coin data with current cell position = base (-1)
localGame.board.coin[this.occupiedBy.charAt(2)].setPosition(-1);
}
//update "coin occupation" cell data:
this.occupiedBy = client.LAST_COIN; //new occupying cell
let coinDom = localGame.board.coin[client.LAST_COIN.charAt(2)].getDom(); //new occupying cell DOM object
//graphically move the new coin to this cell
this.dom.appendChild(coinDom);
//update just moved coin data of curent cell position and previous cell position
localGame.board.coin[client.LAST_COIN.charAt(2)].setPrevPosition(localGame.board.coin[client.LAST_COIN.charAt(2)].getPosition());
localGame.board.coin[client.LAST_COIN.charAt(2)].setPosition(this.id);
//graphically update the selected coin from dark to normal
document.getElementById(this.occupiedBy).src = 'images/coinp' + this.occupiedBy.charAt(1) + '.png'
//if red home cell give points to P1 (and end the game if 4/4)
if (this.id == 19) {
document.getElementById("SCORE_P1").innerHTML = ++localGame.scoreP1;
if (localGame.scoreP1 == 4) {
localGame.winner = 1;
localGame.gameOver = true;
if (localGame.player == 1) {
printMessage(3);
localGame.SendGameOverToServer(); //only winner client sends the game over message to client
} else {
printMessage(4);
}
showP1PathInv(); //p1 win animation
}
}
//if blue home cell give points to P2 (and end the game if 4/4)
if (this.id == 23) {
document.getElementById("SCORE_P2").innerHTML = ++localGame.scoreP2;
if (localGame.scoreP2 == 4) {
localGame.winner = 2;
localGame.gameOver = true;
if (localGame.player == 2) {
printMessage(3);
localGame.SendGameOverToServer(); //only winner client sends the game over message to client
} else {
printMessage(4);
}
showP2PathInv(); //p2 win animation
}
}
}
//Getter for cell ID
this.getId = function () {
return this.id;
}
//"Updater" for cell Image. Doesn't take paramaters, color and type must be specified in their own setters, and then use this "updater" (unused if proper object construction).
this.updateImage = function () {
this.dom.style.backgroundImage = "url('images/cell" + this.type + this.color + ".png')";
this.dom.style.backgroundRepeat = "no-repeat";
this.dom.style.backgroundPosition = "center";
}
//Highlights the cell and enables cell selection to make a move.
this.enable = function () {
client.LAST_CELL = -1;
this.dom.style.backgroundColor = 'yellow';
this.dom.style.cursor = "pointer";
this.dom.onclick = this.move;
}
//Moves LAST_COIN to LAST_CELL (it does not take parameters, it makes this cell LAST_CELL and moves LAST_COIN)
this.move = function () {
client.LAST_CELL = this.id;
this.disable(); //after clicking disables the higlight (and the "buttonability") of the cell.
//con leaves the previous cell (data wise)
this.leaveCoin();
//con moves to this cell (data and graphics wise)
this.setCoin();
//switches turns locally (maybe add timout to allow for socket lag?)
localGame.dice.switch();
}.bind(this); //bind function necessary for proper 'this' functionality (as it is a callback function?)
//disables cell selection
this.disable = function () {
this.dom.style.backgroundColor = 'white';
this.dom.style.cursor = "default";
this.dom.onclick = null;
}
} | function Cell(id, type, color) { //type 0 = empty, 1 = red arrow, 2 = blue arrow, 3 = black arrow (start), 4 = star
//constructor
this.id = id; //cell id
this.type = type; //cell type (used for star graphic and for not "eating" other tokens behaviour)
this.color = color; //needs to match either "white", "blue" or "red"
this.dom = document.getElementById(id); //HTML dom object
this.occupiedBy = -1; //coin sitting at the cell, -1 = empty cell
//cell image
this.dom.style.backgroundImage = "url('images/cell" + this.type + this.color + ".png')";
this.dom.style.backgroundRepeat = "no-repeat";
this.dom.style.backgroundPosition = "center";
//Cell color setter (unused if color assigned properly at object constructor)
this.setColor = function (x) {
this.color = x;
}
//Returns the coin occupying the cell
this.getCoin = function () {
return this.occupiedBy;
}
//"Empties the cell", partially. Will update only the cell "coin occupation" data. Not graphics. Used with other methods.
this.leaveCoin = function () {
let position = localGame.board.coin[client.LAST_COIN.charAt(2)].getPosition();
if (position != -1) {
localGame.board.cell[position].occupiedBy = -1;
}
}
//Moves the coin to this cell (both graphically and "coin occupation data"),
//sends back to the base the coins that were at the cell (if any)
//Updates the score if this cell is home.
this.setCoin = function () {
//if the possible move cell is the same that the coin is occuping you can't make a move to the same cell
//so the whole setCoin method is aborted.
if (this.occupiedBy == client.LAST_COIN) { //without blocks this will never happen. This is useful if blocking the path feature is implemented.
return;
}
//dealing with occupied coins (does not apply at home type cells)
if (this.occupiedBy != -1 && this.type != 4) {
let spawn = localGame.board.coin[this.occupiedBy.charAt(2)].getSpawn(); //base DOM object
let coinDom = localGame.board.coin[this.occupiedBy.charAt(2)].getDom(); //current coin at cell DOM object
//graphically send current occupying coin to base
document.getElementById(spawn).appendChild(coinDom);
//update sent to base coin data with current cell position = base (-1)
localGame.board.coin[this.occupiedBy.charAt(2)].setPosition(-1);
}
//update "coin occupation" cell data:
this.occupiedBy = client.LAST_COIN; //new occupying cell
let coinDom = localGame.board.coin[client.LAST_COIN.charAt(2)].getDom(); //new occupying cell DOM object
//graphically move the new coin to this cell
this.dom.appendChild(coinDom);
//update just moved coin data of curent cell position and previous cell position
localGame.board.coin[client.LAST_COIN.charAt(2)].setPrevPosition(localGame.board.coin[client.LAST_COIN.charAt(2)].getPosition());
localGame.board.coin[client.LAST_COIN.charAt(2)].setPosition(this.id);
//graphically update the selected coin from dark to normal
document.getElementById(this.occupiedBy).src = 'images/coinp' + this.occupiedBy.charAt(1) + '.png'
//if red home cell give points to P1 (and end the game if 4/4)
if (this.id == 19) {
document.getElementById("SCORE_P1").innerHTML = ++localGame.scoreP1;
if (localGame.scoreP1 == 4) {
localGame.winner = 1;
localGame.gameOver = true;
if (localGame.player == 1) {
printMessage(3);
localGame.SendGameOverToServer(); //only winner client sends the game over message to client
} else {
printMessage(4);
}
showP1PathInv(); //p1 win animation
}
}
//if blue home cell give points to P2 (and end the game if 4/4)
if (this.id == 23) {
document.getElementById("SCORE_P2").innerHTML = ++localGame.scoreP2;
if (localGame.scoreP2 == 4) {
localGame.winner = 2;
localGame.gameOver = true;
if (localGame.player == 2) {
printMessage(3);
localGame.SendGameOverToServer(); //only winner client sends the game over message to client
} else {
printMessage(4);
}
showP2PathInv(); //p2 win animation
}
}
}
//Getter for cell ID
this.getId = function () {
return this.id;
}
//"Updater" for cell Image. Doesn't take paramaters, color and type must be specified in their own setters, and then use this "updater" (unused if proper object construction).
this.updateImage = function () {
this.dom.style.backgroundImage = "url('images/cell" + this.type + this.color + ".png')";
this.dom.style.backgroundRepeat = "no-repeat";
this.dom.style.backgroundPosition = "center";
}
//Highlights the cell and enables cell selection to make a move.
this.enable = function () {
client.LAST_CELL = -1;
this.dom.style.backgroundColor = 'yellow';
this.dom.style.cursor = "pointer";
this.dom.onclick = this.move;
}
//Moves LAST_COIN to LAST_CELL (it does not take parameters, it makes this cell LAST_CELL and moves LAST_COIN)
this.move = function () {
client.LAST_CELL = this.id;
this.disable(); //after clicking disables the higlight (and the "buttonability") of the cell.
//con leaves the previous cell (data wise)
this.leaveCoin();
//con moves to this cell (data and graphics wise)
this.setCoin();
//switches turns locally (maybe add timout to allow for socket lag?)
localGame.dice.switch();
}.bind(this); //bind function necessary for proper 'this' functionality (as it is a callback function?)
//disables cell selection
this.disable = function () {
this.dom.style.backgroundColor = 'white';
this.dom.style.cursor = "default";
this.dom.onclick = null;
}
} |
JavaScript | function chatSeverConsole(eventito) {
if (eventito.key == 'Enter') {
let message =
{
type: "CHAT",
data: textarea.value
};
socket.send(JSON.stringify(message));
setTimeout(function () {
textarea.value = "";
textarea.placeholder = "";
}, 10);
}
} | function chatSeverConsole(eventito) {
if (eventito.key == 'Enter') {
let message =
{
type: "CHAT",
data: textarea.value
};
socket.send(JSON.stringify(message));
setTimeout(function () {
textarea.value = "";
textarea.placeholder = "";
}, 10);
}
} |
JavaScript | function toggleFocus() {
var self = this;
// Move up through the ancestors of the current link until we hit .primary-menu.
while ( -1 === self.className.indexOf( 'header-nav-main' ) ) {
// On li elements toggle the class .focus.
if ( 'li' === self.tagName.toLowerCase() ) {
if ( -1 !== self.className.indexOf( 'open' ) ) {
self.className = self.className.replace( ' open', '' );
} else {
self.className += ' open';
}
}
self = self.parentElement;
}
} | function toggleFocus() {
var self = this;
// Move up through the ancestors of the current link until we hit .primary-menu.
while ( -1 === self.className.indexOf( 'header-nav-main' ) ) {
// On li elements toggle the class .focus.
if ( 'li' === self.tagName.toLowerCase() ) {
if ( -1 !== self.className.indexOf( 'open' ) ) {
self.className = self.className.replace( ' open', '' );
} else {
self.className += ' open';
}
}
self = self.parentElement;
}
} |
JavaScript | function create() {
var delegates = [];
for (var _i = 0; _i < arguments.length; _i++) {
delegates[_i] = arguments[_i];
}
var callable = delegates.filter(hasBehavior);
return callable.length !== 0 ? function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return callable.map(function (f) { return f.apply(void 0, args); });
} : noop;
} | function create() {
var delegates = [];
for (var _i = 0; _i < arguments.length; _i++) {
delegates[_i] = arguments[_i];
}
var callable = delegates.filter(hasBehavior);
return callable.length !== 0 ? function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return callable.map(function (f) { return f.apply(void 0, args); });
} : noop;
} |
JavaScript | addTaskId(tasksId) {
var exists = false;
for (let i = 0; i < this.tasksIds.length; i++) {
if (this.tasksIds[i] === tasksId) {
exists = true;
}
}
if (!exists)
this.tasksIds.push(tasksId);
} | addTaskId(tasksId) {
var exists = false;
for (let i = 0; i < this.tasksIds.length; i++) {
if (this.tasksIds[i] === tasksId) {
exists = true;
}
}
if (!exists)
this.tasksIds.push(tasksId);
} |
JavaScript | static removeTask(task) {
for (let i = 0; i < $scope.completedTasks.length; i++) {
let flag = false;
for (let j = 0; j < $scope.completedTasks[i].tasksIds.length; j++) {
if ($scope.completedTasks[i].tasksIds[j] === task.id) {
if ($scope.completedTasks[i].tasksIds.length - 1 === 0) {
$scope.completedTasks.splice(i, 1);
flag = true;
break;
} else {
$scope.completedTasks[i].tasksIds.splice(j, 1);
flag = true;
break;
}
}
}
if (flag) break;
}
} | static removeTask(task) {
for (let i = 0; i < $scope.completedTasks.length; i++) {
let flag = false;
for (let j = 0; j < $scope.completedTasks[i].tasksIds.length; j++) {
if ($scope.completedTasks[i].tasksIds[j] === task.id) {
if ($scope.completedTasks[i].tasksIds.length - 1 === 0) {
$scope.completedTasks.splice(i, 1);
flag = true;
break;
} else {
$scope.completedTasks[i].tasksIds.splice(j, 1);
flag = true;
break;
}
}
}
if (flag) break;
}
} |
JavaScript | static returnMultiplyTable(number) {
var outArray = [];
for (let i = 0; i <= number; i++) {
outArray.push(i + ' * ' + number + ' = ' + number * i);
}
return outArray;
} | static returnMultiplyTable(number) {
var outArray = [];
for (let i = 0; i <= number; i++) {
outArray.push(i + ' * ' + number + ' = ' + number * i);
}
return outArray;
} |
JavaScript | static checkExistsOfMultiplyTable(number) {
var out = false;
for (let i = 0; i < $scope.completedTasks.length; i++) {
if ($scope.completedTasks[i].number === number) {
out = i;
break;
}
}
return out;
} | static checkExistsOfMultiplyTable(number) {
var out = false;
for (let i = 0; i < $scope.completedTasks.length; i++) {
if ($scope.completedTasks[i].number === number) {
out = i;
break;
}
}
return out;
} |
JavaScript | static save() {
Socket.emit('saveTask', {
date: $scope.mytime,
number: $scope.number,
completed: false
});
} | static save() {
Socket.emit('saveTask', {
date: $scope.mytime,
number: $scope.number,
completed: false
});
} |
JavaScript | function createCompletedTasks(tasks) {
for (let i = 0; i < tasks.length; i++) {
if (tasks[i].completed) {
let indexOfCompleteTask = CompleteTask.checkExistsOfMultiplyTable(tasks[i].number);
if (indexOfCompleteTask || indexOfCompleteTask === 0) {
$scope.completedTasks[indexOfCompleteTask].addTaskId(tasks[i].id);
} else {
let newCompleteTask = new CompleteTask(CompleteTask.returnMultiplyTable(tasks[i].number), tasks[i].number);
newCompleteTask.addTaskId(tasks[i].id);
$scope.completedTasks.push(newCompleteTask);
}
}
}
} | function createCompletedTasks(tasks) {
for (let i = 0; i < tasks.length; i++) {
if (tasks[i].completed) {
let indexOfCompleteTask = CompleteTask.checkExistsOfMultiplyTable(tasks[i].number);
if (indexOfCompleteTask || indexOfCompleteTask === 0) {
$scope.completedTasks[indexOfCompleteTask].addTaskId(tasks[i].id);
} else {
let newCompleteTask = new CompleteTask(CompleteTask.returnMultiplyTable(tasks[i].number), tasks[i].number);
newCompleteTask.addTaskId(tasks[i].id);
$scope.completedTasks.push(newCompleteTask);
}
}
}
} |
JavaScript | function returnMultiplyTable(number) {
var outArray = [];
for (let i = 0; i <= number; i++) {
outArray.push(i + ' * ' + number + ' = ' + number * i);
}
return outArray;
} | function returnMultiplyTable(number) {
var outArray = [];
for (let i = 0; i <= number; i++) {
outArray.push(i + ' * ' + number + ' = ' + number * i);
}
return outArray;
} |
JavaScript | function saveTasks(tasks, callback) {
memcached.set('tasks', tasks, lifetime, function (err) {
if (err) {
console.log('Error : cron : saveTasks : ', err);
return callback(err);
} else {
return callback();
}
});
} | function saveTasks(tasks, callback) {
memcached.set('tasks', tasks, lifetime, function (err) {
if (err) {
console.log('Error : cron : saveTasks : ', err);
return callback(err);
} else {
return callback();
}
});
} |
JavaScript | function completeTask(task, io) {
io.emit('taskComplete', {
task: task,
multiplyTable: returnMultiplyTable(task.number)
});
} | function completeTask(task, io) {
io.emit('taskComplete', {
task: task,
multiplyTable: returnMultiplyTable(task.number)
});
} |
JavaScript | function check(io) {
new CronJob('00 * * * * *', function (callback) {
memcached.get('tasks', function (err, tasks) {
if (err) {
console.log('Error : memcached Cron: ', err);
return callback(err);
} else {
var nowDate = new Date();
if (tasks) {
let completedFlag = false;
for (var i = 0; i < tasks.length; i = i + 1) {
let loopDate = new Date(tasks[i].date);
if (loopDate.getFullYear() === nowDate.getFullYear() && loopDate.getMonth() === nowDate.getMonth() && loopDate.getDate() === nowDate.getDate() && loopDate.getHours() === nowDate.getHours() && loopDate.getMinutes() === nowDate.getMinutes()) {
tasks[i].completed = true;
completedFlag = true;
completeTask(tasks[i], io);
}
}
if (completedFlag) {
saveTasks(tasks, function (err) {
if (err) {
console.log('Error : memcached Cron: ', err);
return callback(err);
} else {
getTasks(io);
return callback();
}
});
}else{
return callback();
}
} else {
return callback();
}
}
});
}, function () {
var thisDate = new Date();
console.log('stop Cron in Time : ' + thisDate.getHours() + ':' + thisDate.getMinutes());
}, true, 'Europe/Kiev');
} | function check(io) {
new CronJob('00 * * * * *', function (callback) {
memcached.get('tasks', function (err, tasks) {
if (err) {
console.log('Error : memcached Cron: ', err);
return callback(err);
} else {
var nowDate = new Date();
if (tasks) {
let completedFlag = false;
for (var i = 0; i < tasks.length; i = i + 1) {
let loopDate = new Date(tasks[i].date);
if (loopDate.getFullYear() === nowDate.getFullYear() && loopDate.getMonth() === nowDate.getMonth() && loopDate.getDate() === nowDate.getDate() && loopDate.getHours() === nowDate.getHours() && loopDate.getMinutes() === nowDate.getMinutes()) {
tasks[i].completed = true;
completedFlag = true;
completeTask(tasks[i], io);
}
}
if (completedFlag) {
saveTasks(tasks, function (err) {
if (err) {
console.log('Error : memcached Cron: ', err);
return callback(err);
} else {
getTasks(io);
return callback();
}
});
}else{
return callback();
}
} else {
return callback();
}
}
});
}, function () {
var thisDate = new Date();
console.log('stop Cron in Time : ' + thisDate.getHours() + ':' + thisDate.getMinutes());
}, true, 'Europe/Kiev');
} |
JavaScript | function findTaskById(tasks, id) {
var index = 0;
for (let i = 0; i < tasks.length; i++) {
if (tasks[i].id === id) {
index = i;
break;
}
}
return index;
} | function findTaskById(tasks, id) {
var index = 0;
for (let i = 0; i < tasks.length; i++) {
if (tasks[i].id === id) {
index = i;
break;
}
}
return index;
} |
JavaScript | function generateIdForTask(tasks) {
var id=-1;
for (var i = 0; i < tasks.length; i = i + 1) {
let exists = false;
for (var j = 0; j < tasks.length; j = j + 1) {
if (tasks[j].id === i) {
exists = true;
}
}
if (!exists) {
id = i;
break;
}
}
if (id===-1) {
id = tasks.length;
}
return id;
} | function generateIdForTask(tasks) {
var id=-1;
for (var i = 0; i < tasks.length; i = i + 1) {
let exists = false;
for (var j = 0; j < tasks.length; j = j + 1) {
if (tasks[j].id === i) {
exists = true;
}
}
if (!exists) {
id = i;
break;
}
}
if (id===-1) {
id = tasks.length;
}
return id;
} |
JavaScript | function removeTaskInMem(io, task, callback) {
//Checking for task exists
if (!task) {
io.emit('error', 'No one task have been Send!');
return callback();
}
//try to get tasks from memchached
memcached.get('tasks', function (err, tasks) {
if (err) {
console.log('Error : memcached : removeTaskInMem : ', err);
return callback(err);
} else {
async
.waterfall([
function (waterfallCallback) {
if (!tasks) {
//if dosn't exists create new key
memcached.touch('tasks', lifetime, function (err) {
if (err) {
console.log('Error : memcached : removeTaskInMem :', err);
return waterfallCallback(err);
} else {
//and create new value for key 'tasks'
tasks = [];
return waterfallCallback();
}
});
} else {
//if exists, delete form array task with it's id
tasks.splice(findTaskById(tasks, task.id), 1);
return waterfallCallback();
}
},
function (waterfallCallback) {
//set a new value for key 'tasks' in memcached
memcached.set('tasks', tasks, lifetime, function (err) {
if (err) {
console.log('Error : memcached : removeTaskInMem : ', err);
return waterfallCallback(err);
} else {
return waterfallCallback();
}
});
}
], function (err) {
//last check for errors and send result
if (err) {
io.emit('error', err);
return callback(err);
} else {
io.emit('taskRemoved', tasks);
return callback();
}
});
}
});
} | function removeTaskInMem(io, task, callback) {
//Checking for task exists
if (!task) {
io.emit('error', 'No one task have been Send!');
return callback();
}
//try to get tasks from memchached
memcached.get('tasks', function (err, tasks) {
if (err) {
console.log('Error : memcached : removeTaskInMem : ', err);
return callback(err);
} else {
async
.waterfall([
function (waterfallCallback) {
if (!tasks) {
//if dosn't exists create new key
memcached.touch('tasks', lifetime, function (err) {
if (err) {
console.log('Error : memcached : removeTaskInMem :', err);
return waterfallCallback(err);
} else {
//and create new value for key 'tasks'
tasks = [];
return waterfallCallback();
}
});
} else {
//if exists, delete form array task with it's id
tasks.splice(findTaskById(tasks, task.id), 1);
return waterfallCallback();
}
},
function (waterfallCallback) {
//set a new value for key 'tasks' in memcached
memcached.set('tasks', tasks, lifetime, function (err) {
if (err) {
console.log('Error : memcached : removeTaskInMem : ', err);
return waterfallCallback(err);
} else {
return waterfallCallback();
}
});
}
], function (err) {
//last check for errors and send result
if (err) {
io.emit('error', err);
return callback(err);
} else {
io.emit('taskRemoved', tasks);
return callback();
}
});
}
});
} |
JavaScript | function saveTaskInMem(io, task, callback) {
//Checking for task exists
if (!task) {
io.emit('error', 'No one task have been Send!');
return callback();
}
//try to get tasks from memchached
memcached.get('tasks', function (err, tasks) {
if (err) {
console.log('Error : memcached : saveTaskInMem : ', err);
return callback(err);
} else {
async
.waterfall([
function (waterfallCallback) {
if (!tasks) {
//if dosn't exists create new key
memcached.touch('tasks', lifetime, function (err) {
if (err) {
console.log('Error : memcached : saveTaskInMem : ', err);
return waterfallCallback(err);
} else {
//set new Id for task
task.id = 0
//and create new value for key 'tasks'
tasks = [task];
return waterfallCallback();
}
});
} else {
//set new Id for task
task.id = generateIdForTask(tasks);
//if exists push to is new task
tasks.push(task);
return waterfallCallback();
}
},
function (waterfallCallback) {
//set a new value for key 'tasks' in memcached
memcached.set('tasks', tasks, lifetime, function (err) {
if (err) {
console.log('Error : memcached : saveTaskInMem : ', err);
return waterfallCallback(err);
} else {
return waterfallCallback();
}
});
}
], function (err) {
//last check for errors and send result
if (err) {
io.emit('error', err);
return callback(err);
} else {
io.emit('taskSaved', tasks);
return callback();
}
});
}
});
} | function saveTaskInMem(io, task, callback) {
//Checking for task exists
if (!task) {
io.emit('error', 'No one task have been Send!');
return callback();
}
//try to get tasks from memchached
memcached.get('tasks', function (err, tasks) {
if (err) {
console.log('Error : memcached : saveTaskInMem : ', err);
return callback(err);
} else {
async
.waterfall([
function (waterfallCallback) {
if (!tasks) {
//if dosn't exists create new key
memcached.touch('tasks', lifetime, function (err) {
if (err) {
console.log('Error : memcached : saveTaskInMem : ', err);
return waterfallCallback(err);
} else {
//set new Id for task
task.id = 0
//and create new value for key 'tasks'
tasks = [task];
return waterfallCallback();
}
});
} else {
//set new Id for task
task.id = generateIdForTask(tasks);
//if exists push to is new task
tasks.push(task);
return waterfallCallback();
}
},
function (waterfallCallback) {
//set a new value for key 'tasks' in memcached
memcached.set('tasks', tasks, lifetime, function (err) {
if (err) {
console.log('Error : memcached : saveTaskInMem : ', err);
return waterfallCallback(err);
} else {
return waterfallCallback();
}
});
}
], function (err) {
//last check for errors and send result
if (err) {
io.emit('error', err);
return callback(err);
} else {
io.emit('taskSaved', tasks);
return callback();
}
});
}
});
} |
JavaScript | function restoreOptions() {
// Default values.
chrome.storage.sync.get({
notifications: true,
counters: true,
buttons: true,
}, function(items) {
$(INPUT_NOTIFICATIONS_SELECTOR).prop('checked', items.notifications);
$(INPUT_COUNTERS_SELECTOR).prop('checked', items.counters);
$(INPUT_BUTTONS_SELECTOR).prop('checked', items.buttons);
});
} | function restoreOptions() {
// Default values.
chrome.storage.sync.get({
notifications: true,
counters: true,
buttons: true,
}, function(items) {
$(INPUT_NOTIFICATIONS_SELECTOR).prop('checked', items.notifications);
$(INPUT_COUNTERS_SELECTOR).prop('checked', items.counters);
$(INPUT_BUTTONS_SELECTOR).prop('checked', items.buttons);
});
} |
JavaScript | function main({portletNamespace, contextPath, portletElementId, configuration}) {
if (JSON.stringify(configuration.portletInstance) === '{}') {
ReactDOM.render(<span>Please, configure and save the portlet to make it work</span>,
document.getElementById(portletElementId));
} else if ( ( (JSON.stringify(configuration.system) === '{}') || configuration.system.userid == "" || configuration.system.token == "" ) &&
(configuration.portletInstance.userid == "" || configuration.portletInstance.token == "" )) {
ReactDOM.render(<span>Please, specify both, a valid user ID and token</span>,
document.getElementById(portletElementId));
} else {
ReactDOM.render(
<LRIGBasicDisplay
portletNamespace={portletNamespace}
contextPath={contextPath}
portletElementId={portletElementId}
configuration={configuration}
/>,
document.getElementById(portletElementId)
);
}
} | function main({portletNamespace, contextPath, portletElementId, configuration}) {
if (JSON.stringify(configuration.portletInstance) === '{}') {
ReactDOM.render(<span>Please, configure and save the portlet to make it work</span>,
document.getElementById(portletElementId));
} else if ( ( (JSON.stringify(configuration.system) === '{}') || configuration.system.userid == "" || configuration.system.token == "" ) &&
(configuration.portletInstance.userid == "" || configuration.portletInstance.token == "" )) {
ReactDOM.render(<span>Please, specify both, a valid user ID and token</span>,
document.getElementById(portletElementId));
} else {
ReactDOM.render(
<LRIGBasicDisplay
portletNamespace={portletNamespace}
contextPath={contextPath}
portletElementId={portletElementId}
configuration={configuration}
/>,
document.getElementById(portletElementId)
);
}
} |
JavaScript | function mergePeople(a,b) {
var results = []
if(moment(b[0].from).isBefore(moment(a[0].from))) {
var curTime = moment(b[0].from)
} else {
var curTime = moment(a[0].from)
}
var bn = 0, an=0
var aDollarsCounted = false, bDollarsCounted = false
while(bn < b.length && an < a.length) {
var aFrom = moment(a[an].from), aTo = moment(a[an].to)
var bFrom = moment(b[bn].from), bTo = moment(b[bn].to)
// b's range is before a's range
if( ! bTo.isAfter(aFrom)) {
nonOverlappingItem(b[bn])
bn++
// a's range is before b's range
} else if( ! aTo.isAfter(bFrom)) {
nonOverlappingItem(a[an])
an++
// overlapping
} else {
// b starts before a
if(bFrom.isBefore(aFrom) && curTime.isBefore(aFrom)) {
overlappingItem(b[bn], a[an])
// a starts before b
} else if(aFrom.isBefore(bFrom) && curTime.isBefore(bFrom)) {
overlappingItem(a[an], b[bn])
// start at same time
} else {
var D=0, C=0
if(!aDollarsCounted) {
aDollarsCounted = true
C += a[an].C
D += a[an].D
}
if(!bDollarsCounted) {
bDollarsCounted = true
C += b[bn].C
D += b[bn].D
}
// b ends before a
if(bTo.isBefore(aTo)) {
var overlapEnd = bTo
var increment = 'b'
// a ends before b
} else if(aTo.isBefore(bTo)) {
var overlapEnd = aTo
var increment = 'a'
// end at same time
} else {
var overlapEnd = aTo
var increment = 'both'
}
var totalW = a[an].W+b[bn].W
// combine parts that overlap
var totalItem = {
from: curTime.format('YYYY-MM-DD'), to: overlapEnd.format('YYYY-MM-DD'),
//N: splitNRange(a[an].N, aFrom,aTo, curTime,overlapEnd), // should be same for both 'a' and 'b', so choosing 'a' is arbitrary
S: a[an].S*(a[an].W/totalW) + b[bn].S*(b[bn].W/totalW), // weighted average
W: totalW, // total
C:C, D: D,
}
results.push(totalItem)
curTime = overlapEnd
if(increment === 'a' || increment === 'both') {
an++
aDollarsCounted = false
}
if(increment === 'b' || increment === 'both') {
bn++
bDollarsCounted = false
}
}
}
}
return results
function nonOverlappingItem(x) {
var newItem = copy(x)
newItem.from = curTime.format('YYYY-MM-DD')
results.push(newItem)
curTime = moment(x.to)
}
function overlappingItem(x, y) {
var itemBefore = copy(x)
x.D=0;x.C=0 // don't duplicate the investment (note that this mutates the input, todo: fix this)
//itemBefore.D = 0 // D is added in elsewhere
//itemBefore.N = splitNRange(itemBefore.N, moment(itemBefore.from),moment(itemBefore.to), curTime, moment(y.from))
itemBefore.from = curTime.format('YYYY-MM-DD')
itemBefore.to = y.from
results.push(itemBefore)
curTime = moment(y.from)
}
} | function mergePeople(a,b) {
var results = []
if(moment(b[0].from).isBefore(moment(a[0].from))) {
var curTime = moment(b[0].from)
} else {
var curTime = moment(a[0].from)
}
var bn = 0, an=0
var aDollarsCounted = false, bDollarsCounted = false
while(bn < b.length && an < a.length) {
var aFrom = moment(a[an].from), aTo = moment(a[an].to)
var bFrom = moment(b[bn].from), bTo = moment(b[bn].to)
// b's range is before a's range
if( ! bTo.isAfter(aFrom)) {
nonOverlappingItem(b[bn])
bn++
// a's range is before b's range
} else if( ! aTo.isAfter(bFrom)) {
nonOverlappingItem(a[an])
an++
// overlapping
} else {
// b starts before a
if(bFrom.isBefore(aFrom) && curTime.isBefore(aFrom)) {
overlappingItem(b[bn], a[an])
// a starts before b
} else if(aFrom.isBefore(bFrom) && curTime.isBefore(bFrom)) {
overlappingItem(a[an], b[bn])
// start at same time
} else {
var D=0, C=0
if(!aDollarsCounted) {
aDollarsCounted = true
C += a[an].C
D += a[an].D
}
if(!bDollarsCounted) {
bDollarsCounted = true
C += b[bn].C
D += b[bn].D
}
// b ends before a
if(bTo.isBefore(aTo)) {
var overlapEnd = bTo
var increment = 'b'
// a ends before b
} else if(aTo.isBefore(bTo)) {
var overlapEnd = aTo
var increment = 'a'
// end at same time
} else {
var overlapEnd = aTo
var increment = 'both'
}
var totalW = a[an].W+b[bn].W
// combine parts that overlap
var totalItem = {
from: curTime.format('YYYY-MM-DD'), to: overlapEnd.format('YYYY-MM-DD'),
//N: splitNRange(a[an].N, aFrom,aTo, curTime,overlapEnd), // should be same for both 'a' and 'b', so choosing 'a' is arbitrary
S: a[an].S*(a[an].W/totalW) + b[bn].S*(b[bn].W/totalW), // weighted average
W: totalW, // total
C:C, D: D,
}
results.push(totalItem)
curTime = overlapEnd
if(increment === 'a' || increment === 'both') {
an++
aDollarsCounted = false
}
if(increment === 'b' || increment === 'both') {
bn++
bDollarsCounted = false
}
}
}
}
return results
function nonOverlappingItem(x) {
var newItem = copy(x)
newItem.from = curTime.format('YYYY-MM-DD')
results.push(newItem)
curTime = moment(x.to)
}
function overlappingItem(x, y) {
var itemBefore = copy(x)
x.D=0;x.C=0 // don't duplicate the investment (note that this mutates the input, todo: fix this)
//itemBefore.D = 0 // D is added in elsewhere
//itemBefore.N = splitNRange(itemBefore.N, moment(itemBefore.from),moment(itemBefore.to), curTime, moment(y.from))
itemBefore.from = curTime.format('YYYY-MM-DD')
itemBefore.to = y.from
results.push(itemBefore)
curTime = moment(y.from)
}
} |
JavaScript | function splitNRange(curNrange, curFrom, curTo, newFrom, newTo) {
var aDuration = curTo.diff(curFrom,'days')
var Nslope = (curNrange[1]-curNrange[0])/aDuration
return [curNrange[0]+Nslope*newFrom.diff(curFrom,'days'), curNrange[0]+Nslope*newTo.diff(curFrom,'days')]
} | function splitNRange(curNrange, curFrom, curTo, newFrom, newTo) {
var aDuration = curTo.diff(curFrom,'days')
var Nslope = (curNrange[1]-curNrange[0])/aDuration
return [curNrange[0]+Nslope*newFrom.diff(curFrom,'days'), curNrange[0]+Nslope*newTo.diff(curFrom,'days')]
} |
JavaScript | function personToArray(person, endTime) {
var result = []
var curValues = {S: 0, W: 0}
for(var date in person) {
var changes = person[date]
result.push({from: moment(date), S: newValue(changes, 'S'), W: newValue(changes, 'W'), D: newValue(changes, 'D'), C: newValue(changes, 'C')})
}
result.sort(dateSortFn)
for(var n=0; n<result.length; n++) {
if(n+1<result.length) {
result[n].to = result[n+1].from // note: to is non-inclusive
} else {
result[n].to = endTime
}
}
return result
function newValue(changes, property) {
if(property === 'D')
return changes.D || 0
else if(property === 'C')
return changes.C || 0
else {
if(changes[property] !== undefined) {
var newValue = changes[property]
} else {
var newValue = curValues[property]
}
curValues[property] = newValue
return newValue
}
}
} | function personToArray(person, endTime) {
var result = []
var curValues = {S: 0, W: 0}
for(var date in person) {
var changes = person[date]
result.push({from: moment(date), S: newValue(changes, 'S'), W: newValue(changes, 'W'), D: newValue(changes, 'D'), C: newValue(changes, 'C')})
}
result.sort(dateSortFn)
for(var n=0; n<result.length; n++) {
if(n+1<result.length) {
result[n].to = result[n+1].from // note: to is non-inclusive
} else {
result[n].to = endTime
}
}
return result
function newValue(changes, property) {
if(property === 'D')
return changes.D || 0
else if(property === 'C')
return changes.C || 0
else {
if(changes[property] !== undefined) {
var newValue = changes[property]
} else {
var newValue = curValues[property]
}
curValues[property] = newValue
return newValue
}
}
} |
JavaScript | updateOutput() {
this.setState(prevState => {
let output = null;
if (prevState.firstOperand != null && prevState.operator === null) {
// If we have only the value of the first opersnd, then display the first operand.
output = prevState.firstOperand;
} else if (
// If we have the first operand and the operator, then display the operator
prevState.firstOperand != null &&
prevState.operator != null &&
prevState.secondOperand === null
) {
output = prevState.operator;
} else if (
// If we have the first operand and the operator, then display second operator
prevState.firstOperand != null &&
prevState.operator != null &&
prevState.secondOperand != null
) {
output = prevState.secondOperand;
}
return {
output,
};
});
} | updateOutput() {
this.setState(prevState => {
let output = null;
if (prevState.firstOperand != null && prevState.operator === null) {
// If we have only the value of the first opersnd, then display the first operand.
output = prevState.firstOperand;
} else if (
// If we have the first operand and the operator, then display the operator
prevState.firstOperand != null &&
prevState.operator != null &&
prevState.secondOperand === null
) {
output = prevState.operator;
} else if (
// If we have the first operand and the operator, then display second operator
prevState.firstOperand != null &&
prevState.operator != null &&
prevState.secondOperand != null
) {
output = prevState.secondOperand;
}
return {
output,
};
});
} |
JavaScript | updateOperator(value) {
// To update the operator, we need to have the first operand
if (this.state.secondOperand !== null) {
return;
}
if (this.state.firstOperand !== null && this.state.firstOperand !== '.') {
this.setState({
operator: value,
});
} else if (this.state.output !== null && this.state.firstOperand !== '.') {
this.setState(prevState => ({
firstOperand: `${prevState.output}`,
operator: value,
}));
}
this.updateOutput();
} | updateOperator(value) {
// To update the operator, we need to have the first operand
if (this.state.secondOperand !== null) {
return;
}
if (this.state.firstOperand !== null && this.state.firstOperand !== '.') {
this.setState({
operator: value,
});
} else if (this.state.output !== null && this.state.firstOperand !== '.') {
this.setState(prevState => ({
firstOperand: `${prevState.output}`,
operator: value,
}));
}
this.updateOutput();
} |
JavaScript | processCalculator(value) {
if (value === '=') {
// We should not process the = if no operator has been set
if (this.state.operator === null || this.state.secondOperand === '.') {
return;
}
this.setState(prevState => ({
firstOperand: null,
secondOperand: null,
operator: null,
output: calculator(prevState.operator)(
prevState.firstOperand,
prevState.secondOperand,
),
}));
}
if (value === 'C') {
// We can clear the app
this.setState({
firstOperand: null,
secondOperand: null,
operator: null,
output: null,
});
}
} | processCalculator(value) {
if (value === '=') {
// We should not process the = if no operator has been set
if (this.state.operator === null || this.state.secondOperand === '.') {
return;
}
this.setState(prevState => ({
firstOperand: null,
secondOperand: null,
operator: null,
output: calculator(prevState.operator)(
prevState.firstOperand,
prevState.secondOperand,
),
}));
}
if (value === 'C') {
// We can clear the app
this.setState({
firstOperand: null,
secondOperand: null,
operator: null,
output: null,
});
}
} |
JavaScript | function memberRoleIcon(role) {
switch (role) {
case "Manager":
return '<i class="fas fa-mug-hot"></i>';
case "Engineer":
return '<i class="fas fa-laptop-code"></i>';
case "Intern":
return '<i class="fas fa-graduation-cap"></i>';
default:
return;
}
} | function memberRoleIcon(role) {
switch (role) {
case "Manager":
return '<i class="fas fa-mug-hot"></i>';
case "Engineer":
return '<i class="fas fa-laptop-code"></i>';
case "Intern":
return '<i class="fas fa-graduation-cap"></i>';
default:
return;
}
} |
JavaScript | function createHTML() {
let contentTeam = "";
// loops through all team members added
for (let i = 0; i < team.length; i++) {
const member = team[i];
let memberSpecial = ""
// switch statement to determine whats their role
switch (member.getRole()) {
case "Manager":
memberSpecial =
`<th>Office:</th>
<td>${member.getOffice()}</td>`;
break;
case "Engineer":
memberSpecial =
`<th>GitHub:</th>
<td><a href="https://github.com/${member.getGithub()}" target="_blank">${member.getGithub()}<a></td>`;
break;
case "Intern":
memberSpecial =
`<th>School:</th>
<td>${member.getSchool()}</td>`;
break;
default:
return;
}
// member info under their name and role
let memberInfo =
`<table>
<tr>
<th>ID:</th>
<td>${member.getId()}</td>
<tr>
<tr>
<th>Email:</th>
<td><a href="mailto:${member.getEmail()}" target="_blank">${member.getEmail()}</a></td>
<tr>
<tr>
${memberSpecial}
<tr>
</table>`;
// HTML content for employees
let contentMember =
`<div class="member">
<h2>${member.getName()}</h2>
<h2>${memberRoleIcon(member.getRole())} ${member.getRole()}</h2>
${memberInfo}
</div>`;
contentTeam += contentMember;
}
// the rest of the HTML file that contains the head and body
const contentHTML =
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" type="text/css" href="./assets/css/reset.css" />
<link rel="stylesheet" type="text/css" href="assets/css/style.css"/>
<link href="https://fonts.googleapis.com/css2?family=Open+Sans&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css" integrity="sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm" crossorigin="anonymous">
<title>Team Roster</title>
</head>
<body>
<header>
<h1>Team Roster</h1>
</header>
<main id="team">
${contentTeam}
</main>
</body>
</html>`;
// create teamroster.html file inside the dist folder
fs.writeFile('dist/teamroster.html', contentHTML, function (err) {
if (err) throw err;
console.log("Team Roster Created!");
console.log("Located at Team-Profile-Generator > dist > teamroster.html");
})
} | function createHTML() {
let contentTeam = "";
// loops through all team members added
for (let i = 0; i < team.length; i++) {
const member = team[i];
let memberSpecial = ""
// switch statement to determine whats their role
switch (member.getRole()) {
case "Manager":
memberSpecial =
`<th>Office:</th>
<td>${member.getOffice()}</td>`;
break;
case "Engineer":
memberSpecial =
`<th>GitHub:</th>
<td><a href="https://github.com/${member.getGithub()}" target="_blank">${member.getGithub()}<a></td>`;
break;
case "Intern":
memberSpecial =
`<th>School:</th>
<td>${member.getSchool()}</td>`;
break;
default:
return;
}
// member info under their name and role
let memberInfo =
`<table>
<tr>
<th>ID:</th>
<td>${member.getId()}</td>
<tr>
<tr>
<th>Email:</th>
<td><a href="mailto:${member.getEmail()}" target="_blank">${member.getEmail()}</a></td>
<tr>
<tr>
${memberSpecial}
<tr>
</table>`;
// HTML content for employees
let contentMember =
`<div class="member">
<h2>${member.getName()}</h2>
<h2>${memberRoleIcon(member.getRole())} ${member.getRole()}</h2>
${memberInfo}
</div>`;
contentTeam += contentMember;
}
// the rest of the HTML file that contains the head and body
const contentHTML =
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" type="text/css" href="./assets/css/reset.css" />
<link rel="stylesheet" type="text/css" href="assets/css/style.css"/>
<link href="https://fonts.googleapis.com/css2?family=Open+Sans&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css" integrity="sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm" crossorigin="anonymous">
<title>Team Roster</title>
</head>
<body>
<header>
<h1>Team Roster</h1>
</header>
<main id="team">
${contentTeam}
</main>
</body>
</html>`;
// create teamroster.html file inside the dist folder
fs.writeFile('dist/teamroster.html', contentHTML, function (err) {
if (err) throw err;
console.log("Team Roster Created!");
console.log("Located at Team-Profile-Generator > dist > teamroster.html");
})
} |
JavaScript | function greenlet(asyncFunction) {
// A simple counter is used to generate worker-global unique ID's for RPC:
let currentId = 0;
// Outward-facing promises store their "controllers" (`[request, reject]`) here:
const promises = {};
const func = '$$='+asyncFunction+';onmessage='+(e => {
/* global $$ */
// Invoking within then() captures exceptions in the supplied async function as rejections
Promise.resolve(e.data[1]).then(
v => $$.apply($$, v)
).then(
// success handler - callback(id, SUCCESS(0), result)
// if `d` is transferable transfer zero-copy
d => {
postMessage([e.data[0], 0, d], [d].filter(x => (
(x instanceof ArrayBuffer) ||
(x instanceof MessagePort) ||
(x instanceof ImageBitmap)
)));
},
// error handler - callback(id, ERROR(1), error)
er => { postMessage([e.data[0], 1, '' + er]); }
);
});
// Create an "inline" worker (1:1 at definition time)
let blob;
try {
blob = new Blob([func], { type: 'application/javascript' });
} catch (e) { // Backwards-compatibility
window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
blob = new BlobBuilder();
blob.append(func);
blob = blob.getBlob();
}
const worker = new Worker(URL.createObjectURL(blob));
/** Handle RPC results/errors coming back out of the worker.
* Messages coming from the worker take the form `[id, status, result]`:
* id - counter-based unique ID for the RPC call
* status - 0 for success, 1 for failure
* result - the result or error, depending on `status`
*/
worker.onmessage = e => {
// invoke the promise's resolve() or reject() depending on whether there was an error.
promises[e.data[0]][e.data[1]](e.data[2]);
// ... then delete the promise controller
promises[e.data[0]] = null;
};
// Return a proxy function that forwards calls to the worker & returns a promise for the result.
return function (args) {
args = [].slice.call(arguments);
return new Promise(function () {
// Add the promise controller to the registry
promises[++currentId] = arguments;
// Send an RPC call to the worker - call(id, params)
// The filter is to provide a list of transferables to send zero-copy
worker.postMessage([currentId, args], args.filter(x => (
(x instanceof ArrayBuffer) ||
(x instanceof MessagePort) ||
(x instanceof ImageBitmap)
)));
});
};
} | function greenlet(asyncFunction) {
// A simple counter is used to generate worker-global unique ID's for RPC:
let currentId = 0;
// Outward-facing promises store their "controllers" (`[request, reject]`) here:
const promises = {};
const func = '$$='+asyncFunction+';onmessage='+(e => {
/* global $$ */
// Invoking within then() captures exceptions in the supplied async function as rejections
Promise.resolve(e.data[1]).then(
v => $$.apply($$, v)
).then(
// success handler - callback(id, SUCCESS(0), result)
// if `d` is transferable transfer zero-copy
d => {
postMessage([e.data[0], 0, d], [d].filter(x => (
(x instanceof ArrayBuffer) ||
(x instanceof MessagePort) ||
(x instanceof ImageBitmap)
)));
},
// error handler - callback(id, ERROR(1), error)
er => { postMessage([e.data[0], 1, '' + er]); }
);
});
// Create an "inline" worker (1:1 at definition time)
let blob;
try {
blob = new Blob([func], { type: 'application/javascript' });
} catch (e) { // Backwards-compatibility
window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
blob = new BlobBuilder();
blob.append(func);
blob = blob.getBlob();
}
const worker = new Worker(URL.createObjectURL(blob));
/** Handle RPC results/errors coming back out of the worker.
* Messages coming from the worker take the form `[id, status, result]`:
* id - counter-based unique ID for the RPC call
* status - 0 for success, 1 for failure
* result - the result or error, depending on `status`
*/
worker.onmessage = e => {
// invoke the promise's resolve() or reject() depending on whether there was an error.
promises[e.data[0]][e.data[1]](e.data[2]);
// ... then delete the promise controller
promises[e.data[0]] = null;
};
// Return a proxy function that forwards calls to the worker & returns a promise for the result.
return function (args) {
args = [].slice.call(arguments);
return new Promise(function () {
// Add the promise controller to the registry
promises[++currentId] = arguments;
// Send an RPC call to the worker - call(id, params)
// The filter is to provide a list of transferables to send zero-copy
worker.postMessage([currentId, args], args.filter(x => (
(x instanceof ArrayBuffer) ||
(x instanceof MessagePort) ||
(x instanceof ImageBitmap)
)));
});
};
} |
JavaScript | async function processAction(msg) {
try {
const expression = getExpression(msg);
const result = await transform(expression);
if (result !== undefined) {
return eioUtils.newMessageWithBody(result.body);
}
return;
} catch (e) {
console.log(`ERROR: ${JSON.stringify(e, undefined, 2)}`);
throw new Error(e);
}
} | async function processAction(msg) {
try {
const expression = getExpression(msg);
const result = await transform(expression);
if (result !== undefined) {
return eioUtils.newMessageWithBody(result.body);
}
return;
} catch (e) {
console.log(`ERROR: ${JSON.stringify(e, undefined, 2)}`);
throw new Error(e);
}
} |
JavaScript | async function processAction(msg) {
try {
const expression = getExpression(msg);
const result = await transform(expression);
if (result !== undefined) {
return eioUtils.newMessageWithBody(result.body);
}
return;
} catch (e) {
console.log('ERROR: ', e);
throw new Error(e);
}
} | async function processAction(msg) {
try {
const expression = getExpression(msg);
const result = await transform(expression);
if (result !== undefined) {
return eioUtils.newMessageWithBody(result.body);
}
return;
} catch (e) {
console.log('ERROR: ', e);
throw new Error(e);
}
} |
JavaScript | createEndpoint(method, path, data, callback = null) {
let endpoint = new DummyEndpoint(
this.app,
method,
this.prefix + path,
data,
callback
);
if (!this.endpoints[path]) {
this.endpoints[path] = {};
}
this.endpoints[path][method] = endpoint;
return endpoint;
} | createEndpoint(method, path, data, callback = null) {
let endpoint = new DummyEndpoint(
this.app,
method,
this.prefix + path,
data,
callback
);
if (!this.endpoints[path]) {
this.endpoints[path] = {};
}
this.endpoints[path][method] = endpoint;
return endpoint;
} |
JavaScript | static fromApiObject(response) {
//sanity check of api response
[
"id",
"name",
"state_type_id",
"next_state_id",
"ignore_escalation",
"active",
"note",
"updated_at",
"created_at",
].forEach((key) => {
Utility.ObjectHasKeyOrUnexpectedResponse(response, key);
});
let tstate = new TicketState(
response.id,
response.name,
response.state_type_id,
response.next_state_id,
response.ignore_escalation,
response.active,
response.note,
response.updated_at,
response.created_at
);
return tstate;
} | static fromApiObject(response) {
//sanity check of api response
[
"id",
"name",
"state_type_id",
"next_state_id",
"ignore_escalation",
"active",
"note",
"updated_at",
"created_at",
].forEach((key) => {
Utility.ObjectHasKeyOrUnexpectedResponse(response, key);
});
let tstate = new TicketState(
response.id,
response.name,
response.state_type_id,
response.next_state_id,
response.ignore_escalation,
response.active,
response.note,
response.updated_at,
response.created_at
);
return tstate;
} |
JavaScript | toApiObject() {
let tstate = {};
tstate.id = this.id;
tstate.name = this.name;
tstate.state_type_id = this.stateTypeId;
tstate.next_state_id = this.nextStateId;
tstate.ignore_escalation = this.ignoreEscalation;
tstate.active = this.active;
tstate.note = this.note;
return tstate;
} | toApiObject() {
let tstate = {};
tstate.id = this.id;
tstate.name = this.name;
tstate.state_type_id = this.stateTypeId;
tstate.next_state_id = this.nextStateId;
tstate.ignore_escalation = this.ignoreEscalation;
tstate.active = this.active;
tstate.note = this.note;
return tstate;
} |
JavaScript | _isObjectOrError(data) {
if (typeof data !== "object") {
throw new ApiError.UnexpectedResponse(
"Type of checked data is not object!",
"object",
typeof data
);
}
} | _isObjectOrError(data) {
if (typeof data !== "object") {
throw new ApiError.UnexpectedResponse(
"Type of checked data is not object!",
"object",
typeof data
);
}
} |
JavaScript | _checkResponseCode(res) {
if (res.status !== 200 && res.status !== 201) {
throw new ApiError.UnexpectedResponse(
"Unexpected response code",
"200/ 201",
res.status
);
}
} | _checkResponseCode(res) {
if (res.status !== 200 && res.status !== 201) {
throw new ApiError.UnexpectedResponse(
"Unexpected response code",
"200/ 201",
res.status
);
}
} |
JavaScript | async doPostCall(endpoint, body) {
let response = await axios.post(endpoint, body);
this._isObjectOrError(response.data);
this._checkResponseCode(response);
return response.data;
} | async doPostCall(endpoint, body) {
let response = await axios.post(endpoint, body);
this._isObjectOrError(response.data);
this._checkResponseCode(response);
return response.data;
} |
JavaScript | static fromApiObject(response) {
//sanity check of api response
["id", "firstname", "lastname", "updated_at", "created_at"].forEach(
(key) => {
Utility.ObjectHasKeyOrUnexpectedResponse(response, key);
}
);
let user = new User(
response.id,
response.firstname,
response.lastname,
response.updated_at,
response.created_at
);
//optional fields available in User object
if ("email" in response) {
user.setEmail(response.email);
}
if ("note" in response) {
user.setNote(response.note);
}
if ("organization" in response && "organization_id" in response) {
user.setOrganization(
response.orgnaization_id,
response.organization
);
}
return user;
} | static fromApiObject(response) {
//sanity check of api response
["id", "firstname", "lastname", "updated_at", "created_at"].forEach(
(key) => {
Utility.ObjectHasKeyOrUnexpectedResponse(response, key);
}
);
let user = new User(
response.id,
response.firstname,
response.lastname,
response.updated_at,
response.created_at
);
//optional fields available in User object
if ("email" in response) {
user.setEmail(response.email);
}
if ("note" in response) {
user.setNote(response.note);
}
if ("organization" in response && "organization_id" in response) {
user.setOrganization(
response.orgnaization_id,
response.organization
);
}
return user;
} |
JavaScript | toApiObject() {
let user = {};
user.id = this.id;
user.firstname = this.firstname;
user.lastname = this.lastname;
if (this.email) {
user.email = this.email;
}
if (this.note) {
user.note = this.note;
}
if (this.organizationId && this.organizationName) {
user.orgnaization_id = this.organizationId;
user.organization_name = this.organizationName;
}
return user;
} | toApiObject() {
let user = {};
user.id = this.id;
user.firstname = this.firstname;
user.lastname = this.lastname;
if (this.email) {
user.email = this.email;
}
if (this.note) {
user.note = this.note;
}
if (this.organizationId && this.organizationName) {
user.orgnaization_id = this.organizationId;
user.organization_name = this.organizationName;
}
return user;
} |
JavaScript | static async search(api, query) {
let response = await api.doGetCallWithParams(endpoints.USER_SEARCH, {
[endpoints.USER_SEARCH_QUERY]: query,
});
if (!Array.isArray(response)) {
throw new ApiError.UnexpectedResponse(
"Invalid response (not received array)",
"array",
typeof response
);
}
let users = Array();
response.forEach((obj) => {
users.push(User.fromApiObject(obj));
});
return users;
} | static async search(api, query) {
let response = await api.doGetCallWithParams(endpoints.USER_SEARCH, {
[endpoints.USER_SEARCH_QUERY]: query,
});
if (!Array.isArray(response)) {
throw new ApiError.UnexpectedResponse(
"Invalid response (not received array)",
"array",
typeof response
);
}
let users = Array();
response.forEach((obj) => {
users.push(User.fromApiObject(obj));
});
return users;
} |
JavaScript | async update(api) {
let user = this.toApiObject();
let response = await api.doPutCall(
endpoints.USER_UPDATE + this.id,
user
);
} | async update(api) {
let user = this.toApiObject();
let response = await api.doPutCall(
endpoints.USER_UPDATE + this.id,
user
);
} |
JavaScript | static fromApiObject(response) {
//sanity check of api response
[
"id",
"ticket_id",
"sender_id",
"subject",
"body",
"content_type",
"internal",
"type",
"sender",
"from",
"to",
"cc",
"created_by_id",
"updated_by_id",
"created_at",
"updated_at",
].forEach((key) => {
Utility.ObjectHasKeyOrUnexpectedResponse(response, key);
});
let article = new TicketArticle(
response.id,
response.ticket_id,
response.sender_id,
response.subject,
response.body,
response.content_type,
response.internal,
response.type,
response.sender,
response.from,
response.to,
response.cc,
response.created_by_id,
response.updated_by_id,
response.updated_at,
response.created_at
);
return article;
} | static fromApiObject(response) {
//sanity check of api response
[
"id",
"ticket_id",
"sender_id",
"subject",
"body",
"content_type",
"internal",
"type",
"sender",
"from",
"to",
"cc",
"created_by_id",
"updated_by_id",
"created_at",
"updated_at",
].forEach((key) => {
Utility.ObjectHasKeyOrUnexpectedResponse(response, key);
});
let article = new TicketArticle(
response.id,
response.ticket_id,
response.sender_id,
response.subject,
response.body,
response.content_type,
response.internal,
response.type,
response.sender,
response.from,
response.to,
response.cc,
response.created_by_id,
response.updated_by_id,
response.updated_at,
response.created_at
);
return article;
} |
JavaScript | async sender(api) {
if (this.customerId) {
return await User.getById(api, this.customerId);
} else {
return null;
}
} | async sender(api) {
if (this.customerId) {
return await User.getById(api, this.customerId);
} else {
return null;
}
} |
JavaScript | async ticket(api) {
if (this.ticketId) {
return await Ticket.getById(api, this.ticketId);
} else {
return null;
}
} | async ticket(api) {
if (this.ticketId) {
return await Ticket.getById(api, this.ticketId);
} else {
return null;
}
} |
JavaScript | static randomIsoTimestamp(){
let randomTimestamp = Math.random() * (new Date().getTime());
let randomDate = new Date();
randomDate.setTime(randomTimestamp);
return randomDate.toISOString();
} | static randomIsoTimestamp(){
let randomTimestamp = Math.random() * (new Date().getTime());
let randomDate = new Date();
randomDate.setTime(randomTimestamp);
return randomDate.toISOString();
} |
JavaScript | static fromApiObject(response) {
//sanity check of api response
[
"id",
"title",
"number",
"group_id",
"state_id",
"priority_id",
"customer_id",
"owner_id",
"note",
"updated_at",
"created_at",
].forEach(key => {
Utility.ObjectHasKeyOrUnexpectedResponse(response, key);
});
let ticket = new Ticket(
response.id,
response.title,
response.number,
response.group_id,
response.state_id,
response.priority_id,
response.customer_id,
response.owner_id,
response.note,
response.updated_at,
response.created_at
);
return ticket;
} | static fromApiObject(response) {
//sanity check of api response
[
"id",
"title",
"number",
"group_id",
"state_id",
"priority_id",
"customer_id",
"owner_id",
"note",
"updated_at",
"created_at",
].forEach(key => {
Utility.ObjectHasKeyOrUnexpectedResponse(response, key);
});
let ticket = new Ticket(
response.id,
response.title,
response.number,
response.group_id,
response.state_id,
response.priority_id,
response.customer_id,
response.owner_id,
response.note,
response.updated_at,
response.created_at
);
return ticket;
} |
JavaScript | toApiObject() {
let ticket = {};
ticket.id = this.id;
ticket.title = this.title;
ticket.number = this.number;
ticket.group_id = this.groupId;
ticket.state_id = this.stateId;
ticket.priority_id = this.priorityId;
ticket.customer_id = this.customerId;
ticket.owner_id = this.ownerId;
ticket.note = this.note;
return ticket;
} | toApiObject() {
let ticket = {};
ticket.id = this.id;
ticket.title = this.title;
ticket.number = this.number;
ticket.group_id = this.groupId;
ticket.state_id = this.stateId;
ticket.priority_id = this.priorityId;
ticket.customer_id = this.customerId;
ticket.owner_id = this.ownerId;
ticket.note = this.note;
return ticket;
} |
JavaScript | static async search(api, query) {
let response = await api.doGetCallWithParams(endpoints.TICKET_SEARCH, {
[endpoints.TICKET_SEARCH_QUERY]: query,
});
if (!Array.isArray(response)) {
throw new ApiError.UnexpectedResponse(
"Invalid response (not received array)",
"array",
typeof response
);
}
let tickets = Array();
response.forEach(obj => {
tickets.push(Ticket.fromApiObject(obj));
});
return tickets;
} | static async search(api, query) {
let response = await api.doGetCallWithParams(endpoints.TICKET_SEARCH, {
[endpoints.TICKET_SEARCH_QUERY]: query,
});
if (!Array.isArray(response)) {
throw new ApiError.UnexpectedResponse(
"Invalid response (not received array)",
"array",
typeof response
);
}
let tickets = Array();
response.forEach(obj => {
tickets.push(Ticket.fromApiObject(obj));
});
return tickets;
} |
JavaScript | async update(api) {
let ticket = this.toApiObject();
let response = await api.doPutCall(
endpoints.TICKET_UPDATE + this.id,
ticket
);
} | async update(api) {
let ticket = this.toApiObject();
let response = await api.doPutCall(
endpoints.TICKET_UPDATE + this.id,
ticket
);
} |
JavaScript | async customer(api) {
if (this.customerId) {
return await User.getById(api, this.customerId);
} else {
return null;
}
} | async customer(api) {
if (this.customerId) {
return await User.getById(api, this.customerId);
} else {
return null;
}
} |
JavaScript | async owner(api) {
if (this.ownerId) {
return await User.getById(api, this.ownerId);
} else {
return null;
}
} | async owner(api) {
if (this.ownerId) {
return await User.getById(api, this.ownerId);
} else {
return null;
}
} |
JavaScript | async priority(api) {
if (this.priorityId) {
return await TicketPriority.getById(api, this.priorityId);
} else {
return null;
}
} | async priority(api) {
if (this.priorityId) {
return await TicketPriority.getById(api, this.priorityId);
} else {
return null;
}
} |
JavaScript | async state(api) {
if (this.stateId) {
return await TicketState.getById(api, this.stateId);
} else {
return null;
}
} | async state(api) {
if (this.stateId) {
return await TicketState.getById(api, this.stateId);
} else {
return null;
}
} |
JavaScript | static fromApiObject(response) {
//sanity check of api response
["id", "name", "active", "note", "updated_at", "created_at"].forEach(
(key) => {
Utility.ObjectHasKeyOrUnexpectedResponse(response, key);
}
);
let tprio = new TicketPriority(
response.id,
response.name,
response.active,
response.note,
response.updated_at,
response.created_at
);
return tprio;
} | static fromApiObject(response) {
//sanity check of api response
["id", "name", "active", "note", "updated_at", "created_at"].forEach(
(key) => {
Utility.ObjectHasKeyOrUnexpectedResponse(response, key);
}
);
let tprio = new TicketPriority(
response.id,
response.name,
response.active,
response.note,
response.updated_at,
response.created_at
);
return tprio;
} |
JavaScript | toApiObject() {
let tprio = {};
tprio.id = this.id;
tprio.name = this.name;
tprio.active = this.active;
tprio.note = this.note;
return tprio;
} | toApiObject() {
let tprio = {};
tprio.id = this.id;
tprio.name = this.name;
tprio.active = this.active;
tprio.note = this.note;
return tprio;
} |
JavaScript | function increaseSequence (nextAction) {
return function () {
self.nextExpectedAction = nextAction
++self.sequenceLevels[combo]
self.resetSequenceTimer()
}
} | function increaseSequence (nextAction) {
return function () {
self.nextExpectedAction = nextAction
++self.sequenceLevels[combo]
self.resetSequenceTimer()
}
} |
JavaScript | function callbackAndReset (e) {
var characterFromEvent
self.fireCallback(callback, e, combo)
// we should ignore the next key up if the action is key down
// or keypress. this is so if you finish a sequence and
// release the key the final key will not trigger a keyup
if (action !== 'keyup') {
characterFromEvent = require('../../helpers/characterFromEvent')
self.ignoreNextKeyup = characterFromEvent(e)
}
// weird race condition if a sequence ends with the key
// another sequence begins with
setTimeout(
function () {
self.resetSequences()
},
10
)
} | function callbackAndReset (e) {
var characterFromEvent
self.fireCallback(callback, e, combo)
// we should ignore the next key up if the action is key down
// or keypress. this is so if you finish a sequence and
// release the key the final key will not trigger a keyup
if (action !== 'keyup') {
characterFromEvent = require('../../helpers/characterFromEvent')
self.ignoreNextKeyup = characterFromEvent(e)
}
// weird race condition if a sequence ends with the key
// another sequence begins with
setTimeout(
function () {
self.resetSequences()
},
10
)
} |
JavaScript | function scrollToDemoFrame(targetDemoFrameNumber)
{
const demoFrames = window.frames;
// If any demo is running, stop it.
for (let i = 0; i < demoFrames.length; i++)
{
let currentFrameDemoController = demoFrames[i].demoController;
if (currentFrameDemoController)
currentFrameDemoController.stop();
}
// If we're already scrolling from one demo to another, stop
if (currentDemoScrollSequence)
currentDemoScrollSequence.stop();
// Figure out where the current-selection marker is moving from, and where it is moving to.
let demoChoiceMarkerCurrentRect = demoChoiceMarker.getBoundingClientRect();
let demoChoiceMarkerTargetRect = demoChoiceRects[targetDemoFrameNumber];
// Create the animation to scroll to the selected demo.
currentDemoScrollSequence = new Concert.Sequence();
currentDemoScrollSequence.setDefaults({ easing: DemoScrollAnimationEasing });
currentDemoScrollSequence.addTransformations(
[
// Animate the frames area to shift the proper frame into view.
{
target: entireDemoFramesArea,
feature: "scrollLeft",
keyframes:
{
times: [0, DemoScrollSequenceTime],
values: [entireDemoFramesArea.scrollLeft, demoFrameWidth * targetDemoFrameNumber]
}
},
// Over the same amount of time, animate the currently-selected-demo marker
// to move to the right tab and resize itself to match the newly selected tab.
{
target: demoChoiceMarker,
feature: ["left", "width"],
unit: "px",
applicator: Concert.Applicators.Style,
keyframes:
{
times: [0, DemoScrollSequenceTime],
values:
[
// start value (array of left and width values to be applied to the above array of features)
[
demoChoiceMarkerCurrentRect.left - demoChoiceListRect.left,
demoChoiceMarkerCurrentRect.right - demoChoiceMarkerCurrentRect.left
],
// end value (array of left and width values to be applied to the above array of features)
[
demoChoiceMarkerTargetRect.left - demoChoiceListRect.left - demoChoiceMarkerLeftOffset,
demoChoiceMarkerTargetRect.right - demoChoiceMarkerTargetRect.left
]
]
}
}
]);
// Run the animation
let targetDemoFrame = demoFrames[targetDemoFrameNumber-1];
currentDemoScrollSequence.begin(
{
onAutoStop:
function ()
{
currentDemoScrollSequence = null;
if(targetDemoFrame.demoController)
targetDemoFrame.demoController.enable();
}
});
} // end scrollToDemoFrame()
| function scrollToDemoFrame(targetDemoFrameNumber)
{
const demoFrames = window.frames;
// If any demo is running, stop it.
for (let i = 0; i < demoFrames.length; i++)
{
let currentFrameDemoController = demoFrames[i].demoController;
if (currentFrameDemoController)
currentFrameDemoController.stop();
}
// If we're already scrolling from one demo to another, stop
if (currentDemoScrollSequence)
currentDemoScrollSequence.stop();
// Figure out where the current-selection marker is moving from, and where it is moving to.
let demoChoiceMarkerCurrentRect = demoChoiceMarker.getBoundingClientRect();
let demoChoiceMarkerTargetRect = demoChoiceRects[targetDemoFrameNumber];
// Create the animation to scroll to the selected demo.
currentDemoScrollSequence = new Concert.Sequence();
currentDemoScrollSequence.setDefaults({ easing: DemoScrollAnimationEasing });
currentDemoScrollSequence.addTransformations(
[
// Animate the frames area to shift the proper frame into view.
{
target: entireDemoFramesArea,
feature: "scrollLeft",
keyframes:
{
times: [0, DemoScrollSequenceTime],
values: [entireDemoFramesArea.scrollLeft, demoFrameWidth * targetDemoFrameNumber]
}
},
// Over the same amount of time, animate the currently-selected-demo marker
// to move to the right tab and resize itself to match the newly selected tab.
{
target: demoChoiceMarker,
feature: ["left", "width"],
unit: "px",
applicator: Concert.Applicators.Style,
keyframes:
{
times: [0, DemoScrollSequenceTime],
values:
[
// start value (array of left and width values to be applied to the above array of features)
[
demoChoiceMarkerCurrentRect.left - demoChoiceListRect.left,
demoChoiceMarkerCurrentRect.right - demoChoiceMarkerCurrentRect.left
],
// end value (array of left and width values to be applied to the above array of features)
[
demoChoiceMarkerTargetRect.left - demoChoiceListRect.left - demoChoiceMarkerLeftOffset,
demoChoiceMarkerTargetRect.right - demoChoiceMarkerTargetRect.left
]
]
}
}
]);
// Run the animation
let targetDemoFrame = demoFrames[targetDemoFrameNumber-1];
currentDemoScrollSequence.begin(
{
onAutoStop:
function ()
{
currentDemoScrollSequence = null;
if(targetDemoFrame.demoController)
targetDemoFrame.demoController.enable();
}
});
} // end scrollToDemoFrame()
|
JavaScript | function runShipDownSequence()
{
currentDirection = Directions.Down;
shipDownSequence.begin({ onAutoStop: runShipUpSequence });
} | function runShipDownSequence()
{
currentDirection = Directions.Down;
shipDownSequence.begin({ onAutoStop: runShipUpSequence });
} |
JavaScript | function runShipUpSequence()
{
currentDirection = Directions.Up;
shipUpSequence.begin({ onAutoStop: runShipDownSequence });
} | function runShipUpSequence()
{
currentDirection = Directions.Up;
shipUpSequence.begin({ onAutoStop: runShipDownSequence });
} |
JavaScript | function fireMissile()
{
let missileTopPosition = getMissileStartTop(),
missileDiv = document.createElement("div");
missileDiv.className = "Missile";
missileDiv.style.left = ShipWidth + "px";
missileDiv.style.top = missileTopPosition + "px";
BackgroundArea.appendChild(missileDiv);
let newMissileSequence = missileSequence.clone(function() { return missileDiv; });
newMissileSequence.begin({ onAutoStop: function() { missileDiv.remove(); } });
} | function fireMissile()
{
let missileTopPosition = getMissileStartTop(),
missileDiv = document.createElement("div");
missileDiv.className = "Missile";
missileDiv.style.left = ShipWidth + "px";
missileDiv.style.top = missileTopPosition + "px";
BackgroundArea.appendChild(missileDiv);
let newMissileSequence = missileSequence.clone(function() { return missileDiv; });
newMissileSequence.begin({ onAutoStop: function() { missileDiv.remove(); } });
} |
JavaScript | function extractWordPositions(rootNode)
{
let allWordPositions = [], extracting = true,
currentNode = rootNode, currentNodeExhausted = false;
while (extracting)
{
if (currentNodeExhausted)
{
// This node and all its descendents have been searched already.
if (currentNode === rootNode)
extracting = false; // If the root node is fully searched, there isn't any more searching to be done. Quit searching.
else if (currentNode.nextSibling !== null)
{
// Otherwise, move on to searching the next sibling if there is one.
currentNode = currentNode.nextSibling;
currentNodeExhausted = false;
}
else
currentNode = currentNode.parentNode; // Otherwise, pop back up a level to the parent.
// Note that since we only move up a level when all the siblings at this level are done, moving up means
// the immediate parent is done as well, so in that case we leave currentNodeExhausted set to true.
}
else
{
// This node isn't exhausted yet.
// Get all the words in the current node if it is a text node, and add them to the array of all word positions.
if (currentNode.nodeType === Node.TEXT_NODE)
getWordPositions(currentNode).forEach(function(wordPosition) { allWordPositions.push(wordPosition); });
// Move to the next child level down and continue the search. If there is none, this node is exhausted.
if (currentNode.childNodes.length > 0)
currentNode = currentNode.childNodes[0];
else
currentNodeExhausted = true;
}
} // end while (extracting)
return allWordPositions;
} // end extractWordPositions() | function extractWordPositions(rootNode)
{
let allWordPositions = [], extracting = true,
currentNode = rootNode, currentNodeExhausted = false;
while (extracting)
{
if (currentNodeExhausted)
{
// This node and all its descendents have been searched already.
if (currentNode === rootNode)
extracting = false; // If the root node is fully searched, there isn't any more searching to be done. Quit searching.
else if (currentNode.nextSibling !== null)
{
// Otherwise, move on to searching the next sibling if there is one.
currentNode = currentNode.nextSibling;
currentNodeExhausted = false;
}
else
currentNode = currentNode.parentNode; // Otherwise, pop back up a level to the parent.
// Note that since we only move up a level when all the siblings at this level are done, moving up means
// the immediate parent is done as well, so in that case we leave currentNodeExhausted set to true.
}
else
{
// This node isn't exhausted yet.
// Get all the words in the current node if it is a text node, and add them to the array of all word positions.
if (currentNode.nodeType === Node.TEXT_NODE)
getWordPositions(currentNode).forEach(function(wordPosition) { allWordPositions.push(wordPosition); });
// Move to the next child level down and continue the search. If there is none, this node is exhausted.
if (currentNode.childNodes.length > 0)
currentNode = currentNode.childNodes[0];
else
currentNodeExhausted = true;
}
} // end while (extracting)
return allWordPositions;
} // end extractWordPositions() |
JavaScript | function selectionApplicator(target, feature, value)
{
let selection = window.getSelection(),
range = document.createRange();
selection.removeAllRanges(); // Remove any present text selections in the window.
if(value.start !== null) // Allow for passing in a null value; treat that as selecting nothing at all.
{
// Extract the start and end points for the selection from the value object,
// define the range based on those, and select that range.
range.setStart(value.start.node, value.start.position);
range.setEnd(value.end.node, value.end.position);
selection.addRange(range);
}
} // end selectionApplicator() | function selectionApplicator(target, feature, value)
{
let selection = window.getSelection(),
range = document.createRange();
selection.removeAllRanges(); // Remove any present text selections in the window.
if(value.start !== null) // Allow for passing in a null value; treat that as selecting nothing at all.
{
// Extract the start and end points for the selection from the value object,
// define the range based on those, and select that range.
range.setStart(value.start.node, value.start.position);
range.setEnd(value.end.node, value.end.position);
selection.addRange(range);
}
} // end selectionApplicator() |
JavaScript | function buildAnimation()
{
// Assemble an array of all the transformations in the entire animation.
let transformationSet =
getLyricsTransformations()
.concat(getBeatTransformations())
.concat(getClapTransformations());
// Create a sequence object. This is the basic object used for everything.
let sequence = new Concert.Sequence();
// Add the transformation set to the sequence.
sequence.addTransformations(transformationSet);
// Wire up the event handlers.
// We want the animation to be running whenever the video is running,
// stopped whenever the video is stopped (including reeaching its end),
// and to jump to the appropriate spot whenever the user seeks to a new position.
video.onplay = function() { sequence.syncTo(video); };
video.onpause = video.onended = function() { sequence.stop(); };
video.onseeked = function() { sequence.seek(video.currentTime * 1000); };
return sequence;
} // end buildAnimation() | function buildAnimation()
{
// Assemble an array of all the transformations in the entire animation.
let transformationSet =
getLyricsTransformations()
.concat(getBeatTransformations())
.concat(getClapTransformations());
// Create a sequence object. This is the basic object used for everything.
let sequence = new Concert.Sequence();
// Add the transformation set to the sequence.
sequence.addTransformations(transformationSet);
// Wire up the event handlers.
// We want the animation to be running whenever the video is running,
// stopped whenever the video is stopped (including reeaching its end),
// and to jump to the appropriate spot whenever the user seeks to a new position.
video.onplay = function() { sequence.syncTo(video); };
video.onpause = video.onended = function() { sequence.stop(); };
video.onseeked = function() { sequence.seek(video.currentTime * 1000); };
return sequence;
} // end buildAnimation() |
JavaScript | waitFor (timeout = 0, pollInterval = 0) {
timeout = timeout || this.driver._defaultPollTimeout
pollInterval = pollInterval || this.driver._pollInterval
return this.driver.waitFor.call(this, timeout, pollInterval)
} | waitFor (timeout = 0, pollInterval = 0) {
timeout = timeout || this.driver._defaultPollTimeout
pollInterval = pollInterval || this.driver._pollInterval
return this.driver.waitFor.call(this, timeout, pollInterval)
} |
JavaScript | async sendKeys (text) {
// W3c: Adding 'value' to parameters, so that Chrome works too
var value = text.split('')
await this._execute('post', `/element/${this.id}/value`, { text, value })
return this
} | async sendKeys (text) {
// W3c: Adding 'value' to parameters, so that Chrome works too
var value = text.split('')
await this._execute('post', `/element/${this.id}/value`, { text, value })
return this
} |
JavaScript | compile () {
if (this._compiled) return
this.compiledActions = []
this._takeVirginOutOfCurrentAction()
this.devices.forEach((device) => {
var deviceActions = { actions: [] }
deviceActions.type = device.type
deviceActions.id = device.id
if (device.type === 'pointer') {
deviceActions.parameters = { pointerType: device.pointerType }
}
this.actions.forEach((action) => {
deviceActions.actions.push(action[ device.id ])
})
this.compiledActions.push(deviceActions)
})
// console.log('COMPILED ACTIONS:', require('util').inspect(this.compiledActions, {depth: 10}))
} | compile () {
if (this._compiled) return
this.compiledActions = []
this._takeVirginOutOfCurrentAction()
this.devices.forEach((device) => {
var deviceActions = { actions: [] }
deviceActions.type = device.type
deviceActions.id = device.id
if (device.type === 'pointer') {
deviceActions.parameters = { pointerType: device.pointerType }
}
this.actions.forEach((action) => {
deviceActions.actions.push(action[ device.id ])
})
this.compiledActions.push(deviceActions)
})
// console.log('COMPILED ACTIONS:', require('util').inspect(this.compiledActions, {depth: 10}))
} |
JavaScript | async status () {
var res = await super.status()
res.ready = true
res.message = ''
return res
} | async status () {
var res = await super.status()
res.ready = true
res.message = ''
return res
} |
JavaScript | static get Type () {
return {
MOUSE: 'mouse',
PEN: 'pen',
TOUCH: 'touch'
}
} | static get Type () {
return {
MOUSE: 'mouse',
PEN: 'pen',
TOUCH: 'touch'
}
} |
JavaScript | async startWebDriver () {
// If spawning is required, do so
if (!this._webDriverRunning && this._spawn && this._executable) {
// No port: find a free port
if (!this._port) {
this._port = await getPort({ host: this._hostname })
}
// Options: port, args, env, stdio
var res = await this.run({
port: this._port,
args: this._args,
env: this._env,
stdio: this._stdio }
)
this._killCommand = res.killCommand
}
// It's still possible that no port has been set, since spawn was false
// and no port was defined. In such a case, use the default 4444
if (!this._port) this._port = '4444'
// `_hostname` and `_port` are finally set: make up the first `urlBase`
this._urlBase = `http://${this._hostname}:${this._port}/session`
await this.sleep(200)
// Check that the server is up, by asking for the status
// It might take a little while for the
var success = false
for (var i = 0; i < 40; i++) {
if (i > 5) {
console.log(`Attempt n. ${i} to connect to ${this._hostname}, port ${this._port}... `)
}
try {
await this.status()
success = true
break
} catch (e) {
await this.sleep(300)
}
}
if (!success) {
throw new Error(`Could not connect to the driver`)
}
// Connection worked...
this._webDriverRunning = true
} | async startWebDriver () {
// If spawning is required, do so
if (!this._webDriverRunning && this._spawn && this._executable) {
// No port: find a free port
if (!this._port) {
this._port = await getPort({ host: this._hostname })
}
// Options: port, args, env, stdio
var res = await this.run({
port: this._port,
args: this._args,
env: this._env,
stdio: this._stdio }
)
this._killCommand = res.killCommand
}
// It's still possible that no port has been set, since spawn was false
// and no port was defined. In such a case, use the default 4444
if (!this._port) this._port = '4444'
// `_hostname` and `_port` are finally set: make up the first `urlBase`
this._urlBase = `http://${this._hostname}:${this._port}/session`
await this.sleep(200)
// Check that the server is up, by asking for the status
// It might take a little while for the
var success = false
for (var i = 0; i < 40; i++) {
if (i > 5) {
console.log(`Attempt n. ${i} to connect to ${this._hostname}, port ${this._port}... `)
}
try {
await this.status()
success = true
break
} catch (e) {
await this.sleep(300)
}
}
if (!success) {
throw new Error(`Could not connect to the driver`)
}
// Connection worked...
this._webDriverRunning = true
} |
JavaScript | async deleteSession () {
try {
var value = await this._execute('delete', '')
this._sessionId = null
this._sessionData = {}
this._urlBase = `http://${this._hostname}:${this._port}/session`
return value
} catch (e) {
throw (e)
}
} | async deleteSession () {
try {
var value = await this._execute('delete', '')
this._sessionId = null
this._sessionData = {}
this._urlBase = `http://${this._hostname}:${this._port}/session`
return value
} catch (e) {
throw (e)
}
} |
JavaScript | async performActions (actions) {
actions.compile()
await this._execute('post', '/actions', { actions: actions.compiledActions })
return this
} | async performActions (actions) {
actions.compile()
await this._execute('post', '/actions', { actions: actions.compiledActions })
return this
} |
JavaScript | function generateMarkdown(data) {
return `# ${data.title}
${data.link}
## Description
${data.description}
## Table of Contents
* [instalation](#instalation)
* [Usage](#usage)
* [License](#license)
* [Contributing](#contributing)
* [Tests](#tests)
* [Questions](#questions)
## Installation
To install necessary dependancies, run the following command:
${data.dependencies}
## Usage
${data.using}
## License
This project is licensed under the ${data.license} license
## Contributing
${data.contributing}
## Tests
to run tests, run the following command:
${data.tests}
## Questions
If you have any questions anout the repo, open an issue or contact me directly at [${data.username}](https://github.com/${data.username}/).
Or send me an email at [${data.email}](${data.email})
`;
} | function generateMarkdown(data) {
return `# ${data.title}
${data.link}
## Description
${data.description}
## Table of Contents
* [instalation](#instalation)
* [Usage](#usage)
* [License](#license)
* [Contributing](#contributing)
* [Tests](#tests)
* [Questions](#questions)
## Installation
To install necessary dependancies, run the following command:
${data.dependencies}
## Usage
${data.using}
## License
This project is licensed under the ${data.license} license
## Contributing
${data.contributing}
## Tests
to run tests, run the following command:
${data.tests}
## Questions
If you have any questions anout the repo, open an issue or contact me directly at [${data.username}](https://github.com/${data.username}/).
Or send me an email at [${data.email}](${data.email})
`;
} |
JavaScript | function buildSuggestMessage(userName, userId, requestText, emojis) {
return {
response_type: 'in_channel',
text: `<@${userId}|${userName}> asked for emoji suggestions: *${requestText}*`,
unfurl_links: false,
attachments: [
{
text: emojis.join(' ')
}
]
};
} | function buildSuggestMessage(userName, userId, requestText, emojis) {
return {
response_type: 'in_channel',
text: `<@${userId}|${userName}> asked for emoji suggestions: *${requestText}*`,
unfurl_links: false,
attachments: [
{
text: emojis.join(' ')
}
]
};
} |
JavaScript | function buildErrorMessage(err) {
return {
text: `error occurred with your command. (${err})`,
unfurl_links: false,
};
} | function buildErrorMessage(err) {
return {
text: `error occurred with your command. (${err})`,
unfurl_links: false,
};
} |
JavaScript | static async output() {
if (!Discord) {
Discord = require("../discord");
}
if (Discord.isConnected()) {
for (const log of queue) {
if (log.type === "exception") {
if (log.obj) {
if (log.obj.message && log.obj.innerError && log.obj.innerError.message && log.obj.innerError.code === "ETIMEOUT") {
log.obj = `${log.obj.message} - ${log.obj.innerError.message} - ETIMEOUT`;
}
if (log.obj.message && log.obj.originalError && log.obj.originalError.message && log.obj.originalError.code === "ETIMEOUT") {
log.obj = `${log.obj.message} - ${log.obj.originalError.message} - ETIMEOUT`;
}
if (log.obj.message && log.obj.syscall && log.obj.code === "ETIMEDOUT") {
log.obj = `${log.obj.message} - ${log.obj.syscall} - ETIMEDOUT`;
}
if (log.obj.name === "TimeoutError") {
log.obj = `${log.obj.message} - TimeoutError`;
}
if (log.obj.innerError && log.obj.message && log.obj.innerError.name === "TimeoutError") {
log.obj = `${log.obj.message} - TimeoutError`;
}
if (log.obj.error && log.obj.message && log.obj.error.syscall && log.obj.error.code === "ETIMEDOUT") {
log.obj = `${log.obj.message} - ${log.obj.error.syscall} - ETIMEDOUT`;
}
if (log.obj.message && log.obj.message === "Unexpected server response: 502") {
log.obj = `${log.obj.message}`;
}
try {
const res = await request.post({
uri: settings.logger.url,
body: {
key: settings.logger.key,
application: "otl.gg",
category: "exception",
message: `${log.message}\n${util.inspect(log.obj)}`,
date: new Date().getTime()
},
json: true
});
if (res.body.id) {
await Discord.queue(`Error occurred, see ${res.body.url}.`, /** @type {DiscordJs.TextChannel} */ (Discord.findChannelByName("otlbot-errors"))); // eslint-disable-line no-extra-parens
} else {
await Discord.queue("Error occurred, problem sending log, see https://logger.roncli.com.", /** @type {DiscordJs.TextChannel} */ (Discord.findChannelByName("otlbot-errors"))); // eslint-disable-line no-extra-parens
}
} catch (err) {
await Log.outputToDiscord(log, err);
}
} else {
const message = Discord.messageEmbed({
color: 0xFF0000,
fields: [],
timestamp: log.date
});
if (log.message) {
message.setDescription(log.message);
}
await Discord.richQueue(message, /** @type {DiscordJs.TextChannel} */ (Discord.findChannelByName("otlbot-errors"))); // eslint-disable-line no-extra-parens
}
} else {
const message = Discord.messageEmbed({
color: log.type === "log" ? 0x80FF80 : log.type === "warning" ? 0xFFFF00 : 0xFF0000,
fields: [],
timestamp: log.date
});
if (log.message) {
message.setDescription(log.message);
}
await Discord.richQueue(message, /** @type {DiscordJs.TextChannel} */ (Discord.findChannelByName("otlbot-log"))); // eslint-disable-line no-extra-parens
}
}
queue.splice(0, queue.length);
} else {
console.log(queue[queue.length - 1]);
}
} | static async output() {
if (!Discord) {
Discord = require("../discord");
}
if (Discord.isConnected()) {
for (const log of queue) {
if (log.type === "exception") {
if (log.obj) {
if (log.obj.message && log.obj.innerError && log.obj.innerError.message && log.obj.innerError.code === "ETIMEOUT") {
log.obj = `${log.obj.message} - ${log.obj.innerError.message} - ETIMEOUT`;
}
if (log.obj.message && log.obj.originalError && log.obj.originalError.message && log.obj.originalError.code === "ETIMEOUT") {
log.obj = `${log.obj.message} - ${log.obj.originalError.message} - ETIMEOUT`;
}
if (log.obj.message && log.obj.syscall && log.obj.code === "ETIMEDOUT") {
log.obj = `${log.obj.message} - ${log.obj.syscall} - ETIMEDOUT`;
}
if (log.obj.name === "TimeoutError") {
log.obj = `${log.obj.message} - TimeoutError`;
}
if (log.obj.innerError && log.obj.message && log.obj.innerError.name === "TimeoutError") {
log.obj = `${log.obj.message} - TimeoutError`;
}
if (log.obj.error && log.obj.message && log.obj.error.syscall && log.obj.error.code === "ETIMEDOUT") {
log.obj = `${log.obj.message} - ${log.obj.error.syscall} - ETIMEDOUT`;
}
if (log.obj.message && log.obj.message === "Unexpected server response: 502") {
log.obj = `${log.obj.message}`;
}
try {
const res = await request.post({
uri: settings.logger.url,
body: {
key: settings.logger.key,
application: "otl.gg",
category: "exception",
message: `${log.message}\n${util.inspect(log.obj)}`,
date: new Date().getTime()
},
json: true
});
if (res.body.id) {
await Discord.queue(`Error occurred, see ${res.body.url}.`, /** @type {DiscordJs.TextChannel} */ (Discord.findChannelByName("otlbot-errors"))); // eslint-disable-line no-extra-parens
} else {
await Discord.queue("Error occurred, problem sending log, see https://logger.roncli.com.", /** @type {DiscordJs.TextChannel} */ (Discord.findChannelByName("otlbot-errors"))); // eslint-disable-line no-extra-parens
}
} catch (err) {
await Log.outputToDiscord(log, err);
}
} else {
const message = Discord.messageEmbed({
color: 0xFF0000,
fields: [],
timestamp: log.date
});
if (log.message) {
message.setDescription(log.message);
}
await Discord.richQueue(message, /** @type {DiscordJs.TextChannel} */ (Discord.findChannelByName("otlbot-errors"))); // eslint-disable-line no-extra-parens
}
} else {
const message = Discord.messageEmbed({
color: log.type === "log" ? 0x80FF80 : log.type === "warning" ? 0xFFFF00 : 0xFF0000,
fields: [],
timestamp: log.date
});
if (log.message) {
message.setDescription(log.message);
}
await Discord.richQueue(message, /** @type {DiscordJs.TextChannel} */ (Discord.findChannelByName("otlbot-log"))); // eslint-disable-line no-extra-parens
}
}
queue.splice(0, queue.length);
} else {
console.log(queue[queue.length - 1]);
}
} |
JavaScript | static async outputToDiscord(log, err) {
let value = util.inspect(log.obj),
continued = false;
while (value.length > 0) {
if (continued) {
await Discord.queue(value.substring(0, 1024), /** @type {DiscordJs.TextChannel} */ (Discord.findChannelByName("otlbot-errors"))); // eslint-disable-line no-extra-parens
} else if (log.message) {
const message = Discord.messageEmbed({
color: 0xFF0000,
fields: [],
timestamp: log.date
});
message.setDescription(log.message);
message.fields.push({
name: "Message",
value: value.substring(0, 1024),
inline: false
});
continued = true;
await Discord.richQueue(message, /** @type {DiscordJs.TextChannel} */ (Discord.findChannelByName("otlbot-errors"))); // eslint-disable-line no-extra-parens
}
value = value.substring(1024);
}
value = `Error while writing to logging database: ${util.inspect(err)}`;
continued = false;
while (value.length > 0) {
if (continued) {
await Discord.queue(value.substring(0, 1024), /** @type {DiscordJs.TextChannel} */ (Discord.findChannelByName("otlbot-errors"))); // eslint-disable-line no-extra-parens
} else if (log.message) {
const message = Discord.messageEmbed({
color: 0xFF0000,
fields: [],
timestamp: log.date
});
message.setDescription(log.message);
message.fields.push({
name: "Message",
value: value.substring(0, 1024),
inline: false
});
continued = true;
await Discord.richQueue(message, /** @type {DiscordJs.TextChannel} */ (Discord.findChannelByName("otlbot-errors"))); // eslint-disable-line no-extra-parens
}
value = value.substring(1024);
}
} | static async outputToDiscord(log, err) {
let value = util.inspect(log.obj),
continued = false;
while (value.length > 0) {
if (continued) {
await Discord.queue(value.substring(0, 1024), /** @type {DiscordJs.TextChannel} */ (Discord.findChannelByName("otlbot-errors"))); // eslint-disable-line no-extra-parens
} else if (log.message) {
const message = Discord.messageEmbed({
color: 0xFF0000,
fields: [],
timestamp: log.date
});
message.setDescription(log.message);
message.fields.push({
name: "Message",
value: value.substring(0, 1024),
inline: false
});
continued = true;
await Discord.richQueue(message, /** @type {DiscordJs.TextChannel} */ (Discord.findChannelByName("otlbot-errors"))); // eslint-disable-line no-extra-parens
}
value = value.substring(1024);
}
value = `Error while writing to logging database: ${util.inspect(err)}`;
continued = false;
while (value.length > 0) {
if (continued) {
await Discord.queue(value.substring(0, 1024), /** @type {DiscordJs.TextChannel} */ (Discord.findChannelByName("otlbot-errors"))); // eslint-disable-line no-extra-parens
} else if (log.message) {
const message = Discord.messageEmbed({
color: 0xFF0000,
fields: [],
timestamp: log.date
});
message.setDescription(log.message);
message.fields.push({
name: "Message",
value: value.substring(0, 1024),
inline: false
});
continued = true;
await Discord.richQueue(message, /** @type {DiscordJs.TextChannel} */ (Discord.findChannelByName("otlbot-errors"))); // eslint-disable-line no-extra-parens
}
value = value.substring(1024);
}
} |
JavaScript | static get channels() {
if (otlGuild) {
return otlGuild.channels.cache;
}
return new DiscordJs.Collection();
} | static get channels() {
if (otlGuild) {
return otlGuild.channels.cache;
}
return new DiscordJs.Collection();
} |
JavaScript | static startup() {
discord.on("ready", () => {
Log.log("Connected to Discord.");
otlGuild = discord.guilds.cache.find((g) => g.name === settings.guild);
if (!readied) {
readied = true;
}
captainRole = otlGuild.roles.cache.find((r) => r.name === "Captain");
exemptRole = otlGuild.roles.cache.find((r) => r.name === "Cap Exempt");
founderRole = otlGuild.roles.cache.find((r) => r.name === "Founder");
testersRole = otlGuild.roles.cache.find((r) => r.name === "Testers");
alertsChannel = /** @type {DiscordJs.TextChannel} */ (otlGuild.channels.cache.find((c) => c.name === "otlbot-alerts")); // eslint-disable-line no-extra-parens
announcementsChannel = /** @type {DiscordJs.TextChannel} */ (otlGuild.channels.cache.find((c) => c.name === "announcements")); // eslint-disable-line no-extra-parens
matchResultsChannel = /** @type {DiscordJs.TextChannel} */ (otlGuild.channels.cache.find((c) => c.name === "match-results")); // eslint-disable-line no-extra-parens
rosterUpdatesChannel = /** @type {DiscordJs.TextChannel} */ (otlGuild.channels.cache.find((c) => c.name === "roster-updates")); // eslint-disable-line no-extra-parens
scheduledMatchesChannel = /** @type {DiscordJs.TextChannel} */ (otlGuild.channels.cache.find((c) => c.name === "scheduled-matches")); // eslint-disable-line no-extra-parens
vodsChannel = /** @type {DiscordJs.TextChannel} */ (otlGuild.channels.cache.find((c) => c.name === "vods")); // eslint-disable-line no-extra-parens
challengesCategory = /** @type {DiscordJs.CategoryChannel} */ (otlGuild.channels.cache.find((c) => c.name === "Challenges")); // eslint-disable-line no-extra-parens
Notify.setupNotifications();
});
discord.on("disconnect", (ev) => {
Log.exception("Disconnected from Discord.", ev);
});
discord.on("message", (message) => {
Discord.message(message.author, message.content, message.channel);
});
discord.on("guildMemberRemove", async (member) => {
if (member.guild && member.guild.id === otlGuild.id) {
try {
await member.leftDiscord();
} catch (err) {
Log.exception(`There was a problem with ${member.displayName} leaving the server.`, err);
}
}
});
discord.on("guildMemberUpdate", async (/** @type {DiscordJs.GuildMember} */ oldMember, newMember) => {
if (newMember.guild && newMember.guild.id === otlGuild.id) {
if (oldMember.displayName === newMember.displayName) {
return;
}
try {
await newMember.updateName(oldMember);
} catch (err) {
Log.exception(`There was a problem with ${oldMember.displayName} changing their name to ${newMember.displayName}.`, err);
}
}
});
discord.on("presenceUpdate", async (oldPresence, newPresence) => {
if (newPresence && newPresence.activities && newPresence.member && newPresence.guild && newPresence.guild.id === otlGuild.id) {
const activity = newPresence.activities.find((p) => p.name === "Twitch");
if (activity && urlParse.test(activity.url)) {
const {groups: {user}} = urlParse.exec(activity.url);
await newPresence.member.addTwitchName(user);
if (activity.state.toLowerCase() === "overload") {
await newPresence.member.setStreamer();
}
}
}
});
discord.on("error", (err) => {
if (err.message === "read ECONNRESET") {
// Swallow this error, see https://github.com/discordjs/discord.js/issues/3043#issuecomment-465543902
return;
}
Log.exception("Discord error.", err);
});
} | static startup() {
discord.on("ready", () => {
Log.log("Connected to Discord.");
otlGuild = discord.guilds.cache.find((g) => g.name === settings.guild);
if (!readied) {
readied = true;
}
captainRole = otlGuild.roles.cache.find((r) => r.name === "Captain");
exemptRole = otlGuild.roles.cache.find((r) => r.name === "Cap Exempt");
founderRole = otlGuild.roles.cache.find((r) => r.name === "Founder");
testersRole = otlGuild.roles.cache.find((r) => r.name === "Testers");
alertsChannel = /** @type {DiscordJs.TextChannel} */ (otlGuild.channels.cache.find((c) => c.name === "otlbot-alerts")); // eslint-disable-line no-extra-parens
announcementsChannel = /** @type {DiscordJs.TextChannel} */ (otlGuild.channels.cache.find((c) => c.name === "announcements")); // eslint-disable-line no-extra-parens
matchResultsChannel = /** @type {DiscordJs.TextChannel} */ (otlGuild.channels.cache.find((c) => c.name === "match-results")); // eslint-disable-line no-extra-parens
rosterUpdatesChannel = /** @type {DiscordJs.TextChannel} */ (otlGuild.channels.cache.find((c) => c.name === "roster-updates")); // eslint-disable-line no-extra-parens
scheduledMatchesChannel = /** @type {DiscordJs.TextChannel} */ (otlGuild.channels.cache.find((c) => c.name === "scheduled-matches")); // eslint-disable-line no-extra-parens
vodsChannel = /** @type {DiscordJs.TextChannel} */ (otlGuild.channels.cache.find((c) => c.name === "vods")); // eslint-disable-line no-extra-parens
challengesCategory = /** @type {DiscordJs.CategoryChannel} */ (otlGuild.channels.cache.find((c) => c.name === "Challenges")); // eslint-disable-line no-extra-parens
Notify.setupNotifications();
});
discord.on("disconnect", (ev) => {
Log.exception("Disconnected from Discord.", ev);
});
discord.on("message", (message) => {
Discord.message(message.author, message.content, message.channel);
});
discord.on("guildMemberRemove", async (member) => {
if (member.guild && member.guild.id === otlGuild.id) {
try {
await member.leftDiscord();
} catch (err) {
Log.exception(`There was a problem with ${member.displayName} leaving the server.`, err);
}
}
});
discord.on("guildMemberUpdate", async (/** @type {DiscordJs.GuildMember} */ oldMember, newMember) => {
if (newMember.guild && newMember.guild.id === otlGuild.id) {
if (oldMember.displayName === newMember.displayName) {
return;
}
try {
await newMember.updateName(oldMember);
} catch (err) {
Log.exception(`There was a problem with ${oldMember.displayName} changing their name to ${newMember.displayName}.`, err);
}
}
});
discord.on("presenceUpdate", async (oldPresence, newPresence) => {
if (newPresence && newPresence.activities && newPresence.member && newPresence.guild && newPresence.guild.id === otlGuild.id) {
const activity = newPresence.activities.find((p) => p.name === "Twitch");
if (activity && urlParse.test(activity.url)) {
const {groups: {user}} = urlParse.exec(activity.url);
await newPresence.member.addTwitchName(user);
if (activity.state.toLowerCase() === "overload") {
await newPresence.member.setStreamer();
}
}
}
});
discord.on("error", (err) => {
if (err.message === "read ECONNRESET") {
// Swallow this error, see https://github.com/discordjs/discord.js/issues/3043#issuecomment-465543902
return;
}
Log.exception("Discord error.", err);
});
} |
JavaScript | static async connect() {
Log.log("Connecting to Discord...");
try {
await discord.login(settings.discord.token);
Log.log("Connected.");
} catch (err) {
Log.exception("Error connecting to Discord, will automatically retry.", err);
}
} | static async connect() {
Log.log("Connecting to Discord...");
try {
await discord.login(settings.discord.token);
Log.log("Connected.");
} catch (err) {
Log.exception("Error connecting to Discord, will automatically retry.", err);
}
} |
JavaScript | static async queue(message, channel) {
if (channel.id === discord.user.id) {
return void 0;
}
let msg;
try {
msg = await Discord.richQueue(new DiscordJs.MessageEmbed({description: message}), channel);
} catch {}
return msg;
} | static async queue(message, channel) {
if (channel.id === discord.user.id) {
return void 0;
}
let msg;
try {
msg = await Discord.richQueue(new DiscordJs.MessageEmbed({description: message}), channel);
} catch {}
return msg;
} |
JavaScript | static async richEdit(message, embed) {
embed.setFooter(embed.footer ? embed.footer.text : "", Discord.icon);
if (embed && embed.fields) {
embed.fields.forEach((field) => {
if (field.value && field.value.length > 1024) {
field.value = field.value.substring(0, 1024);
}
});
}
embed.color = message.embeds[0].color;
if (!embed.timestamp) {
embed.setTimestamp(new Date());
}
await message.edit("", embed);
} | static async richEdit(message, embed) {
embed.setFooter(embed.footer ? embed.footer.text : "", Discord.icon);
if (embed && embed.fields) {
embed.fields.forEach((field) => {
if (field.value && field.value.length > 1024) {
field.value = field.value.substring(0, 1024);
}
});
}
embed.color = message.embeds[0].color;
if (!embed.timestamp) {
embed.setTimestamp(new Date());
}
await message.edit("", embed);
} |
JavaScript | static async richQueue(embed, channel) {
if (channel.id === discord.user.id) {
return void 0;
}
embed.setFooter(embed.footer ? embed.footer.text : "", Discord.icon);
if (embed && embed.fields) {
embed.fields.forEach((field) => {
if (field.value && field.value.length > 1024) {
field.value = field.value.substring(0, 1024);
}
});
}
if (!embed.color) {
embed.setColor(0xFF6600);
}
if (!embed.timestamp) {
embed.setTimestamp(new Date());
}
let msg;
try {
const msgSend = await channel.send("", embed);
if (msgSend instanceof Array) {
msg = msgSend[0];
} else {
msg = msgSend;
}
} catch {}
return msg;
} | static async richQueue(embed, channel) {
if (channel.id === discord.user.id) {
return void 0;
}
embed.setFooter(embed.footer ? embed.footer.text : "", Discord.icon);
if (embed && embed.fields) {
embed.fields.forEach((field) => {
if (field.value && field.value.length > 1024) {
field.value = field.value.substring(0, 1024);
}
});
}
if (!embed.color) {
embed.setColor(0xFF6600);
}
if (!embed.timestamp) {
embed.setTimestamp(new Date());
}
let msg;
try {
const msgSend = await channel.send("", embed);
if (msgSend instanceof Array) {
msg = msgSend[0];
} else {
msg = msgSend;
}
} catch {}
return msg;
} |
JavaScript | static createChannel(name, type, overwrites, reason) {
if (!otlGuild) {
return void 0;
}
return otlGuild.channels.create(name, {type, permissionOverwrites: overwrites, reason});
} | static createChannel(name, type, overwrites, reason) {
if (!otlGuild) {
return void 0;
}
return otlGuild.channels.create(name, {type, permissionOverwrites: overwrites, reason});
} |
JavaScript | static createRole(data, reason) {
if (!otlGuild) {
return void 0;
}
return otlGuild.roles.create({data, reason});
} | static createRole(data, reason) {
if (!otlGuild) {
return void 0;
}
return otlGuild.roles.create({data, reason});
} |
JavaScript | static findChannelById(id) {
if (!otlGuild) {
return void 0;
}
return otlGuild.channels.cache.find((c) => c.id === id);
} | static findChannelById(id) {
if (!otlGuild) {
return void 0;
}
return otlGuild.channels.cache.find((c) => c.id === id);
} |
JavaScript | static findChannelByName(name) {
if (!otlGuild) {
return void 0;
}
return otlGuild.channels.cache.find((c) => c.name === name);
} | static findChannelByName(name) {
if (!otlGuild) {
return void 0;
}
return otlGuild.channels.cache.find((c) => c.name === name);
} |
JavaScript | static findGuildMemberByDisplayName(displayName) {
if (!otlGuild) {
return void 0;
}
return otlGuild.members.cache.find((m) => m.displayName === displayName);
} | static findGuildMemberByDisplayName(displayName) {
if (!otlGuild) {
return void 0;
}
return otlGuild.members.cache.find((m) => m.displayName === displayName);
} |
JavaScript | static findGuildMemberById(id) {
if (!otlGuild) {
return void 0;
}
return otlGuild.members.cache.find((m) => m.id === id);
} | static findGuildMemberById(id) {
if (!otlGuild) {
return void 0;
}
return otlGuild.members.cache.find((m) => m.id === id);
} |
JavaScript | static async checkChallengeDetails(challenge, member, channel) {
try {
await challenge.loadDetails();
} catch (err) {
await Discord.queue(`Sorry, ${member}, but there was a server error. An admin will be notified about this.`, channel);
throw err;
}
} | static async checkChallengeDetails(challenge, member, channel) {
try {
await challenge.loadDetails();
} catch (err) {
await Discord.queue(`Sorry, ${member}, but there was a server error. An admin will be notified about this.`, channel);
throw err;
}
} |
JavaScript | static async checkChallengeIdExists(id, member, channel) {
let challenge;
try {
challenge = await Challenge.getById(id);
} catch (err) {
await Discord.queue(`Sorry, ${member}, but there was a server error. An admin will be notified about this.`, channel);
throw err;
}
if (!challenge) {
await Discord.queue(`Sorry, ${member}, but that was an invalid challenge ID.`, channel);
throw new Warning("Invalid challenge ID.");
}
return challenge;
} | static async checkChallengeIdExists(id, member, channel) {
let challenge;
try {
challenge = await Challenge.getById(id);
} catch (err) {
await Discord.queue(`Sorry, ${member}, but there was a server error. An admin will be notified about this.`, channel);
throw err;
}
if (!challenge) {
await Discord.queue(`Sorry, ${member}, but that was an invalid challenge ID.`, channel);
throw new Warning("Invalid challenge ID.");
}
return challenge;
} |
JavaScript | static async checkChallengeIsConfirmed(challenge, member, channel) {
if (!challenge.details.dateConfirmed) {
await Discord.queue(`Sorry, ${member}, but this match has not yet been confirmed.`, channel);
throw new Warning("Match was not confirmed.");
}
} | static async checkChallengeIsConfirmed(challenge, member, channel) {
if (!challenge.details.dateConfirmed) {
await Discord.queue(`Sorry, ${member}, but this match has not yet been confirmed.`, channel);
throw new Warning("Match was not confirmed.");
}
} |
JavaScript | static async checkChallengeIsNotConfirmed(challenge, member, channel) {
if (challenge.details.dateConfirmed) {
await Discord.queue(`Sorry, ${member}, but this match has already been confirmed.`, channel);
throw new Warning("Match was already confirmed.");
}
} | static async checkChallengeIsNotConfirmed(challenge, member, channel) {
if (challenge.details.dateConfirmed) {
await Discord.queue(`Sorry, ${member}, but this match has already been confirmed.`, channel);
throw new Warning("Match was already confirmed.");
}
} |
JavaScript | static async checkChallengeIsNotLocked(challenge, member, channel) {
if (challenge.details.adminCreated) {
await Discord.queue(`Sorry, ${member}, but this match is locked, and this command is not available.`, channel);
throw new Warning("Match is locked by admin.");
}
} | static async checkChallengeIsNotLocked(challenge, member, channel) {
if (challenge.details.adminCreated) {
await Discord.queue(`Sorry, ${member}, but this match is locked, and this command is not available.`, channel);
throw new Warning("Match is locked by admin.");
}
} |
JavaScript | static async checkChallengeIsNotPenalized(challenge, member, channel) {
if (challenge.details.challengingTeamPenalized || challenge.details.challengedTeamPenalized) {
await Discord.queue(`Sorry, ${member}, but due to penalties to ${challenge.details.challengingTeamPenalized && challenge.details.challengedTeamPenalized ? "both teams" : challenge.details.challengingTeamPenalized ? `**${challenge.challengingTeam.name}**` : `**${challenge.challengedTeam.name}**`}, this command is not available.`, channel);
throw new Warning("Penalties apply.");
}
} | static async checkChallengeIsNotPenalized(challenge, member, channel) {
if (challenge.details.challengingTeamPenalized || challenge.details.challengedTeamPenalized) {
await Discord.queue(`Sorry, ${member}, but due to penalties to ${challenge.details.challengingTeamPenalized && challenge.details.challengedTeamPenalized ? "both teams" : challenge.details.challengingTeamPenalized ? `**${challenge.challengingTeam.name}**` : `**${challenge.challengedTeam.name}**`}, this command is not available.`, channel);
throw new Warning("Penalties apply.");
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.