Nothing is shown when running a d3 sample code

I am quite new to d3.js and javascript.
I just want to try out some d3 sample code.

I copied over the d3.js code from here.

<!DOCTYPE html>
<meta charset="utf-8" />
<style>
  .node circle {
    fill: #999;
  }

  .node text {
    font: 10px sans-serif;
  }

  .node--internal circle {
    fill: #555;
  }

  .node--internal text {
    text-shadow: 0 1px 0 #fff, 0 -1px 0 #fff, 1px 0 0 #fff, -1px 0 0 #fff;
  }

  .link {
    fill: none;
    stroke: rgb(214, 15, 145);
    stroke-opacity: 0.4;
    stroke-width: 1px;
  }

  form {
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  }

  label {
    display: block;
  }
</style>
<svg width="928" height="928"></svg>
<script src="http://d3js.org/d3.v6.min.js"></script>
<script>

  const data = {
        name: "Name",
        children: [
          {
            name: "A_F",
            children: [
              {
                name: "Alice",
              },
              {
                name: "Bob",
              },
              {
                name: "Charlie",
              },
            ],
          },
          {
            name: "G_P",
            children: [
              {
                name: "Gary",
              },
              {
                name: "Helen",
              },
            ],
          },
        ],
      };

  // Specify the chart’s dimensions.
  const width = 928;
  const height = width;
  const radius = width / 6;

  // Create the color scale.
  const color = d3.scaleOrdinal(d3.quantize(d3.interpolateRainbow, data.children.length + 1));

  // Compute the layout.
  const hierarchy = d3.hierarchy(data)
      .sum(d => d.value)
      .sort((a, b) => b.value - a.value);
  const root = d3.partition()
      .size([2 * Math.PI, hierarchy.height + 1])
    (hierarchy);
  root.each(d => d.current = d);

  // Create the arc generator.
  const arc = d3.arc()
      .startAngle(d => d.x0)
      .endAngle(d => d.x1)
      .padAngle(d => Math.min((d.x1 - d.x0) / 2, 0.005))
      .padRadius(radius * 1.5)
      .innerRadius(d => d.y0 * radius)
      .outerRadius(d => Math.max(d.y0 * radius, d.y1 * radius - 1))

  // Create the SVG container.
  const svg = d3.create("svg")
      .attr("viewBox", [-width / 2, -height / 2, width, width])
      .style("font", "10px sans-serif");

  // Append the arcs.
  const path = svg.append("g")
    .selectAll("path")
    .data(root.descendants().slice(1))
    .join("path")
      .attr("fill", d => { while (d.depth > 1) d = d.parent; return color(d.data.name); })
      .attr("fill-opacity", d => arcVisible(d.current) ? (d.children ? 0.6 : 0.4) : 0)
      .attr("pointer-events", d => arcVisible(d.current) ? "auto" : "none")

      .attr("d", d => arc(d.current));

  // Make them clickable if they have children.
  path.filter(d => d.children)
      .style("cursor", "pointer")
      .on("click", clicked);

  const format = d3.format(",d");
  path.append("title")
      .text(d => `${d.ancestors().map(d => d.data.name).reverse().join("/")}n${format(d.value)}`);

  const label = svg.append("g")
      .attr("pointer-events", "none")
      .attr("text-anchor", "middle")
      .style("user-select", "none")
    .selectAll("text")
    .data(root.descendants().slice(1))
    .join("text")
      .attr("dy", "0.35em")
      .attr("fill-opacity", d => +labelVisible(d.current))
      .attr("transform", d => labelTransform(d.current))
      .text(d => d.data.name);

  const parent = svg.append("circle")
      .datum(root)
      .attr("r", radius)
      .attr("fill", "none")
      .attr("pointer-events", "all")
      .on("click", clicked);

  // Handle zoom on click.
  function clicked(event, p) {
    parent.datum(p.parent || root);

    root.each(d => d.target = {
      x0: Math.max(0, Math.min(1, (d.x0 - p.x0) / (p.x1 - p.x0))) * 2 * Math.PI,
      x1: Math.max(0, Math.min(1, (d.x1 - p.x0) / (p.x1 - p.x0))) * 2 * Math.PI,
      y0: Math.max(0, d.y0 - p.depth),
      y1: Math.max(0, d.y1 - p.depth)
    });

    const t = svg.transition().duration(750);

    // Transition the data on all arcs, even the ones that aren’t visible,
    // so that if this transition is interrupted, entering arcs will start
    // the next transition from the desired position.
    path.transition(t)
        .tween("data", d => {
          const i = d3.interpolate(d.current, d.target);
          return t => d.current = i(t);
        })
      .filter(function(d) {
        return +this.getAttribute("fill-opacity") || arcVisible(d.target);
      })
        .attr("fill-opacity", d => arcVisible(d.target) ? (d.children ? 0.6 : 0.4) : 0)
        .attr("pointer-events", d => arcVisible(d.target) ? "auto" : "none") 

        .attrTween("d", d => () => arc(d.current));

    label.filter(function(d) {
        return +this.getAttribute("fill-opacity") || labelVisible(d.target);
      }).transition(t)
        .attr("fill-opacity", d => +labelVisible(d.target))
        .attrTween("transform", d => () => labelTransform(d.current));
  }
  
  function arcVisible(d) {
    return d.y1 <= 3 && d.y0 >= 1 && d.x1 > d.x0;
  }

  function labelVisible(d) {
    return d.y1 <= 3 && d.y0 >= 1 && (d.y1 - d.y0) * (d.x1 - d.x0) > 0.03;
  }

  function labelTransform(d) {
    const x = (d.x0 + d.x1) / 2 * 180 / Math.PI;
    const y = (d.y0 + d.y1) / 2 * radius;
    return `rotate(${x - 90}) translate(${y},0) rotate(${x < 180 ? 0 : 180})`;
  }

  svg.node();
