Styling scrollbar on specific element on mui v5

I have tried styling Box components using the suggested approach from this answer.

<Box sx={{
  overflow:"auto",
  scrollbarWidth: 'thin',
  '&::-webkit-scrollbar': {
    width: '0.4em',
  },
  '&::-webkit-scrollbar-track': {
    background: "#f1f1f1",
  },
  '&::-webkit-scrollbar-thumb': {
    backgroundColor: '#888',
  },
  '&::-webkit-scrollbar-thumb:hover': {
    background: '#555'
  }
  }}>
</Box>

However it doesn’t work on my end, the scrollbar style works only if I put it on the global styles, but it will be applied to all elements which I don’t want. Any suggestions?

How do I hide this menu with a media query in ReactJS/NextJS

I am having issues getting my hamburger menu to hide when the screen size gets to a certain width. If I do not manually close the hamburger menu before changing the screen size the hamburger menu goes away but the menu icons stay in place and a duplicate menu is observed.

Here is my Navbar component:

// Navbar component.
export default function Navbar() {
    // to change burger classes
    const [burger_class, setBurgerClass] = useState("burger-bar unclicked")
    const [isMenuClicked, setIsMenuClicked] = useState(false)
    const [isMenuVisible, setIsMenuVisible] = useState(false);

    // toggle burger menu change
    const updateMenu = () => {
      if(!isMenuClicked) {
          setBurgerClass("burger-bar clicked")
          setIsMenuVisible(true)
          
      }
      else {
          setBurgerClass("burger-bar unclicked")
          setIsMenuVisible(false)
      }
      setIsMenuClicked(!isMenuClicked)
  }
  return (
  <>
    <nav id="nav" className="navbar navbar-expand-lg sticky-top">
      <div className="container-fluid">
        <span id="site-title" className="navbar-brand">
          Large Gate Studios
        </span>
        <ul className="navbar-nav">
          <div className="burger-menu" onClick={updateMenu}>
            <div className={burger_class} ></div>
            <div className={burger_class} ></div>
            <div className={burger_class} ></div>
          </div>
          <li className="nav-item">
            <Link id="a" className="nav" href="/">Home</Link>
          </li>
          <li className="nav-item">
            <Link id="a" className="nav" href="/team">Our Team</Link>
          </li>
          <li className="nav-item">
            <Link id="a" className="nav" href="/contact">Contact</Link>
          </li>
        </ul>
        <li className="nav-item" style={{'display':` ${isMenuVisible ? 'inline' : 'none'}`}}>
        <Link id="a" className="nav" href="/">Home</Link>
        </li>
        <li className="nav-item" style={{'display':` ${isMenuVisible ? 'inline' : 'none'}`}}>
          <Link id="a" className="nav" href="/team">Our Team</Link>
        </li>
        <li className="nav-item" style={{'display':` ${isMenuVisible ? 'inline' : 'none'}`}}>
          <Link id="a" className="nav" href="/contact">Contact</Link>
        </li>
      </div>
    </nav>
  </>
  );
}

Here is the CSS for this class:

#nav {
  background-color: #e2e1e1;
  display: flex;
  position: fixed;
  width: 100%;
  justify-content: space-between;
  align-items: center;
  gap: 2rem;
  padding: 0 1rem;
  opacity: 0.95;
}

#logo-img {
  padding-right: 5px;
  padding-bottom: 5px;
}

#site-title {
  color: #000000;
  font-size: 2rem;
}
  
#a {
  color: #000000;
  text-decoration: none;
  font-size: 1.25rem;
  padding: 1rem;
}
  
#a:hover {
  color: #ff0000;
}

.burger-bar:hover {
  background-color: #ff0000;
}

#link {
  display: inline;
  color: #000000;
  text-decoration: none;
  font-size: 1.25rem;
  padding: 1rem;
}

#link:hover {
  color: #ff0000;
}


