Error: GET http://localhost:5000/api/notes/fetchallnotes 401 (Unauthorized) and TypeError: notes.map is not a function

*I am working on a React application where I am fetching notes from an API. However, I am encountering two errors:

  1. GET http://localhost:5000/api/notes/fetchallnotes 401 (Unauthorized): This error indicates that the request to fetch notes is unauthorized. I have tried including the access token in the request headers, but the error persists.
  2. TypeError: notes.map is not a function: This error occurs in the Notes.js file when I attempt to iterate over the notes array. However, the useEffect hook ensures that the getNotes function is called and the notes array is populated before the render.
    Additional Information:
  • I am using React and the context API for state management.
  • The relevant code snippets are provided below:
    NoteState.js:
import React, { useContext, useEffect, useRef, useState } from "react";

import noteContext from "../Context/notes/noteContext";
import Noteitem from "./Noteitem";
import AddNote from "./AddNote";
import { useNavigate } from "react-router-dom";

const Notes = (props) => {
  const context = useContext(noteContext);
  let navigate = useNavigate();
  const { notes, getNotes, editNote } = context;

  useEffect(() => {
    if (localStorage.getItem("token")) {
      getNotes();
    } else {
      navigate("/");
    }
  // eslint-disable-next-line
  }, []);

  // ...

  return (
    <>
      {/* ... */}
      <div className="row my-3">
        <h2>Your Notes</h2>
        <div className="container mx-2">
          {notes.length === 0 && "No notes to display."}
        </div>
        {notes.map((note) => {
          return (
            <Noteitem
              key={note._id}
              updateNote={updateNote}
              note={note}
              showAlert={props.showAlert}
            />
          );
        })}
      </div>
    </>
  );
};

export default Notes;

Note.js:

import React, { useContext, useEffect, useRef, useState } from "react";

import noteContext from "../Context/notes/noteContext";
import Noteitem from "./Noteitem";
import AddNote from "./AddNote";
import { useNavigate } from "react-router-dom";

const Notes = (props) => {
  const context = useContext(noteContext);
  let navigate = useNavigate();
  const { notes, getNotes, editNote } = context;

  useEffect(() => {
    if (localStorage.getItem("token")) {
      getNotes();
    } else {
      navigate("/");
    }
  // eslint-disable-next-line
  }, []);

  // ...

  return (
    <>
      {/* ... */}
      <div className="row my-3">
        <h2>Your Notes</h2>
        <div className="container mx-2">
          {notes.length === 0 && "No notes to display."}
        </div>
        {notes.map((note) => {
          return (
            <Noteitem
              key={note._id}
              updateNote={updateNote}
              note={note}
              showAlert={props.showAlert}
            />
          );
        })}
      </div>
    </>
  );
};

export default Notes;

Threejs: Pointlight not lighting up my geometries

I’m trying to create a scene from a set of triangles using Threejs. To get the shape of all the triangles i used a BufferGeometry which seems to create the shape correctly. However, it does not respond to lighting. I have tried with several different materials including standard, phong and lambert. With on luck. I understood that one might need to compute normals to the mesh, so i tried adding computeVertexNormals to the code as well but no luck. Ive also tried using flatshading, but that did not seem to have any effect either.

I then figured it might be the geometry and not the material that was throwing me of, so I tried adding a spinning torus to my scence using phong material, but it does not get iluminated either.

The code I have so far is this:

import * as THREE from 'three';
import {OrbitControls} from 'three/addons/controls/OrbitControls.js';

const canvas = document.querySelector('#c')
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000000);
const renderer = new THREE.WebGLRenderer({antialias: true,castShadow:true, canvas});
const controls = new OrbitControls(camera, canvas)

renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement)

const topoGeometry = new THREE.BufferGeometry();
// Fetching triangles from static file
await fetch('http://{localserver}/topography.json')
    .then((response) => response.json())
        .then((json) => {
            const vertices = new Float32Array(json.geometry.vertices.map((coord) => {
                return [coord[0], coord[1], coord[2]]
            }).flat())
            const indices = json.geometry.triangles.flat()
            topoGeometry.setIndex( indices )
            topoGeometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3))
            topoGeometry.computeVertexNormals()
        });
const  topoMaterial = new THREE.MeshStandardMaterial({
    wireframe: false,
    color: 0x00ff00,
});
const topo = new THREE.Mesh( topoGeometry, topoMaterial )
scene.add(topo)

camera.position.z = 2000;
camera.position.x = 0;
camera.position.y = 0;

const torusGeometry = new THREE.TorusGeometry(50,50)
const torusMaterial = new THREE.MeshPhongMaterial()
const torus = new THREE.Mesh(boxGeometry, boxMaterial)
torus.position.setZ(400)
scene.add(torus)


//Adding pointlight to scene
const light = new THREE.PointLight( 0xffffff, 1, 1000 );
light.position.set( 0, 0, 600 );
light.castShadow = true;
scene.add( light );

const lighthelper = new THREE.PointLightHelper(light,30, 0xffffff)
const gridHelper = new THREE.GridHelper(3000,50)
gridHelper.rotateX(Math.PI / 2)
scene.add(lighthelper, gridHelper)

function animate(){
    requestAnimationFrame(animate)
    camera.updateProjectionMatrix()
    controls.update(0.01)
    box.rotateX(0.01)
    box.rotateY(0.01)
    renderer.render(scene, camera)
}
animate()

Heres a small gif from the resulting scene:
Dark scene, pointlighthelper displayed as the white wireframe diamond

Why a string strictly compared (===) to a value of type string stored in a variable gives false?

I am trying to write a function do some math operations with operands fed into it as a string. The return should also be a string. Whatever I do I still get undefined.

Here’s the function:

function calculator(string) {

There is another function with switch inside of it that outputs the desired string:

function arithmetic (op1, op2, operation) {
    switch (operation) {
      case "/" :
return String(Math.floor(op1/op2));
        break
      case "*" :
        return String(op1*op2);
        break
      case "-":
        return String(op1-op2);
        break
      case "+" :
        return String(op1+op2);
        break
    }

Next there goes a map for converting Arabic numerals to Roman ones and a similar function for operations with Roman numerals, but I’ll leave it out. Come to speak of it, it gives undefined also.

Now I create arrays with operands and with an operation needed (tried to put them in the beginning – no difference)

let arrOperands = string.split(/W/).filter(i=> i!= "").map (item=>Number.isInteger(parseInt(item)) ? +item : item);
  let arrOperation = string.split(/w/).filter(i=> i!= "");

At last there is a ternary operator that ensures the string would meet the conditions imposed (have switched it off while debugging)

/* (arrOperands.length == 2 && arrOperation.length == 1) &&
    (Number.isInteger(arrOperands[0]) && Number.isInteger(arrOperands[1])) &&
    (arrOperands[0] <= 10 && arrOperands[1] <= 10)
    ? arithmetic (arrOperands[0], arrOperands[1], arrOperation[0])
    : (arrOperands.length == 2 && arrOperation.length == 1) && ( typeof arrOperands[0] === typeof string && typeof arrOperands[1] === typeof string )
    ?  romanArithmetic (arrOperands[0], arrOperands[1], arrOperation[0])
    : new Error()*/

While having tried to find why it doesn’t work I came across that the arithmetic function invoked as arithmetic (arrOperands[0], arrOperands[1], "/") works fine and gives the output aspired (say 9 / 3 gives 3), while the same function invoked as arithmetic(arrOperands[0], arrOperands[1], arrOperation[0]) throws undefined. It turned out that arrOperation[0] === “/” results in false which apparently does not trigger case "/" : return String(Math.floor(op1/op2)) of
switch and returns nothing (undefined).

I do not get it, the more so because the type of arrOperation[0] and that of "/" are string. Why is that so?

How to Animate SVG Progress Bar with Needle?

I’m currently working on implementing an SVG progress bar with a needle in a React Native project, and I’m facing challenges with the necessary transformations and animations. The progress bar represents a certain percentage of completion, and I’d like to animate the needle to point to the current progress dynamically.

I’ve tried incorporating transformations using React Native Animated library, but I’m encountering issues with the SVG elements and their animations. Specifically, I need assistance with the correct usage of transformations and creating a smooth animation for the needle that accurately corresponds to the progress.

enter image description here

...

interface SpeedometerSvgProps {
  value: number; // Value to determine the rotation of the needle
}

const SpeedometerSvg: React.FC<SpeedometerSvgProps> = ({ value }) => {
  // Calculate the rotation angle based on the provided value
  const rotationAngle = (value / 100) * 180; // Assuming the value ranges from 0 to 100
  console.log(rotationAngle)
  return (
    <Svg width="174" height="89.139" viewBox="0 0 174 89.139">
      <G id="Group_1370" data-name="Group 1370" transform="translate(-128 -230.287)">
        <Path
          id="Path_927"
          data-name="Path 927"
          d="M174,87A87,87,0,0,0,0,87H37.821a49.177,49.177,0,0,1,98.354,0Z"
          transform="translate(128 230.287)"
          fill="#fff"
          fill-rule="evenodd"
        />
        <Path
          id="Path_928"
          data-name="Path 928"
          d="M88.17,89.06a6.325,6.325,0,0,1-4.336-7.8L112.8,2.47,96,84.753A6.314,6.314,0,0,1,88.17,89.06"
          transform={`translate(122.258 230.118) rotate(${rotationAngle} 100 100)`}
          fill="#848a94"
          fill-rule="evenodd"
        />
        <Path
          id="Path_929"
          data-name="Path 929"
          d="M37.821,87A49.17,49.17,0,0,1,87,37.823a48.33,48.33,0,0,1,6.841.464L107.059,2.3A87.162,87.162,0,0,0,0,87Z"
          transform="translate(128 230.287)"
          fill="#ef3f23"
          fill-rule="evenodd"
        />
      </G>
    </Svg>
  );
};

export default SpeedometerSvg;

If anyone has experience with animating SVG elements, especially progress bars with needles, in a React Native environment, your insights would be greatly appreciated! Feel free to share code snippets, examples, or any guidance that could help me achieve a seamless animation for this SVG progress bar with a needle.

D3 map shifts after rendering new paragraph below

I am trying to create a D3 map that allows me to create text paragraphs below the map when countries in blue are clicked.

The map initially looks like this: centered world map
When clicking the blue countries, a text paragraph is generated which says a blurb of text below.
The issue is the map shifts to the far left side when the text paragraph is rendered as shown here: Map shifted

link to codesandbox dev environment:
https://codesandbox.io/p/devbox/d3-world-map-shifts-after-rendering-paragraph-przqvp?file=%2Fsrc%2Findex.jsx&embed=1

JSX:

import React, { useEffect, useRef,useState} from "react"; 
import ReactDOM from 'react-dom';
import * as d3 from "d3";
import mapdata from "./Components/data.csv";

let visitedCountries = ["USA","Canada","Ireland","Egypt","Czech Republic","Germany","France","Greece","Iceland","Italy","Japan","Lao People's Democratic Republic","Mexico","Norway","Poland","Thailand"];
function RecieveCountry(props) {
    let contains = visitedCountries.includes(props.name);
    if(contains){
        return(
            <div >
                    <p className = "Text">
                    Smallest directly families surprise honoured am an. Speaking replying mistress him numerous she returned feelings may day. Evening way luckily son exposed get general greatly. Zealously prevailed be arranging do. Set arranging too dejection september happiness. Understood instrument or do connection no appearance do invitation. Dried quick round it or order. Add past see west felt did any. Say out noise you taste merry plate you share. My resolve arrived is we chamber be removal.

                    On on produce colonel pointed. Just four sold need over how any. In to september suspicion determine he prevailed admitting. On adapted an as affixed limited on. Giving cousin warmly things no spring mr be abroad. Relation breeding be as repeated strictly followed margaret. One gravity son brought shyness waiting regular led ham.

                    </p>
            </div>
        );
    }else{
        return(
            <div >
            </div>
        );
    }

}

const WorldMap = () => {
  const ref = useRef();
  const ref2 = useRef();
  const [Country, setCountry] = useState("");
  useEffect(() => {
    // set the dimensions and margins of the graph
    const width = 900;
    const height = 900;
    
    const svg = d3
      .select(ref.current)
      .append("svg")
      .attr("width", width)
      .attr("height",height)

    // Map and projection
    const path = d3.geoPath();
    const projection = d3.geoMercator()

    .center([0,20])
    .translate([width / 2, height / 2]);
  
  // Data and color scale
  const data = new Map();
  const colorScale = d3.scaleLinear()
  .domain([0,1])
  .range(["grey","blue"]);
  
  // Load external data and boot
  Promise.all([
  d3.json("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/world.geojson"),
  d3.csv("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/world_population.csv", function(d) {
      data.set(d.code, +d.visited)
  })]).then(function(loadData){
      let topo = loadData[0]
  
      let mouseOver = function(d) {
      d3.selectAll(".Country")
        .transition()
        .duration(200)
        .style("opacity", .5)
      d3.select(this)
        .transition()
        .duration(200)
        .style("opacity", 1)
        .style("stroke", "black")
    }
  
    let mouseLeave = function(d) {
      d3.selectAll(".Country")
        .transition()
        .duration(200)
        .style("opacity", .8)
      d3.select(this)
        .transition()
        .duration(200)
        .style("stroke", "transparent")
    }

    let mouseClick = function (event, d) {
            d3.selectAll(".Country")
              .transition()
              .duration(200)
              .style("opacity", 0.8);
            d3.select(this)
              .transition()
              .duration(200)
              .style("stroke", "transparent");
              setCountry(d.properties.name);
              console.log(d.properties.name);
              
          };
    
    // Draw the map
    svg.append("g")
      .selectAll("path")
      .data(topo.features)
      .enter()
      .append("path")
        // draw each country
        .attr("d", d3.geoPath()
          .projection(projection)
        )
        // set the color of each country
        .attr("fill", function (d) {
          d.total = data.get(d.id) || 0;
          return colorScale(d.total);
        })
        .style("stroke", "transparent")
        .attr("class", function(d){ return "Country" } )
        .style("opacity", .8)
        .on("mouseover", mouseOver )
        .on("mouseleave", mouseLeave )
        .on("click", mouseClick); // Attach the mouseClick function
  
  });
  }, [Country]);
  
  return <div className = "worldTravel">
    <div><svg width={900} height={900} id="WorldMap" ref={ref} /></div>
    <div><RecieveCountry name = {Country} ref = {ref2}/></div>
    </div>;
};

function App() {
    return (
      <div className ="worldTravel">
      <WorldMap />
      </div>
    );
  }

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <App/>
);

CSS:

html, body {
  margin:0;
  width: 100%;
  height: 100%;
}

.worldTravel{
  display:flex;
  flex-direction: column;
  align-self: center;
}

.Text{
  color:black;
  font-size: 20px;
}

Problem on TaskEither sequenceArray function for processing different types of return type

I am working on functional programming using fp-ts library.
Here is my code and my problem:

import * as TE from 'fp-ts/TaskEither';
import { pipe } from 'fp-ts/lib/function';

function getName(): TE.TaskEither<Error, String> {
  return TE.right('John Doe');
}

function getAge(): TE.TaskEither<Error, number> {
  return TE.right(40);
}

export function seqArrayTest() {
  return pipe(
    TE.sequenceArray([getName(), getAge()]),
    TE.chain(([name, age]) => {
      return TE.right(`Name: ${name}, Age: ${age}`);
    }),
  );
}

Here:

  1. I have two functions: getName and getAge returning TaskEither with different value types.
  2. I am calling them parallel using TE.sequenceArray.
  3. After the computation, I am just chaining the response and returning another TaskEither.

During compilation, on TE.sequenceArray([getName(), getAge()]), it shows below error for getAge():

Type ‘TaskEither<Error, number>’ is not assignable to type ‘TaskEither<Error, String>’.
Type ‘number’ is not assignable to type ‘String’.ts(2322)

But my understanding is: TE.sequenceArray should take an array of functions with different return types but wrap with TaskEither and it will also return an array of responses sequentially.

What is the purpose of the .txt files generated for each route?

I just recently upgraded my pages router to app router, and everything went fairly smooth. However I noticed that for every page, Next also generates a .txt file.

My main concern here is that for my own project, it generates about 500 .txt files, that are all uploaded to Vercel during a production build.

I tried this on a new project:

npx create-next-app@latest

next.config.js:

const nextConfig = {
    output: 'export'
}

npm run build

In the out directory, I can see an index.html and index.txt. The content of this file is:

2:I[1749,["749","static/chunks/749-fc220e462fd6a346.js","931","static/chunks/app/page-7da0e53e89db0c3c.js"],"Image"]
3:I[5613,[],""]
4:I[1778,[],""]
0:["67cSbQl5_wFlHWg_tKfIU",[[["",{"children":["__PAGE__",{}]},"$undefined","$undefined",true],["",{"children":["__PAGE__",{},["$L1",["$","main",null,{"className":"flex min-h-screen flex-col items-center justify-between p-24","children":[["$","div",null,{"className":"z-10 max-w-5xl w-full items-center justify-between font-mono text-sm lg:flex","children":[["$","p",null,{"className":"fixed left-0 top-0 flex w-full justify-center border-b border-gray-300 bg-gradient-to-b from-zinc-200 pb-6 pt-8 backdrop-blur-2xl dark:border-neutral-800 dark:bg-zinc-800/30 dark:from-inherit lg:static lg:w-auto  lg:rounded-xl lg:border lg:bg-gray-200 lg:p-4 lg:dark:bg-zinc-800/30","children":["Get started by editing ",["$","code",null,{"className":"font-mono font-bold","children":"app/page.tsx"}]]}],["$","div",null,{"className":"fixed bottom-0 left-0 flex h-48 w-full items-end justify-center bg-gradient-to-t from-white via-white dark:from-black dark:via-black lg:static lg:h-auto lg:w-auto lg:bg-none","children":["$","a",null,{"className":"pointer-events-none flex place-items-center gap-2 p-8 lg:pointer-events-auto lg:p-0","href":"https://vercel.com?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app","target":"_blank","rel":"noopener noreferrer","children":["By"," ",["$","$L2",null,{"src":"/vercel.svg","alt":"Vercel Logo","className":"dark:invert","width":100,"height":24,"priority":true}]]}]}]]}],["$","div",null,{"className":"relative flex place-items-center before:absolute before:h-[300px] before:w-[480px] before:-translate-x-1/2 before:rounded-full before:bg-gradient-radial before:from-white before:to-transparent before:blur-2xl before:content-[''] after:absolute after:-z-20 after:h-[180px] after:w-[240px] after:translate-x-1/3 after:bg-gradient-conic after:from-sky-200 after:via-blue-200 after:blur-2xl after:content-[''] before:dark:bg-gradient-to-br before:dark:from-transparent before:dark:to-blue-700 before:dark:opacity-10 after:dark:from-sky-900 after:dark:via-[#0141ff] after:dark:opacity-40 before:lg:h-[360px] z-[-1]","children":["$","$L2",null,{"className":"relative dark:drop-shadow-[0_0_0.3rem_#ffffff70] dark:invert","src":"/next.svg","alt":"Next.js Logo","width":180,"height":37,"priority":true}]}],["$","div",null,{"className":"mb-32 grid text-center lg:max-w-5xl lg:w-full lg:mb-0 lg:grid-cols-4 lg:text-left","children":[["$","a",null,{"href":"https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app","className":"group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30","target":"_blank","rel":"noopener noreferrer","children":[["$","h2",null,{"className":"mb-3 text-2xl font-semibold","children":["Docs"," ",["$","span",null,{"className":"inline-block transition-transform group-hover:translate-x-1 motion-reduce:transform-none","children":"->"}]]}],["$","p",null,{"className":"m-0 max-w-[30ch] text-sm opacity-50","children":"Find in-depth information about Next.js features and API."}]]}],["$","a",null,{"href":"https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app","className":"group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30","target":"_blank","rel":"noopener noreferrer","children":[["$","h2",null,{"className":"mb-3 text-2xl font-semibold","children":["Learn"," ",["$","span",null,{"className":"inline-block transition-transform group-hover:translate-x-1 motion-reduce:transform-none","children":"->"}]]}],["$","p",null,{"className":"m-0 max-w-[30ch] text-sm opacity-50","children":"Learn about Next.js in an interactive course with quizzes!"}]]}],["$","a",null,{"href":"https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app","className":"group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30","target":"_blank","rel":"noopener noreferrer","children":[["$","h2",null,{"className":"mb-3 text-2xl font-semibold","children":["Templates"," ",["$","span",null,{"className":"inline-block transition-transform group-hover:translate-x-1 motion-reduce:transform-none","children":"->"}]]}],["$","p",null,{"className":"m-0 max-w-[30ch] text-sm opacity-50","children":"Explore starter templates for Next.js."}]]}],["$","a",null,{"href":"https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template&utm_campaign=create-next-app","className":"group rounded-lg border border-transparent px-5 py-4 transition-colors hover:border-gray-300 hover:bg-gray-100 hover:dark:border-neutral-700 hover:dark:bg-neutral-800/30","target":"_blank","rel":"noopener noreferrer","children":[["$","h2",null,{"className":"mb-3 text-2xl font-semibold","children":["Deploy"," ",["$","span",null,{"className":"inline-block transition-transform group-hover:translate-x-1 motion-reduce:transform-none","children":"->"}]]}],["$","p",null,{"className":"m-0 max-w-[30ch] text-sm opacity-50","children":"Instantly deploy your Next.js site to a shareable URL with Vercel."}]]}]]}]]}],null]]},[null,["$","html",null,{"lang":"en","children":["$","body",null,{"className":"__className_e66fe9","children":["$","$L3",null,{"parallelRouterKey":"children","segmentPath":["children"],"loading":"$undefined","loadingStyles":"$undefined","loadingScripts":"$undefined","hasLoading":false,"error":"$undefined","errorStyles":"$undefined","errorScripts":"$undefined","template":["$","$L4",null,{}],"templateStyles":"$undefined","templateScripts":"$undefined","notFound":[["$","title",null,{"children":"404: This page could not be found."}],["$","div",null,{"style":{"fontFamily":"system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"","height":"100vh","textAlign":"center","display":"flex","flexDirection":"column","alignItems":"center","justifyContent":"center"},"children":["$","div",null,{"children":[["$","style",null,{"dangerouslySetInnerHTML":{"__html":"body{color:#000;background:#fff;margin:0}.next-error-h1{border-right:1px solid rgba(0,0,0,.3)}@media (prefers-color-scheme:dark){body{color:#fff;background:#000}.next-error-h1{border-right:1px solid rgba(255,255,255,.3)}}"}}],["$","h1",null,{"className":"next-error-h1","style":{"display":"inline-block","margin":"0 20px 0 0","padding":"0 23px 0 0","fontSize":24,"fontWeight":500,"verticalAlign":"top","lineHeight":"49px"},"children":"404"}],["$","div",null,{"style":{"display":"inline-block"},"children":["$","h2",null,{"style":{"fontSize":14,"fontWeight":400,"lineHeight":"49px","margin":0},"children":"This page could not be found."}]}]]}]}]],"notFoundStyles":[],"styles":null}]}]}],null]],[[["$","link","0",{"rel":"stylesheet","href":"/_next/static/css/d9c1932c9f423671.css","precedence":"next","crossOrigin":""}]],"$L5"]]]]
5:[["$","meta","0",{"name":"viewport","content":"width=device-width, initial-scale=1"}],["$","meta","1",{"charSet":"utf-8"}],["$","title","2",{"children":"Create Next App"}],["$","meta","3",{"name":"description","content":"Generated by create next app"}],["$","link","4",{"rel":"icon","href":"/favicon.ico","type":"image/x-icon","sizes":"16x16"}],["$","meta","5",{"name":"next-size-adjust"}]]
1:null

There’s no reference to any of these files.

Difference in reading imagedata on local vs production

I wrote a trimming function that uses getImageData to trim from the right end of the image until it comes across a line that doesn’t just consist of just that pixel color. However, during my testing I noticed that on localhost, everything is fine, but on production, the source image that I drag and drop onto the page now has some image values where the alpha is indeed 0, but the r, g or b value has a 1 or higher in it, meaning it fails detecting a pixel that looks like [0,0,0,0].

This is the source image, with the right hand side having transparent alpha pixels (and the left because I’m a bit lazy here, but that shouldn’t affect the outcome):

This is the source image created with a photoshop like program

I wrote a method (normaliseCanvasAlphaValues in the snippet below) that goes over the image data and draws a reasonably thick stroke around any pixel whose alpha is 0 but whose rgb values are not. On localhost the result is this (I know, it looks the same but this one was downloaded after being drawn to a canvas in the browser):

All looks normal on localhost

All good so far! But when I try exactly the same code on production, something weird happens:

RGB pixels values with alpha 0 appear

What is going on here? I tried adjusting the colorSpace of various contexts to srgb and display-p3 but none of those make the issue go away. The only difference is from where it is run, but I am unsure why encoding or decoding would differ between these two environments?

You can try it out by downloading the original image and plonking it in the snippet, even on Stack Overflow itself it generates these empty pixels. Anybody got any idea how I can work around this? Or what exactly is the issue here? I am aware I could just check for only the alpha value and it would be fine, but I’d like my trim method to be versatile enough to also trim whites and blacks and other colors.

function dragActivate( event ){

    event.preventDefault();

    event.target.classList.add( 'dragging-over' );

}
function dragDeactivate( event ){

    event.preventDefault();

    event.target.classList.remove( 'dragging-over' );

}
function normaliseCanvasAlphaValues( canvas ){

    const { width, height } = canvas;
    const ctx = canvas.getContext( '2d' );
    const data = ctx.getImageData( 0, 0, width, height ).data;
   
    for( let i = 0; i < data.length; i += 4 ){
        
        let [ r, g, b, a ] = data.slice( i, i + 4 );
        const p = i / 4;
        const x = p % width;
        const y = (p - x) / width;

        if( a === 0 && (r || g || b) ){
        
            ctx.clearRect( x, y, 1, 1 );
            ctx.filLStyle = 'blue';
            ctx.lineWidth = 10;
            ctx.strokeRect( x, y, 1, 1 );

            console.log( `Correction ${x},${y}` );

        }

    }

    return canvas;

}
function trimRight(
    source, 
    color = [ 0, 0, 0, 0 ],
    visualiser
){

    const ctx = source.getContext( '2d', { willReadFrequently: true } );
    const vCtx = visualiser.getContext( '2d' );

    visualiser.height = source.height;
    visualiser.width = source.width;

    vCtx.save();
    vCtx.globalAlpha = .25;
    vCtx.drawImage( source, 0, 0 );
    vCtx.restore();

    let x = source.width - 1;

    while( x > 0 ){
        
        const data = ctx.getImageData( x, 0, 1, source.height, { colorSpace: "display-p3" } ).data;
        const isEmpty = data.every((c, i) => color[i%4] === c);

        if( !isEmpty ){

            const pixels = [];

            for( let y = 0; y < source.height; y++ ){

                const pixel = data.slice( y * 4, y * 4 + 4 );
                const isEmpty = pixel.every((c, i) => color[i%4] === c);

                if( !isEmpty ){

                    vCtx.fillStyle = 'orange';
                    vCtx.fillRect( x - 20, y, 20, 1 );
                    vCtx.strokeStyle = 'blue';
                    vCtx.lineWidth = 3;
                    vCtx.strokeRect( x - 20, y, 20, 1 );

                    console.log( y, isEmpty, pixel )

                } else {

                    vCtx.fillStyle = 'red';
                    vCtx.fillRect( x - 20, y, 20, 1 );

                }

                pixels.push( pixel );

            }

            break;

        }

        vCtx.fillStyle = 'green';
        vCtx.fillRect( x, 0, 1, visualiser.height );

        x--;

    }

    trimSyncBuffer.width = Math.max( 1, x + 1 );
    trimSyncBuffer.height = source.height;
    trimSyncBuffer.getContext( '2d', { willReadFrequently: true } ).drawImage( source, 0, 0 );

    source.width = trimSyncBuffer.width;
    source.height = trimSyncBuffer.height;
    
    ctx.drawImage( trimSyncBuffer, 0, 0 );

    return source;

}
function cloneCanvas( canvas ){

    const target = document.createElement( 'canvas' );
    const data = canvas.getContext( '2d' ).getImageData( 0, 0, canvas.width, canvas.height );
    const ctx = target.getContext( '2d', { willReadFrequently: true } );

    target.width = canvas.width;
    target.height = canvas.height;

    ctx.putImageData( data, 0, 0 );

    return target;

}

async function drop( event ){

    event.preventDefault();
    event.target.classList.remove( 'dragging-over' );
    
    const file = event.dataTransfer.files[0];
    const original = normaliseCanvasAlphaValues( await blobToCanvas( file ) );
    const trimmed = cloneCanvas( original );
    const visualised = cloneCanvas( original );

    main.innerHTML = '';
    main.append( original, visualised, trimmed );

    trimRight( trimmed, [ 0, 0, 0, 0 ], visualised );

}
async function blobToCanvas( blob, canvas = document.createElement( 'canvas' ) ){

    const image = new Image;
    const url = URL.createObjectURL( blob );
    
    return new Promise((resolve, reject) => {

        image.addEventListener( 'load', event => {

            canvas.width = image.naturalWidth;
            canvas.height = image.naturalHeight;

            canvas.getContext( '2d', { colorSpace: 'srgb', willReadFrequently: true }  ).drawImage( image, 0, 0 );

            resolve( canvas );

        });
        image.addEventListener( 'error', reject )
        image.src = url;

    }).finally(canvas => {

        URL.revokeObjectURL( url );

        return canvas;

    });

}

const main = document.querySelector( 'main' );
const trimSyncBuffer = document.createElement( 'canvas' );

main.addEventListener( 'dragenter', dragActivate );
main.addEventListener( 'dragover', dragActivate );
main.addEventListener( 'dragleave', dragDeactivate );
main.addEventListener( 'dragend', dragDeactivate );
main.addEventListener( 'drop', drop );
html, body {
    height: 100%;
}
main {
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-template-rows: 1fr 1fr;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}
main.dragging-over {
    background: red;
}
canvas {
    box-shadow: 0 0 20px black;
    width: 100%;
    height: auto;
}
<main></main>

React (Native) – is it possible to converting class component with static into functional component

I have created a custom component called FlixToast using class component long time ago

FlixToast.js

export default class FlixToast extends React.PureComponent {
  animation = new Animated.Value(0);
  constructor() {
    super();
    FlixToast.Flix = this;
    this.state = {
      toastList: [],
    };
  }
  
  // here i have a static method that need to be called globally
  static show(message, options) {
    FlixToast.Flix.show(message, options);
  }

  show(message, options) {
    const id = new Date().getTime().toString();
    const onClose = () => {
      this.hide(id);
    };
    requestAnimationFrame(() => {
      this.setState({
        toastList: [
          // ...this.state.toastList,
          {message, key: id, onClose, ...options},
        ],
      });
    });
  }

  hide(id) {
    this.setState({
      toastList: this.state.toastList.filter(t => t.key !== id),
    });
  }

  render() {
    return (
      <KeyboardAvoidingView
        behavior={Platform.OS === 'ios' ? 'position' : undefined}
        style={styles.containerView}
        pointerEvents="box-none"
      >
        {this.state.toastList.map((el, index) => (
          <Toast {...el} />
        ))}
      </KeyboardAvoidingView>
    );
  }
}

usually i call this render in App.js like this

App.js

import React from 'react';
import FlixToast from './path-of-my-flixtoast'
import MainApp from './path-of-my-MainApp'

const App = props => {
  return (
    <>
      <MainApp/>
      <FlixToast/>
    </>
  );
};

export default App;

so, everytime i want to show Toast i only need to call the show method without importing the FlixToast component like this

import React from 'react';
import {View, Text} from 'react-native';
import FlixToast from './path-of-my-flixtoast'

const Home = props => {
  React.useEffect(() => {
    FlixToast.show('Welcome user')
  }, []);
  return (
    <View style={{flex: 1}}>
      <Text>Home</Text>
    </View>
  );
};

export default Home;

Main Issue:

I want to convert FlixToast class based component into functional component, but i have a problem about converting the static method into function that can be called globally, is it possible?
any idea would be welcome

How to bind JS-to-python variable binding in jupyter notebooks with `IPython` in VsCode?

We use the IPython library to enable JS-to-python binding (have JS to “talk back” to python) in jupyter notebooks.
Our code works in jupyter notebooks in the browser, but not in VsCode’s jupyter notebooks.

Here’s a simple example to reproduce the problem.

from IPython.display import display, HTML, Javascript

js_code = """
function sendToPython(){
    var data = document.querySelector("#myInput").value;
    var kernel = IPython.notebook.kernel;
    kernel.execute("data_from_js = '" + data + "'");
}

document.querySelector("#myButton").addEventListener("click", function(){
    sendToPython();
});
"""

data_from_js = None

HTML_code = """
<input type="text" id="myInput" placeholder="Enter some text">
<button id="myButton">Submit</button>
<script type="text/Javascript">{}</script>
""".format(js_code)

display(HTML(HTML_code))

This will display a text element and a submit button.
Enter “hello” in input text field, then click “Submit” button.
Then, in a different cell, if you do print(data_from_js), you should get “hello”.

And we do, in a browser-based notebook.
But in VsCode the data_from_js variables remains untouched:

The developer tools console says “IPython is not defined”:

For more details, and attempts at solving this problem, see the Getting JS to talk back to Python jy discussion.

Fast forwarding a online video [closed]

I am on a online platform watching a video. But the video does not have the functionality to move forward the video progress bar. we have to watch the whole video to go to the next video. How can I move the progress bar forward?

I tried some JS code in chrome console but it dint work out

JavaScript loop backwards only works for 2 rounds, not 3 or more

I’m trying to calculate the number of player needed to start a tournament, based on number of games, rounds, team size, and other factors. The problem arises when there are 3 or more rounds. The math works for 1 and 2 rounds, but my loop is broken for 3+

For example:

  1. if you choose 4 players and singles in round 1, then the result is correct. Starting players = 4
  2. if you choose 4 players and singles in round 2, then the result is correct. Starting players = 16
  3. if you choose 4 players and singles in round 3, then the result is wrong. It should say starting players = 64, but it doesn’t update.

The calculations need to be made in reverse, from the final round back to the first.

  1. The starting players for each round determines the winning players for the previous round
  2. The winning players for that round determine the number of games
  3. The number of games determine the starting players
  4. And the starting players determine the winning players for the previous round… all the way back to round 1

I have this on codepen if it helps – https://codepen.io/Nim-Chimpsky/pen/NWoOQxZ

document.addEventListener('DOMContentLoaded', function() {
    let roundCount = 1;
    const roundsContainer = document.querySelector('.rounds-container');
    const roundsInfoContainer = document.querySelector('#roundsInfoContainer');
    const firstRound = document.querySelector('.round');

    const teamSizes = {
        'Singles': 1,
        'Doubles': 2,
        'Triples': 3,
        'Quads': 4,
        'Fivers': 5,
        'Sixers': 6,
        'Crusades': 12
    };

    function updateTeamsOptions(selectedPlayers, roundContainer) {
        roundContainer.querySelectorAll('.team-option').forEach(option => {
            const teamSize = teamSizes[option.getAttribute('data-value')];
            if (selectedPlayers % teamSize === 0 && selectedPlayers / teamSize >= 2) {
                option.disabled = false;
            } else {
                option.disabled = true;
                option.classList.remove('selected');
            }
        });
    }

    function updatePlayersOptions(mapValue, roundContainer) {
        let playerOptions = '';
        const maxPlayers = mapValue === 'Other' ? 24 : 12;

        for (let i = 2; i <= maxPlayers; i++) {
            playerOptions += `<button class="player-option" data-value="${i}">${i}</button>`;
        }

        const playersContainer = roundContainer.querySelector('.players');
        if (playersContainer) {
            playersContainer.innerHTML = playerOptions;
        }

        roundContainer.querySelectorAll('.player-option').forEach(option => {
            option.addEventListener('click', function() {
                clearSelected(roundContainer.querySelectorAll('.player-option'));
                this.classList.add('selected');
                updateTeamsOptions(parseInt(this.getAttribute('data-value')), roundContainer);
                updateRoundInfo();
            });
        });
    }

    function clearSelected(buttons) {
        buttons.forEach(btn => btn.classList.remove('selected'));
    }

    function initializeMapOptionListeners(roundElement) {
        roundElement.querySelectorAll('.map-option').forEach(option => {
            option.addEventListener('click', function() {
                const roundContainer = this.closest('.round');
                clearSelected(roundContainer.querySelectorAll('.map-option'));
                this.classList.add('selected');
                updatePlayersOptions(this.getAttribute('data-value'), roundContainer);
            });
        });
    }

    function initializeTeamOptionListeners(roundElement) {
        roundElement.querySelectorAll('.team-option').forEach(option => {
            option.addEventListener('click', function() {
                if (!this.disabled) {
                    const roundContainer = this.closest('.round');
                    clearSelected(roundContainer.querySelectorAll('.team-option'));
                    this.classList.add('selected');
                    updateRoundInfo();
                }
            });
        });
    }

    function updateRoundInfo() {
        const roundElements = document.querySelectorAll('.round');
        let nextRoundPlayers = 0;
        let roundInfos = [];

        for (let i = roundElements.length - 1; i >= 0; i--) {
            const round = roundElements[i];
            const selectedTeamOption = round.querySelector('.team-option.selected');
            let teamSize = 0;
            if (selectedTeamOption) {
                const teamType = selectedTeamOption.getAttribute('data-value');
                teamSize = teamSizes[teamType] || 0;
            }

            const playerSize = round.querySelector('.player-option.selected') ? parseInt(round.querySelector('.player-option.selected').getAttribute('data-value'), 10) : 0;

            let totalGames, totalWinners, totalPlayers;

            if (i === roundElements.length - 1) {
                totalGames = 1;
                totalWinners = teamSize;
                totalPlayers = playerSize;
            } else {
                totalWinners = nextRoundPlayers;
                totalGames = totalWinners / teamSize;
                totalPlayers = playerSize * totalGames;
            }

            nextRoundPlayers = playerSize; 

            const roundInfo = document.getElementById('roundsInfoTemplate').cloneNode(true);
            roundInfo.id = '';
            roundInfo.style.display = '';

            roundInfo.querySelector('.round-number').textContent = i + 1;
            roundInfo.querySelector('.num-players').textContent = totalPlayers;
            roundInfo.querySelector('.num-games').textContent = totalGames;
            roundInfo.querySelector('.num-winners').textContent = totalWinners;

            roundInfos.push(roundInfo);
        }

        roundsInfoContainer.innerHTML = '';

        for (let j = roundInfos.length - 1; j >= 0; j--) {
            roundsInfoContainer.appendChild(roundInfos[j]);
        }
    }

    function createRound() {
        roundCount++;
        const roundTemplate = firstRound.cloneNode(true);
        roundTemplate.querySelector('h2').textContent = `Round ${roundCount}`;

        roundTemplate.querySelectorAll('button').forEach(button => {
            button.classList.remove('selected');
            if (button.classList.contains('team-option')) {
                button.disabled = true;
            }
        });

        const mapOptions = roundTemplate.querySelectorAll('.map-option');
        mapOptions.forEach(btn => btn.classList.remove('selected'));
        const defaultMapButton = roundTemplate.querySelector(`.map-option[data-value="Other"]`);
        if (defaultMapButton) {
            defaultMapButton.classList.add('selected');
            updatePlayersOptions('Other', roundTemplate);
        }

        const deleteButton = document.createElement('button');
        deleteButton.textContent = `Delete Round ${roundCount}`;
        deleteButton.addEventListener('click', function() {
            roundsContainer.removeChild(this.parentElement);
            roundCount--;
            updateRoundInfo();
        });
        roundTemplate.appendChild(deleteButton);

        initializeMapOptionListeners(roundTemplate);
        initializeTeamOptionListeners(roundTemplate);

        roundsContainer.appendChild(roundTemplate);
        updateRoundInfo();
    }

    const addRoundButton = document.getElementById('addRound');
    addRoundButton.addEventListener('click', createRound);

    initializeMapOptionListeners(firstRound);
    initializeTeamOptionListeners(firstRound);
    updatePlayersOptions('Other', firstRound);
    updateRoundInfo();
});
body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.container {
    display: flex;
    justify-content: space-between;
    padding: 20px;
}

.left-side, .right-side {
    flex: 1;
    padding: 20px;
}

.rounds-container {
    margin-bottom: 20px;
}

.options {
    margin-bottom: 20px;
}

.options label {
    display: block;
    margin-bottom: 5px;
    font-weight: bold;
}

button {
    margin-right: 10px;
    padding: 5px 10px;
    cursor: pointer;
    background-color: #f0f0f0;
    border: 1px solid #ccc;
    border-radius: 5px;
}

button:hover {
    background-color: #e0e0e0;
}

.selected {
    background-color: #4CAF50; /* Green background for selected buttons */
    color: white;
}

h2 {
    color: #333;
    margin-bottom: 20px;
}

#addRound {
    padding: 10px 15px;
    background-color: #4CAF50;
    color: white;
    border: none;
    cursor: pointer;
    border-radius: 5px;
    font-size: 1em;
}

#addRound:hover {
    background-color: #4b844e;
}
<body>
    <div class="container">
        <div class="left-side">
            <div class="rounds-container">
                <div class="round">
                    <h2>Round 1</h2>
                    <div class="options">
                        <label>Map:</label>
                        <button class="map-option" data-value="12D">12D</button>
                        <button class="map-option" data-value="LandRush">Land Rush</button>
                        <button class="map-option selected" data-value="Other">Other</button>
                    </div>

                    <div class="options">
                        <label>Players:</label>
                        <div class="players"></div>
                    </div>

                    <div class="options">
                        <label>Teams:</label>
                        <button class="team-option" data-value="Singles">Singles</button>
                        <button class="team-option" data-value="Doubles">Doubles</button>
                        <button class="team-option" data-value="Triples">Triples</button>
                        <button class="team-option" data-value="Quads">Quads</button>
                        <button class="team-option" data-value="Fivers">Fivers</button>
                        <button class="team-option" data-value="Sixers">Sixers</button>
                        <button class="team-option" data-value="Crusades">Crusades</button>
                    </div>
                </div>
            </div>
            <button id="addRound">Add Another Round</button>
        </div>
        <div class="right-side">
            <div id="roundsInfoContainer">
                <!-- Round info will be dynamically added here -->
            </div>
            <div id="roundsInfoTemplate" style="display: none;">
              
              <div><h3>Round: <span class="round-number">1</span></h3></div>
                <div>Total Players in Round: <span class="num-players">0</span></div>
                <div>Total Games in Round: <span class="num-games">0</span></div>
                <div>Total Winners in Round: <span class="num-winners">0</span></div>
            </div>
        </div>
    </div>
    <script src="script.js"></script>
</body>

Strange GET responses from axios [closed]

I’m working on a small project. I’m fetching the current state of the user from API in react. For some reason, the response that I get from API differs when I use the fetch function and Axios. Here’s the code:

const API = axios.create({
    baseURL: `http://localhost:3001`
});
const response = await API.get(`auth/status/`)
        .then((res) => {
            console.log(res.data) // returns {status: false}
            user = res.data;
})
fetch("../auth/status/")
        .then((res) => res.json())
        .then((data) => {
            console.log(data) // return {status: true, user: "username"}
        });

Why does this happen? I need my Axios code to return the same response as the fetch function

Cannot import Container from NextUi

Hey guys I am pretty new at nodejs and I am having an issue when I try to use some components from NextUI. Basically, I followed the installation steps from here but it says
Module'@nextui-org/react' has no exported member Container for both components below:

import { Container, useToasts } from '@nextui-org/react';

Neverthless, these 2 imports are working fine for same library,

import { Input, Button } from '@nextui-org/react';

Here is my package.json:

{
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@nextui-org/react": "^2.2.9",
    "framer-motion": "^10.16.15",
    "next": "^14.0.3",
    "react": "^18.2.0",
    "react-dom": "^18.2.0"
  },
  "devDependencies": {
    "@types/node": "^20",
    "@types/react": "^18",
    "@types/react-dom": "^18",
    "autoprefixer": "^10.0.1",
    "eslint": "^8",
    "eslint-config-next": "14.0.3",
    "postcss": "^8",
    "tailwindcss": "^3.3.6",
    "typescript": "^5"
  }
}

And I am using node 18.

I would appreciate any help, thanks.