React Google Maps and unnecessary re-render

I am working on a simple app that shows a list of places in Europe.
I am using @react-google-maps/api and apollo client to get the data which is then passed to the markers.
Every time the user zooms or moves the map, the app will call a graphQL endpoint and get the new data to render, based on the map bounds.

My issue is that when I zoom on the map, it works fine and smoothly, but when I drag (move) the map then the map flashes and basically goes to the initial state. This happens also when I simply set the state inside the handleBounds function, but what I don’t understand is why it works fine with zooming but not with dragging, I tried also using the drag_end event but is always the same situation. I am stuck with this issue for some time now.
Here is the whole code:

export const Map = () => {
  const [map, setMap] = useState<google.maps.Map | null>(null)

  const {
    data = {
      map: [],
    },
    loading,
    error,
    refetch,
  } = useQuery(GET_PROPERTIES_ON_MAP, {
    variables: {
      bounds: map?.getBounds()?.toJSON(),
    },
  })

  const onLoad = useCallback(
    (map: google.maps.Map) => {
      map.fitBounds(EUROPE_BOUNDS)
      setMap(map)
    },
    [setMap]
  )

  const options: GoogleMapProps["options"] = {
    restriction: {
      latLngBounds: EUROPE_BOUNDS,
      strictBounds: false,
    },
  }

  const handleBounds = useCallback(() => {
    const bounds = map?.getBounds()?.toJSON()
    if (bounds) {
      refetch({ bounds })
    }
  }, [map, refetch])

  if (loading) {
    return <p>Loading ...</p>
  }

  return (
    <div
      style={{
        height: 400,
        borderRadius: 8,
        overflow: "hidden",
        marginTop: 32,
      }}
    >
      <GoogleMap
        mapContainerStyle={{ height: "100%" }}
        zoom={4}
        center={DEFAULT_CENTER}
        onLoad={onLoad}
        onBoundsChanged={handleBounds}
        clickableIcons
        options={options}
      >
        {data.map.map((property: Property) => (
          <Marker key={property.id} lat={property.lat} lng={property.lng} />
        ))}
      </GoogleMap>
    </div>
  )
}

this code

const handleBounds = useCallback(() => {
    const bounds = map?.getBounds()?.toJSON()
    if (bounds) {
      refetch({ bounds })
    }
  }, [map, refetch])

is what causes the issue, basically I tried all the GoogleMaps options including onDrag** events, but nothing each time the app re-renders, but weirdly it works when the user is zooming. Any idea what am I doing wrong?
Thanks

Using charts in HTML wil chart.js

I’m trying to learn how to create graphs using chart.js, but for some reason my chart isn’t showing up on my webpage

Here’s the code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>

    <div style="width: 900px; height: 400px;">
        <canvas id="myChart"></canvas>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.2.1/chart.min.js" integrity="sha512-v3ygConQmvH0QehvQa6gSvTE2VdBZ6wkLOlmK7Mcy2mZ0ZF9saNbbk19QeaoTHdWIEiTlWmrwAL4hS8ElnGFbA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

    <script>

        let labels = ['Big Mac', 'QuarterPounder', 'Mcdouble', 'Doubler Cheeseburger', 'Hamburger'];
        let itemData = [550, 520, 400, 450, 250];

        const data = {
            labels: labels,
            dataset: [{
                data: itemData,
                backgroundColor: 'rgb(66,221, 245)'
            }]
        };

        const config = {
            type: 'bar',
            data: data
        };

        const chart = new Chart(
            document.getElementById('myChart'),
            config
        );
    </script>


</body>
</html>

Ajax XMLHttpRequestUpload returning null and “progress” eventListener not working even though the file has been uploaded

To learn more JavaScript and PHP, I am currently working on a small private project that allows me to upload single or multiple files to my server via PHP. The file/s get sent to the PHP script via Ajax. If I upload several files, I send one file after the other in a loop via Ajax to the PHP script. Since I wanted to make the visual part of the upload a bit more appealing, I added a progress bar via xhr.upload and a “progress” eventlistener, which worked well until a while ago.