@media (max-width: 1200px) {
  .burger-menu {
    display: inline;
    height: 100%;
    width: 3em;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: space-between;
    cursor: pointer;
  }
  
  .burger-bar {
    display: inline;
    width: 3em;
    height: 0.5em;
    background-color: #292f36;
    border-radius: 0.5rem;
    margin: 2px;
  }

  .nav-item {
    display: none;
  }
}

@media (max-width >= 1200px) {
  .burger-menu {
    display: none;
  }
  
  .burger-bar {
    display: none;
  }
}

How can I fix my hamburger menu so that it closes as expected when the screen size increase according to my media query?

Embedded HubSpot form as a React component

I’m trying to do what the title suggests. That is, I want the following vanilla JS code from HubSpot to work as a React component for my website:

<script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/embed/v2.js">    </script>
<script>
  hbspt.forms.create({
    region: "na1",
    portalId: "key",
    formId: "key"
  });
</script>

However, I’m having a tough time doing this conversion. What would be a simple approach to solve this?

Error encountered when creating a post in a blog page

I am developing a blog page where users can create posts. Upon clicking the “Create Post” button, the post is successfully added to the database and displayed on the blog. However, I am encountering an error during this process. The page turns red and I receive an error message saying “Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it’s defined in, or you might have mixed up default and named imports.”

To create a post, I have implemented the following steps:

On the server-side (index.js), I have created routes for registering, logging in, and creating posts. I have also defined a middleware for file upload using multer.
On the client-side, I have an IndexPage component that fetches and displays the posts.
I have a CreatePost component where users can enter the post details, including a file upload using ReactQuill and the input type “file”.

I expected that upon creating a post, it would be successfully added to the database and displayed on the blog without any errors. However, the encountered error turns the page red and prevents a smooth experience.

I would appreciate any insights or suggestions on how to identify and fix the error in order to successfully create a post without encountering any issues. Thank you in advance for your help.

/////////////////////
Index.js
/////////////////////

const express = require('express');
const mongoose = require('mongoose');
const User = require('./models/User');
const Post = require('./models/Post');
const cors = require('cors');
const bcrypt = require('bcryptjs');
const app = express();
const jwt = require('jsonwebtoken');
const cookieParser = require('cookie-parser');
const multer = require('multer');
const uploadMiddleware = multer({ dest: 'uploads/' });
const fs = require('fs');

const salt = bcrypt.genSaltSync(10);
const secret = 'asdfe45we45w345wegw345werjktjwertkj';

app.use(cors({ credentials: true, origin: 'http://localhost:3000' }));
app.use(express.json());
app.use(cookieParser());

mongoose.connect('mongodb+srv://g00366442:[email protected]/?retryWrites=true&w=majority');

app.post('/register', async (req, res) => {
  const { username, password } = req.body;
  try {
    const userDoc = await User.create({
      username,
      password: bcrypt.hashSync(password, salt),
    });
    res.json(userDoc);
  } catch (e) {
    console.log(e);
    res.status(400).json(e);
  }
});

app.post('/login', async (req, res) => {
  const { username, password } = req.body;
  const userDoc = await User.findOne({ username });
  const passOk = bcrypt.compareSync(password, userDoc.password);
  if (passOk) {
    // logged in
    jwt.sign({ username, id: userDoc._id }, secret, {}, (err, token) => {
      if (err) throw err;
      res.cookie('token', token).json({
        id: userDoc._id,
        username,
      });
    });
  } else {
    res.status(400).json('wrong credentials');
  }
});

app.get('/profile', (req, res) => {
  const { token } = req.cookies;
  jwt.verify(token, secret, {}, (err, info) => {
    if (err) throw err;
    res.json(info);
  });
});

app.post('/logout', (req, res) => {
  res.cookie('token', '').json('ok');
});

app.post('/post', uploadMiddleware.single('file'), async (req, res) => {
  const { originalname, path } = req.file;
  const parts = originalname.split('.');
  const ext = parts[parts.length - 1];
  const newPath = path + '.' + ext;
  fs.renameSync(path, newPath);

  const { token } = req.cookies;
  jwt.verify(token, secret, {}, async (err, info) => {
    if (err) throw err;
    const { title, summary, content } = req.body;
    const postDoc = await Post.create({
      title,
      summary,
      content,
      cover: newPath,
      author: info.id,
    });
    res.json(postDoc);
  });
});

