Can Socket.IO work in Heroku but only locally?

So I’ve created a web app using ReactJS and Socket.IO, we were able to use it in our esports organization’s tournaments and was successfully executed. I’ve made one for LoL:Wild Rift & Valorant. But I’m planning on putting it on at least Heroku maybe so that other tournament organizers can use this overlay as well.

Basically, this app has 2 pages, the Index (AKA the Admin, “/”), and the Overlay (“/overlay”). Whatever I pick and ban in the Admin, gets transmitted to the Overlay in real-time. As well as the team names, scores, and player names.

So my question is, would it be possible to use Heroku but will only run the websocket/socket.io locally on whoever uses this app?

Here’s a demo of the app: https://youtu.be/LLb0xMhqcrQ

recursive backtracking algorithm that counts all solutions

I’m building a sudoku generator-solver app and currently finishing the hiding algorithm for useless cells.

I have a working backtracking algorithm that returns true when the solution is found, but I need to check if there’re any other solutions to prevent a wrong board from creating.

findEmpty function finds the next empty cell inside a sudoku board.
isValid function checks if the parameter passed fits in a current cell.
Provided code returns true if the board is solved.
It does overwrite the passed variable, so to access a solved board I call the variable passed.

If there’s at least one extra solution, the function must return false.
If the board cannot be solved, the function must return false.
If there’s a solution(only 1), return true

function backTrackSolve(board)
  {
      let find = findEmpty(board)
      if (find[0] == -1)
          return true
      
      let row = find[0]
      let col = find[1]
  
  
      for (let i = 1; i < 10; i++)
      {
  
          if (isValid(board, { row,col }, i))
          {
              board[row][col] = i
              if (backTrackSolve(board)){
                    return true
              }
  
            }
              board[row][col] = 0
      }
  
      return false
  
  }

Message collector not working discord js v13

        let filter = m => m.author.id === message.author.id
    const collector = message.channel.createMessageCollector({filter, time: 15000, max: 1});

    //name
    let name = message.author.username
    gender()
    //gender

    function gender(){
    embed = embed
    .setTitle(`${message.author.username}'s About Me setup || Gender`)
    .setDescription('Whats your gender/pronounce?')
    .setColor("BLUE")
    message.reply({embeds: })


    collector.on('collect', m =>{
        let gender = m.content
        m.channel.send(`${gender}`)
        age()
        })
}

    //age
    function age(){
    embed = embed
    .setTitle(`${message.author.username}'s About Me setup || Age`)
    .setDescription('How old are you?')
    .setColor("BLUE")
    message.reply({embeds: })

    collector.on('collect', m =>{
        let age = m.content
        m.channel.send(`${age}`)
        nationality()
        })
    }
    //nationality
    function nationality() {
    embed = embed
    .setTitle(`${message.author.username}'s About Me setup || Nationality`)
    .setDescription('Where are you from?')
    .setColor("BLUE")
    message.reply({embeds: })

    collector.on('collect', m =>{
        let nationality = m.content
        m.channel.send(`${nationality}`)
        description()
        })
}
    //description
    function description(){
    embed = embed
    .setTitle(`${message.author.username}'s About Me setup || Age`)
    .setDescription('Describe yourself, tell others your favorite hobbies, favorite movies, ect. in less than 1500 characters')
    .setColor("BLUE")
    message.reply({embeds: })

    collector.on('collect', m =>{
        if(m.content.length > 1500){
            embed = embed
            .setTitle(':warning: Error! :warning:')
            .setDescription('Your description can only be less than 1500 characters')
            .setColor("BLUE")
            message.reply({embeds: })
            description()    
        }
        let description = m.content
        m.channel.send(`${description}`)
        })
    }

hey, so I’m trying to make an about me command where when users say “about me setup” it will run through the setup and ask for information like gender, age, desc, etc. (the message.channel.send is just a placeholder, once I get it to work ill put it in an actual database), but it doesn’t seem to work like how I expected it to, here’s what happens when I try to run the command

I’m trying ….I had an idea so

Ok so here is what I want to do….