However, after uploading a file for the first time in a while, I noticed that the progress bar no longer works. In the meantime, the code around the function has of course been extended, but the function itself has remained the same. Furthermore, uploading the file(s) to the server works perfectly and I get no errors.

After a few console outputs, it quickly became clear that the xhr.upload function only returns “null” values (see screenshot below). I guess that the “progress” eventlistener not firing is also due to this?

Console output of XMLHttpRequest after upload

Im working with php 8.0.8 and i am using MAMP as my localhost.
I tested in Chrome and Safari.

This is my JavaScript function with which I send the files via Ajax to my upload.php:

let percentComplete = [];
let xhr = [];
let j = 0;

function uploadFiles() {
    text.innerHTML = "Sendet ...";
    
    $("#mssgBox").css({ 'display': 'block', 'bottom': '0' });

    let formData = new FormData();
    formData.append('file[]', fileListArr[j]);
    let progressbarID = $(".progressbar_" + id[j]);
    $.ajax({
        url: "../upload.php",
        type: "POST",
        xhr: function () {
            xhr[j] = new XMLHttpRequest();
            console.log(xhr[j]);
            xhr[j].upload.addEventListener("progress", function (e) {
                console.log(e.loaded + ' & ' + e.total + ' & ' + Math.floor((e.loaded / e.total) * 100));
                progressbarID.css({ "width": Math.floor((e.loaded / e.total) * 100) + '%' });
                //notifyMe('Uploading', Math.floor((e.loaded / e.total) * 100));
            }, false);
            return xhr[j];
        },
        error: function (error) {
            text.innerHTML += '<br/>Error: ' + error;
        },
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
        timeout: 60000
    }).done(function (respond) {
        text.textContent = '';
        text.innerHTML += respond + '<br/>';
        console.log(respond);
        notifyMe(respond, '100');

        j = j + 1;
        if (j < fileListArr.length) {
            uploadFiles();
        } else {
            j = 0;
        }

        $("#uploadedFiles").load("filesuploaded.php");
    });
}

My upload.php:

<?php
session_start();
include('assets/imgResize.php');
$total_count = count($_FILES['file']['name']);

$phpFileUploadErrors = array(
  0 => 'ACHTUNG: There is no error, the file uploaded with success',
  1 => 'ACHTUNG: The uploaded file exceeds the upload_max_filesize directive in php.ini',
  2 => 'ACHTUNG: The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
  3 => 'ACHTUNG: The uploaded file was only partially uploaded',
  4 => 'ACHTUNG: No file was uploaded',
  6 => 'ACHTUNG: Missing a temporary folder',
  7 => 'ACHTUNG: Failed to write file to disk.',
  8 => 'ACHTUNG: A PHP extension stopped the file upload.',
);

for ($i = 0; $i < $total_count; $i++) {
  if ($_FILES["file"]["error"][$i] > 0) {
    $errorCode = $_FILES["file"]["error"][$i];
    echo $phpFileUploadErrors[$errorCode];
  } else {
    if (file_exists("upload/" . $_SESSION['userUid'] . '/' . str_replace(' ', '_', $_FILES["file"]["name"][$i]))) {

      echo "ACHTUNG: " . $_FILES["file"]["name"][$i] . " existiert bereits.<br/>";

    } else {

      if (imageType($_FILES["file"]['tmp_name'][$i])) {
        $image = scaleImageFileToBlob($_FILES['file']['tmp_name'][$i], 'thumb_' . $_SESSION['userUid'] . '_' . str_replace(' ', '_', $_FILES["file"]["name"][$i]));
        if ($image == '') {
          echo 'ACHTUNG: Image type not supported';
        }

      }

      $uploadFile = move_uploaded_file($_FILES["file"]["tmp_name"][$i], "upload/" . $_SESSION['userUid'] . '/' . str_replace(' ', '_', $_FILES["file"]["name"][$i]));
      if ($uploadFile) {
        echo $_FILES["file"]["name"][$i] . " erfolgreich hochgeladen";
      } else {
        echo "ACHTUNG: Fehler beim hochgeladen von " . $_FILES["file"]["name"][$i];
      }
    }
  }
}
?>

Can someone tell me for what reason I only get null values for my xhr.upload?

Also if you need more information, I will give them to you.

Thanks in advance 🙂