app.get('/post', async (req, res) => {
  res.json(await Post.find());
});

app.listen(4000);

/////////////////////////////////////////////////////
IndexPage.js
///////////////

import Post from "../Post";
import { useEffect, useState } from "react";

export default function IndexPage() {
  const [posts, setPosts] = useState([]);

  useEffect(() => {
    fetch('http://localhost:4000/post').then(response => {
      response.json().then(posts => {
        setPosts(posts);
      });
    });
  }, []);

  return (
    <>
      {posts.length > 0 && posts.map(post => (
        <Post key={post.id} {...post} />
      ))}
    </>
  );
}

/////////////////////////////
CreatePost.js
//////////////////

import React, { useState, Navigate } from "react";
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";

const modules = {
  toolbar: [
    [{ header: [1, 2, false] }],
    ["bold", "italic", "underline", "strike", "blockquote"],
    [{ list: "ordered" }, { list: "bullet" }, { indent: "-1" }],
    ["link", "image"],
    ["clean"]
  ]
};

const formats = [
  'header',
  'bold', 'italic', 'underline', 'strike', 'blockquote',
  'list', 'bullet', 'indent',
  'link', 'image'
];

export default function CreatePost() {
  const [title, setTitle] = useState("");
  const [summary, setSummary] = useState("");
  const [content, setContent] = useState("");
  const [files, setFiles] = useState("");
  const [redirect, setRedirect] = useState(false);

  async function createNewPost(ev) {
    const data = new FormData();
    data.set('title', title);
    data.set('summary', summary);
    data.set('content', content);
    data.set('file', files[0]);
    ev.preventDefault();
    const response = await fetch('http://localhost:4000/post', {
      method: 'POST',
      body: data,
      credentials: 'include',
    });

    if (response.ok) {
      setRedirect(true);
    }
  }

  if (redirect) {
    return <Navigate to={'/'} />;
  }

  return (
    <form onSubmit={createNewPost}>
      <input
        type="title"
        placeholder={'Title'}
        value={title}
        onChange={ev => setTitle(ev.target.value)}
      />
      <input
        type="summary"
        placeholder={'Summary'}
        value={summary}
        onChange={ev => setSummary(ev.target.value)}
      />
      <input type="file" onChange={ev => setFiles(ev.target.files)} />

      <ReactQuill
        value={content}
        onChange={value => setContent(value)}
        modules={modules}
        formats={formats}
        theme="snow"
      />

      <button type="submit">Create Post</button>
    </form>
  );
}

How to display DecalGeometry from ThreeJs on Specific Mesh

I have this Mesh:
The specific mesh named OCounter
and I want to display the Decal on the front of the mesh.

I tried this:

    textureDecal.side = THREE.DoubleSide
  const euler = new THREE.Euler(0,0,0, "XYZ");
  const decalImage = new DecalGeometry(
    OCounter,
    new THREE.Vector3(0, 0, 5),
    euler,
    new THREE.Vector3(2,2, 10)
  );

  
  const decalMaterial = new THREE.MeshStandardMaterial({
    transparent: true, 
    depthTest: true,   
    depthWrite: false,   
    polygonOffset: true,  
    polygonOffsetFactor: -4,   
    
  });


  decalMaterial.side = THREE.DoubleSide;
  DecalLogo = new THREE.Mesh(decalImage, decalMaterial);
  scene.add(DecalLogo);

I tried with a cube and a sphere, it works properly by changing Vector3 values in DecalGeometry.

But even with various settings on this mesh, it does not display at all, not even a small portion of the decal.

Unexpected behavior: Node.js vs Vanila JavaScript [duplicate]

Consider the following code:

var fullname = "John Doe";
var obj = {
  fullname: "Colin Ihrig",
  prop: {
    fullname: "Aurelio De Rosa",
    getFullname: function () {
      return this.fullname;
    },
  },

  getFirstName: () => {
    console.log(this);
    return this.fullname.split(" ")[0];
  },
};

console.log(obj.prop.getFullname());
console.log(obj.getFirstName());

When I run the above code in browser. this inside the getFirstName() points to the window object (which is expected). When I run the same code in Node.js shell it gives the same output (intead of window, this now points to the global object).

However, when I run code as node prog.js:

The code throws the following error:

Aurelio De Rosa
{}
/home/x/code/var.js:13
    return this.fullname.split(" ")[0];
                         ^

TypeError: Cannot read properties of undefined (reading 'split')
    at Object.getFirstName (/home/x/code/revise/ctci/var.js:13:26)
    at Object.<anonymous> (/home/x/code/revise/ctci/var.js:18:17)
    at Module._compile (node:internal/modules/cjs/loader:1254:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)
    at Module.load (node:internal/modules/cjs/loader:1117:32)
    at Module._load (node:internal/modules/cjs/loader:958:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at node:internal/main/run_main_module:23:47

Node.js v18.14.1

Here is the demo.

Why is that?

How to remove encircle element using javascript without target id or class?

How to remove encircle element using javascript without target id or class????
Like that

<div>
  Choice 1 <span>close X</span>
</div>

I hope that when someone click the “close X” word, it will delete Choice 1 and close X

I try to

    <div>
          Choice 1 <span onclick="remove(this)">close X</span>
    </div>
    <script>
    function remove(val) {
      //val.remove();   Just remove the "close X" word
      //val.previousElementSibling.remove();   //Not work
      //$(this).prev().remove();   using Jquery //Still Not work
    }
    </script>

Anyidea How to do it?? Thank you very much

html, css, javascript and php in vscode cannot stored data in phpmyadmin database

My intention is after the user submit the form from signup.html, the input data will be transfer and stored in database. So the problem is I dont know where are the error or any mistake in my coding that prevent the data to be stored in phpmyadmin database. I already install php extension and connect the server in vscode.

signup.html

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

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> Sign Up - GlampinGetaways</title>
    <link rel="stylesheet" href="signupstyle.css">
</head>

<body>
    <div class="container">
        <h1>Sign Up</h1>
        <form id="signupForm" action="signup.php" method="POST">
            <label for="fname">First name:</label>
            <input type="text" id="fname" name="fname" required>

            <label for="lname">Last name:</label>
            <input type="text" id="lname" name="lname" required>

            <label for="SUusername">Username:</label>
            <input type="text" id="SUusername" name="SUusername" required>

            <label for="SUemail">Email:</label>
            <input type="email" id="SUemail" name="SUemail" required>

            <label for="SUpassword">Password:</label>
            <input type="password" id="SUpassword" name="SUpassword" required>

            <label for="SUcpassword">Confirm password:</label>
            <input type="text" id="SUcpassword" name="SUcpassword" required>

            <button type="submit">Sign Up</button>
        </form>
        <p>Already have an account? <a href="signin.html">Sign In</a></p>
    </div>

    <script src="signup.js"></script>
</body>

</html>

signup.js

document.getElementById("signupForm").addEventListener("submit", function(event) {
  event.preventDefault(); // Prevent form submission

  // Get form values
  var fname = document.getElementById("fname").value;
  var lname = document.getElementById("lname").value;
  var username = document.getElementById("SUusername").value;
  var email = document.getElementById("SUemail").value;
  var password = document.getElementById("SUpassword").value;

  // Perform form validation
  if (fname === "" || lname === "" || username === "" || email === "" || password === "") {
    alert("Please fill in all fields.");
    return;
  }

  // Perform further processing (e.g., sending data to the server)

  // Clear form fields
  document.getElementById("fname").value = "";
  document.getElementById("lname").value = "";
  document.getElementById("SUusername").value = "";
  document.getElementById("SUemail").value = "";
  document.getElementById("SUpassword").value = "";
  document.getElementById("SUcpassword").value = "";

  // Create an object to hold the form data
  var formData = {
    fname: fname,
    lname: lname,
    SUusername: username,
    SUemail: email,
    SUpassword: password
  };

  // Send the form data to the server
  var xhr = new XMLHttpRequest();
  xhr.open("POST", "signup.php", true);
  xhr.setRequestHeader("Content-Type", "application/json");
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
      alert(xhr.responseText);
    }
  };
  xhr.send(JSON.stringify(formData));
});
  