I want to write a script that compares an html element from a external website with an element located on my local file.

For example I go to stackoverflow.com and
run the webprogram(scripts) to compare x element with my z element located on my local file. Let’s make clear that I don’t want to save any information from stackoverflow I just want to compare the elements.

Is this possible with Javascript or I’m just to stupid?

Total newbie Ofc……

Security error when trying to use js-dos API to run DOS games

I’m trying to use the js-dos API to run DOS games on my website, but the emulator stops loading the game at 100% percent, and the browser console gives me this error:

Security Error: Content at file:///C:/Desktop/test.html may not load data from https://js-dos.com/v7/build/releases/latest/js-dos/wdosbox.js.

This is my code:

<script>
  emulators.pathPrefix =
    "https://js-dos.com/v7/build/releases/latest/js-dos/";
  Dos(document.getElementById("jsdos")).run(
    "https://doszone-uploads.s3.dualstack.eu-central-1.amazonaws.com/original/2X/2/24b00b14f118580763440ecaddcc948f8cb94f14.jsdos"
  );
</script>

Error adding leaflet marker in vue.js – Cannot read properties of null (reading ‘lat’)

I have the following code in Vue.js that retrieves some information from the database as it gets close to the coordinate. However, my code shows some errors when adding the markers to the leaflet map (getContributionsAndEMSI function), as shown in the following image. Also, sometimes the map indicates that the instance has already been initialized, even though I try to handle this situation within the beforeMount hook.

enter image description here

Vue.js code:

<template>
  <div id="map-container" class="w-full h-full z-10"></div>
</template>

<script>
/* eslint-disable global-require */
/* eslint-disable no-underscore-dangle */

import 'leaflet/dist/leaflet.css';

import L from 'leaflet';

import shp from 'shpjs';

import _ from 'lodash';

import wkt from 'wkt';
import EMSI from '../services/EMSI';
import Shapefile from '../services/Shapefile';
import contribution from '../services/Contribution';

import genHexColor from '../utils/colorGenerator';

delete L.Icon.Default.prototype._getIconUrl;

L.Icon.Default.mergeOptions({
  iconRetinaUrl: require('leaflet/dist/images/marker-icon-2x.png'),
  iconUrl: require('leaflet/dist/images/marker-icon.png'),
  shadowUrl: require('leaflet/dist/images/marker-shadow.png'),
});

