How do you call these clickable “scrollbars” to jump to exact points on the website?

I’m very new to coding and don’t know what to google to find any tutorials on this, can anyone tell me what this type of “scrollbar” is called?

And how are these scrollbars made? Is it similar to a nav-bar just vertically and without text or is there a different method to achieve this?

Of course if you know a good tutorial a link is very much appreciated as well :).

Failed to fetch a worker script. VueJS application

I’ve been trying to use a SharedWorker in a Vue application, but faced the error “Failed to fetch a worker script“.

I want to use a SharedWorker to get and post messages to WebSocket.

socketworker.js

const API_KEY =
  "380ec498044c900f249ad39326e8320a2cb4ee09b94afe4dff6911e37ef56bfc";
const socket = new WebSocket(
  `wss://streamer.cryptocompare.com/v2?api_key=${API_KEY}`
);

self.onconnect = e => {
  const port = e.ports[0];

  socket.addEventListener("message", evt => {
    if (evt.data) {
      port.postMessage(evt.data);
      return;
    }
  });
};

self.onmessage = e => {
  message = e.data;

  socket.send(message);
};

api.js

const socketWorker = new SharedWorker("./workers/socketworker.js", {
  type: "module",
  name: "socketWorker"
});

socketWorker.port.onmessage = e => {
 ...
}

CodePipeline: create vpc in stack and use it in post CodeBuildStep

I am creating a pipeline using AWS CDK. I first create my stack which consists in a vpc and an rds, I export the vpc object and use it in a post CodeBuildStep which migrates the database:

export class CdkPipelineStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props)

    const repo = new codecommit.Repository(this, 'CloudFrontCDKRepo', {
      repositoryName: 'claimsmate-backend',
    })
    const pipeline = new CodePipeline(this, 'Pipeline', {
      crossAccountKeys: false,
      pipelineName: 'MyPipeline2',
      synth: new ShellStep('Synth', {
        input: CodePipelineSource.codeCommit(repo, 'cdk'),
        commands: ['cd cdk', 'npm ci', 'npm run build', 'npx cdk synth'],
        primaryOutputDirectory: 'cdk/cdk.out',
      }),
    })

    const deploy = new DevStage(this, 'Deploy-dev')
    const deployStage = pipeline.addStage(deploy)
    deployStage.addPost(
      new CodeBuildStep('SLS Deploy', {
        commands: ['./build.sh'],
        vpc: deploy.vpc
      }),
    )
  }
}

However I am getting the following error:

Stack "MyPipelineStack" cannot consume a cross reference from stack "MyPipelineStack/Deploy-dev/S3Stack". Cross stack references are only supported for stacks deployed to the same environment or between nested stacks and their parent stack

How can I correctly import the vpc here? And if this is not possible, how do I run a codebuildstep as a separate stack which executes only after the main stack has finished?

Regular expression to allow two non-consecutive dots before “@” in the email validation

I have used the below regular expression to validate the email ids, can someone please correct this regex to allow the email ids which contain two non-consecutive dots like “[email protected]” before “@”.

regex:
var pattern = new RegExp(/^((“[w-s]+”)|^(?!..{2})[a-z0-9]|([w-]+(?:.[w-]+))|(“[w-s]+”)([w-]+(?:.[w-]+)))(@((?:[w-]+.)w[w-]{0,66}).([a-z]{2,6}(?:.[a-z]{2})?)$)|(@[?((25[0-5].|2[0-4][0-9].|1[0-9]{2}.|[0-9]{1,2}.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2}).){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})]?$)/i);

React Router v6 render component on same page

I’m trying to change some “state varibale” managed component rendering into react-routing.I am using react-router 6.3.
This is the App.js

function App() {
  return (
    <Router>
      <Header />
      <Selections />
      <Routes>
        <Route path='/:type' element={<PostMain />}>
          <Route path=':comments' index element={<Comments />} />
         </Route>
      </Routes>
    </Router>
  );
}

