How to add a div element in Viewer

the question is how to add a div element in Viewer.

enter image description here

the code is below.

cesium.js

import { Viewer, KmlDataSource } from "resium";
import { useState } from "react";
import styles from "../styles/Cesium.module.css";

const kml1 = ('./electric.kml');
const kml2 = ('./electric2.kml');

export default function Cesium() {
  const [showKml, setShowKml] = useState(false);
  const [showLabel, setShowLabel] = useState(false);

  const handleToggleKml = () => {
    setShowKml((prevShowKml) => !prevShowKml);
  };

  const handleToggleLabel = () => {
    setShowLabel((prevShowLabel) => !prevShowLabel);
  };


  return (
    <>
      <Viewer full>
        <KmlDataSource
          data={kml1}
          onLoad={(dataSource) => {
            console.log(dataSource);
          }}
          show={showKml}
        />
        <KmlDataSource
          data={kml2}
          onLoad={(dataSource) => {
            console.log(dataSource);
          }}
          show={showKml}
        />
        <div className={styles.buttonWrapper}>
          <button onClick={handleToggleLabel} className={styles.button}>
            button
          </button>
          {showLabel && (
            <label className={styles.label}>
              <input
                className={styles.input}
                type="checkbox"
                checked={showKml}
                onChange={handleToggleKml}
              />
              list
            </label>
          )}
        </div>
      </Viewer>
    </>
  )
}

index.js

import Head from 'next/head'
import dynamic from 'next/dynamic'

const Cesium = dynamic(
  () => import('../components/Cesium'),
  { ssr: false }
)

export default function Home() {
  return (
    <>
      <Head>
        <link rel="stylesheet" href="cesium/Widgets/widgets.css" />
      </Head>
      <Cesium />
    </>
  )
}

I want to add the div into the direct viewer.

Do I have to edit the library of resium or cesium?

I lost way to do that. Does anybody help me.

I tried that adding div into viewer, but that did not work.

animated text with javacript and requestAnimationFrame API

Am trying to make animated text using javascript without external modules,
here is what i have achieved now:

let i = 0;
function animateText(){
    const textContainer = document.querySelector('#skills');

    let txt = 'I am a web developer';
    setTimeout(function(){
        if(i == txt.length) return;
        
        textContainer.textContent += txt[i];
        i++;
        requestAnimationFrame(animateText);
    }, 100);

}

requestAnimationFrame(animateText);
#skills {
    border-right: 4px solid cadetblue;
    padding: .2rem;
    font-size: 2rem;
}
<span id="skills"></span>

my code works fine but i would like to make it more dynamic, the requestAnimationFrame API does not accept a function with parameters, so the question is how can i make a dynamic version of my code since the text and the element can be changed i want something like this

requestAnimationFrame(animateText(el, txt));

but this does not work since the animation API take the timestamp as an argument, https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame

any ideas or suggestions??

Insert encrypted token (Uint8Array) to mongodb

I’m trying to save encrypted token in mongodb. I’m using AWS KMS to encrypt the token. Then I save it in mongo. Buw when I try to fetch it back it returns as an object with unknown characters, and not as an ArrayBuffer. So when I try to decrypt it, KMS says
‘argument must be ArrayBuffer’

The object in mongo look like this.
I tried to insert the encrypted key exactly how it return from KMS encryption.

This is the returned object from mongoDB.

My question is how to properly save/fetch the encrypted data in/from mongoDB?

Thanks for any help

Array not properly updating (possible TLE)

So I am trying to code something similar to candy crush and am currently working on the array logic. The problem is however, that the array logic doesn’t seem to want to work in Javascript. I have done this project in Python’s Pygame already and this is the process of moving it over to Javascript, a language I’ve never used before, so bear with me.
As far as the problem, I am basically trying to generate a random array, remove all connected components larger than 3, replace them with zeros, shift the zeros to the top, then replace the zeros with random integers and repeat the process again until there are no connected components with a bigger size than 3. The problem however, is that the process doesn’t seem to finish (final print statements don’t print) and this makes me wonder if there is an infinite loop somewhere that I don’t see, or another issue. The compiler I was using was: https://www.programiz.com/javascript/online-compiler/, so it could be that the “break” it, but I doubt it.
As far as a minimum reproducable sample, here:

const candy_codes = {
    1: '/candies/Blue.png',
    2: '/candies/Green.png',
    3: '/candies/Orange.png',
    4: '/candies/Purple.png',
    5: '/candies/Red.png',
    6: '/candies/Yellow.png',
    7: '/candies/BlueWrapped.png',
    8: '/candies/GreenWrapped.png',
    9: '/candies/OrangeWrapped.png',
    10: '/candies/PurpleWrapped.png',
    11: '/candies/RedWrapped.png',
    12: '/candies/YellowWrapped.png'
};

const numOfRows = 9;
const numOfCols = 9;

let grid;
let gridContainerElem;
let visited
function createGridArray() {
    grid = new Array(numOfRows);
    for (let i = 0; i < numOfRows; i++) {
        grid[i] = new Array(numOfCols);
    }
}

function createImageGrid() {
    const maxNumOfCandyCodes = Object.keys(candy_codes).length - 6;

    for (let i = 0; i < numOfRows; i++) {
        // Generate image elements within row container
        for (let j = 0; j < numOfCols; j++) {
            image_num = (Math.floor(Math.random() * maxNumOfCandyCodes) + 1);
            
            grid[i][j] = image_num;
        }
    }
}

function createVisted(){
    visited = new Array(numOfRows);
    for (let i = 0; i < numOfRows; i++) {
        visited[i] = new Array(numOfCols);
    }
}

function clearVisited(){
    for (var i =0 ; i < numOfRows; i++){
        for (var j = 0 ; j < numOfCols; j++){
            visited[i][j] = false;
        }
    }
}


function printGridArray() {
    for (let i = 0; i < grid.length; i++) {
        let ranText = "";
        for (let j = 0; j < grid[i].length; j++) {
            ranText += grid[i][j];
            ranText += " ";
        }
        console.log(ranText);
    }
    console.log("Done printing!");
}

function dfs(i, j, grid) {

    let original_Value = grid[i][j];
    let stack = [[i, j]];
    let size = 0;
    while (stack.length != 0) {
        let [x, y] = stack.pop();
        visited[x][y] = true;
        size += 1;
        if (x + 1 < grid.length && grid[x + 1][y] == original_Value && !visited[x + 1][y]) {
            stack.push([x + 1, y]);
        }
        if (x - 1 >= 0 && grid[x - 1][y] == original_Value && !visited[x - 1][y]) {
            stack.push([x - 1, y]);
        }
        if (y + 1 < grid[x].length && grid[x][y + 1] == original_Value && !visited[x][y + 1]) {
            stack.push([x, y + 1]);
        }
        if (y - 1 >= 0 && grid[x][y - 1] == original_Value && !visited[x][y - 1]) {
            stack.push([x, y - 1]);
        }
        
    }
    return size;

}


function changingDFS(i, j, grid){
    let original_Value = grid[i][j];
    let stack = [[i, j]];
    clearVisited();
    while (stack.length != 0){
        let [x,y] = stack.pop();
        grid[x][y] = 0;
        visited[x][y] = true;
        if (x + 1 < grid.length && grid[x + 1][y] == original_Value && !visited[x + 1][y]) {
            stack.push([x + 1, y]);
        }
        if (x - 1 >= 0 && grid[x - 1][y] == original_Value && !visited[x - 1][y]) {
            stack.push([x - 1, y]);
        }
        if (y + 1 < grid[x].length && grid[x][y + 1] == original_Value && !visited[x][y + 1]) {
            stack.push([x, y + 1]);
        }
        if (y - 1 >= 0 && grid[x][y - 1] == original_Value && !visited[x][y - 1]) {
            stack.push([x, y - 1]);
        }
    }
    return clearVisited();
}

function eraseValidMoves() {
    var changesDone = false;
    clearVisited();

    for (let i = 0; i < numOfRows; i++) {
        for (let j = 0; j < numOfCols; j++) {
            if (!visited[i][j]) {
                var size = dfs(i, j, grid, visited);
                if (size >= 3) {
                    changingDFS(i,j , grid);
                    gravity();
                    changesDone = true;
                }
            }
        }
    }
    clearVisited()
    return changesDone;
}
function gravity(){
    const maxNumOfCandyCodes = Object.keys(candy_codes).length - 6;
    for (let j =0 ; j < grid[0].length; j++){
        var temp = [];
        for (let i = 0; i < grid.length; i++){
            if (grid[i][j] == 0){
                temp.unshift((Math.floor(Math.random() * maxNumOfCandyCodes) + 1));
            }
            else {
                temp.push(grid[i][j]);
            }
        }    
        for (let i = 0; i < temp.length; i++){
            grid[i][j] = temp.shift();
        }    
    }
    
}



