language
stringclasses
6 values
original_string
stringlengths
25
887k
text
stringlengths
25
887k
JavaScript
function secondsToTime (seconds) { const hours = Math.floor(seconds / 3600) const minutes = Math.floor((seconds % 3600) / 60) const secs = seconds % 60 return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}` }
function secondsToTime (seconds) { const hours = Math.floor(seconds / 3600) const minutes = Math.floor((seconds % 3600) / 60) const secs = seconds % 60 return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}` }
JavaScript
function DOMDisplay(parent, level) { this.wrap = parent.appendChild(createElement('div','game')); this.level = level; this.wrap.appendChild(this.drawBackground()); //this.wrap.appendChild(this.drawActors()); this.actorsLayer = null; }
function DOMDisplay(parent, level) { this.wrap = parent.appendChild(createElement('div','game')); this.level = level; this.wrap.appendChild(this.drawBackground()); //this.wrap.appendChild(this.drawActors()); this.actorsLayer = null; }
JavaScript
find(a) { while (this.parent[a] !== a) { a = this.parent[a]; } return a; }
find(a) { while (this.parent[a] !== a) { a = this.parent[a]; } return a; }
JavaScript
function Level(plan) { if (!validateLevel(plan)) throw new Error('You need a player and a coin.'); this.width = plan[0].length; this.height = plan.length; this.status = null; this.finishDelay = null; this.grid = []; this.actors = []; for (let y = 0; y < this.height; y++) { let line = plan[y]; let gridLine = []; for (let x = 0; x < this.width; x++) { var character = line[x]; var characterType = null; let Actor = ACTORS[character]; if (Actor) this.actors.push(new Actor(new Vector(x, y), character)); if (character === 'x') characterType = 'wall'; else if (character === '!') characterType = 'lava'; gridLine.push(characterType); } this.grid.push(gridLine); //console.log(gridLine); } this.player = this.actors.filter(actor => actor.type === 'player')[0]; //console.log(this.actor); }
function Level(plan) { if (!validateLevel(plan)) throw new Error('You need a player and a coin.'); this.width = plan[0].length; this.height = plan.length; this.status = null; this.finishDelay = null; this.grid = []; this.actors = []; for (let y = 0; y < this.height; y++) { let line = plan[y]; let gridLine = []; for (let x = 0; x < this.width; x++) { var character = line[x]; var characterType = null; let Actor = ACTORS[character]; if (Actor) this.actors.push(new Actor(new Vector(x, y), character)); if (character === 'x') characterType = 'wall'; else if (character === '!') characterType = 'lava'; gridLine.push(characterType); } this.grid.push(gridLine); //console.log(gridLine); } this.player = this.actors.filter(actor => actor.type === 'player')[0]; //console.log(this.actor); }
JavaScript
function factorialize(num) { if(num < 0) return -1; else if (num == 0) return 1; else return (num * factorialize(num - 1)); }
function factorialize(num) { if(num < 0) return -1; else if (num == 0) return 1; else return (num * factorialize(num - 1)); }
JavaScript
onBeginRendererPage(page) { let model = page.model; if (!(model instanceof reflections_1.Reflection)) { return; } const trail = []; while (!(model instanceof reflections_1.ProjectReflection) && !model.kindOf(reflections_1.ReflectionKind.SomeModule)) { trail.unshift(model); model = model.parent; } const tocRestriction = this.owner.toc; page.toc = new NavigationItem_1.NavigationItem(); TocPlugin_1.TocPlugin.buildToc(model, trail, page.toc, tocRestriction); this.buildGroupTocContent(page); }
onBeginRendererPage(page) { let model = page.model; if (!(model instanceof reflections_1.Reflection)) { return; } const trail = []; while (!(model instanceof reflections_1.ProjectReflection) && !model.kindOf(reflections_1.ReflectionKind.SomeModule)) { trail.unshift(model); model = model.parent; } const tocRestriction = this.owner.toc; page.toc = new NavigationItem_1.NavigationItem(); TocPlugin_1.TocPlugin.buildToc(model, trail, page.toc, tocRestriction); this.buildGroupTocContent(page); }
JavaScript
function FactoryReset(){ var graphDiv = 'ProjectionsVisual' Plotly.purge(graphDiv); location.reload(); }
function FactoryReset(){ var graphDiv = 'ProjectionsVisual' Plotly.purge(graphDiv); location.reload(); }
JavaScript
function fetchVal(callback) { var file, fr; file = input.files[0]; fr = new FileReader(); fr.onload = function (e) { lines = e.target.result; callback(lines); }; fr.readAsText(file); }
function fetchVal(callback) { var file, fr; file = input.files[0]; fr = new FileReader(); fr.onload = function (e) { lines = e.target.result; callback(lines); }; fr.readAsText(file); }
JavaScript
function parseData(url) { var graphDiv = 'gridVisual' Plotly.purge(graphDiv); document.getElementById("loader").style.display = "block"; Papa.parse(url, { download: true, header: true, dynamicTyping: true, skipEmptyLines: true, complete: function(results) { results.data = results.data.filter(function (el) { var counter = 0; for(key in el) { if(el.hasOwnProperty(key)) { var value = el[key]; if(key === "id" || key === "Version" || typeof(value) !== 'number' || value === undefined){ // Add more limitations if needed in both areas. This is for the calculations so it needs more limitations! delete el[key]; }else{ el[counter] = el[key]; delete el[key]; counter = counter + 1; } } } return el; }); Papa.parse(url, { download: true, header: true, dynamicTyping: true, skipEmptyLines: true, complete: function(data) { doStuff(data.data.filter(function (el) { var counter = 0; for(key in el) { if(el.hasOwnProperty(key)) { var value = el[key]; if(key === "id" || key === "Version"){ // Add more limitations if needed in both areas. Key limitations here! delete el[key]; } } } return el; })); } }); function doStuff(results_all){ results_all_global = results_all // results_all variable is all the columns multiplied by all the rows. // results.data variable is all the columns except strings, undefined values, or "Version" plus beta and cost values." // results.meta.fields variable is all the features (columns) plus beta and cost strings. if (mode == 2) { if (insideCall) { init(results.data, results_all, results.meta.fields); // Call the init() function that starts everything! } else { $.post(BACKEND_API_URL+"/resetAll", JSON.stringify(''), function(){ }); var parametersLocal = [] parametersLocal.push(document.getElementById("param-perplexity-value").value) parametersLocal.push(document.getElementById("param-learningrate-value").value) parametersLocal.push(document.getElementById("param-maxiter-value").value) parametersLocal.push(results_all) $.post(BACKEND_API_URL+"/receiverSingle", JSON.stringify(parametersLocal), function(){ $.get(BACKEND_API_URL+"/senderSingle", function( data ) { dataReceivedFromServer = data projections = dataReceivedFromServer['projections'] betas = dataReceivedFromServer['betas'] cost_per_point = dataReceivedFromServer['cpp'] cost_overall = dataReceivedFromServer['cpi'] activeProjectionNumber = 0 activeProjectionNumberProv = 0 init(results.data, results_all, results.meta.fields); // Call the init() function that starts everything! }); }); } } else { if (flagAnalysis) { $('#myModal').modal('hide'); $.post(BACKEND_API_URL+"/resetAll", JSON.stringify(''), function(){ }); var parametersLocal = [] parametersLocal.push(document.getElementById("param-perplexity-value").value) parametersLocal.push(document.getElementById("param-learningrate-value").value) parametersLocal.push(document.getElementById("param-maxiter-value").value) parametersLocal.push(results_all) $.post(BACKEND_API_URL+"/receiverSingle", JSON.stringify(parametersLocal), function(){ $.get(BACKEND_API_URL+"/senderSingle", function( data ) { dataReceivedFromServer = data projections = dataReceivedFromServer['projections'] betas = dataReceivedFromServer['betas'] cost_per_point = dataReceivedFromServer['cpp'] cost_overall = dataReceivedFromServer['cpi'] activeProjectionNumber = 0 init(results.data, results_all, results.meta.fields); // Call the init() function that starts everything! }); }); } else { // ajax the JSON to the server $.post(BACKEND_API_URL+"/resetAll", JSON.stringify(''), function(){ }); $.post(BACKEND_API_URL+"/receiver", JSON.stringify(results_all), function(){ $.get(BACKEND_API_URL+"/sender", function( data ) { dataReceivedFromServer = data ReSortOver() }); }); } } } } }); }
function parseData(url) { var graphDiv = 'gridVisual' Plotly.purge(graphDiv); document.getElementById("loader").style.display = "block"; Papa.parse(url, { download: true, header: true, dynamicTyping: true, skipEmptyLines: true, complete: function(results) { results.data = results.data.filter(function (el) { var counter = 0; for(key in el) { if(el.hasOwnProperty(key)) { var value = el[key]; if(key === "id" || key === "Version" || typeof(value) !== 'number' || value === undefined){ // Add more limitations if needed in both areas. This is for the calculations so it needs more limitations! delete el[key]; }else{ el[counter] = el[key]; delete el[key]; counter = counter + 1; } } } return el; }); Papa.parse(url, { download: true, header: true, dynamicTyping: true, skipEmptyLines: true, complete: function(data) { doStuff(data.data.filter(function (el) { var counter = 0; for(key in el) { if(el.hasOwnProperty(key)) { var value = el[key]; if(key === "id" || key === "Version"){ // Add more limitations if needed in both areas. Key limitations here! delete el[key]; } } } return el; })); } }); function doStuff(results_all){ results_all_global = results_all // results_all variable is all the columns multiplied by all the rows. // results.data variable is all the columns except strings, undefined values, or "Version" plus beta and cost values." // results.meta.fields variable is all the features (columns) plus beta and cost strings. if (mode == 2) { if (insideCall) { init(results.data, results_all, results.meta.fields); // Call the init() function that starts everything! } else { $.post(BACKEND_API_URL+"/resetAll", JSON.stringify(''), function(){ }); var parametersLocal = [] parametersLocal.push(document.getElementById("param-perplexity-value").value) parametersLocal.push(document.getElementById("param-learningrate-value").value) parametersLocal.push(document.getElementById("param-maxiter-value").value) parametersLocal.push(results_all) $.post(BACKEND_API_URL+"/receiverSingle", JSON.stringify(parametersLocal), function(){ $.get(BACKEND_API_URL+"/senderSingle", function( data ) { dataReceivedFromServer = data projections = dataReceivedFromServer['projections'] betas = dataReceivedFromServer['betas'] cost_per_point = dataReceivedFromServer['cpp'] cost_overall = dataReceivedFromServer['cpi'] activeProjectionNumber = 0 activeProjectionNumberProv = 0 init(results.data, results_all, results.meta.fields); // Call the init() function that starts everything! }); }); } } else { if (flagAnalysis) { $('#myModal').modal('hide'); $.post(BACKEND_API_URL+"/resetAll", JSON.stringify(''), function(){ }); var parametersLocal = [] parametersLocal.push(document.getElementById("param-perplexity-value").value) parametersLocal.push(document.getElementById("param-learningrate-value").value) parametersLocal.push(document.getElementById("param-maxiter-value").value) parametersLocal.push(results_all) $.post(BACKEND_API_URL+"/receiverSingle", JSON.stringify(parametersLocal), function(){ $.get(BACKEND_API_URL+"/senderSingle", function( data ) { dataReceivedFromServer = data projections = dataReceivedFromServer['projections'] betas = dataReceivedFromServer['betas'] cost_per_point = dataReceivedFromServer['cpp'] cost_overall = dataReceivedFromServer['cpi'] activeProjectionNumber = 0 init(results.data, results_all, results.meta.fields); // Call the init() function that starts everything! }); }); } else { // ajax the JSON to the server $.post(BACKEND_API_URL+"/resetAll", JSON.stringify(''), function(){ }); $.post(BACKEND_API_URL+"/receiver", JSON.stringify(results_all), function(){ $.get(BACKEND_API_URL+"/sender", function( data ) { dataReceivedFromServer = data ReSortOver() }); }); } } } } }); }
JavaScript
function normDist(data, dist) { var max_dist = 0; for(var i = 0; i < data.length; i++) { for(var j = i + 1; j < data.length; j++) { if(dist[i][j] > max_dist) max_dist = dist[i][j]; } } for(var i = 0; i < data.length; i++) { for(var j = 0; j < data.length; j++) { dist[i][j] /= max_dist; } } return dist; }
function normDist(data, dist) { var max_dist = 0; for(var i = 0; i < data.length; i++) { for(var j = i + 1; j < data.length; j++) { if(dist[i][j] > max_dist) max_dist = dist[i][j]; } } for(var i = 0; i < data.length; i++) { for(var j = 0; j < data.length; j++) { dist[i][j] /= max_dist; } } return dist; }
JavaScript
function computeDistances(data, distFunc, transFunc) { dist = eval(distFunc)(eval(transFunc)(data)); dist = normDist(data, dist); return dist; }
function computeDistances(data, distFunc, transFunc) { dist = eval(distFunc)(eval(transFunc)(data)); dist = normDist(data, dist); return dist; }
JavaScript
function step() { step_counter++; if(step_counter <= max_counter) { //cost = tsne.step(); //cost_each = cost[1]; //for(var i = 0; i < final_dataset.length; i++) final_dataset[i].cost = cost_each[i]; if (sliderTrigger) { if (sliderInsideTrigger) { if (cost_overall[activeProjectionNumberProv][step_counter-1].toFixed(3) < 0) { $("#cost").html("(Ov. Cost: 0.000)"); ArrayWithCosts.push(0); Iterations.push(step_counter); } else { $("#cost").html("(Ov. Cost: " + cost_overall[activeProjectionNumberProv][step_counter-1].toFixed(3) + ")"); ArrayWithCosts.push(cost_overall[activeProjectionNumberProv][step_counter-1].toFixed(3)); Iterations.push(step_counter); } } else { if (cost_overall[activeProjectionNumber][step_counter-1].toFixed(3) < 0) { $("#cost").html("(Ov. Cost: 0.000)"); ArrayWithCosts.push(0); Iterations.push(step_counter); } else { $("#cost").html("(Ov. Cost: " + cost_overall[activeProjectionNumber][step_counter-1].toFixed(3) + ")"); ArrayWithCosts.push(cost_overall[activeProjectionNumber][step_counter-1].toFixed(3)); Iterations.push(step_counter); } } } else { if (cost_overall[activeProjectionNumber][step_counter-1].toFixed(3) < 0) { $("#cost").html("(Ov. Cost: 0.000)"); ArrayWithCosts.push(0); Iterations.push(step_counter); } else { $("#cost").html("(Ov. Cost: " + cost_overall[activeProjectionNumber][step_counter-1].toFixed(3) + ")"); ArrayWithCosts.push(cost_overall[activeProjectionNumber][step_counter-1].toFixed(3)); Iterations.push(step_counter); } } } else { clearInterval(runner); } if (step_counter == max_counter){ ArrayWithCostsList.push(ArrayWithCosts); IterationsList.push(Iterations); updateEmbedding(AnalysisResults); } }
function step() { step_counter++; if(step_counter <= max_counter) { //cost = tsne.step(); //cost_each = cost[1]; //for(var i = 0; i < final_dataset.length; i++) final_dataset[i].cost = cost_each[i]; if (sliderTrigger) { if (sliderInsideTrigger) { if (cost_overall[activeProjectionNumberProv][step_counter-1].toFixed(3) < 0) { $("#cost").html("(Ov. Cost: 0.000)"); ArrayWithCosts.push(0); Iterations.push(step_counter); } else { $("#cost").html("(Ov. Cost: " + cost_overall[activeProjectionNumberProv][step_counter-1].toFixed(3) + ")"); ArrayWithCosts.push(cost_overall[activeProjectionNumberProv][step_counter-1].toFixed(3)); Iterations.push(step_counter); } } else { if (cost_overall[activeProjectionNumber][step_counter-1].toFixed(3) < 0) { $("#cost").html("(Ov. Cost: 0.000)"); ArrayWithCosts.push(0); Iterations.push(step_counter); } else { $("#cost").html("(Ov. Cost: " + cost_overall[activeProjectionNumber][step_counter-1].toFixed(3) + ")"); ArrayWithCosts.push(cost_overall[activeProjectionNumber][step_counter-1].toFixed(3)); Iterations.push(step_counter); } } } else { if (cost_overall[activeProjectionNumber][step_counter-1].toFixed(3) < 0) { $("#cost").html("(Ov. Cost: 0.000)"); ArrayWithCosts.push(0); Iterations.push(step_counter); } else { $("#cost").html("(Ov. Cost: " + cost_overall[activeProjectionNumber][step_counter-1].toFixed(3) + ")"); ArrayWithCosts.push(cost_overall[activeProjectionNumber][step_counter-1].toFixed(3)); Iterations.push(step_counter); } } } else { clearInterval(runner); } if (step_counter == max_counter){ ArrayWithCostsList.push(ArrayWithCosts); IterationsList.push(Iterations); updateEmbedding(AnalysisResults); } }
JavaScript
function updateBarChart() { ///////////////////////////////////////////////////////////// ////////// Update the bars of the main bar chart //////////// ///////////////////////////////////////////////////////////// var bar = d3v3.select(".mainGroup").selectAll(".bar") .data(correlationResultsFinal, function(d) { return +d[2]; }) //, function(d) { return d.key; }); bar .attr("x", function (d) { return main_xScale(Math.min(0, d[1])); }) .attr("width", function(d) { return Math.abs(main_xScale(d[1]) - main_xScale(0)); }) .attr("y", function(d,i) { return main_yScale(d[0]); }) .attr("height", main_yScale.rangeBand()); //ENTER bar.enter().append("rect") .attr("class", "bar") .style("fill", "url(#gradient-main)") .attr("x", function (d) { return main_xScale(Math.min(0, d[1])); }) .attr("width", function(d) { return Math.abs(main_xScale(d[1]) - main_xScale(0)); }) .attr("y", function(d,i) { return main_yScale(d[0]); }) .attr("height", main_yScale.rangeBand()) .on("mouseover", () => { svg.select('.tooltip').style('display', 'none'); }) .on("click", function(d) { var flag = false; points.forEach(function (p) { if (p.DimON == d[0]) { flag = true; } }); if (flag == false){ correlationResultsFinal.forEach(function(corr){ var str2 = corr[0]; var elements2 = $("*:contains('"+ str2 +"')").filter( function(){ return $(this).find("*:contains('"+ str2 +"')").length == 0 } ); elements2[0].style.fontWeight = 'normal'; if (typeof elements2[1] != "undefined"){ elements2[1].style.fontWeight = 'normal'; } }); points.forEach(function (p) { if (p.schemaInv == true) { p.DimON = d[0]; var str = p.DimON; var elements = $("*:contains('"+ str +"')").filter( function(){ return $(this).find("*:contains('"+ str +"')").length == 0 } ); elements[0].style.fontWeight = 'bold'; } }) } else{ correlationResultsFinal.forEach(function(corr){ var str2 = corr[0]; var elements2 = $("*:contains('"+ str2 +"')").filter( function(){ return $(this).find("*:contains('"+ str2 +"')").length == 0 } ); elements2[0].style.fontWeight = 'normal'; if (typeof elements2[1] != "undefined"){ elements2[1].style.fontWeight = 'normal'; } }); points.forEach(function (p) { p.DimON = null; }); } BetatSNE(points); }); //EXIT bar.exit() .remove(); }//update
function updateBarChart() { ///////////////////////////////////////////////////////////// ////////// Update the bars of the main bar chart //////////// ///////////////////////////////////////////////////////////// var bar = d3v3.select(".mainGroup").selectAll(".bar") .data(correlationResultsFinal, function(d) { return +d[2]; }) //, function(d) { return d.key; }); bar .attr("x", function (d) { return main_xScale(Math.min(0, d[1])); }) .attr("width", function(d) { return Math.abs(main_xScale(d[1]) - main_xScale(0)); }) .attr("y", function(d,i) { return main_yScale(d[0]); }) .attr("height", main_yScale.rangeBand()); //ENTER bar.enter().append("rect") .attr("class", "bar") .style("fill", "url(#gradient-main)") .attr("x", function (d) { return main_xScale(Math.min(0, d[1])); }) .attr("width", function(d) { return Math.abs(main_xScale(d[1]) - main_xScale(0)); }) .attr("y", function(d,i) { return main_yScale(d[0]); }) .attr("height", main_yScale.rangeBand()) .on("mouseover", () => { svg.select('.tooltip').style('display', 'none'); }) .on("click", function(d) { var flag = false; points.forEach(function (p) { if (p.DimON == d[0]) { flag = true; } }); if (flag == false){ correlationResultsFinal.forEach(function(corr){ var str2 = corr[0]; var elements2 = $("*:contains('"+ str2 +"')").filter( function(){ return $(this).find("*:contains('"+ str2 +"')").length == 0 } ); elements2[0].style.fontWeight = 'normal'; if (typeof elements2[1] != "undefined"){ elements2[1].style.fontWeight = 'normal'; } }); points.forEach(function (p) { if (p.schemaInv == true) { p.DimON = d[0]; var str = p.DimON; var elements = $("*:contains('"+ str +"')").filter( function(){ return $(this).find("*:contains('"+ str +"')").length == 0 } ); elements[0].style.fontWeight = 'bold'; } }) } else{ correlationResultsFinal.forEach(function(corr){ var str2 = corr[0]; var elements2 = $("*:contains('"+ str2 +"')").filter( function(){ return $(this).find("*:contains('"+ str2 +"')").length == 0 } ); elements2[0].style.fontWeight = 'normal'; if (typeof elements2[1] != "undefined"){ elements2[1].style.fontWeight = 'normal'; } }); points.forEach(function (p) { p.DimON = null; }); } BetatSNE(points); }); //EXIT bar.exit() .remove(); }//update
JavaScript
function brushmove() { var extent = brush.extent(); //Reset the part that is visible on the big chart var originalRange = main_yZoom.range(); main_yZoom.domain( extent ); //Update the domain of the x & y scale of the big bar chart main_yScale.domain(correlationResultsFinal.map(function(d) { return d[0]; })); main_yScale.rangeBands( [ main_yZoom(originalRange[0]), main_yZoom(originalRange[1]) ], 0.4, 0); //Update the y axis of the big chart d3v3.select(".mainGroup") .select(".y.axis") .select("textLength","10") .call(main_yAxis); //Which bars are still "selected" var selected = mini_yScale.domain() .filter(function(d) { return (extent[0] - mini_yScale.rangeBand () + 1e-2 <= mini_yScale(d)) && (mini_yScale(d) <= extent[1] - 1e-2); }); //Update the colors of the mini chart - Make everything outside the brush grey d3.select(".miniGroup").selectAll(".bar") .style("fill", function(d, i) { return selected.indexOf(d[0]) > -1 ? "url(#gradient-mini)" : "#e0e0e0"; }); //Update the label size d3v3.selectAll(".y.axis text") .style("font-size", textScale(selected.length)); //Update the big bar chart updateBarChart(); }//brushmove
function brushmove() { var extent = brush.extent(); //Reset the part that is visible on the big chart var originalRange = main_yZoom.range(); main_yZoom.domain( extent ); //Update the domain of the x & y scale of the big bar chart main_yScale.domain(correlationResultsFinal.map(function(d) { return d[0]; })); main_yScale.rangeBands( [ main_yZoom(originalRange[0]), main_yZoom(originalRange[1]) ], 0.4, 0); //Update the y axis of the big chart d3v3.select(".mainGroup") .select(".y.axis") .select("textLength","10") .call(main_yAxis); //Which bars are still "selected" var selected = mini_yScale.domain() .filter(function(d) { return (extent[0] - mini_yScale.rangeBand () + 1e-2 <= mini_yScale(d)) && (mini_yScale(d) <= extent[1] - 1e-2); }); //Update the colors of the mini chart - Make everything outside the brush grey d3.select(".miniGroup").selectAll(".bar") .style("fill", function(d, i) { return selected.indexOf(d[0]) > -1 ? "url(#gradient-mini)" : "#e0e0e0"; }); //Update the label size d3v3.selectAll(".y.axis text") .style("font-size", textScale(selected.length)); //Update the big bar chart updateBarChart(); }//brushmove
JavaScript
function pearsonCorrelation(prefs, p1, p2) { var si = []; for (var key in prefs[p1]) { if (prefs[p2][key]) si.push(key); } var n = si.length; if (n == 0) return 0; var sum1 = 0; for (var i = 0; i < si.length; i++) sum1 += prefs[p1][si[i]]; var sum2 = 0; for (var i = 0; i < si.length; i++) sum2 += prefs[p2][si[i]]; var sum1Sq = 0; for (var i = 0; i < si.length; i++) { sum1Sq += Math.pow(prefs[p1][si[i]], 2); } var sum2Sq = 0; for (var i = 0; i < si.length; i++) { sum2Sq += Math.pow(prefs[p2][si[i]], 2); } var pSum = 0; for (var i = 0; i < si.length; i++) { pSum += prefs[p1][si[i]] * prefs[p2][si[i]]; } var num = pSum - (sum1 * sum2 / n); var den = Math.sqrt((sum1Sq - Math.pow(sum1, 2) / n) * (sum2Sq - Math.pow(sum2, 2) / n)); if (den == 0) return 0; return num / den; }
function pearsonCorrelation(prefs, p1, p2) { var si = []; for (var key in prefs[p1]) { if (prefs[p2][key]) si.push(key); } var n = si.length; if (n == 0) return 0; var sum1 = 0; for (var i = 0; i < si.length; i++) sum1 += prefs[p1][si[i]]; var sum2 = 0; for (var i = 0; i < si.length; i++) sum2 += prefs[p2][si[i]]; var sum1Sq = 0; for (var i = 0; i < si.length; i++) { sum1Sq += Math.pow(prefs[p1][si[i]], 2); } var sum2Sq = 0; for (var i = 0; i < si.length; i++) { sum2Sq += Math.pow(prefs[p2][si[i]], 2); } var pSum = 0; for (var i = 0; i < si.length; i++) { pSum += prefs[p1][si[i]] * prefs[p2][si[i]]; } var num = pSum - (sum1 * sum2 / n); var den = Math.sqrt((sum1Sq - Math.pow(sum1, 2) / n) * (sum2Sq - Math.pow(sum2, 2) / n)); if (den == 0) return 0; return num / den; }
JavaScript
function seed(Model, rows) { return (others={}) => { if (typeof rows === 'function') { rows = Promise.props( mapValues(others, other => // Is other a function? If so, call it. Otherwise, leave it alone. typeof other === 'function' ? other() : other) ).then(rows) } return Promise.resolve(rows) .then(rows => Promise.props( Object.keys(rows) .map(key => { const row = rows[key] return { key, value: Promise.props(row) .then(row => Model.create(row) .catch(error => { throw new BadRow(key, row, error) }) ) } }).reduce( (all, one) => Object.assign({}, all, {[one.key]: one.value}), {} ) ) ) .then(seeded => { console.log(`Seeded ${Object.keys(seeded).length} ${Model.name} OK`) return seeded }).catch(error => { console.error(`Error seeding ${Model.name}: ${error} \n${error.stack}`) }) } }
function seed(Model, rows) { return (others={}) => { if (typeof rows === 'function') { rows = Promise.props( mapValues(others, other => // Is other a function? If so, call it. Otherwise, leave it alone. typeof other === 'function' ? other() : other) ).then(rows) } return Promise.resolve(rows) .then(rows => Promise.props( Object.keys(rows) .map(key => { const row = rows[key] return { key, value: Promise.props(row) .then(row => Model.create(row) .catch(error => { throw new BadRow(key, row, error) }) ) } }).reduce( (all, one) => Object.assign({}, all, {[one.key]: one.value}), {} ) ) ) .then(seeded => { console.log(`Seeded ${Object.keys(seeded).length} ${Model.name} OK`) return seeded }).catch(error => { console.error(`Error seeding ${Model.name}: ${error} \n${error.stack}`) }) } }
JavaScript
function finishHTML() { let cards = ""; for (let i = 1; i < team.length; i++) { if (team[i].getRole() === "Manager") { cards = cards + managerCard(team[i]); } else if(team[i].getRole() === "Engineer") { cards = cards + engineerCard(team[i]) }else{ cards = cards + internCard(team[i]) } } fs.writeFile("./dist/index.html", bodyHTML(team[0], cards), function(err) { if (err) { console.log (err) } else { console.log(` =============================================================================== Team Profile complete! Check index.html in dist directory to see the output! =============================================================================== `); } }) }
function finishHTML() { let cards = ""; for (let i = 1; i < team.length; i++) { if (team[i].getRole() === "Manager") { cards = cards + managerCard(team[i]); } else if(team[i].getRole() === "Engineer") { cards = cards + engineerCard(team[i]) }else{ cards = cards + internCard(team[i]) } } fs.writeFile("./dist/index.html", bodyHTML(team[0], cards), function(err) { if (err) { console.log (err) } else { console.log(` =============================================================================== Team Profile complete! Check index.html in dist directory to see the output! =============================================================================== `); } }) }
JavaScript
async function handleCommand(interaction) { const command = interaction.client.commands.get(interaction.commandName) if (!command) return Promise.reject(`no command ${interaction.commandName}`) logger.info( { command: interaction.commandName, }, `command ${interaction.commandName} called` ) const policyResult = await PolicyChecker.check(command.policy, interaction) if (!policyResult.allowed) { return interaction.reply({ content: policyResult.errorMessages.join(". "), ephemeral: true, }) } if (!interaction.guild) { if (command.dm) return command.dm(interaction) return interaction.reply({ content: "This command does not work in DMs. Sorry!", ephemeral: true, }) } ParticipationCreator.findOrCreateByInteraction(interaction) return command.execute(interaction) }
async function handleCommand(interaction) { const command = interaction.client.commands.get(interaction.commandName) if (!command) return Promise.reject(`no command ${interaction.commandName}`) logger.info( { command: interaction.commandName, }, `command ${interaction.commandName} called` ) const policyResult = await PolicyChecker.check(command.policy, interaction) if (!policyResult.allowed) { return interaction.reply({ content: policyResult.errorMessages.join(". "), ephemeral: true, }) } if (!interaction.guild) { if (command.dm) return command.dm(interaction) return interaction.reply({ content: "This command does not work in DMs. Sorry!", ephemeral: true, }) } ParticipationCreator.findOrCreateByInteraction(interaction) return command.execute(interaction) }
JavaScript
async function handleAutocomplete(interaction) { const command = interaction.client.commands.get(interaction.commandName) if (!command) return Promise.reject( `no command ${interaction.commandName} (autocomplete)` ) const option = interaction.options.getFocused(true) const completer = command.autocomplete.get(option.name) if (!completer) return Promise.reject( `no autocomplete for option ${option.name} on command ${interaction.commandName}` ) return completer.complete(interaction) }
async function handleAutocomplete(interaction) { const command = interaction.client.commands.get(interaction.commandName) if (!command) return Promise.reject( `no command ${interaction.commandName} (autocomplete)` ) const option = interaction.options.getFocused(true) const completer = command.autocomplete.get(option.name) if (!completer) return Promise.reject( `no autocomplete for option ${option.name} on command ${interaction.commandName}` ) return completer.complete(interaction) }
JavaScript
function inCorrectEnv(interaction) { return ( !(process.env.NODE_ENV !== "development") == process.env.DEV_GUILDS.includes(interaction.guildId) ) }
function inCorrectEnv(interaction) { return ( !(process.env.NODE_ENV !== "development") == process.env.DEV_GUILDS.includes(interaction.guildId) ) }
JavaScript
execute(interaction) { if (!module.exports.inCorrectEnv(interaction)) return Promise.resolve("wrong guild for env") // handle command invocations if (interaction.isCommand() || interaction.isApplicationCommand()) { return module.exports.handleCommand(interaction).catch((err) => { console.log(err) logger.error( { origin: "command", error: err, guild: interaction.guildId, command: interaction.commandName, }, `Error while executing command ${interaction.commandName}` ) const fn = getReplyFn(interaction) return interaction[fn]({ content: "There was an error while executing this command!", components: [], ephemeral: true, }) }) } // handle autocomplete requests if (interaction.isAutocomplete()) { return module.exports.handleAutocomplete(interaction).catch((err) => { logger.error( { origin: "autocomplete", error: err, guild: interaction.guildId, command: interaction.commandName, option: interaction.options.getFocused(true), }, `Error while executing autocomplete for command ${interaction.commandName}` ) return interaction.respond([]) }) } }
execute(interaction) { if (!module.exports.inCorrectEnv(interaction)) return Promise.resolve("wrong guild for env") // handle command invocations if (interaction.isCommand() || interaction.isApplicationCommand()) { return module.exports.handleCommand(interaction).catch((err) => { console.log(err) logger.error( { origin: "command", error: err, guild: interaction.guildId, command: interaction.commandName, }, `Error while executing command ${interaction.commandName}` ) const fn = getReplyFn(interaction) return interaction[fn]({ content: "There was an error while executing this command!", components: [], ephemeral: true, }) }) } // handle autocomplete requests if (interaction.isAutocomplete()) { return module.exports.handleAutocomplete(interaction).catch((err) => { logger.error( { origin: "autocomplete", error: err, guild: interaction.guildId, command: interaction.commandName, option: interaction.options.getFocused(true), }, `Error while executing autocomplete for command ${interaction.commandName}` ) return interaction.respond([]) }) } }
JavaScript
static associate(models) { Guilds.hasMany(models.Games, { foreignKey: "guildId" }) Guilds.hasMany(models.Bans, { foreignKey: "bannableId", constraints: false, scope: { bannableType: "Guilds", }, }) Guilds.belongsToMany(models.Users, { through: models.Participations, foreignKey: "guildId" }) }
static associate(models) { Guilds.hasMany(models.Games, { foreignKey: "guildId" }) Guilds.hasMany(models.Bans, { foreignKey: "bannableId", constraints: false, scope: { bannableType: "Guilds", }, }) Guilds.belongsToMany(models.Users, { through: models.Participations, foreignKey: "guildId" }) }
JavaScript
static findBySnowflake(snowflake, options = {}) { if (!snowflake) return null return Guilds.findOne({ where: { snowflake: snowflake }, ...options, }) }
static findBySnowflake(snowflake, options = {}) { if (!snowflake) return null return Guilds.findOne({ where: { snowflake: snowflake }, ...options, }) }
JavaScript
static associate(models) { Logs.belongsTo(models.Feedback, { foreignKey: "loggableId", constraints: false, }) Logs.belongsTo(models.Bans, { foreignKey: "loggableId", constraints: false, }) Logs.belongsTo(models.Quotes, { foreignKey: "loggableId", constraints: false, }) Logs.belongsTo(models.Lines, { foreignKey: "loggableId", constraints: false, }) }
static associate(models) { Logs.belongsTo(models.Feedback, { foreignKey: "loggableId", constraints: false, }) Logs.belongsTo(models.Bans, { foreignKey: "loggableId", constraints: false, }) Logs.belongsTo(models.Quotes, { foreignKey: "loggableId", constraints: false, }) Logs.belongsTo(models.Lines, { foreignKey: "loggableId", constraints: false, }) }
JavaScript
static hook(models) { Logs.addHook("afterFind", (findResult) => { findResult = forceArray(findResult) for (const instance of findResult) { switch (instance.loggableType) { case "Feedback": if (instance.Feedback === undefined) break instance.loggable = instance.Feedback break case "Bans": if (instance.Bans === undefined) break instance.loggable = instance.Bans break case "Quotes": if (instance.Quotes === undefined) break instance.loggable = instance.Quotes break case "Lines": if (instance.Lines === undefined) break instance.loggable = instance.Lines break } // to prevent mistakes delete instance.Feedback delete instance.dataValues.Feedback delete instance.Bans delete instance.dataValues.Bans delete instance.Quotes delete instance.dataValues.Quotes delete instance.Lines delete instance.dataValues.Lines } }) }
static hook(models) { Logs.addHook("afterFind", (findResult) => { findResult = forceArray(findResult) for (const instance of findResult) { switch (instance.loggableType) { case "Feedback": if (instance.Feedback === undefined) break instance.loggable = instance.Feedback break case "Bans": if (instance.Bans === undefined) break instance.loggable = instance.Bans break case "Quotes": if (instance.Quotes === undefined) break instance.loggable = instance.Quotes break case "Lines": if (instance.Lines === undefined) break instance.loggable = instance.Lines break } // to prevent mistakes delete instance.Feedback delete instance.dataValues.Feedback delete instance.Bans delete instance.dataValues.Bans delete instance.Quotes delete instance.dataValues.Quotes delete instance.Lines delete instance.dataValues.Lines } }) }
JavaScript
async complete(interaction) { const data = await GamesForGuild.get(interaction.guildId.toString()) return interaction.respond( data .filter((game) => game.name.toLowerCase().includes(interaction.options.getFocused().toLowerCase())) .slice(0, 25) .map((game) => { return { name: game.name, value: game.name } }) ) }
async complete(interaction) { const data = await GamesForGuild.get(interaction.guildId.toString()) return interaction.respond( data .filter((game) => game.name.toLowerCase().includes(interaction.options.getFocused().toLowerCase())) .slice(0, 25) .map((game) => { return { name: game.name, value: game.name } }) ) }
JavaScript
static associate(models) { Bans.belongsTo(models.Users, { foreignKey: "bannableId", constraints: false, }) Bans.belongsTo(models.Guilds, { foreignKey: "bannableId", constraints: false, }) Bans.hasMany(models.Logs, { foreignKey: "loggableId", constraints: false, scope: { loggableType: "Bans", }, }) }
static associate(models) { Bans.belongsTo(models.Users, { foreignKey: "bannableId", constraints: false, }) Bans.belongsTo(models.Guilds, { foreignKey: "bannableId", constraints: false, }) Bans.hasMany(models.Logs, { foreignKey: "loggableId", constraints: false, scope: { loggableType: "Bans", }, }) }
JavaScript
static hook(models) { Bans.addHook("afterFind", (findResult) => { findResult = forceArray(findResult) for (const instance of findResult) { switch (instance.bannableType) { case "Users": if (instance.Users === undefined) break instance.bannable = instance.Users break case "Guilds": if (instance.Guilds === undefined) break instance.bannable = instance.Guilds break } // to prevent mistakes delete instance.Users delete instance.dataValues.Users delete instance.Guilds delete instance.dataValues.Guilds } }) }
static hook(models) { Bans.addHook("afterFind", (findResult) => { findResult = forceArray(findResult) for (const instance of findResult) { switch (instance.bannableType) { case "Users": if (instance.Users === undefined) break instance.bannable = instance.Users break case "Guilds": if (instance.Guilds === undefined) break instance.bannable = instance.Guilds break } // to prevent mistakes delete instance.Users delete instance.dataValues.Users delete instance.Guilds delete instance.dataValues.Guilds } }) }
JavaScript
function paginationControls(pageNum, total) { if (total <= PAGE_SIZE) return [] const actions = new MessageActionRow().addComponents( new MessageButton() .setCustomId("paginateBack") .setLabel("Back") .setStyle("SECONDARY") .setDisabled(pageNum == 1), new MessageButton() .setCustomId("paginateNext") .setLabel("Next") .setStyle("SECONDARY") .setDisabled(pageNum * PAGE_SIZE >= total) ) return [actions] }
function paginationControls(pageNum, total) { if (total <= PAGE_SIZE) return [] const actions = new MessageActionRow().addComponents( new MessageButton() .setCustomId("paginateBack") .setLabel("Back") .setStyle("SECONDARY") .setDisabled(pageNum == 1), new MessageButton() .setCustomId("paginateNext") .setLabel("Next") .setStyle("SECONDARY") .setDisabled(pageNum * PAGE_SIZE >= total) ) return [actions] }
JavaScript
static associate(models) { Games.belongsTo(models.Guilds, { foreignKey: "guildId" }) Games.hasMany(models.Quotes, { foreignKey: "gameId" }) Games.hasMany(models.DefaultGames, { foreignKey: "gameId" }) }
static associate(models) { Games.belongsTo(models.Guilds, { foreignKey: "guildId" }) Games.hasMany(models.Quotes, { foreignKey: "gameId" }) Games.hasMany(models.DefaultGames, { foreignKey: "gameId" }) }
JavaScript
async complete(interaction) { const data = await GamesForGuild.get(interaction.guildId.toString()) const options = data .filter((game) => game.name.toLowerCase().includes(interaction.options.getFocused().toLowerCase())) .slice(0, 24) .map((game) => { return { name: game.name, value: game.name } }) if (data.length > 1) options.push({ name: "All Games", value: ALL_GAMES}) return interaction.respond(options) }
async complete(interaction) { const data = await GamesForGuild.get(interaction.guildId.toString()) const options = data .filter((game) => game.name.toLowerCase().includes(interaction.options.getFocused().toLowerCase())) .slice(0, 24) .map((game) => { return { name: game.name, value: game.name } }) if (data.length > 1) options.push({ name: "All Games", value: ALL_GAMES}) return interaction.respond(options) }
JavaScript
async function promptForGame(interaction, guild) { const gameSelectRow = new MessageActionRow().addComponents( new MessageSelectMenu() .setCustomId("newQuoteGameSelect") .setPlaceholder("Pick a game") .addOptions(GameSelectTransformer.transform(guild.Games)) ) const gameSelectMessage = await interaction.reply({ content: "Which game is this quote from?", components: [gameSelectRow], ephemeral: true, fetchReply: true, }) const filter = (i) => { i.deferUpdate() return i.user.id === interaction.user.id } return gameSelectMessage.awaitMessageComponent({ filter, componentType: 'SELECT_MENU', time: 60000 }) .then(async (i) => { const game = await Games.findByPk(i.values[0]) await interaction.editReply({ content: `Saving your quote to ${game.name}...`, components: [] }) return game }) .catch(async (err) => { if(err.code == 'INTERACTION_COLLECTOR_ERROR') { await interaction.editReply({ content: "You didn't pick a game, so I could not save the quote!", components: [] }) return null } else { throw err } }) }
async function promptForGame(interaction, guild) { const gameSelectRow = new MessageActionRow().addComponents( new MessageSelectMenu() .setCustomId("newQuoteGameSelect") .setPlaceholder("Pick a game") .addOptions(GameSelectTransformer.transform(guild.Games)) ) const gameSelectMessage = await interaction.reply({ content: "Which game is this quote from?", components: [gameSelectRow], ephemeral: true, fetchReply: true, }) const filter = (i) => { i.deferUpdate() return i.user.id === interaction.user.id } return gameSelectMessage.awaitMessageComponent({ filter, componentType: 'SELECT_MENU', time: 60000 }) .then(async (i) => { const game = await Games.findByPk(i.values[0]) await interaction.editReply({ content: `Saving your quote to ${game.name}...`, components: [] }) return game }) .catch(async (err) => { if(err.code == 'INTERACTION_COLLECTOR_ERROR') { await interaction.editReply({ content: "You didn't pick a game, so I could not save the quote!", components: [] }) return null } else { throw err } }) }
JavaScript
scopeMention() { switch (this.target_type) { case DefaultGames.TYPE_GUILD: return "the server" case DefaultGames.TYPE_CHANNEL: return channelMention(this.target_snowflake) } }
scopeMention() { switch (this.target_type) { case DefaultGames.TYPE_GUILD: return "the server" case DefaultGames.TYPE_CHANNEL: return channelMention(this.target_snowflake) } }
JavaScript
async check(policies, interaction) { if (!policies) return new PolicyResult() return Promise.all( forceArray(policies).map((policy) => policy.allow(interaction).then((allowed) => { return { result: allowed, errorMessage: policy.errorMessage } }) ) ).then((allResults) => { const errorLines = [] const allowed = allResults.reduce( (accumulator, curr) => { if (!curr.result) errorLines.push(curr.errorMessage) return accumulator && curr.result }, { result: true } ) return new PolicyResult(allowed, errorLines) }) }
async check(policies, interaction) { if (!policies) return new PolicyResult() return Promise.all( forceArray(policies).map((policy) => policy.allow(interaction).then((allowed) => { return { result: allowed, errorMessage: policy.errorMessage } }) ) ).then((allResults) => { const errorLines = [] const allowed = allResults.reduce( (accumulator, curr) => { if (!curr.result) errorLines.push(curr.errorMessage) return accumulator && curr.result }, { result: true } ) return new PolicyResult(allowed, errorLines) }) }
JavaScript
function hashGlobalCommandJSON() { // Quick hash function courtesy of https://stackoverflow.com/users/815680/bryc found // at https://stackoverflow.com/a/52171480 const cyrb53 = function(str, seed = 0) { let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed; for (let i = 0, ch; i < str.length; i++) { ch = str.charCodeAt(i); h1 = Math.imul(h1 ^ ch, 2654435761); h2 = Math.imul(h2 ^ ch, 1597334677); } h1 = Math.imul(h1 ^ (h1>>>16), 2246822507) ^ Math.imul(h2 ^ (h2>>>13), 3266489909); h2 = Math.imul(h2 ^ (h2>>>16), 2246822507) ^ Math.imul(h1 ^ (h1>>>13), 3266489909); return (h2>>>0).toString(16).padStart(8,0)+(h1>>>0).toString(16).padStart(8,0); }; // use fn from module.exports so we can mock it out in tests return cyrb53(JSON.stringify(module.exports.buildGlobalCommandJSON())) }
function hashGlobalCommandJSON() { // Quick hash function courtesy of https://stackoverflow.com/users/815680/bryc found // at https://stackoverflow.com/a/52171480 const cyrb53 = function(str, seed = 0) { let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed; for (let i = 0, ch; i < str.length; i++) { ch = str.charCodeAt(i); h1 = Math.imul(h1 ^ ch, 2654435761); h2 = Math.imul(h2 ^ ch, 1597334677); } h1 = Math.imul(h1 ^ (h1>>>16), 2246822507) ^ Math.imul(h2 ^ (h2>>>13), 3266489909); h2 = Math.imul(h2 ^ (h2>>>16), 2246822507) ^ Math.imul(h1 ^ (h1>>>13), 3266489909); return (h2>>>0).toString(16).padStart(8,0)+(h1>>>0).toString(16).padStart(8,0); }; // use fn from module.exports so we can mock it out in tests return cyrb53(JSON.stringify(module.exports.buildGlobalCommandJSON())) }
JavaScript
async function deployGlobals(hash = null) { if(hash) { const newHash = module.exports.hashGlobalCommandJSON() if (hash === newHash) { logger.info("Global commands have not changed, skipping deploy") return } } logger.info("Deploying global commands") return restClient() .put(Routes.applicationCommands(clientId), { body: buildGlobalCommandJSON(), }) .catch((error) => { logger.warn(`Error deploying global commands: ${error}`) }) .finally(() => { logger.info("Done with globals") }) }
async function deployGlobals(hash = null) { if(hash) { const newHash = module.exports.hashGlobalCommandJSON() if (hash === newHash) { logger.info("Global commands have not changed, skipping deploy") return } } logger.info("Deploying global commands") return restClient() .put(Routes.applicationCommands(clientId), { body: buildGlobalCommandJSON(), }) .catch((error) => { logger.warn(`Error deploying global commands: ${error}`) }) .finally(() => { logger.info("Done with globals") }) }
JavaScript
async function deployDev() { const devFlakes = JSON.parse(process.env.DEV_GUILDS) const guilds = await Guilds.findAll({ where: { snowflake: devFlakes } }) logger.info("Deploying global commands as guild commands to dev servers") const commandJSON = buildGlobalCommandJSON() return Promise .all(guilds.map(guild => restClient() .put(Routes.applicationGuildCommands(clientId, guild.snowflake), { body: commandJSON, }) .catch((error) => { logger.warn(`Error deploying commands to guild ${guild.name}: ${error}`) }) .finally(() => { logger.info(`Deployed to guild ${guild.name}`) }))) .finally(() => { logger.info("Done with dev guilds") }) }
async function deployDev() { const devFlakes = JSON.parse(process.env.DEV_GUILDS) const guilds = await Guilds.findAll({ where: { snowflake: devFlakes } }) logger.info("Deploying global commands as guild commands to dev servers") const commandJSON = buildGlobalCommandJSON() return Promise .all(guilds.map(guild => restClient() .put(Routes.applicationGuildCommands(clientId, guild.snowflake), { body: commandJSON, }) .catch((error) => { logger.warn(`Error deploying commands to guild ${guild.name}: ${error}`) }) .finally(() => { logger.info(`Deployed to guild ${guild.name}`) }))) .finally(() => { logger.info("Done with dev guilds") }) }
JavaScript
static associate(models) { Lines.belongsTo(models.Quotes, { foreignKey: "quoteId" }) Lines.belongsTo(models.Users, { as: "speaker", foreignKey: "speakerId" }) Lines.hasMany(models.Logs, { foreignKey: "loggableId", constraints: false, scope: { loggableType: "Lines", }, }) }
static associate(models) { Lines.belongsTo(models.Quotes, { foreignKey: "quoteId" }) Lines.belongsTo(models.Users, { as: "speaker", foreignKey: "speakerId" }) Lines.hasMany(models.Logs, { foreignKey: "loggableId", constraints: false, scope: { loggableType: "Lines", }, }) }
JavaScript
static associate(models) { Quotes.belongsTo(models.Games, { foreignKey: "gameId" }) Quotes.hasMany(models.Lines, { foreignKey: "quoteId" }) Quotes.belongsTo(models.Users, { as: "quoter", foreignKey: "quoterId" }) Quotes.hasMany(models.QuoteEditCodes, { foreignKey: "quoteId" }) Quotes.hasMany(models.Logs, { foreignKey: "loggableId", constraints: false, scope: { loggableType: "Quotes", }, }) }
static associate(models) { Quotes.belongsTo(models.Games, { foreignKey: "gameId" }) Quotes.hasMany(models.Lines, { foreignKey: "quoteId" }) Quotes.belongsTo(models.Users, { as: "quoter", foreignKey: "quoterId" }) Quotes.hasMany(models.QuoteEditCodes, { foreignKey: "quoteId" }) Quotes.hasMany(models.Logs, { foreignKey: "loggableId", constraints: false, scope: { loggableType: "Quotes", }, }) }
JavaScript
static associate(models) { Feedback.belongsTo(models.Users, { as: "reporter", foreignKey: "reporterId", }) Feedback.hasMany(models.Logs, { foreignKey: "loggableId", constraints: false, scope: { loggableType: "Feedback", }, }) }
static associate(models) { Feedback.belongsTo(models.Users, { as: "reporter", foreignKey: "reporterId", }) Feedback.hasMany(models.Logs, { foreignKey: "loggableId", constraints: false, scope: { loggableType: "Feedback", }, }) }
JavaScript
async function updateOrCreate(quote) { const [editCode, _isNew] = await QuoteEditCodes.findOrCreate({ where: { quoteId: quote.id }, defaults: { shortcode: randomBytes(3).toString("hex").substring(0, 5), expiresAt: addMinutes(new Date(), DURATION), }, }) if (editCode.expiresAt <= new Date()) { await editCode.update({ shortcode: randomBytes(3).toString("hex").substring(0, 5), expiresAt: addMinutes(new Date(), DURATION), }) } return editCode }
async function updateOrCreate(quote) { const [editCode, _isNew] = await QuoteEditCodes.findOrCreate({ where: { quoteId: quote.id }, defaults: { shortcode: randomBytes(3).toString("hex").substring(0, 5), expiresAt: addMinutes(new Date(), DURATION), }, }) if (editCode.expiresAt <= new Date()) { await editCode.update({ shortcode: randomBytes(3).toString("hex").substring(0, 5), expiresAt: addMinutes(new Date(), DURATION), }) } return editCode }
JavaScript
async findOrCreateByInteraction(interaction) { if (!interaction.guildId) return null const [guild, _isNewGuild] = await Guilds.findOrCreate({ where: { snowflake: interaction.guildId.toString(), }, defaults: { name: interaction.guild.name, }, }) const [user, _isNewUser] = await Users.findOrCreate({ where: { snowflake: interaction.user.id.toString() }, defaults: { name: interaction.user.username, } }) return Participations.findOrCreate({ where: { userId: user.id, guildId: guild.id, } }) }
async findOrCreateByInteraction(interaction) { if (!interaction.guildId) return null const [guild, _isNewGuild] = await Guilds.findOrCreate({ where: { snowflake: interaction.guildId.toString(), }, defaults: { name: interaction.guild.name, }, }) const [user, _isNewUser] = await Users.findOrCreate({ where: { snowflake: interaction.user.id.toString() }, defaults: { name: interaction.user.username, } }) return Participations.findOrCreate({ where: { userId: user.id, guildId: guild.id, } }) }
JavaScript
static associate(models) { Users.hasMany(models.Lines, { foreignKey: "speakerId" }) Users.hasMany(models.Quotes, { foreignKey: "quoterId" }) Users.hasMany(models.Feedback, { foreignKey: "reporterId" }) Users.hasMany(models.Bans, { foreignKey: "bannableId", constraints: false, scope: { bannableType: "Users", }, }) Users.belongsToMany(models.Guilds, { through: models.Participations, foreignKey: "userId" }) }
static associate(models) { Users.hasMany(models.Lines, { foreignKey: "speakerId" }) Users.hasMany(models.Quotes, { foreignKey: "quoterId" }) Users.hasMany(models.Feedback, { foreignKey: "reporterId" }) Users.hasMany(models.Bans, { foreignKey: "bannableId", constraints: false, scope: { bannableType: "Users", }, }) Users.belongsToMany(models.Guilds, { through: models.Participations, foreignKey: "userId" }) }
JavaScript
static async findBySnowflake(snowflake, options = {}) { if (!snowflake) return null return Users.findOne({ where: { snowflake: snowflake }, ...options, }) }
static async findBySnowflake(snowflake, options = {}) { if (!snowflake) return null return Users.findOne({ where: { snowflake: snowflake }, ...options, }) }
JavaScript
async memberOrAnonymous(guild, user) { if (user.id === process.env.CLIENT_ID) { return module.exports.anonymousMember } return guild.members.fetch(user) }
async memberOrAnonymous(guild, user) { if (user.id === process.env.CLIENT_ID) { return module.exports.anonymousMember } return guild.members.fetch(user) }
JavaScript
function render() { /* This array holds the relative URL to the image used * for that particular row of the game level. */ if (play === true) { document.getElementById('counter').hidden = false; document.getElementById('easy').hidden = true; document.getElementById('medium').hidden = true; document.getElementById('hard').hidden = true; gameDescription = ""; var rowImages = [ 'images/water-block.png', // Top row is water 'images/grass-block.png', // Row 1 of 6 is grass 'images/grass-block.png', // Row 2 of 6 is grass 'images/grass-block.png', // Row 3 of 6 is grass 'images/grass-block.png', // Row 4 of 6 is grass 'images/grass-block.png', // Row 5 of 6 is grass 'images/grass-block.png', // Row 6 of 6 is grass 'images/stone-block.png', // Bottom row is stone ], numRows = 8, numCols = 8, row, col; /* Loop through the number of rows and columns we've defined above * and, using the rowImages array, draw the correct image for that * portion of the "grid" */ for (row = 0; row < numRows; row++) { for (col = 0; col < numCols; col++) { /* The drawImage function of the canvas' context element * requires 3 parameters: the image to draw, the x coordinate * to start drawing and the y coordinate to start drawing. * We're using our Resources helpers to refer to our images * so that we get the benefits of caching these images, since * we're using them over and over. */ ctx.drawImage(Resources.get(rowImages[row]), col * 101, row * 83); } } renderEntities(); } else { startScreen(); } }
function render() { /* This array holds the relative URL to the image used * for that particular row of the game level. */ if (play === true) { document.getElementById('counter').hidden = false; document.getElementById('easy').hidden = true; document.getElementById('medium').hidden = true; document.getElementById('hard').hidden = true; gameDescription = ""; var rowImages = [ 'images/water-block.png', // Top row is water 'images/grass-block.png', // Row 1 of 6 is grass 'images/grass-block.png', // Row 2 of 6 is grass 'images/grass-block.png', // Row 3 of 6 is grass 'images/grass-block.png', // Row 4 of 6 is grass 'images/grass-block.png', // Row 5 of 6 is grass 'images/grass-block.png', // Row 6 of 6 is grass 'images/stone-block.png', // Bottom row is stone ], numRows = 8, numCols = 8, row, col; /* Loop through the number of rows and columns we've defined above * and, using the rowImages array, draw the correct image for that * portion of the "grid" */ for (row = 0; row < numRows; row++) { for (col = 0; col < numCols; col++) { /* The drawImage function of the canvas' context element * requires 3 parameters: the image to draw, the x coordinate * to start drawing and the y coordinate to start drawing. * We're using our Resources helpers to refer to our images * so that we get the benefits of caching these images, since * we're using them over and over. */ ctx.drawImage(Resources.get(rowImages[row]), col * 101, row * 83); } } renderEntities(); } else { startScreen(); } }
JavaScript
function startScreen() { document.getElementById('counter').hidden = true; ctx.drawImage(Resources.get('images/background.jpg'), canvas.width, canvas.height); //variables for game description const gameDescription = "Collect all the gems and reach the water by avoiding the bugs."; const gameDescription2 ="Collect hearts to gain life."; const gameDescription3 = "Remember: You can't go through the stones."; const control = "Move your player using arrow keys."; ctx.font = '20pt cursive'; ctx.textAlign = 'center'; ctx.fillStyle = 'red'; ctx.fillText(gameDescription, canvas.width/2, 72); ctx.fillText(gameDescription2, canvas.width/2, 100); ctx.fillText(gameDescription3, canvas.width/2, 130); ctx.fillText(control, canvas.width/2, 160); ctx.font = "20pt cursive"; ctx.textAlign = 'center'; ctx.fillStyle = "Yellow"; ctx.fillText("Choose your Difficulty", canvas.width/2, 235); ctx.font = "20pt cursive"; ctx.textAlign = 'center'; ctx.fillStyle = "#159753"; ctx.fillText("Choose your character and press enter to start game", (canvas.width*0.5), 348); function loadRender() { for (col = 0; col <5; col++) { ctx.drawImage(Resources.get("images/stone-block.png"), col * 101 + 152, 400); } selector.render(); for (var i = 0; i < chars.length; i++) { ctx.drawImage(Resources.get(chars[i]), i * 101 + 152, 350); } } loadRender(); }
function startScreen() { document.getElementById('counter').hidden = true; ctx.drawImage(Resources.get('images/background.jpg'), canvas.width, canvas.height); //variables for game description const gameDescription = "Collect all the gems and reach the water by avoiding the bugs."; const gameDescription2 ="Collect hearts to gain life."; const gameDescription3 = "Remember: You can't go through the stones."; const control = "Move your player using arrow keys."; ctx.font = '20pt cursive'; ctx.textAlign = 'center'; ctx.fillStyle = 'red'; ctx.fillText(gameDescription, canvas.width/2, 72); ctx.fillText(gameDescription2, canvas.width/2, 100); ctx.fillText(gameDescription3, canvas.width/2, 130); ctx.fillText(control, canvas.width/2, 160); ctx.font = "20pt cursive"; ctx.textAlign = 'center'; ctx.fillStyle = "Yellow"; ctx.fillText("Choose your Difficulty", canvas.width/2, 235); ctx.font = "20pt cursive"; ctx.textAlign = 'center'; ctx.fillStyle = "#159753"; ctx.fillText("Choose your character and press enter to start game", (canvas.width*0.5), 348); function loadRender() { for (col = 0; col <5; col++) { ctx.drawImage(Resources.get("images/stone-block.png"), col * 101 + 152, 400); } selector.render(); for (var i = 0; i < chars.length; i++) { ctx.drawImage(Resources.get(chars[i]), i * 101 + 152, 350); } } loadRender(); }
JavaScript
function toolbarChangeHandler() { var updatedUrl, value, field = this, params = {}; // Detect if field is a select menu or a checkbox if ( "selectedIndex" in field ) { value = field.options[ field.selectedIndex ].value || undefined; } else { value = field.checked ? ( field.defaultValue || true ) : undefined; } params[ field.name ] = value; updatedUrl = QUnit.url( params ); if ( "hidepassed" === field.name && "replaceState" in window.history ) { config[ field.name ] = value || false; if ( value ) { addClass( id( "qunit-tests" ), "hidepass" ); } else { removeClass( id( "qunit-tests" ), "hidepass" ); } // It is not necessary to refresh the whole page window.history.replaceState( null, "", updatedUrl ); } else { window.location = updatedUrl; } }
function toolbarChangeHandler() { var updatedUrl, value, field = this, params = {}; // Detect if field is a select menu or a checkbox if ( "selectedIndex" in field ) { value = field.options[ field.selectedIndex ].value || undefined; } else { value = field.checked ? ( field.defaultValue || true ) : undefined; } params[ field.name ] = value; updatedUrl = QUnit.url( params ); if ( "hidepassed" === field.name && "replaceState" in window.history ) { config[ field.name ] = value || false; if ( value ) { addClass( id( "qunit-tests" ), "hidepass" ); } else { removeClass( id( "qunit-tests" ), "hidepass" ); } // It is not necessary to refresh the whole page window.history.replaceState( null, "", updatedUrl ); } else { window.location = updatedUrl; } }
JavaScript
function generarPDF() { var jsPDF = require('jspdf'); require('jspdf-autotable'); let pdf = new jsPDF('p', 'pt'); let res = pdf.autoTableHtmlToJson(document.getElementById('tablaPedidos')); let res2 = pdf.autoTableHtmlToJson(document.getElementById('tableinfo')); let res3 = pdf.autoTableHtmlToJson(document.getElementById('table-bottom')); pdf.autoTable(res2.columns, res2.data, { startY: false, tableWidth: 'auto', columnWidth: 'auto', styles: { overflow: 'linebreak' }, margin: {top: 75} }); pdf.autoTable(res.columns, res.data, { startY: pdf.autoTableEndPosY() + 10, tableWidth: 'auto', columnWidth: 'auto', styles: { overflow: 'linebreak' }, theme: 'grid', margin: {top: 150} }); pdf.autoTable(res3.columns, res3.data, { startY: pdf.autoTableEndPosY() + 20, tableWidth: 'auto', columnWidth: 'auto', styles: { overflow: 'linebreak', fillColor: [255, 255, 255], textColor: [0, 0, 0], }, margin: {top: 150}, theme: 'grid', // 'striped', 'grid', tableLineColor: [255, 255, 255] }); pdf.save('Pedido.pdf'); pdf.output('dataurlnewwindow'); }
function generarPDF() { var jsPDF = require('jspdf'); require('jspdf-autotable'); let pdf = new jsPDF('p', 'pt'); let res = pdf.autoTableHtmlToJson(document.getElementById('tablaPedidos')); let res2 = pdf.autoTableHtmlToJson(document.getElementById('tableinfo')); let res3 = pdf.autoTableHtmlToJson(document.getElementById('table-bottom')); pdf.autoTable(res2.columns, res2.data, { startY: false, tableWidth: 'auto', columnWidth: 'auto', styles: { overflow: 'linebreak' }, margin: {top: 75} }); pdf.autoTable(res.columns, res.data, { startY: pdf.autoTableEndPosY() + 10, tableWidth: 'auto', columnWidth: 'auto', styles: { overflow: 'linebreak' }, theme: 'grid', margin: {top: 150} }); pdf.autoTable(res3.columns, res3.data, { startY: pdf.autoTableEndPosY() + 20, tableWidth: 'auto', columnWidth: 'auto', styles: { overflow: 'linebreak', fillColor: [255, 255, 255], textColor: [0, 0, 0], }, margin: {top: 150}, theme: 'grid', // 'striped', 'grid', tableLineColor: [255, 255, 255] }); pdf.save('Pedido.pdf'); pdf.output('dataurlnewwindow'); }
JavaScript
function handleClientPing (socket, host, port, data) { const parser = createDeserializer(true); const serializer = createSerializer(true); parser.on('data', (parsed) => { if (parsed.data.name === 'unconnected_ping') { for (const connector of Object.values(connectors)) { if (connector.remoteServerID !== null) { const updatedServerName = connector.remoteServerName.replace(connector.privatePort, connector.publicPort); serializer.write({ name: 'unconnected_pong', params: { pingID: parsed.data.params.pingID, serverID: connector.remoteServerID, magic: connector.remoteServerMagic, serverName: updatedServerName } }); } } } else { console.error('Received unexpected packet on listen port:', parsed.data.name); } }); serializer.on('data', (chunk) => { socket.send(chunk, 0, chunk.length, port, host); }); parser.write(data); }
function handleClientPing (socket, host, port, data) { const parser = createDeserializer(true); const serializer = createSerializer(true); parser.on('data', (parsed) => { if (parsed.data.name === 'unconnected_ping') { for (const connector of Object.values(connectors)) { if (connector.remoteServerID !== null) { const updatedServerName = connector.remoteServerName.replace(connector.privatePort, connector.publicPort); serializer.write({ name: 'unconnected_pong', params: { pingID: parsed.data.params.pingID, serverID: connector.remoteServerID, magic: connector.remoteServerMagic, serverName: updatedServerName } }); } } } else { console.error('Received unexpected packet on listen port:', parsed.data.name); } }); serializer.on('data', (chunk) => { socket.send(chunk, 0, chunk.length, port, host); }); parser.write(data); }
JavaScript
static isThisABotCommand(message) { const commandCandidate = message.content.split(" ")[0]; const isThisABotCommandResult = commandCandidate === command; //console.log({ isThisABotCommandResult, commandCandidate }); return isThisABotCommandResult; }
static isThisABotCommand(message) { const commandCandidate = message.content.split(" ")[0]; const isThisABotCommandResult = commandCandidate === command; //console.log({ isThisABotCommandResult, commandCandidate }); return isThisABotCommandResult; }
JavaScript
static evaluateDiceRoll(diceRoll) { const dieType = diceRoll.getDieType(); let evalResult = Math.floor(Math.random() * Math.floor(dieType)) + 1; console.log({ evalResult }) return evalResult; }
static evaluateDiceRoll(diceRoll) { const dieType = diceRoll.getDieType(); let evalResult = Math.floor(Math.random() * Math.floor(dieType)) + 1; console.log({ evalResult }) return evalResult; }
JavaScript
static evaluateDiceRollArgument(diceRoll) { const rollMultiplier = diceRoll.getRollMultiplier(); let resultingTotal = 0; let evaluatedString = ""; for (let i = 0; i < rollMultiplier; i++) { let rollResult = this.evaluateDiceRoll(diceRoll); resultingTotal += rollResult; if (rollMultiplier === (i + 1)) { evaluatedString += rollResult } else { evaluatedString += `${rollResult} + `; } } let finalString = `\`${evaluatedString}(${diceRoll.getAddition()}) = ${resultingTotal + parseInt(diceRoll.getAddition())}\`` console.log(finalString) return finalString; }
static evaluateDiceRollArgument(diceRoll) { const rollMultiplier = diceRoll.getRollMultiplier(); let resultingTotal = 0; let evaluatedString = ""; for (let i = 0; i < rollMultiplier; i++) { let rollResult = this.evaluateDiceRoll(diceRoll); resultingTotal += rollResult; if (rollMultiplier === (i + 1)) { evaluatedString += rollResult } else { evaluatedString += `${rollResult} + `; } } let finalString = `\`${evaluatedString}(${diceRoll.getAddition()}) = ${resultingTotal + parseInt(diceRoll.getAddition())}\`` console.log(finalString) return finalString; }
JavaScript
start() { var twitterIsReady = setInterval(function () { let version = '1.1.0'; let name = 'Queer wisdom for Twitter'; let copyright = '(c) 2021 • Stephanie Fuchs • https://github.com/stephfuchs'; let classes = '.css-1dbjc4n.r-1awozwy.r-18u37iz.r-156q2ks'; if (document.querySelector(classes) !== null || document.querySelector(classes) !== undefined) { let wisdom = new QueerWisdom(); console.info('loaded script: "' + name + '" with version: ' + version + '\n' + copyright); clearInterval(twitterIsReady); console.debug(wisdom.debug + 'removed interval'); wisdom.init(); console.debug(wisdom.debug + 'created new wisdom object'); } }, 3000); // check every 3sec /** * Check the system every min whether the button is been missing. */ setInterval(function () { if (document.getElementById('queer_wisdom') === null) { console.debug('Button was deleted. Restarts.'); let wisdom = new QueerWisdom(); wisdom.init(); console.info('reloaded the queer button, because it disappeared.'); console.debug('Restart finished.'); } }, 60000); // check every minute }
start() { var twitterIsReady = setInterval(function () { let version = '1.1.0'; let name = 'Queer wisdom for Twitter'; let copyright = '(c) 2021 • Stephanie Fuchs • https://github.com/stephfuchs'; let classes = '.css-1dbjc4n.r-1awozwy.r-18u37iz.r-156q2ks'; if (document.querySelector(classes) !== null || document.querySelector(classes) !== undefined) { let wisdom = new QueerWisdom(); console.info('loaded script: "' + name + '" with version: ' + version + '\n' + copyright); clearInterval(twitterIsReady); console.debug(wisdom.debug + 'removed interval'); wisdom.init(); console.debug(wisdom.debug + 'created new wisdom object'); } }, 3000); // check every 3sec /** * Check the system every min whether the button is been missing. */ setInterval(function () { if (document.getElementById('queer_wisdom') === null) { console.debug('Button was deleted. Restarts.'); let wisdom = new QueerWisdom(); wisdom.init(); console.info('reloaded the queer button, because it disappeared.'); console.debug('Restart finished.'); } }, 60000); // check every minute }
JavaScript
_createQueerElement() { this.queerElement = document.createElement('a'); this.queerElement.id = this.queerElementId; this.queerElement.style.paddingLeft = '10px'; this.queerElement.title = 'add a random queer wisdom'; this.queerElement.innerHTML = this._getFlagSVG(); this.queerElement.setAttribute('href', 'https://twitter.com/intent/tweet?text=' + encodeURI(this._getJsonWisdom())); console.debug(this.debug + 'Created tweet: https://twitter.com/intent/tweet?text=' + encodeURI(this._getJsonWisdom())); }
_createQueerElement() { this.queerElement = document.createElement('a'); this.queerElement.id = this.queerElementId; this.queerElement.style.paddingLeft = '10px'; this.queerElement.title = 'add a random queer wisdom'; this.queerElement.innerHTML = this._getFlagSVG(); this.queerElement.setAttribute('href', 'https://twitter.com/intent/tweet?text=' + encodeURI(this._getJsonWisdom())); console.debug(this.debug + 'Created tweet: https://twitter.com/intent/tweet?text=' + encodeURI(this._getJsonWisdom())); }
JavaScript
function leerDatosCurso(curso){ // console.log(curso) const infoCurso = { img: curso.querySelector('img').src, titulo : curso.querySelector('.info-card h4').textContent, precio: curso.querySelector('.info-card .precio span').textContent, id: curso.querySelector('.info-card a').getAttribute('data-id'), cantidad: 1 } // console.log(infoCurso) //todo: revisa si ya existe un elemento const existe = articulosCarrito.some( (curso) => curso.id === infoCurso.id); // console.log(existe) if(existe){ const cursos = articulosCarrito.map((curso) => { if(curso.id === infoCurso.id){ curso.cantidad++; return curso //!retorna objetos actualizados en la cantidad }else{ return curso //! retorna el objeto tal cual } } ); articulosCarrito = [...cursos] }else{ //todo: agrega articulos al carrito articulosCarrito = [...articulosCarrito,infoCurso] } // console.log(articulosCarrito); carritoHtml() }
function leerDatosCurso(curso){ // console.log(curso) const infoCurso = { img: curso.querySelector('img').src, titulo : curso.querySelector('.info-card h4').textContent, precio: curso.querySelector('.info-card .precio span').textContent, id: curso.querySelector('.info-card a').getAttribute('data-id'), cantidad: 1 } // console.log(infoCurso) //todo: revisa si ya existe un elemento const existe = articulosCarrito.some( (curso) => curso.id === infoCurso.id); // console.log(existe) if(existe){ const cursos = articulosCarrito.map((curso) => { if(curso.id === infoCurso.id){ curso.cantidad++; return curso //!retorna objetos actualizados en la cantidad }else{ return curso //! retorna el objeto tal cual } } ); articulosCarrito = [...cursos] }else{ //todo: agrega articulos al carrito articulosCarrito = [...articulosCarrito,infoCurso] } // console.log(articulosCarrito); carritoHtml() }
JavaScript
function carritoHtml(){ //* limpia el html limpiarHtml() //*recorre carrito y genera html articulosCarrito.forEach((curso) =>{ const {img,titulo,precio,cantidad,id} = curso const row = document.createElement('tr') row.innerHTML = ` <td><img src ="${img}" width="120"></td> <td> ${titulo} </td> <td>${precio}</td> <td>${cantidad}</td> <td> <a href="#" class= "borrar-curso" data-id="${id}"> X </a> </td> ` contenidoCarrito.appendChild(row) }); }
function carritoHtml(){ //* limpia el html limpiarHtml() //*recorre carrito y genera html articulosCarrito.forEach((curso) =>{ const {img,titulo,precio,cantidad,id} = curso const row = document.createElement('tr') row.innerHTML = ` <td><img src ="${img}" width="120"></td> <td> ${titulo} </td> <td>${precio}</td> <td>${cantidad}</td> <td> <a href="#" class= "borrar-curso" data-id="${id}"> X </a> </td> ` contenidoCarrito.appendChild(row) }); }
JavaScript
resolvePath(path) { if (path === null || path === undefined) return path; // already fully qualified if (path.indexOf('.') !== -1) return path; // the name of a knot - doesn't need further qualification if (this._story.KnotContainerWithName(path)) return path; // getting the current knot is *really* hacky const previousPath = this._story.state.callStack.currentThread.previousPointer.path.toString(); const dotIndex = previousPath.indexOf('.'); const currentKnot = dotIndex === -1 ? previousPath : previousPath.substring(0, dotIndex); return currentKnot + '.' + path; }
resolvePath(path) { if (path === null || path === undefined) return path; // already fully qualified if (path.indexOf('.') !== -1) return path; // the name of a knot - doesn't need further qualification if (this._story.KnotContainerWithName(path)) return path; // getting the current knot is *really* hacky const previousPath = this._story.state.callStack.currentThread.previousPointer.path.toString(); const dotIndex = previousPath.indexOf('.'); const currentKnot = dotIndex === -1 ? previousPath : previousPath.substring(0, dotIndex); return currentKnot + '.' + path; }
JavaScript
function Url1() { for (var i = 0; i < main2.Rounds1.length; i++) { for (var j = 0; j < main2.Rounds1[i].matches.length; j++) { main2.firstApiRounds.push(main2.Rounds1[i].matches[j]); } } for (var i = 0; i < main2.firstApiRounds.length; i++) { if ((main2.firstApiRounds[i].team1.key === main.teamkey || main2.firstApiRounds[i].team2.key === main.teamkey)) { main.totalMatchesPlayed1.push(main2.firstApiRounds[i].team1.name); if (main2.firstApiRounds[i].team1.key === main.teamkey) { main.teamname1 = main2.firstApiRounds[i].team1.name; main.totalgoals1 = main.totalgoals1 + main2.firstApiRounds[i].score1; if (main2.firstApiRounds[i].score1 > main2.firstApiRounds[i].score2) { main.totalWins1.push(main2.firstApiRounds[i].team2.key); } else if (main2.firstApiRounds[i].score1 < main2.firstApiRounds[i].score2) { main.totalLost1.push(main2.firstApiRounds[i].team1.key); } else if (main2.firstApiRounds[i].score1 == main2.firstApiRounds[i].score2) { main.totaldraw1.push(main2.firstApiRounds[i].team1.key); } else { console.log(response); } } if (main2.firstApiRounds[i].team2.key === main.teamkey) { main.totalgoals1 = main.totalgoals1 + main2.firstApiRounds[i].score2; if (main2.firstApiRounds[i].score1 < main2.firstApiRounds[i].score2) { main.totalWins1.push(main2.firstApiRounds[i].team2.key); } else if (main2.firstApiRounds[i].score1 > main2.firstApiRounds[i].score2) { main.totalLost1.push(main2.firstApiRounds[i].team1.key); } else if (main2.firstApiRounds[i].score1 == main2.firstApiRounds[i].score2) { main.totaldraw1.push(main2.firstApiRounds[i].team1.key); } else { console.log(nresponse); } } } } // end for loop }
function Url1() { for (var i = 0; i < main2.Rounds1.length; i++) { for (var j = 0; j < main2.Rounds1[i].matches.length; j++) { main2.firstApiRounds.push(main2.Rounds1[i].matches[j]); } } for (var i = 0; i < main2.firstApiRounds.length; i++) { if ((main2.firstApiRounds[i].team1.key === main.teamkey || main2.firstApiRounds[i].team2.key === main.teamkey)) { main.totalMatchesPlayed1.push(main2.firstApiRounds[i].team1.name); if (main2.firstApiRounds[i].team1.key === main.teamkey) { main.teamname1 = main2.firstApiRounds[i].team1.name; main.totalgoals1 = main.totalgoals1 + main2.firstApiRounds[i].score1; if (main2.firstApiRounds[i].score1 > main2.firstApiRounds[i].score2) { main.totalWins1.push(main2.firstApiRounds[i].team2.key); } else if (main2.firstApiRounds[i].score1 < main2.firstApiRounds[i].score2) { main.totalLost1.push(main2.firstApiRounds[i].team1.key); } else if (main2.firstApiRounds[i].score1 == main2.firstApiRounds[i].score2) { main.totaldraw1.push(main2.firstApiRounds[i].team1.key); } else { console.log(response); } } if (main2.firstApiRounds[i].team2.key === main.teamkey) { main.totalgoals1 = main.totalgoals1 + main2.firstApiRounds[i].score2; if (main2.firstApiRounds[i].score1 < main2.firstApiRounds[i].score2) { main.totalWins1.push(main2.firstApiRounds[i].team2.key); } else if (main2.firstApiRounds[i].score1 > main2.firstApiRounds[i].score2) { main.totalLost1.push(main2.firstApiRounds[i].team1.key); } else if (main2.firstApiRounds[i].score1 == main2.firstApiRounds[i].score2) { main.totaldraw1.push(main2.firstApiRounds[i].team1.key); } else { console.log(nresponse); } } } } // end for loop }
JavaScript
function Url2() { for (var i = 0; i < main2.Rounds2.length; i++) { for (var j = 0; j < main2.Rounds2[i].matches.length; j++) { main2.secondApiRounds.push(main2.Rounds2[i].matches[j]); } } for (var i = 0; i < main2.secondApiRounds.length; i++) { if ((main2.secondApiRounds[i].team1.key === main.teamkey || main2.secondApiRounds[i].team2.key === main.teamkey)) { main.totalMatchesPlayed2.push(main2.secondApiRounds[i].team1.name); if ( main2.secondApiRounds[i].team1.key === main.teamkey) { main.teamname2 = main2.secondApiRounds[i].team1.name; main.totalgoals2 = main.totalgoals2 + main2.firstApiRounds[i].score1; if (main2.secondApiRounds[i].score1 > main2.secondApiRounds[i].score2) { main.totalWins2.push(main2.secondApiRounds[i].team2.key); } else if (main2.secondApiRounds[i].score1 < main2.secondApiRounds[i].score2) { main.totalLost2.push(main2.secondApiRounds[i].team1.key); } else if (main2.secondApiRounds[i].score1 == main2.secondApiRounds[i].score2) { main.totaldraw2.push(main2.secondApiRounds[i].team1.key); } else { console.log(response); } } if ( main2.secondApiRounds[i].team2.key === main.teamkey) { main.totalgoals2 = main.totalgoals2 + main2.firstApiRounds[i].score2; if (main2.secondApiRounds[i].score1 < main2.secondApiRounds[i].score2) { main.totalWins2.push(main2.secondApiRounds[i].team2.key); } else if (main2.secondApiRounds[i].score1 > main2.secondApiRounds[i].score2) { main.totalLost2.push(main2.secondApiRounds[i].team1.key); } else if (main2.secondApiRounds[i].score1 == main2.secondApiRounds[i].score2) { main.totaldraw2.push(main2.secondApiRounds[i].team1.key); } else { console.log(response); } } } } // end for loop }
function Url2() { for (var i = 0; i < main2.Rounds2.length; i++) { for (var j = 0; j < main2.Rounds2[i].matches.length; j++) { main2.secondApiRounds.push(main2.Rounds2[i].matches[j]); } } for (var i = 0; i < main2.secondApiRounds.length; i++) { if ((main2.secondApiRounds[i].team1.key === main.teamkey || main2.secondApiRounds[i].team2.key === main.teamkey)) { main.totalMatchesPlayed2.push(main2.secondApiRounds[i].team1.name); if ( main2.secondApiRounds[i].team1.key === main.teamkey) { main.teamname2 = main2.secondApiRounds[i].team1.name; main.totalgoals2 = main.totalgoals2 + main2.firstApiRounds[i].score1; if (main2.secondApiRounds[i].score1 > main2.secondApiRounds[i].score2) { main.totalWins2.push(main2.secondApiRounds[i].team2.key); } else if (main2.secondApiRounds[i].score1 < main2.secondApiRounds[i].score2) { main.totalLost2.push(main2.secondApiRounds[i].team1.key); } else if (main2.secondApiRounds[i].score1 == main2.secondApiRounds[i].score2) { main.totaldraw2.push(main2.secondApiRounds[i].team1.key); } else { console.log(response); } } if ( main2.secondApiRounds[i].team2.key === main.teamkey) { main.totalgoals2 = main.totalgoals2 + main2.firstApiRounds[i].score2; if (main2.secondApiRounds[i].score1 < main2.secondApiRounds[i].score2) { main.totalWins2.push(main2.secondApiRounds[i].team2.key); } else if (main2.secondApiRounds[i].score1 > main2.secondApiRounds[i].score2) { main.totalLost2.push(main2.secondApiRounds[i].team1.key); } else if (main2.secondApiRounds[i].score1 == main2.secondApiRounds[i].score2) { main.totaldraw2.push(main2.secondApiRounds[i].team1.key); } else { console.log(response); } } } } // end for loop }
JavaScript
async function create(auth, title) { const service = google.sheets({version: 'v4', auth}); const resource = { properties: { title, }, }; try { const spreadsheet = await service.spreadsheets.create({ resource, fields: 'spreadsheetId', }); console.log(`Spreadsheet ID: ${spreadsheet.data.spreadsheetId}`); return spreadsheet.data.spreadsheetId; } catch (err) { throw err; } }
async function create(auth, title) { const service = google.sheets({version: 'v4', auth}); const resource = { properties: { title, }, }; try { const spreadsheet = await service.spreadsheets.create({ resource, fields: 'spreadsheetId', }); console.log(`Spreadsheet ID: ${spreadsheet.data.spreadsheetId}`); return spreadsheet.data.spreadsheetId; } catch (err) { throw err; } }
JavaScript
function authorize() { const oAuth2Client = new google.auth.OAuth2(); const token = { AccessToken: process.env.INTEGRATION_ACCESS_TOKEN, RefressToken: process.env.INTEGRATION_REFRESH_TOKEN } return oAuth2Client.setCredentials(token); }
function authorize() { const oAuth2Client = new google.auth.OAuth2(); const token = { AccessToken: process.env.INTEGRATION_ACCESS_TOKEN, RefressToken: process.env.INTEGRATION_REFRESH_TOKEN } return oAuth2Client.setCredentials(token); }
JavaScript
function validateForm(formFields) { const formErrors = { hasErrors: false, fieldErrors: {}, }; Object.entries(formFields).forEach(([fieldName, value]) => { const errors = validateField(value); if (errors.length > 0) { formErrors.hasErrors = true; } formErrors.fieldErrors[fieldName] = errors; }); return formErrors; }
function validateForm(formFields) { const formErrors = { hasErrors: false, fieldErrors: {}, }; Object.entries(formFields).forEach(([fieldName, value]) => { const errors = validateField(value); if (errors.length > 0) { formErrors.hasErrors = true; } formErrors.fieldErrors[fieldName] = errors; }); return formErrors; }
JavaScript
function buttonMash (sample,chunkSize){ // if(textWidth(displayString) > windowWidth * windowHeight / textSizeNum / 1.5){ // displayString = displayString.slice(lineCounter); // console.log("yo"); // } displayString += (sample.substr((counter*chunkSize-1),chunkSize)); $('h1').text(displayString); counter++; window.scrollTo(0,document.body.scrollHeight); }
function buttonMash (sample,chunkSize){ // if(textWidth(displayString) > windowWidth * windowHeight / textSizeNum / 1.5){ // displayString = displayString.slice(lineCounter); // console.log("yo"); // } displayString += (sample.substr((counter*chunkSize-1),chunkSize)); $('h1').text(displayString); counter++; window.scrollTo(0,document.body.scrollHeight); }
JavaScript
function showText(string) { //First we change the contents of the h1 to the line of our poem aka 'string' $('h1').html(string) //Then we do some specific styling things based on which line of the poem it is //So if it's the title of the poem, we change the bg image to James Brown and make sure the text is on the right if(string == "James Brown Gives Me a Poetry Solo, and I Realize That This Is 'My Moment'"){ $('html').css('background-image','url(jamesbrownBG.jpg)') $('h1').addClass("text-right").removeClass("text-left") } //Here we check for spans to find the big exclamation texts so we can change the bg image to yelling face and move text to the left, but also we don't want to change effect the one where we made the text smaller so we make sure it doesn't contain the word 'corporate', this is objectively pretty sloppy code but that is ok! It is ok to write bad code! else if(string.indexOf("span") != -1 && string.indexOf("corporate") == -1){ $('html').css('background-image','url(toddCloseup.png)') $('h1').addClass("text-left").removeClass("text-right") } //If the text isn't the title or big, this is what we do to it else { $('html').css('background-image','url(toddBG.png)') $('h1').addClass("text-left").removeClass("text-right") } }
function showText(string) { //First we change the contents of the h1 to the line of our poem aka 'string' $('h1').html(string) //Then we do some specific styling things based on which line of the poem it is //So if it's the title of the poem, we change the bg image to James Brown and make sure the text is on the right if(string == "James Brown Gives Me a Poetry Solo, and I Realize That This Is 'My Moment'"){ $('html').css('background-image','url(jamesbrownBG.jpg)') $('h1').addClass("text-right").removeClass("text-left") } //Here we check for spans to find the big exclamation texts so we can change the bg image to yelling face and move text to the left, but also we don't want to change effect the one where we made the text smaller so we make sure it doesn't contain the word 'corporate', this is objectively pretty sloppy code but that is ok! It is ok to write bad code! else if(string.indexOf("span") != -1 && string.indexOf("corporate") == -1){ $('html').css('background-image','url(toddCloseup.png)') $('h1').addClass("text-left").removeClass("text-right") } //If the text isn't the title or big, this is what we do to it else { $('html').css('background-image','url(toddBG.png)') $('h1').addClass("text-left").removeClass("text-right") } }
JavaScript
function playSound(id) { //this first line isn't relevent to sound playing, but just sets the linear counter to whatever line was last played, so if you press one of the letter keys you can still go back to linear from that spot counter = parseInt(id); //here we check for any other sounds tha are playing and pause/reset them since we dont want two lines said on top of each other $(".played").each(function(){ this.pause(); this.currentTime = 0 }); //Here we use jQuery do find the sound in the html file sound = $("#jb" + id).addClass("played")[0] //Set the playhead to the beginning it its already been played if (sound.ended){sound.currentTime = 0}; //If the sound is currently playing replay it from the beginning (this makes pressing the same button over and over really fun) if (sound.currentTime > 0){ sound.currentTime = 0 } //Play the sound else { sound.play() } }
function playSound(id) { //this first line isn't relevent to sound playing, but just sets the linear counter to whatever line was last played, so if you press one of the letter keys you can still go back to linear from that spot counter = parseInt(id); //here we check for any other sounds tha are playing and pause/reset them since we dont want two lines said on top of each other $(".played").each(function(){ this.pause(); this.currentTime = 0 }); //Here we use jQuery do find the sound in the html file sound = $("#jb" + id).addClass("played")[0] //Set the playhead to the beginning it its already been played if (sound.ended){sound.currentTime = 0}; //If the sound is currently playing replay it from the beginning (this makes pressing the same button over and over really fun) if (sound.currentTime > 0){ sound.currentTime = 0 } //Play the sound else { sound.play() } }
JavaScript
function playLinear(){ //here we find the line of the poem with the index 'counter' and showText it showText(poemText[counter]); //Then we add one to counter (++) to get to the next line for the next one counter++; //Then we play the sound associated with that line (the counters for the sounds are one more than the counters for the lines, this is sloppy and fine but probably dont do it like this yourself) playSound((counter).toString()); //When we reach the end of the poem, reset the counter to 0 aka pressing space again will start over, and then play 'I Feel Good' after 8 seconds if (counter >= 34){ setTimeout(function(){playSound("feelGood")},8000); counter = 0; } }
function playLinear(){ //here we find the line of the poem with the index 'counter' and showText it showText(poemText[counter]); //Then we add one to counter (++) to get to the next line for the next one counter++; //Then we play the sound associated with that line (the counters for the sounds are one more than the counters for the lines, this is sloppy and fine but probably dont do it like this yourself) playSound((counter).toString()); //When we reach the end of the poem, reset the counter to 0 aka pressing space again will start over, and then play 'I Feel Good' after 8 seconds if (counter >= 34){ setTimeout(function(){playSound("feelGood")},8000); counter = 0; } }
JavaScript
function foley(index){ if(!vid){vid = $('#bgvid')[0]} if(!hasBegun && vid.currentTime == 0){startTextAndVoice()} if(vid.currentTime < 8){ playSoundEl('lab', index); } if(vid.currentTime >= 8 && vid.currentTime < 11){ $('.lab').animate({volume: 0}, 1000) playSoundEl('gm', index); } if(vid.currentTime >= 11 && vid.currentTime < 21){ if($('#rain')[0].currentTime == 0){$('#rain')[0].play();} $('.gm').animate({volume: 0}, 1000) playSoundEl('rain',index) } if(vid.currentTime >= 21 && vid.currentTime < 33){ $('#rain').animate({volume: 0}, 1000) if($('#wyb')[0].currentTime == 0){ $('#wyb')[0].play() $('#tintDiv').css("opacity", "0.65"); } else{ tint += 10 * index; $('#tintDiv').css("filter", "hue-rotate("+tint.toString()+"deg)") $('#tintDiv').css("-webkit-filter", "hue-rotate("+tint.toString()+"deg)") } } if(vid.currentTime >= 33 && vid.currentTime < 44){ tint += 3 * index; $('#tintDiv').css("transition", '1s') $('#tintDiv').css("filter", "hue-rotate("+tint.toString()+"deg)") $('#tintDiv').css("-webkit-filter", "hue-rotate("+tint.toString()+"deg)") playSoundEl('tone', index) } if(vid.currentTime >= 44 && vid.currentTime < 50){ $('#tintDiv').css({transition: '0s', display:'none' }) $('.tone').animate({volume: 0}, 1000) playSoundEl("gun", index) } if(vid.currentTime >= 50 && vid.currentTime < 56){ $('#tintDiv').css({transition: '0s', display:'none' }) playSoundEl("quadcopter", index) } if(vid.currentTime >= 56 && vid.currentTime < 60){ $('.quadcopter').animate({volume: 0}, 1000) $('.lab').css("volume", "1.0") playSoundEl("lab", index) } if(vid.currentTime >= 60 || vid.currentTime == 0 && hasEnded == true){ playSoundEl('ha', index) } }
function foley(index){ if(!vid){vid = $('#bgvid')[0]} if(!hasBegun && vid.currentTime == 0){startTextAndVoice()} if(vid.currentTime < 8){ playSoundEl('lab', index); } if(vid.currentTime >= 8 && vid.currentTime < 11){ $('.lab').animate({volume: 0}, 1000) playSoundEl('gm', index); } if(vid.currentTime >= 11 && vid.currentTime < 21){ if($('#rain')[0].currentTime == 0){$('#rain')[0].play();} $('.gm').animate({volume: 0}, 1000) playSoundEl('rain',index) } if(vid.currentTime >= 21 && vid.currentTime < 33){ $('#rain').animate({volume: 0}, 1000) if($('#wyb')[0].currentTime == 0){ $('#wyb')[0].play() $('#tintDiv').css("opacity", "0.65"); } else{ tint += 10 * index; $('#tintDiv').css("filter", "hue-rotate("+tint.toString()+"deg)") $('#tintDiv').css("-webkit-filter", "hue-rotate("+tint.toString()+"deg)") } } if(vid.currentTime >= 33 && vid.currentTime < 44){ tint += 3 * index; $('#tintDiv').css("transition", '1s') $('#tintDiv').css("filter", "hue-rotate("+tint.toString()+"deg)") $('#tintDiv').css("-webkit-filter", "hue-rotate("+tint.toString()+"deg)") playSoundEl('tone', index) } if(vid.currentTime >= 44 && vid.currentTime < 50){ $('#tintDiv').css({transition: '0s', display:'none' }) $('.tone').animate({volume: 0}, 1000) playSoundEl("gun", index) } if(vid.currentTime >= 50 && vid.currentTime < 56){ $('#tintDiv').css({transition: '0s', display:'none' }) playSoundEl("quadcopter", index) } if(vid.currentTime >= 56 && vid.currentTime < 60){ $('.quadcopter').animate({volume: 0}, 1000) $('.lab').css("volume", "1.0") playSoundEl("lab", index) } if(vid.currentTime >= 60 || vid.currentTime == 0 && hasEnded == true){ playSoundEl('ha', index) } }
JavaScript
__val (val) { if (val === null || val === undefined) { return 0 } if (val.length === 2) { return Math.sqrt(val[0] * val[0] + val[1] * val[1]) } else { return val[0] } }
__val (val) { if (val === null || val === undefined) { return 0 } if (val.length === 2) { return Math.sqrt(val[0] * val[0] + val[1] * val[1]) } else { return val[0] } }
JavaScript
createTile (coords, done) { // const key = this._tileCoordsToKey(coords) // console.time(`${key} total`) const tile = L.DomUtil.create('canvas', 'leaflet-tile') const { colorScale } = this.options const ctx = tile.getContext('2d') const size = this.getTileSize() const map = this._map tile.width = size.x tile.height = size.y const nw = coords.scaleBy(size) const se = nw.add(size) // const colorMap = {} // console.time(`${key} load`) this.loadData(coords, (err, data) => { if (err) return console.error(err) // console.timeEnd(`${key} load`) // console.time(`${key} render total`) // console.time(`${key} colormap`) for (let y = nw.y - DOT_SIZE; y < se.y + DOT_SIZE; y += DOT_DENSITY) { for (let x = nw.x - DOT_SIZE; x < se.x + DOT_SIZE; x += DOT_DENSITY) { const latlng = map.unproject([x, y], coords.z) const value = data.get([latlng.lat, latlng.lng]) const colorValues = colorScale.getColor(value) if (colorValues !== null) { const [r, g, b] = colorValues const color = `rgba(${r}, ${g}, ${b}, 0.02)` const point = [x - nw.x, y - nw.y] ctx.fillStyle = color ctx.beginPath() ctx.arc( point[0] + Math.random() * 3, point[1] + Math.random() * 3, DOT_SIZE, 0, Math.PI * 2 ) ctx.closePath() ctx.fill() // if (!colorMap[color]) { // colorMap[color] = [] // } // // colorMap[color].push([x - nw.x, y - nw.y]) } } } // console.timeEnd(`${key} colormap`) // console.time(`${key} render`) // Object.keys(colorMap).forEach((color) => { // const points = colorMap[color] // ctx.fillStyle = color // points.forEach((point) => { // ctx.beginPath() // ctx.arc(point[0] + Math.random() * 3, point[1] + Math.random() * 3, DOT_SIZE, 0, Math.PI * 2) // ctx.closePath() // ctx.fill() // }) // }) // console.timeEnd(`${key} render`) // console.timeEnd(`${key} render total`) // ctx.fillStyle = `rgba(${Math.round(Math.random()*255)}, ${Math.round(Math.random()*255)}, ${Math.round(Math.random()*255)}, 1)` // data.forEach(([lat, lng]) => { // const point = map.project([lat, lng], coords.z) // ctx.beginPath() // ctx.arc(point.x - nw.x, point.y - nw.y, 5, 0, Math.PI * 2) // ctx.closePath() // ctx.fill() // }) done(null, tile) // console.timeEnd(`${key} total`) }) return tile }
createTile (coords, done) { // const key = this._tileCoordsToKey(coords) // console.time(`${key} total`) const tile = L.DomUtil.create('canvas', 'leaflet-tile') const { colorScale } = this.options const ctx = tile.getContext('2d') const size = this.getTileSize() const map = this._map tile.width = size.x tile.height = size.y const nw = coords.scaleBy(size) const se = nw.add(size) // const colorMap = {} // console.time(`${key} load`) this.loadData(coords, (err, data) => { if (err) return console.error(err) // console.timeEnd(`${key} load`) // console.time(`${key} render total`) // console.time(`${key} colormap`) for (let y = nw.y - DOT_SIZE; y < se.y + DOT_SIZE; y += DOT_DENSITY) { for (let x = nw.x - DOT_SIZE; x < se.x + DOT_SIZE; x += DOT_DENSITY) { const latlng = map.unproject([x, y], coords.z) const value = data.get([latlng.lat, latlng.lng]) const colorValues = colorScale.getColor(value) if (colorValues !== null) { const [r, g, b] = colorValues const color = `rgba(${r}, ${g}, ${b}, 0.02)` const point = [x - nw.x, y - nw.y] ctx.fillStyle = color ctx.beginPath() ctx.arc( point[0] + Math.random() * 3, point[1] + Math.random() * 3, DOT_SIZE, 0, Math.PI * 2 ) ctx.closePath() ctx.fill() // if (!colorMap[color]) { // colorMap[color] = [] // } // // colorMap[color].push([x - nw.x, y - nw.y]) } } } // console.timeEnd(`${key} colormap`) // console.time(`${key} render`) // Object.keys(colorMap).forEach((color) => { // const points = colorMap[color] // ctx.fillStyle = color // points.forEach((point) => { // ctx.beginPath() // ctx.arc(point[0] + Math.random() * 3, point[1] + Math.random() * 3, DOT_SIZE, 0, Math.PI * 2) // ctx.closePath() // ctx.fill() // }) // }) // console.timeEnd(`${key} render`) // console.timeEnd(`${key} render total`) // ctx.fillStyle = `rgba(${Math.round(Math.random()*255)}, ${Math.round(Math.random()*255)}, ${Math.round(Math.random()*255)}, 1)` // data.forEach(([lat, lng]) => { // const point = map.project([lat, lng], coords.z) // ctx.beginPath() // ctx.arc(point.x - nw.x, point.y - nw.y, 5, 0, Math.PI * 2) // ctx.closePath() // ctx.fill() // }) done(null, tile) // console.timeEnd(`${key} total`) }) return tile }
JavaScript
loadData (tile, cb) { // const letkey = this._tileCoordsToKey(tile) // console.log(`tile ${tile.x}:${tile.y}@${tile.z}`) const map = this._map const size = this.getTileSize() let nwPx = tile.scaleBy(size) let sePx = nwPx.add(size) // console.log(`px bounds ${nwPx.x}:${nwPx.y} - ${sePx.x}:${sePx.y}`) nwPx = nwPx.subtract([DOT_SIZE, DOT_SIZE]) sePx = sePx.add([DOT_SIZE, DOT_SIZE]) // console.log(`px bounds ${nwPx.x}:${nwPx.y} - ${sePx.x}:${sePx.y}`) // nwPx.subtract([DOT_SIZE * 2, DOT_SIZE * 2]) // sePx.add([DOT_SIZE * 4, DOT_SIZE * 4]) const nw = map.unproject(nwPx, tile.z) const se = map.unproject(sePx, tile.z) // console.log(`geo bounds ${nw.lng}:${nw.lat} - ${se.lng}:${se.lat}`) const resolution = Math.max(1, (6 - tile.z) * 2) const nwLat = nw.lat + resolution - nw.lat % resolution let nwLng = nw.lng - resolution - nw.lng % resolution const seLat = se.lat - resolution - se.lat % resolution let seLng = se.lng + resolution - se.lng % resolution if (Math.abs(seLng - nwLng) >= 360) { nwLng = -180 seLng = 180 - resolution } const bounds = [nwLng, Math.min(90, nwLat), seLng, Math.max(-90, seLat)] // console.log('bounds', bounds) const time = this.getCurrentDate().getTime() // console.time(`${key} io`) request .get(`${this.options.baseUrl}/layer/${this.options.type}/${time}`) .query({ bb: bounds.join(','), sf: resolution }) .responseType('arraybuffer') .end((err, res) => { if (err) return cb(err) // console.timeEnd(`${key} io`) // console.time(`${key} parse`) const buf = parseXProtobuf(res) if (!buf || !buf.buf || !buf.buf.length) return const points = geobuf.decode(buf) const grid = points.features.shift() const { dx, dy, bounds } = grid.properties let field // console.timeEnd(`${key} parse`) // console.log(`${nw.lng}:${nw.lat} - ${se.lng}:${se.lat}`) // console.time(`${key} parse=>prepare`) if (this.options.type === 'uvgrd') { field = new VectorField(bounds, dx, dy, points.features) } else { field = new ValueField(bounds, dx, dy, points.features) } // console.timeEnd(`${key} parse=>prepare`) // console.log(field) cb(null, field) }) }
loadData (tile, cb) { // const letkey = this._tileCoordsToKey(tile) // console.log(`tile ${tile.x}:${tile.y}@${tile.z}`) const map = this._map const size = this.getTileSize() let nwPx = tile.scaleBy(size) let sePx = nwPx.add(size) // console.log(`px bounds ${nwPx.x}:${nwPx.y} - ${sePx.x}:${sePx.y}`) nwPx = nwPx.subtract([DOT_SIZE, DOT_SIZE]) sePx = sePx.add([DOT_SIZE, DOT_SIZE]) // console.log(`px bounds ${nwPx.x}:${nwPx.y} - ${sePx.x}:${sePx.y}`) // nwPx.subtract([DOT_SIZE * 2, DOT_SIZE * 2]) // sePx.add([DOT_SIZE * 4, DOT_SIZE * 4]) const nw = map.unproject(nwPx, tile.z) const se = map.unproject(sePx, tile.z) // console.log(`geo bounds ${nw.lng}:${nw.lat} - ${se.lng}:${se.lat}`) const resolution = Math.max(1, (6 - tile.z) * 2) const nwLat = nw.lat + resolution - nw.lat % resolution let nwLng = nw.lng - resolution - nw.lng % resolution const seLat = se.lat - resolution - se.lat % resolution let seLng = se.lng + resolution - se.lng % resolution if (Math.abs(seLng - nwLng) >= 360) { nwLng = -180 seLng = 180 - resolution } const bounds = [nwLng, Math.min(90, nwLat), seLng, Math.max(-90, seLat)] // console.log('bounds', bounds) const time = this.getCurrentDate().getTime() // console.time(`${key} io`) request .get(`${this.options.baseUrl}/layer/${this.options.type}/${time}`) .query({ bb: bounds.join(','), sf: resolution }) .responseType('arraybuffer') .end((err, res) => { if (err) return cb(err) // console.timeEnd(`${key} io`) // console.time(`${key} parse`) const buf = parseXProtobuf(res) if (!buf || !buf.buf || !buf.buf.length) return const points = geobuf.decode(buf) const grid = points.features.shift() const { dx, dy, bounds } = grid.properties let field // console.timeEnd(`${key} parse`) // console.log(`${nw.lng}:${nw.lat} - ${se.lng}:${se.lat}`) // console.time(`${key} parse=>prepare`) if (this.options.type === 'uvgrd') { field = new VectorField(bounds, dx, dy, points.features) } else { field = new ValueField(bounds, dx, dy, points.features) } // console.timeEnd(`${key} parse=>prepare`) // console.log(field) cb(null, field) }) }
JavaScript
function initialize() { //set up the canvas and background image canvas = document.getElementById("theCanvas"); context = canvas.getContext("2d"); displayOwnSpeed(0); //display the static text labels for the vehicle states context.beginPath(); context.font = "30px Arial"; context.fillStyle = "#ffffff"; context.fillText("This vehicle (", ownLabelX, line1Y); context.fillText("Cooperating vehicles", otherHeadlineX, line1Y); context.font = "24px Arial"; context.fillStyle = "#99ffff"; context.fillText("Connected", ownLabelX, line2Y); context.fillText("Automated", ownLabelX, line3Y); context.closePath(); //display own vehicle indicator default states setOwnServerConnection(false); setOwnAutomation(0); //manual // draw a line to the right and bottom edge of the canvas to help scale the screen display // keep this block to use when customizing to fit new hardware /*---- context.beginPath(); context.fillStyle = "#ff3333"; var w = canvas.width - 1; var h = canvas.height - 1; context.moveTo(w, h); context.lineTo((w-30), h); context.moveTo(w, (h-30)); context.lineTo(w, h); context.lineTo((w-600), (h-100)); //context.closePath(); context.strokeStyle = "#aaff55"; context.stroke(); ----*/ }
function initialize() { //set up the canvas and background image canvas = document.getElementById("theCanvas"); context = canvas.getContext("2d"); displayOwnSpeed(0); //display the static text labels for the vehicle states context.beginPath(); context.font = "30px Arial"; context.fillStyle = "#ffffff"; context.fillText("This vehicle (", ownLabelX, line1Y); context.fillText("Cooperating vehicles", otherHeadlineX, line1Y); context.font = "24px Arial"; context.fillStyle = "#99ffff"; context.fillText("Connected", ownLabelX, line2Y); context.fillText("Automated", ownLabelX, line3Y); context.closePath(); //display own vehicle indicator default states setOwnServerConnection(false); setOwnAutomation(0); //manual // draw a line to the right and bottom edge of the canvas to help scale the screen display // keep this block to use when customizing to fit new hardware /*---- context.beginPath(); context.fillStyle = "#ff3333"; var w = canvas.width - 1; var h = canvas.height - 1; context.moveTo(w, h); context.lineTo((w-30), h); context.moveTo(w, (h-30)); context.lineTo(w, h); context.lineTo((w-600), (h-100)); //context.closePath(); context.strokeStyle = "#aaff55"; context.stroke(); ----*/ }
JavaScript
function displayOwnSpeed(mph) { //display rectangle for current speed drawSpeedometer(drawOwnSpeed, mph); //store this as the current speed for future reference currentSpeed = mph; }
function displayOwnSpeed(mph) { //display rectangle for current speed drawSpeedometer(drawOwnSpeed, mph); //store this as the current speed for future reference currentSpeed = mph; }
JavaScript
function drawSpeedometer(overlay, speed) { var img = new Image(); img.onload = function() { context.drawImage(img, speedScaleX, speedScaleY); overlay(speed); }; img.src = "images/speedscale.png"; }
function drawSpeedometer(overlay, speed) { var img = new Image(); img.onload = function() { context.drawImage(img, speedScaleX, speedScaleY); overlay(speed); }; img.src = "images/speedscale.png"; }
JavaScript
function drawOwnSpeed(speed) { if (speed > 0) { context.beginPath(); var width = speed*pixelsPerMph; context.rect(speed0x, speedometerY, width, speedometerHeight); context.fillStyle = "#0050ff"; context.fill(); } }
function drawOwnSpeed(speed) { if (speed > 0) { context.beginPath(); var width = speed*pixelsPerMph; context.rect(speed0x, speedometerY, width, speedometerHeight); context.fillStyle = "#0050ff"; context.fill(); } }
JavaScript
function displaySpeedCmd(newCmdMph, conf) { //compute geometric params var cmdX = currentCmd*pixelsPerMph + speed0x; //centerline of the indicator in pixels var indicatorLeft = cmdX - 0.5*commandWidth; var indicatorRight = cmdX + 0.5*commandWidth; //erase the existing command widget var rectHeight = commandWidth + confidenceHeight; context.beginPath(); context.clearRect(indicatorLeft-1, commandY-1, commandWidth+2, rectHeight+2); //display the widget at the new command location cmdX = newCmdMph*pixelsPerMph + speed0x; indicatorLeft = cmdX - 0.5*commandWidth; indicatorRight = cmdX + 0.5*commandWidth; var triangleBottom = commandY + commandWidth; context.beginPath(); context.moveTo(cmdX, commandY); //begin the triangle context.lineTo(indicatorRight, triangleBottom); context.lineTo(indicatorLeft, triangleBottom); context.lineTo(cmdX, commandY); var intensityRed = 0.01*(255-bgndR)*conf + bgndR; //compute color fill of the triangle; goes from bgnd to bright yellow var intensityGreen = 0.01*(255-bgndG)*conf + bgndG; var intensityBlue = bgndB; var irs = decimalToHex2(intensityRed); var igs = decimalToHex2(intensityGreen); var ibs = decimalToHex2(intensityBlue); var intensityStr = "#" + irs + igs + ibs; context.fillStyle = intensityStr; context.fill(); context.fillStyle = "#ffff00"; //create yellow rectangle for confidence display context.fillRect(indicatorLeft, triangleBottom, commandWidth, confidenceHeight); //display the current command confidence value in the widget context.beginPath(); context.font = "20px Arial"; var confStr = conf.toString() + "%"; var confX = indicatorLeft + confXOffset; var confY = triangleBottom + confYOffset; context.fillStyle = "#000000"; context.fillText(confStr, confX, confY); context.closePath(); //store the new command and confidence as current values for future reference currentCmd = newCmdMph; confidence = conf; }
function displaySpeedCmd(newCmdMph, conf) { //compute geometric params var cmdX = currentCmd*pixelsPerMph + speed0x; //centerline of the indicator in pixels var indicatorLeft = cmdX - 0.5*commandWidth; var indicatorRight = cmdX + 0.5*commandWidth; //erase the existing command widget var rectHeight = commandWidth + confidenceHeight; context.beginPath(); context.clearRect(indicatorLeft-1, commandY-1, commandWidth+2, rectHeight+2); //display the widget at the new command location cmdX = newCmdMph*pixelsPerMph + speed0x; indicatorLeft = cmdX - 0.5*commandWidth; indicatorRight = cmdX + 0.5*commandWidth; var triangleBottom = commandY + commandWidth; context.beginPath(); context.moveTo(cmdX, commandY); //begin the triangle context.lineTo(indicatorRight, triangleBottom); context.lineTo(indicatorLeft, triangleBottom); context.lineTo(cmdX, commandY); var intensityRed = 0.01*(255-bgndR)*conf + bgndR; //compute color fill of the triangle; goes from bgnd to bright yellow var intensityGreen = 0.01*(255-bgndG)*conf + bgndG; var intensityBlue = bgndB; var irs = decimalToHex2(intensityRed); var igs = decimalToHex2(intensityGreen); var ibs = decimalToHex2(intensityBlue); var intensityStr = "#" + irs + igs + ibs; context.fillStyle = intensityStr; context.fill(); context.fillStyle = "#ffff00"; //create yellow rectangle for confidence display context.fillRect(indicatorLeft, triangleBottom, commandWidth, confidenceHeight); //display the current command confidence value in the widget context.beginPath(); context.font = "20px Arial"; var confStr = conf.toString() + "%"; var confX = indicatorLeft + confXOffset; var confY = triangleBottom + confYOffset; context.fillStyle = "#000000"; context.fillText(confStr, confX, confY); context.closePath(); //store the new command and confidence as current values for future reference currentCmd = newCmdMph; confidence = conf; }
JavaScript
function displayVersionId(id) { //display the ID info context.beginPath(); context.font = "14px Arial"; context.fillStyle = "#888888"; context.fillText(id, versionX, canvas.height - 14); context.closePath(); }
function displayVersionId(id) { //display the ID info context.beginPath(); context.font = "14px Arial"; context.fillStyle = "#888888"; context.fillText(id, versionX, canvas.height - 14); context.closePath(); }
JavaScript
function displayUiMessage(uiMessage) { "use strict" //determine the message source, which tells us which elements are meaningful var source = uiMessage.source; //if message source is the main loop then if (source == 1) { //pull out the vehicle name, own speed and own automation state vehicleName = uiMessage.ownName; ownSpeed = uiMessage.ownSpeed; ownAutomation = uiMessage.ownAuto; //display these items setOwnName(vehicleName); displayOwnSpeed(ownSpeed); setOwnAutomation(ownAutomation); //pull out the speed command, confidence and connection status speedCmd = uiMessage.spdCmd; confidence = uiMessage.conf; serverConnection = uiMessage.ownConnection; //display these items displaySpeedCmd(speedCmd, confidence); setOwnServerConnection(serverConnection); //pull out the other vehicle statuses var otherStates = uiMessage.otherStates; v1Auto = otherStates & 0x00000003; v2Auto = (otherStates >> 2) & 0x00000003; v3Auto = (otherStates >> 4) & 0x00000003; v4Auto = (otherStates >> 6) & 0x00000003; numOthers = uiMessage.numPartners; //these names should never contain obsolete entries (e.g. if a vehicle has dropped out), since the // number of partners is always kept current by the Java server side v1Name = uiMessage.v1Name; v2Name = uiMessage.v2Name; v3Name = uiMessage.v3Name; v4Name = uiMessage.v4Name; //display these items, making sure to clear the auto indicators if the vehicle doesn't exist setVehicle1Name(v1Name); setVehicle2Name(v2Name); setVehicle3Name(v3Name); setVehicle4Name(v4Name); if (numOthers >= 1) { setVehicle1Automation(v1Auto); if (numOthers >= 2) { setVehicle2Automation(v2Auto); if (numOthers >= 3) { setVehicle3Automation(v3Auto); if (numOthers >= 4) { setVehicle4Automation(v4Auto); }else { setVehicle4Automation(9); //a value > 2 displays the indicator in background color } }else { setVehicle3Automation(9); setVehicle4Automation(9); } }else { setVehicle2Automation(9); setVehicle3Automation(9); setVehicle4Automation(9); } }else { setVehicle1Automation(9); setVehicle2Automation(9); setVehicle3Automation(9); setVehicle4Automation(9); } //else if message source is initializer then }else if (source == 4) { versionId = uiMessage.version; displayVersionId(versionId); //else (should never happen) }else { //alert the user alert("Illegal message type received from secondary computer: " + source); } }
function displayUiMessage(uiMessage) { "use strict" //determine the message source, which tells us which elements are meaningful var source = uiMessage.source; //if message source is the main loop then if (source == 1) { //pull out the vehicle name, own speed and own automation state vehicleName = uiMessage.ownName; ownSpeed = uiMessage.ownSpeed; ownAutomation = uiMessage.ownAuto; //display these items setOwnName(vehicleName); displayOwnSpeed(ownSpeed); setOwnAutomation(ownAutomation); //pull out the speed command, confidence and connection status speedCmd = uiMessage.spdCmd; confidence = uiMessage.conf; serverConnection = uiMessage.ownConnection; //display these items displaySpeedCmd(speedCmd, confidence); setOwnServerConnection(serverConnection); //pull out the other vehicle statuses var otherStates = uiMessage.otherStates; v1Auto = otherStates & 0x00000003; v2Auto = (otherStates >> 2) & 0x00000003; v3Auto = (otherStates >> 4) & 0x00000003; v4Auto = (otherStates >> 6) & 0x00000003; numOthers = uiMessage.numPartners; //these names should never contain obsolete entries (e.g. if a vehicle has dropped out), since the // number of partners is always kept current by the Java server side v1Name = uiMessage.v1Name; v2Name = uiMessage.v2Name; v3Name = uiMessage.v3Name; v4Name = uiMessage.v4Name; //display these items, making sure to clear the auto indicators if the vehicle doesn't exist setVehicle1Name(v1Name); setVehicle2Name(v2Name); setVehicle3Name(v3Name); setVehicle4Name(v4Name); if (numOthers >= 1) { setVehicle1Automation(v1Auto); if (numOthers >= 2) { setVehicle2Automation(v2Auto); if (numOthers >= 3) { setVehicle3Automation(v3Auto); if (numOthers >= 4) { setVehicle4Automation(v4Auto); }else { setVehicle4Automation(9); //a value > 2 displays the indicator in background color } }else { setVehicle3Automation(9); setVehicle4Automation(9); } }else { setVehicle2Automation(9); setVehicle3Automation(9); setVehicle4Automation(9); } }else { setVehicle1Automation(9); setVehicle2Automation(9); setVehicle3Automation(9); setVehicle4Automation(9); } //else if message source is initializer then }else if (source == 4) { versionId = uiMessage.version; displayVersionId(versionId); //else (should never happen) }else { //alert the user alert("Illegal message type received from secondary computer: " + source); } }
JavaScript
function playAndroidSound() { // doesn't work on many android devices //document.getElementById("audioId").play(); playSound('audio-fix'); }
function playAndroidSound() { // doesn't work on many android devices //document.getElementById("audioId").play(); playSound('audio-fix'); }
JavaScript
function unitTest1() { if (test1Count == 0) { testSpeed = 18; }else if (test1Count == 1) { testSpeed = 0; }else if (test1Count == 2) { testSpeed = 40; }else { testSpeed = 71; } ++test1Count; if (test1Count > 3) test1Count = 0; displayOwnSpeed(testSpeed); }
function unitTest1() { if (test1Count == 0) { testSpeed = 18; }else if (test1Count == 1) { testSpeed = 0; }else if (test1Count == 2) { testSpeed = 40; }else { testSpeed = 71; } ++test1Count; if (test1Count > 3) test1Count = 0; displayOwnSpeed(testSpeed); }
JavaScript
function unitTest2() { if (test2Count == 0) { testCmd = 0; testConf = 0; }else if (test2Count == 1) { testCmd = 25; testConf = 99; }else if (test2Count == 2) { testCmd = 25; testConf = 81; }else if (test2Count == 3) { testCmd = 49; testConf = 81; }else if (test2Count == 4) { testCmd = 38; testConf = 50; }else if (test2Count == 5) { testCmd = 37; testConf = 49; }else if (test2Count == 6) { testCmd = 36; testConf = 24; } ++test2Count; if (test2Count > 6) test2Count = 0; displaySpeedCmd(testCmd, testConf); }
function unitTest2() { if (test2Count == 0) { testCmd = 0; testConf = 0; }else if (test2Count == 1) { testCmd = 25; testConf = 99; }else if (test2Count == 2) { testCmd = 25; testConf = 81; }else if (test2Count == 3) { testCmd = 49; testConf = 81; }else if (test2Count == 4) { testCmd = 38; testConf = 50; }else if (test2Count == 5) { testCmd = 37; testConf = 49; }else if (test2Count == 6) { testCmd = 36; testConf = 24; } ++test2Count; if (test2Count > 6) test2Count = 0; displaySpeedCmd(testCmd, testConf); }
JavaScript
function unitTest3() { if (test3Count == 0) { testName = ""; }else if (test3Count == 1) { testName = "Black"; }else if (test3Count == 2) { testName = "WEIRD-LONG-NAME"; }else if (test3Count == 3) { testName = "13 chars long"; } ++test3Count; if (test3Count > 3) test3Count = 0; setOwnName(testName); }
function unitTest3() { if (test3Count == 0) { testName = ""; }else if (test3Count == 1) { testName = "Black"; }else if (test3Count == 2) { testName = "WEIRD-LONG-NAME"; }else if (test3Count == 3) { testName = "13 chars long"; } ++test3Count; if (test3Count > 3) test3Count = 0; setOwnName(testName); }
JavaScript
function unitTest4() { if (test4Count == 0) { conn = false; auto = 0; }else if (test4Count == 1) { conn = true; auto = 2; }else if (test4Count == 2) { conn = false; auto = 1; }else if (test4Count == 3) { conn = true; auto = 1; } ++test4Count; if (test4Count > 3) test4Count = 0; setOwnServerConnection(conn); setOwnAutomation(auto); }
function unitTest4() { if (test4Count == 0) { conn = false; auto = 0; }else if (test4Count == 1) { conn = true; auto = 2; }else if (test4Count == 2) { conn = false; auto = 1; }else if (test4Count == 3) { conn = true; auto = 1; } ++test4Count; if (test4Count > 3) test4Count = 0; setOwnServerConnection(conn); setOwnAutomation(auto); }
JavaScript
function unitTest5() { name1 = ""; name2 = ""; name3 = ""; name4 = ""; auto1 = 0; auto2 = 0; auto3 = 0; auto4 = 0; if (test5Count == 0) { name1 = "Yellow"; auto1 = 1; }else if (test5Count == 1) { name1 = "Yellow"; name2 = "Purple"; auto1 = 1; }else if (test5Count == 2) { name1 = "Yellow"; name2 = "Purple"; name3 = "Hideous"; auto2 = 1; auto3 = 2; }else if (test5Count == 3) { name1 = "Yellow"; name2 = "Violet"; name3 = "Worse"; name4 = "Mauve"; auto1 = 1; auto2 = 1; auto4 = 1; }else if (test5Count == 4) { name1 = "Blue"; name2 = "Orange"; }else if (test5Count == 5) { name1 = "Blue"; name2 = "Orange"; auto1 = 1; auto2 = 1; auto3 = 2; auto4 = 1; } ++test5Count; if (test5Count > 5) test5Count = 0; setVehicle1Name(name1); setVehicle2Name(name2); setVehicle3Name(name3); setVehicle4Name(name4); setVehicle1Automation(auto1); setVehicle2Automation(auto2); setVehicle3Automation(auto3); setVehicle4Automation(auto4); }
function unitTest5() { name1 = ""; name2 = ""; name3 = ""; name4 = ""; auto1 = 0; auto2 = 0; auto3 = 0; auto4 = 0; if (test5Count == 0) { name1 = "Yellow"; auto1 = 1; }else if (test5Count == 1) { name1 = "Yellow"; name2 = "Purple"; auto1 = 1; }else if (test5Count == 2) { name1 = "Yellow"; name2 = "Purple"; name3 = "Hideous"; auto2 = 1; auto3 = 2; }else if (test5Count == 3) { name1 = "Yellow"; name2 = "Violet"; name3 = "Worse"; name4 = "Mauve"; auto1 = 1; auto2 = 1; auto4 = 1; }else if (test5Count == 4) { name1 = "Blue"; name2 = "Orange"; }else if (test5Count == 5) { name1 = "Blue"; name2 = "Orange"; auto1 = 1; auto2 = 1; auto3 = 2; auto4 = 1; } ++test5Count; if (test5Count > 5) test5Count = 0; setVehicle1Name(name1); setVehicle2Name(name2); setVehicle3Name(name3); setVehicle4Name(name4); setVehicle1Automation(auto1); setVehicle2Automation(auto2); setVehicle3Automation(auto3); setVehicle4Automation(auto4); }
JavaScript
function isLoggedIn(req, res, next) { // if user is authenticated in the session, carry on if (req.isAuthenticated()) return next(); // if they aren't redirect them to the home page //req.session.error = 'Not Logged In!, can\'t see profile' req.flash('info', 'Not Logged In!, Can\'t see profile'); req.session.save(()=>{ res.redirect('/'); }); }
function isLoggedIn(req, res, next) { // if user is authenticated in the session, carry on if (req.isAuthenticated()) return next(); // if they aren't redirect them to the home page //req.session.error = 'Not Logged In!, can\'t see profile' req.flash('info', 'Not Logged In!, Can\'t see profile'); req.session.save(()=>{ res.redirect('/'); }); }
JavaScript
function _authBasic(str) { // str: am9objpqb2hubnk= let base64Buffer = Buffer.from(str, 'base64'); // <Buffer 01 02 ...> let bufferString = base64Buffer.toString(); // john:mysecret let [username, password] = bufferString.split(':'); // john='john'; mysecret='mysecret'] let auth = {username,password}; // { username:'john', password:'mysecret' } return User.authenticateBasic(auth) .then(user => _authenticate(user) ) .catch(next); }
function _authBasic(str) { // str: am9objpqb2hubnk= let base64Buffer = Buffer.from(str, 'base64'); // <Buffer 01 02 ...> let bufferString = base64Buffer.toString(); // john:mysecret let [username, password] = bufferString.split(':'); // john='john'; mysecret='mysecret'] let auth = {username,password}; // { username:'john', password:'mysecret' } return User.authenticateBasic(auth) .then(user => _authenticate(user) ) .catch(next); }
JavaScript
function _authBearer(authString) { console.log('first log', authString); return User.authenticateToken(authString) .then( user => _authenticate(user) ) .catch((e) => { console.log(e); next(e); }); }
function _authBearer(authString) { console.log('first log', authString); return User.authenticateToken(authString) .then( user => _authenticate(user) ) .catch((e) => { console.log(e); next(e); }); }
JavaScript
function avg (object) { function add (a, b) { return a + b } const props = Object.keys(object) const total = props.map(prop => object[prop]).reduce(add, 0) return total / props.length }
function avg (object) { function add (a, b) { return a + b } const props = Object.keys(object) const total = props.map(prop => object[prop]).reduce(add, 0) return total / props.length }
JavaScript
function calculateProfitAndLossPartials (data) { const years = getYears(data) const corporateTaxRate = parseValue(data.parameters.corporateTaxRate) const revenues = calculatePxQ(filterGroup(data, 'revenues', 'all'), years) const directCosts = calculatePxQ(filterGroup(data, 'costs', 'direct'), years, revenues) const holidayProvision = parseValue(data.parameters.holidayProvision) const SSCEmployer = parseValue(data.parameters.SSCEmployer) const personnelCosts = multiplyPropsWith( calculatePxQ(filterGroup(data, 'costs', 'personnel'), years), (1 + holidayProvision) * (1 + SSCEmployer) ) const indirectCosts = calculatePxQ(filterGroup(data, 'costs', 'indirect'), years, revenues) const grossMargin = subtractProps(revenues, directCosts) const EBITDA = subtractProps(grossMargin, indirectCosts) const allInvestments = filterSection(data, 'investments') // both tangible and intangible const depreciation = calculatePxQ(allInvestments, years) const EBIT = subtractProps(EBITDA, depreciation) const interestPayableOnLoans = parseValue(data.parameters.interestPayableOnLoans) const longTermDept = calculateLongTermDebt(data, years) const interest = {} years.forEach(year => { // average over current and previous year, multiplied with the interest percentage interest[year] = (longTermDept[year - 1] + longTermDept[year]) / 2 * interestPayableOnLoans }) const EBT = subtractProps(EBIT, interest) const corporateTaxes = multiplyPropsWith(EBT, corporateTaxRate) const netResult = subtractProps(EBT, corporateTaxes) return { revenues, directCosts, grossMargin, personnelCosts, indirectCosts, EBITDA, depreciation, EBIT, interest, EBT, corporateTaxes, netResult } }
function calculateProfitAndLossPartials (data) { const years = getYears(data) const corporateTaxRate = parseValue(data.parameters.corporateTaxRate) const revenues = calculatePxQ(filterGroup(data, 'revenues', 'all'), years) const directCosts = calculatePxQ(filterGroup(data, 'costs', 'direct'), years, revenues) const holidayProvision = parseValue(data.parameters.holidayProvision) const SSCEmployer = parseValue(data.parameters.SSCEmployer) const personnelCosts = multiplyPropsWith( calculatePxQ(filterGroup(data, 'costs', 'personnel'), years), (1 + holidayProvision) * (1 + SSCEmployer) ) const indirectCosts = calculatePxQ(filterGroup(data, 'costs', 'indirect'), years, revenues) const grossMargin = subtractProps(revenues, directCosts) const EBITDA = subtractProps(grossMargin, indirectCosts) const allInvestments = filterSection(data, 'investments') // both tangible and intangible const depreciation = calculatePxQ(allInvestments, years) const EBIT = subtractProps(EBITDA, depreciation) const interestPayableOnLoans = parseValue(data.parameters.interestPayableOnLoans) const longTermDept = calculateLongTermDebt(data, years) const interest = {} years.forEach(year => { // average over current and previous year, multiplied with the interest percentage interest[year] = (longTermDept[year - 1] + longTermDept[year]) / 2 * interestPayableOnLoans }) const EBT = subtractProps(EBIT, interest) const corporateTaxes = multiplyPropsWith(EBT, corporateTaxRate) const netResult = subtractProps(EBT, corporateTaxes) return { revenues, directCosts, grossMargin, personnelCosts, indirectCosts, EBITDA, depreciation, EBIT, interest, EBT, corporateTaxes, netResult } }
JavaScript
function calculateProfitAndLoss (data) { const partials = calculateProfitAndLossPartials(data) return [ { label: 'Total revenues', values: partials.revenues, info: 'Revenues: can be initial or one-time sales and recurring revenues. It can also include incidental non-core business revenues such as book gains on the sale of assets or participation (you sold it for more than you bought it for), but you do not plan for those so they are not in the category.' }, { label: 'Total direct costs', values: partials.directCosts, info: 'Direct costs: these are the "purchase cost" of the revenue you generate. The most important property they have is that they are NOT scalable. So the more you sell, the higher this is, and fully linear with the sales. In many cases planners simply know that this is a certain percentage of their sales so simply model it like this. This has been decoupled to offer a bit more flexibility.' }, { label: 'Gross margin', values: partials.grossMargin }, { label: 'Total personnel costs', values: partials.personnelCosts }, { label: 'Total other indirect costs', values: partials.indirectCosts, info: 'Indirect costs. Also referred to as "overhead". These costs develop more or less independent of the revenue development. Personnel is the most important part here. But in certain business models rarely, you may argue that some of it is part of direct costs. Especially in consultancy when the external tariff is ties to the salary of the consultant. This category also includes all other stuff such as housing, transport, communications, travel, and also marketing costs.' }, { label: 'EBITDA', values: partials.EBITDA, info: 'EBITDA: Earnings before Interest, tax, depreciation and amortization. Often used as "quick and dirty" cashflow from operations indicator.' }, { label: 'Depreciation and amortization', values: partials.depreciation, info: 'Depreciation and amortization. The annual portion of the purchase price of an asset (which is basically the cost of something that you use for more than one year). The mechanism it that you bring the purchase price of such an "asset" to the balance sheet, under "asset" (duh) which can be tangible (you can touch it) or intangible such as IPR, rights of use, licenses which are called intangible.\nFor each asset there is a reasonable usage period which should be determined by your business. So for example if you determine that something you bought can be used in your company for 5 years, you bring 1/5 of the purchase price to D&A in the P&L, and decrease the value of the asset in the balance sheet with the same amount. So after 5 years the whole purchase cost has been run through the P&L and the value on the balance sheet is brought back to 0.\nAmortization strictly would be depreciation of intangibles, but is also used for exceptional depreciation out of the above described linear method. So for example you have determined that developments go so quickly that you can use the asset for only 3 years instead of 5. IF you are sure about this you can/ should do additional depreciation. Again here, this is not something you "plan" obviously.' }, { label: 'EBIT', values: partials.EBIT, className: 'main middle', info: 'EBIT: Earnings before Interest and Taxes, also referred to as "result from operations"' }, { label: 'Interest', values: partials.interest, info: 'Interest: interest has been discarded on current accounts as it creates a nasty circular reference that is really hard to get rid of, and interest on current account is negligible anyway. Amounts here are tied to the long-term financing on the Balance sheet, which in turn runs on the manual input in the cashflow, where you asses the operational deficit and plan for bank or equity financing (or redemption or dividends in case of cash surplus)' }, { label: 'EBT', values: partials.EBT }, { label: 'Corporate taxes', values: partials.corporateTaxes, info: 'Tax: this is the pro-forma amount based on the tax rate. As explained negative amounts can be accumulated for 9 years and offset against future positive amounts until the stash of accumulated negative mounts is exhausted. This is called "loss carry forward" and the tax part of it (so the amount that can be offset) is brought to the balance sheet as an asset (which it is of course, if you plan to make a profit in the near future)' }, { label: 'Net result', values: partials.netResult } ] }
function calculateProfitAndLoss (data) { const partials = calculateProfitAndLossPartials(data) return [ { label: 'Total revenues', values: partials.revenues, info: 'Revenues: can be initial or one-time sales and recurring revenues. It can also include incidental non-core business revenues such as book gains on the sale of assets or participation (you sold it for more than you bought it for), but you do not plan for those so they are not in the category.' }, { label: 'Total direct costs', values: partials.directCosts, info: 'Direct costs: these are the "purchase cost" of the revenue you generate. The most important property they have is that they are NOT scalable. So the more you sell, the higher this is, and fully linear with the sales. In many cases planners simply know that this is a certain percentage of their sales so simply model it like this. This has been decoupled to offer a bit more flexibility.' }, { label: 'Gross margin', values: partials.grossMargin }, { label: 'Total personnel costs', values: partials.personnelCosts }, { label: 'Total other indirect costs', values: partials.indirectCosts, info: 'Indirect costs. Also referred to as "overhead". These costs develop more or less independent of the revenue development. Personnel is the most important part here. But in certain business models rarely, you may argue that some of it is part of direct costs. Especially in consultancy when the external tariff is ties to the salary of the consultant. This category also includes all other stuff such as housing, transport, communications, travel, and also marketing costs.' }, { label: 'EBITDA', values: partials.EBITDA, info: 'EBITDA: Earnings before Interest, tax, depreciation and amortization. Often used as "quick and dirty" cashflow from operations indicator.' }, { label: 'Depreciation and amortization', values: partials.depreciation, info: 'Depreciation and amortization. The annual portion of the purchase price of an asset (which is basically the cost of something that you use for more than one year). The mechanism it that you bring the purchase price of such an "asset" to the balance sheet, under "asset" (duh) which can be tangible (you can touch it) or intangible such as IPR, rights of use, licenses which are called intangible.\nFor each asset there is a reasonable usage period which should be determined by your business. So for example if you determine that something you bought can be used in your company for 5 years, you bring 1/5 of the purchase price to D&A in the P&L, and decrease the value of the asset in the balance sheet with the same amount. So after 5 years the whole purchase cost has been run through the P&L and the value on the balance sheet is brought back to 0.\nAmortization strictly would be depreciation of intangibles, but is also used for exceptional depreciation out of the above described linear method. So for example you have determined that developments go so quickly that you can use the asset for only 3 years instead of 5. IF you are sure about this you can/ should do additional depreciation. Again here, this is not something you "plan" obviously.' }, { label: 'EBIT', values: partials.EBIT, className: 'main middle', info: 'EBIT: Earnings before Interest and Taxes, also referred to as "result from operations"' }, { label: 'Interest', values: partials.interest, info: 'Interest: interest has been discarded on current accounts as it creates a nasty circular reference that is really hard to get rid of, and interest on current account is negligible anyway. Amounts here are tied to the long-term financing on the Balance sheet, which in turn runs on the manual input in the cashflow, where you asses the operational deficit and plan for bank or equity financing (or redemption or dividends in case of cash surplus)' }, { label: 'EBT', values: partials.EBT }, { label: 'Corporate taxes', values: partials.corporateTaxes, info: 'Tax: this is the pro-forma amount based on the tax rate. As explained negative amounts can be accumulated for 9 years and offset against future positive amounts until the stash of accumulated negative mounts is exhausted. This is called "loss carry forward" and the tax part of it (so the amount that can be offset) is brought to the balance sheet as an asset (which it is of course, if you plan to make a profit in the near future)' }, { label: 'Net result', values: partials.netResult } ] }
JavaScript
function sanitizeDoc (doc) { const _doc = Immutable(merge({}, newScenario, doc)) let updatedCategories = updateRevenueCategories( _doc.data.categories, _doc.data.description.products, _doc.data.description.customers) updatedCategories = checkBMCCategories(updatedCategories, _doc.data.description.type) return _doc.setIn(['data', 'categories'], updatedCategories) }
function sanitizeDoc (doc) { const _doc = Immutable(merge({}, newScenario, doc)) let updatedCategories = updateRevenueCategories( _doc.data.categories, _doc.data.description.products, _doc.data.description.customers) updatedCategories = checkBMCCategories(updatedCategories, _doc.data.description.type) return _doc.setIn(['data', 'categories'], updatedCategories) }
JavaScript
function checkBMCCategories (categories, companyType) { // uncheck all existing categories which are not marked as bmcDefault===true const uncheckedCategories = categories.map(category => { if (!category.bmcCheckedManually) { return category.set('bmcChecked', false) } else { return category } }) // loop over all default categories for this companyType, // apply default bmcChecked values const defaultCategories = bmcDefaults[companyType] if (defaultCategories) { const defaults = {} defaultCategories.forEach(c => defaults[c.bmcId] = c.bmcChecked) const existing = {} uncheckedCategories.forEach(c => existing[c.bmcId] = true) // update existing categories const checkedCategories = uncheckedCategories.map(category => { if (category.bmcId in defaults && !category.bmcCheckedManually) { return category.set('bmcChecked', defaults[category.bmcId]) } else { return category } }) // add new categories const newCategories = defaultCategories .filter(category => !existing[category.bmcId]) .map(defaultCategory => { const bmcId = defaultCategory.bmcId const { bmcGroup, label } = bmcCategories.categories.find(c => c.bmcId === bmcId) const { section, group } = bmcCategories.groups[bmcGroup] const price = (section === 'investments') ? types.investment.defaultPrice // investments : types.constant.defaultPrice // costs return { id: uuid(), label, section, group, price, quantities: {}, bmcGroup: bmcGroup, bmcId, bmcChecked: defaults[bmcId], custom: false } }) return checkedCategories.concat(newCategories) } else { return uncheckedCategories } }
function checkBMCCategories (categories, companyType) { // uncheck all existing categories which are not marked as bmcDefault===true const uncheckedCategories = categories.map(category => { if (!category.bmcCheckedManually) { return category.set('bmcChecked', false) } else { return category } }) // loop over all default categories for this companyType, // apply default bmcChecked values const defaultCategories = bmcDefaults[companyType] if (defaultCategories) { const defaults = {} defaultCategories.forEach(c => defaults[c.bmcId] = c.bmcChecked) const existing = {} uncheckedCategories.forEach(c => existing[c.bmcId] = true) // update existing categories const checkedCategories = uncheckedCategories.map(category => { if (category.bmcId in defaults && !category.bmcCheckedManually) { return category.set('bmcChecked', defaults[category.bmcId]) } else { return category } }) // add new categories const newCategories = defaultCategories .filter(category => !existing[category.bmcId]) .map(defaultCategory => { const bmcId = defaultCategory.bmcId const { bmcGroup, label } = bmcCategories.categories.find(c => c.bmcId === bmcId) const { section, group } = bmcCategories.groups[bmcGroup] const price = (section === 'investments') ? types.investment.defaultPrice // investments : types.constant.defaultPrice // costs return { id: uuid(), label, section, group, price, quantities: {}, bmcGroup: bmcGroup, bmcId, bmcChecked: defaults[bmcId], custom: false } }) return checkedCategories.concat(newCategories) } else { return uncheckedCategories } }
JavaScript
function updateRevenueCategories(categories, products, customers) { const revenueCategories = generateRevenueCategories(products, customers) const newRevenueCategories = revenueCategories .filter(category => !categories.find(c => c.bmcId === category.bmcId)) const labels = {} revenueCategories.forEach(category => labels[category.bmcId] = category.label) return categories // filter categories that no longer exist .filter(category => category.bmcGroup === 'revenues' ? labels[category.bmcId] : true) // update label of existing categories .map(category => { return category.bmcGroup === 'revenues' ? category.set('label', labels[category.bmcId]) : category }) // append new categories .concat(newRevenueCategories) }
function updateRevenueCategories(categories, products, customers) { const revenueCategories = generateRevenueCategories(products, customers) const newRevenueCategories = revenueCategories .filter(category => !categories.find(c => c.bmcId === category.bmcId)) const labels = {} revenueCategories.forEach(category => labels[category.bmcId] = category.label) return categories // filter categories that no longer exist .filter(category => category.bmcGroup === 'revenues' ? labels[category.bmcId] : true) // update label of existing categories .map(category => { return category.bmcGroup === 'revenues' ? category.set('label', labels[category.bmcId]) : category }) // append new categories .concat(newRevenueCategories) }
JavaScript
function onAuth (accessToken, refreshToken, params, profile, done) { profile.auth = { accessToken: accessToken, refreshToken: refreshToken, params: params }; return done(null, profile); }
function onAuth (accessToken, refreshToken, params, profile, done) { profile.auth = { accessToken: accessToken, refreshToken: refreshToken, params: params }; return done(null, profile); }
JavaScript
function init_db () { // create the database if not existing // will just fail if already existing nano.db.create(DB_NAME, function(err){ if (!err) { debug('Database "' + DB_NAME + '" created'); } // create a view listing all documents of current user var view = { "_id": "_design/users", "_rev": "1-80752753bca4affbaad0789d9e8963c1", "views": { "docs": { "map": "function (doc) {\n if (doc.auth) {\n for (var userId in doc.auth) {\n if (doc.auth[userId] != undefined) {\n emit(userId, {id: doc._id, rev: doc._rev, title: doc.title, updated: doc.updated});\n }\n }\n }\n}" } } }; db.insert(view, function (err) { if (!err) { debug('View "' + view._id + '" created or updated'); } }); }); }
function init_db () { // create the database if not existing // will just fail if already existing nano.db.create(DB_NAME, function(err){ if (!err) { debug('Database "' + DB_NAME + '" created'); } // create a view listing all documents of current user var view = { "_id": "_design/users", "_rev": "1-80752753bca4affbaad0789d9e8963c1", "views": { "docs": { "map": "function (doc) {\n if (doc.auth) {\n for (var userId in doc.auth) {\n if (doc.auth[userId] != undefined) {\n emit(userId, {id: doc._id, rev: doc._rev, title: doc.title, updated: doc.updated});\n }\n }\n }\n}" } } }; db.insert(view, function (err) { if (!err) { debug('View "' + view._id + '" created or updated'); } }); }); }
JavaScript
function request (method, url, body) { debug('fetch', method, url, body) return fetch(BASE_URL + url, { method: method, headers: body ? new Headers({ 'Content-Type': 'application/json' }) : undefined, body: body ? JSON.stringify(body) : undefined, credentials: 'include' }).then((response) => { if (response.status < 200 || response.status >= 300) { debug('Error fetching user profile', response.status, response) throw new Error(`Error fetching ${method} ${url}`) } // Parse response body return response.json().then(data => { debug('fetch response', data) return data }) }) }
function request (method, url, body) { debug('fetch', method, url, body) return fetch(BASE_URL + url, { method: method, headers: body ? new Headers({ 'Content-Type': 'application/json' }) : undefined, body: body ? JSON.stringify(body) : undefined, credentials: 'include' }).then((response) => { if (response.status < 200 || response.status >= 300) { debug('Error fetching user profile', response.status, response) throw new Error(`Error fetching ${method} ${url}`) } // Parse response body return response.json().then(data => { debug('fetch response', data) return data }) }) }
JavaScript
function parseValue (value) { // parse a number const matchNumber = numberRegExp.exec(value) if (matchNumber) { let suffixes = { 'undefined': 1, k: 1e3, M: 1e6, B: 1e9, T: 1e12 } if (matchNumber[2] && (!(matchNumber[2] in suffixes))) { throw new Error('Invalid value "' + value + '"') } return parseFloat(matchNumber[1]) * suffixes[matchNumber[2]] } let matchPercentage = percentageRegExp.exec(value) if (matchPercentage) { return parseFloat(matchPercentage[1]) / 100 } return 0 }
function parseValue (value) { // parse a number const matchNumber = numberRegExp.exec(value) if (matchNumber) { let suffixes = { 'undefined': 1, k: 1e3, M: 1e6, B: 1e9, T: 1e12 } if (matchNumber[2] && (!(matchNumber[2] in suffixes))) { throw new Error('Invalid value "' + value + '"') } return parseFloat(matchNumber[1]) * suffixes[matchNumber[2]] } let matchPercentage = percentageRegExp.exec(value) if (matchPercentage) { return parseFloat(matchPercentage[1]) / 100 } return 0 }
JavaScript
function isWhitespace(str){ var re = /[\S]/g if (re.test(str)) return false; return true; }
function isWhitespace(str){ var re = /[\S]/g if (re.test(str)) return false; return true; }
JavaScript
function stripWhitespace(str, replacement){ if (replacement == null) replacement = ''; var result = str; var re = /\s/g if(str.search(re) != -1){ result = str.replace(re, replacement); } return result; }
function stripWhitespace(str, replacement){ if (replacement == null) replacement = ''; var result = str; var re = /\s/g if(str.search(re) != -1){ result = str.replace(re, replacement); } return result; }
JavaScript
function withTestSecurityGroupAndKey(subnetId, cb) { const ec2 = new aws.EC2(); return new Promise((resolve, reject) => { tmp.file(async (err, keyPath, keyfd) => { if (err) { reject(err); } let keyPair, response, securityGroup; try { // Get VPC ID from subnet const subnet = await ec2.describeSubnets({ SubnetIds: [subnetId] }).promise(); // Set up security group in subnet securityGroup = await ec2.createSecurityGroup({ Description: 'Allows inbound SSH', GroupName: `ec2-test-${uuid()}`, VpcId: subnet.Subnets[0].VpcId }).promise(); await ec2.authorizeSecurityGroupIngress({ GroupId: securityGroup.GroupId, IpPermissions: [{ FromPort: 22, ToPort: 22, IpProtocol: 'tcp', IpRanges: [{ CidrIp: '0.0.0.0/0' }] }] }).promise(); console.log(`Created temporary security group ${securityGroup.GroupId}`); keyPair = await ec2.createKeyPair({ KeyName: `ec2-test-${uuid()}` }).promise(); console.log(`Created temporary key pair ${keyPair.KeyName}`); await promisify(fs.write)(keyfd, keyPair.KeyMaterial); response = await cb(keyPair.KeyName, keyPath, securityGroup.GroupId); } catch (err) { reject(err); } finally { // Cleanup try { if (securityGroup) { console.log(`Deleting temporary security group ${securityGroup.GroupId} ...`); await ec2.deleteSecurityGroup({ GroupId: securityGroup.GroupId }).promise(); } if (keyPair) { console.log(`Deleting temporary key pair ${keyPair.KeyName} ...`); await ec2.deleteKeyPair({ KeyName: keyPair.KeyName }).promise(); } } catch (err) { console.log(err); } resolve(response); } }); }); }
function withTestSecurityGroupAndKey(subnetId, cb) { const ec2 = new aws.EC2(); return new Promise((resolve, reject) => { tmp.file(async (err, keyPath, keyfd) => { if (err) { reject(err); } let keyPair, response, securityGroup; try { // Get VPC ID from subnet const subnet = await ec2.describeSubnets({ SubnetIds: [subnetId] }).promise(); // Set up security group in subnet securityGroup = await ec2.createSecurityGroup({ Description: 'Allows inbound SSH', GroupName: `ec2-test-${uuid()}`, VpcId: subnet.Subnets[0].VpcId }).promise(); await ec2.authorizeSecurityGroupIngress({ GroupId: securityGroup.GroupId, IpPermissions: [{ FromPort: 22, ToPort: 22, IpProtocol: 'tcp', IpRanges: [{ CidrIp: '0.0.0.0/0' }] }] }).promise(); console.log(`Created temporary security group ${securityGroup.GroupId}`); keyPair = await ec2.createKeyPair({ KeyName: `ec2-test-${uuid()}` }).promise(); console.log(`Created temporary key pair ${keyPair.KeyName}`); await promisify(fs.write)(keyfd, keyPair.KeyMaterial); response = await cb(keyPair.KeyName, keyPath, securityGroup.GroupId); } catch (err) { reject(err); } finally { // Cleanup try { if (securityGroup) { console.log(`Deleting temporary security group ${securityGroup.GroupId} ...`); await ec2.deleteSecurityGroup({ GroupId: securityGroup.GroupId }).promise(); } if (keyPair) { console.log(`Deleting temporary key pair ${keyPair.KeyName} ...`); await ec2.deleteKeyPair({ KeyName: keyPair.KeyName }).promise(); } } catch (err) { console.log(err); } resolve(response); } }); }); }