P.S. I can imagine that doing multiple ajax requests in a loop like I did is probably not optimal but it’s the only way I managed to get one progressbar per uploaded file.

Using to ask for user consent before loading external resources

I made a site which embeds a Google Programmable Search Engine. But I want it to show a <dialog> asking the user for consent prior to loading scripts from Google.

In order not to annoy returning visitors, a “remember my consent” checkbox shall be used to store a cookie which prevents the dialog from popping up again.

I figured out to adapt the dialog demo from Mozilla to already fit roughly my needs (➡️ jsfiddle)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />    
  <style>
    dialog::backdrop {
      backdrop-filter: blur(5px);
    }
  </style>
</head>
<body>
  
  <dialog id="favDialog">
    <form method="dialog">
      <p><strong>If you proceed, Google will collect and process data according to the <a href="#">Google Privacy Policy</a>.</p>
      
      <div>
        <button value="disagreed">Cancel</button>
        <button id="confirmBtn" value="agreed">I Agree</button><br />
        
        <input type="checkbox" id="chkRemember" name="chkRemember" value="agreed-plus-cookies">
        <label for="chkRemember">Remember my consent (this requires cookies, <a href="#">legal mumbo-jumbo</a> applies)</label>
      </div>
    </form>
  </dialog>
  
  <output></output>
  
  <div class="gcse-searchresults-only" id="gcse_results"></div>
  
  <script>
    const gcse_results = document.getElementById('gcse_results');
    const favDialog = document.getElementById('favDialog');
    const outputBox = document.querySelector('output');
    const confirmBtn = favDialog.querySelector('#confirmBtn');
    const chkRemember = favDialog.querySelector('#chkRemember');
    
    
    // automatically open the <dialog>
    window.addEventListener("load", (event) => {
      favDialog.showModal();
    });
    
    // checkbox sets value of the submit buttom
    chkRemember.addEventListener('change', (e) => {
      confirmBtn.value = chkRemember.value;
    });
    // "Confirm" button of form triggers "close" on dialog because of [method="dialog"]
    favDialog.addEventListener('close', () => {
      outputBox.value = `ReturnValue: ${favDialog.returnValue}.`;
    });
  </script>  

  <script async src="https://cse.google.com/cse.js?cx=c6dd01376f2fb45af"></script>

</body>
</html> 

The dialog returns 3 possible values: disagreed, agreed, agreed-plus-cookie

What I could not figure out yet is how to actually process ${favDialog.returnValue}, i.e.:

  1. When agreed is returned, add the following code to the dom: <script async src="https://cse.google.com/cse.js?cx=mycode"></script>
  2. When agreed-plus-cookies is returned, do the same as 1. and place a cookie
  3. When disagreed is returned, add a short explanation to the site’s body (e.g. “sorry, this site does not work without loading stuff from google, see faq”)
  4. When the cookie from 2. is already present, do not automatically open the and proceed as in 1.

Plain JS is highly appreciated.

This is my 2nd attempt for this post. Sorry for my poor first try, I hope I am doing better—and thanks to those who pointed me to dialog at all. Turns out, a lot has happened to the web in the past. 🙂

How to remove padding from html element when pasted in js

there is a problem with inserting html into js , when inserting indents are added and I don’t understand why. Building a simple calculator

for (var i = 0; i < num.length; i++) {
    num[i].addEventListener("click", function () {
        if (!operator) {

            console.log(this)
            num1 += this.textContent
            ny.push(num1)
            console.log(ny)
            result.innerHTML = num1;
        } else if (operator.length > 0) {

            num2 += this.textContent
            result.innerHTML = num2;
        }


    })

}

enter image description here

If any two numbers’ multiplication in array is greater than 26 return true, otherwise false

Return the string true if any two numbers can be multiplied so that the answer is greater than double the sum of all the elements in the array. If not, return the string false.

let arr = [2,2,2,2,4,1]
function SumMultiplier(arr) { 

  let sum = arr.reduce((acc, item) => acc +item,0)
  let trueStr = "true"
  let falseStr = "false"
  let double = sum*2
  let arrLength = arr.length
  let i = 0
  let j = 1
  while(i < arrLength){
    let multi = arr[i] * arr[j]
    if(double < multi) {
      j++
    }else{
      return trueStr
    }
  }
  return falseStr 

}