createGridArray();
createImageGrid();
printGridArray();
createVisted();
clearVisited();

var erase = true;
while (erase){
    erase = eraseValidMoves();
}
console.log("All done!")
printGridArray();

That will work to get you the same error as I am. If you wanted to see the Python code that I am basing it off of: https://github.com/frankvp11/CandyCrush2.0/blob/main/candies.py
The functions that are basically shared right now are: is_valid, bfs, checker, custombfs, printgrid and gravity.

How does WEBRTC works? Is it possible to implement a demo offline?

How does WEBRTC works? Is it possible to implement a demo offline?
Which I need is:
Open two windows on browser, without web server, and send messages between them.
For example:

    const localPeer = new RTCPeerConnection();
    const offer = localPeer.createOffer();
    localPeer.setLocalDescription(offer)
    // output offer as TEXT on page
    const remotePeer = new RTCPeerConnection();
    remotePeer.setRemoteDescription(/* input the TEXT offer here*/);
    const answer = await remotePeer.createAnswer()
    remotePeer.setLocalDescription(answer)
    // output answer on page as TEXT
    localPeer.setRemoteDescription(/* input the TEXT answer here */)
    const localChannel = localPeer.createDataChannel("test")
    const remoteChannel = remotePeer.createDataChannel("test")
    localChannel.addEventListener("message", () => {})
    remoteChannel.addEventListener("message", () => {})

is it possible?

here is the demo, and it seems doesn’t work.
https://github.com/flowfire/demo-webrtc-001

How to have a faster rendering, when moving a slider for colorscale range, with Plotly?

The following code works to change the β€œmin” of the color scale of a Plotly heatmap with a slider.

But it is very slow : we have a 1 fps movement when dragging the slider.

Solutions like replacing “heatmap” by “heatmapgl” don’t really solve the problem (it maybe improves to 2 fps).

How to have a more responsive / faster change of the color scale with a slider?

For many applications, it is crucial to be able to see in “realtime” (more than 10 fps), the result of a change in the color scale, and it is possible to do this with Matplotlib, etc.

How to get the same behaviour in Plotly JS?

var z = Array.from({length: 500}, () => Array.from({length: 1000}, () => Math.floor(Math.random() * 500)));  
var steps = [], i;
for (i = 0; i < 500; i++)
    steps.push({label: i, method: 'restyle', args: ['zmin', i]});
Plotly.newPlot('myDiv',  [{z: z, colorscale: 'Jet', type: 'heatmap'}], {sliders: [{steps: steps}]});
<script src="https://cdn.plot.ly/plotly-2.16.2.min.js"></script>
<div id="myDiv"></div>

Javascript find pro rate value on the every month end in between two dates

I need to calculate pro rated value of every month end between two dates value. My sample values are here below.

enter image description here

I can able to arrive the solution using the for loop and the formula given below.

For every month,

(Number of month end days / Total number of days ) * Final value

I wanted to get pro rate value of End of January, February, March, April, May of Item ‘A’. But Is there any Javascript way to arrive this solution with the efficient code?

How to avoid echo in webrtc?

I need to implement simple peer to peer video calling app.

I use the next simple example.

When I run it locally and open web page on my MacBook / iPhone it has echo. I hear what I just told. Even before starting a call.

I record audio and quality is terrible:

const chunks = [];
navigator.mediaDevices.getUserMedia({ audio: true, video: false }).then(handleSuccess);
const handleSuccess = function (stream) {
    const mediaRecorder = new MediaRecorder(stream);
    mediaRecorder.addEventListener('dataavailable', (event) => {
        chunks.push(event.data);
        sendData(event.data);
    });
};

I tried the next code but it did not help:

const pc = new RTCPeerConnection(servers);
pc.setConfiguration({echoCancellation: true});
pc.setConfiguration({noiseSuppression: true, autoGainControl: true});

How to remove echo? Should I use separate lib for that?

