How are my popups not showing in my Leaflet map? - javascript

How can I make popups show up in leaflet that I plot using this code?
leaflet(df) %>%
addTiles() %>%
setView(-119.09, 43.70, zoom = 5) %>%
addCircles(~long, ~lat, popup=df$hrus, color="#ffa500") %>%
addLegend("bottomright", colors= "#ffa500", labels="HRUs", title="P")
I can see the dots, but nothing shows up on the popup (Inside RStudio view pane). I tried saving it as HTML, but the saved page neither has the basemap nor the popup
How can I do it?
dput(df)
structure(list(lat = structure(c(41.26124, 41.45247, 41.50923,
41.57602, 41.62999, 41.60664, 41.63508, 41.83411, 41.84721, 41.84382,
41.83294, 41.85096, 41.60179, 41.8572, 41.64224, 41.85058, 41.14342,
41.77109, 41.35783, 41.39253, 41.78496, 41.5982, 41.66492, 41.70302,
41.56481, 41.55544, 41.59929, 41.71257, 41.85876, 41.42739, 41.39722,
41.76483, 41.49387, 41.46879, 41.50355, 41.95393, 41.8932, 41.96956,
41.76675, 41.93061, 41.93767, 41.53439, 41.51667, 41.50472, 41.5053,
41.67506, 41.68689, 41.78533, 41.79546, 41.87722), .Dim = 50L),
long = structure(c(-116.21489, -114.91972, -114.74541, -114.72553,
-114.83965, -114.81267, -114.84702, -113.49586, -113.48851,
-113.46151, -113.45017, -113.38449, -114.91356, -113.41496,
-114.85369, -113.50472, -116.21671, -114.25468, -116.32436,
-116.18391, -114.23875, -115.05154, -114.95098, -114.99438,
-115.75044, -115.89944, -115.84581, -114.9099, -114.19781,
-116.59131, -116.53819, -114.07782, -116.38066, -116.4347,
-116.33524, -113.51231, -113.51787, -113.55034, -114.96587,
-113.34303, -113.24616, -116.28699, -116.60549, -116.63497,
-116.55531, -115.19046, -114.72527, -114.64668, -114.54489,
-113.59969), .Dim = 50L), hrus = structure(1:50, .Label = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
"13", "14", "15", "16", "17", "18", "19", "20", "21", "22",
"23", "24", "25", "26", "27", "28", "29", "30", "31", "32",
"33", "34", "35", "36", "37", "38", "39", "40", "41", "42",
"43", "44", "45", "46", "47", "48", "49", "50"), class = "factor")), .Names = c("lat",
"long", "hrus"), row.names = c(NA, 50L), class = "data.frame")

Related

discord.js edit embed timeout

I made a fun command and I got no errors so far.
Here's the code:
const { MessageEmbed } = require('discord.js')
module.exports = {
name: "spin",
description: "spin",
permissions: ["SEND_MESSAGES"],
run: async (client, message, args) => {
if(message.author.bot) return;
let number = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36"];
let secondEmbed = new MessageEmbed()
.setTitle("The wheel is spinning...")
.setColor('#fc8eac')
.setTimestamp()
.addField("Spinner", `<#!${message.author.id}>`, true)
.addField("Result", ` <a:dotload:928216650614968321>`, true)
.setThumbnail('https://cdn.discordapp.com/emojis/928270805492699177.webp?size=160&quality=lossless')
.setFooter(`${message.author.tag}`, message.author.displayAvatarURL());
const m = await message.channel.send({embeds: [secondEmbed] })
let firstEmbed = new MessageEmbed()
.setTitle("The wheel has stopped spinning!")
.setColor('#fc8eac')
.setTimestamp()
.addField("Spinner", `<#!${message.author.id}>`, true)
.addField("Result", `${number[Math.floor(Math.random() * number.length)]}`, true)
.setThumbnail('https://cdn.discordapp.com/emojis/928270805492699177.webp?size=160&quality=lossless')
.setFooter(`${message.author.tag}`, message.author.displayAvatarURL());
await m.edit(({embeds: [firstEmbed] }), {timeout: 5000})
}
}
I'm having trouble on this line 'coz the embed gets edited in less than the given time length {timeout: 5000}
await m.edit(({embeds: [firstEmbed] }), {timeout: 5000})
I need help on how to fix this.
I'm not sure if there is a timeout option for the Message#edit method. At least I can't find it in the documentation.
However, you could use the good old setTimeout method to achieve the same:
setTimeout(() => {
m.edit({ embeds: [firstEmbed] })
}, 5000)

How to set a good date with chart js

