Mapbox zoom level per country

Hi i’m trying to find a way to show a country by a country code in Mapbox.

I’m using country-iso-to-coordinates to get the coordinates by country code

For example searching FR (France) i’m getting 2.213749, 46.227638 as center points. This works, but i’d like to set the zoom level fitting the country’s boundaries. France for example looks perfect at zoom level 4.3, while big countries like Russia or China need zoom level ~ 2.2

data() {
    return {
        accessToken: 'xxxxx',
        mapStyle: 'mapbox://styles/psteger/cl0y1upof001f16sxix3n00oe',
        center: [10, 51],
        zoom: 4.3,
        minZoom: 2.2,
        maxZoom: 14,
        markers: [],
        params: {
            access_token: 'xxxxx',
            country: 'de',
            language: 'en'
        }
    }
},
mounted() {
    const coordinates = IsoToLatLong[this.userCountry];
    this.center = [coordinates.coordinate[1], coordinates.coordinate[0]]
},

How can i find a good zoom level per country without manually trying and writing a list for each single country? Is there a package with ratios of each country so i could calculate the zoom levels or can mapbox set a zoom level by a country’s borders?

Thanks for any help!

Subsequent mediarecorder webcam recordings are corrupted when uploaded

I am trying to record 3 movies after eachother, with different instructions showing to the user. The code seems to work fine, the instructions change, the variables I am logging check out fine (chunks recorded, saving recording).

After running the script, I have 3 webm files, all roughly the same size. However, only one is playable. The other two are corrupted. Been tinkering alot in the code, but everything seems to be fine.

Would love if someone could give a hand!

Initialization:

    var constraints = { audio: true,video: {width: {min: 1280}, height: {min: 720}, facingmode: 'user'}};
navigator.mediaDevices.getUserMedia(constraints).then((stream) => { video.srcObject = stream; cameraStream = stream;  startRecording(); });

StartRecording function:

function startRecording() 
{
    if(stage == 1) 
    {
        console.log('Started stage '+stage);
        lineOne.innerHTML = "Kijk recht in de camera";
        line.animate(1);
        fName = 'base'; 
         
        
    }
    if(stage == 2) 
    {
        lineOne.innerHTML = "Kijk over uw linkerschouder";
        line.set(0);
        line.animate(1);
        fName = 'left';
    }
    if(stage == 3) 
    {
        lineOne.innerHTML = "Kijk over uw rechterschouder";
        line.set(0);
        line.animate(1);
        fName = 'right';
    }
    blobs_recorded = [];
    mr = new MediaRecorder(cameraStream);
            
        
    mr.addEventListener('dataavailable', function(e) {
            blobs_recorded.push(e.data);
             
    });
        
        
    
    mr.start(500);
    setTimeout(function(){stopRecording(fName);},5000);     
   
    
    
}

Stop recording / save file / start next movie:

function stopRecording(name) 
{
    recording = null;
    mr.stop();
    console.log("stopped recording");
    console.log(blobs_recorded.length);
    recording = new File(blobs_recorded, name+'.webm', { type: 'video/webm' });
    
    var xhr = new XMLHttpRequest();
    
    
    const upload = new FormData();
    upload.append('file',recording);
    upload.append('fileName',name);
    upload.append('code',code);
    upload.append('renterId',renterId);

    
    xhr.open('POST','upload.php',false);
    
    xhr.send(upload);
    stage = stage+1;
    lineOne.innerHTML = "";
    if(stage < 4) 
    {
        startRecording();
    }
    

}

After running the script, I got a base.webm / left.webm and right.webm, but only base.webm is playable, the other two are corrupted.

E056 – ‘addNewJoke’ was used before it was declared, which is illegal for ‘const’ variables [duplicate]

I’m a beginner web developer but as far as I know, we can use call functions before declaring.
The guy I am learning from did exactly the same, like no difference but there was no problem for him.

problem: E056 – ‘addNewJoke’ was used before it was declared, which is illegal for ‘const’ variables. I also tried using let but still the same problem.

Heres the code:

const jokes = document.querySelector("#jokes")
const button = document.querySelector('button')
button.addEventListener('click', addNewJoke)

const addNewJoke = async () => {
const jokeText = await getDadJoke();
console.log(jokeText)

}


const getDadJoke = async () => {
const headers = {headers: {Accept: 'application/json'}}
const res = await axios.get('https://icanhazdadjoke.com/',headers);
return res.data.joke;
}
getDadJoke();

Keeps saying “unhandled promise rejection” and “missing ) after argument list”?

So, I’m trying to send a regular message saying- “Click the rainbow pancakes to bake!” with a custom reaction attached. Then when the user clicks the rainbow pancake reaction I want it to send an embed saying alot, has a title, color, description, footer, thumbnail and etc. This is the code I am trying to use!—

