unable to get a hard-coded svg line on d3 chart

I’m trying to just get a simple line on a D3 chart without using an array of data (that will be the next step).

The x-axis is years from 2007 to 2023. The y-axis is numbers from 0.00 to 0.50.

I assume the data pairs I’ll need will be x in a time formatted year and y as a number.

But when I put in the code to draw a line from one point to the other on the chart, nothing appears and I get no error message.

<div id="container"></div>
<script type="module">

const width = 1140;
const height = 400;
const marginTop = 20;
const marginRight = 20;
const marginBottom = 50;
const marginLeft = 70;

//x-axis is years
const x = d3.scaleUtc()
    .domain([new Date("2007-01-01"), new Date("2023-01-01")])
    .range([marginLeft, width - marginRight]);

//y-axis is numbers between 0 and .5
const y = d3.scaleLinear()
    .domain([0, .5])
    .range([height - marginBottom, marginTop]);

const svg = d3.create("svg")
    .attr("width", width)
    .attr("height", height);

svg.append("g")
    .attr("transform", `translate(0,${height - marginBottom})`)
    .call(d3.axisBottom(x)
        .ticks(d3.utcYear.every(1))
);
    
svg.append("text") //label
    .attr("class", "x label")
    .attr("text-anchor", "end")
    .attr("x", width/2)
    .attr("y", height - 6)
    .text("Year");

svg.append("text") //label
    .attr("class", "y label")
    .attr("text-anchor", "end")
    .attr("x", -height/3)
    .attr("y", 6)
    .attr("dy", ".75em")
    .attr("transform", "rotate(-90)")
    .text("Percent");

svg.append("g")
    .attr("transform", `translate(${marginLeft},0)`)
    .call(d3.axisLeft(y));

const parseTime = d3.utcFormat("%Y");

svg.append("line")          // nothing appears
.style("stroke", "black")  
.attr("x1", parseTime(new Date("2007")))     // x position of the first end of the line
.attr("y1", 0.50)      // y position of the first end of the line
.attr("x2", parseTime(new Date("2008")))      // x position of the second end of the line
.attr("y2", 0.40);

container.append(svg.node());

Data from html disappears and doesn’t not post using rest api call. When submit button is selected the form clears and data is not submitted

I have a basic HTML form that submits data to a SharePoint list. There are no errors in the code, nor do I receive anything that would cause the form not to submit to the SharePoint list. I am using basic HTML, some CSS, and AngularJS. The angular code uses a basic rest api call to post the data when the button is selected.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
    <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.0.4/css/bootstrap-combined.min.css">
    <link rel="stylesheet" href="calendar.css">
    <!-- <title>Document</title> -->
</head>
<body>

    <div class="container">
    <div class="row">
      <div class="col-md-8 col-md-offset-2">
        <div class="form-container">
          <h2 class="text-center" style="font-weight: bold;">Tour Request Form</h2>
          <form action="#" method="post" enctype="multipart/form-data">
            <div class="form-group">
                <div ng-controller="calendarController as calendar">
              <label for="tourRequest">Tour Request</label>
                    <input type="text" class="form-control" id="tourRequest" name="tourRequest" required>
                    <input class="btn-primary" type="submit" value="add">


            </div>
            </div>
          </form>
        </div>
      </div>
    </div>
    </div>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script src="calendar.js"></script>