</script>

The only thing I edit is to remove the last return svg.node(); and change it to svg.node();

When I spin up a local http server (py3 -m http.server 8000), I found that there is nothing shown in the browser and there is no error when I click the inspect.

Just want to learn how to triage this issue and trouble shoot. Thank you!

Passing auth credentials in nextjs server side api call

I’m using Laravel breeze-next nextjs starter package to create a nextjs app with a backend powered by laravel and protected by sanctum.

Laravel expects a csrf header value and a session cookie. I’m having no problem setting these values in client components and getting data back from laravel using something like this:

async function fetchData(url: string): Promise<Response> {
    let fetch_path = process.env.NEXT_PUBLIC_BACKEND_URL + '/api/' + url
    console.log('fetch data called')

    const options: RequestInit = {
        method: "GET",
        credentials: "include",
        headers: {
            "Accept": "application/json",
            "Referer": process.env.APP_URL,
            "X-Requested-With": "XMLHttpRequest",
            "Content-Type": "application/json",
        }
    };

    return await fetch(fetch_path, options);
}

When I try to make an API request in a server component doing something similar it fails every time with a 401:

async function fetchDataServerSide(url: string) {
    'use server'
    let fetch_path = process.env.NEXT_PUBLIC_BACKEND_URL + '/api/' + url

    const options: RequestInit = {
        method: "GET",
        headers: {
            "Accept": "application/json",
            "Referer": process.env.APP_URL,
            "X-Requested-With": "XMLHttpRequest",
            "Content-Type": "application/json",
            "X-CSRF-TOKEN": cookies().get('XSRF-TOKEN'),
        }
    };

    return await fetch(fetch_path, options);
}

Note that this is basically exactly what I’m doing with the same calls via Postman, and they work as expected.

Can anyone point out what I’m doing wrong?

Would event listeners prevent garbage collecting objects referenced in outer function scopes?

Let’s assume I have the following code:

(function () {

    const largeObject = provideSomeLargeObject();
    const largeStaticListOfElements = document.querySelectorAll('span');
    const someElementThatWillBeRemoved = document.getElementById('i-will-be-removed');

    const elms = document.getElementsByClassName('click-me');

    for (let i = 0; i < elms.length; ++i) {

        const anotherLargeObject = provideAnotherLargeObject();

        elms[i].addEventListener('click', function (e) {
            // callback just uses i, which contains a literal value
            e.preventDefault();
            console.log(i);
        });
    }

    // largeObject, largeStaticListOfElements, someElementThatWillBeRemoved, and anotherLargeObject
    // are no longer used in this code. Should they be set to null to allow GC them?

})();

The event listeners create function scopes, and after executing the above code, the event listeners still exist, thus the outer function scopes are preserved so that the event handlers can use the variables they contain.