i found double the sum of all elemets in array, but cant solve multiplaction each element in array.

Reactnative map function does not render view

I have the following screen :-

import React, { useEffect, useState } from "react";
import { View, StyleSheet, ScrollView, Text } from "react-native";
import Header from "../components/Header";
import PageTitle from "../components/PageTitle";
import BottomLine from "../components/svg/BottomLine";
import Button from "../components/Button";
import SelectDropdown from "react-native-select-dropdown";
import { User } from "../services/User";


const Users = ({ navigation }) => {
  const [isLoading, setIsLoading] = useState(true);
  const [data, setData] = useState();
  const [roles, setRoles] = useState();
  const [selectedRole, setSelectedRole] = useState("مراقب");

  useEffect(() => {
    User.getAll().then((res) => {
      setData(res.data);
      let apiRoles = [];
      res.data.forEach((row) => {
        apiRoles.push(row.name);
      });
      setRoles(apiRoles);
      setIsLoading(false);
    });
  }, []);

  console.log("data", data);
  return (
    <View style={styles.container}>
      <Header style={{ alignSelf: "center" }} />

      <ScrollView style={{ marginRight: 13, marginLeft: 13 }}>
        <PageTitle>المستخدمون</PageTitle>
        <BottomLine />
        <View style={{ display: "flex", flexDirection: "row" }}>
          <SelectDropdown
            buttonStyle={{
              alignSelf: "center",
              width: "80%",
              marginBottom: 12,
              borderWidth: 1,
              height: 40,
            }}
            data={!isLoading && roles}
            defaultButtonText="الصلاحية"
            //onSelect={onChange}
            buttonTextAfterSelection={(selectedItem, index) => {
              // text represented after item is selected
              // if data array is an array of objects then return selectedItem.property to render after item is selected
              return selectedItem;
            }}
            rowTextForSelection={(item, index) => {
              // text represented for each item in dropdown
              // if data array is an array of objects then return item.property to represent item in dropdown
              return item;
            }}
          />
          <Button
            onPress={() => navigation.navigate("NewUser")}
            style={{ marginLeft: "auto", marginTop: 0, height: 40 }}
          >
            + اضافه
          </Button>
        </View>

        {isLoading && (
          
            <Text
              style={{
                alignSelf: "center",
                marginTop: 55,
                color: "#ecebeb",
              }}
            >
             Loading...
            </Text>
            
        )}
      </ScrollView>
      {!isLoading &&
        data.map((r) => {
          console.log("r.users", r.users);
          r.users.map((user, i) => {
            console.log("user.first_name", user.first_name);
            return <Text style={{ color: "black" }}>Test Text</Text>;
          });
        })}
    </View>
  );
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: "#fff",
  },
});
export default Users;

The map function on above code should render a text, but nothing showing:-

    r.users.map((user, i) => {
                console.log("user.first_name", user.first_name);
                return <Text style={{ color: "black" }}>Test Text</Text>;
          });

Output screen:-
enter image description here

Log:-
enter image description here

ml5.js error when creating a neural network

I’m following this tutorial: https://www.youtube.com/watch?v=3MqJzMvHE3E&t=480s on shape classification and I’m encountering the problem

Uncaught Error: Error in oneHot: depth must be >=2, but it is 1
    at oneHot_ (tf-core.esm.js:17:357944)
    at Object.oneHot (tf-core.esm.js:17:71801)
    at NeuralNetworkData.js:560:38
    at tf-core.esm.js:17:40461
    at t.scopedRun (tf-core.esm.js:17:40603)
    at t.tidy (tf-core.esm.js:17:40355)
    at Object.rn (tf-core.esm.js:17:67569)
    at t.value (NeuralNetworkData.js:550:15)
    at NeuralNetworkData.js:533:33
    at Array.forEach (<anonymous>)

I’m using ml5.js version 0.6.0 and here is my js file:

const circles = []

function preload() {
    for(let i = 0; i < 10; i++) {
        let index = nf(i+1, 4, 0);
        circles[i] = loadImage(`/data/circle/circle${index}.png`)
    }
}