</body>
</html>
angular.module('mcalendarapp', [])
  .controller('myController', function($scope, $http) {
    $scope.newItem = {
      Title: $scope.tourRequest, // Example: A field in your SharePoint list
     // Description: '' // Example: Another field
    };

    $scope.addItem = function() {
      var listName = 'TourRequest'; // Replace with your list name
      var apiUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('" + listName + "')/items";

      var dataPayload = {
        '__metadata': {
          'type': 'SP.Data.' + listName + 'ListItem' // Adjust if your list name has spaces or special characters
        },
        'Title': $scope.newItem.Title,
       // 'Description': $scope.newItem.Description
      };

      $http({
        method: 'POST',
        url: "/_api/web/lists/getByTitle('mylist')/items",
        headers: {
          'Accept': 'application/json; odata=verbose',
          'Content-Type': 'application/json; odata=verbose',
          'X-RequestDigest': jQuery('#__REQUESTDIGEST').val() // Get the request digest
        },
        data: JSON.stringify(dataPayload)
      }).then(function(response) {
        // Success handling
        alert('Item added successfully!');
        $scope.newItem = {}; // Clear the form
      }).catch(function(error) {
        // Error handling
        console.error('Error adding item:', error);
        alert('Failed to add item. Check console for details.');
      });
    };
  });

Assistance with code and reasoning behind the api call failing

image map with random image on page load

Alright so this is the code i’m using for this section.

<div class="center">
<div class="imgcenter">
 <img id= "myRandomImg" usemap="#map" width="100%" height="100%">

<map name="map">
    <area shape="rect" coords="952,428,1203,657" alt="recent release" href="https://www.google.com">
</map>

<script>
myarray = ["webite1.png", "webite2.png", "webite3.png", "webite4.png", "webite5.png", "webite6.png"]
window.onload = function(){
 var randomNum = Math.floor(Math.random() * 6);
 var randomImgSrc =document.getElementById("myRandomImg").src = myarray[randomNum]; 
 console.log(randomNum)
}
</script>


How to set this image map on the photos being generated when the page loads?

All of the photos are the same size. I’m pretty new to this.

Trouble embedding SSRS report in iframe – scripts fail to load from correct origin

I’m having trouble embedding an SSRS report in an from an external application. The app calls the report server URL, and we’ve already configured CORS and switched to basic authentication.

