Timeout – Async callback was not invoked within the 5000ms

I created this hook:

import { useQuery, gql } from '@apollo/client';

export const GET_DECIDER = gql`
  query GetDecider($name: [String]!) {
    deciders(names: $name) {
      decision
      name
      value
    }
  }
`;

export const useDecider = (name) => {
  const { loading, data } = useQuery(GET_DECIDER, { variables: { name } });
  console.log('loading:', loading);
  console.log('data:', data);
  return { enabled: data?.deciders[0]?.decision, loading };
};

Im trying to test it with react testing library:

const getMock = (decision) => [
  {
    request: {
      query: GET_DECIDER,
      variables: { name: 'FAKE_DECIDER' },
    },
    result: {
      data: {
        deciders: [{ decision }],
      },
    },
  },
];

const FakeComponent = () => {
  const { enabled, loading } = useDecider('FAKE_DECIDER');

  if (loading) return <div>loading</div>;

  console.log('DEBUG-enabled:', enabled);

  return <div>{enabled ? 'isEnabled' : 'isDisabled'}</div>;
};


// Test 
import React from 'react';
import { render, screen, cleanup, act } from '@testing-library/react';
import '@testing-library/jest-dom';
import { MockedProvider } from '@apollo/client/testing';
import { useDecider, GET_DECIDER } from './useDecider';


describe('useDecider', () => {
  afterEach(() => {
    cleanup();
  });

  it('when no decider provided - should return false', async () => {
    render(<MockedProvider mocks={getMock(false)}>
             <FakeComponent />
           </MockedProvider>
          );
    expect(screen.getByText('loading')).toBeTruthy();

    act(() => new Promise((done) => setTimeout(done, ms)))

    const result = screen.findByText('isDisabled');
    expect(result).toBeInTheDocument();
  });
});

I keep getting this error:

Timeout – Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Timeout – Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error:

Which regex modifiers are used with regex.test(string)?

It seems there are 7 JS RegExp modifiers:

  • d indices
  • g global
  • i case
  • m multiline
  • s dotall
  • u unicode
  • y sticky

Which of the above are applicable for doing regex.test(string) ? For example, since it just tests whether the string contains one or more matches or not, isn’t the g flag N/A for it? In other words:

/h/.test("h h h h") === /h/g.test("h h h h")

i, m, s, and u seem like they would be applicable, but I’m also not certain about d (I think not since it relates to indices and this just returns a bool?) or y (I think yes). Which modifiers make sense for the .test() method?

created pdf using html2cavas and jsPDF get the width right only on desktop?

I have the following code the issue the implementation is like the following
generated items go in to a div that has a fixed width of 1100, using mui btw, when creating the pdf on desktop the results are as they should be how ever when creating the pdf from mobile phone the width of the created pdf is small I could say only 400 of the 1100 div is showing, when creating from chrome responsive it is working as it should, how to what is the right options to make jspdf created a pdf with the right width I think jsPdf is confusing iphone screen size ?

html2canvas(
      document.getElementById('pdfItems')!,
      {
        onclone: function (clonedDoc) {
          // none ! hidden show !!
          clonedDoc.getElementById('pdfItems')!.style.display = 'flex';
        },
        // TO INCREASE QUALITY !!!!!!!!!!
        scale: /*3*/ 2,
        //width: document.getElementById('pdfItems')!.clientWidth,
      }
      /* {
      allowTaint: false,
      width: window.innerWidth,
      height: window.innerHeight,
      scrollX: window.pageXOffset,
      scrollY: window.pageYOffset,
      x: window.pageXOffset,
      y: window.pageYOffset,
      imageTimeout: 1500,
    }*/
    ).then((canvas) => {
      //document.body.appendChild(canvas); // if you want see your screenshot in body.
      const imgData = canvas.toDataURL('image/png');

      //A4
      var imgWidth = 210;
      //var pageHeight = 295;
      var imgHeight = (canvas.height * imgWidth) / canvas.width;
      //var heightLeft = imgHeight;
      // A4
      var doc = new jsPDF('p', 'mm' /*pt*/, 'a4', true);
    
      doc.addPage([imgWidth, imgHeight]);
      doc.addImage(imgData, 'PNG', 0,0 , imgWidth, imgHeight);
      doc.deletePage(1);
      const fileName = 'test'
      doc.save(`${fileName}.pdf`);
    });
  };
  
  
  // PDF DIV STYLE 
  <div
      id='pdfItems'
      style={{
        display: 'flex',
        flexDirection: 'column',
        margin: 0,
        padding: 0,
        textAlign: 'center',
        width: 1100,
       
      
      }}
    >
    // Itemes
    </div>

