This “undefined” error has been driving me crazy! Can you find the error? [duplicate]

The code below references a td object with id “00”. I’m simply trying to get the the background color (which is currently expected to be “white”). I’ve declared the background in CSS as “white”. I can’t figure out how the statement below would result in an error. Can you?

console.log(document.getElementById("00").style.backgroundColor);

Length issue with Javascript carry-forward choices from multiple questions using Qualtrics?

I am using a matrix drag and drop on Qualtrics to ask respondents to sort 46 statements into the categories: agree less, neutral, and agree more (QID1).

QID1

In QID6 I ask them to sort the statements carried forward from the category agree less into -5 to 0.

QID6

Then in QID7 I ask them to sort the statements carried forward from the category agree more into 0 to 5.

QID7

In QID4 I show them how they sorted the statements (from -5 to 5) from QID6 and QID7. However, I wanted to combine how they sorted the responses in QID1, QID6, and QID7 specifically for the neutral and 0 responses. However, I have been unsuccessful at getting all the statements to carry forward. If only one statement was put into each of the categories of neutral (in QID1), category 0 in QID6, and category 0 in QID7 then those three statements appear in QID4.(QID1selection, QID6selection, QID7selection, result)

However, if more than one statement is placed into any of those categories (neutral in QID1 or 0 in QID6 and 7), then none of them appear in QID4. This does not seem to be an issue for the statements selected in the other categories (-5,-4,-3,-2,-1,1,2,3,4,5). Is this an issue with length or is concat the incorrect function to use? I am not familiar with javascript at all, so I am having a hard time figuring out what is the issue.