const passwordInput = document.getElementById('SUpassword');
const confirmPasswordInput = document.getElementById('SUcpassword');
const form = document.querySelector('form');

form.addEventListener('submit', function(e) {
    if (passwordInput.value !== confirmPasswordInput.value) {
        e.preventDefault();
        alert("Passwords do not match. Please try again.");
    }
});

signup.php

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Establish a connection to the MySQL database
$servername = "localhost";
$username = "root";
$password = ""; // Leave it empty for no password
$dbname = "glampinguser";

$conn = new mysqli($servername, $username, $password, $dbname);

// Retrieve form data
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$username = $_POST['SUusername'];
$email = $_POST['SUemail'];
$password = $_POST['SUpassword'];

// Check the connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
} 

// Insert data into the table
$sql = "INSERT INTO `user` (`fname`, `lname`, `SUusername`, `SUemail`, `SUpassword`) VALUES ('".$fname."', '".$lname."', '".$username."', '".$email."', '".$password."')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

I already ask the chatgpt is the coding are wrong or there is error but chatgpt said there is no error. Now I am confused as the data did not store in database.

Can I position angular material components by code?

I am trying develop a responsive angular app.

Is it possible to set height, set position to angular material <mat-sidenav-content></mat-sidenav-content> component by code without css?

I had tried with css, its not working as expected.

eg. in javascript

const box = document.getElementById('box');
box.style.position = 'absolute';
box.style.top = '150px';
box.style.left = '150px';

I want to set height of <mat-sidenav> and <mat-sidenav-content> dynamically on pageload.

I am expecting this layout.

enter image description here

But my current layout is

enter image description here

Here is my code

<header>
    <mat-toolbar color="primary">
        <button (click)="snav.toggle()" mat-icon-button>
            <mat-icon>menu</mat-icon>
        </button>
        <span>My App</span>
        <span class="mat-toolbar-spacer"></span>
        <button mat-icon-button [matMenuTriggerFor]="menu">
            <mat-icon>more_vert</mat-icon>
        </button>
        <mat-menu #menu="matMenu">
            <button mat-menu-item>
                <mat-icon>dialpad</mat-icon>
                <span>Redial</span>
            </button>
            <button mat-menu-item disabled>
                <mat-icon>voicemail</mat-icon>
                <span>Check voice mail</span>
            </button>
            <button mat-menu-item>
                <mat-icon>notifications_off</mat-icon>
                <span>Disable alerts</span>
            </button>
        </mat-menu>
    </mat-toolbar>
</header>

<mat-sidenav-container class="mat-sidenav-container" [style.marginTop.px]="mobileQuery.matches ? 56 : 0">
    <mat-sidenav #snav [opened] = "!mobileQuery.matches" [mode]="mobileQuery.matches ? 'over' : 'side'" [fixedInViewport]="mobileQuery.matches"
        fixedTopGap="56">
        <mat-nav-list>
            <a mat-list-item routerLink="." *ngFor="let nav of fillerNav">{{nav}}</a>
        </mat-nav-list>
    </mat-sidenav>

    <mat-sidenav-content #matSidenavContent >
        <p *ngFor="let content of fillerContent">{{content}}</p>
    </mat-sidenav-content>
</mat-sidenav-container>



.mat-toolbar-spacer {
    flex: 1 1 auto;
}

header {
    width: 100%;
    position: fixed;
    top: 0;
    z-index: 100;
    display: flex;
}