let shapeClassifier;

function setup() {
    let options = {
        inputs: [128, 128, 4],
        task: 'imageClassification',
        debug: true
      };
      shapeClassifier = ml5.neuralNetwork(options);
    
      for (let i = 0; i < circles.length; i++) {
        shapeClassifier.addData({ image: circles[i] }, { label: 'circle' });
      }
      shapeClassifier.normalizeData();
      shapeClassifier.train({ epochs: 50 }, () => finishedTraining());
}
    
function finishedTraining() {
    console.log('finished training!');
}

I’m not familiar with ml5 or machine learning in general so I have no idea what this error means or how to fix it, I would really appreciate the help!

I expected it to work and start training the neural network but it didn’t and got this error instead

I expected it to start training the model on the input data but instead got that error

I want to change JavaScript code snippet to Python code snippet

<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
<script>
    var e = '00ad5ef1ed2619e45c2591819e55ad9b04cd4801821c15177312e490b18f51446e0626a079aa2be1d84030ddf618b63115qm1aYI7SySPXm/hxvoJFMfgHpE/RjXIIGpT7ShdeXRYijBT9COM0Pj4ku+m2rLOyBc3GeQKfFC+u6kdLSa0C0pu+sMUZoMAbXGuKM/CoFrOhgivTKrYEwwmUZB2wtmi4uh3nudyX9jPU3visJd91FFH4vZAm7RTae9ZjwXUNZPdVsD1ErscLV9eJXKWmBbs0dgYLpLydk3mGMYQ/if8FX32wg/6tBSFej6o790aTuKnwjJfq2TbpDitqz+xCK1vNgGpwo2PBdcsasobasoAlsrZCXxWfPxE+TzvdIOAHG6qVQYb0+I/EBjacmVX/+R80lkrzpOLQXCyTt52ubUk7UWHKjWuT26RtUL6edWKLexuNSXCDVWksuPJoR0lMz8'
    var o = 'cxqj5edKQYprkbHo5lkYQFGSIqZCpkAM6l2UX6p1Ws3q1vb1xLHuZqG7n2v9EJFk.cG9ydGFsX2RvbWFpbi9lbGQ0'
    var t = o.substr(0, 32),
        s = e.substr(0, 64),
        n = e.substr(64, 32),
        r = e.substr(96),
        i = CryptoJS.PBKDF2(t, CryptoJS.enc.Hex.parse(s), {
            keySize: 4,
            iterations: 1e3,
            hasher: CryptoJS.algo.SHA256
        }),
        u = CryptoJS.AES.decrypt(r, i, {
            iv: CryptoJS.enc.Hex.parse(n)
        }),
        l = u.toString(CryptoJS.enc.Utf8);
</script>

I’m trying to change the above JavaScript code snippet to Python, but I can’t get the result I want.

This is the result I want:

&result_code=00&result_msg=&now_round_num=1290003&lotto_name=스피드키노&last_sec=282&sell_sts=1&prev_round_num=1290002&prev_round_status=5&prev_winnum=44,51,57,68,67,35,07,01,39,50,40,11,56,60,46,55,61,21,26,06,34,30:865&money=0&coupon=0&buy_data=&is_last_inning=N&is_last_pre_inning=N&etc=&

The value of the variable l is the above data.

renderUI not returning graph from javascript to R Shiny app

I am trying to create a force graph using javascript within an R shiny application. The code for the app is below.

library(shiny)
library(jsonlite)
network_data <- jsonlite::read_json("miserables.json")

ui <- fluidPage(
  
    tags$script(src='https://d3js.org/d3.v6.min.js'),
    titlePanel("force graph example - miserables"),
    sidebarLayout(
        sidebarPanel(
          actionButton(
            "go",
            label = "go"
          )
        ),
        mainPanel(
          p("yo"),
          uiOutput("output_result")
        )
    )
    
)

# Define server logic required to draw a histogram
server <- function(input, output, session) {
  
  observeEvent(input$go, {
      session$sendCustomMessage(type = "jsondata",network_data)
    },ignoreNULL = TRUE,ignoreInit = TRUE)
  output$output_result <- renderUI({
    result <- HTML('<script type="text/javascript", src="fn_canvas.js">  </script>')
    return(result)
  })
  
}