However, the event handlers just use some literal value from the outer scopes, but in these scopes there are other variables, that are not used anymore.

  • Would the event listeners prevent garbage collecting the objects referenced by these variables, so I have to manually assign null to the variables at the end of the code,
  • or are JavaScript engines smart enough to detect that the event handler never uses the variables, so the referenced objects can be GC even if the variables reside in a still existing function scope?

My JavaScript calculator is unable to correctly solve a problem with two or more-digit numbers

I feel like it’s important for me to mention that this is my very first JavaScript project ever. Some parts of the code may or may not be difficult to understand, but that’s because this project is part of my HTML curriculum, so I copied my instructor’s code basically character for character since I don’t know anything else I could do.
So, my calculator is supposed to be able to solve problems with two numbers. For example, it should be able to solve 5 + 4 or 988 / 35. The calculator is able to correctly solve problems with one-digit numbers, for example 5 + 4 = 9 or 5 / 2 = 2.5. However, my calculator seems to get confused with 2 or more-digit numbers. For example, for an addition problem: If num1 = 56 and num2 = 8,643, the calculator will only work with the first digits of the numbers. So, in this case, it would instead calculate 5 + 8 so the answer would be 13, even though it’s very obvious that 56 + 8,643 =/= 13. I’m pretty sure the main problem is that only the first digit is getting converted to an integer. But I don’t know how to make it so that the entire string (is that the correct term?) gets turned into an integer. (Yes, I’ve looked at tons of videos and articles and none of them solve my problem.)

Here is my code… I’m very new to JavaScript so most of my comments are intended for me:

// This calculator is intended to only be able to calculate two numbers (so far, at least). The var currentNumber is
// supposed to indicate whether num1 or num2 is active (so, initially currentNumber will be equal to 1, to match
// with num1. Once an operator is pressed, then currentNumber equals 2, meaning that you can now insert your second
// number)

var currentNumber = 1;
var num1;
var num2;

var $screen = $("#screen");
var $number = $(".number");

// when someone clicks on a number
// it saves the number to do the math
$number.on('click', function() {
    var numberPressed = $(this).html();
    $screen.append(numberPressed);

    if (currentNumber == 1) {
        if (num1 == null) {
            num1 = numberPressed;
        } 
        else {
            num1 = num1 + numberPressed;
            console.log(num1);
        }
    }
    
    if (currentNumber == 2) {
        if (num2 == null) {
            num2 = numberPressed;
        } 
        else {
            num2 = num2 + numberPressed;
            console.log(num2);
        }
    }
});


/* Code for the operators (and clear)*/
// Note: currentNumber++ is the short version of currentNumber = currentNumber + 1  
// Which would be the equivalent of if (currentNumber == 1) { currentNumber = 2 }  

$("#clear").on('click', function ()
    {
        $screen.empty();
        num1 = null;
        num2 = null;
        currentNumber = 1;
    })

$("#plus").on('click', function ()
    {
        $screen.append("+");
        op = "+";
        currentNumber++;
    })

$("#minus").on('click', function ()
    {
        $screen.append("-");
        op = "-";
        currentNumber++;
    })

$("#times").on('click', function ()
    {
        $screen.append("x");
        op = "*";
        currentNumber++;
    })

$("#over").on('click', function ()
    {
        $screen.append("/");
        op = "/";
        currentNumber++;
    })

$("#equal").on('click', function ()
    {
        $screen.append("=");    
        console.log(num1, num2);  
        num1 = parseInt(num1);        
        num2 = parseInt(num2);       
        console.log(num1, op, num2);    
        if (op == "+") {
            answer = num1 + num2;
        }
        if (op == "-") {
            answer = num1 - num2;
        }
        if (op == "*") {
            answer = num1 * num2;
        }
        if (op == "/") {
            answer = num1 / num2;
        }
        $screen.append(answer);
        num1 = null;
        num2 = null;
        currentNumber = 1;
    })

As I stated before, this is part of a class I’m taking for school. My instructor posts video lessons for us to follow. I’ve looked at my code, and then their code, over and over and over again. And my code is the exact same as theirs, word for word and character for character. Yet their code works completely fine, and mine doesn’t. I’ve tried looking up solutions to this problem, because it seems that the calculator’s main problem is not being able to convert a string (?) of numbers into actual numbers that can be added and divided and stuff. However, I haven’t found anything that I can apply to my code in this situation. And I’m so new to coding that I genuinely have no idea what to do. I even asked my instructor, and they didn’t know what the problem was.

Array received as prop from parent used as a dependency of useMemo triggers infinite re-rendering