We pass the credentials in the request using JavaScript, and it seems to work — the report loads the parameter header without prompting for login. However, the page fails to load completely because the Sys scripts throw errors. The issue is that the loaded page tries to fetch scripts from the iframe’s origin (http://192.168.1.101:8081) instead of the SSRS server (http://192.168.1.101), resulting in Uncaught ReferenceError: Sys.

Interestingly, if I embed the iframe without passing credentials and manually authenticate when prompted by the browser, the report loads perfectly.
Below is the JavaScript code used to embed the iframe and the error message. Any suggestions or workarounds would be greatly appreciated!

<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<title>Report Viewer</title>
<style>
    body, html {
        margin: 0;
        padding: 0;
        height: 100%;
    }
    iframe {
        width: 100%;
        height: 100%;
        border: none;
    }
</style>
</head>
<body>
<iframe id="reportFrame"></iframe>

<script>
    const username = "user";
    const password = "password";

    const reportUrl = "http://192.168.1.101:80/ReportServer/Pages/ReportViewer.aspx?/MyReport&rs:Embed=True&rc:LinkTarget=main";

    const credentials = btoa(username + ":" + password);

    fetch(reportUrl, {
        method: "GET",
        headers: {
            "Authorization": "Basic " + credentials,
            "Upgrade-Insecure-Requests": "1",
            "Cache-Control":"max-age=0",
            
            "Access-Control-Allow-Origin":"http://192.168.1.101:8081",
            "Access-Control-Allow-Credentials":"true",
            "Access-Control-Allow-Methods":"GET, PUT, POST, PATCH, DELETE",
            "Access-Control-Allow-Headers":"Origin, X-Requested-With, Content-Type, Accept, Authorization",
        }
    })
    .then(response => response.text())
    .then(html => {
        const iframe = document.getElementById("reportFrame");
        const blob = new Blob([html], { type: "text/html" });
        iframe.src = URL.createObjectURL(blob);
    })
    .catch(error => {
        console.error("Error to load the report:", error);
    });
</script>

Browser Error

We’re using the latest PBI Reporting Server.

unable to adjust d3 y-axis label position

I want to vertically center the y-axis label on a d3 graph. Right now, I have the label at the top of the y-axis. When I try to adjust the y or dy attributes, the label moves horizontally, not vertically. I suspect this has to do with the label being rotated, but when I comment out the rotation, the label disappears.

<div id="container"></div>
<script type="module">

const width = 1140;
const height = 400;
const marginTop = 20;
const marginRight = 20;
const marginBottom = 50;
const marginLeft = 70;

const x = d3.scaleUtc()
    .domain([new Date("2007-01-01"), new Date("2023-01-01")])
    .range([marginLeft, width - marginRight]);

const y = d3.scaleLinear()
    .domain([0, .5])
    .range([height - marginBottom, marginTop]);

const svg = d3.create("svg")
    .attr("width", width)
    .attr("height", height);

svg.append("g")
    .attr("transform", `translate(0,${height - marginBottom})`)
    .call(d3.axisBottom(x)
        .ticks(d3.utcYear.every(1))
);
    
svg.append("text")
    .attr("class", "x label")
    .attr("text-anchor", "end")
    .attr("x", width/2)
    .attr("y", height - 6)
    .text("Year");

svg.append("text")
    .attr("class", "y label")
    .attr("text-anchor", "end")
    .attr("y", 6) //if I change this value, the label moves horizontally
    .attr("dy", ".75em") //if I change this value, the label moves horizontally
    .attr("transform", "rotate(-90)") //if I comment this out, the label disappears
    .text("Percent");

svg.append("g")
    .attr("transform", `translate(${marginLeft},0)`)
    .call(d3.axisLeft(y));

container.append(svg.node());

Over riding a forms Submit button with Javascript

I have a login form with a submit button to submit the form. it ‘Fetches’ a PHP page that sets some SESSION Variables and returns to the login screen.
on completion I hide the Login Name and Password inputs and change the value of the Login button to ‘Logout’. I have a JQuery .click function to ‘Fetch’ a PHP page to unset the SESSION vars. However, now the form doesn’t submit. I assume the .click() function on the button is causing this?
How can I successfully overide the submit?

code below:

HTML

    <input
        class="btn"
        id="loginBtn"
        type="submit"
        value="Login"
    />

Javascript:

$("#loginBtn").click(function () {
    if ($("#loginBtn").value != "Logout") {
    return;
    }
    else {
        fetch("./logout.php")
        .then((response) => response.text())
        .then(window.location.replace("./login.html"))
        .catch((error) => console.error("Error:", error));
        }
});

Ive searched high and low but can’t understand a solution.
I could create a new button outside of the form and make that visible when required but thats giving in….

SVG Javascript Animated Arrows Missing

I am trying to animate a series of arrows between text boxes in a html file. The text boxes are receiving json strings sent via API calls. That part is working perfectly. However I am trying to animate four arrows between the boxes to illustrate and syncronize with the data exchanges and I cannot get my arrows to appear. There are no error messages in Chrome inspector and I can see the arrows becoming active and inactive but none appear, which makes me think it is a simple problem, perhaps an opacity switch somewhere. The literature is unclear on possible solutions. What is the problem with the js code that the arrows will not appear or animate? Any assistance would be gratefully received. I have enclosed the relevant html and js of my page.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Privacy API Exchange Flow</title>
<style>

  body { font-family: sans-serif; background: #f8f8f8; padding: 1rem;}
  h1 { text-align: center; }
  .buttons { text-align: center; margin: 1rem 0; }
  
  button {
    margin: 0.3rem; padding: 0.5rem 1rem; font-size: 1rem;
    border-radius: 4px; cursor: pointer;
  }
  
  #statusLine {
    text-align: center; font-weight: bold; font-size: 1.1rem;
    margin-bottom: 0.5rem; color: #1976d2;
  }
  .container { position: relative; width: 100%; }
  .boxes {
    display: flex; justify-content: space-around; margin-top: 1rem;
    position: relative; z-index: 2;
  }
  .box {
    width: 28%; background: white; border: 2px solid #444;
    border-radius: 6px; padding: 0.5rem;
    box-shadow: 0 2px 4px rgba(0,0,0,0.2);
  }
  .title { font-weight: bold; text-align: center; margin-bottom: 0.5rem;}
  
  pre {
    background: #f0f0f0; height: 200px; overflow: auto;
    padding: 0.5rem; border-radius: 4px; font-size: 0.8rem;
  }

  /* Arrow styling */
  svg.arrow {
     position: absolute; top: 290px; width: 100%; height: 50px; 
     overflow: visible; z-index: 1;
  }
  
  svg.arrow path {
    transition: stroke-dashoffset 1s ease-in-out;
    stroke: #1976d2; stroke-width: 3; fill: none;
    marker-end: url(#arrowhead);    
    opacity: 1; /* hidden until animated */
  }
  
  path.active {
    stroke: #4CAF50; 
    stroke-width: 2px;
    stroke-dasharray: 300; 
    stroke-dashoffset: 300;
    opacity: 1; 
    animation: draw 1s forwards;
  }
  
  @keyframes draw {
    to { stroke-dashoffset: 0; }
  }
  
</style>
</head>
<body>

<h1>API Exchange</h1>

<div class="buttons">
  <button id="runDemo">Run Demo</button>
  <button id="resetDemo">Reset Demo</button>
</div>

<div id="statusLine">Ready to start</div>

<div class="container">

  <svg id="arrow1" class="arrow" width="100" height="50" viewBox="0 0 100 50">
  <path
    d= "M 20 50 L 20 20"
    fill="none"
    stroke="black"
    stroke-width="1"
  />
</svg>

<svg id="arrow2" class="arrow" width="100" height="50" viewBox="0 0 100 50">
  <path
    d= "M 50 20 L 20 20"
    fill="none"
    stroke="black"
    stroke-width="1"
  />
</svg>

<svg id="arrow3" class="arrow" width="100" height="50" viewBox="0 0 100 50">
  <path
    d= "M 80 30 L 50 30"
    fill="none"
    stroke="black"
    stroke-width="1"
  />
</svg>

<svg id="arrow4" class="arrow" width="100" height="50" viewBox="0 0 100 50">
  <path
    d= "M 50 40 L 80 40"
    fill="none"
    stroke="black"
    stroke-width="1"
  />
</svg>

  <svg class="arrow">
    <defs>
      <marker id="arrowhead" markerWidth="10" markerHeight="7"
              refX="10" refY="3.5" orient="auto">
        <polygon points="0 0, 10 3.5, 0 7" fill="#1976d2" />
      </marker>
    </defs>
  </svg>

 
  <div class="boxes">
    <div class="box">
      <div class="title">User</div>
      <pre id="userBox">// waiting…</pre>
    </div>
    <div class="box">
      <div class="title">Service Provider</div>
      <pre id="spBox">// waiting…</pre>
    </div>
    <div class="box">
      <div class="title">Trusted Third Party</div>
      <pre id="ttpBox">// waiting…</pre>
    </div>
  </div>
</div>

<script >
const sp_base = "http://localhost:8080";
const ttp_base = "http://localhost:8090";

const delay = ms => new Promise(res => setTimeout(res, ms));

function show(id, data) {
  document.getElementById(id).textContent =
    (typeof data === "string" ? data : JSON.stringify(data, null, 2));
}
function setStatus(text) {
  document.getElementById("statusLine").textContent = text;
}

function resetDemo() {
  show("userBox", "// waiting…");
  show("spBox", "// waiting…");
  show("ttpBox", "// waiting…");
  setStatus("Ready to start");
  document.querySelectorAll("svg.arrow path").forEach(p => p.classList.remove("active"));
  console.log("Demo Reset");
}

function animateArrow(id) {
  const path = document.getElementById(id);
  console.log("Arrow animated");
  if (!path) {
    console.error(`Arrow with id "${id}" not found!`);
    return;
  }

  //Reset Animation

 path.style.strokeDashoffset = "300"; 
 void path.offsetWidth; // Force reflow
 console.log("Animation Restart");

  //trigger animation
  path.classList.add("active");
  console.log("Animation Triggered");

  //remove active status after animation finish
  setTimeout(() => path.classList.remove("active"), 1000);
}


// Ensure DOM is ready
document.addEventListener("DOMContentLoaded", () => {
  document.getElementById("runDemo").onclick = async () => {
    resetDemo();
    setStatus("Step 1: User → Service Provider");
    show("userBox", "Running demo..."); 
    //await delay(5000);

  try {
    // Step 1
    animateArrow("arrow1");
    
    await delay(5000);
    //this logic is working only the animation is missing
    const uidResp = await fetch(`${sp_base}/UID/issue`, {
      method: "POST",
      headers: {"Content-Type": "application/json"},
      body: JSON.stringify({ dln: dln, sh: shx, audience: "sp"})
    }).then(r=>r.json());
    show("spBox", uidResp);

    await delay(5000);

    // Step 2
    setStatus("Step 2: Service Provider → User (UID issued)");
    animateArrow("arrow2");
    show("userBox", { message: "Received signed UID from SP", uid: uidResp });

    await delay(5000);

    // Step 3
    setStatus("Step 3: User → TTP (send UID)");
    animateArrow("arrow3");
    const ttpResp = await fetch(`${ttp_base}/token/issue`, {
      method: "POST",
      headers: {"Content-Type": "application/json"},
      body: JSON.stringify({
        uid: uidResp.uid,
        signature: uidResp.signature,
        signer: uidResp.signer
      })
    }).then(r=>r.json());
    show("ttpBox", ttpResp);

    await delay(5000);

    // Step 4
    setStatus("Step 4: TTP → User (note issued)");
    animateArrow("arrow4");
    show("userBox", {
      message: "Received note from TTP after verification",
      token: ttpResp
    });

    setStatus("Demo complete ✅");

  } catch (err) {
    console.error(err);
    show("userBox", { error: err.message });
    setStatus("Error: " + err.message);
  }
};
});
document.getElementById("resetDemo").onclick = resetDemo;

</script>

</body>
</html>

Google Maps Platform Autocomplete Fullscreen issue, vis.gl/react-google-maps

im using google maps autocomplete element.

I’ve set up my code just as in the example shown on the react-google-maps website:
https://visgl.github.io/react-google-maps/examples/autocomplete

My issue is that after the viewport becomes smaller than 450px search results of the said element are shown in a fullscreen overlay and since I’m making a mobile app the input field gets obscured by the phone notch. See the screenshots

How do you style this fullscreen overlay so that it has proper padding. Also is there a way to disable this fullscreen feature?

On Google’s official docummentation website: https://developers.google.com/maps/documentation/javascript/place-autocomplete-new there’s no information about vis.gl’s react-google-maps which is recommended in other places so I’m not sure if it’s the react-google-maps issue or there’s something to configure with the actual gmp element.

Here’s my code:


export default function LocationPickerMap() {
  useEffect(() => {
    //without it the gmp-place-autocomplete won't work
    google.maps.importLibrary("places");
  }, []);

  return (
    <>
      <div className="w-full h-full">
        <div className="p-5 bg-lmp-panel">
          <gmp-place-autocomplete/>
        </div>
      </div>
    </>
  );
}

declare module "react" {
  namespace JSX {
    interface IntrinsicElements {
      "gmp-place-autocomplete": React.DetailedHTMLProps<
        React.HTMLAttributes<google.maps.places.PlaceAutocompleteElement>,
        google.maps.places.PlaceAutocompleteElement
      >;
    }
  }
}

Normal Dropdown
Fullscreen Dropdown

Google Maps performance issue when removing many markers

I have about 2000 markers on my v3 map.

Often, but not always, there will be a significant delay (~30s) when clearing the map.
Markers are removed by looping through them and calling setMap(null).

I have measured the time it takes to remove each marker using the delta between Date.now() calls. This is usually 0 to 1 ms.
In the slow case however, there is a significant number of markers that take 30 to 50 ms to remove.

Using the Firefox profiler, I can see that the time is spent on Node.compareDocumentPosition within

setMap
 dispose
  lS
   _.O
    Sg/<
     pI
      oI
       _.cB
        Node.compareDocumentPosition (~50%)
        $ha
         Node.compareDocumentPosition (~50%)

What could be the cause of this and what can be done about it?

Can JavaScript add a hyperlink to a word on a page, without privileged security settings or other programs?

I am trying to automate some functionality in Acrobat PDFs. I use Adobe Acrobat (version shows 2025.001.20693, 64 bit). I prepare many reports that have words in them on which I have to set hyperlinks manually. The hyperlinks are URLs to the Web, and they don’t change.

Here’s a brief explanation for adding one of the links: I want to add a hyperlink to microsoft.com, on word 268 on the user’s page 7 (page 6 in the code). I want to automate this in JavaScript which I can add to a document, so I can click a button and it’ll add the hyperlink.

I have searched for answers here, on Adobe, and using other resource. I want to know: is it even possible to set these hyperlinks programmatically? I’m neither a programmer nor able to force my firm to change its IT/security protocol. So if an answer is already out there, but it is very technical or it tells me to create a whole new setup, then I can’t use it.

If there is not a way to do this under these constraints, can you tell me why? For instance, perhaps hyperlinks have some security requirement so that they can’t be added from JavaScript without further permissions or security access.

If there is a way to do this, what am I doing wrong, and can you suggest anything? Here’s the code I have so far, with comments. The button which calls this function is in the same document where I want to add the hyperlinks.

var link;

function selectWords()
{
    var whichWord = app.response("Enter the word number:", "Which word:", 268);
    this.selectPageNthWord(6, whichWord);

    //first, get coordinates
    var bBox = this.getPageNthWordQuads(6, whichWord); //quads returns x1, y1, x2, y2, x3, y3, x4, y4 - left-bottom, left-top, right-bottom, right-top
    var quadStr = bBox.toString();
    var quadArray = quadStr.split(",");

    var wordRect = [quadArray[0], quadArray[1], quadArray[6], quadArray[7]]; //wordRect needs left, bottom, right, top

    //then, use this to create the link
    link = this.addAnnot({
        page: 6,
        rect: wordRect,
        borderStyle: "solid",
        color: color.transparent,
        action: {
            url: "https://www.microsoft.com/",
            type: "Launch"
        }
    });
    link.type = "Link"; //when you use this in the addAnnot call, the object returned is null! Why?

    // I've also tried to set a link action HERE but this line fails
//link.setAction("app.launchURL('https://www.microsoft.com/', true);");

}

Leaflet – How to include polygon area measurement labels in map print (html2canvas/jsPDF)

I’m working on a Leaflet-based map where users can draw polygons and get the area measurement displayed on the map.

When I use a print/export tool (based on html2canvas/jsPDF), the labels with area values don’t appear in the generated print/PDF.

Distance measurement tooltips (line length) do appear in the print.

But the area measurement labels (polygon) do not.

It seems the plugin injects HTML elements into the DOM (not canvas-compatible), so html2canvas ignores them.

What I’ve tried so far:

Checking the printing plugin docs (they mention this limitation).

Inspecting the polygon measurement plugin: it creates divs instead of drawing on canvas/SVG.

Tried forcing CSS classes to match distance tooltips → no success.

What I need:

A way to make polygon measurement labels appear in the map print/export, without forking and editing the original plugin if possible.

Suggestions for workarounds (e.g., intercepting measurement events and redrawing labels in a canvas/SVG layer that html2canvas can capture).

HTML ID behavior in JavaScript and CSS [duplicate]

CSS

Let’s say there are multiple elements inside our HTML having same ID now I wanna select the element using ID then it will select the entire element having same ID in CSS.

JavaScript

Same thing if I do in JavaScript. Let’s say I wanna fetch element having id from HTML and same scenario here also means multiple elements having same ID at that time it selects only the first matching element.

How is it working??

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Duplicate ID Example</title>
</head>
<body>
  <div id="myDiv">This is the first div with ID "myDiv"</div>
  <div id="myDiv">This is the second div with the SAME ID "myDiv"</div>
</body>
</html>
#myDiv{
color: red; /*It will be selecting the both div*/
}
let div = document.getElementById("myDiv") //it will be returning the first div

some part of my javascript code are not working? [closed]

i am running a code to convert tempretures to each other at the same time .
when i am running my codes part of js code is running but part of it doesnt.

const celvalue = document.getElementById('cel-num');
const farvalue = document.getElementById('far-num');
const kelvalue = document.getElementById('kel-num');

function tempfunccel() {
  const tempfar = celvalue.value * (9 / 5) + 32;
  const tempkel = celvalue.value + 273.32;
  farvalue.value = tempfar.toFixed(2);
  kelvalue.value = tempkel.toFixed(2);
}
<div class="box">
  <label for="" >celsius:</label>
  <input  type="number" class="inp" id="cel-num" onchange="tempfunccel()">
</div>
<div class="box">
  <label for="">fahrenheit:</label>
  <input type="number" class="inp" id="far-num" onchange="tempfuncfar()">
</div>
<div class="box">
  <label for="">kelvin:</label>
  <input type="number" class="inp" id="kel-num" onchange="tempfunckel()">
</div>

in function line 1 and 3 are working but line 2 and 4 are not working

Why is my crypto.getRandomValues() base36 ID generator producing duplicates despite 2.8 trillion possibilities?

Here is the function:

export function generateId(): string {
  const chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  let result = "";

  const randomArray = new Uint8Array(8);
  crypto.getRandomValues(randomArray);

  for (let i = 0; i < 8; i++) {
    result += chars[randomArray[i] % 36];
  }

  return result;
}

It should generate 8-character random base36 IDs, e.g. QZ08HNDL. Base36 uses 0-9 and A-Z (36 characters). If the id is 8 characters = 36^8 = ~2.8 trillion possibilities.

But I’ve had some “INVALID_RECORD: record is invalid and can’t be saved. ID is not unique” errors reported in the last few days, and I’m not sure if it’s because this function is generating duplicates. How likely is it? Are there flaws in this function?

How to design extensible data aggregation code to avoid manual updates in multiple places?

I have a data aggregation function that collects statistics from multiple sources. The problem is that whenever I add a new metric, I need to manually update the code in three different places, which is error-prone and hard to maintain.

Current Code Structure:

// Part 1: Initialize data object
const storeData = {
    collectors_count: 0,
    toys_count: 0,
    toys_inspected: 0,
    toys_cleaned: 0,
    inspection_percent: 0,
    cleaning_percent: 0,
};

// Part 2: Accumulate data from each source
for (const collector of collectors) {
    const details = await db.getCollectorDetails(collector.id);
    
    if (!details) continue;

    storeData.collectors_count++;
    storeData.toys_count += details.toy_count;
    storeData.toys_inspected += details.inspected_count;
    storeData.toys_cleaned += details.cleaned_count;
}

// Part 3: Calculate derived metrics
storeData.inspection_percent = (storeData.toys_inspected / storeData.toys_count) * 100;
storeData.cleaning_percent = (storeData.toys_cleaned / storeData.toys_count) * 100;

return storeData;

The Problem:

  • When I want to add a new metric (e.g., toys_repaired), I have to:
  • Add it to the initial object with value 0
  • Add accumulation logic in the loop: storeData.toys_repaired += details.repaired_count
  • Possibly add calculation logic if it’s a derived metric: storeData.repair_percent = ...

This becomes tedious with many metrics and I sometimes forget to update all three places.

Is there a way to refactor this code to be more extensible and maintainable?