# Run the application 
shinyApp(ui = ui, server = server)

The application is pretty simple. You hit the go button and it sends the miserables JSON to a javascript file, called fn_canvas.js, which should create the force graph. The code for the force graph can be found here which I pulled and created this javascript file.

Shiny.addCustomMessageHandler('jsondata', function(message) {
  
  console.log("helllooooo")
  var network_data = message;
  
  function ForceGraph({
    nodes, // an iterable of node objects (typically [{id}, …])
    links // an iterable of link objects (typically [{source, target}, …])
  }, {
    nodeId = d => d.id, // given d in nodes, returns a unique identifier (string)
    nodeGroup, // given d in nodes, returns an (ordinal) value for color
    nodeGroups, // an array of ordinal values representing the node groups
    nodeFill = "currentColor", // node stroke fill (if not using a group color encoding)
    nodeStroke = "#fff", // node stroke color
    nodeStrokeWidth = 1.5, // node stroke width, in pixels
    nodeStrokeOpacity = 1, // node stroke opacity
    nodeRadius = 5, // node radius, in pixels
    nodeStrength,
    linkSource = ({source}) => source, // given d in links, returns a node identifier string
    linkTarget = ({target}) => target, // given d in links, returns a node identifier string
    linkStroke = "#999", // link stroke color
    linkStrokeOpacity = 0.6, // link stroke opacity
    linkStrokeWidth = 1.5, // given d in links, returns a stroke width in pixels
    linkStrokeLinecap = "round", // link stroke linecap
    linkStrength,
    colors = d3.schemeTableau10, // an array of color strings, for the node groups
    width = 640, // outer width, in pixels
    height = 400
    ///, // outer height, in pixels
    ///invalidation // when this promise resolves, stop the simulation,
  } = {}) {
    // Compute values.
    const N = d3.map(nodes, nodeId).map(intern);
    const LS = d3.map(links, linkSource).map(intern);
    const LT = d3.map(links, linkTarget).map(intern);
    const G = nodeGroup == null ? null : d3.map(nodes, nodeGroup).map(intern);
    const W = typeof linkStrokeWidth !== "function" ? null : d3.map(links, linkStrokeWidth);
    const L = typeof linkStroke !== "function" ? null : d3.map(links, linkStroke);
  
    // Replace the input nodes and links with mutable objects for the simulation.
    nodes = d3.map(nodes, (_, i) => ({id: N[i]}));
    links = d3.map(links, (_, i) => ({source: LS[i], target: LT[i]}));
  
    // Compute default domains.
    if (G && nodeGroups === undefined) nodeGroups = d3.sort(G);
  
    // Construct the scales.
    const color = nodeGroup == null ? null : d3.scaleOrdinal(nodeGroups, colors);
  
    // Construct the forces.
    const forceNode = d3.forceManyBody();
    const forceLink = d3.forceLink(links).id(({index: i}) => N[i]);
    if (nodeStrength !== undefined) forceNode.strength(nodeStrength);
    if (linkStrength !== undefined) forceLink.strength(linkStrength);
  
    const simulation = d3.forceSimulation(nodes)
      .force("link", forceLink)
      .force("charge", forceNode)
      .force("center",  d3.forceCenter(width/2, height/2))
      .on("tick", ticked);
  
    /// Is it ok to do the below??!
    function context2d(width, height, dpi) {
      if (dpi == null) dpi = devicePixelRatio;
      var canvas = document.createElement("canvas");
      canvas.width = width * dpi;
      canvas.height = height * dpi;
      canvas.style.width = width + "px";
      var context = canvas.getContext("2d");
      context.scale(dpi, dpi);
      return context;
    }
  
    const context = context2d(width, height);
    ///const context = DOM.context2d(width, height);
  
    function ticked() {
      context.clearRect(0, 0, width, height);
  
      context.save();
      context.globalAlpha = linkStrokeOpacity;
      for (const [i, link] of links.entries()) { 
        context.beginPath();        
        drawLink(link);
        context.strokeStyle = L ? L[i]: linkStroke;
        context.lineWidth = W ? W[i]: linkStrokeWidth;
        context.stroke();
      }
      context.restore();
  
      context.save();
      context.strokeStyle = nodeStroke;
      context.globalAlpha = nodeStrokeOpacity;
      for (const [i, node] of nodes.entries()) {
        context.beginPath();
        drawNode(node) 
        context.fillStyle = G ? color(G[i]): nodeFill;
        context.strokeStyle = nodeStroke;
        context.fill();
        context.stroke();
      }
      context.restore();
    }
  
    function drawLink(d) {
      context.moveTo(d.source.x, d.source.y);
      context.lineTo(d.target.x, d.target.y);
    }
  
    function drawNode(d) {
      context.moveTo(d.x + nodeRadius, d.y);
      context.arc(d.x, d.y, nodeRadius, 0, 2 * Math.PI);
    }  
  
    ///if (invalidation != null) invalidation.then(() => simulation.stop());
  
    function intern(value) {
      return value !== null && typeof value === "object" ? value.valueOf() : value;
    }
  
    function drag(simulation) {    
      function dragstarted(event) {
        if (!event.active) simulation.alphaTarget(0.3).restart();
        event.subject.fx = event.subject.x;
        event.subject.fy = event.subject.y;
      }
      
      function dragged(event) {
        event.subject.fx = event.x;
        event.subject.fy = event.y;
      }
      
      function dragended(event) {
        if (!event.active) simulation.alphaTarget(0);
        event.subject.fx = null;
        event.subject.fy = null;
      }
  
      function dragsubject(event) {
        return simulation.find(event.sourceEvent.offsetX, event.sourceEvent.offsetY);
      }
      
      return d3.drag()
        .subject(dragsubject)
        .on("start", dragstarted)
        .on("drag", dragged)
        .on("end", dragended);
    }
  
    console.log("finished")
    return Object.assign(d3.select(context.canvas).call(drag(simulation)).node(), {scales: {color}});
    
  }
  
  chart = ForceGraph(network_data, {
    nodeId: (d) => d.id,
    nodeGroup: (d) => d.group,
    linkStrokeWidth: (l) => Math.sqrt(l.value),  
    width: 600,
    height: 600
    ///,
    ///invalidation, // a promise to stop the simulation when the cell is re-run
  })
  return chart
  
});