footer {
    height: auto;
    background-color: #F5F5F5;
    text-align: center;
    padding: 20px 0px 20px 0px;
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 100;
}

mat-sidenav-container {
    background-color: #FFFFFF;
    height: auto;
    overflow: auto;
}

mat-sidenav{
    margin-top: 65px;
    position: fixed;
    margin-bottom: 60px;
}

mat-sidenav-content{
    padding: 20px;
    margin-top: 60px;
    overflow: auto;
    /*height:520px;*/ /* i don't want to set it here */
    height:100%;
}

mat-nav-list{
    width: 250px;
    padding: 5px;
}

mat-nav-list mat-list-item{
    width: 100%;
    padding-right: 100px;
}

@media (max-width: 767.98px) {
    mat-nav-list{
        margin-top: 0px;
        width: auto;
    }

    mat-sidenav{
        margin-top: 0px;
        margin-bottom: 0px;
    }

    mat-sidenav-content{
        padding: 20px;
        margin-top: 0px;
        height:auto;
    }
    
    footer {
        position:initial;
        left:initial;
        bottom: initial;
    }
}

Why is my NextJS Image component not converting images to webp?

Using Next version 12.3.2.

I have a custom component ImagewithFallback setup in my NextJS application. For some reason, it is not loading images as webp, but rather jpg. I have tried to remove the custom loader as the default loader uses the next image optimisation api, but then I get a 500 sever error. The images are coming from my mongodb database which is running on another port. On vercel they are being sent from an api. Below is my entire custom image component.

import React, { useEffect, useState } from "react";
import Image from "next/image";
import PropTypes from "prop-types";

const ImageWithFallback = (props) => {
  const { src, fallbackSrc, width, height, objectFit, presrc, ...rest } = props;
  const [imgSrc, setImgSrc] = useState(src);

  // update the image src if a new src is supplied. e.g. first src is undefined but then later its defined
  // without this the fallback image will always be selected if the initial component render has a bad src
  useEffect(() => {
    if (!src || src.endsWith("null") || src.endsWith("undefined")) {
      setImgSrc(fallbackSrc);
    } else if (src !== imgSrc) {
      setImgSrc(src);
    }
  }, [src]);

  const loader = ({ src, width, quality }) => {
    return `${src}?w=${width}&q=${quality || 75}`;
  };

  return (
    <Image
      {...rest}
      width={width}
      
      height={height}
      src={imgSrc}
      objectFit={objectFit}
      onError={() => {
        setImgSrc(fallbackSrc);
      }}
    />
  );
};

ImageWithFallback.propTypes = {
  width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
  src: PropTypes.string,
  fallbackSrc: PropTypes.string,
  objectFit: PropTypes.string,
};

ImageWithFallback.defaultProps = {
  fallbackSrc: "/images/placeholder.gif",
};

export default ImageWithFallback;

For my next.config.js I have set up the domain names for localhost as such

  images: {
    domains: ['localhost'],
  },

How can I make it so images sent from my localhost db server are converted into webp?

Is there a js shorthand contructor parameter assignment?

class MyClass {
  constructor(prop1, prop2, prop3, prop4) {
    this.prop1 = prop1
    this.prop2 = prop2
    this.prop3 = prop3
    this.prop4 = prop4
    //prop 50 and so on
  }
}

In js, for this type of constructor assigning where all I’m doing is making instance properties with the exact same name and values as the constructor params, is there some shorthand syntax to just do this in like one line or something, or do I have to do it this way?

Working around missing ES6 functions in JavaScript import of libraries from CDN?

I do not have much experience with Node.js, and when I try a JavaScript library, I try to write a single test.html file, that loads requirements for the library from an online CDN, and then develop my script there.

So, I tried to make that kind of an example for the demo shown on https://pathwaycommons.github.io/cytoscape-sbgn-stylesheet/. This is how far I got:

test.html