How can I get the oauth_token data from my backend when it’s sent via a http response to my frontend?

I am using react-twitter-auth as part of my OAuth 1.0a user authentication flow on my site. My goal is to authenticate a user and then access their username. So far I have a bunch of code I borrowed from a website. There is client side code and backend code.

The client starts the authentication flow, sending a request to http://localhost:4000/api/v1/auth/twitter/reverse. There, I see from a console.log statement that I have the oauth_token value that I will need later for step 3 of the so-called “3 legged auth” authentication flow that I am going through.

Here is the server route I am hitting:

router.route("/auth/twitter/reverse").post(function (req, res) {
  console.log(72);
  request.post(
    {
      url: "https://api.twitter.com/oauth/request_token",
      oauth: {
        oauth_callback: "http://localhost:3000/",
        consumer_key: twitterConfig.consumerKey,
        consumer_secret: twitterConfig.consumerSecret,
      },
    },
    function (err, r, body) {
      if (err) {
        console.log(err, 83);
        return res.send(500, { message: e.message });
      }

      var jsonStr =
        '{ "' + body.replace(/&/g, '", "').replace(/=/g, '": "') + '"}';
      console.log(jsonStr, 88);
      res.send(JSON.parse(jsonStr));
    }
  );
});

I get values such as:

{ "oauth_token": "HnQ1SgAAAAAAAABco", "oauth_token_secret": "y1qeyxZeiCEWqkKz9y", "oauth_callback_confirmed": "true"} 88

Some characters have been deleted in case that isn’t data I should be exposing. Anyway:

I need that “oauth_token” value to make it to my client. Why? Because I’m getting a pin in the 3 legged auth part, and so I need both values to arrive on my server at the same time.

If i wasn’t using the react-twitter-auth library, I would have no problem here, because I would just be sending a http request via fetch, and so I would have a .then() block to show me what the value of res.send(JSON.parse(jsonStr)); is on the frontend. But I don’t have that, nothing is there to listen for the res.send() part. How can I listen for it?

Thanks

edit: I am critical of this library because it doesn’t account for what happens with the PIN based strategy for 3 legged auth.

Online piano works but I want to eliminate static sound