export default {
  props: {
    useUserLocation: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      map: null,

      contributions: [],
      emsis: [],
    };
  },
  methods: {
    async getUserLocation() {
      try {
        const geolocation = await new Promise((resolve, reject) => {
          navigator.geolocation.getCurrentPosition(resolve, reject);
        });

        this.coords = geolocation.coords;
      } catch (error) {
        this.coords = { latitude: -20.7542, longitude: -42.8819 };
      }
    },
    getContributionsAndEMSI: _.debounce(async function (x, y) {
      let result = await contribution.index(x, y);
      if (result.success) {
        this.contributions = result.contribution;
      }

      result = await EMSI.index(x, y);
      if (result.success) {
        this.emsis = result.emsi;
      }

      // Error on showing contributions
      this.contributions.forEach((elemento) => {
        if (elemento.local.indexOf('POINT') !== '-1') {
          L.marker(wkt.parse(elemento.local).coordinates).addTo(this.map).bindPopup(
            `${'<strong>Tipo de colaboração: </strong>Colaboração normal<br>'
            + '<strong>Data de ocorrência:</strong> '}${elemento.occurrence}<br>`
            + `<strong>Vítimas:</strong> ${elemento.victims}<br>`
            + `<strong>Risco de danos:</strong> ${elemento.risk_damage}<br>`
            + `<strong>Descrição:</strong> ${elemento.desc}<br>`
            + `<strong>Categoria:</strong> ${elemento.category_name}`,
          );
        } else if (elemento.local.indexOf('LINESTRING') !== '-1') {
          L.polyline(wkt.parse(elemento.local).coordinates).addTo(this.map).bindPopup(
            `${'<strong>Tipo de colaboração: </strong>Colaboração normal<br>'
            + '<strong>Data de ocorrência:</strong> '}${elemento.occurrence}<br>`
            + `<strong>Vítimas:</strong> ${elemento.victims}<br>`
            + `<strong>Risco de danos:</strong> ${elemento.risk_damage}<br>`
            + `<strong>Descrição:</strong> ${elemento.desc}<br>`
            + `<strong>Categoria:</strong> ${elemento.category_name}`,
          );
        } else if (elemento.local.indexOf('POLYGON') !== '-1') {
          L.polygon(wkt.parse(elemento.local).coordinates).addTo(this.map).bindPopup(
            `${'<strong>Tipo de colaboração: </strong>Colaboração normal<br>'
            + '<strong>Data de ocorrência:</strong> '}${elemento.occurrence}<br>`
            + `<strong>Vítimas:</strong> ${elemento.victims}<br>`
            + `<strong>Risco de danos:</strong> ${elemento.risk_damage}<br>`
            + `<strong>Descrição:</strong> ${elemento.desc}<br>`
            + `<strong>Categoria:</strong> ${elemento.category_name}`,
          );
        }
      });

      // FIM - Visualização das contribuições
    }, 2000), // Espera 2 segundos pra mandar a requisição
    async fetchAndShow(e) {
      const center = e.target.getCenter();

      await this.getContributionsAndEMSI(center.lat, center.lng);
    },
  },
  beforeMount() {
    if (this.map) { this.map.off(); this.map.remove(); }
  },
  async mounted() {
    if (this.useUserLocation) {
      await this.getUserLocation();
    } else {
      this.coords = { latitude: -20.7542, longitude: -42.8819 };
    }

    const osm = L.tileLayer('https://{s}.tile.osm.org/{z}/{x}/{y}.png', {
      minZoom: 5,
      attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
    });

    const satellite = L.tileLayer.wms(
      'https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
      {
        minZoom: 5,
        maxZoom: 17,
        attribution:
          'Tiles &copy; Esri &mdash; Source: Esri, i-cubed, USDA, USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP, and the GIS User Community',
      },
    );

    const baseMap = {
      'Open Street Map': osm,
      'Visão Satélite': satellite,
    };

    // Definição e plotagem do mapa
    const map = L.map('map-container', {
      center: [this.coords.latitude, this.coords.longitude],
      layers: [osm],
      zoom: 15,
    });

    const layerControl = L.control.layers(baseMap, null, { collapse: true }).addTo(map);

    L.control.scale({ metric: true, imperial: false }).addTo(map);

    const center = map.getCenter();
    await this.getContributionsAndEMSI(center.lat, center.lng);

    map.on('dragend', this.fetchAndShow);

    // INÍCIO - Indexação de Shapefiles
    const shapes = await Shapefile.index('y');
    if (shapes.success) {
      shapes.shapefile.forEach((s) => {
        const randomColor = genHexColor();

        shp(s.uri)
          .then((data) => {
            let shpName = data.fileName.replaceAll(/[-_]/g, ' ');

            if (shpName.length > 25) {
              shpName = `${shpName.slice(0, 26)}...`;
            }

            layerControl.addOverlay(
              L.geoJSON(data, {
                style() {
                  return { color: randomColor };
                },
              }),
              shpName,
            );
          })
          .catch((err) => {
            console.warn('Um ou mais arquivos não possuem layers!', err);
          });
      });
    }
    // FIM - Indexação de Shapefiles

    this.map = map;
  },
};
</script>

Recursive loop to build object

I can’t figure out how to explain this right, but I wanna make a function that takes this array:

const tasks = [
    {id: 1, goal: 'Clean apartment', parent_id: null},
    {id: 2, goal: 'Clean bathroom', parent_id: 1},
    {id: 3, goal: 'Clean kitchen', parent_id: 1},
    {id: 4, goal: 'Clean sink', parent_id: 2},
    {id: 5, goal: 'Clean shower', parent_id: 2},
    {id: 6, goal: 'Make app', parent_id: null}

]