Once you hit the go button in the application, the force graph should be returned from the javascript file. However, currently nothing is returned from the file. I even print console messages which say the code was run. I’m not sure whether there is an issue with my R code or the javascript code. Any help appreciated. Thanks for reading.

why is php generating different hmac-sha256 compared to online generators?

I am using below php code to generate hmac-sha256 and encode it to base64

$data ="sdkfhglkjfdsglfdslkgjdfl;kjsdflk;jsdlgldgweprepoifepiorgi";
$secret = "da851675-c797-4edd-b492-af1c0753e5c0";
$hash = hash_hmac('sha256', $data, $secret);
$base64 = base64_encode($hash);
echo $base64;

but hash is always different from the hash generated from online generators like https://www.javainuse.com/hmac or https://www.devglan.com/online-tools/hmac-sha256-online

same is the case with below javascript code as well.

var data ="sdkfhglkjfdsglfdslkgjdfl;kjsdflk;jsdlgldgweprepoifepiorgi"
var secret = "da851675-c797-4edd-b492-af1c0753e5c0"
function generate_data_hash(data, secret) {
    var hash = CryptoJS.HmacSHA256(data, secret);
    var hashInBase64 = CryptoJS.enc.Base64.stringify(hash);
    return hashInBase64
}
console.log(generate_data_hash(data, secret))

any clue on what’s going on wrong here?

How can I set the img in the slider?

const slides = [
  {
    eachSlide: "url(https://www.consilium.europa.eu/media/54319/erasmus.png)",
  },
  {
    eachSlide: "url(https://unsplash.it/1900/1024/?image=291)",
  },
  {
    eachSlide: "url(https://unsplash.it/1900/1024/?image=786)",
  },
  {
    eachSlide: "url(https://unsplash.it/1900/1024/?image=768)",
  },
  {
    eachSlide: "url(https://unsplash.it/1900/1024/?image=726)",
  },
  {
    eachSlide: "url(https://unsplash.it/1900/1024/?image=821)",
  },
];
.slider {
  width: 85vw;
  height: 65vh;
  overflow: hidden;
  position: relative;
  margin-top: 2%;
  margin-left: 5%;
}