This is the Component

 const handleLoadComments = () => {
    if (!comments) { 
    dispatch(loadCommentsByPost(props.permalink));
    } else {
      navigate(-1);
      //navigate(`/${type}`)
      //console.log(type);
    }
}
  return (
    <div className="Post">npm 
      <div className='Post-header' >
        <p>Subbreddit: {props.subreddit_name_prefixed}</p>
        <p>{created(props.created_utc)}</p>
      </div>
      <Media post={props} />
      <div className='Post-footer-container' >
        <div className='Post-footer' >
        <div className='Post-footer-votes'>
          <img src={upVote} alt="upvote" />
          <p style={{color: "green"}} > {props.ups} -</p>
          <img src={downVote} alt='downvote' />
          <p style={{color: "red"}} > {props.downs}</p>
        </div>
        <Link to={`${props.id}`} >
        <div className='Post-footer-comments' onClick={handleLoadComments} >
          <input type="image" className='Comments-image' src={commentImg} alt='comment bubble' />
          <p>{props.num_comments}</p>
        </div>
        </Link>
      </div>
        {/* { loading && <div className='Loading-container' ><img src={Loading} alt='loading' className='Comment-loading' /></div>} */}
      </div>
      <Outlet />
        {/* {comments && <Comments comments={comments} />} */}
    </div>
  );
}

My goal would be to render the comments under the post, i did it with local state and setState before but is there a way to do it with routing?
I can see the change in the url when i click on a comment, i tried “navigate(/${type})” but not even the url changed so i used “navigate(-1)”
But the Comments component doesn’t render!
Thanks in Advance!

React ticker package giving an error “Uncaught Error: Maximum update depth exceeded”

I am using the react-ticker package inside my code as follows:

import React from "react";
import "./VideoFooter.css"
import { Button, Avatar } from "@mui/material"
import MusicNoteIcon from '@mui/icons-material/MusicNote';
import Ticker from "react-ticker";

function VideoFooter({ channel, song, likes, shares, avatarSrc }) {
    console.log(song)
    return (
        <div className="videoFooter">
            <div className="videoFooter__text">
                <Avatar src={avatarSrc} />
                <h3>{channel} . <Button>Follow</Button></h3>
            </div>
            <div className="videoFooter__ticker">
                <MusicNoteIcon className="videoFooter__icon" />
                <Ticker>
                    {({ index }) => (
                        <>
                            <h1>{song}</h1>
                        </>
                    )}
                </Ticker>
            </div>
        </div>
    )
}

export default VideoFooter

Whenever I include the Ticker component I get the error as follows:

Uncaught Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
    at checkForNestedUpdates (react-dom.development.js:27084:1)
    at scheduleUpdateOnFiber (react-dom.development.js:25266:1)
    at Object.enqueueSetState (react-dom.development.js:13234:1)
    at Ticker.Component.setState (react.development.js:354:1)
    at Ticker._this.setRect (index.js:52:1)
    at TickerElement._this.setPosition (Element.js:111:1)
    at TickerElement._this.componentDidMount (Element.js:50:1)
    at commitLayoutEffectOnFiber (react-dom.development.js:23118:1)
    at commitLayoutMountEffects_complete (react-dom.development.js:24461:1)
    at commitLayoutEffects_begin (react-dom.development.js:24447:1)

This only happens if I include Ticker component.

This is my project hierarchy:

<VideoHeader />
            <video className="videoCard__player"
                ref={videoRef}
                onClick={onVideoPress}
                src={url}
                alt="IG Reel Video"
                loop
                autoPlay
            />
            <VideoFooter 
                channel={channel}
                likes={likes}
                shares={shares}
                avatarSrc={avatarSrc}
                song={song}
            />

It contains 3 parts, VideoHeader, <video /> tag and VideoFooter component. The error is appearing in the VideoFooter component.

Kindly comment if more information is needed.

Js function is not recognize in github page

I have uploaded my local project to github and turned it into github page.

All the functions are working properly in my localhost but, when I open the app via github page (this is repo for you to see code), it shows the error on console that the function calculateAmount() is not defined. See the screenshot

I have tried pushing the code to github again a few time to make sure it is not commit error. But, the error is still the same.

I have double checked the function name and it is the same.