Below is the Javascript function I am using (based on this discussion post: https://community.qualtrics.com/XMcommunity/discussion/14728/carry-forward-response-into-drag-drop-box)

    Qualtrics.SurveyEngine.addOnReady(function () {
    let ques = this;
    //let a1 = "${q://QID1/ChoiceGroup/SelectedChoicesForAnswer/1}";
    let a2 = "${q://QID1/ChoiceGroup/SelectedChoicesForAnswer/2}"; //this is neutral
    //let a3 = "${q://QID1/ChoiceGroup/SelectedChoicesForAnswer/3}";
    let b1 = "${q://QID6/ChoiceGroup/SelectedChoicesForAnswer/1}";
    let b2 = "${q://QID6/ChoiceGroup/SelectedChoicesForAnswer/2}";
    let b3 = "${q://QID6/ChoiceGroup/SelectedChoicesForAnswer/3}";
    let b4 = "${q://QID6/ChoiceGroup/SelectedChoicesForAnswer/4}";
    let b5 = "${q://QID6/ChoiceGroup/SelectedChoicesForAnswer/5}";
    let b6 = "${q://QID6/ChoiceGroup/SelectedChoicesForAnswer/6}"; //this is 0
    let c1 = "${q://QID7/ChoiceGroup/SelectedChoicesForAnswer/1}"; //this is 0
    let c2 = "${q://QID7/ChoiceGroup/SelectedChoicesForAnswer/2}";
    let c3 = "${q://QID7/ChoiceGroup/SelectedChoicesForAnswer/3}";
    let c4 = "${q://QID7/ChoiceGroup/SelectedChoicesForAnswer/4}";
    let c5 = "${q://QID7/ChoiceGroup/SelectedChoicesForAnswer/5}";
    let c6 = "${q://QID7/ChoiceGroup/SelectedChoicesForAnswer/6}";
    
    let d1 = a2.concat(b6,c1); //this should combine all the statements selected for QID1 (ans2), QID6 (ans6), and QID7 (ans1)
    
    let choice_text = ques.getChoiceContainer().innerText.split(/n/gm);
    let all_choices = ques.getChoices();
    let all_answers = ques.getAnswers();
    
    for (let i = 0; i < choice_text.length; i++) {
        let set_choice= -1
        switch (true) {
            case b1.includes(choice_text[i]):
                set_choice = all_answers[0];
                break;
            case b2.includes(choice_text[i]):
                set_choice = all_answers[1];
                break;
            case b3.includes(choice_text[i]):
                set_choice = all_answers[2];
                break;
             case b4.includes(choice_text[i]):
                set_choice = all_answers[3];
                break;
             case b5.includes(choice_text[i]):
                set_choice = all_answers[4];
                break;
            case d1.includes(choice_text[i]): //this should show all the statements selected for QID1 (ans2), QID6 (ans6), and QID7 (ans1)
                set_choice = all_answers[5];
                break;  
            case c2.includes(choice_text[i]):
                set_choice = all_answers[6];
                break;
            case c3.includes(choice_text[i]):
                set_choice = all_answers[7];
                break;
             case c4.includes(choice_text[i]):
                set_choice = all_answers[8];
                break;
             case c5.includes(choice_text[i]):
                set_choice = all_answers[9];
                break;
            case c6.includes(choice_text[i]):
                set_choice = all_answers[10];
                break;
        }
        ques.setChoiceValue(all_choices[i], set_choice, true);
    }
});

I would appreciate it if anyone can point me to the right direction or to any helpful resources.

Automatic scroll to the current song in the playlist

I have a div with vertical scrollbar. It contains a list of 20 songs, with variable length titles. At any given moment, the div can display only 7 songs.

I am able to highlight the song being played in the div, however, it remains hidden under the div, as moving to the next song refreshes the page and the div scroll to the top.

Q. How do I scroll the div such that the current song (and preferably prev and next) always remain in the view?

Any points are greatly appreciated!

JS using dot, string notation to map nested and assign errors

Ok, this is an odd one that I just can’t seem to get right.

I have a large, complex object to send to a backend. After various attempts, I tried using Joi to validate the schema, and I like it, but passing the errors back to the inputs is a nightmare

The body is subdivided into 5 sections, with each subsection containing between 10-30 fields, some of which are string[], interface[], number[], or general nested interfaces.

I tried writing my own custom validation and the complexity grew outta control.

(I know some of you are thinking “your schema is too complex” and you’re right, but its not something I can change right now. Clients blah blah.)

The problem: Joi.validate(myBody) gives me a bunch of errors in the following format:

[ // <- error.details
  {
    context: {},
    message: "X is not allowed to be empty",
    path:["path","to","property"], // <- this is the key
    type: ""
  }
]

How can I map error.details to create a new validation object that I can then use for the form items themselves.

For example:

path = ["path","to","property"] // -> map over to create

let newObj = {
  path:{
    to: {
       property: ""
    }
}
}

I hope this make sense.

I want to take an array of vallidation errors, and turn them into a validation object that matches the initial object

Yarn local node modules checksum verification

I came across the following statement:

“Yarn uses checksums to verify the integrity of every installed package before its code is executed.”

I am not able to find details however on how this actually works.

As a test, I have modified the integrity fields in yarn.lock to random values and yarn seems not to be performing any checks on them.

Does that mean that it’s pulling those values from the npm repository every time automatically?

Google analytics data in react application

I,m working on an admin dashboard of a react web application and I want to use google analytics to track my web app data. I know how to do it in google analytics but actually, I want to get the data from google analytics to my website admin dashboard.

I’ve been looking for that in a lot of resources but I couldn’t find a good information resource. Here I want to track the data using google analytics ad display it inside my website admin dashboard.

Uncaught TypeError: signinUsingGoogle is not a function

I’m trying to add firebase authentication to my website. but having an error. I’m trying to solve this last three days. below I’m shared my code and error. i use react router dom, firebase authentication system with react js. when I click sign in with google button, it show hello in console, that’s right. but after it, I’m facing this error.

the error is,
error screenshot

in useFirebase.js file, I write below code,

import React, { useEffect, useState } from 'react';
import { getAuth, GoogleAuthProvider, onAuthStateChanged, signInWithPopup } from "firebase/auth";
import initializeConfig from '../Firebase/Firebase.init';

initializeConfig();

const useFirebase = () => {
    const auth = getAuth();
    const provider = new GoogleAuthProvider();
    const [user, setUser] = useState({});

    

    const signinUsingGoogle = () => {
        return signInWithPopup(auth, provider)
    }



    useEffect(() => {
        const unsubscribed = onAuthStateChanged(auth, user => {
            if (user) {
                setUser(user)
            }
            else {
                setUser({})
            }
        });
        return () => unsubscribed;
    }, [])



    const signOut = () => {
        signOut(auth)
            .then(() => {
            
        })
    }
    return (
        user,
        signinUsingGoogle,
        signOut

    );
};

export default useFirebase;

and in signin.js file, I write the below code,

import React from "react";
import { Button } from "react-bootstrap";
import { useLocation, useNavigate } from "react-router-dom";
import useAuth from "../../Hooks/useAuth";
import "./Signin.css";

const Signin = () => {
    const { signinUsingGoogle } = useAuth();
    const navigate = useNavigate();
    const location = useLocation();
    const navigateUrl = location?.state?.from || "/home";
    const GoogleSignin = () => {
        console.log("hello");
        signinUsingGoogle()
            .then((result) => {
                navigate(navigateUrl);
            })
            .finally(() => {});
    };

    return (
        <div className="signin d-flex justify-content-center align-items-center mx-auto">
            <div className="signin-card p-3 m-3">
                <img
                    src="https://c.tenor.com/9Xf0d7BGQ5oAAAAC/computer-log-in.gif"
                    alt="img not found"
                    width="360px"
                />
                <div className="d-grid gap-2 mt-3 text-center">
                    <Button variant="primary" size="lg" onClick={GoogleSignin}>
                        <h5>
                            <i className="fab fa-google-plus"></i> Google
                        </h5>
                    </Button>
                    <Button variant="secondary" size="lg" className="github">
                        <h5>
                            <i className="fab fa-github"></i> Github
                        </h5>
                    </Button>
                    <Button variant="secondary" size="lg" className="facebook">
                        <h5>
                            <i className="fa-brands fa-facebook"></i> Facebook
                        </h5>
                    </Button>
                </div>
            </div>
        </div>
    );
};

export default Signin;

I’m confused with declaring a let variable , closure, functions and lexical environment in JS [duplicate]

My prof provided me with the following code:

function makeCounter() {
  let count = 0;

  return function() {
    return count++;
  };
}

let counter = makeCounter();

alert( counter() ); // 0
alert( counter() ); // 1
alert( counter() ); // 2

I know that counter() is being called. But I don’t see any function named as counter. Could someone shred some lights?

Display checkmark svg on top of theme on click of particular theme

I want to display themes ( can be image or div ) and when user selects particular theme checkmark-inside-circle svg in overlay should be displayed on top but transparent so that theme below should be visible (dummy example). Considering theme as mat-radio-button , below is code

HTML

<div class="text-container" name="themeList">
   <mat-radio-group formControlName="theme" aria-label="Select a theme" class="theme-radio-group">
       <mat-radio-button
         *ngFor="let op of themeId; let i = index"
          name="themeList"
          class="theme-radio"
          [value]="i"
          (click)="selectThemeOnClick(i)">

          <div *ngIf="i == 0; else elseBlock">Theme {{i + 1}} (Default) </div>

          <ng-template #elseBlock>Theme {{i + 1}}</ng-template>
          <div #radio [attr.id]=i class="theme-radio-div themeDiv"></div>

        </mat-radio-button>
    </mat-radio-group>
</div>

In above code getting data from array and adding theme name ( default for 1st ) and adding themeDiv with it’s ID.
Tried to display checkmark for 1st theme but was not able to do that ( [checked]=”i === 0″ inside mat-radio-button , didn’t worked )

CSS

:host ::ng-deep .mat-radio-container {
  display: none;
}

.theme-container {
  .text-container {
    .theme-radio-group {
      display: grid;
      grid-gap: 20px;
      grid-template-columns: repeat(3, 226px);
      align-content: space-around;
      justify-content: space-between;

  .themeDiv {
    content: url('example.jpg');
    width: 226px;
    height: 142px;
  }

  .theme-radio-check-mark {
    width:24px;
    height: 24px;
    content: url('check-mark-in-circle.svg');
    opacity: 0.5;
    position:relative;
    left:100px;
    top:60px;
  }
}
 }
}

Hiding radio buttons just showing themeDiv for selection, using grid as div has to be of fixed size ( want to use flexbox , but space-between property creates problem in last row ). Checkmark has to be in middle of div. opacity also didn’t worked .

TS

public selectThemeOnClick(value) {
    this.themeValueId = value;
    const themeRadioDivArray = Array.from(document.querySelectorAll(".theme-radio-div"));
    if (themeRadioDivArray) {
      themeRadioDivArray
      .filter(element => element.classList.contains("theme-radio-check-mark"))
      .forEach((element) => {
          element.classList.remove("theme-radio-check-mark");
      });
    }
    const themeRadioDiv = document.getElementById(this.themeValueId);
    if (themeRadioDiv) {
      themeRadioDiv.classList.add("theme-radio-check-mark");
    }
  }

If clicked on theme, removing class from all other elements and adding class to that clicked theme.

I could only think of replacing div with svg content using css.

Struggling to do following :

  1. Checkmark should be displayed for default theme (considering 1st one for now)
  2. Display checkmark on overlay for selected theme
  3. Use flexbox

Trying to make a tic-tac-toe app, why doesn’t my component work as expected?

quick question on reactjs. So I’m new to react and I’m trying to make a tic-tac-toe application.

Currently, this is what I have:
App.js:

import logo from './logo.svg';
import './App.css';
import { Row } from './components/Row';
import {Board} from './components/Board'

function App() {
  // App renders Row
  return (
    <div>
      <Board />
    </div>
    
  );
}

export default App;

Board.js

import React from "react";
import { ReactDOM } from "react";
import { Row } from "./Row";

export function Board() {
    return (
        <div className="Board">
            <Row />
            <Row />
            <Row />
        </div>
    )
}

Row.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Square } from './Square';