and generates this object:

{id: 1, goal: 'Clean apartment', parent_id: null, children: [
    {id: 2, goal: 'Clean bathroom', parent_id: 1, children: [
        {id: 4, goal: 'Clean sink', parent_id: 2, children: []},
        {id: 5, goal: 'Clean shower', parent_id: 2, children: []},
    ]},
    {id: 3, goal: 'Clean kitchen', parent_id: 1, children: []},
]},
{id: 6, goal: 'Make app', parent_id: null, children: []}

Restart button using html & js

How do you add a restart button on this game so that every time user click on the button it restart the game. Tried few ways to do it but i think i am dumb lol, just cant figure it out.
Anyone knows how to do that ?

How do you add a restart button on this game so that every time user click on the button it restart the game. Tried few ways to do it but i think i am dumb lol, just cant figure it out.
Anyone knows how to do that ?

html    
----------
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Rock Paper Scissors Tutorial</title>
  </head>
  <body>

    <h2>Computer Choice: <span id="computer-choice"></span></h2>
    <h2>Your Choice: <span id="user-choice"></span></h2>
    <h2>Result: <span id="result"></span></h2>

    <button id="rock">rock</button>
    <button id="paper">paper</button>
    <button id="scissors">scissors</button>
    <div class="restart">Re-Start</div>

    <script src="app.js" charset="utf-8"></script>
  </body>
</html>
--------
js file
---------
const computerChoiceDisplay = document.getElementById('computer-choice')
const userChoiceDisplay = document.getElementById('user-choice')
const resultDisplay = document.getElementById('result')
const possibleChoices = document.querySelectorAll('button')
let userChoice
let computerChoice
let result

possibleChoices.forEach(possibleChoice => possibleChoice.addEventListener('click', (e) => {
  userChoice = e.target.id
  userChoiceDisplay.innerHTML = userChoice
  generateComputerChoice()
  getResult()
}))

function generateComputerChoice() {
  const randomNumber = Math.floor(Math.random() * 3) + 1 // or you can use possibleChoices.length
  
  if (randomNumber === 1) {
    computerChoice = 'rock'
  }
  if (randomNumber === 2) {
    computerChoice = 'scissors'
  }
  if (randomNumber === 3) {
    computerChoice = 'paper'
  }
  computerChoiceDisplay.innerHTML = computerChoice
}

function getResult() {
  if (computerChoice === userChoice) {
    result = 'its a draw!'
  }
  if (computerChoice === 'rock' && userChoice === "paper") {
    result = 'you win!'
  }
  if (computerChoice === 'rock' && userChoice === "scissors") {
    result = 'you lost!'
  }
  if (computerChoice === 'paper' && userChoice === "scissors") {
    result = 'you win!'
  }
  if (computerChoice === 'paper' && userChoice === "rock") {
    result = 'you lose!'
  }
  if (computerChoice === 'scissors' && userChoice === "rock") {
    result = 'you win!'
  }
  if (computerChoice === 'scissors' && userChoice === "paper") {
    result = 'you lose!'
  }
  resultDisplay.innerHTML = result
}

document.getElementById("reset").onclick = function() {
  document.getElementById("number").innerHTML = "";
};

Paypal invoice status stays on “DRAFT”

i have got a problem recently trying to make a paypal invoice. well, check this code here.

paypal.invoice.create({
        merchant_info: {
            email: "EMAIL",
            first_name: "FIRST_NAME",
            last_name: "LAST_NAME",
            business_name: "NAME",
            phone: {
                country_code: "CODE",
                national_number: "NUMBER"
            },
            address: {
                line1: "STREET",
                city: "Riyadh",
                state: "Riyadh Province",
                postal_code: "0000",
                country_code: "SA"
            }
        },
        status: "UNPAID",
        billing_info: [{
            "email": "[email protected]"
        }],
        items: [],
        note: `Thank You For Buying`
    })

Ok, i got the invoice made and everything, but the status is “DRAFT”, can someone explain please?
btw i want the status to be “UNPAID”