const { Database } = require("quickmongo");
const db = new Database("mongodb+srv://Nixie:[email protected]/test");
const ms = require("parse-ms");

module.exports = {
  name: "bake",
  aliases: ["b"],
  /**
  *
  * @param {Client} client
  * @param {Message} message
  * @param {String[]} args
  */
  run: async (client, message, args) =>  {

    let user = message.author;


    db.on("ready", () => {
      console.log(`Fetched wish Database from - userId: ${user.id}`);
    });
  
    // top-level awaits
    await db.connect(); 

  let amount = [3, 6, 9]
  let amountOutcome = Math.floor(Math.random() * amount.length) 
  let reaction = ('<:rpck:954892806214791212>')
  let timeout = 180000;//5 mins

  let daily = await db.get(`bakeTime-${user.id}`);

  if (daily !== null && timeout - (Date.now() - daily) > 0) {
      let time = ms(timeout - (Date.now() - daily));

      let timeEmbed = new MessageEmbed()
          .setColor("0A0301")
          .setDescription(`❌ You've already bakednnBake again in ${time.hours}h ${time.minutes}m ${time.seconds}s!!`);
      message.channel.send({embeds: [timeEmbed]})
  } else {
   
    bot.on('bake', message => {
    if(message.author.bot) return;

    if(message.content.toLowerCase() === 'bake'){
  
        const embed = new Discord.MessageEmbed();
        embed.setTitle("<:tppc:953062342680252476>..**It's Time To Bake!!**..<:tppc:953062342680252476>")
        embed.setColor("0A0301");
        embed.setThumbnail('https://i.postimg.cc/7LGcsBHV/bake.jpg')
        embed.setFooter("Tip! You can bake again in 15 minutes!","https://i.postimg.cc/139pM3Rd/nixiethumbnail.jpg")
        embed.setDescription("Bake time! Earn some <:galaxp:952320002848092161> by clicking on the Rainbow Pancakes!n**Use your Galaxy Pop in the ~starcandyshop!!");
        message.channel.send(embed).then(embedMsg => {
            embedMsg.react('<:rpck:954892806214791212>')
            .then(reaction => embedMsg.react('<:rpck:954892806214791212>'))
            .catch(err => console.error);

            const filter = (r, u) => r.emoji.id == '<:rpck:954892806214791212>';
            const collector = message.createReactionCollector(filter, {time: 60000});
            collector.on('collect', (r, u) => {
               //Put your response to reactions here
               message.channel.send("You baked some Rainbow Pancakes!! " + u.tag + " because you reacted with " + r.emoji.name + ` **and earned ${amountOutcome} <:galaxp:952320002848092161>**`);
            });
      message.channel.send({embeds: });
      db.add(`galaxyPop-${user.id}`, amountOutcome)
      db.set(`bakeTime-${user.id}`, Date.now())
  })};
  }
}```

ANY and ALL Help is much appreciated! TIA!

Why does the error “JSX element type ‘Home’ does not have any construct or call signatures.” appear when using react-router-dom?

I have tried to use react-router-dom to create my routes, but I have this error:

JSX element type ‘Home’ does not have any construct or call
signatures.

I have this component:

import React from "react";

function Home() {
  return <div>Home</div>;
}

export default { Home };

And here is where I am using the route:

 import React from "react";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";

import Home from "./Pages/Home/Home";

export default function AppRoutes() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Home />} />
      </Routes>
    </Router>
  );
}

How to reenable Intellisense/suggestions in VS Code (I may have accidentally removed the program’s path for the dictionary

I hope I’m using the correct terms here. In VS Code, I messed up the program’s Intellisense. It no longer shows most methods/options/suggestions (specifically for Javascript, I haven’t tried others. If I type ‘consol’ in an empty .js file, nothing pops up. If I type ‘console.l’ it will suggest ‘console.log’. But if I type ‘console.’, it won’t suggest anything at all. It used to, but I think I wrecked something when I was messing with deep program settings, trying to disable them (the wrong way).

What I’m looking for is this:
code suggestions
VS Code used to give Javascript suggestions like these, when typing built-in Javascript components, like Date, or Console.
But now, it only suggests things you’ve already typed, but that’s about it. The same code from above (the date), looks like this in VS Code:
vs code lacking suggestions

Nothing pops up when I get that ‘.’ after the variable name. No methods or suggestions whatsoever.

Any help would be GREATLY appreciated.

D3 heatmap change specific rect color in react js

I am using D3 to display over 10k grid, and each rect has own color.
But there are several specific rect info which comes from backend API, I need to change those specific rects’ color.

My code is:

const ref = useD3(
    (svg) => {

      const tooltip = d3.select(".tooltip");

      const mouseleave = function(d) {
        tooltip.style("opacity", 0);
        d3.select(this)
          .style("stroke", "#FFF")
          .style("stroke-opacity", 0.3)
          .style("stroke-width", 1)
          .style("opacity", "1");
      };
    
      svg.select(".main-area")
        .selectAll("rect")
        .data(data1, function(d) {return 'price: ' + d.price;})
        .enter()
        .append("rect")
          .attr("x", d => d.x)
          .attr("y", d => d.y)
          .attr("width", d => d.width )
          .attr("height", d=> d.height )
          .style("stroke-width", 1)
          .style("stroke", "#FFF")
          .style("stroke-opacity", 1)
          .style("opacity", 1)
          .style("cursor", "pointer")
        .on("mouseover", mouseover)
        .on("mouseleave", mouseleave)
        .on("mousemove", mousemove)
        .on("click", mouseclick);
    },

    [data1]
  );

As you can see above code, I appended ‘rect’ to “.main-area”.
After this, I want to change specific rects’ color when event happens.

Here is what I’ve done.

// on event…
// custom D3

var svg = d3.select('svg');
       svg.select(".main-area")
          .select("rect")
          .attr('x', decX)
          .attr('y', decY)
          .attr('fill', "#ef32d3"); 

But it doesn’t work.

What meaning the dash in array when iterating an array in for of loop with entries iterator?

If I normally use for of loop and use iterator as entries that situation look like this:

var a = ['a', 'b', 'c'];
var iterator = a.entries();

for (let e of iterator) {
  console.log(e);
}
// [0, 'a']
// [1, 'b']
// [2, 'c']

iterator: will be the entire array that contain all elements key/value pair. Key will be the index.

e: will be an element in the array

BUT what is this??????

let text = "A A A";
let splitwords = text.split(" ");
let words = [];
for (const [, item] of splitwords.entries()) {
  words.push(item.split(""));
}

console.log(`This is the words: ${words}`);

what meaning the [, item] part???

and why should i use this pattern?

text.split(“”) do exactly same thing or not?

(Otherwise I try solve an text animation problem and this inherit from that code:

framer motion text animation )

Thank you

Angular js adding attribute directive from another directive

Pretend I have this:
<span ng-bind="value" my-dir my-dir-param="value"></span>
So my-dir is a custom directive that adds another directive to an existing element.
I guess it gonna look like this (skipping everything except some props from dir. def. object:

...
priority: 1001,
terminal: true
compile: function(el, attrs) {
 attrs.$set("some_directive", "placeholder_text");
 var compiled = $compile(el, null, 1001);
 return function linkFn(scope, el, attrs) {
  compiled(scope)
  ...some extra logic here...
}
}
...

I’ve tried to do such away and the problem is that ng-bind will bind on value from the directive scope, not the outer scope. I don’t want to affect scopes from which other directives absorb values. What I want is that by adding my-dir directive I will apply “some_directive” and that won’t affect the values that other directives receive. Thank you

Remove Last Character in th using ajax

how to remove last character inside of table header using javascript/ajax?

Example table

Product Price X
First 1000
Second 2000

what i want to reach is remove the X on Price X column header with some button, I’ve use slice before but not working.

how i supposed to do?

Thanks

how to avoid recursion or to fix the problem?

Teaching JS trying to do a ticatactoe game and got a problem with recursion, specifically with ‘Maximum call stack size exceeded’.

When I try to make a random move by the computer player I make a random number, which then will be checked of his value in array called gameState.
So, if this value has defined already (there are X or O mark in a cell), I need to generate a random number again. So I need to stop this infinite loop when all cells are marked or I’ll get an error ‘Maximum call stack size exceeded’.

Can you please take a look, am I do the right thing or it is generally wrong?
Actually, I thought about another implementation of this game scene, but I thought if i’ve started with that I should lead this to the end


let gameState = ["", "", "", "", "", "", "", "", "",];
let playerAi = "O";

// ai's turn
function playerAiTurn() {
    let randomNum = Math.floor(Math.random() * gameState.length);
    if (gameState[randomNum] === '') {
    gameState[randomNum] = playerAi;
    document.getElementById(randomNum).innerHTML = playerAi;
    resultCheck();
    } else {
        playerAiTurn()
    };
};

catch in promise not working in javascript

Any ideas why my .catch won’t work whenever I provide a wrong number (“articlenumber” that doesn’t exist)?

fetch(`/scripts/articles/${articlenumber}.txt`)
    .then(response => response.text())
    .then(responsearticle => articlecontent.innerHTML = responsearticle)
    .catch(function() {
        console.log("File not found")
});