<!DOCTYPE html>
<!-- based on https://pathwaycommons.github.io/cytoscape-sbgn-stylesheet/index.html -->
<html>
  <head>
  <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
  <title>test_cyto demo</title>

  <!--<script src="https://unpkg.com/[email protected]/fetch.js"></script>
  <script src="https://unpkg.com/cytoscape/dist/cytoscape.min.js"></script>-->

  <style>
    body {
      font-family: helvetica neue, helvetica, liberation sans, arial, sans-serif;
      font-size: 14px;
    }

    #cy2 {
      width: 100%;
      height: 100%;
      position: absolute;
      left: 0;
      top: 0;
      z-index: 999;
    }

    h1 {
      opacity: 0.5;
      font-size: 1em;
      font-weight: bold;
            }
  </style>
  </head>

  <body>
  <h1>test_cyto demo</h1>

  <div id="cy2">
  </div>

  <!-- <script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.js"></script> -->
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.js" type="module"></script>
  <script src="https://unpkg.com/[email protected]/fetch.js"></script>
  <script src="https://unpkg.com/cytoscape/dist/cytoscape.min.js"></script>
  <script src="test_cyto_module.js" type="module"></script> <!-- needs a local server to serve this with correct MIME type for javascript; for python, see https://stackoverflow.com/q/63166774 -->
  </body>
</html>

test_cyto_module.js

//~ import * as lodash_exports from 'https://cdn.jsdelivr.net/npm/[email protected]/lodash.js'; //  // seems to run, but no exports
//import * as lodash from 'https://cdn.jsdelivr.net/npm/[email protected]/lodash.js'; //  // runs, with exports
//import * as lodash_exports from 'https://cdn.jsdelivr.net/npm/[email protected]/lodash.js'; //  // runs, with exports
import { memoize } from 'https://cdn.jsdelivr.net/npm/[email protected]/lodash.js'; //  // runs, with exports
//~ Object.entries(lodash_exports).forEach(([name, exported]) => window[name] = exported); // runs after import * as demo_exports ...
//~ export { default as memoize } from 'https://cdn.jsdelivr.net/npm/[email protected]/lodash.js';
import * as demo_exports from 'https://cdn.jsdelivr.net/gh/PathwayCommons/cytoscape-sbgn-stylesheet@master/build/bundle.js'; // seems to run, but TypeError: memoize is not a function - even with lodash load above
//import * as demo_exports from 'https://pathwaycommons.github.io/cytoscape-sbgn-stylesheet/build/demo.js'; // object with only Symbol(Symbol.toStringTag): "Module", and it runs - to trick the running part, rename div id="cy" to div id="cy2 in html? that breaks cytoscape.min.js:32:157281 then .. 

function startup() {
  //import * as demo_exports from 'https://cdn.jsdelivr.net/gh/PathwayCommons/cytoscape-sbgn-stylesheet@master/build/bundle.js'; // import declarations may only appear at top level of a module
  console.log("startup lodash_exports ->", lodash_exports, "<-");
  console.log("startup demo_exports ->", demo_exports, "<-");
  Object.entries(demo_exports).forEach(([name, exported]) => console.log(name, exported));
  //Object.entries(ip6).forEach(([name, exported]) => console.log(name, exported));
}

export default { startup }

//startup(); // actually, this runs now; also as type="module"

document.addEventListener('DOMContentLoaded', function() {
  startup();
}, false);

Basically, cytoscape-sbgn-stylesheet has two files in its build:

  • build/demo.js – this does imports without errors, but contains the demo.js code (shown at end) that draws the demo on the “#cy” div, which I don’t want; if I rename ‘#cy’ to ‘#cy2’ to avoid that, then something else crashes; and yet, I cannot find any functions like sbgnStylesheet being imported here
  • build/bundle.js – this import fails with “TypeError: memoize is not a function”, even if I attempt to import memoize from lodash …

So my question is: is there anything I can do, so I can use the cytoscape-sbgn-stylesheet in my own/html JS pulled from CDN, and still be able to do my own version of the demo.js they use:

var sbgnStylesheet = require('./build/bundle.js');
var cytoscape = window.cytoscape;