export function Row() {

    return(
        <div className='Row'>
            <Square />
            <Square />
            <Square />
        </div>
    )
}

Square.js

import React, {useState} from 'react';
import ReactDOM from 'react-dom';

export function Square(props){
    // Square is rendered by App
    const [currLetter, changeLetter] = useState(" ");

    function toggleLetter(str) {
        if(str === " ") {return "X";}
        else if(str === "X") {return "O";}
        else if(str === "O") {return "X";}
    }

    return(
        <div >
            <button onClick={() => changeLetter(toggleLetter)} className='Square'> {currLetter} </button>
        
        </div>
               
    );
}

and it works well, but I’m wondering why it doesn’t work when I write Square.js like this:

export function Square(props){
    // Square is rendered by App
    const [currLetter, changeLetter] = useState("X");

    function toggleLetter(str) {
        if(str === "X") {changeLetter("O");}
        else if(str === "O") {changeLetter("X");}
    }

    return(
        <div >
            <button onClick={toggleLetter} className='Square'> {currLetter} </button>
        
        </div>
               
    );
}

why can’t onClick just take in toggleLetter as is? it’s a function right?

second question
this is what my css looks like:

.Board {
  display: flex;
  flex-direction: column;
  justify-content: space-between;

  
  /* width: 55%;
  height: 55%; */
  margin-top: 18%;
}