I have a component that looks like this

import { useState, useEffect, useMemo } from 'react'
import Input from '~/components/Input'
import Fuse from 'fuse.js'

interface Props {
  data: any[]
  keys: string[]
  onUpdate: (data: any[]) => void
  placeholder: string
}

const FilterInput = ({ data, keys, onUpdate, placeholder }: Props) => {
  const [search, setSearch] = useState('')
  const handleSearch = (e) => setSearch(e.target.value)

  // Memorize the fuse instance to avoid recreating it on every render
  const fuse = useMemo(() => {
    return new Fuse(data, {
      includeScore: true,
      keys,
      threshold: 0.3,
      distance: 100,
    })
  }, [data, keys]) //THIS IS THE RELEVANT PART

  useEffect(() => {
    const results =
      search === '' ? data : fuse.search(search).map((result) => result.item)
    onUpdate(results) // Invoke onUpdate with the filtered or original list
  }, [search, fuse, onUpdate, data]) // Effect dependencies

  return (
    <div className={'mb-10'}>
      <Input value={search} onChange={handleSearch} placeholder={placeholder} />
    </div>
  )
}

export default FilterInput

I am using it like this

const ProjectFeatureListing = ({ projects }: Props) => {
  const [filteredProjects, setFilteredProjects] = useState(projects) // State to hold the filtered list
  console.log(projects)
  return (
    <div className={'max-w-7xl py-10 mx-auto px-10'}>
      <FilterInput
        data={projects}
        keys={['title', 'description']}
        onUpdate={setFilteredProjects}
        placeholder={'Find our creators'}
      />
...

I can’t figure out why sending this static array would trigger a re-render since it’s not changing, to be clear when I do this

  const fuse = useMemo(() => {
    return new Fuse(data, {
      includeScore: true,
      keys,
      threshold: 0.3,
      distance: 100,
    })
  }, [data]) //THIS IS THE RELEVANT PART

It does NOT infinitely re-render

Browserify Error: Uncaught TypeError: Unable to determine current node version in bundle.js


bundle.js:10677 Uncaught TypeError: Unable to determine current node version
    at versionIncluded (bundle.js:10677:9)
    at isCore (bundle.js:10694:28)
    at 71../core.json (bundle.js:15883:21)
    at o (bundle.js:1:265)
    at bundle.js:1:316
    at 67../lib/async (bundle.js:15523:14)
    at o (bundle.js:1:265)
    at bundle.js:1:316
    at Object.<anonymous> (bundle.js:6817:12)
    at Object.<anonymous> (bundle.js:7158:4)

Hi all, so I recently installed browserify into my application, and I’m getting this error in the console. Here is the code that is relevant to the error



    var current = typeof nodeVersion === 'undefined'
        ? process.versions && process.versions.node
        : nodeVersion;

    if (typeof current !== 'string') {
        throw new TypeError(typeof nodeVersion === 'undefined' ? 'Unable to determine current node version' : 'If provided, a valid node version is required');
    }

So, basically it throws an error when it cannot get the the node version, it will not assign a value to current and it will throw an error later. I have Node v20.6.1, so I don’t understand why nodeVersion is undefined or how to fix that. I’m guessing my app is supposed to pass that value when building the webpack but for some reason is not building it correctly. However, I am running the correct command to build the webpack:

 browserify scripts.js -o bundle.js

Any guidance would be appreciated.

I have tried deleting the bundle.js and rebuilding it. I have also tried commenting out the error handling in general, but it needs the node version to assign a value to current for later.

Leaflet Map Media Queries

I am trying to make a map media query for phones and make the zoom decrease to 8. However, this doesn’t seem to work, the map doesn’t decrease zoom when I set the width, is there any error in this code?

 window.addEventListener('resize', function(event){
    var width = this.document.documentElement.clientWidth;
    console.log(width);
    if (width < 376) {
      map.setZoom(8);
    } else {
      map.setZoom(10); 
    }
});

Indexing in ServiceNow Jelly Report not working

I have to create a custom report on a ServiceNow UI Page using Javascript and HTML/Jelly. Everything is working except for this line:

<td>${jelly.jvar_bucket.timebuckets[idx].totalSystem;} </td>

If I replace idx with a number, say 20 or 25, then the report shows as expected. With idx it is all blanks.

Here is the full script.

<?xml version="1.0" encoding="utf-8" ?>
<j:jelly trim="false" xmlns:j="jelly:core" xmlns:g="glide" xmlns:j2="null" xmlns:g2="null">
<g:ui_form> 
<g:evaluate var="jvar_surveys" object="true" jelly="true">
        var bucket = [];
<!-- // Helper function to determine AM or PM from hour -->
        function timeflip(hour) 
        {
            if(hour &gt; 12)
            {
                return "PM";
            }
            if(hour == 12)
            {
                return "PM";
            }
            if(hour &lt; 12)
            {
                return "AM";
            }
        } <!-- end function timeflip -->
        var buckets = [];
 
        var ind = 0;
        var hour = 0;
        while(ind &lt; 48)
        {
            var itm = {};
            var h = hour;
            var daynight = "AM";
        if(hour &gt; 12)
        {
            h = hour-12;
            daynight = "PM";
        }
        if(hour == 12)
        {
            h = hour;
            daynight = "PM";
        }
        var notWhole =  (h - Math.floor(h)) !== 0;
                    if(notWhole)
                        {
                            h = Math.floor(h);
                            if(h == 0 &amp;&amp; daynight=='PM')
                            {h=12};
                            itm.interval = (h) +":30 "+timeflip(hour)+" - "+(h+1)+":00 "+timeflip(hour+1) ;
                            if(h == 12 &amp;&amp; daynight=='PM')
                            itm.interval = (h) +":30 "+timeflip(hour)+" - "+(h-11)+":00 "+timeflip(hour) ;
                        }
                    else
                        {
                            h = Math.floor(h);
                            itm.interval = h +":00 "+timeflip(hour)+" - "+h+":30 "+timeflip(hour);
                        }
 
                    itm.totalInterviewer = itm.totalSystem = itm.totalRow = 0;
                    hour += 0.5;
                    ind++;
                    buckets.push(itm);
                }
<!-- TOP HALF SCRIPT -->
        var ga = new GlideRecord('x_igngr_fema_cati_study_table');
        ga.query();
        while(ga.next())
        {
            var obj = {};
            var stdy = ga.study_type.getDisplayValue();
            obj.timebuckets = buckets;  
            obj.study_type = stdy;
            obj.totComp = ga.surveys_completed.getDisplayValue();
            obj.totQuota = ga.quota_study.getDisplayValue();
            obj.intNames = ga.study_interviewer.getDisplayValue();
            if(obj.intNames.trim() === ""){
                obj.intCount = 0;
            } else {
                var splitNames = obj.intNames.split(',');
                obj.intCount = splitNames.length;
            }
            var totAtt = 0
            var attempts = new GlideRecord('x_igngr_fema_cati_piror_attempts');
            attempts.addEncodedQuery('survey_record.collection_cycle.status=open');
            attempts.query();
            while(attempts.next()) {
                totAtt += 1;
            }
            obj.totAtt = totAtt;
            <!-- Time buckets -->
                <!-- var timeBuckets = buckets; -->
                var interviewerGrandTotal = 0; 
                var systemGrandTotal = 0;
                
                var surveyRecord = new GlideRecord('x_igngr_fema_cati_survey_record');
                surveyRecord.addEncodedQuery('study_type.study_type='+stdy);
                surveyRecord.addQuery('in_queue=true^callback_date_timeISNOTEMPTY');
                surveyRecord.addQuery('schedule_status=by_interviewer^ORschedule_status=unmet^ORschedule_status=no_answer');
                <!-- surveyRecord.addQuery('schedule_status=no_answer'); -->
                surveyRecord.query();
                while(surveyRecord.next())
                {
                    var t = surveyRecord.callback_date_time;
                    var startTime = new GlideDateTime(t);
                    var testtime = startTime.getDisplayValueInternal();
                    var finalTime = new GlideDateTime(testtime);
                    var mSecs = finalTime.getTime().getNumericValue();
                    var min = mSecs / (1000 * 60); 
                    var b = Math.floor(min / 30);
                    if (b >= 18 &amp;&amp; 39 >= b){
                        if(surveyRecord.schedule_status == 'no_answer')
                        {
                            var tot = obj.timebuckets[b].totalSystem;
                            obj.timebuckets[b].totalSystem = tot + 1;
                            obj.timebuckets[b].totalRow = obj.timebuckets[b].totalRow + tot + 1;
                            systemGrandTotal = systemGrandTotal + 1;
                        }
                    else{
                        var tot = obj.timebuckets[b].totalInterviewer;
                        obj.timebuckets[b].totalInterviewer = tot + 1;
                        obj.timebuckets[b].totalRow = obj.timebuckets[b].totalRow + tot + 1;
                        interviewerGrandTotal = interviewerGrandTotal + 1;

                    }     
                    } 
                }
            bucket.push(obj);
        }
</g:evaluate>
</g:ui_form>
<center>
</center> 
<div class="col-sm-12 col-md-12">
    <h1>All Studies Scheduling Report</h1>
</div> 
<table id="exportTable" name="exportTable" class="table table-bordered">
<thead>
<tr>
<th rowspan="2">Study</th> 
<j:forEach var="jvar_key" items="${bucket}">
    <th style="text-align: center" colspan="2">${jvar_key.study_type}</th>
</j:forEach>

</tr>
</thead>
<tbody>
<g:evaluate jelly="true">
            
</g:evaluate>   
<tr>
<th scope="row">Total Quota</th>
    <j:forEach var="jvar_key" items="${bucket}">
        <th style="text-align: center" colspan="2">${jvar_key.totQuota}</th>
    </j:forEach>
</tr>
<tr>
<th scope="row">Total Completes</th>
    <j:forEach var="jvar_key" items="${bucket}">
        <th style="text-align: center" colspan="2">${jvar_key.totComp}</th>
    </j:forEach>
</tr>
<tr>
<th scope="row">Total Attempts</th>
    <j:forEach var="jvar_key" items="${bucket}">
        <th style="text-align: center" colspan="2">${jvar_key.totAtt}</th>
    </j:forEach>
</tr>
<tr>
<th scope="row">Number of Interviewers Assigned</th>
    <j:forEach var="jvar_key" items="${bucket}">
        <th style="text-align: center" colspan="2">${jvar_key.intCount}</th>
    </j:forEach>
</tr>
<tr>
<th scope="row">Names of Assigned Interviewers</th>
    <j:forEach var="jvar_key" items="${bucket}">
        <th style="text-align: center" colspan="2">${jvar_key.intNames}</th>
    </j:forEach>
</tr>
<tr>  
<th>Queue Time Interval</th>
<j:forEach var="jvar_key" items="${bucket}">
    <th bgcolor="EBF3FC">System Scheduled Record Count</th>
    <th bgcolor="EBF3FC">Interviewer Scheduled Callback Record Count</th>
</j:forEach>

</tr>
<g:evaluate jelly="true">
    var idx = 0;
</g:evaluate>
<j:forEach items="${buckets}" var="jvar_field_name">

    <j:if test="${idx >= 18 &amp;&amp; 39 >= idx }">
    <tr>
    <td scope="row">${jvar_field_name.interval;}</td>
    
     <j:forEach items="${bucket}" var="jvar_bucket">
        
        <!-- <g:evaluate jelly="true">
            var interval = jvar_bucket.timebuckets[idx].interval;
            var interviewer = jvar_bucket.timebuckets[idx].totalInterviewer;
            var system = jvar_bucket.timebuckets[idx].totalSystem;
            if (interviewer == 0)
            {
                interviewer = "";
            }
            if (system == 0)
            {
                system = "";
            }
        </g:evaluate>    -->
        
        <td>${jvar_bucket.timebuckets[idx].totalSystem;} </td>
        <td>${jvar_bucket.timebuckets[idx].totalInterviewer;} </td>
        
    <!-- <j:forEach begin="0" end="2" items="${bucket}" var="jvar_bucket">
        <td>${jvar_bucket.timebuckets.totalSystem;}</td>
        <td>${idx} </td>
    </j:forEach> -->
    </j:forEach>
    </tr>   
    </j:if> 
    <g:evaluate jelly="true">
        idx++;
    </g:evaluate>
</j:forEach>
<tr class="success">
<th>Total</th>
<!-- <td>${systemGrandTotal}</td>
<td>${interviewerGrandTotal}</td> -->
</tr>
</tbody>
 
</table>
 
    <button type="button" class="btn btn-primary col-sm-2 col-md-2" style="position: relative; bottom: 0; right: 0;" onClick="tableToCSV()">Export Report </button>

</j:jelly>

Angular 17 – Trigger recurrent polling whenever a boolean variable becomes true and as long as it remains so

The situation is as follows:
I have a websocket for communication between app and server. If the websocket were to break I would like to enable backup long polling until the websocket becomes active again.

I thought of creating a Signal boolean that changes state based on the connection/disconnection of the WS. If the WS is active I set the signal to true otherwise to false.

 WSStatus = signal(false);
 WS is up: this.WSStatus(true)
 WS go down: this.WSStatus(false)

I thought about doing something like this, but takeUntil waits for an Observable and I was unable to replace the Signal operation with an Observable

 this.startPolling(5000).pipe(takeUntil(!this.WSStatus())).subscribe()
 startPolling(interval: number = 5000): Observable<string> {
  
    return timer(0, interval)
      .pipe(
        switchMap( () => { return this.myHttpRequest() })
      );
  }

From Buffer(“string”, “hex) to string JS

I’m writing a function to reduce the key by 2 times. The function accepts a key in the following form:
Buffer.from('0xe581d529cc69816e768432a8aa09178470c9b1e703951f4a85e0dab7d8008e2a9e9e179', 'hex')
so that I can reduce the key I need to convert it to a string. The toString() or toString(‘hex’) method does not work.
I also tried using sha256 encryption for the key, but when I called the function with different keys I still got the same value after hashing.
Checking the value of a key or its length using console.log() showed that the length was 0, but when printing the key it did not output anything

The toString() or toString(‘hex’) method does not work.
I also tried using sha256 encryption for the key, but when I called the function with different keys I still got the same value after hashing.
Checking the value of a key or its length using console.log() showed that the length was 0, but when printing the key it did not output anything

Java backend not responding to API call

I am trying to create a calculator app with Vue.js as the frontend and Java as the backend. I need the frontend to send calculations to the backend and the backend to respond with the result of the calculation in JSON format.

async function handleEquals() {
    if (error.value) {
        return;
    }
    const equation = current.value;
    const sendData = {
        equation: equation
    };

    try {
        const response = await axios.post('http://localhost:8080/api/calculate', sendData);
        if (!(/d/.test(response.data.toString()))) {
            error.value = true;
        }
        current.value = response.data.toString();
    } catch (error) {
        console.error(error);
    }
}

The client connects to the server but the calculations are not received by the backend.

@RestController
@RequestMapping(path = "/api")
public class CalculationController {

  private final CalculationService calculationService;
  Logger logger = LoggerFactory.getLogger(CalculationController.class);

  @Autowired
  public CalculationController(CalculationService calculationService) {
    this.calculationService = calculationService;
  }
  @PostMapping("/calculate")
  @CrossOrigin(origins = "*")
  public String calculate(@RequestBody Calculation calculation) {
    logger.info("Received expression: {}", calculation.getExpression());
    return calculationService.calculate(calculation.getExpression());
  }
}

The backend throws a NullPointerException because the calculation is null. I suspect the issue is in the frontend but not sure how to fix it.

I have changed the frontend code multiple times but am unable to get the calculations sent to the backend. The backend is constructed with Spring Boot and compiled with Maven and Java 21.

Solidjs reactivity on arrays

I can’t really figure out why below code reacts this way with solidjs. In the function handleFileChange, if I update the array by modifying its elements field directly, solidjs detects the change. But if I replace the element, nothing happens. This is really strange to me. I need to understand why it is like this or I’m giving up on this framework asap. Please help !

function Test() {
    const [files, setFiles] = createSignal([{ f: null }, { f: null }]);

    const handleFileChange = (index: number, event: any) => {
        const file = event.target.files[0]
        const newFiles = [...files()];
        // newFiles[index].f = file;        // This works as expected.
        newFiles[index] = {f:file}       // Nothing happens here. ????
        setFiles(newFiles);
    };
 

    return (
        <div>
            <For each={files()}>
                {(_, index) => (
                    <div>
                        <input
                            type="file"
                            onChange={(event) => handleFileChange(index(), event)}
                         />
     
                    </div>
                )}
            </For>
        </div>
    );
}

Bla bla… I hate that I’m forced to write something here. Nonsense.

How can make z-index absolute even if there’s transformation modifiers on the element?

In my codesnippit I want to make the red box appear over the black box but under the text. The problem is when I add transform: translateZ(0px); to the black box, my z-index: 2; CSS on my text doesn’t work anymore. I was wondering if there was a way for one thing to appear on top of another even if they are being transformed. like no matter what Z space each box is in I want the text to appear on top of the red box.

body {
  width: 100vw;
  height: 100vh;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
}

.black-box {
  width: 200px;
  height: 150px;
  background: black;
  display: flex;
  justify-content: center;
  align-items: center;
  transform: translateZ(0px);
  border-radius: 20px;
}

.black-box p {
  font-size: 30px;
  z-index: 2;
}

.red-box {
  position: absolute;
  width: 100px;
  height: 100px;
  background: red;
  transform: translateX(-40px);
  z-index: 1;
  border-radius: 100%;
  opacity: 75%;
}
<div class="black-box">
  <p>hello</p>
</div>
<div class="red-box"></div>

How to address timeout issue on fetch function

I am currently developing a program that utilizes long polling to perform periodic fetches.

However, I am frequently encountering timeout errors during the fetch process, despite having a stable internet connection. I have thoroughly verified that my internet connection is functioning properly, and the issue persists.

I have already tried the following solutions, but the problem still persists:

  • increase timeout by signal: AbortSignal.timeout(1000 * 200)
  • use keepAlive option
  • increase timeout from query string on telegram api
  • fetch per 2 second instead of miliseconds

Here are some additional details that may be relevant:

Test by speedtest:

Idle Latency:    20.14 ms   (jitter: 2.87ms, low: 19.27ms, high: 29.80ms)
    Download:     9.76 Mbps (data used: 11.5 MB)                                                   
                522.78 ms   (jitter: 88.34ms, low: 45.85ms, high: 1349.79ms)
      Upload:     0.34 Mbps (data used: 597.3 kB)                                                   
               2274.00 ms   (jitter: 93.18ms, low: 186.00ms, high: 3920.09ms)
 Packet Loss:     0.0%

Error log (actually it happens more than three times):

TypeError: fetch failed
    at node:internal/deps/undici/undici:12443:11
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async handler (/home/user/control-center/start-service.js:15:22) {
  cause: AggregateError [ETIMEDOUT]: 
      at internalConnectMultiple (node:net:1116:18)
      at internalConnectMultiple (node:net:1184:5)
      at Timeout.internalConnectMultipleTimeout (node:net:1707:5)
      at listOnTimeout (node:internal/timers:575:11)
      at process.processTimers (node:internal/timers:514:7) {
    code: 'ETIMEDOUT',
    [errors]: [ [Error], [Error] ]
  }
}
TypeError: fetch failed
    at node:internal/deps/undici/undici:12443:11
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async handler (/home/user/control-center/start-service.js:15:22) {
  cause: AggregateError [ETIMEDOUT]: 
      at internalConnectMultiple (node:net:1116:18)
      at internalConnectMultiple (node:net:1184:5)
      at Timeout.internalConnectMultipleTimeout (node:net:1707:5)
      at listOnTimeout (node:internal/timers:575:11)
      at process.processTimers (node:internal/timers:514:7) {
    code: 'ETIMEDOUT',
    [errors]: [ [Error], [Error] ]
  }
}
TypeError: fetch failed
    at node:internal/deps/undici/undici:12443:11
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async handler (/home/user/control-center/start-service.js:15:22) {
  cause: AggregateError [ETIMEDOUT]: 
      at internalConnectMultiple (node:net:1116:18)
      at internalConnectMultiple (node:net:1184:5)
      at Timeout.internalConnectMultipleTimeout (node:net:1707:5)
      at listOnTimeout (node:internal/timers:575:11)
      at process.processTimers (node:internal/timers:514:7) {
    code: 'ETIMEDOUT',
    [errors]: [ [Error], [Error] ]
  }
}

The snippet code:

const param = `timeout=150&offset=${last_update}`;
const response = await fetch(`${process.env.BASE_URL}/getUpdates?${param}`, { keepalive: true }).then(res => res.json())

full code availabe on github repository

how to solve CORS problem whith local html three.js?

I´ve been trying to make an sphere whith three.js with an image texture but without a server, i mean im just learning and i jjust want to use vs code but ether way this an local image or an https image online it gives this error:

Access to image at 'file:///C:/Users/***/...../***/sun.jpg' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted.
GET file:///C:/Users/...../sun.jpg net::ERR_FAILED

And here the code im using:

const geometry = new THREE.SphereGeometry(5, 32, 32);
const cargador = new THREE.TextureLoader().load("sun.jpg");
const cargaTextura = new THREE.MeshBasicMaterial({
map: cargador
});
const sphere = new THREE.Mesh(geometry, material);
scene.add(sphere);

im not a profesional programer so if someone can explain everthing it would be great
thanks for all help.