Enviar cookies por metodo Get axios NodeJs a un web services

estoy queriendo enviar una cookie que me devuelve otra petición.
Lo he intentado enviar de muchas formas pero al revisar las cookies del header del web services veo que no las recibe.

Este es mi codigo..
enter image description here

        var config2 = {
            method: 'get',
            url: 'https://srienlinea.sri.gob.ec/sri-captcha-servicio-internet/captcha/start/1',
            headers: { 
              'set-cookie': 'BIGipServerDecla_Sesion=404619530.47873.0000; path=/; Httponly; Secure',
              withCredentials: true
            },
            data : data
          };

          //console.log(config2.headers);
          
          axios(config2)
          .then(function (response) {                
            console.log('cookie 2');
            console.log(JSON.stringify(response.headers['set-cookie'][1]));
          })
          .catch(function (error) {
            console.log(error);
          });

testcafe within circleci chrome keeps getting disconnected

I have the following circleci job to run my testcafe tests,

# Job to run testcafe e2e test suite
e2e-test:
  executor: machine-ubuntu
  description: Run e2e tests on local app in the pipeline container
  working_directory: ~/project
  parameters:
    is_local:
      type: boolean
      default: true
    testcafe_base_url:
      type: string
      default: https://localhost:4180/<redacted>
  steps:
    - checkout:
        path: ~/project
    - browser-tools/install-browser-tools
    - install-dependencies
    - run:
        name: Install ffmeg for video recording
        command: npm i @ffmpeg-installer/ffmpeg
    - when:
        condition: << parameters.is_local >>
        steps:
          - run:
              name: Setup docker compose file
              command: ./scripts/setup-docker-compose-file.sh
          - run:
              name: Run app locally
              command: docker-compose up -d
    - run:
        name: Wait for app to be live
        command: ./scripts/wait-for-server.sh <<parameters.testcafe_base_url>>
    - run:
        name: Run e2e test suite
        command: npm run testcafe:chrome:headless chromium --no-sandbox testcafe/fixtures/*.ts --config-file .testcaferc.ci.json -r xunit:/tmp/test-results/testcafe/results.xml --video /tmp/artifacts/videos
        environment:
          TESTCAFE_BASE_URL: <<parameters.testcafe_base_url>>
    - store_test_results:
        path: /tmp/test-results
    - store_artifacts:
        path: /tmp/artifacts/videos

however, I keep getting the following

The Chrome 99.0.4844.51 / Linux 0.0 browser disconnected. If you did not close the browser yourself, browser performance or network issues may be at fault

Here is the message within circleci
enter image description here

Everything is green up until it starts running the tests, I’ve ran these locally and they all pass, so not sure what’s going on.

Here is my executors and orbs

executors:
  docker-node:
    resource_class: large
    docker:
      - image: cimg/node:16.13.1
  machine-ubuntu:
    machine:
      image: ubuntu-2004:202010-01

commands:
  install-dependencies:
    description: Installs dependencies
    steps:
      - checkout:
          path: ~/project
      - run:
          name: NPM install
          command: npm ci
      - run:
          name: NPM cdk
          command: cd cdk && npm ci

orbs:
  browser-tools: circleci/[email protected]

Hide elements based on their Page or class using JS or JQuery

I’m using Jquery FullPage.js for scrolling pages inside website.
How can I write a simple js script, where, for example, if we are on the firstPage the elements will dissappear, and if we are on the other pages fixed element will remain?
I just don’t know JS well, but the logic is like – if firstPage element display none – else display block.
Thank You

How does the var x and var lineY code work?

I have this processing.js code made on khan academy:

background(255, 255, 247);
stroke(173, 222, 237);

for (var i = 0; i < 20; i++) {
    
    var lineY = 20 + (i * 20);
    line(0, lineY, 400, lineY);
    
}

for (var j = 0; j < 20; j++) {
    
    var x = 20 + (j * 20);
    line(x, 0, x, 400);

}

What does the

var lineY = 20 + (i * 20);

code do? And what does the

var x = 20 + (j * 20);

code do?

Im a beginner