I make a graph with NextJs and ChartJs on the stats of the covid (over the last 30 days) that I get with an API that provides me with the date and the stats :
timeline: {
cases: {
'5/13/21': 5902343,
'...' : ...
},
}
I managed to make the graph but I would like to place the date returned for each stats on the X line of my label
I managed to do this code (lineData is't my request) :
labels: [Object.keys(lineData.timeline.cases)],
but it shows me all the dates as one and the same object.
For now my label looks like this
labels: [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23",
"24",
"25",
"26",
"27",
"28",
"29",
"30",
],
and I would like to replace values with the one provided by the api
Object.keys returns an array. So currently you have an array of array like:
labels: [ ['5/13/21'] ]
You can just do:
labels: Object.keys(lineData.timeline.cases) // labels: ['5/13/21']

Compare Object properties that contain array with each other to find difference

Problem:
I am working on a mini project involving a JSON file and express/nodejs and I am stuck on a portion that contains the following instructions:
Using a post route, determine the user's most compatible friend using
the following rules: Convert each user's results into a simple array
of numbers.
Compare the difference between current user's scores against those
from potential matches, question by question. Add up the differences
to calculate the totalDifference.
Example: User 1: [5, 1, 4, 4, 5, 1, 2, 5, 4, 1] User 2: [3, 2, 6, 4,
5, 1, 2, 2, 4, 1]
Total Difference: 2 + 1 + 2 + 3 = 8
Remember to use the absolute value of the differences; no negative
results! Your app should calculate both 5-3 and 3-5 as 2, etc.
I am able to get the results that look like this (the submitted array is the last array all 5's):
Here is the portion of code I am using for that:
app.post('/surveyResponse', function(req,res){
let photo = req.body.url;
let name = req.body.name;
let travel = req.body.travel;
let affection = req.body.affection;
let family = req.body.family;
let fitness = req.body.fitness;
let movie = req.body.movie;
let education = req.body.education;
let career = req.body.career;
let marriage = req.body.marriage;
let children = req.body.children;
let pets = req.body.pets;
let sum = 0;
let obj = {};
let person = {
name: name,
photo: photo,
scores: [
travel,
affection,
family,
fitness,
movie,
education,
career,
marriage,
children,
pets
]
}
//finding the sum of all the numbers
for(i in person.scores){
sum+=Number(person.scores[i]);
}
//form submission results
let score = person.scores;
// Read the file and send to the callback
fs.readFile('./app/data/friends.json', handleFile)
// Write the callback function
function handleFile(err, data) {
if (err) throw err
obj = JSON.parse(data)
for(var key in obj){
var obj2 = obj[key];
console.log(obj2.scores);
}
//this is the console.log for my form submission array
console.log(score);
}
//------------------------------------
// result that prints out on the HTML
res.send('Your name is ' + name + ' You Score is ' + sum );
});
GOAL
The goal is the find the user with the least difference between their results and what the user submitted.
RESEARCH
I have done research How to compare each object in an array with each other. When found update the object with a new property How to Subtract Multiple Objects from an Array with Another array
and most of the examples deal with having separate JSON objects and comparing them to each other and the one I found that compared an array of JSON objects was just comparing phone numbers. I am stuck on my next steps. I just need a jump start/guidance please.
Here is the JSON file I am working with:
[
{
"name": "Mike Jackson",
"photo": "./app/public/matchPhotos/photo0.jpg",
"scores": [
"3",
"2",
"4",
"3",
"3",
"4",
"4",
"4",
"3",
"4"
]
},
{
"name": "Jermaine Subia",
"photo": "./app/public/matchPhotos/photo1.jpg",
"scores": [
"4",
"4",
"2",
"2",
"4",
"5",
"3",
"4",
"5",
"2"
]
},
{
"name": "Taji Gibson",
"photo": "./app/public/matchPhotos/photo2.jpg",
"scores": [
"1",
"5",
"3",
"2",
"3",
"1",
"3",
"4",
"3",
"3"
]
},
{
"name": "Jamie Schully",
"photo": "./app/public/matchPhotos/photo3.jpg",
"scores": [
"5",
"3",
"3",
"4",
"2",
"4",
"4",
"5",
"5",
"5"
]
},
{
"name": "Justin Andres",
"photo": "./app/public/matchPhotos/photo4.jpg",
"scores": [
"2",
"1",
"1",
"1",
"2",
"3",
"2",
"2",
"2",
"4"
]
},
{
"name": "Austin Brooks",
"photo": "./app/public/matchPhotos/photo5.jpg",
"scores": [
"2",
"3",
"4",
"2",
"4",
"4",
"4",
"4",
"5",
"4"
]
},
{
"name": "Jessica Jones",
"photo": "./app/public/matchPhotos/photo6.jpg",
"scores": [
"4",
"4",
"4",
"4",
"4",
"4",
"4",
"4",
"5",
"4"
]
},
{
"name": "Jasmine Love",
"photo": "./app/public/matchPhotos/photo7.jpg",
"scores": [
"4",
"3",
"3",
"2",
"2",
"2",
"2",
"1",
"2",
"1"
]
},
{
"name": "Sandra Smith",
"photo": "./app/public/matchPhotos/photo8.jpg",
"scores": [
"1",
"2",
"2",
"2",
"4",
"3",
"4",
"3",
"3",
"1"
]
},
{
"name": "Kevin Hart",
"photo": "./app/public/matchPhotos/photo9.jpg",
"scores": [
"5",
"5",
"3",
"3",
"2",
"2",
"5",
"5",
"4",
"3"
]
}
]
UPDATE 1
I am trying to incorporate the following code but am not understanding as to why I keep getting the following error:
ReferenceError: data is not defined
I believe it has to do with how I am trying to incorporate the incoming data. I took the code and tried to translate it to fit my code.
// Read the file and send to the callback
fs.readFileSync('./app/data/friends.json', findCompatibility); <---- This is the line I think is causing issues
// Write the callback function
function findCompatibility(data) {
var results = [];
for (let i = 0; i < data.length; i++) {
for (let j = 1; j < data.length - 1; j++) {
const user1 = data[i];
const user2 = data[j];
var difference = 0;
for (let k = 0; k < user1.scores.length; k++) {
difference += Math.abs(Number(user1.scores[k]) - Number(user2.scores[k]));
}
results.push({"name": user1.name, "friend": user2.name, "difference": difference});
}
}
return results;
}
console.log(findCompatibility(data));
Some pointers to point you in right direction:
To ensure that differences aren't negative use Math.abs() to get the absolute value of the difference.
Right now all the scores are strings, convert them to number using Number() or parseInt().
var data = [ { "name": "Mike Jackson", "photo": "./app/public/matchPhotos/photo0.jpg", "scores": [ "3", "2", "4", "3", "3", "4", "4", "4", "3", "4" ] }, { "name": "Jermaine Subia", "photo": "./app/public/matchPhotos/photo1.jpg", "scores": [ "4", "4", "2", "2", "4", "5", "3", "4", "5", "2" ] }, { "name": "Taji Gibson", "photo": "./app/public/matchPhotos/photo2.jpg", "scores": [ "1", "5", "3", "2", "3", "1", "3", "4", "3", "3" ] }, { "name": "Jamie Schully", "photo": "./app/public/matchPhotos/photo3.jpg", "scores": [ "5", "3", "3", "4", "2", "4", "4", "5", "5", "5" ] }, { "name": "Justin Andres", "photo": "./app/public/matchPhotos/photo4.jpg", "scores": [ "2", "1", "1", "1", "2", "3", "2", "2", "2", "4" ] }, { "name": "Austin Brooks", "photo": "./app/public/matchPhotos/photo5.jpg", "scores": [ "2", "3", "4", "2", "4", "4", "4", "4", "5", "4" ] }, { "name": "Jessica Jones", "photo": "./app/public/matchPhotos/photo6.jpg", "scores": [ "4", "4", "4", "4", "4", "4", "4", "4", "5", "4" ] }, { "name": "Jasmine Love", "photo": "./app/public/matchPhotos/photo7.jpg", "scores": [ "4", "3", "3", "2", "2", "2", "2", "1", "2", "1" ] }, { "name": "Sandra Smith", "photo": "./app/public/matchPhotos/photo8.jpg", "scores": [ "1", "2", "2", "2", "4", "3", "4", "3", "3", "1" ] }, { "name": "Kevin Hart", "photo": "./app/public/matchPhotos/photo9.jpg", "scores": [ "5", "5", "3", "3", "2", "2", "5", "5", "4", "3" ] } ];
function findCompatibility(data) {
var results = [];
for (let i = 0; i < data.length; i++) {
for (let j = 1; j < data.length - 1; j++) {
const user1 = data[i];
const user2 = data[j];
var difference = 0;
for (let k = 0; k < user1.scores.length; k++) {
difference += Math.abs(Number(user1.scores[k]) - Number(user2.scores[k]));
}
results.push({"name": user1.name, "friend": user2.name, "difference": difference});
}
}
return results;
}
console.log(findCompatibility(data));
var arr1 = [1,4,7,88,40];
var arr2 = [1,77,3,45];
function diff(a1, a2){
var s1 = a1.reduce((red,n) => red+n);
var s2 = a2.reduce((red,n) => red+n);
var total = s1 - s2;
return total >= 0 ? total : -1*total;
}
console.log(diff(arr2, arr1));

Mapping Firebase element as array

I am developing a Pool betting app. Everything looks good and Im finishing the final module on it.
In firebase, I have a POOL of bets, that have many users. Any user has many matches with their betting on the matches. Like this:
When I do a request on the firebase like this:
fetchPoolData = async () => {
const { firebaseApp } = this.props;
await firebaseApp
.database()
.ref(`/pools/${this.props.location.state.pool.key}/users`)
.once("value")
.then(snapshot => {
this.setState({
poolData: this.snapshotToArray(snapshot),
isLoadingPool: false
});
});
};
Everything Looks great. Now I have an array of users, and want to make some calculations to get the points each user did on each match. So Im mapping the users like this:
this.props.poolData.map(user => {
allUserMatches.push(calculatePoints(user.matches, outcomeMatches));
});
The issue here is that user.matches IS NOT being retrieved as an array. Instead, its coming like a big json object that I can map and make my math to calculate the points.
How can I map this element? If I do a Object.keys I only got a object like this:
Object.keys(user.matches)
(66) ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "result", "topscorer"
And If I do a Object.entries, it is still not very usefull (because I need to do a find on the objects of the array, to get the elements filtered by an atribute of the object).
Object.entries(user.matches)
(66) [Array(2), Array(2), Array(2), Array(2)
Im lost here. What to do?
If you want to use such mapping you can go with
Object.keys(user.matches).map(key => user.matches[key])
Above will return you keys from each object which later on can be used in map of object through their keys.
Also it doesn't return as array as you have two wild properties (result and topscorer) that doesn't work like array indexes so it need to return them as Object instead of an Array
A way to retrieve all values without result and topscorer from that key value pair
Object.keys(user.matches).filter(key => Number.isInteger(parseInt(key))).map(key => user.matches[key]).
This will transform the object with number indices (type string) to the array you want:
Object.keys(user.matches).reduce((arr, key) => {
arr[parseInt(key)] = user.matches[key]
return arr
}, [])

How to repeat a function with Javascript

This is the code that I've been working on, which makes the background color flicker colors. I'm wondering if anyone knows how to make this repeat so that the background continues to change colors on and on and on.
var a = new Array("ff", "ee", "dd", "cc", "bb", "aa", "99", "88", "77",
"66", "55", "44", "33", "22", "11", "00", "00", "11",
"22", "33", "44", "55", "66", "77", "88", "99", "AA",
"BB", "CC", "DD", "EE", "ff");
x = 0;
var b = new Array("ff", "ee", "dd", "cc", "bb", "aa", "99", "88", "77",
"66", "55", "44", "33", "22", "11", "00", "00", "11",
"22", "33", "44", "55", "66", "77", "88", "99", "AA",
"BB", "CC", "DD", "EE", "ff");
x = 0;
var c = new Array("00", "11", "22", "33", "44", "55", "66", "77", "88",
"99", "AA", "BB", "CC", "DD", "EE", "ff", "ff", "ee",
"dd", "cc", "bb", "aa", "99", "88", "77", "66", "55",
"44", "33", "22", "11", "00");
x = 0;
function bg_eff() {
col_val = "#" + a[x] + b[x] + c[x];
document.bgColor = col_val;
x++;
if (x == 32) {
clearInterval(change_bg);
}
}
change_bg = setInterval("bg_eff()", 50);
x = (x + 1) % 32;
Also, you should remove the clearInterval (and associated if), and there is no need to use a string for the setInterval:
change_bg = setInterval(bg_eff, 50);
modified code here (using jquery)
http://jsfiddle.net/generalhenry/S8g6k/1/
I use a recursive setTimeout instead of the interval, it's more resilient that way (if your function takes longer than the interval nothing odd occurs)
I would do this:
x += 1;
if ( x === 32 ) { x = 0; }
in addition to Matthew's answer but since the arrays are in the same sequence, you could do something like this.
var a = new Array("ff", "ee", "dd", "cc", "bb", "aa", "99", "88", "77", "66", "55", "44", "33", "22", "11", "00", "00", "11", "22", "33", "44", "55","66", "77", "88", "99", "AA", "BB", "CC", "DD", "EE", "ff"); // one array
var x = 0; // var for not global (even though in this context it still is...)
function big_eff() {
col_val = "#" + a[x] + a[(x + 5) % 32] + a[(x + 10) % 32]; // or whatever spacing you want
document.bgColor = col_val;
x = (x + 1) % 32;
setTimeout("big_eff()",50); // setTimeout baby!
}
a new version with pure Jquery
http://jsfiddle.net/generalhenry/S8g6k/5/
I use .animate for much cleaner code (no need for the arrays or the x++)
oh and warning: scary color swaping
$("body").css("background-color","#ffff00");
var bg_eff;
(bg_eff = function(x)
{
var duration = 1600;
if(x)
{
$("body").animate({backgroundColor:"#0000ff"},duration,function(){
bg_eff(false);
});
}
else
{
$("body").animate({backgroundColor:"#ffff00"},duration,function(){
bg_eff(true);
});
}
})(true);

Categories

Resources