var cy = window.cy = cytoscape({
  container: document.getElementById('cy'),
  elements: fetch('./demo.json').then( res => res.json() ),
  layout: { name: 'preset' },
  style: sbgnStylesheet(cytoscape)
});

ReactJs: Why is the `useEffect` not running even once in this case?

I have a web application which should show the contents in different languages based on a value chosen from the dropdown. The chosen language is stored in a LanguageContext and the page should update with new strings when the language is changed.

We have StringsContext and StringsProvider taken from a createContext().

I have an AppProvider written like this:

function AppProvider({ children, languageStrings }) {
  const val = useLoader(languageStrings);
  const [isTranslationsLoading, intl] = val;
  if (isTranslationsLoading) {
    return null;
  }
  return <StringsProvider value={intl}>{children}</StringsProvider>;
}

And useLoader written like this:

const useLoader = (languageStrings = {}) => {
  const { language } = useLanguageContext();

  const [intl, setIntl] = useState(null);
  const [isTranslationsLoading, setIsTranslationsLoading] = useState(false);
  const [translationLoadingError, setTranslationLoadingError] = useState('');

  const fetchStrings2 = () => {
    .
    .
    .// some function call
    .

  };
  
  console.log('before useEffect');
  useEffect(() => {
    console.log('inside useEffect');
    fetchStrings2();
  }, [language]);
  console.log('after useEffect');

  return [isTranslationsLoading, intl, translationLoadingError];
};

Now when I run this, I’m expecting the useEffect() above to be executed once during initilization. Rest of the console logs are printing but execution is not going inside useEffect(). I couldn’t understand why.

How to change values inside a span tag in Shiny

I’m trying to change the values inside the span tag in a shiny App based on dataframe

Dataframe

df <- tibble(
  Date_Time = c("2023-06-14 09:43:06", "2023-06-14 09:43:09", "2023-06-14 09:43:12", "2023-06-14 09:43:16", "2023-06-14 09:43:19"),
  Heat_Capacity = c(159.65, 159.67, 159.68, 159.66, 159.70),
  Heat_Rate = c(-151.06, -151.07, -151.08, -151.09, -151.10),
  
)

Shiny Code:

library(shiny)

ui <-
  fluidPage(tags$head(tags$link(rel = "stylesheet", href = "./styles.css")),
            
            
            
            mainPanel(
                tags$div(class = "circle1",
                         tags$p("Heat Capacity"),
                         tags$span("")
                ),
                tags$div(class = "circle1",
                         tags$p("Heat Capacity"),
                         tags$span("")
                )
              )
              
             
            )
        
server <- function(input, output, session) {
  
}
shinyApp(ui, server)


I’m trying to display the values inside the dataframe one by one in the span tag where the value changes every second or two when the Shiny App starts.

Desired Outcome Example:

Desire Outcome Example

styles.css

.circle1 {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    background-color: #11141a;
    position: absolute;
    top: 110px;
    left: 100px;
    
    /*flex box */
   display: flex;
   justify-content: center;
   align-items: center;
   border: 3px solid #f1c40f;
   
}
        
.circle2 {
      width: 115px;
    height: 115px;
    border-radius: 50%;
    background-color: #11141a;
    position: absolute;
    top: 110px;
    right: 460px;
    
    
    
    /*flex box */
   display: flex;
   justify-content: center;
   align-items: center;
   border: 3px solid #f1c40f;
   
}

Why is the timeout function returning the previous state?

I know that state changes happen asynchronously, but I tried to get the current state value using a 1 second timeout, my reasoning being that this will allow enough time for the state to update, but the function is still returning the previous state. I’d like to know what causes this.

export default function App() {
  const [num, setNum] = React.useState(1)
 
  function handleChange() {
    setNum(prev => prev + 1)
    let timer = setTimeout(() => {
      console.log(num)
    }, 1000)
  }
  
  return (
    <div>
      <button onClick={handleChange}>+</button>
      <p>{num}</p>
    </div>
  );
}