.Row {
  text-align: center;
  /* position: absolute; */
  /* left: 35%;
  right: 50%;
  top: 25%;
  
  width: 25%;
  height: 25%; */

  display: flex;
  flex-direction: row;
  justify-content: center;

  
}
.Square {
  /* position: absolute; */
  
  width: 70px;
  height: 70px;
  border-color: #99ccff;
  text-align: center;
  font-size: xx-large;
  font-family: 'Courier New', Courier, monospace;
}
/* .Row {

} */

.App-logo {
  height: 40vmin;
  pointer-events: none;
}

@media (prefers-reduced-motion: no-preference) {
  .App-logo {
    animation: App-logo-spin infinite 20s linear;
  }
}

.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}

.App-link {
  color: #61dafb;
}

@keyframes App-logo-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

body {
  min-height: 100%;
  margin: 0;
  padding: 0;
  background-color: #ffcccc;
}
html {
  height: 100%;
}

What I wanted to do was make sure the board is centred in body, and therefore centred on the page. As it is, it is centred on the page but then the body is moved down. When I inspect the page, the top edge of the body is moved down to the same level of the top edge of board, as opposed to the body being where it was by default and the board being in its centre. How do I fix this?

what it looks like:

how-it’s-going

React Routes not routing correctly v6

I’m trying to get the routing to work correctly but whenever I click on my navbar component it does not properly go to the component that’s supposed to be rendered by the Route.

There are no errors indicated by React. Just super stuck right now.

import React from 'react';
import Navbar from './components/Navbar';
import Home from './components/Home.js';
import BlankPage from './components/BlankPage';
import {BrowserRouter as Router, Routes, Route} from 'react-router-dom';

function App() {
  return (
    <>
      <Router>

      <Navbar/>

      <Routes>
        <Route path="/" component={Home}/>
        <Route path="/blankpage" component={BlankPage}/>
      </Routes>

    </Router> 
    </>
  );
}

export default App;

Count dates within date intervals

I’ve an array abc containing date and time. I need to convert it into time slots of 1 day with limits determined by startDate and endDate with ‘x’ containing time slots and ‘y’ containing count of occurrence in those time slots. How can I get the count of occurrences in abc as per the interval and map it correctly it as per the date intervals?

const abc = ['2021-09-05T00:53:44.953Z', '2021-08-05T05:08:10.950Z', '2022-03-05T00:53:40.951Z'];
const startDate = '2021-07-05'; 
const endDate = '2021-11-05';
const res = [{x: '2021-07-05 - 2021-08-05' , y: '1' },{x: '2021-08-05 - 2021-09-05' , y: '2' }, {x: '2021-09-05 - 2021-10-05' , y: '1' },{x: '2021-10-05 - 2021-11-05' , y: '0' }];
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Scraper with puppeteer to website iframe there is a #document that does not let me get the data