Customize Upload Feature working but not showing File Name

I’m trying to customize my file upload feature. The code works fine, but does not show the file upload’s name.

I’ve tried to use JavaScript to display the name in the ‘span’ tag but it isn’t working.

Could you help me spot the problem with the code below.

Thanks in advance!


<script>

$('#getFile').change(function(){
$('#fileName').text($('#getFile')[0].files[0].name);
});

</script>
 
<span id="fileName">No file selected</span></font>
<input type="file" name="file" id="getFile" style="display: none">
<a style="text-decoration: none;" onclick="document.getElementById('getFile').click()">
Browse File ...
</a>

Angular click event of dropdown child is fighting with dropdown event

I have simple custom dropdown with items in angular. When I focus out from dropdown or press enter set method is called

Problem is that when i click on menu-item method setx is not called but again method set from focus out. What can I do to call method from click event because only method from focusout is called.

<dropdown (keydown.enter)="set($event)" (focusout)="set($event)">
        <menu-item *ngFor="let val of values"
                      (click)="setx(val)">
        </menu-item>
    </dropdown>

how to resolve lighthouse issue “Serve static assets with an efficient cache policy”

Hi as per the title i am trying to cache for SSR pages and below are the approach i’ve already tried but still getting issue in Lighthouse.
Lighthouse Report

export const getServerSideProps = async context => { context.res.setHeader( 'Cache-Control', 'public, maxage=10, stale-while-revalidate=59' ) const baseProps = await basePageServerSide(context, ROUTES.HOMEPAGE); return baseProps }

Please let me know if there are any other approach i can use to resolve this.

i tried caching using basepageServerSide

How to get telegram channel post history?

I need to get all the news from the telegram channel. I’ve read the documentation, and I see that I can only get getUpdates, which doesn’t show all the news, just the latest updates.But the documentation has a messages.getHistory method, but it requires some kind of peer, and no matter what I substitute into it, I always get an error.

I tried to use many libraries, one of them is telegram-mtproto,

const { Telegram } = require('telegram-mtproto');

const telegram = Telegram({
  api_id: "bot number before hash",
  api_hash: 'hash after : symbol',
});

export default async (req, res) => {

  try {

    const channelHistory = await telegram('messages.getHistory', {
      peer: ???,
      limit: 100,
    });

    res.end(JSON.stringify(channelHistory))
  
  } catch(error) {
    console.log(error)
    res.end("error")
  }
}

Maybe someone has already parsed news from the telegram channel, tell me what I’m doing wrong?

How to store dynamic references inside a loop and watch them?

I’m using Vue3 with a UI framework that doesn’t support stacked snackbars ( only one ). I’m trying to generate multiple ones and apply a custom margin to achieve the desired behaviour.

When creating the notification components I want to store their reference to the DOM element, so I can watch this collection and perform the custom CSS. I followed function-refs

Reproduction link

<script setup>
import { ref, onMounted, watch } from 'vue'

const items = ref(new Map())
const itemReferences = ref(new Map())

onMounted(() => {
  for(let i = 0; i < 5; i++) {
    const itemId = self.crypto.randomUUID();
    
    items.value.set(itemId, "message for id" + itemId);
  }
});

watch(itemReferences, () => {
  let divIndex = 0;
  
  for (const [key, divElement] of itemReferences.value) {
    console.log("perform CSS code on divElement here");
    
    divIndex++;
  }
}, { immediate: true });
</script>

<template>
  <div v-for="[key, value] in items" :key="key" :ref="(divElement) => { itemReferences.set(key, divElement) }">{{ value }}</div>
</template>

but unfortunately the watcher never runes. Do you have any ideas what’s wrong or missing?

Neo4j Queries cannot be run directly on a session with an open transaction; either run from within the transaction or use a different session

I am new to using Neo4J and I came across this error, I am closing and opening the sessions, however, I am receiving this error.

const session = driver.session({ database });
await session.run(`CREATE (u:USER} {name:"Test Demo"} ) return u`)

I use the above code in the signup function. I’m using session.close() at the finally block.
It is working fine for single requests. when I hit API from 2 devices simultaneously one API gets the error “Queries cannot be run directly on a session with an open transaction; either run from within the transaction or use a different session.”

If it is possible to handle multiple requests at same time, tell me how to achieve that. Thanks