I have no idea what is happening.

Please help.

Three JS not rendering anything at all. It’s all a black screen

I’ve went through similar questions on this site, and I have seen all the things that are recommended. Like, camera positioning (not inside the mesh), calling the render function, setting the (ambient) light. Each and every thing I’ve found so far in the forum I’ve tried, but nothing is working.

Can anyone please look at this fiddle and guide me as to what I am doing wrong?

https://jsfiddle.net/4mxybs5h/1/

// HTML
  <main>
  <div id="threeContainer">
    hi
    <canvas #canvas id="canvas"></canvas>
  </div>
</main>

// JS
//this.animate(null);
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
boxGeometry = new THREE.BoxGeometry(2, 2, 2);
material = new THREE.MeshBasicMaterial({color: 0xff0000});
mesh = new THREE.Mesh( boxGeometry, material );
  canva = document.getElementById("canvas");
     renderer = new THREE.WebGLRenderer({antialias: true, canvas: canva });

startScene();
animate();

function startScene() {

  //let scene = new THREE.Scene();
  //let camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
  
  let light = new THREE.AmbientLight( 0xffaaff ); 
 

    scene.add( mesh );
    light.position.set(10,10,10)
    scene.add( light );
    camera.position.set(500, 500, 500);
    mesh.castShadow = true;
    mesh.receiveShadow = true;
    
    //this.renderer.setClearColor('#E5E5E5')
    renderer.setClearColor(0xEEEEEE);
    //this.renderer.setSize(window.innerWidth, window.innerHeight)
    //this.renderer.render(this.scene, this.camera)
    //this.renderer.setAnimationLoop(this.animate.bind(this))
    //document.body.appendChild(this.renderer.domElement)

    // window.addEventListener('resize', () => {
    //   this.renderer.setSize(window.innerWidth, window.innerHeight)
    //   this.camera.aspect = window.innerWidth / innerHeight
    //   this.camera.updateProjectionMatrix();
    // })
} 

function animate() {
 camera.aspect = window.innerWidth / innerHeight
    camera.updateProjectionMatrix();
    requestAnimationFrame( animate );

    mesh.rotation.x += 0.01;
    //this.mesh.rotation.y += 1;
    //document.body.appendChild(this.renderer.domElement)

    renderer.render(scene, camera);
}

I feel like it must be something small or obvious, but I am not able to be figure out. Any help is appreciated.

How to dynamically type text in Cypress

I want to enter dynamic text in cypress, so at each run, the name field will not have repeated input, for example name1, name 2…

So in the js file I would have something like

And("I enter a name", () => {
     portalPage.roleName().type("Cypress admin" + 1, { force: true })
})

Any help is appreciated.

ReactJS/MUI (v5.6.2) Dark mode toggle not updating state

I am trying to wrap my mind around this and find the breaking point for all morning but am not able to. I have only followed the official docs until now.

I need to update the theme from dark to light in a React App but the state wont change (or resets immediately)
Heres my code:

App.tsx

import React, { createContext, useMemo, useState } from 'react';
import styles from './App.module.scss';
import {createTheme,CssBaseline,PaletteMode,responsiveFontSizes,ThemeProvider,
useMediaQuery} from '@mui/material';
import { getDefaultThemeMode } from './shared/theme/default-theme-mode';
import { getDesignTokens } from './shared/theme/mui-design-tokens';
import Main from './main/Main';
import { Navigate, Route, Routes } from 'react-router-dom';
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import { OPTIONS } from './shared/i18n/translations';

export const ColorModeContext = React.createContext({
  toggleColorMode: () => {    },
});