There is a casino website

https://www.888casino.com/live-casino/?reason=0#filters=all-roulette

When I enter one of the tables, an IFRAME opens and inside the IFRAME there is a #document

The #document does not let me select the data inside the iframe and that is where the data I need is

let mesaRoulette = false; 
    const browser = await puppeteer.launch({
        headless: false,
        userDataDir: './userData',
        args: ['--start-maximized'],
        devtools: true,
    });
    const [ page ] = await browser.pages();
    await page.setDefaultNavigationTimeout(0); 

    await page.goto('https://es.888casino.com/live-casino/?reason=0#filters=all-roulette');
    await page.waitForTimeout(10000);
    const mesas = await page.$$('#orbit-container > div > main > div > div > div > div > div.item-wrapper-box');
    for (const mesa of mesas) {
        const tituloSelector = await mesa.$('#orbit-container > div > main > div > div > div > div > div.item-wrapper-box > div > span');
        if (tituloSelector){
            const titulo = await mesa.$eval('#orbit-container > div > main > div > div > div > div > div.item-wrapper-box > div > span', el => el.innerText);
            console.log(titulo);
            if (titulo === 'Roulette'){
                // const img = await mesa.$('#orbit-container > div > main > div > div > div > div > div.item-wrapper-box > div > img');
                await mesa.click('#orbit-container > div > main > div > div > div > div > div.item-wrapper-box');
                mesaRoulette = true;
                break;
            }
        };
    }

IMAGE #Document problem selector

Javascript Loop canvas

I am working on an assignment where I have to draw a four point star and create a for loop to generate between 1 and 100 stars depending on the user input. Here are the instructions:

The requirements of painting stars are as follows:

  • a. for loop should be used in this function.
  • b. The number of stars should match the user’s input. If the user’s input is not a number or not from 1 to 100, show an alert message to ask the user to input a valid number.
  • c. The center of each star is randomly located on the canvas.
  • d. The color of each dot is randomly generated.
  • e. The distance between the far point and the center is randomly generated between 5 and 50. The distance between the near point and the center is ΒΌ of the distance between far point and the center.

But mine is not working. I am not sure where the values of part d and e should be entered. I not sure if the way I created it is right. Could someone please help me here?

const ctx = document.querySelector("canvas").getContext("2d"),
  b1 = document.getElementById("b1");

b1.addEventListener("input", paintStar);

function paintStar() {
  ctx.clearRect(
    0,
    0,
    800,
    400
  );

  for (let i = 1; i <= b1.value; i++) { /*this loop is not working correctly, not multiplying according to my b1.value*/
    x = Math.floor(Math.random() * 800) + 1;
    y = Math.floor(Math.random() * 400) + 1;
    d = Math.random() * 45 + 5; /*number between 5 and 50*/
    e = d / 4; /*1/4 of size*/

    /*I created my start using rotation and one more FOR loop*/
    ctx.beginPath();
    ctx.translate(x, y); /* Here I put my X and Y to change the positions of the starts on my canvas*/
    ctx.beginPath();
    ctx.rotate((-90 * Math.PI) / 180);
    ctx.moveTo(50, 0);
    
    for (let j = 1; j <= 4; j++) {
      ctx.rotate((45 * Math.PI) / 180);
      ctx.lineTo(20, 0); /*I tried to put D and E here in Lineto, but did not work out*/
      ctx.rotate((45 * Math.PI) / 180);
      ctx.lineTo(50, 0);
    }

    ctx.fillStyle =
      "rgb(" +
      Math.floor(Math.random() * 256) +
      "," +
      Math.floor(Math.random() * 256) +
      "," +
      Math.floor(Math.random() * 256) +
      ")";
    ctx.fill();
  }
}
<input id="b1" type="number" placeholder="b1"/>
<canvas width="800" height="400"></canvas>

WordPress menu closes too fast on smartphone

Hi currently making a website for a client using the getaway theme. But when I resize my browser to a mobile phone and open the menu it opens and then closes really quickly. I have added in the following code into the theme repo:

jQuery(document).ready(function($) {
   $('.x-nav .menu-item a').off('click');
   $('.x-nav .menu-item a').click(function() {
      return true;

This unfortunately did not work.
the link to the website is leisurely.in any help is greatly appreciated.