This code works(just copy and paste the sketch.js code below into the online p5.js editor: https://editor.p5js.org/ ) but every note plays emits a static-sound when the synth turns on. Can anyone suggest a way to eliminate the static sound? Maybe leave the synth running all the time and switching frequencies as notes are needed? Thank you.(to run this on your own editor you need p5.js and p5.sound.min.js files in your project folder.)

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <script src="p5.js"></script>
    <script src="p5.sound.min.js"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
    <meta charset="utf-8">
</head>
<body>
    <script src="sketch.js"></script>
</body>
</html>

style.CSS

html, body {
  margin: 0;
  padding: 0;
}
canvas {
  display: block;
}

sketch.js

// Removing Objects from Arrays
// Code! Programming with p5.js
// The Coding Train / Daniel Shiffman
// https://thecodingtrain.com/beginners/p5js/7.5-removing-objects-from-array.html
// https://youtu.be/tA_ZgruFF9k

// Main Sketch: https://editor.p5js.org/codingtrain/sketches/smC4Jedi
// Trail Sketch: https://editor.p5js.org/codingtrain/sketches/9Ve9S6Mx
var wave;
var playing = false;
let bubbles = [];
let time = .25;
let t = 1;
let waves = [];
let freqs = [392, 440, 392, 494, 523, 523, 330, 370, 392, 494, 587, 294, 294, 392, 440, 294, 330, 294, 294, 370, 392, 294, 330, 294, 294];
var freq;
let xs = [410, 500, 410, 600, 700, 700, 200, 350, 410, 700, 800, 100, 100, 410, 500, 100, 200, 100, 100, 350, 410, 100, 200, 100, 100];
let ys = [0, 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000, 1050, 1100, 1150, 1200, ];

function setup() {
    createCanvas(1600, 2000);
    wave = new p5.Oscillator();


    for (let i = 0; i < 25; i++) {
        let x = xs[i];
        let y = ys[i];
        let r = 24;
        let b = new Bubble(x, y, r);
        bubbles.push(b);
    }
}

function mousePressed() {
    for (let i = bubbles.length - 1; i >= 0; i--) {
        if (bubbles[i].contains(mouseX, mouseY)) {
            //bubbles.splice(i, 1);
            wave.setType('sine');
            wave.start();
            wave.freq(freqs[i]);
            wave.amp(1);
            playing = true;
            wave.stop(time);
            waves.push(wave);
        }
    }
    console.log(waves);
    console.log(bubbles);
}

function draw() {
    background(0);
    strokeWeight(5);
    //stroke(255,0,255);
    fill(255, 255, 255);
    rect(60, 1400, 90, 180);
    rect(160, 1400, 90, 180);
    rect(260, 1400, 90, 180);
    rect(360, 1400, 90, 180);
    rect(460, 1400, 90, 180);
    rect(560, 1400, 90, 180);
    rect(660, 1400, 90, 180);
    rect(760, 1400, 90, 180);
    rect(860, 1400, 90, 180);
    stroke(0, 0, 255);
    fill(0, 0, 0);
    rect(10, 1300, 82, 180);
    rect(110, 1300, 82, 180);
    rect(310, 1300, 82, 180);
    rect(410, 1300, 82, 180);
    rect(510, 1300, 82, 180);
    rect(710, 1300, 82, 180);
    rect(810, 1300, 82, 180);


    for (let i = 0; i < bubbles.length; i++) {
        if (bubbles[i].contains(mouseX, mouseY)) {
            bubbles[i].changeColor('magenta');
        } else {
            bubbles[i].changeColor(0);
        }

        bubbles[i].move();
        bubbles[i].show();
    }
}

class Bubble {
    constructor(x, y, r) {
        this.x = x;
        this.y = y;
        this.r = r;
        this.brightness = 0;
    }

    changeColor(bright) {
        color = bright;
    }

    contains(px, py) {
        let d = dist(px, py, this.x, this.y);
        if (d < this.r) {
            return true;
        } else {
            return false;
        }
    }

    move() {
        this.x = this.x;
        this.y = this.y + 1.95;
    }

    show() {
        stroke(255);
        strokeWeight(4);
        fill(color);
        ellipse(this.x, this.y, this.r * 2);
    }
}

Prod Server not receiving HTTP requests from Prod Client

First a quick preface I think may be helpful: I am new to splitting my client and server into separate web apps. My previous apps have all had my server.js at the root level in my directory and the client (typically a create-react-app) in a /client folder.

What I wanted to do: Host a single express.js server on the web which multiple other web applications could make requests to.

I did the first part using an express server and aws elastic beanstalk.

server.js

require('dotenv').config()
const express = require('express');
const app = express();
const cors = require('cors');
const PORT = process.env.PORT || 5000;
const Mongoose = require('mongoose');
const { Sequelize } = require("sequelize");

//ROUTES
const APIUser = require('./routes/api/mongo/api-user');
more routes...

//INITIATE DATA MAPPING CONNECTIONS START
Mongoose.connect(
    process.env.MONGO_URI,
    { useNewUrlParser: true, useUnifiedTopology: true },
    console.log("connected to MongoDB")
);

const Postgres = new Sequelize(process.env.PG_CONN_STRING);

try {
    Postgres.authenticate()
        .then(console.log("connected to Postgres"));
} catch {
    console.log("Postgres connection failed")
}
//INITIATE DATA MAPPING CONNECTIONS END

//middleware
app.use(cors())
more middleware...

//home route
app.get('/api', (req, res) => {
    console.log('RECEIVED REQ to [production]/api/')
    res.status(200).send('models api home').end();
})

//all other routes
app.use('/api/user', APIUser);
more route definitions...

//launch
app.listen(PORT, () => console.log(`listening on port ${PORT}`));

The log file for successful boot up on aws: https://imgur.com/vLgdaxK

At first glance it seemed to work as my postman requests were working. Status 200 with appropriate response: https://imgur.com/VH4eHzH

Next I tested this from one of my actual clients in localhost. Here is one of my react client’s api util files where axios calls are made to the backend:

import { PROXY_URL } from '../../config';
import { axiosInstance } from '../util';

const axiosProxy = axios.create({baseURL: PROXY_URL}); //this was the most reliable way I found to proxy requests to the server

export const setAuthToken = () => {
    const route = "/api/authorization/new-token";
    console.log("SENDING REQ TO: " + PROXY_URL + route)

    return axiosProxy.post(route)
}

export const authorize = clientsecret => {
    const route = "/api/authorization/authorize-survey-analytics-client";
    console.log("SENDING REQ TO: " + PROXY_URL + route)
    
    return axiosProxy.post(route, { clientsecret })
}

Once again it worked… or rather I eventually got it to work: https://imgur.com/c2rPuoc

So I figured all was well now but when I tried using the live version of the client the request failed somewhere.

in summary the live api works when requests are made from postman or localhost but doesn’t respond when requests are made from a live client https://imgur.com/kOk2RWf

I have confirmed that the requests made from the live client do not make it to the live server (by making requests from a live client and then checking the aws live server logs).

I am not receiving any Cors or Cross-Origin-Access errors and the requests from the live client to the live server don’t throw any loud errors, I just eventually get a net::ERR_CONNECTION_TIMED_OUT. Any ideas where I can look for issues or is there more code I could share?

Thank you!

Page background Images are not changing on scroll

I am trying to change the background image when the user scrolls the page. The code I have written is not working. I am running this code on a WordPress website. Below Is my code.

 <script type="text/javascript">
jQuery(document).ready(function( jQuery ) {
    jQuery(window).on('scroll touchmove', function() {

        if (jQuery(document).scrollTop() >= jQuery('#one').position().top) {
            jQuery('body').css('background', jQuery('#one').attr('data-src'));
        }

        if (jQuery(document).scrollTop() > jQuery('#two').position().top) {
            jQuery('body').css('background', jQuery('#two').attr('data-src'));
        }

        if (jQuery(document).scrollTop() > jQuery('#three').position().top) {
            jQuery('body').css('background', jQuery('#three').attr('data-src'));
        }

        if (jQuery(document).scrollTop() > jQuery('#four').position().top) {
            jQuery('body').css('background', jQuery('#four').attr('data-src'));
        }

        if (jQuery(document).scrollTop() > jQuery('#five').position().top) {
            jQuery('body').css('background', jQuery('#five').attr('data-src'));
        }

    });
})(jQuery);
</script>

Here I have five sections and I gave an ID to my section as I define on the code. Below is how I added the ‘data-src’ attribute to the particular section through the elementor data attribute option.

data-src|http://www.kasundev.xyz/design/wp-content/uploads/2022/02/WhatsApp-Image-2022-02-10-at-11.00.38.jpeg

This is the CSS I am using when the page loads first. This code applies to the whole page.

body {
  background:#333333;
  transition: all 1200ms ease-out;
  will-change: background;
}

My question is nothing is changing when I scroll. Instead of an image If I give a color like this
data-color|#000000 will change.

How I change my background image when scrolling. Can anyone help me out?

Thanks

generating numbers using loops (no arrays)

How can I generate 500 Numbers between 1 and 50 using javascript and without using arrays only loops (for)? I have written the below code but it’s not generating any number

    for (let i = 0; i < 500, i++){
    var temp = Math.floor((Math.random() * 50) + 1);
    }

What is the best way to pass an object’s data from one page to another in Ionic?

I am trying to pass user data from my main page component to a details page component. I am currently mapping the user data in to a custom Ionic Component. When the custom component is clicked on in the main page, I need it to send the user data to the detail page and render the detail page using the data passed in from the main page.

Main.tsx:

const userAPILink: string = "https://randomuser.me/api/";
const usersToRender: number = 5;

const Main: React.FC<RouteComponentProps> = ({ history }) => {
  interface IUser {
    data: {
      name: string;
      email: string;
      icon: string;
      country: string;
    };
  }
  const [userList, setUserList] = useState<IUser[]>([]);

  useEffect(() => {
    for (let i = 0; i < usersToRender; ++i) {
      (async () => {
        const res = await axios.get(userAPILink);
        let tempUser: IUser = {
          data: {
            name: `${res.data.results[0].name.first} ${res.data.results[0].name.last}`,
            email: `${res.data.results[0].email}`,
            icon: `${res.data.results[0].picture.thumbnail}`,
            country: `${res.data.results[0].location.country}`,
          },
        };
        setUserList((userList) => {
          return [...userList, tempUser];
        });
      })();
    }
  }, []);

  return (
    <IonPage>
      <IonHeader>
        <IonToolbar mode="ios">
          <IonIcon slot="end" ios={optionsOutline} />
          <IonButtons slot="start">
            <IonMenuButton />
          </IonButtons>
          <IonTitle className="ionTextCenter">LOGO</IonTitle>
        </IonToolbar>
      </IonHeader>

      <IonContent fullscreen className="ionPadding">
        <IonHeader collapse="condense"></IonHeader>
        <IonSegment>
          <IonSegmentButton>Tab 1</IonSegmentButton>
          <IonSegmentButton>Tab 2</IonSegmentButton>
          <IonSegmentButton>Tab 3</IonSegmentButton>
        </IonSegment>
        <IonList>
          {userList.map((user, index) => {
            return (
              <IonItem
                key={index}
                onClick={(e) => {
                  e.preventDefault();
                  history.push({
                    pathname: `/detail/${user.data.name}`,
                    state: [
                      user.data.name,
                      user.data.email,
                      user.data.icon,
                      user.data.country,
                    ],
                  });
                }}
              >
                <UserCard id={index} data={user.data}></UserCard>
              </IonItem>
            );
          })}
        </IonList>
      </IonContent>
    </IonPage>
  );
};

export default Main;

UserCard.tsx

type UserCardProps = {
  id: number,
  data: {
    name: string;
    icon: string;
    email: string;
    country: string;
  };
};

class UserCard extends React.Component<UserCardProps> {
  render() {
    return (
      <IonCard
        // routerLink={`detail/${this.props.data.name}`}
        id={this.props.data.name}
      >
        <IonCardHeader className="card-header">
          <IonGrid>
            <IonRow>
              <IonCol size="3">
                <IonAvatar>
                  <img src={this.props.data.icon} />
                </IonAvatar>
              </IonCol>
              <IonCol size="9">
                <IonCardTitle>{this.props.data.name}</IonCardTitle>
                <IonCardSubtitle>{this.props.data.email}</IonCardSubtitle>
              </IonCol>
            </IonRow>
          </IonGrid>
        </IonCardHeader>
        <IonCardContent>
          <IonText>
            <IonLabel>{this.props.data.country}</IonLabel>
          </IonText>
          <IonImg className="character-img"></IonImg>
          Lorem Ipsum is simply dummy text of the printing and typesetting
          industry. Lorem Ipsum has been the industry's standard dummy text ever
          since the 1500s, when an unknown printer took a galley of type and
          scrambled it to make a type specimen book.
        </IonCardContent>
      </IonCard>
    );
  }
}

export default ({
  id,
  data,
}:

{
  id: number
  data: {
    name: string;
    icon: string;
    email: string;
    country: string;
  };
}) => (
  <UserCard
    id={id}
    data={data}
  ></UserCard>
);

Detail.tsx

interface DetailProps extends RouteComponentProps<{
  name: string;
  country: string;
  email: string;
  icon: string;
}> {}

const Detail: React.FC <DetailProps> = ({match, history}) => {
  return (
    <IonPage>
      <DetailComponent id={3} name="Bob" email="email" country="canada" icon="icon" />
    </IonPage>
  );
};

export default Detail;

DetailComponent.tsx

type DetailItemProps = {
  id: number;
  name: string;
  icon: string;
  email: string;
  country: string;
};

class DetailItem extends React.Component<DetailItemProps> {
  render() {
    return (
      <IonHeader>
        <IonToolbar mode="ios">
          <IonIcon slot="end" ios={optionsOutline} />
          <IonButtons slot="start">
            <IonMenuButton />
          </IonButtons>
          <IonTitle className="ionTextCenter">{this.props.name}</IonTitle>
        </IonToolbar>
      </IonHeader>
    );
  }
}

export default ({
  id,
  name,
  icon,
  email,
  country,
}: {
  id: number;
  name: string;
  icon: string;
  email: string;
  country: string;
}) => (
  <DetailItem
    id={id}
    name={name}
    icon={icon}
    email={email}
    country={country}
  ></DetailItem>
);

Modifying an existing CodePen Galaxy affect (Zoom out to Zoom In)

so recently I have found this awesome galaxy effect on codepen:
https://codepen.io/zeztron/pen/MPNxxR

I tried to modify the JavaScript and couldn’t figure out a way to change it so instead of it feeling like Zooming out, making it to feel like Zooming in.

Can anyone help? Thank you!!

Here are the codes:

<body>
  <canvas id="canvas"></canvas>
</body>
body {
    background: black;
    height: 100%;
    min-height: 100%;
}


#canvas {
    height: 100%;
    width: 100%;
    position: fixed;
    top: 0;
    left: 0;
    opacity: 0;
}
var Space = {
  init: function(){
    var self = this;
    this.config = {
      perspective: 3,
      star_color: '255, 255, 255',
      speed: 1,
      stars_count: 2
    };
    this.canvas = document.getElementById('canvas');
    this.context = canvas.getContext('2d');
    this.start();
    window.onresize = function(){
      self.start();
    };
  },

  start: function(){
    var self = this;

    this.canvas.width  = this.canvas.offsetWidth;
    this.canvas.height = this.canvas.offsetHeight;
    this.canvas_center_x = this.canvas.width / 2;
    this.canvas_center_y = this.canvas.height / 2;

    this.stars_count = this.canvas.width / this.config.stars_count;
    this.focal_length = this.canvas.width / this.config.perspective;
    this.speed = this.config.speed * this.canvas.width / 2000;

    this.stars = [];

    for(i = 0; i < this.stars_count; i++){
      this.stars.push({
        x: Math.random() * this.canvas.width,
        y: Math.random() * this.canvas.height,
        z: Math.random() * this.canvas.width,
      });
    }

    window.cancelAnimationFrame(this.animation_frame);
    this.canvas.style.opacity = 1;

    this.cow = new Image();
    this.cow.src = 'https://gallery.yopriceville.com/var/resizes/Free-Clipart-Pictures/Fast-Food-PNG-Clipart/Hamburger_PNG_Vector_Picture.png?m=1507172108';
    this.cow.onload = function(){
      self.render();
    }
  },

  render: function(){
    var self = this;
    this.animation_frame = window.requestAnimationFrame(function(){
      self.render();
    });
    this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
    for(var i = 0, length = this.stars.length; i < length; i += 1){
      var star = this.stars[i];
      star.z -= this.speed;
      if(star.z <= 0) {
        this.stars[i] = {
          x: Math.random() * this.canvas.width,
          y: Math.random() * this.canvas.height,
          z: this.canvas.width,
        };
      }

      var star_x = (star.x - this.canvas_center_x) * (this.focal_length / star.z) + this.canvas_center_x;
      var star_y = (star.y - this.canvas_center_y) * (this.focal_length / star.z) + this.canvas_center_y;
      var star_radius  = Math.max(0, 1.4 * (this.focal_length / star.z) / 2);
      var star_opacity = 1.2 - star.z / this.canvas.width;
      var cow_width = Math.max(0.1, 100 * (this.focal_length / star.z) / 2);

      if(star.cow){
        this.context.save();
        this.context.translate((star_x-cow_width)+(cow_width/2), (star_y-cow_width)+(cow_width/2));
        this.context.rotate(star.z/star.rotation_speed);
        this.context.translate(-((star_x-cow_width)+(cow_width/2)), -((star_y-cow_width)+(cow_width/2)));
        this.context.globalAlpha = star_opacity;
        this.context.drawImage(this.cow, 0, 0, this.cow.width, this.cow.width, star_x-cow_width, star_y-cow_width, cow_width, cow_width);
        this.context.restore();
      } else {
        this.context.fillStyle = 'rgba(' + this.config.star_color + ',' + star_opacity + ')';
        this.context.beginPath();
        this.context.arc(star_x, star_y, star_radius, 0, Math.PI * 2);
        this.context.fill();
      }
    }
  }
};