.slider .each-slide {
  width: 100vw;
  height: 100vh;
  image-rendering: auto;
  float: left;
  line-height: 100vh;
  font-size: 40vh;
  text-align: center;
  background-size: cover;
  background-position: center center;
  background-color: transparent;
}

The slider feature was broken when it was necessary to change the width and height.A different image I added does not fit in this range.It looks like it’s half-fitted.How can I give width-height to a different image I added?

Fetch OMDB API 2 times

I’m trying to fetch OMDB API to get a list of movies IDs and limit them to 3 and then map over them to get detailed info for each movie.

Here’s the code I have, It only work for the first movie ID in the IDs array

export const load = async () => {
    const moviesList = await fetch(`https://www.omdbapi.com/?apikey=${SECRET_API_KEY}&s=avengers`);
    const moviesData = await moviesList.json();
    const movies = moviesData.Search;
    const movieId = movies.map(m => m.imdbID)
    const movieData = await fetch(`https://www.omdbapi.com/?apikey=${SECRET_API_KEY}&i=${movieId[0]}`);
    const movie = await movieData.json();
    return {
        movieId,
        movie
    }
}

How do I insert values from first and second API response into my 3rd API call’s request ? (Angular RXJS)

        registerUser(){
    
          let payload={
            "Id": 0,
            "UserId": 0,
            "AccountName": this.formData?.companyName,
            "Address": this.formData?.address,
            "Email": this.formData?.email,
            "MobileNumber": this.formData?.contactNumber,
            "UserName": this.formData?.userId,
            "Password": this.formData?.password,
          }
          this.registerService.registerUserFormData(payload) //for registering account details
        .pipe(tap((resp:any)=>{
          this.accountData=resp.data //storing the response into a variable for later use
        }),
        switchMap((response1:any)=>{ 
     
          const formData = new FormData();
          formData.append('file', this.registerService.companyRegistrationDocument);
      
    
        return this.registerService.uploadFile(formData)
          
    }),
    switchMap( (response2:any) =>{
      let payload=[
        {
          "Id":0,
          "AccountId": this.accountData.id,
          "Name": response2.data.name
        }]
        console.log(payload) //all values are defined here
        return this.registerService.uploadDocumentData(payload) //but when sending the api request "accountId" becomes undefined here
        } 
        ),).subscribe({next:(responseMain)=>{
          console.log(responseMain)
          alert("Your account details have been registered successfully")
           },
          error:()=>{
            alert("An error occurred, please try again")
          }})
          }

Given the above code, my requirement here is to send an initial API call to save data of a newly created account, followed by a document upload in the second API call, and then in the third API call I will send a payload comprising of some data from first and second API call’s response data objects.

The issue I face here is that the first API call’s response data comes as undefined when I try to declare it into the payload of third API call (when I console the payload, the data is defined, but on sending the API call, the request body property of that value comes up undefined, while the second API call data shows up fine in all cases). Is there any workaround for this issue? or am I missing something

(In the future, I may also have to incorporate multiple file uploads in the future, so it maybe necessary to reuse the response data from first API call in the subsequent API calls’ request body)

desktopCapture still prompts the tab to share even after specifying the targetTab property

I setup the desktopCatpure in the background script, and specify the current tab as the targetTab property in order to proceed to get the streamId without prompting which tab the user wants to share. But after I test the extension, it still prompts the user to select which tab screen they want to share

background.js
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
            const tabId = tabs[0].id;
            const currentTab = tabs[0];
            console.log(currentTab);
          
            // Initialize desktopCapture with the targetTab property
             chrome.desktopCapture.chooseDesktopMedia(
               ['tab'],
               currentTab,
              
               function(streamId) {
                 // Create a MediaStream object for the selected tab
                 if(streamId !== null || streamId != undefined) {
                     sendResponse(streamId);
                     console.log(streamId);
                     
                 }
                 else {
                     
                 }
               }
              
           
             );

          
                });
              });
          });