language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
loadFile(path) { // WEBREPL_FILE = "<2sBBQLH64s" let rec = new Uint8Array(2 + 1 + 1 + 8 + 4 + 2 + 64); rec[0] = 'W'.charCodeAt(0); rec[1] = 'A'.charCodeAt(0); rec[2] = 2; // get rec[3] = 0; rec[4] = 0; rec[5] = 0; rec[6] = 0; rec[7] = 0; rec[8] = 0; rec[9] = 0; rec[10] = 0; rec[11] = 0; rec[12] = 0; rec[13] = 0; rec[14] = 0; rec[15] = 0; rec[16] = path.length & 0xff; rec[17] = (path.length >> 8) & 0xff; for (let i = 0; i < 64; ++i) { if (i < path.length) { rec[18 + i] = path.charCodeAt(i); } else { rec[18 + i] = 0; } } // initiate get this.binaryState = 21; this.getFileName = path; this.getFileData = new Uint8Array(0); this.evaluate(rec); }
loadFile(path) { // WEBREPL_FILE = "<2sBBQLH64s" let rec = new Uint8Array(2 + 1 + 1 + 8 + 4 + 2 + 64); rec[0] = 'W'.charCodeAt(0); rec[1] = 'A'.charCodeAt(0); rec[2] = 2; // get rec[3] = 0; rec[4] = 0; rec[5] = 0; rec[6] = 0; rec[7] = 0; rec[8] = 0; rec[9] = 0; rec[10] = 0; rec[11] = 0; rec[12] = 0; rec[13] = 0; rec[14] = 0; rec[15] = 0; rec[16] = path.length & 0xff; rec[17] = (path.length >> 8) & 0xff; for (let i = 0; i < 64; ++i) { if (i < path.length) { rec[18 + i] = path.charCodeAt(i); } else { rec[18 + i] = 0; } } // initiate get this.binaryState = 21; this.getFileName = path; this.getFileData = new Uint8Array(0); this.evaluate(rec); }
JavaScript
removeFile(path) { const pCode = `from os import remove remove('${path}')` this.execute(pCode) }
removeFile(path) { const pCode = `from os import remove remove('${path}')` this.execute(pCode) }
JavaScript
function ImgObject(name, filePath) { this.name = name; this.filePath = filePath; this.timesShown = 0; this.votes = 0; ImgObject.allImages.push(this); imgNames.push(this.name); }
function ImgObject(name, filePath) { this.name = name; this.filePath = filePath; this.timesShown = 0; this.votes = 0; ImgObject.allImages.push(this); imgNames.push(this.name); }
JavaScript
function displayHighScores() { var storedImgObject = JSON.parse(localStorage.getItem('storedImgObject')); if (storedImgObject && storedImgObject.length) { var noHighScore = document.getElementById('noHighScore'); noHighScore.style.display = 'none'; var highScoreCards = document.getElementById('high-score-card'); highScoreCards.style.visibility = 'inherit'; sortedVotesArray.sort(function (a, b) { return b - a; }); for (var i = 0; i < 3; i++) { for (var j = 0; j < ImgObject.allImages.length; j++){ if (sortedVotesArray[i] === ImgObject.allImages[j].votes && ImgObject.allImages[j].name !== topVoteNames[i-1]){ topVoteNum[i] = ImgObject.allImages[j].votes; topVoteNames[i] = ImgObject.allImages[j].name; topVoteTimesShown[i] = ImgObject.allImages[j].timesShown; topVoteFilePath[i] = ImgObject.allImages[j].filePath; break; } } } for (i = 0; i < 3; i++){ var nameID = 'top-product-name' + (i + 1); var nameEl = document.getElementById(nameID); nameEl.innerHTML = topVoteNames[i]; var imgID = 'top-product-img' + (i + 1); var imgEl = document.getElementById(imgID); imgEl.src = topVoteFilePath[i]; imgEl.alt = topVoteNames[i]; var topProductChart = document.getElementById('top-product-chart' + (i +1)); var ctx = topProductChart.getContext('2d'); var myDoughnutChart = new Chart(ctx, { type: 'doughnut', data: { datasets: [{ data: [topVoteNum[i], topVoteTimesShown[i]], backgroundColor: [ '#EFF6E0', '#124559' ] }], labels: [ 'No. Times Voted', 'No. Times Shown' ] }, options: { legend: { labels: { fontColor: 'white' //set your desired color } } } }); } } else { var noHighScore = document.getElementById('noHighScore'); noHighScore.style.display = 'inherit'; highScoreCards = document.getElementById('high-score-card'); highScoreCards.style.visibility = 'hidden'; } }
function displayHighScores() { var storedImgObject = JSON.parse(localStorage.getItem('storedImgObject')); if (storedImgObject && storedImgObject.length) { var noHighScore = document.getElementById('noHighScore'); noHighScore.style.display = 'none'; var highScoreCards = document.getElementById('high-score-card'); highScoreCards.style.visibility = 'inherit'; sortedVotesArray.sort(function (a, b) { return b - a; }); for (var i = 0; i < 3; i++) { for (var j = 0; j < ImgObject.allImages.length; j++){ if (sortedVotesArray[i] === ImgObject.allImages[j].votes && ImgObject.allImages[j].name !== topVoteNames[i-1]){ topVoteNum[i] = ImgObject.allImages[j].votes; topVoteNames[i] = ImgObject.allImages[j].name; topVoteTimesShown[i] = ImgObject.allImages[j].timesShown; topVoteFilePath[i] = ImgObject.allImages[j].filePath; break; } } } for (i = 0; i < 3; i++){ var nameID = 'top-product-name' + (i + 1); var nameEl = document.getElementById(nameID); nameEl.innerHTML = topVoteNames[i]; var imgID = 'top-product-img' + (i + 1); var imgEl = document.getElementById(imgID); imgEl.src = topVoteFilePath[i]; imgEl.alt = topVoteNames[i]; var topProductChart = document.getElementById('top-product-chart' + (i +1)); var ctx = topProductChart.getContext('2d'); var myDoughnutChart = new Chart(ctx, { type: 'doughnut', data: { datasets: [{ data: [topVoteNum[i], topVoteTimesShown[i]], backgroundColor: [ '#EFF6E0', '#124559' ] }], labels: [ 'No. Times Voted', 'No. Times Shown' ] }, options: { legend: { labels: { fontColor: 'white' //set your desired color } } } }); } } else { var noHighScore = document.getElementById('noHighScore'); noHighScore.style.display = 'inherit'; highScoreCards = document.getElementById('high-score-card'); highScoreCards.style.visibility = 'hidden'; } }
JavaScript
function zoneDialog(){ $("#zone").dialog({ minWidth:800, width:'auto', colseOnEscape:true, modal: true, buttons: { 关闭: function() { $( this).dialog( "close" ); } } }); // update zone height to adapt content. $("#zone").css({ width: 'auto', minWidth:800, height: 'auto' }); }
function zoneDialog(){ $("#zone").dialog({ minWidth:800, width:'auto', colseOnEscape:true, modal: true, buttons: { 关闭: function() { $( this).dialog( "close" ); } } }); // update zone height to adapt content. $("#zone").css({ width: 'auto', minWidth:800, height: 'auto' }); }
JavaScript
function load(req, res, next, id) { Scanner.get(id) .then((user) => { req.user = user; // eslint-disable-line no-param-reassign return next(); }) .catch(e => next(e)); }
function load(req, res, next, id) { Scanner.get(id) .then((user) => { req.user = user; // eslint-disable-line no-param-reassign return next(); }) .catch(e => next(e)); }
JavaScript
function load(req, res, next, id) { Inspector.get(id) .then((user) => { req.user = user; // eslint-disable-line no-param-reassign return next(); }) .catch(e => next(e)); }
function load(req, res, next, id) { Inspector.get(id) .then((user) => { req.user = user; // eslint-disable-line no-param-reassign return next(); }) .catch(e => next(e)); }
JavaScript
static associate(models) { Message.belongsTo(models.Users, { foreignKey: 'senderId', }); Message.belongsTo(models.Users, { foreignKey: 'recieverId', }); }
static associate(models) { Message.belongsTo(models.Users, { foreignKey: 'senderId', }); Message.belongsTo(models.Users, { foreignKey: 'recieverId', }); }
JavaScript
static associate(models) { Users.hasMany(models.Message, { onDelete: 'CASCADE', foreignKey: 'senderId', }); Users.hasMany(models.Message, { onDelete: 'CASCADE', foreignKey: 'recieverId', }); }
static associate(models) { Users.hasMany(models.Message, { onDelete: 'CASCADE', foreignKey: 'senderId', }); Users.hasMany(models.Message, { onDelete: 'CASCADE', foreignKey: 'recieverId', }); }
JavaScript
function streamNull(data) { var urlChannel = data._links.channel + callback; $.getJSON(urlChannel, function(userData) { //console.log(userData); if(userData.status === 404){ streamError(userData); }else{ //console.log(userData); name = userData.display_name; // console.log(name); status = "Offline"; if (userData.logo === null) { logo = noLogo; } else { logo = userData.logo; } link = userData.url; $("#dataUl").prepend("<li class='offline'>" + "<div class='listBg'>" + "<img id='logoImg' src='" + logo + "' alt='Logo for account'>" + "<h3>" + name + "</h3>" + "<a href='" + link + "' target='_blank'>" + "<br>" + "<h4 class='status'>" + status + "</h4>" + "</div>" + "</a>" + "</li>"); } }); }
function streamNull(data) { var urlChannel = data._links.channel + callback; $.getJSON(urlChannel, function(userData) { //console.log(userData); if(userData.status === 404){ streamError(userData); }else{ //console.log(userData); name = userData.display_name; // console.log(name); status = "Offline"; if (userData.logo === null) { logo = noLogo; } else { logo = userData.logo; } link = userData.url; $("#dataUl").prepend("<li class='offline'>" + "<div class='listBg'>" + "<img id='logoImg' src='" + logo + "' alt='Logo for account'>" + "<h3>" + name + "</h3>" + "<a href='" + link + "' target='_blank'>" + "<br>" + "<h4 class='status'>" + status + "</h4>" + "</div>" + "</a>" + "</li>"); } }); }
JavaScript
function streamError(data) { logo = noLogo; name = data.message; name = name.replace("Channel '", ""); name = name.replace("' is unavailable", ""); name = name.replace("' does not exist", ""); status = "Account Closed"; $("#dataUl").prepend("<li class='closed'>" + "<div class='listBg'>" + "<img id='logoImg' src='" + logo + "' alt='Logo for account'>" + "<h3>" + name + "</h3>" + "<br>" + "<h4 class='status'>" + status + "</h4>" + "</div>" + "</li>"); }
function streamError(data) { logo = noLogo; name = data.message; name = name.replace("Channel '", ""); name = name.replace("' is unavailable", ""); name = name.replace("' does not exist", ""); status = "Account Closed"; $("#dataUl").prepend("<li class='closed'>" + "<div class='listBg'>" + "<img id='logoImg' src='" + logo + "' alt='Logo for account'>" + "<h3>" + name + "</h3>" + "<br>" + "<h4 class='status'>" + status + "</h4>" + "</div>" + "</li>"); }
JavaScript
function checkPlane(plane) { const viewPoint = math.matrix([0, 0, -10000, 1]); // Computing plane equation var equation = planeEquation(plane[0], plane[1], plane[2]); // Correcting equation var figureCenter = getCenterPoint(); if (math.multiply(equation, figureCenter) > 0) { equation = math.multiply(equation, -1) } // Apply projection equation = projectEquation(equation); // Visability checking if (math.multiply(viewPoint, equation) < 0) { return false; } return true; }
function checkPlane(plane) { const viewPoint = math.matrix([0, 0, -10000, 1]); // Computing plane equation var equation = planeEquation(plane[0], plane[1], plane[2]); // Correcting equation var figureCenter = getCenterPoint(); if (math.multiply(equation, figureCenter) > 0) { equation = math.multiply(equation, -1) } // Apply projection equation = projectEquation(equation); // Visability checking if (math.multiply(viewPoint, equation) < 0) { return false; } return true; }
JavaScript
function planeEquation(point, otherPoint, thirdPoint) { var a1 = getX(otherPoint) - getX(point); var b1 = getY(otherPoint) - getY(point) var c1 = getZ(otherPoint) - getZ(point) var a2 = getX(thirdPoint) - getX(point); var b2 = getY(thirdPoint) - getY(point); var c2 = getZ(thirdPoint) - getZ(point); var a = b1 * c2 - b2 * c1 ; var b = a2 * c1 - a1 * c2 ; var c = a1 * b2 - b1 * a2; var d = (-a * getX(point) - b * getY(point) - c * getZ(point)); return math.matrix([a, b, c, d]); }
function planeEquation(point, otherPoint, thirdPoint) { var a1 = getX(otherPoint) - getX(point); var b1 = getY(otherPoint) - getY(point) var c1 = getZ(otherPoint) - getZ(point) var a2 = getX(thirdPoint) - getX(point); var b2 = getY(thirdPoint) - getY(point); var c2 = getZ(thirdPoint) - getZ(point); var a = b1 * c2 - b2 * c1 ; var b = a2 * c1 - a1 * c2 ; var c = a1 * b2 - b1 * a2; var d = (-a * getX(point) - b * getY(point) - c * getZ(point)); return math.matrix([a, b, c, d]); }
JavaScript
uploadFileBuffer(fileName, fileBuffer, bucket, region) { // Check if maybe we`re not using the default region let s3Client = region ? _createS3ClientForNonDefaultRegion(region) : this.s3 const params = { Key: fileName, Body: fileBuffer, Bucket: bucket } return s3Client.putObject(params).promise() }
uploadFileBuffer(fileName, fileBuffer, bucket, region) { // Check if maybe we`re not using the default region let s3Client = region ? _createS3ClientForNonDefaultRegion(region) : this.s3 const params = { Key: fileName, Body: fileBuffer, Bucket: bucket } return s3Client.putObject(params).promise() }
JavaScript
function handleReversedCoordinates(){ if (complexScope.aLeftUpper > complexScope.aRightBottom) { complexScope.changer = complexScope.aLeftUpper; complexScope.aLeftUpper = complexScope.aRightBottom; complexScope.aRightBottom = complexScope.changer; // if you create the new area from right to left } if (complexScope.bLeftUpper < complexScope.bRightBottom) { complexScope.changer = complexScope.bLeftUpper; complexScope.bLeftUpper = complexScope.bRightBottom; complexScope.bRightBottom = complexScope.changer; // if you create the new area from right to left } }
function handleReversedCoordinates(){ if (complexScope.aLeftUpper > complexScope.aRightBottom) { complexScope.changer = complexScope.aLeftUpper; complexScope.aLeftUpper = complexScope.aRightBottom; complexScope.aRightBottom = complexScope.changer; // if you create the new area from right to left } if (complexScope.bLeftUpper < complexScope.bRightBottom) { complexScope.changer = complexScope.bLeftUpper; complexScope.bLeftUpper = complexScope.bRightBottom; complexScope.bRightBottom = complexScope.changer; // if you create the new area from right to left } }
JavaScript
editTask(id, name, description){ this.setState({ editTaskData: { id, name, description }, editTaskModal: !this.state.editTaskModal }) }
editTask(id, name, description){ this.setState({ editTaskData: { id, name, description }, editTaskModal: !this.state.editTaskModal }) }
JavaScript
deleteTask(id){ axios.delete('http://localhost:8000/api/task/'+id).then((response) => { this.loadTask() }) }
deleteTask(id){ axios.delete('http://localhost:8000/api/task/'+id).then((response) => { this.loadTask() }) }
JavaScript
toggleNewTaskModal(){ this.setState({ newTaskModal: !this.state.newTaskModal, }) }
toggleNewTaskModal(){ this.setState({ newTaskModal: !this.state.newTaskModal, }) }
JavaScript
function flipPlacement(placement) { const direction = (typeof window !== "undefined" && document.body.getAttribute("dir")) || "ltr"; if (direction !== "rtl") { return placement; } switch (placement) { case "bottom-end": return "bottom-start"; case "bottom-start": return "bottom-end"; case "top-end": return "top-start"; case "top-start": return "top-end"; default: return placement; } }
function flipPlacement(placement) { const direction = (typeof window !== "undefined" && document.body.getAttribute("dir")) || "ltr"; if (direction !== "rtl") { return placement; } switch (placement) { case "bottom-end": return "bottom-start"; case "bottom-start": return "bottom-end"; case "top-end": return "top-start"; case "top-start": return "top-end"; default: return placement; } }
JavaScript
async function createModulePackages({ from, to }) { const directoryPackages = glob .sync("*/index.js", { cwd: from }) .map(path.dirname); await Promise.all( directoryPackages.map(async directoryPackage => { const packageJson = { sideEffects: false, module: path.join("../es", directoryPackage, "index.js"), typings: "index.d.ts", }; const packageJsonPath = path.join(to, directoryPackage, "package.json"); const [typingsExist] = await Promise.all([ fse.exists(path.join(to, directoryPackage, "index.d.ts")), fse.writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2)), ]); if (!typingsExist) { throw new Error(`index.d.ts for ${directoryPackage} is missing`); } return packageJsonPath; }), ); }
async function createModulePackages({ from, to }) { const directoryPackages = glob .sync("*/index.js", { cwd: from }) .map(path.dirname); await Promise.all( directoryPackages.map(async directoryPackage => { const packageJson = { sideEffects: false, module: path.join("../es", directoryPackage, "index.js"), typings: "index.d.ts", }; const packageJsonPath = path.join(to, directoryPackage, "package.json"); const [typingsExist] = await Promise.all([ fse.exists(path.join(to, directoryPackage, "index.d.ts")), fse.writeFile(packageJsonPath, JSON.stringify(packageJson, null, 2)), ]); if (!typingsExist) { throw new Error(`index.d.ts for ${directoryPackage} is missing`); } return packageJsonPath; }), ); }
JavaScript
function returnList() { var userProfileSource = document.getElementById('user-profile-template').innerHTML, userProfileTemplate = Handlebars.compile(userProfileSource), userProfilePlaceholder = document.getElementById('user-profile'); var params = getHashParams(); var access_token = params.access_token, refresh_token = params.refresh_token, error = params.error; if(document.getElementById("number").value > 50) { alert("50 is the maximum amount of song that will be returned."); document.getElementById("number").value = 50; } else if(document.getElementById("number").value < 0) { alert("You must at least enter 1 as the number of songs to return ya dingus"); document.getElementById("number").value = 1; } if (error) { alert('There was an error during the authentication'); } else { if (access_token) { userProfilePlaceholder.innerHTML = userProfileTemplate(""); var time_range = document.getElementById("timeRange").value; var limit = document.getElementById("number").value; $.ajax({ url: 'https://api.spotify.com/v1/me/top/tracks?time_range=' + time_range + '&limit=' + limit, headers: { 'Authorization': 'Bearer ' + access_token }, success: function(response) { setSongList(response); //userProfilePlaceholder.innerHTML = userProfileTemplate(response); userProfilePlaceholder.innerHTML = userProfileTemplate(trackList); console.log(response); }, error: function(jqXHR, exception) { //if the access token is expired it ends up here. console.log("jqXHR: " + jqXHR.responseJSON); console.log("exception: " + exception); } }); } else { // render initial screen $('#login').show(); $('#loggedIn').hide(); } } }
function returnList() { var userProfileSource = document.getElementById('user-profile-template').innerHTML, userProfileTemplate = Handlebars.compile(userProfileSource), userProfilePlaceholder = document.getElementById('user-profile'); var params = getHashParams(); var access_token = params.access_token, refresh_token = params.refresh_token, error = params.error; if(document.getElementById("number").value > 50) { alert("50 is the maximum amount of song that will be returned."); document.getElementById("number").value = 50; } else if(document.getElementById("number").value < 0) { alert("You must at least enter 1 as the number of songs to return ya dingus"); document.getElementById("number").value = 1; } if (error) { alert('There was an error during the authentication'); } else { if (access_token) { userProfilePlaceholder.innerHTML = userProfileTemplate(""); var time_range = document.getElementById("timeRange").value; var limit = document.getElementById("number").value; $.ajax({ url: 'https://api.spotify.com/v1/me/top/tracks?time_range=' + time_range + '&limit=' + limit, headers: { 'Authorization': 'Bearer ' + access_token }, success: function(response) { setSongList(response); //userProfilePlaceholder.innerHTML = userProfileTemplate(response); userProfilePlaceholder.innerHTML = userProfileTemplate(trackList); console.log(response); }, error: function(jqXHR, exception) { //if the access token is expired it ends up here. console.log("jqXHR: " + jqXHR.responseJSON); console.log("exception: " + exception); } }); } else { // render initial screen $('#login').show(); $('#loggedIn').hide(); } } }
JavaScript
function populatePlaylist(playlist) { //declares song list var array = []; var songList = { uris: [] }; //sets the array inside the json object to the song's uris to be added to the playlist. for(var i = 0; i < trackList.length; i++) { if(trackList[i].addToPlaylist == true) { array.push(trackList[i].uri); } } songList.uris = array; var params = getHashParams(); var access_token = params.access_token, refresh_token = params.refresh_token, error = params.error; if(error) { alert("There was an error." + error); } else { $.ajax({ type: 'POST', url: 'https://api.spotify.com/v1/playlists/' + playlist.id + '/tracks', data: JSON.stringify(songList), dataType: 'json', headers: { 'Authorization': 'Bearer ' + access_token, 'Content-Type': 'application/json' }, success: function(response) { console.log("Playlist populated successfully"); }, error: function(jqXHR, exception) { console.log(jqXHR.responseJSON.error); } }); } }
function populatePlaylist(playlist) { //declares song list var array = []; var songList = { uris: [] }; //sets the array inside the json object to the song's uris to be added to the playlist. for(var i = 0; i < trackList.length; i++) { if(trackList[i].addToPlaylist == true) { array.push(trackList[i].uri); } } songList.uris = array; var params = getHashParams(); var access_token = params.access_token, refresh_token = params.refresh_token, error = params.error; if(error) { alert("There was an error." + error); } else { $.ajax({ type: 'POST', url: 'https://api.spotify.com/v1/playlists/' + playlist.id + '/tracks', data: JSON.stringify(songList), dataType: 'json', headers: { 'Authorization': 'Bearer ' + access_token, 'Content-Type': 'application/json' }, success: function(response) { console.log("Playlist populated successfully"); }, error: function(jqXHR, exception) { console.log(jqXHR.responseJSON.error); } }); } }
JavaScript
function copyDependency(moduleName) { return function(cb) { var srcModulePath = path.resolve(scope.sailsRoot, 'node_modules', moduleName); var destModulePath = path.resolve(scope.rootPath, 'node_modules',moduleName); // Use the "junction" option for Windows fs.symlink(srcModulePath, destModulePath, 'junction', cb); } }
function copyDependency(moduleName) { return function(cb) { var srcModulePath = path.resolve(scope.sailsRoot, 'node_modules', moduleName); var destModulePath = path.resolve(scope.rootPath, 'node_modules',moduleName); // Use the "junction" option for Windows fs.symlink(srcModulePath, destModulePath, 'junction', cb); } }
JavaScript
function countNeighbors(indexX, indexY) { // starts on x in row -1,-1 // xoo // oXo continue on x,y = 0 // ooo let num = 0; for (let x = -1; x < 2; x++) { for (let y = -1; y < 2; y++) { if (x === 0 && y === 0) { continue; } const column = (indexX + x + grid.length) % grid.length; const row = (indexY + y + grid[0].length) % grid[0].length; if ( column >= 0 && row >= 0 && column < grid.length && row < grid[0].length ) { const currentNeighbour = grid[column][row]; num += currentNeighbour; } } } return num; }
function countNeighbors(indexX, indexY) { // starts on x in row -1,-1 // xoo // oXo continue on x,y = 0 // ooo let num = 0; for (let x = -1; x < 2; x++) { for (let y = -1; y < 2; y++) { if (x === 0 && y === 0) { continue; } const column = (indexX + x + grid.length) % grid.length; const row = (indexY + y + grid[0].length) % grid[0].length; if ( column >= 0 && row >= 0 && column < grid.length && row < grid[0].length ) { const currentNeighbour = grid[column][row]; num += currentNeighbour; } } } return num; }
JavaScript
function embedColor(starcount, threshold) { // use a hue of 0.14 (yellow-gold) and a saturation 100% const h = 0.14; const s = 1; // ensure luminance will be between 0.8 and 0.5, and scale smoothly throughout. const scaledlum = (((((threshold / starcount) - 0.5) / 0.5) * 0.3) + 0.5); const l = Math.max(Math.min((scaledlum), 0.5), Math.min(Math.max((scaledlum), 0.5), 0.8)); function hue2rgb(p, q, t) { if(t < 0) t += 1; if(t > 1) t -= 1; if(t < 1 / 6) return p + (q - p) * 6 * t; if(t < 1 / 2) return q; if(t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; return p; } const q = l < 0.5 ? l * (1 + s) : l + s - l * s; const p = 2 * l - q; // convert to hex let r = Math.round(hue2rgb(p, q, h + 1 / 3) * 255).toString(16); let g = Math.round(hue2rgb(p, q, h) * 255).toString(16); let b = Math.round(hue2rgb(p, q, h - 1 / 3) * 255).toString(16); if (r.length < 2) { r = '0' + r; } if (g.length < 2) { g = '0' + g; } if (b.length < 2) { b = '0' + b; } return `#${r}${g}${b}`; }
function embedColor(starcount, threshold) { // use a hue of 0.14 (yellow-gold) and a saturation 100% const h = 0.14; const s = 1; // ensure luminance will be between 0.8 and 0.5, and scale smoothly throughout. const scaledlum = (((((threshold / starcount) - 0.5) / 0.5) * 0.3) + 0.5); const l = Math.max(Math.min((scaledlum), 0.5), Math.min(Math.max((scaledlum), 0.5), 0.8)); function hue2rgb(p, q, t) { if(t < 0) t += 1; if(t > 1) t -= 1; if(t < 1 / 6) return p + (q - p) * 6 * t; if(t < 1 / 2) return q; if(t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; return p; } const q = l < 0.5 ? l * (1 + s) : l + s - l * s; const p = 2 * l - q; // convert to hex let r = Math.round(hue2rgb(p, q, h + 1 / 3) * 255).toString(16); let g = Math.round(hue2rgb(p, q, h) * 255).toString(16); let b = Math.round(hue2rgb(p, q, h - 1 / 3) * 255).toString(16); if (r.length < 2) { r = '0' + r; } if (g.length < 2) { g = '0' + g; } if (b.length < 2) { b = '0' + b; } return `#${r}${g}${b}`; }
JavaScript
async function retrieveStarGivers(message, starboardMsg) { const PKData = await message.pkQuery(); const starreacts = await message.reactions.cache.get('⭐'); const usrArr = []; if (starreacts) { await starreacts.users.fetch(); starreacts.users.cache.forEach(user => { if (!usrArr.includes(user.id) // comment this line to enable self-starring. && user.id != message.author.id && (!PKData.author || user.id != PKData.author.id) ) usrArr.push(user.id); }); } if (starboardMsg && starboardMsg.reactions) { const starboardreacts = await starboardMsg.reactions.cache.get('⭐'); if (!starboardreacts) return usrArr; await starboardreacts.users.fetch(); starboardreacts.users.cache.forEach(user => { if (!usrArr.includes(user.id) // comment this line to enable self-starring. && user.id != message.author.id && (!PKData.author || user.id != PKData.author.id) ) usrArr.push(user.id); }); } return usrArr; }
async function retrieveStarGivers(message, starboardMsg) { const PKData = await message.pkQuery(); const starreacts = await message.reactions.cache.get('⭐'); const usrArr = []; if (starreacts) { await starreacts.users.fetch(); starreacts.users.cache.forEach(user => { if (!usrArr.includes(user.id) // comment this line to enable self-starring. && user.id != message.author.id && (!PKData.author || user.id != PKData.author.id) ) usrArr.push(user.id); }); } if (starboardMsg && starboardMsg.reactions) { const starboardreacts = await starboardMsg.reactions.cache.get('⭐'); if (!starboardreacts) return usrArr; await starboardreacts.users.fetch(); starboardreacts.users.cache.forEach(user => { if (!usrArr.includes(user.id) // comment this line to enable self-starring. && user.id != message.author.id && (!PKData.author || user.id != PKData.author.id) ) usrArr.push(user.id); }); } return usrArr; }
JavaScript
async function starsGivenUpdater(origMessage, usrArr, botdb) { let starsChanged = false; // retrieve all items from starboard_stars table associated with the given msg. returns array of objects in format { stargiver: userid }. const starArr = await botdb.all('SELECT stargiver FROM starboard_stars WHERE original_msg = ?', origMessage.id); for (const { stargiver } of starArr) { // for each item of this the array from the starboard_stars table, compare to usrArr... if (!usrArr.includes(stargiver)) { // if usrArr passed to this function does not contain a stargiver item, that must mean the user has removed their star. await botdb.run('DELETE FROM starboard_stars WHERE original_msg = ? AND stargiver = ?', origMessage.id, stargiver).then((result) => { if (result.changes > 0) starsChanged = true; }); } else { // else if usrarr DOES contain the item, discard it. usrArr.splice(usrArr.indexOf(stargiver), 1); } } if (usrArr.length > 0) { // remaining items in usrArr do not exist in starboard_stars table. attempt to insert into starboard_stars. for (const usr of usrArr) { await botdb.run('INSERT OR IGNORE INTO starboard_stars(original_msg, stargiver) VALUES(?, ?)', origMessage.id, usr).then((result) => { if (result.changes > 0) starsChanged = true; }); } } return starsChanged; }
async function starsGivenUpdater(origMessage, usrArr, botdb) { let starsChanged = false; // retrieve all items from starboard_stars table associated with the given msg. returns array of objects in format { stargiver: userid }. const starArr = await botdb.all('SELECT stargiver FROM starboard_stars WHERE original_msg = ?', origMessage.id); for (const { stargiver } of starArr) { // for each item of this the array from the starboard_stars table, compare to usrArr... if (!usrArr.includes(stargiver)) { // if usrArr passed to this function does not contain a stargiver item, that must mean the user has removed their star. await botdb.run('DELETE FROM starboard_stars WHERE original_msg = ? AND stargiver = ?', origMessage.id, stargiver).then((result) => { if (result.changes > 0) starsChanged = true; }); } else { // else if usrarr DOES contain the item, discard it. usrArr.splice(usrArr.indexOf(stargiver), 1); } } if (usrArr.length > 0) { // remaining items in usrArr do not exist in starboard_stars table. attempt to insert into starboard_stars. for (const usr of usrArr) { await botdb.run('INSERT OR IGNORE INTO starboard_stars(original_msg, stargiver) VALUES(?, ?)', origMessage.id, usr).then((result) => { if (result.changes > 0) starsChanged = true; }); } } return starsChanged; }
JavaScript
async function publicOnStar(message, botdb, force = false) { if (!config.starboardChannelId || !config.starboardToggle || config.starboardIgnoreChannels.includes(message.channel.id)) return; // initialize PK data for message. await message.pkQuery(); // check if user or message are on the blocklist if(await blockCheck(message, botdb)) return; const starboardChannel = await message.client.channels.fetch(config.starboardChannelId); let dbdata; // if the starred item was in the starboard, we look up the starboard entry for that message, then change 'message' to point to the original message instead of the starboard message. if (message.channel == starboardChannel) { dbdata = await queryByStarboard(message.id, botdb); try { message = await message.client.channels.fetch(dbdata.channel).then(channel => { return channel.messages.fetch(dbdata.original_msg); }); } catch (error) { // edge case where e.g. original has been deleted, but retained in the starboard. // this will eliminate the item from the starboard table and the starboard message will stop being updated. const messageRegEx = /(?:(?:https*:\/\/)*.*discord.*\/channels\/)\d+\/(\d+)\/(\d+)/; const urlfield = message.embeds[0].fields.find(field => { return field.name == 'Source'; }); const target = { chanID: messageRegEx.exec(urlfield.value)[1], msgID: messageRegEx.exec(urlfield.value)[2] }; await botdb.run('DELETE FROM starboard WHERE original_msg = ?', target.msgID); await botdb.run('DELETE FROM starboard_stars WHERE original_msg = ?', target.msgID); return; } } // ...otherwise we can just search by the original id else { dbdata = await queryByOriginal(message.id, botdb); } if (dbdata) { // item is already in star db; starboard message should exist. Skip policy-check and simply get starboard message. const starboardMsg = await starboardChannel.messages.fetch(dbdata.starboard_msg); // pass original message and starboard message to starcounter const usrArr = await retrieveStarGivers(message, starboardMsg); const starcount = usrArr.length; await starsGivenUpdater(message, usrArr, botdb); if (starcount >= dbdata.starthreshold) { // starcount is above the threshold from when it was starboarded and star count has changed. generate new embed and add data to db. const starboardEmbed = await generateEmbed(message, starcount, dbdata.starthreshold); const starboardEmoji = generateEmoji(starcount, dbdata.starthreshold); starboardMsg.edit(`${starboardEmoji} **${starcount}** ${message.channel}`, starboardEmbed); } else if (starcount < dbdata.starthreshold) { // item has dropped below its original threshold of star reacts. Delete from starboard and db. starboardMsg.delete(); await botdb.run('DELETE FROM starboard WHERE original_msg = ?', message.id); await botdb.run('DELETE FROM starboard_stars WHERE original_msg = ?', message.id); } } else if (!dbdata) { const usrArr = await retrieveStarGivers(message); const starcount = usrArr.length; let msgPolicy; if (force === true) { msgPolicy = true; } else { msgPolicy = await policyCheck(message, botdb); } // console.log('policy = ' + msgPolicy); // if item's policy is false or the item is not in db and has fewer stars than threshold, do nothing. if (!msgPolicy || (!dbdata && (starcount < config.starThreshold)) ) { return; } else if (starcount >= config.starThreshold && msgPolicy == true) { // item is new starboard candidate. generate embed and message const starboardEmbed = await generateEmbed(message, starcount, config.starThreshold); const starboardEmoji = generateEmoji(starcount, config.starThreshold); const starboardMsg = await starboardChannel.send(`${starboardEmoji} **${starcount}** ${message.channel}`, starboardEmbed); // update starboard_stars table and starboard table await starsGivenUpdater(message, usrArr, botdb); return await botdb.run('INSERT INTO starboard(original_msg,starboard_msg,channel,author,starthreshold) VALUES(?,?,?,?,?)', message.id, starboardMsg.id, message.channel.id, getAuthorAccount(message), config.starThreshold); } else if (starcount >= config.starThreshold && msgPolicy == 'ask') { // starboard_limbo - Columns: author channel original_msg dm_id // check if item is already in starboard limbo and a DM was sent. const inLimbo = await botdb.get('SELECT * FROM starboard_limbo WHERE original_msg = ?', message.id); if (!inLimbo) { const authorAccount = await message.client.users.fetch(getAuthorAccount(message)); const DM = await authorAccount.send(` "Hey! your post at ${message.url} got ${starcount} stars and is eligible for the starboard! Since it is in a private channel, I need your affirmation to put it on the starboard. React to this post with one of the following: - :white_check_mark: to **permit** this single post to go to the starboard. - :ok: to **permit** all of your posts in **#${message.channel.name}** to be starboarded indefinitely. - :cool: to **permit** all of your posts in *all* **private** channels on ${message.guild.name} to be starboarded indefinitely. - :x: to **block** all of your posts in **#${message.channel.name}** from being starboarded. - :no_entry: to **block** all of your posts in *all* **private** channels on ${message.guild.name} from being starboarded indefinitely. - :no_entry_sign: to **block** all your posts in **all** channels on ${message.guild.name} from the starboard. (your extant starboard posts will not be removed, but staff can remove them for you.) *This DM will not be repeated for this individual post. If you don't react, the post will not go to the starboard.* The .starboard command can be also be used in server to access these functionalities."`); // add DM data to limbo table. return await botdb.run('INSERT INTO starboard_limbo(author, channel, original_msg, dm_id) VALUES(?,?,?,?)', getAuthorAccount(message), message.channel.id, message.id, DM.id); } else { return; } } } }
async function publicOnStar(message, botdb, force = false) { if (!config.starboardChannelId || !config.starboardToggle || config.starboardIgnoreChannels.includes(message.channel.id)) return; // initialize PK data for message. await message.pkQuery(); // check if user or message are on the blocklist if(await blockCheck(message, botdb)) return; const starboardChannel = await message.client.channels.fetch(config.starboardChannelId); let dbdata; // if the starred item was in the starboard, we look up the starboard entry for that message, then change 'message' to point to the original message instead of the starboard message. if (message.channel == starboardChannel) { dbdata = await queryByStarboard(message.id, botdb); try { message = await message.client.channels.fetch(dbdata.channel).then(channel => { return channel.messages.fetch(dbdata.original_msg); }); } catch (error) { // edge case where e.g. original has been deleted, but retained in the starboard. // this will eliminate the item from the starboard table and the starboard message will stop being updated. const messageRegEx = /(?:(?:https*:\/\/)*.*discord.*\/channels\/)\d+\/(\d+)\/(\d+)/; const urlfield = message.embeds[0].fields.find(field => { return field.name == 'Source'; }); const target = { chanID: messageRegEx.exec(urlfield.value)[1], msgID: messageRegEx.exec(urlfield.value)[2] }; await botdb.run('DELETE FROM starboard WHERE original_msg = ?', target.msgID); await botdb.run('DELETE FROM starboard_stars WHERE original_msg = ?', target.msgID); return; } } // ...otherwise we can just search by the original id else { dbdata = await queryByOriginal(message.id, botdb); } if (dbdata) { // item is already in star db; starboard message should exist. Skip policy-check and simply get starboard message. const starboardMsg = await starboardChannel.messages.fetch(dbdata.starboard_msg); // pass original message and starboard message to starcounter const usrArr = await retrieveStarGivers(message, starboardMsg); const starcount = usrArr.length; await starsGivenUpdater(message, usrArr, botdb); if (starcount >= dbdata.starthreshold) { // starcount is above the threshold from when it was starboarded and star count has changed. generate new embed and add data to db. const starboardEmbed = await generateEmbed(message, starcount, dbdata.starthreshold); const starboardEmoji = generateEmoji(starcount, dbdata.starthreshold); starboardMsg.edit(`${starboardEmoji} **${starcount}** ${message.channel}`, starboardEmbed); } else if (starcount < dbdata.starthreshold) { // item has dropped below its original threshold of star reacts. Delete from starboard and db. starboardMsg.delete(); await botdb.run('DELETE FROM starboard WHERE original_msg = ?', message.id); await botdb.run('DELETE FROM starboard_stars WHERE original_msg = ?', message.id); } } else if (!dbdata) { const usrArr = await retrieveStarGivers(message); const starcount = usrArr.length; let msgPolicy; if (force === true) { msgPolicy = true; } else { msgPolicy = await policyCheck(message, botdb); } // console.log('policy = ' + msgPolicy); // if item's policy is false or the item is not in db and has fewer stars than threshold, do nothing. if (!msgPolicy || (!dbdata && (starcount < config.starThreshold)) ) { return; } else if (starcount >= config.starThreshold && msgPolicy == true) { // item is new starboard candidate. generate embed and message const starboardEmbed = await generateEmbed(message, starcount, config.starThreshold); const starboardEmoji = generateEmoji(starcount, config.starThreshold); const starboardMsg = await starboardChannel.send(`${starboardEmoji} **${starcount}** ${message.channel}`, starboardEmbed); // update starboard_stars table and starboard table await starsGivenUpdater(message, usrArr, botdb); return await botdb.run('INSERT INTO starboard(original_msg,starboard_msg,channel,author,starthreshold) VALUES(?,?,?,?,?)', message.id, starboardMsg.id, message.channel.id, getAuthorAccount(message), config.starThreshold); } else if (starcount >= config.starThreshold && msgPolicy == 'ask') { // starboard_limbo - Columns: author channel original_msg dm_id // check if item is already in starboard limbo and a DM was sent. const inLimbo = await botdb.get('SELECT * FROM starboard_limbo WHERE original_msg = ?', message.id); if (!inLimbo) { const authorAccount = await message.client.users.fetch(getAuthorAccount(message)); const DM = await authorAccount.send(` "Hey! your post at ${message.url} got ${starcount} stars and is eligible for the starboard! Since it is in a private channel, I need your affirmation to put it on the starboard. React to this post with one of the following: - :white_check_mark: to **permit** this single post to go to the starboard. - :ok: to **permit** all of your posts in **#${message.channel.name}** to be starboarded indefinitely. - :cool: to **permit** all of your posts in *all* **private** channels on ${message.guild.name} to be starboarded indefinitely. - :x: to **block** all of your posts in **#${message.channel.name}** from being starboarded. - :no_entry: to **block** all of your posts in *all* **private** channels on ${message.guild.name} from being starboarded indefinitely. - :no_entry_sign: to **block** all your posts in **all** channels on ${message.guild.name} from the starboard. (your extant starboard posts will not be removed, but staff can remove them for you.) *This DM will not be repeated for this individual post. If you don't react, the post will not go to the starboard.* The .starboard command can be also be used in server to access these functionalities."`); // add DM data to limbo table. return await botdb.run('INSERT INTO starboard_limbo(author, channel, original_msg, dm_id) VALUES(?,?,?,?)', getAuthorAccount(message), message.channel.id, message.id, DM.id); } else { return; } } } }
JavaScript
function writeConfig(message) { fs.writeFileSync(configPath, prettyPrintConfig(), function(err) { if (err) { if (message) { message.channel.send('There was an error saving the config file!'); } else { console.error('Error saving config!'); } return console.error(err); } }); }
function writeConfig(message) { fs.writeFileSync(configPath, prettyPrintConfig(), function(err) { if (err) { if (message) { message.channel.send('There was an error saving the config file!'); } else { console.error('Error saving config!'); } return console.error(err); } }); }
JavaScript
async function msgCollector(message) { // let responses = 0; let reply = false; // create a filter to ensure output is only accepted from the author who initiated the command. const filter = input => (input.author.id === message.author.id); await message.channel.awaitMessages(filter, { max: 1, time: 30000, errors: ['time'] }) // this method creates a collection; since there is only one entry we get the data from collected.first .then(collected => reply = collected.first()) .catch(() => message.channel.send('Sorry, I waited 30 seconds with no response, please run the command again.')); return reply; }
async function msgCollector(message) { // let responses = 0; let reply = false; // create a filter to ensure output is only accepted from the author who initiated the command. const filter = input => (input.author.id === message.author.id); await message.channel.awaitMessages(filter, { max: 1, time: 30000, errors: ['time'] }) // this method creates a collection; since there is only one entry we get the data from collected.first .then(collected => reply = collected.first()) .catch(() => message.channel.send('Sorry, I waited 30 seconds with no response, please run the command again.')); return reply; }
JavaScript
function prettyPrintConfig(cfg) { const output = JSON.stringify(cfg, function(k, v) { if (v instanceof Array) { return JSON.stringify(v); } return v; }, 2).replace(/\\/g, '') .replace(/"\[/g, '[') .replace(/\]"/g, ']') .replace(/"\{/g, '{') .replace(/\}"/g, '}'); return output; }
function prettyPrintConfig(cfg) { const output = JSON.stringify(cfg, function(k, v) { if (v instanceof Array) { return JSON.stringify(v); } return v; }, 2).replace(/\\/g, '') .replace(/"\[/g, '[') .replace(/\]"/g, ']') .replace(/"\{/g, '{') .replace(/\}"/g, '}'); return output; }
JavaScript
function writeConfig(cfg) { fs.writeFileSync(configPath, prettyPrintConfig(cfg), function(err) { if (err) { console.log('There was an error saving the config file!'); return console.log(err); } }); }
function writeConfig(cfg) { fs.writeFileSync(configPath, prettyPrintConfig(cfg), function(err) { if (err) { console.log('There was an error saving the config file!'); return console.log(err); } }); }
JavaScript
async pkQuery(force = false) { if (!this.author.bot) { this.PKData = { author: null, system: null, systemMember: null, }; return this.PKData; } if (!force && this.pkCached) return this.PKData; const pkAPIurl = 'https://api.pluralkit.me/v1/msg/' + this.id; try { let pkResponse = await fetch(pkAPIurl); if (pkResponse.headers.get('content-type').includes('application/json')) { this.isPKMessage = true; pkResponse = await pkResponse.json(); try { this.PKData.author = await this.guild.members.fetch(pkResponse.sender);} catch (err) { this.PKData.author = await this.client.users.fetch(pkResponse.sender);} this.PKData.system = pkResponse.system; this.PKData.systemMember = pkResponse.member; this.pkCached = true; return this.PKData; } } catch (err) { console.log('Error caching PK data on message at:\n' + this.url + '\nError:\n' + err + '\nPK Data for message not cached. Will try again next time pkQuery is called.'); return this.PKData ; } this.pkCached = true; return this.PKData = { author: null, system: null, systemMember: null, }; }
async pkQuery(force = false) { if (!this.author.bot) { this.PKData = { author: null, system: null, systemMember: null, }; return this.PKData; } if (!force && this.pkCached) return this.PKData; const pkAPIurl = 'https://api.pluralkit.me/v1/msg/' + this.id; try { let pkResponse = await fetch(pkAPIurl); if (pkResponse.headers.get('content-type').includes('application/json')) { this.isPKMessage = true; pkResponse = await pkResponse.json(); try { this.PKData.author = await this.guild.members.fetch(pkResponse.sender);} catch (err) { this.PKData.author = await this.client.users.fetch(pkResponse.sender);} this.PKData.system = pkResponse.system; this.PKData.systemMember = pkResponse.member; this.pkCached = true; return this.PKData; } } catch (err) { console.log('Error caching PK data on message at:\n' + this.url + '\nError:\n' + err + '\nPK Data for message not cached. Will try again next time pkQuery is called.'); return this.PKData ; } this.pkCached = true; return this.PKData = { author: null, system: null, systemMember: null, }; }
JavaScript
function rollDice(dice, sides) { const arr = []; for (let i = 0; i < dice; i++) { arr.push(Math.floor(Math.random() * sides + 1)); } // sort ascending arr.sort((a, b) => a - b); return arr; }
function rollDice(dice, sides) { const arr = []; for (let i = 0; i < dice; i++) { arr.push(Math.floor(Math.random() * sides + 1)); } // sort ascending arr.sort((a, b) => a - b); return arr; }
JavaScript
function convertToD(dice, sides, mod) { let convertedString = `${dice}d${sides}`; if (mod != 0) { if (mod > 0) {convertedString = `${convertedString}+${mod}`;} if (mod < 0) {convertedString = `${convertedString}${mod}`;} } return convertedString; }
function convertToD(dice, sides, mod) { let convertedString = `${dice}d${sides}`; if (mod != 0) { if (mod > 0) {convertedString = `${convertedString}+${mod}`;} if (mod < 0) {convertedString = `${convertedString}${mod}`;} } return convertedString; }
JavaScript
async function msgCollector(message) { let reply = false; // create a filter to ensure output is only accepted from the author who initiated the command. const filter = input => (input.author.id === message.author.id); await message.channel.awaitMessages(filter, { max: 1, time: 60000, errors: ['time'] }) // this method creates a collection; since there is only one entry we get the data from collected.first .then(collected => reply = collected.first()) .catch(collected => message.channel.send('Sorry, I waited 60 seconds with no response, please run the command again.')); return reply; }
async function msgCollector(message) { let reply = false; // create a filter to ensure output is only accepted from the author who initiated the command. const filter = input => (input.author.id === message.author.id); await message.channel.awaitMessages(filter, { max: 1, time: 60000, errors: ['time'] }) // this method creates a collection; since there is only one entry we get the data from collected.first .then(collected => reply = collected.first()) .catch(collected => message.channel.send('Sorry, I waited 60 seconds with no response, please run the command again.')); return reply; }
JavaScript
function writeData(filePath, file) { fs.writeFile(filePath, prettyPrintJson(file), function(err) { if (err) { return console.log(err); } }); }
function writeData(filePath, file) { fs.writeFile(filePath, prettyPrintJson(file), function(err) { if (err) { return console.log(err); } }); }
JavaScript
function formatDate(timestamp) { const messageDate = new Date(timestamp); const month = (messageDate.getMonth() + 1); const year = messageDate.getFullYear(); const dateString = year + '-' + ((month < 10) ? ('0' + month) : month); return dateString; }
function formatDate(timestamp) { const messageDate = new Date(timestamp); const month = (messageDate.getMonth() + 1); const year = messageDate.getFullYear(); const dateString = year + '-' + ((month < 10) ? ('0' + month) : month); return dateString; }
JavaScript
function monthPlusOne(dateString) { const dateArray = dateString.split('-'); let year = parseInt(dateArray[0]); let month = parseInt(dateArray[1]); if (month != 12) { month++; } else if (month == 12) { year++; month = 1; } const nextMonth = year + '-' + ((month < 10) ? ('0' + month) : month); return nextMonth; }
function monthPlusOne(dateString) { const dateArray = dateString.split('-'); let year = parseInt(dateArray[0]); let month = parseInt(dateArray[1]); if (month != 12) { month++; } else if (month == 12) { year++; month = 1; } const nextMonth = year + '-' + ((month < 10) ? ('0' + month) : month); return nextMonth; }
JavaScript
function prettyPrintJson() { const output = JSON.stringify(global.dataLog, function(k, v) { if (v instanceof Array) { return JSON.stringify(v); } return v; }, 2).replace(/\\/g, '') .replace(/"\[/g, '[') .replace(/\]"/g, ']') .replace(/"\{/g, '{') .replace(/\}"/g, '}'); return output; }
function prettyPrintJson() { const output = JSON.stringify(global.dataLog, function(k, v) { if (v instanceof Array) { return JSON.stringify(v); } return v; }, 2).replace(/\\/g, '') .replace(/"\[/g, '[') .replace(/\]"/g, ']') .replace(/"\{/g, '{') .replace(/\}"/g, '}'); return output; }
JavaScript
function writeData() { fs.writeFile(dataLogPath, prettyPrintJson(), function(err) { if (err) { return console.log(err); } }); }
function writeData() { fs.writeFile(dataLogPath, prettyPrintJson(), function(err) { if (err) { return console.log(err); } }); }
JavaScript
async function pruneDataMaintenance(client) { for (const gID of Object.keys(global.dataLog)) { const pruneData = new Map(global.dataLog[gID].pruneData); const g = await client.guilds.cache.get(gID); const currentGuildUsrs = await g.members.fetch().then(members => members.filter(member => !member.user.bot)); const usersToAdd = currentGuildUsrs.filter(user => !pruneData.has(user.user.id)); for (const user of usersToAdd) { pruneData.set(user[0], [0]); // console.log("adding " + user[0]); } if (global.dataLog[gID].pruneData) { const usersToRemove = global.dataLog[gID].pruneData.filter(user => !currentGuildUsrs.has(user[0])); for (const user of usersToRemove) { pruneData.delete(user[0]); // console.log("deleting " + user[0]); } } global.dataLog[gID].pruneData = [...pruneData]; writeData(); } }
async function pruneDataMaintenance(client) { for (const gID of Object.keys(global.dataLog)) { const pruneData = new Map(global.dataLog[gID].pruneData); const g = await client.guilds.cache.get(gID); const currentGuildUsrs = await g.members.fetch().then(members => members.filter(member => !member.user.bot)); const usersToAdd = currentGuildUsrs.filter(user => !pruneData.has(user.user.id)); for (const user of usersToAdd) { pruneData.set(user[0], [0]); // console.log("adding " + user[0]); } if (global.dataLog[gID].pruneData) { const usersToRemove = global.dataLog[gID].pruneData.filter(user => !currentGuildUsrs.has(user[0])); for (const user of usersToRemove) { pruneData.delete(user[0]); // console.log("deleting " + user[0]); } } global.dataLog[gID].pruneData = [...pruneData]; writeData(); } }
JavaScript
function capitalize(str) { return str.replace(/(?:^\w|\b\w)/g, function(ltr) { return ltr.toUpperCase(); }); }
function capitalize(str) { return str.replace(/(?:^\w|\b\w)/g, function(ltr) { return ltr.toUpperCase(); }); }
JavaScript
function writegameList() { fs.writeFile(listPath, JSON.stringify(gameList, null, 2), function(err) { if (err) { message.channel.send('There was an error saving your account information!'); return console.log(err); } }); }
function writegameList() { fs.writeFile(listPath, JSON.stringify(gameList, null, 2), function(err) { if (err) { message.channel.send('There was an error saving your account information!'); return console.log(err); } }); }
JavaScript
async tick() { const now = moment.utc(); const votesByGuild = Object.entries(this.ongoingVotes); for (const [guild, votes] of votesByGuild) { const endingVotes = votes.filter((vote) => vote.due.isSameOrBefore(now)); this.ongoingVotes[guild] = votes.filter((vote) => vote.due.isAfter(now), ); await this.saveState(); if (endingVotes.length > 0) { for (const vote of endingVotes) { /* const voteAge = moment.duration(now.diff(vote.due)); // Discard votes we missed for more than 5 minutes if (voteAge.asMinutes() >= 5) { break; } */ const destChannel = await this.client.channels.fetch(vote.channel); if (!destChannel) { console.log('Got vote for unknown channel', vote.channel); break; } console.log(vote); const totals = this.getResults(vote); let resultString = ''; totals.forEach((v, k) => resultString += `${k} : ${v}\n`); // send vote results to channel await destChannel.send(`In the matter of '${vote.summary}', the vote results are: \n ${resultString}`); } } } await this.saveState(); }
async tick() { const now = moment.utc(); const votesByGuild = Object.entries(this.ongoingVotes); for (const [guild, votes] of votesByGuild) { const endingVotes = votes.filter((vote) => vote.due.isSameOrBefore(now)); this.ongoingVotes[guild] = votes.filter((vote) => vote.due.isAfter(now), ); await this.saveState(); if (endingVotes.length > 0) { for (const vote of endingVotes) { /* const voteAge = moment.duration(now.diff(vote.due)); // Discard votes we missed for more than 5 minutes if (voteAge.asMinutes() >= 5) { break; } */ const destChannel = await this.client.channels.fetch(vote.channel); if (!destChannel) { console.log('Got vote for unknown channel', vote.channel); break; } console.log(vote); const totals = this.getResults(vote); let resultString = ''; totals.forEach((v, k) => resultString += `${k} : ${v}\n`); // send vote results to channel await destChannel.send(`In the matter of '${vote.summary}', the vote results are: \n ${resultString}`); } } } await this.saveState(); }
JavaScript
function onYearInput(event) { var year = event.target.value; if (event.delta) year = (parseInt(year) + event.delta).toString(); if (year.length === 4 || event.key === "Enter") { self.currentYearElement.blur(); if (!/[^\d]/.test(year)) changeYear(year); } }
function onYearInput(event) { var year = event.target.value; if (event.delta) year = (parseInt(year) + event.delta).toString(); if (year.length === 4 || event.key === "Enter") { self.currentYearElement.blur(); if (!/[^\d]/.test(year)) changeYear(year); } }
JavaScript
function bind(element, event, handler) { if (event instanceof Array) return event.forEach(function (ev) { return bind(element, ev, handler); }); if (element instanceof Array) return element.forEach(function (el) { return bind(el, event, handler); }); element.addEventListener(event, handler); self._handlers.push({ element: element, event: event, handler: handler }); }
function bind(element, event, handler) { if (event instanceof Array) return event.forEach(function (ev) { return bind(element, ev, handler); }); if (element instanceof Array) return element.forEach(function (el) { return bind(el, event, handler); }); element.addEventListener(event, handler); self._handlers.push({ element: element, event: event, handler: handler }); }
JavaScript
function onClick(handler) { return function (evt) { return evt.which === 1 && handler(evt); }; }
function onClick(handler) { return function (evt) { return evt.which === 1 && handler(evt); }; }
JavaScript
function bindEvents() { self._handlers = []; self._animationLoop = []; if (self.config.wrap) { ["open", "close", "toggle", "clear"].forEach(function (evt) { Array.prototype.forEach.call(self.element.querySelectorAll("[data-" + evt + "]"), function (el) { return bind(el, "mousedown", onClick(self[evt])); }); }); } if (self.isMobile) return setupMobile(); self.debouncedResize = debounce(onResize, 50); self.triggerChange = function () { triggerEvent("Change"); }; self.debouncedChange = debounce(self.triggerChange, 300); if (self.config.mode === "range" && self.daysContainer) bind(self.daysContainer, "mouseover", function (e) { return onMouseOver(e.target); }); bind(window.document.body, "keydown", onKeyDown); if (!self.config.static) bind(self._input, "keydown", onKeyDown); if (!self.config.inline && !self.config.static) bind(window, "resize", self.debouncedResize); if (window.ontouchstart !== undefined) bind(window.document, "touchstart", documentClick); bind(window.document, "mousedown", onClick(documentClick)); bind(self._input, "blur", documentClick); if (self.config.clickOpens === true) { bind(self._input, "focus", self.open); bind(self._input, "mousedown", onClick(self.open)); } if (!self.config.noCalendar) { self.monthNav.addEventListener("wheel", function (e) { return e.preventDefault(); }); bind(self.monthNav, "wheel", debounce(onMonthNavScroll, 10)); bind(self.monthNav, "mousedown", onClick(onMonthNavClick)); bind(self.monthNav, ["keyup", "increment"], onYearInput); bind(self.daysContainer, "mousedown", onClick(selectDate)); if (self.config.animate) { bind(self.daysContainer, ["webkitAnimationEnd", "animationend"], animateDays); bind(self.monthNav, ["webkitAnimationEnd", "animationend"], animateMonths); } } if (self.config.enableTime) { var selText = function selText(e) { return e.target.select(); }; bind(self.timeContainer, ["wheel", "input", "increment"], updateTime); bind(self.timeContainer, "mousedown", onClick(timeIncrement)); bind(self.timeContainer, ["wheel", "increment"], self.debouncedChange); bind(self.timeContainer, "input", self.triggerChange); bind([self.hourElement, self.minuteElement], "focus", selText); if (self.secondElement !== undefined) bind(self.secondElement, "focus", function () { return self.secondElement.select(); }); if (self.amPM !== undefined) { bind(self.amPM, "mousedown", onClick(function (e) { updateTime(e); self.triggerChange(e); })); } } }
function bindEvents() { self._handlers = []; self._animationLoop = []; if (self.config.wrap) { ["open", "close", "toggle", "clear"].forEach(function (evt) { Array.prototype.forEach.call(self.element.querySelectorAll("[data-" + evt + "]"), function (el) { return bind(el, "mousedown", onClick(self[evt])); }); }); } if (self.isMobile) return setupMobile(); self.debouncedResize = debounce(onResize, 50); self.triggerChange = function () { triggerEvent("Change"); }; self.debouncedChange = debounce(self.triggerChange, 300); if (self.config.mode === "range" && self.daysContainer) bind(self.daysContainer, "mouseover", function (e) { return onMouseOver(e.target); }); bind(window.document.body, "keydown", onKeyDown); if (!self.config.static) bind(self._input, "keydown", onKeyDown); if (!self.config.inline && !self.config.static) bind(window, "resize", self.debouncedResize); if (window.ontouchstart !== undefined) bind(window.document, "touchstart", documentClick); bind(window.document, "mousedown", onClick(documentClick)); bind(self._input, "blur", documentClick); if (self.config.clickOpens === true) { bind(self._input, "focus", self.open); bind(self._input, "mousedown", onClick(self.open)); } if (!self.config.noCalendar) { self.monthNav.addEventListener("wheel", function (e) { return e.preventDefault(); }); bind(self.monthNav, "wheel", debounce(onMonthNavScroll, 10)); bind(self.monthNav, "mousedown", onClick(onMonthNavClick)); bind(self.monthNav, ["keyup", "increment"], onYearInput); bind(self.daysContainer, "mousedown", onClick(selectDate)); if (self.config.animate) { bind(self.daysContainer, ["webkitAnimationEnd", "animationend"], animateDays); bind(self.monthNav, ["webkitAnimationEnd", "animationend"], animateMonths); } } if (self.config.enableTime) { var selText = function selText(e) { return e.target.select(); }; bind(self.timeContainer, ["wheel", "input", "increment"], updateTime); bind(self.timeContainer, "mousedown", onClick(timeIncrement)); bind(self.timeContainer, ["wheel", "increment"], self.debouncedChange); bind(self.timeContainer, "input", self.triggerChange); bind([self.hourElement, self.minuteElement], "focus", selText); if (self.secondElement !== undefined) bind(self.secondElement, "focus", function () { return self.secondElement.select(); }); if (self.amPM !== undefined) { bind(self.amPM, "mousedown", onClick(function (e) { updateTime(e); self.triggerChange(e); })); } } }
JavaScript
function animateDays(e) { if (self.daysContainer.childNodes.length > 1) { switch (e.animationName) { case "fpSlideLeft": self.daysContainer.lastChild.classList.remove("slideLeftNew"); self.daysContainer.removeChild(self.daysContainer.firstChild); self.days = self.daysContainer.firstChild; processPostDayAnimation(); break; case "fpSlideRight": self.daysContainer.firstChild.classList.remove("slideRightNew"); self.daysContainer.removeChild(self.daysContainer.lastChild); self.days = self.daysContainer.firstChild; processPostDayAnimation(); break; default: break; } } }
function animateDays(e) { if (self.daysContainer.childNodes.length > 1) { switch (e.animationName) { case "fpSlideLeft": self.daysContainer.lastChild.classList.remove("slideLeftNew"); self.daysContainer.removeChild(self.daysContainer.firstChild); self.days = self.daysContainer.firstChild; processPostDayAnimation(); break; case "fpSlideRight": self.daysContainer.firstChild.classList.remove("slideRightNew"); self.daysContainer.removeChild(self.daysContainer.lastChild); self.days = self.daysContainer.firstChild; processPostDayAnimation(); break; default: break; } } }
JavaScript
function animateMonths(e) { switch (e.animationName) { case "fpSlideLeftNew": case "fpSlideRightNew": self.navigationCurrentMonth.classList.remove("slideLeftNew"); self.navigationCurrentMonth.classList.remove("slideRightNew"); var nav = self.navigationCurrentMonth; while (nav.nextSibling && /curr/.test(nav.nextSibling.className)) { self.monthNav.removeChild(nav.nextSibling); }while (nav.previousSibling && /curr/.test(nav.previousSibling.className)) { self.monthNav.removeChild(nav.previousSibling); }self.oldCurMonth = null; break; } }
function animateMonths(e) { switch (e.animationName) { case "fpSlideLeftNew": case "fpSlideRightNew": self.navigationCurrentMonth.classList.remove("slideLeftNew"); self.navigationCurrentMonth.classList.remove("slideRightNew"); var nav = self.navigationCurrentMonth; while (nav.nextSibling && /curr/.test(nav.nextSibling.className)) { self.monthNav.removeChild(nav.nextSibling); }while (nav.previousSibling && /curr/.test(nav.previousSibling.className)) { self.monthNav.removeChild(nav.previousSibling); }self.oldCurMonth = null; break; } }
JavaScript
function jumpToDate(jumpDate) { jumpDate = jumpDate ? self.parseDate(jumpDate) : self.latestSelectedDateObj || (self.config.minDate > self.now ? self.config.minDate : self.config.maxDate && self.config.maxDate < self.now ? self.config.maxDate : self.now); try { self.currentYear = jumpDate.getFullYear(); self.currentMonth = jumpDate.getMonth(); } catch (e) { /* istanbul ignore next */ console.error(e.stack); /* istanbul ignore next */ console.warn("Invalid date supplied: " + jumpDate); } self.redraw(); }
function jumpToDate(jumpDate) { jumpDate = jumpDate ? self.parseDate(jumpDate) : self.latestSelectedDateObj || (self.config.minDate > self.now ? self.config.minDate : self.config.maxDate && self.config.maxDate < self.now ? self.config.maxDate : self.now); try { self.currentYear = jumpDate.getFullYear(); self.currentMonth = jumpDate.getMonth(); } catch (e) { /* istanbul ignore next */ console.error(e.stack); /* istanbul ignore next */ console.warn("Invalid date supplied: " + jumpDate); } self.redraw(); }
JavaScript
function updateValue(triggerChange) { if (!self.selectedDates.length) return self.clear(triggerChange); if (self.isMobile) { self.mobileInput.value = self.selectedDates.length ? self.formatDate(self.latestSelectedDateObj, self.mobileFormatStr) : ""; } var joinChar = self.config.mode !== "range" ? "; " : self.l10n.rangeSeparator; self.input.value = self.selectedDates.map(function (dObj) { return self.formatDate(dObj, self.config.dateFormat); }).join(joinChar); if (self.config.altInput) { self.altInput.value = self.selectedDates.map(function (dObj) { return self.formatDate(dObj, self.config.altFormat); }).join(joinChar); } if (triggerChange !== false) triggerEvent("ValueUpdate"); }
function updateValue(triggerChange) { if (!self.selectedDates.length) return self.clear(triggerChange); if (self.isMobile) { self.mobileInput.value = self.selectedDates.length ? self.formatDate(self.latestSelectedDateObj, self.mobileFormatStr) : ""; } var joinChar = self.config.mode !== "range" ? "; " : self.l10n.rangeSeparator; self.input.value = self.selectedDates.map(function (dObj) { return self.formatDate(dObj, self.config.dateFormat); }).join(joinChar); if (self.config.altInput) { self.altInput.value = self.selectedDates.map(function (dObj) { return self.formatDate(dObj, self.config.altFormat); }).join(joinChar); } if (triggerChange !== false) triggerEvent("ValueUpdate"); }
JavaScript
function createElement(tag, className, content) { var e = window.document.createElement(tag); className = className || ""; content = content || ""; e.className = className; if (content !== undefined) e.textContent = content; return e; }
function createElement(tag, className, content) { var e = window.document.createElement(tag); className = className || ""; content = content || ""; e.className = className; if (content !== undefined) e.textContent = content; return e; }
JavaScript
function formatDate(dateObj, frmt) { var _this = this; if (this.config !== undefined && this.config.formatDate !== undefined) return this.config.formatDate(dateObj, frmt); return frmt.split("").map(function (c, i, arr) { return _this.formats[c] && arr[i - 1] !== "\\" ? _this.formats[c](dateObj) : c !== "\\" ? c : ""; }).join(""); }
function formatDate(dateObj, frmt) { var _this = this; if (this.config !== undefined && this.config.formatDate !== undefined) return this.config.formatDate(dateObj, frmt); return frmt.split("").map(function (c, i, arr) { return _this.formats[c] && arr[i - 1] !== "\\" ? _this.formats[c](dateObj) : c !== "\\" ? c : ""; }).join(""); }
JavaScript
function occurrences(string, subString, allowOverlapping) { string += ""; subString += ""; if (subString.length <= 0) return (string.length + 1); var n = 0, pos = 0, step = allowOverlapping ? 1 : subString.length; while (true) { pos = string.indexOf(subString, pos); if (pos >= 0) { ++n; pos += step; } else break; } return n; }
function occurrences(string, subString, allowOverlapping) { string += ""; subString += ""; if (subString.length <= 0) return (string.length + 1); var n = 0, pos = 0, step = allowOverlapping ? 1 : subString.length; while (true) { pos = string.indexOf(subString, pos); if (pos >= 0) { ++n; pos += step; } else break; } return n; }
JavaScript
async function deleteEmployee(email) { const params = { TableName: tableName, Key: { 'email': { S: email } } }; const result = await new Promise((resolve, reject) => { client.deleteItem(params, (err, data) => { if(err) { console.error("Unable to delete employee from table. Error JSON: ", JSON.stringify(err, null, 2)); resolve(buildResult(false, '', 'Fail to delete employee')); } else { resolve(buildResult(true, {}, '')); } }); }); return result; }
async function deleteEmployee(email) { const params = { TableName: tableName, Key: { 'email': { S: email } } }; const result = await new Promise((resolve, reject) => { client.deleteItem(params, (err, data) => { if(err) { console.error("Unable to delete employee from table. Error JSON: ", JSON.stringify(err, null, 2)); resolve(buildResult(false, '', 'Fail to delete employee')); } else { resolve(buildResult(true, {}, '')); } }); }); return result; }
JavaScript
function userSelection() { inquirer .prompt({ type: 'list', name: 'userSelect', message: 'What would you like to do?', choices: [ 'Add Employee', 'View All Employees', 'Add Role', 'View All Roles', 'Add Department', 'View All Departments', 'Update Employee Role', 'Exit' ] }) .then((answer) => { switch (answer.userSelect) { case "Add Employee": addEmployee(); break; case "View All Employees": viewEmployee(); break; case "Add Role": addRole(); break; case "View All Roles": viewRole(); break; case "Add Department": addDepartment(); break; case "View All Departments": viewDepartment(); break; case "Update Employee Role": updateEmployee(); break; case "Update Employee Manager": updateManager(); break; case "Exit": connection.end(); } }); }
function userSelection() { inquirer .prompt({ type: 'list', name: 'userSelect', message: 'What would you like to do?', choices: [ 'Add Employee', 'View All Employees', 'Add Role', 'View All Roles', 'Add Department', 'View All Departments', 'Update Employee Role', 'Exit' ] }) .then((answer) => { switch (answer.userSelect) { case "Add Employee": addEmployee(); break; case "View All Employees": viewEmployee(); break; case "Add Role": addRole(); break; case "View All Roles": viewRole(); break; case "Add Department": addDepartment(); break; case "View All Departments": viewDepartment(); break; case "Update Employee Role": updateEmployee(); break; case "Update Employee Manager": updateManager(); break; case "Exit": connection.end(); } }); }
JavaScript
function useRemoteTheme(){ var userId = firebase.auth().currentUser.uid; return firebase.database().ref('/users/' + userId).once('value').then(function(snapshot) { var theme = snapshot.child("theme").val(); setLocalTheme(theme); }); }
function useRemoteTheme(){ var userId = firebase.auth().currentUser.uid; return firebase.database().ref('/users/' + userId).once('value').then(function(snapshot) { var theme = snapshot.child("theme").val(); setLocalTheme(theme); }); }
JavaScript
function TichuMovementService($http, $q, $log, $cacheFactory, TichuTournamentStore, TichuMovementStore) { /** * The HTTP request service injected at creation. * * @type {angular.$http} * @private */ this._$http = $http; /** * The Q promise service injected at creation. * * @type {angular.$q} * @private */ this._$q = $q; /** * The log service injected at creation. * * @private * @type {angular.$log} */ this._$log = $log; /** * The cache of Tournament-related objects. * * @type {TichuTournamentStore} * @private */ this._tournamentStore = TichuTournamentStore; /** * The cache of Movement instances. * * @type {angular.$cacheFactory.Cache} * @private */ this._movementStore = TichuMovementStore; /** * The cache of promises for Movement instances. * * @type {angular.$cacheFactory.Cache} * @private */ this._movementPromiseCache = $cacheFactory("MovementPromises"); }
function TichuMovementService($http, $q, $log, $cacheFactory, TichuTournamentStore, TichuMovementStore) { /** * The HTTP request service injected at creation. * * @type {angular.$http} * @private */ this._$http = $http; /** * The Q promise service injected at creation. * * @type {angular.$q} * @private */ this._$q = $q; /** * The log service injected at creation. * * @private * @type {angular.$log} */ this._$log = $log; /** * The cache of Tournament-related objects. * * @type {TichuTournamentStore} * @private */ this._tournamentStore = TichuTournamentStore; /** * The cache of Movement instances. * * @type {angular.$cacheFactory.Cache} * @private */ this._movementStore = TichuMovementStore; /** * The cache of promises for Movement instances. * * @type {angular.$cacheFactory.Cache} * @private */ this._movementPromiseCache = $cacheFactory("MovementPromises"); }
JavaScript
function TournamentListController($scope, $window, $route, $location, $mdDialog, loadResults) { $scope.appController.setPageHeader({ header: "Tournaments", backPath: "/home", showHeader: true }); /** * List of tournaments to be displayed to the user. * * @type {?tichu.TournamentHeader[]} * @export */ this.tournaments = loadResults.tournaments; /** * The details about the failure, if there was one. * * @type {?tichu.RpcError} */ this.failure = loadResults.failure; if (this.failure) { var redirectToLogin = this.failure.redirectToLogin; var dialog = $mdDialog.confirm() .title(this.failure.error) .textContent(this.failure.detail); if (redirectToLogin) { dialog = dialog .ok("Log me in") .cancel("Never mind"); } else { dialog = dialog .ok("Try again") .cancel("Never mind"); } $mdDialog.show(dialog).then(function() { if (redirectToLogin) { // use $window.location since we're going out of the Angular app $window.location.href = '/api/login?then=' + encodeURIComponent($location.url()) } else { $route.reload(); } }, function(autoHidden) { if (!autoHidden) { $location.url("/home"); } }); $scope.$on("$destroy", function() { $mdDialog.cancel(true); }); } }
function TournamentListController($scope, $window, $route, $location, $mdDialog, loadResults) { $scope.appController.setPageHeader({ header: "Tournaments", backPath: "/home", showHeader: true }); /** * List of tournaments to be displayed to the user. * * @type {?tichu.TournamentHeader[]} * @export */ this.tournaments = loadResults.tournaments; /** * The details about the failure, if there was one. * * @type {?tichu.RpcError} */ this.failure = loadResults.failure; if (this.failure) { var redirectToLogin = this.failure.redirectToLogin; var dialog = $mdDialog.confirm() .title(this.failure.error) .textContent(this.failure.detail); if (redirectToLogin) { dialog = dialog .ok("Log me in") .cancel("Never mind"); } else { dialog = dialog .ok("Try again") .cancel("Never mind"); } $mdDialog.show(dialog).then(function() { if (redirectToLogin) { // use $window.location since we're going out of the Angular app $window.location.href = '/api/login?then=' + encodeURIComponent($location.url()) } else { $route.reload(); } }, function(autoHidden) { if (!autoHidden) { $location.url("/home"); } }); $scope.$on("$destroy", function() { $mdDialog.cancel(true); }); } }
JavaScript
function mapRoute($routeProvider) { $routeProvider .when("/tournaments", { templateUrl: "src/tournaments/tournament-list.html", controller: "TournamentListController", controllerAs: "tournamentListController", resolve: { "loadResults": /** @ngInject */ function(TichuTournamentService) { return loadTournamentList(TichuTournamentService); } } }); }
function mapRoute($routeProvider) { $routeProvider .when("/tournaments", { templateUrl: "src/tournaments/tournament-list.html", controller: "TournamentListController", controllerAs: "tournamentListController", resolve: { "loadResults": /** @ngInject */ function(TichuTournamentService) { return loadTournamentList(TichuTournamentService); } } }); }
JavaScript
function TournamentStatusController($scope, TichuTournamentService, $mdDialog, $window, $location, $route, loadResults) { var backPath = "/tournaments" + (loadResults.id ? "/" + loadResults.id + "/view" : ""); $scope.appController.setPageHeader({ header: loadResults.failure ? "Tournament Error" : (loadResults.tournament ? "Editing " + loadResults.id : "Tournament Status"), backPath: backPath, showHeader: true }); /** * The tournament service injected at creation. * @type {TichuTournamentService} * @private */ this._tournamentService = TichuTournamentService; /** * The details about the failure, if there was one. * * @type {tichu.RpcError} */ this.failure = loadResults.failure; /** * The status of all hands in the tournament. * * @type {tichu.TournamentStatus} */ this.tournamentStatus = loadResults.tournamentStatus /** The location service injected at creation. */ this._$location = $location; /** The scope this controller exists in. */ this._$scope = $scope; /** * The dialog service injected at creation. * @type {$mdDialog} * @private */ this._$mdDialog = $mdDialog; if (this.failure) { var redirectToLogin = this.failure.redirectToLogin; var dialog = $mdDialog.confirm() .title(this.failure.error) .textContent(this.failure.detail); if (redirectToLogin) { dialog = dialog .ok("Log me in") .cancel("Never mind"); } else { dialog = dialog .ok("Try again") .cancel("Never mind"); } $mdDialog.show(dialog).then(function () { if (redirectToLogin) { // use $window.location since we're going out of the Angular app $window.location.href = '/api/login?then=' + encodeURIComponent($location.url()) } else { $route.reload(); } }, function (autoHidden) { if (!autoHidden) { $location.url(backPath); } }); $scope.$on("$destroy", function () { $mdDialog.cancel(true); }); } }
function TournamentStatusController($scope, TichuTournamentService, $mdDialog, $window, $location, $route, loadResults) { var backPath = "/tournaments" + (loadResults.id ? "/" + loadResults.id + "/view" : ""); $scope.appController.setPageHeader({ header: loadResults.failure ? "Tournament Error" : (loadResults.tournament ? "Editing " + loadResults.id : "Tournament Status"), backPath: backPath, showHeader: true }); /** * The tournament service injected at creation. * @type {TichuTournamentService} * @private */ this._tournamentService = TichuTournamentService; /** * The details about the failure, if there was one. * * @type {tichu.RpcError} */ this.failure = loadResults.failure; /** * The status of all hands in the tournament. * * @type {tichu.TournamentStatus} */ this.tournamentStatus = loadResults.tournamentStatus /** The location service injected at creation. */ this._$location = $location; /** The scope this controller exists in. */ this._$scope = $scope; /** * The dialog service injected at creation. * @type {$mdDialog} * @private */ this._$mdDialog = $mdDialog; if (this.failure) { var redirectToLogin = this.failure.redirectToLogin; var dialog = $mdDialog.confirm() .title(this.failure.error) .textContent(this.failure.detail); if (redirectToLogin) { dialog = dialog .ok("Log me in") .cancel("Never mind"); } else { dialog = dialog .ok("Try again") .cancel("Never mind"); } $mdDialog.show(dialog).then(function () { if (redirectToLogin) { // use $window.location since we're going out of the Angular app $window.location.href = '/api/login?then=' + encodeURIComponent($location.url()) } else { $route.reload(); } }, function (autoHidden) { if (!autoHidden) { $location.url(backPath); } }); $scope.$on("$destroy", function () { $mdDialog.cancel(true); }); } }
JavaScript
function mapRoute($routeProvider) { $routeProvider .when("/tournaments/:id/status", { templateUrl: "src/tournaments/tournament-status.html", controller: "TournamentStatusController", controllerAs: "tournamentStatusController", resolve: { "loadResults": /** @ngInject */ function($route, TichuTournamentService) { return loadTournamentStatus(TichuTournamentService, $route.current.params["id"]); } } }); }
function mapRoute($routeProvider) { $routeProvider .when("/tournaments/:id/status", { templateUrl: "src/tournaments/tournament-status.html", controller: "TournamentStatusController", controllerAs: "tournamentStatusController", resolve: { "loadResults": /** @ngInject */ function($route, TichuTournamentService) { return loadTournamentStatus(TichuTournamentService, $route.current.params["id"]); } } }); }
JavaScript
function ScoreDetailController($scope, $mdDialog, $location, $window, TichuMovementService, loadResults) { /** * The scope this controller is attached to. * @type {angular.Scope} * @private */ this._$scope = $scope; /** * Whether a pair code was used. * @type {?string} * @export */ this.pairCode = loadResults.pairCode; /** * The hand being displayed. * @type {!tichu.Hand} * @export */ this.hand = loadResults.hand; /** * The position to be displayed. * @type {tichu.PairPosition} * @export */ this.position = loadResults.position; /** * The tournament ID this dialog is editing a score from. * @type {string} * @private */ this._tournamentId = loadResults.tournamentId; /** * The current edited form of the score. * @type {{northSouthScore: string, eastWestScore: string, calls: Object.<tichu.Position, tichu.Call>, notes: string}} * @export */ this.score = convertScoreToEditable(this.hand.score); /** * Whether an existing score should be overwritten. * @type {boolean} * @export */ this.overwriting = false; /** * Whether the user has elected to delete the score instead. * @type {boolean} * @export */ this.deleting = false; /** * Whether a save or delete operation is in progress. * @type {boolean} * @export */ this.saving = false; /** * The error resulting from the last save or delete operation. * @type {?tichu.RpcError} * @export */ this.saveError = null; /** * The dialog service used to close the dialog. * @type {$mdDialog} * @private */ this._$mdDialog = $mdDialog; /** * The location service used to navigate if needed. * @type {$location} * @private */ this._$location = $location; /** * The window used to log in if needed. * @type {$window} * @private */ this._$window = $window; /** * The movement serice injected at creation. * @type {TichuMovementService} * @private */ this._movementService = TichuMovementService; }
function ScoreDetailController($scope, $mdDialog, $location, $window, TichuMovementService, loadResults) { /** * The scope this controller is attached to. * @type {angular.Scope} * @private */ this._$scope = $scope; /** * Whether a pair code was used. * @type {?string} * @export */ this.pairCode = loadResults.pairCode; /** * The hand being displayed. * @type {!tichu.Hand} * @export */ this.hand = loadResults.hand; /** * The position to be displayed. * @type {tichu.PairPosition} * @export */ this.position = loadResults.position; /** * The tournament ID this dialog is editing a score from. * @type {string} * @private */ this._tournamentId = loadResults.tournamentId; /** * The current edited form of the score. * @type {{northSouthScore: string, eastWestScore: string, calls: Object.<tichu.Position, tichu.Call>, notes: string}} * @export */ this.score = convertScoreToEditable(this.hand.score); /** * Whether an existing score should be overwritten. * @type {boolean} * @export */ this.overwriting = false; /** * Whether the user has elected to delete the score instead. * @type {boolean} * @export */ this.deleting = false; /** * Whether a save or delete operation is in progress. * @type {boolean} * @export */ this.saving = false; /** * The error resulting from the last save or delete operation. * @type {?tichu.RpcError} * @export */ this.saveError = null; /** * The dialog service used to close the dialog. * @type {$mdDialog} * @private */ this._$mdDialog = $mdDialog; /** * The location service used to navigate if needed. * @type {$location} * @private */ this._$location = $location; /** * The window used to log in if needed. * @type {$window} * @private */ this._$window = $window; /** * The movement serice injected at creation. * @type {TichuMovementService} * @private */ this._movementService = TichuMovementService; }
JavaScript
function TichuTournamentService($http, $log, $q, $cacheFactory, TichuTournamentStore) { /** * The HTTP request service injected at creation. * * @type {angular.$http} * @private */ this._$http = $http; /** * The log service injected at creation. * @type {angular.$log} * @private */ this._$log = $log; /** * The Q promise service injected at creation. * * @type {angular.$q} * @private */ this._$q = $q; /** * The current outstanding promise to return the tournament headers from the server. * * @type {angular.$q.Promise<tichu.TournamentHeader[]>} * @private */ this._tournamentListPromise = null; /** * The current outstanding promise(s) for loading tournaments. * * @type {angular.$cacheFactory.Cache} * @private */ this._tournamentPromises = $cacheFactory("TournamentPromises"); /** * The current outstanding promise(s) for loading tournament hand status. * * @type {angular.$cacheFactory.Cache} * @private */ this._tournamentStatusPromises = $cacheFactory("TournamentStatusPromises"); /** * The cache of tournament headers in the order they were received from the server. * * @type {tichu.TournamentHeader[]} * @private */ this._tournamentList = null; /** * The cache of Tournament-related objects. * * @type {TichuTournamentStore} * @private */ this._tournamentStore = TichuTournamentStore; }
function TichuTournamentService($http, $log, $q, $cacheFactory, TichuTournamentStore) { /** * The HTTP request service injected at creation. * * @type {angular.$http} * @private */ this._$http = $http; /** * The log service injected at creation. * @type {angular.$log} * @private */ this._$log = $log; /** * The Q promise service injected at creation. * * @type {angular.$q} * @private */ this._$q = $q; /** * The current outstanding promise to return the tournament headers from the server. * * @type {angular.$q.Promise<tichu.TournamentHeader[]>} * @private */ this._tournamentListPromise = null; /** * The current outstanding promise(s) for loading tournaments. * * @type {angular.$cacheFactory.Cache} * @private */ this._tournamentPromises = $cacheFactory("TournamentPromises"); /** * The current outstanding promise(s) for loading tournament hand status. * * @type {angular.$cacheFactory.Cache} * @private */ this._tournamentStatusPromises = $cacheFactory("TournamentStatusPromises"); /** * The cache of tournament headers in the order they were received from the server. * * @type {tichu.TournamentHeader[]} * @private */ this._tournamentList = null; /** * The cache of Tournament-related objects. * * @type {TichuTournamentStore} * @private */ this._tournamentStore = TichuTournamentStore; }
JavaScript
function searchWord(word){ const definition = document.getElementById("definition"); definition.innerHTML = "Definition"; // check for valid word let alphaCheck = /^[a-zA-Z]+$/.test(word); // check that word length is greater than 0 and only contains letters if (alphaCheck == true && word.length > 0){ // navigate to URL of merriam webster page for the given word inputted by the user const URL = `https://www.merriam-webster.com/dictionary/${word}`; var text = getSourceAsDOM(URL); return text; } }
function searchWord(word){ const definition = document.getElementById("definition"); definition.innerHTML = "Definition"; // check for valid word let alphaCheck = /^[a-zA-Z]+$/.test(word); // check that word length is greater than 0 and only contains letters if (alphaCheck == true && word.length > 0){ // navigate to URL of merriam webster page for the given word inputted by the user const URL = `https://www.merriam-webster.com/dictionary/${word}`; var text = getSourceAsDOM(URL); return text; } }
JavaScript
set value(newValue) { var options = this.options, i, index; for (i=0; i<options.length; i++) { if (options[i].value == newValue) { index = i; break; } } if (index !== undefined) { this.setAttribute('value', newValue); this.selectedIndex = index; } }
set value(newValue) { var options = this.options, i, index; for (i=0; i<options.length; i++) { if (options[i].value == newValue) { index = i; break; } } if (index !== undefined) { this.setAttribute('value', newValue); this.selectedIndex = index; } }
JavaScript
runSequence() { var args = []; if(arguments.length > 0) { args = _.toArray(arguments); } return CallbackHandler.runSequence(this._getFunctions(), args); }
runSequence() { var args = []; if(arguments.length > 0) { args = _.toArray(arguments); } return CallbackHandler.runSequence(this._getFunctions(), args); }
JavaScript
function web3AsynWrapper (web3Fun) { return function (arg) { return new Promise((resolve, reject) => { web3Fun(arg, (e, data) => e ? reject(e) : resolve(data)) }) } }
function web3AsynWrapper (web3Fun) { return function (arg) { return new Promise((resolve, reject) => { web3Fun(arg, (e, data) => e ? reject(e) : resolve(data)) }) } }
JavaScript
function transform(map, state) { const result = {}; _.forEach(map, (value, key) => { if (typeof value === 'function') { const transformation = value(key, _.get(state, key), state); if (transformation.targetKey && _.has(transformation, 'targetValue')) { _.set(result, transformation.targetKey, transformation.targetValue); } if (_.has(transformation, 'sourceValue')) { _.set(result, key, transformation.sourceValue); } } else { _.set(result, value, _.get(state, key)); } }); return _.merge({}, state, result); }
function transform(map, state) { const result = {}; _.forEach(map, (value, key) => { if (typeof value === 'function') { const transformation = value(key, _.get(state, key), state); if (transformation.targetKey && _.has(transformation, 'targetValue')) { _.set(result, transformation.targetKey, transformation.targetValue); } if (_.has(transformation, 'sourceValue')) { _.set(result, key, transformation.sourceValue); } } else { _.set(result, value, _.get(state, key)); } }); return _.merge({}, state, result); }
JavaScript
function insertAt (array, items, position) { for (var i = 0, l = items.length; i < l; i++) { array.splice(position + i, 0, items[i]); } }
function insertAt (array, items, position) { for (var i = 0, l = items.length; i < l; i++) { array.splice(position + i, 0, items[i]); } }
JavaScript
function matches (obj, props) { for (var prop in props) { if (has(props, prop) && (props[prop] !== obj[prop])) { return false; } } return true; }
function matches (obj, props) { for (var prop in props) { if (has(props, prop) && (props[prop] !== obj[prop])) { return false; } } return true; }
JavaScript
function findMarker (str, marker) { // Return early if the paragraph starts with the marker. if (startsWith(str, marker)) { return 0; } // Search for the marker following a soft break. var length = marker.length; var position = str.indexOf('\n' + marker, length + 1); return (position > length) ? position + 1 : -1; }
function findMarker (str, marker) { // Return early if the paragraph starts with the marker. if (startsWith(str, marker)) { return 0; } // Search for the marker following a soft break. var length = marker.length; var position = str.indexOf('\n' + marker, length + 1); return (position > length) ? position + 1 : -1; }
JavaScript
function rule (state) { var tokens = state.tokens; for (var i = 0, l = tokens.length; i < l; i++) { // Find the opening tag of the next blockquote. var start = findToken(tokens, { type: TokenType.BLOCKQUOTE_OPEN }, i); if (start === -1) { continue; } // Find the closing tag of the current block quote. var level = tokens[start].level; var end = findToken(tokens, { type: TokenType.BLOCKQUOTE_CLOSE, level: level }, start + 1); /* istanbul ignore if */ if (end === -1) { continue; } // Find the attribution line of the current block quote. var position = findAttribution(tokens, options.marker, level, start + 1, end); if (position === -1) { continue; } // Increase the level of each block quote token as it will be wrapped in a // container element. for (var j = start; j <= end; j++) { tokens[j].level++; } // Remove the attribution line from the rest of the paragraph. var token = tokens[position]; var source = token.content; var index = findMarker(source, options.marker); var content = (index > 0) ? trimEnd(source.slice(0, index)) : null; var attribution = (index > 0) ? source.slice(index) : source; token.content = content; // Remove the paragraph tokens from the stream, if no content is left. if (isEmpty(content)) { end -= remove(tokens, position - 1, position + 2); } // Use any url found in the attribution line as the cite attribute. var blockquoteOpen = tokens[start]; var url = extractUrl(attribution); if (!isEmpty(url)) { blockquoteOpen.attrSet('cite', url); } // Create new tokens for the attribution line. var captionOpen = new state.Token('blockquote_attribution_open', 'figcaption', 1); captionOpen.block = true; captionOpen.level = level + 1; var caption = new state.Token('inline', '', 0); caption.children = []; caption.level = level + 2; caption.content = options.removeMarker ? trimStart(attribution.slice(options.marker.length)) : attribution; var captionClose = new state.Token('blockquote_attribution_close', 'figcaption', -1); captionClose.block = true; captionClose.level = level + 1; if (!isEmpty(options.classNameAttribution)) { captionOpen.attrSet('class', options.classNameAttribution); } insertAt(tokens, [captionOpen, caption, captionClose], end + 1); // Wrap block quote and attribution in a figure element. var figureOpen = new state.Token('blockquote_container_open', 'figure', 1); figureOpen.block = true; figureOpen.level = level; var figureClose = new state.Token('blockquote_container_close', 'figure', -1); figureClose.block = true; figureClose.level = level; if (!isEmpty(options.classNameContainer)) { figureOpen.attrSet('class', options.classNameContainer); } insertAt(tokens, [figureClose], end + 4); insertAt(tokens, [figureOpen], start); // Skip the generated block quote tokens in the stream. i = end + 5; // Update the length of the token stream. l = l + 4; } }
function rule (state) { var tokens = state.tokens; for (var i = 0, l = tokens.length; i < l; i++) { // Find the opening tag of the next blockquote. var start = findToken(tokens, { type: TokenType.BLOCKQUOTE_OPEN }, i); if (start === -1) { continue; } // Find the closing tag of the current block quote. var level = tokens[start].level; var end = findToken(tokens, { type: TokenType.BLOCKQUOTE_CLOSE, level: level }, start + 1); /* istanbul ignore if */ if (end === -1) { continue; } // Find the attribution line of the current block quote. var position = findAttribution(tokens, options.marker, level, start + 1, end); if (position === -1) { continue; } // Increase the level of each block quote token as it will be wrapped in a // container element. for (var j = start; j <= end; j++) { tokens[j].level++; } // Remove the attribution line from the rest of the paragraph. var token = tokens[position]; var source = token.content; var index = findMarker(source, options.marker); var content = (index > 0) ? trimEnd(source.slice(0, index)) : null; var attribution = (index > 0) ? source.slice(index) : source; token.content = content; // Remove the paragraph tokens from the stream, if no content is left. if (isEmpty(content)) { end -= remove(tokens, position - 1, position + 2); } // Use any url found in the attribution line as the cite attribute. var blockquoteOpen = tokens[start]; var url = extractUrl(attribution); if (!isEmpty(url)) { blockquoteOpen.attrSet('cite', url); } // Create new tokens for the attribution line. var captionOpen = new state.Token('blockquote_attribution_open', 'figcaption', 1); captionOpen.block = true; captionOpen.level = level + 1; var caption = new state.Token('inline', '', 0); caption.children = []; caption.level = level + 2; caption.content = options.removeMarker ? trimStart(attribution.slice(options.marker.length)) : attribution; var captionClose = new state.Token('blockquote_attribution_close', 'figcaption', -1); captionClose.block = true; captionClose.level = level + 1; if (!isEmpty(options.classNameAttribution)) { captionOpen.attrSet('class', options.classNameAttribution); } insertAt(tokens, [captionOpen, caption, captionClose], end + 1); // Wrap block quote and attribution in a figure element. var figureOpen = new state.Token('blockquote_container_open', 'figure', 1); figureOpen.block = true; figureOpen.level = level; var figureClose = new state.Token('blockquote_container_close', 'figure', -1); figureClose.block = true; figureClose.level = level; if (!isEmpty(options.classNameContainer)) { figureOpen.attrSet('class', options.classNameContainer); } insertAt(tokens, [figureClose], end + 4); insertAt(tokens, [figureOpen], start); // Skip the generated block quote tokens in the stream. i = end + 5; // Update the length of the token stream. l = l + 4; } }
JavaScript
function takeFirst(pattern, saga, ...args) { // eslint-disable-next-line func-names return fork(function*() { while (true) { const action = yield take(pattern); yield call(saga, ...args.concat(action)); } }); }
function takeFirst(pattern, saga, ...args) { // eslint-disable-next-line func-names return fork(function*() { while (true) { const action = yield take(pattern); yield call(saga, ...args.concat(action)); } }); }
JavaScript
function $D2nT$var$applyStyles(_ref) { var state = _ref.state; Object.keys(state.elements).forEach(function (name) { var style = state.styles[name] || {}; var attributes = state.attributes[name] || {}; var element = state.elements[name]; // arrow is optional + virtual elements if (!$wsKO$export$isHTMLElement(element) || !$B1zX$export$default(element)) { return; } // Flow doesn't support to extend this property, but it's the most // effective way to apply styles to an HTMLElement // $FlowFixMe[cannot-write] Object.assign(element.style, style); Object.keys(attributes).forEach(function (name) { var value = attributes[name]; if (value === false) { element.removeAttribute(name); } else { element.setAttribute(name, value === true ? '' : value); } }); }); }
function $D2nT$var$applyStyles(_ref) { var state = _ref.state; Object.keys(state.elements).forEach(function (name) { var style = state.styles[name] || {}; var attributes = state.attributes[name] || {}; var element = state.elements[name]; // arrow is optional + virtual elements if (!$wsKO$export$isHTMLElement(element) || !$B1zX$export$default(element)) { return; } // Flow doesn't support to extend this property, but it's the most // effective way to apply styles to an HTMLElement // $FlowFixMe[cannot-write] Object.assign(element.style, style); Object.keys(attributes).forEach(function (name) { var value = attributes[name]; if (value === false) { element.removeAttribute(name); } else { element.setAttribute(name, value === true ? '' : value); } }); }); }
JavaScript
function $CUhI$export$default(element) { var window = $QiNa$export$default(element); var offsetParent = $CUhI$var$getTrueOffsetParent(element); while (offsetParent && $rK11$export$default(offsetParent) && $S6rb$export$default(offsetParent).position === 'static') { offsetParent = $CUhI$var$getTrueOffsetParent(offsetParent); } if (offsetParent && ($B1zX$export$default(offsetParent) === 'html' || $B1zX$export$default(offsetParent) === 'body' && $S6rb$export$default(offsetParent).position === 'static')) { return window; } return offsetParent || $CUhI$var$getContainingBlock(element) || window; }
function $CUhI$export$default(element) { var window = $QiNa$export$default(element); var offsetParent = $CUhI$var$getTrueOffsetParent(element); while (offsetParent && $rK11$export$default(offsetParent) && $S6rb$export$default(offsetParent).position === 'static') { offsetParent = $CUhI$var$getTrueOffsetParent(offsetParent); } if (offsetParent && ($B1zX$export$default(offsetParent) === 'html' || $B1zX$export$default(offsetParent) === 'body' && $S6rb$export$default(offsetParent).position === 'static')) { return window; } return offsetParent || $CUhI$var$getContainingBlock(element) || window; }
JavaScript
function $yEje$export$default(element) { var _element$ownerDocumen; var html = $sJcE$export$default(element); var winScroll = $oJ75$export$default(element); var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body; var width = $FuL6$export$max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0); var height = $FuL6$export$max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0); var x = -winScroll.scrollLeft + $zwcJ$export$default(element); var y = -winScroll.scrollTop; if ($S6rb$export$default(body || html).direction === 'rtl') { x += $FuL6$export$max(html.clientWidth, body ? body.clientWidth : 0) - width; } return { width: width, height: height, x: x, y: y }; }
function $yEje$export$default(element) { var _element$ownerDocumen; var html = $sJcE$export$default(element); var winScroll = $oJ75$export$default(element); var body = (_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body; var width = $FuL6$export$max(html.scrollWidth, html.clientWidth, body ? body.scrollWidth : 0, body ? body.clientWidth : 0); var height = $FuL6$export$max(html.scrollHeight, html.clientHeight, body ? body.scrollHeight : 0, body ? body.clientHeight : 0); var x = -winScroll.scrollLeft + $zwcJ$export$default(element); var y = -winScroll.scrollTop; if ($S6rb$export$default(body || html).direction === 'rtl') { x += $FuL6$export$max(html.clientWidth, body ? body.clientWidth : 0) - width; } return { width: width, height: height, x: x, y: y }; }
JavaScript
function $m3DJ$export$default(element, list) { var _element$ownerDocumen; if (list === void 0) { list = []; } var scrollParent = $Qnrt$export$default(element); var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body); var win = $QiNa$export$default(scrollParent); var target = isBody ? [win].concat(win.visualViewport || [], $j3Hf$export$default(scrollParent) ? scrollParent : []) : scrollParent; var updatedList = list.concat(target); return isBody ? updatedList : // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here updatedList.concat($m3DJ$export$default($IVKl$export$default(target))); }
function $m3DJ$export$default(element, list) { var _element$ownerDocumen; if (list === void 0) { list = []; } var scrollParent = $Qnrt$export$default(element); var isBody = scrollParent === ((_element$ownerDocumen = element.ownerDocument) == null ? void 0 : _element$ownerDocumen.body); var win = $QiNa$export$default(scrollParent); var target = isBody ? [win].concat(win.visualViewport || [], $j3Hf$export$default(scrollParent) ? scrollParent : []) : scrollParent; var updatedList = list.concat(target); return isBody ? updatedList : // $FlowFixMe[incompatible-call]: isBody tells us target will be an HTMLElement here updatedList.concat($m3DJ$export$default($IVKl$export$default(target))); }
JavaScript
function expandPartials(parsed, root, ext, callback) { process.nextTick(function () { var partials = getPartials(parsed); if (!partials.length) { return callback(undefined, parsed); } var actions = partials.map(function (partial) { return function (callback) { Mu.Parser.parse(partial, root, ext, callback); }; }); parallel(actions, function (results) { var partials = {}; // result.result[0] => the parsed partial // result.result[1] => the filename of the partial results.forEach(function (result) { if (result.type === 'success') { partials[result.result[1]] = result.result[0]; } }); callback(undefined, expandPartialsFromMap(parsed, partials)); }); }); }
function expandPartials(parsed, root, ext, callback) { process.nextTick(function () { var partials = getPartials(parsed); if (!partials.length) { return callback(undefined, parsed); } var actions = partials.map(function (partial) { return function (callback) { Mu.Parser.parse(partial, root, ext, callback); }; }); parallel(actions, function (results) { var partials = {}; // result.result[0] => the parsed partial // result.result[1] => the filename of the partial results.forEach(function (result) { if (result.type === 'success') { partials[result.result[1]] = result.result[0]; } }); callback(undefined, expandPartialsFromMap(parsed, partials)); }); }); }
JavaScript
function expandPartialsFromMap(parsed, partials) { return parsed.map(function (line) { var number = line.number; var source = line.source; var filename = line.filename; var tokens = line.tokens; tokens = tokens.map(function (token) { return token.type === 'partial' ? {type: 'partial', value: partials[token.value] || []} : token; }); return { number: number, source: source, filename: filename, tokens: tokens }; }); }
function expandPartialsFromMap(parsed, partials) { return parsed.map(function (line) { var number = line.number; var source = line.source; var filename = line.filename; var tokens = line.tokens; tokens = tokens.map(function (token) { return token.type === 'partial' ? {type: 'partial', value: partials[token.value] || []} : token; }); return { number: number, source: source, filename: filename, tokens: tokens }; }); }
JavaScript
function clean(parsed) { return parsed.map(function (line) { var number = line.number; var source = line.source; var filename = line.filename; var tokens = line.tokens; return { number: number, source: source, filename: filename, tokens: tokens.map(function (token, i) { // Removes the whitespace and the newline if the only thing on this line // is whitespace and a non variable tag. if (tokens.length === 2 && i === 0 && token.type === 'string' && token.value.trim() === '\\n' && tokens[1].type !== 'variable' && tokens[1].type !== 'unescaped' && tokens[1].type !== 'partial') { return null; } // Recursively clean partials if (token.type === 'partial') { return {type: 'partial', value: clean(token.value)}; } // removes useless empty strings if (token.type === 'string' && token.value === '') { return null; } // escape quotes if (token.type === 'string') { return {type: 'string', value: token.value.replace(/"/g, "\\\"")}; } return token; }).filter(filterFalsy) }; }); }
function clean(parsed) { return parsed.map(function (line) { var number = line.number; var source = line.source; var filename = line.filename; var tokens = line.tokens; return { number: number, source: source, filename: filename, tokens: tokens.map(function (token, i) { // Removes the whitespace and the newline if the only thing on this line // is whitespace and a non variable tag. if (tokens.length === 2 && i === 0 && token.type === 'string' && token.value.trim() === '\\n' && tokens[1].type !== 'variable' && tokens[1].type !== 'unescaped' && tokens[1].type !== 'partial') { return null; } // Recursively clean partials if (token.type === 'partial') { return {type: 'partial', value: clean(token.value)}; } // removes useless empty strings if (token.type === 'string' && token.value === '') { return null; } // escape quotes if (token.type === 'string') { return {type: 'string', value: token.value.replace(/"/g, "\\\"")}; } return token; }).filter(filterFalsy) }; }); }
JavaScript
function instantiateReactComponent(node, parentCompositeType) { var instance; if (node === null || node === false) { node = ReactEmptyComponent.emptyElement; } if (typeof node === 'object') { var element = node; if (__DEV__) { warning( element && (typeof element.type === 'function' || typeof element.type === 'string'), 'Only functions or strings can be mounted as React components.' ); } // Special case string values if (typeof element.type === 'string') { instance = ReactNativeComponent.createInstanceForTag( element.type, element.props, parentCompositeType ); // If the injected special class is not an internal class, but another // composite, then we must wrap it. // TODO: Move this resolution around to something cleaner. if (typeof instance.mountComponent !== 'function') { instance = new ReactCompositeComponentWrapper(instance); } } else if (isInternalComponentType(element.type)) { // This is temporarily available for custom components that are not string // represenations. I.e. ART. Once those are updated to use the string // representation, we can drop this code path. instance = new element.type(element); } else { // TODO: Update to follow new ES6 initialization. Ideally, we can use // props in property initializers. var inst = new element.type(element.props); instance = new ReactCompositeComponentWrapper(inst); } } else if (typeof node === 'string' || typeof node === 'number') { instance = ReactNativeComponent.createInstanceForText(node); } else { invariant( false, 'Encountered invalid React node of type %s', typeof node ); } if (__DEV__) { warning( typeof instance.construct === 'function' && typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.' ); } // Sets up the instance. This can probably just move into the constructor now. instance.construct(node); // Internal instances should fully constructed at this point, so they should // not get any new fields added to them at this point. if (__DEV__) { if (Object.preventExtensions) { Object.preventExtensions(instance); } } return instance; }
function instantiateReactComponent(node, parentCompositeType) { var instance; if (node === null || node === false) { node = ReactEmptyComponent.emptyElement; } if (typeof node === 'object') { var element = node; if (__DEV__) { warning( element && (typeof element.type === 'function' || typeof element.type === 'string'), 'Only functions or strings can be mounted as React components.' ); } // Special case string values if (typeof element.type === 'string') { instance = ReactNativeComponent.createInstanceForTag( element.type, element.props, parentCompositeType ); // If the injected special class is not an internal class, but another // composite, then we must wrap it. // TODO: Move this resolution around to something cleaner. if (typeof instance.mountComponent !== 'function') { instance = new ReactCompositeComponentWrapper(instance); } } else if (isInternalComponentType(element.type)) { // This is temporarily available for custom components that are not string // represenations. I.e. ART. Once those are updated to use the string // representation, we can drop this code path. instance = new element.type(element); } else { // TODO: Update to follow new ES6 initialization. Ideally, we can use // props in property initializers. var inst = new element.type(element.props); instance = new ReactCompositeComponentWrapper(inst); } } else if (typeof node === 'string' || typeof node === 'number') { instance = ReactNativeComponent.createInstanceForText(node); } else { invariant( false, 'Encountered invalid React node of type %s', typeof node ); } if (__DEV__) { warning( typeof instance.construct === 'function' && typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.' ); } // Sets up the instance. This can probably just move into the constructor now. instance.construct(node); // Internal instances should fully constructed at this point, so they should // not get any new fields added to them at this point. if (__DEV__) { if (Object.preventExtensions) { Object.preventExtensions(instance); } } return instance; }
JavaScript
function warnForPropsMutation(propName, element) { var type = element.type; var elementName = typeof type === 'string' ? type : type.displayName; var ownerName = element._owner ? element._owner.getPublicInstance().constructor.displayName : null; var warningKey = propName + '|' + elementName + '|' + ownerName; if (warnedPropsMutations.hasOwnProperty(warningKey)) { return; } warnedPropsMutations[warningKey] = true; var elementInfo = ''; if (elementName) { elementInfo = ' <' + elementName + ' />'; } var ownerInfo = ''; if (ownerName) { ownerInfo = ' The element was created by ' + ownerName + '.'; } warning( false, 'Don\'t set .props.' + propName + ' of the React component' + elementInfo + '. Instead, specify the correct value when ' + 'initially creating the element.' + ownerInfo ); }
function warnForPropsMutation(propName, element) { var type = element.type; var elementName = typeof type === 'string' ? type : type.displayName; var ownerName = element._owner ? element._owner.getPublicInstance().constructor.displayName : null; var warningKey = propName + '|' + elementName + '|' + ownerName; if (warnedPropsMutations.hasOwnProperty(warningKey)) { return; } warnedPropsMutations[warningKey] = true; var elementInfo = ''; if (elementName) { elementInfo = ' <' + elementName + ' />'; } var ownerInfo = ''; if (ownerName) { ownerInfo = ' The element was created by ' + ownerName + '.'; } warning( false, 'Don\'t set .props.' + propName + ' of the React component' + elementInfo + '. Instead, specify the correct value when ' + 'initially creating the element.' + ownerInfo ); }
JavaScript
function convertWeightToGrams(weight, units) { if (units.toLowerCase() === "lbs"){ weight = weight * 453.592; } else if (units.toLowerCase() === "oz"){ weight = weight * 28.3495; } else if (untis.toLocaleLowerCase() === "kg"){ weight = weight * 1000; } else if (untis.toLocaleLowerCase() === "mg"){ weight = weight / 1000; } return weight; }
function convertWeightToGrams(weight, units) { if (units.toLowerCase() === "lbs"){ weight = weight * 453.592; } else if (units.toLowerCase() === "oz"){ weight = weight * 28.3495; } else if (untis.toLocaleLowerCase() === "kg"){ weight = weight * 1000; } else if (untis.toLocaleLowerCase() === "mg"){ weight = weight / 1000; } return weight; }
JavaScript
function sumUniquePositiveFactors(number){ number = Math.abs(number); let sum = 0; for (i=1; i<=number; i++){ if (number % i === 0) { sum = sum + i; } } return sum; }
function sumUniquePositiveFactors(number){ number = Math.abs(number); let sum = 0; for (i=1; i<=number; i++){ if (number % i === 0) { sum = sum + i; } } return sum; }
JavaScript
function addOther(data, targetBox){ var otherBox = $("#factory .otherBox").clone(); $(".otherName", otherBox).text(data.name); var appendToBox; if (typeof data.link != "undefined") { $(".otherDesc", otherBox).html(""); appendToBox = $("<a>").attr("target", "_blank").attr("href", data.link); $(".otherDesc", otherBox).append(appendToBox); } else { appendToBox = $(".otherDesc", otherBox); } var descCtr; for (descCtr in data.desc) { appendToBox.append( KC3Meta.term(data.desc[descCtr])+" " ); } targetBox.append(otherBox); }
function addOther(data, targetBox){ var otherBox = $("#factory .otherBox").clone(); $(".otherName", otherBox).text(data.name); var appendToBox; if (typeof data.link != "undefined") { $(".otherDesc", otherBox).html(""); appendToBox = $("<a>").attr("target", "_blank").attr("href", data.link); $(".otherDesc", otherBox).append(appendToBox); } else { appendToBox = $(".otherDesc", otherBox); } var descCtr; for (descCtr in data.desc) { appendToBox.append( KC3Meta.term(data.desc[descCtr])+" " ); } targetBox.append(otherBox); }
JavaScript
function ExpedTabUpdateConfig() { const conf = ExpedTabValidateConfig(selectedExpedition); if(selectedFleet > 4) return; conf.fleetConf[ selectedFleet ].expedition = selectedExpedition; conf.expedConf[ selectedExpedition ].greatSuccess = plannerIsGreatSuccess; localStorage.expedTab = JSON.stringify( conf ); }
function ExpedTabUpdateConfig() { const conf = ExpedTabValidateConfig(selectedExpedition); if(selectedFleet > 4) return; conf.fleetConf[ selectedFleet ].expedition = selectedExpedition; conf.expedConf[ selectedExpedition ].greatSuccess = plannerIsGreatSuccess; localStorage.expedTab = JSON.stringify( conf ); }
JavaScript
function ExpedTabApplyConfig() { if(selectedFleet > 4) return; let conf = ExpedTabValidateConfig(selectedExpedition); selectedExpedition = conf.fleetConf[ selectedFleet ].expedition; // re-validate config in case that fleet has just returned from a new exped conf = ExpedTabValidateConfig(selectedExpedition); plannerIsGreatSuccess = (conf.expedConf[selectedExpedition] || {}).greatSuccess || false; }
function ExpedTabApplyConfig() { if(selectedFleet > 4) return; let conf = ExpedTabValidateConfig(selectedExpedition); selectedExpedition = conf.fleetConf[ selectedFleet ].expedition; // re-validate config in case that fleet has just returned from a new exped conf = ExpedTabValidateConfig(selectedExpedition); plannerIsGreatSuccess = (conf.expedConf[selectedExpedition] || {}).greatSuccess || false; }
JavaScript
function runUpdatingMoraleTimer() { moraleTimerLastUpdated = Date.now(); // console.log(moraleClockValue, moraleClockEnd, moraleClockRemain); if(moraleClockEnd > 0){ moraleClockRemain = Math.ceil( (moraleClockEnd - Date.now())/1000); if(moraleClockRemain > 0){ $(".module.status .status_morale .status_text").text("~"+(moraleClockRemain+"").toHHMMSS()); }else{ moraleClockValue = 100; moraleClockEnd = 0; moraleClockRemain = 0; $(".module.status .status_morale .status_text").text( KC3Meta.term("PanelRecoveredMorale") ); // Morale desktop notification if not on sortie/PvP, if(ConfigManager.alert_morale_notif && !(KC3SortieManager.isOnSortie() || KC3SortieManager.isPvP()) ){ // Play sound if alert sound setting is not none if(KC3TimerManager.notifSound){ KC3TimerManager.notifSound.pause(); } switch(ConfigManager.alert_type){ case 1: KC3TimerManager.notifSound = new Audio("../../../../assets/snd/pop.mp3"); break; case 2: KC3TimerManager.notifSound = new Audio(ConfigManager.alert_custom); break; case 3: KC3TimerManager.notifSound = new Audio("../../../../assets/snd/ding.mp3"); break; case 4: KC3TimerManager.notifSound = new Audio("../../../../assets/snd/dong.mp3"); break; case 5: KC3TimerManager.notifSound = new Audio("../../../../assets/snd/bell.mp3"); break; default: KC3TimerManager.notifSound = false; break; } if(KC3TimerManager.notifSound){ KC3TimerManager.notifSound.volume = ConfigManager.alert_volume / 100; KC3TimerManager.notifSound.play(); } // Send desktop notification (new RMsg("service", "notify_desktop", { notifId: "morale", data: { type: "basic", title: KC3Meta.term("DesktopNotifyMoraleTitle"), message: KC3Meta.term("DesktopNotifyMoraleMessage"), iconUrl: "../../assets/img/ui/morale.png" }, tabId: chrome.devtools.inspectedWindow.tabId })).execute(); // Focus game tab if settings enabled if(ConfigManager.alert_focustab){ (new RMsg("service", "focusGameTab", { tabId: chrome.devtools.inspectedWindow.tabId })).execute(); } } } } }
function runUpdatingMoraleTimer() { moraleTimerLastUpdated = Date.now(); // console.log(moraleClockValue, moraleClockEnd, moraleClockRemain); if(moraleClockEnd > 0){ moraleClockRemain = Math.ceil( (moraleClockEnd - Date.now())/1000); if(moraleClockRemain > 0){ $(".module.status .status_morale .status_text").text("~"+(moraleClockRemain+"").toHHMMSS()); }else{ moraleClockValue = 100; moraleClockEnd = 0; moraleClockRemain = 0; $(".module.status .status_morale .status_text").text( KC3Meta.term("PanelRecoveredMorale") ); // Morale desktop notification if not on sortie/PvP, if(ConfigManager.alert_morale_notif && !(KC3SortieManager.isOnSortie() || KC3SortieManager.isPvP()) ){ // Play sound if alert sound setting is not none if(KC3TimerManager.notifSound){ KC3TimerManager.notifSound.pause(); } switch(ConfigManager.alert_type){ case 1: KC3TimerManager.notifSound = new Audio("../../../../assets/snd/pop.mp3"); break; case 2: KC3TimerManager.notifSound = new Audio(ConfigManager.alert_custom); break; case 3: KC3TimerManager.notifSound = new Audio("../../../../assets/snd/ding.mp3"); break; case 4: KC3TimerManager.notifSound = new Audio("../../../../assets/snd/dong.mp3"); break; case 5: KC3TimerManager.notifSound = new Audio("../../../../assets/snd/bell.mp3"); break; default: KC3TimerManager.notifSound = false; break; } if(KC3TimerManager.notifSound){ KC3TimerManager.notifSound.volume = ConfigManager.alert_volume / 100; KC3TimerManager.notifSound.play(); } // Send desktop notification (new RMsg("service", "notify_desktop", { notifId: "morale", data: { type: "basic", title: KC3Meta.term("DesktopNotifyMoraleTitle"), message: KC3Meta.term("DesktopNotifyMoraleMessage"), iconUrl: "../../assets/img/ui/morale.png" }, tabId: chrome.devtools.inspectedWindow.tabId })).execute(); // Focus game tab if settings enabled if(ConfigManager.alert_focustab){ (new RMsg("service", "focusGameTab", { tabId: chrome.devtools.inspectedWindow.tabId })).execute(); } } } } }
JavaScript
init() { this.defineSorters(); this.showListRowCallback = this.showShipLockingRow; // Amount of locking tags depends on MO/EO settings of each event, // order and colors of tag texture see: main.js#BannerPlate.prototype._getTexture, // and please update `lockingTagConfigs` and `lockingTagColors` by themes in `fud_quarterly.json` file. // NOTE: texture ID and our color ID is 0-based index, but API property `sally` is 1-based. const configs = KC3Meta.eventLockingTagConfigs(); this.lockLimit = ConfigManager.sr_locktag_max || configs.maxTagAmount || 2; this.moLocks = ConfigManager.sr_locktag_mo || configs.moTagIds || []; this.eoLocks = ConfigManager.sr_locktag_eo || configs.eoTagIds || []; this.heartLockMode = 2; this.showShipLevel = true; this.scrollFixed = true; this.currentTab = "all"; }
init() { this.defineSorters(); this.showListRowCallback = this.showShipLockingRow; // Amount of locking tags depends on MO/EO settings of each event, // order and colors of tag texture see: main.js#BannerPlate.prototype._getTexture, // and please update `lockingTagConfigs` and `lockingTagColors` by themes in `fud_quarterly.json` file. // NOTE: texture ID and our color ID is 0-based index, but API property `sally` is 1-based. const configs = KC3Meta.eventLockingTagConfigs(); this.lockLimit = ConfigManager.sr_locktag_max || configs.maxTagAmount || 2; this.moLocks = ConfigManager.sr_locktag_mo || configs.moTagIds || []; this.eoLocks = ConfigManager.sr_locktag_eo || configs.eoTagIds || []; this.heartLockMode = 2; this.showShipLevel = true; this.scrollFixed = true; this.currentTab = "all"; }
JavaScript
reload() { KC3ShipManager.load(); KC3GearManager.load(); this.loadShipLockPlan(); this.prepareFilters(); this.prepareShipList(true, this.mapShipLockingStatus); }
reload() { KC3ShipManager.load(); KC3GearManager.load(); this.loadShipLockPlan(); this.prepareFilters(); this.prepareShipList(true, this.mapShipLockingStatus); }
JavaScript
execute() { this.tab = $(".tab_locking"); this.addLockBoxes(); this.loadLockModeColors(); $(".map_area, .ships_area", $(".lock_modes")).empty(); this.fillLockBoxes(); this.setDroppable(); this.switchToLockTab(this.currentTab); let startTime = Date.now(); $(".selectTab", this.tab).on("click", (e) => { const newTab = $(e.currentTarget).data("tab"); if (!!newTab && newTab !== this.currentTab) { this.switchToLockTab(newTab); } }); $(".clearAllPlans", this.tab).on("click", this.clearAllPlannedLocks.bind(this)); $(".toggleShipLevel", this.tab).on("click", (e) => { this.showShipLevel = !this.showShipLevel; $(".ships_area .lship .level", this.tab).toggle(this.showShipLevel); }); $(".ships_area .lship .level", this.tab).toggle(this.showShipLevel); $(".toggleFixedScroll", this.tab).on("click", (e) => { this.scrollFixed = !this.scrollFixed; $(".vscroll", this.tab).toggleClass("scroll_fix", this.scrollFixed); if (this.scrollFixed) this.adjustHeight(); }); $(".vscroll", this.tab).toggleClass("scroll_fix", this.scrollFixed); this.shipListDiv = $(".ship_list", this.tab); this.shipListDiv.on("preShow", () => { $(".filters input").each((_, elem) => { elem.disabled = true; }); startTime = Date.now(); }); this.shipListDiv.on("postShow", ()=> { $(".filters input").each((_, elem) => { elem.disabled = false; }); this.adjustHeight(); // Defer another adjustment because at this timing new version chrome still hide dom (fail to get element's size and offset) setTimeout(() => { this.switchToLockTab(this.currentTab); this.adjustHeight(); }, Date.now() - startTime); }); this.shipRowTemplateDiv = $(".factory .ship_item", this.tab); this.addFilterUI(); this.showListGrid(); $(".ship_header .ship_stat img").each((_, img) => { $(img).attr("src", KC3Meta.statIcon($(img).parent().data("type"))); }); this.shipListHeaderDiv = $(".ship_header .ship_field.hover", this.tab); this.registerShipListHeaderEvent(this.shipListHeaderDiv); this.shipListHeaderDiv.on("click", (e) => { $(".ship_header .ship_field.hover.sorted").removeClass("sorted"); $(e.currentTarget).addClass("sorted"); }); this.shipListDiv.on("click", ".ship_item .ship_sally", (e) => { const ship = this.getShipById($(e.currentTarget) .closest(".ship_item").data("ship_id")); if (ship.sally === 0) { this.switchPlannedLock(ship); } }); }
execute() { this.tab = $(".tab_locking"); this.addLockBoxes(); this.loadLockModeColors(); $(".map_area, .ships_area", $(".lock_modes")).empty(); this.fillLockBoxes(); this.setDroppable(); this.switchToLockTab(this.currentTab); let startTime = Date.now(); $(".selectTab", this.tab).on("click", (e) => { const newTab = $(e.currentTarget).data("tab"); if (!!newTab && newTab !== this.currentTab) { this.switchToLockTab(newTab); } }); $(".clearAllPlans", this.tab).on("click", this.clearAllPlannedLocks.bind(this)); $(".toggleShipLevel", this.tab).on("click", (e) => { this.showShipLevel = !this.showShipLevel; $(".ships_area .lship .level", this.tab).toggle(this.showShipLevel); }); $(".ships_area .lship .level", this.tab).toggle(this.showShipLevel); $(".toggleFixedScroll", this.tab).on("click", (e) => { this.scrollFixed = !this.scrollFixed; $(".vscroll", this.tab).toggleClass("scroll_fix", this.scrollFixed); if (this.scrollFixed) this.adjustHeight(); }); $(".vscroll", this.tab).toggleClass("scroll_fix", this.scrollFixed); this.shipListDiv = $(".ship_list", this.tab); this.shipListDiv.on("preShow", () => { $(".filters input").each((_, elem) => { elem.disabled = true; }); startTime = Date.now(); }); this.shipListDiv.on("postShow", ()=> { $(".filters input").each((_, elem) => { elem.disabled = false; }); this.adjustHeight(); // Defer another adjustment because at this timing new version chrome still hide dom (fail to get element's size and offset) setTimeout(() => { this.switchToLockTab(this.currentTab); this.adjustHeight(); }, Date.now() - startTime); }); this.shipRowTemplateDiv = $(".factory .ship_item", this.tab); this.addFilterUI(); this.showListGrid(); $(".ship_header .ship_stat img").each((_, img) => { $(img).attr("src", KC3Meta.statIcon($(img).parent().data("type"))); }); this.shipListHeaderDiv = $(".ship_header .ship_field.hover", this.tab); this.registerShipListHeaderEvent(this.shipListHeaderDiv); this.shipListHeaderDiv.on("click", (e) => { $(".ship_header .ship_field.hover.sorted").removeClass("sorted"); $(e.currentTarget).addClass("sorted"); }); this.shipListDiv.on("click", ".ship_item .ship_sally", (e) => { const ship = this.getShipById($(e.currentTarget) .closest(".ship_item").data("ship_id")); if (ship.sally === 0) { this.switchPlannedLock(ship); } }); }
JavaScript
function activateDmmPlay(){ localStorage.extract_api = false; localStorage.dmmplay = true; applyCookiesAndRedirect(); }
function activateDmmPlay(){ localStorage.extract_api = false; localStorage.dmmplay = true; applyCookiesAndRedirect(); }
JavaScript
function tl_loadLanguageVersion(){ var lang = ConfigManager.language; $(document).ajaxError(function(event, request, settings){ console.debug(event, request, settings); $(".tl_checklive_status").text("Unable to load online translations for this language"); $(".tl_checklive_status").css({ color:'#f00' }); }); $.ajax({ url: source+'/'+lang+'/custom.json', dataType: 'JSON', success: function(response){ $(".tl_checklive_status").text("Loading files..."); tl_loadLanguageFile("quests.json", response.version.quests, $("#tlfile_item_quests")); tl_loadLanguageFile("quotes.json", response.version.quotes, $("#tlfile_item_quotes")); tl_loadLanguageFile("ships.json", response.version.ships, $("#tlfile_item_ships")); tl_loadLanguageFile("items.json", response.version.items, $("#tlfile_item_items")); } }); }
function tl_loadLanguageVersion(){ var lang = ConfigManager.language; $(document).ajaxError(function(event, request, settings){ console.debug(event, request, settings); $(".tl_checklive_status").text("Unable to load online translations for this language"); $(".tl_checklive_status").css({ color:'#f00' }); }); $.ajax({ url: source+'/'+lang+'/custom.json', dataType: 'JSON', success: function(response){ $(".tl_checklive_status").text("Loading files..."); tl_loadLanguageFile("quests.json", response.version.quests, $("#tlfile_item_quests")); tl_loadLanguageFile("quotes.json", response.version.quotes, $("#tlfile_item_quotes")); tl_loadLanguageFile("ships.json", response.version.ships, $("#tlfile_item_ships")); tl_loadLanguageFile("items.json", response.version.items, $("#tlfile_item_items")); } }); }
JavaScript
function tl_loadLanguageFile(filename, filever, element){ var lang = ConfigManager.language; $(".tlfile_status_icon", element).hide(); $(".loader", element).show(); $.ajax({ url: source+'/'+lang+'/'+filename, dataType: 'JSON', success: function(response){ KC3Translation.updateTranslations(lang, filename, filever, response, function(){ $(".tlfile_status_icon", element).hide(); $(".done", element).show(); loadFileComplete(); }); } }); }
function tl_loadLanguageFile(filename, filever, element){ var lang = ConfigManager.language; $(".tlfile_status_icon", element).hide(); $(".loader", element).show(); $.ajax({ url: source+'/'+lang+'/'+filename, dataType: 'JSON', success: function(response){ KC3Translation.updateTranslations(lang, filename, filever, response, function(){ $(".tlfile_status_icon", element).hide(); $(".done", element).show(); loadFileComplete(); }); } }); }
JavaScript
function accumulateStats(statSets,ThisSlotitem) { return function(p,i) { statSets[p].push( ThisSlotitem.stats[p] ); }; }
function accumulateStats(statSets,ThisSlotitem) { return function(p,i) { statSets[p].push( ThisSlotitem.stats[p] ); }; }
JavaScript
function isBattleShipKai( mst ) { return [ 82, // Ise Kai 553, // Ise K2 88, // Hyuuga Kai 554, // Hyuuga K2 148, // Musashi Kai 546, // Musashi K2 ].indexOf( mst.api_id ) !== -1; }
function isBattleShipKai( mst ) { return [ 82, // Ise Kai 553, // Ise K2 88, // Hyuuga Kai 554, // Hyuuga K2 148, // Musashi Kai 546, // Musashi K2 ].indexOf( mst.api_id ) !== -1; }
JavaScript
function isBritishShips( mst ) { return [ 67, // Queen Elizabeth Class 78, // Ark Royal Class 82, // Jervis Class 88, // Nelson Class // Shelffield not been capable until 2021-2-5 fix // https://twitter.com/KanColle_STAFF/status/1357645300895080449 108, // Town Class ].indexOf( mst.api_ctype ) !== -1 || // Kongou Class Kai Ni, K2C [149, 150, 151, 152, 591, 592].indexOf( mst.api_id ) !== -1; }
function isBritishShips( mst ) { return [ 67, // Queen Elizabeth Class 78, // Ark Royal Class 82, // Jervis Class 88, // Nelson Class // Shelffield not been capable until 2021-2-5 fix // https://twitter.com/KanColle_STAFF/status/1357645300895080449 108, // Town Class ].indexOf( mst.api_ctype ) !== -1 || // Kongou Class Kai Ni, K2C [149, 150, 151, 152, 591, 592].indexOf( mst.api_id ) !== -1; }