window.onload = function(){
  Space.init();
};

Does JavaScript ‘Set’ work for HTMLStyleElement objects?

In my website there are some duplicated <Style> elements in DOM. I am trying to use a Set in JavaScript to do some de-duplication for these elements. The code to generate non-dup elements is something like:

const CSSCache = new Set<HTMLStyleElement>();
const styles = document.getElementsByTagName('style');
for (let i = 0; i < styles.length; i++) {
   CSSCache.add(styles[i] as HTMLStyleElement);
}

I am wondering if the JavaScript Set able to unique-fy these HTMLStyleElement objects.

Also, some of these elelment doesn’t have any content, e.g. <style></style> but they have rules in element.sheet.cssRules inserted with insertRule (https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule). I am wondering if Set works for these types of Style as well.

bootstrap not showing dropdown

I have a bootstrap form that I have added a dropdown list. When I click on the dropdown I see the list, but when I click on it doesn’t show as selected it still shows “select Domain” all the time. I found this link

https://www.codeply.com/go/pTWA3jYWEv/bootstrap-bootstrap-dropdown-selected-value

I have modified it, but I am missing something cause it is not working for me.

<div class="form-group">
<div class="dropdown">
  <button class="btn btn-primary btn-user btn-block dropdown-toggle" type="button"
          id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    Select Domain
      <span class="caret"></span>
  </button>
  <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
    <a class="dropdown-item">Corp</a>
    <a class="dropdown-item">Domain2</a>
    <a class="dropdown-item">Domain3</a>
    <a class="dropdown-item">Local</a>
  </div>
</div>
</div>


<script type="text/javascript">
$(".dropdown-menu li a").click(function(){
  var selText = $(this).text();
  $(this).parents('.dropdown').find('.btn btn-primary btn-user btn-block dropdown-toggle').html(selText+' <span class="caret"></span>');
});
</script>