function App() {
// THEME
const prefersDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
const [mode, setMode] = React.useState<'light' | 'dark'>('light');
React.useEffect(() => {
    setMode(prefersDarkMode ? 'dark' : 'light');
}, [prefersDarkMode]);

const colorMode = React.useMemo(
    () => ({
        toggleColorMode: () => {
            setMode((prevMode) => (prevMode === 'light' ? 'dark' : 'light'));
        },
    }),
    []
);
let theme = React.useMemo(
    () =>
        createTheme(getDesignTokens(mode)),
    [mode]
);
theme = responsiveFontSizes(theme);

return (
    <ColorModeContext.Provider value={colorMode}>
        <ThemeProvider theme={theme}>
            <div className={styles.app} style={{background: theme.palette.background.default}}>
                <CssBaseline/>
                <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"/>
                <Routes>
                    <Route path='/home' element={<Main/>}/>
                    <Route path='*' element={<Navigate to='home'/>}/>
                </Routes>
            </div>
        </ThemeProvider>
    </ColorModeContext.Provider>
);
}
export default App;

getDesignTokens Function:

const getDesignTokens = (mode: PaletteMode): ThemeOptions => ({
palette: {
    mode,
    ...(mode === 'light' ? {
        primary: {
            main: '#3c3c3c',
        },
    } : {
        primary: {
            main: '#3c3c3c',
        },
    })
}});

And finally, I am trying to update the theme from outside the App.tsx component this way:

const ThemeToggle = () => {
const theme = useTheme();
const colorMode = useContext(ColorModeContext);

return (
    <>
        <label htmlFor='theme-toggle' className={`${styles.toggleBtn} 
               ${theme.palette.mode === 'dark' ? styles.dark : ''}`}
               onClick={colorMode.toggleColorMode}>
            <input type='checkbox' id='theme-toggle' className={styles.input}/>
        </label>
    </>
)
}
export default ThemeToggle;

I must be missing something obvious but have tried everything. Anyone has done something similar?

How do I block a certain script from loading?

How would I block a URL from loading like AdBlock does?

For example https://example.com/hi.js

I’ve tried this with XMLHttpRequest, but didn’t succeed.
I would very like to do this in JavaScript. Not DevTools or some other stuff.

XMLHttpRequest.prototype.realOpen = XMLHttpRequest.prototype.open;

// Create a new function to filter out certain urls
var myOpen = function(method, url, async, user, password) {
  // Redirects the /pause to /play
  // (which will do nothing since Spotify is already playing)
  if (url.match(/doubleclick/gi)) {
    alert("a")
    url = "about:blank";
  }
  this.realOpen(method, url, async, user, password);
}

// Overwrite the original open with our modded version
XMLHttpRequest.prototype.open = myOpen;

Please DO NOT answer with “it’s not possible” or “use DevTools instead” when clearly AdBlock is capable of it.

Explain me callback and its refer to array [duplicate]

I dont understand what is callback in this example, espicially line
newArray.push(callback(this[i]));
as i got it (this[i]) is item from Array, but how does CALLBACK refer to code;

const s = [23, 65, 98, 5];

Array.prototype.myMap = function(callback) {
  const newArray = [];
  
  for(let i=0;i<this.length;i++){
      newArray.push(callback(this[i]));
  }
  return newArray;
};



const new_s = s.myMap(function(item) {
  return item * 2;
});

console.log(new_s);

From a number, create a name with incrementing letters

I have a number. From this number, I wish to create a string representing it with letters, going from A to ZZZ (there’s not limit to the number of letters in a name).

To picture it better :

1    =    A
27   =    AA
52   =    AZ
53   =    BA

...

676  =    ZZ
677  =    AAA

... And so on

I would like to make it as simple as possible. I’ll be honest, I have absolutely no idea on how to approach that.

Any tips or approaches to recommend ?

How to run Node with the –experimental-global-webcrypto command line options?

I’m using Node v18.0.0 and want to use the webcrypto API. I have multiple npm scripts reyling on the mentioned experimental flag. The following mocha script works fine

"test": "npx mocha --async-only --bail --recursive --ui tdd --require ts-node/register './test/**/*Tests.ts' --experimental-global-webcrypto",

but others don’t work, e.g.

"myscript": "npx ts-node ./path/to/file.ts --experimental-global-webcrypto",

I also tried

"myscript": "npx --experimental-global-webcrypto ts-node ./path/to/file.ts",

Running the script still comes up with the error

ReferenceError: crypto is not defined

So what is a good way to work with the experimental flag on Node v18?