JavaScript: Wrap portions of a string in html to customize color

Thanks for any time dedicated to this conundrum, in advance.
I am attempting to reprint the html markup of a button inside of a code element. However, I need to split the code elements up into separate spans, to add some color to the output.
Using Regex and HTML character encoding, I am able to correctly wrap all targeted element strings. This is where I hit the wall.
The out of the code is markup, indeed, but I need the wrapping spans to be only that… wrappers of a particular portion of the code string. I was thinking .split() .join(), but really do not want to deal with a huge array of substrings.

<span class="chev"><<span>button id=<span class="quote">">"<span>btn<span class="quote">">"<span> class=<span class="quote">">"<span>btn btn-primary tru-btn<span class="quote">">"<span> data-value=<span class="quote">">"<span>btn-primary<span class="quote">">"<span> type=<span class="quote">">"<span>button<span class="quote">">"<span><span class="chev">><span>Button<span class="chev"><<span>/butt
on<span class="chev">><span> 

generateHTMLBlock = () => {
  let someButton = document.querySelector('div').innerHTML,
    modBtnCode = someButton.replace(/^.s+|s+$/gm, ''),
    btnMarkup = modBtnCode.replace(/(.{100})/g, "$1r");
  encodeElement = (output) => {
    return output.replace(/</g, '&lt;span class=&quot;chev&quot;&gt;&#60;&lt;span&gt;')
      .replace(/>/g, '&lt;span class=&quot;chev&quot;&gt;&#62;&lt;span&gt;')
      .replace(/"/g, '&lt;span class=&quot;quote&quot;&gt;&quot;&gt;&#34;&lt;span&gt;');
  };
  let code = encodeElement(btnMarkup);
  document.getElementsByTagName('code').appendChild(code);
};
.btn-primary:not(disabled):not(.disabled),
.btn-secondary:not(disabled):not(.disabled) {
  box-sizing: border-box;
  display: flex;
  align-items: center;
  max-width: fit-content;
  padding: 0.338rem 1.5rem;
  margin: 0;
  overflow: hidden;
  background: black;
  border-radius: .625rem;
  border-width: .125rem;
  border: 1px solid transparent;
  border-color: black;
  box-shadow: none;
  font-family: arial;
  color: white;
  font-size: 16px;
  font-weight: 400;
  text-align: center;
  vertical-align: middle;
  text-transform: none;
  user-select: none;
  line-height: 2.2rem;
  letter-spacing: .25px;
  text-decoration: none !important;
  cursor: pointer;
  transition: all .3s ease-in-out;
}

pre {
  padding: 1rem;
  margin-bottom: 0;
  width: 100%;
  height: 6em;
}

code {
  display: block;
  color: black;
  width: 100%;
  height: 100%;
  border: 1px solid red;
}

.quote {
  color: green;
}

.chev {
  color: blue;
}
<div>
  <button id="btn" class="btn btn-primary" data-value="btn-primary" type="button">Button</button>
</div>
<pre>
  <code></code>
</pre>

When should I develop a REST API to access Redshift data rather than using either a library to connect to Redshift or the Redshift Data API

For the most part, users connect to our Redshift cluster using a SQL client and either username/password or SSO. Sometimes reporting tools connect to it using whatever method is required from the specific reporting tool. Internal processes (e.g. ETL jobs) connect using the psycopg2 Python library.

An internal web application will now need access to our Redshift data. Is it bad practice for this application to access the Redshift data “directly” using a Javascript library like “node-redshift” or “pg”? Should it instead use either the Redshift Data API or, even more indirectly, a REST API to access the data? Since many users/applications already access the data directly (i.e. configuring JDBC URL, access tables by name), does it matter if this web application also accesses the Redshift data in the same way? Or are there different standards since the web application is part of a programmatic process and owned by a team external to the team which owns the Redshift cluster?Though the team is part of the same company and the web application is private to the company.

Are there risks to allowing the web application to access the Redshift data directly using a library rather than building out a REST API?

Need general guidance

Tab Navigator, React-Native

started to learn React-Native recently.
Have a problem with Tab-Navigation, pretty weird thing is going on.

My createBottomTabNavigator doesn’t work at all. At first I tried some things that didn’t help and after this tried to launch a first example from https://reactnavigation.org/docs/tab-based-navigation/

import * as React from 'react';
import { Text, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';

function HomeScreen() {
  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>Home!</Text>
    </View>
  );
}

function SettingsScreen() {
  return (
    <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
      <Text>Settings!</Text>
    </View>
  );
}

const Tab = createBottomTabNavigator();

export default function App() {
  return (
    <NavigationContainer>
      <Tab.Navigator>
        <Tab.Screen name="Home" component={HomeScreen} />
        <Tab.Screen name="Settings" component={SettingsScreen} />
      </Tab.Navigator>
    </NavigationContainer>
  );
}

For some reason even this code doesn’t work, the same problem as in my app. Of course this code works in Snack

I have just white screen with logo of my app if I try to add TabNavigator no matter what I do.
No error, just blank white screen with logo for 2-3 minutes and then expo’s crashing. Maybe something wrong with dependencies or is it iPhone/Expo Go fault? idk

  "dependencies": {
    "@react-native-masked-view/masked-view": "0.2.9",
    "@react-navigation/bottom-tabs": "^6.5.8",
    "@react-navigation/native": "^6.1.7",
    "@react-navigation/stack": "^6.3.17",
    "expo": "~49.0.11",
    "expo-status-bar": "~1.6.0",
    "react": "18.2.0",
    "react-native": "0.72.4",
    "react-native-gesture-handler": "~2.12.0",
    "react-native-safe-area-context": "4.6.3",
    "react-native-screens": "~3.22.0"

I’m using expo-CLI on physical device – Iphone X, didn’t try emulator

Update:
Okay, I tried to connect via Snack to my Phone and It works for me.
So it’s almost 100% that something is wrong with my dependecies/settings/configs etc.

Uncaught TypeError: this.getElementById is not a function

I am making a Vanilla Javascript Component for a Top Navigation Bar. I am trying to add an “active” class to a certain element based upon a component argument. The code is attached below, I will explain further.

class navbarC extends HTMLElement {
  constructor() {
    super();
  }
  connectedCallback(){
    const page = this.getAttribute('page');
    console.log(page) //Returns "home"
    console.log(typeof page) //Returns "string"
    this.getElementById(page).classList.add("active");
    this.render()
  }
  render(){
    this.innerHTML=`
<style>
  .nav-pills .nav-item {
    margin-right: 5px;
}

.nav-pills .nav-item:last-child { 
    margin-right: 0px;
}

.nav-pills .nav-item .nav-link.active {
    background-color: #e92121;
    color: #fff; 
    border-radius: 0;
    transition: all 0.5s ease;
}
  
.nav-pills .nav-item .nav-link:hover {
    background-color: #c91010; 
    color: #fff; 
    border-radius: 0;
    transition: all 0.5s ease;
}

.nav-pills .nav-item .nav-link:not(active) {
    color: #000000; 
}
</style>
<nav class="navbar navbar-expand-lg navbar-light" style="background-color: #fff;">
  <div class="container-fluid">
    <a class="navbar-brand px-3" href="#"> 
      <img src="assets/logo2.png" width="30" height="30" alt="Random Thingy">
      Random Thingy
    </a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbar"
      aria-controls="navbar" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbar">
      <ul class="nav nav-pills ms-auto">
        <li class="nav-item">
          <a class="nav-link" href="/index.html" id="home">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="/menu.html" id="menu">Menu</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="/reservation.html" id="reservations">Reservations</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="/reviews.html" id="reviews">Reviews</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="/aboutus.html" id="about-us">About Us</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="/checkout.html" id="checkout">Checkout</a>
        </li>
      </ul>
    </div>
  </div>
</nav>`
  }
}
customElements.define("navbar-c",navbarC)

The problem I am having here is that I am trying to reference and alter HTML code to the render() function by adding a class to an element with the certain id. this.getElementById(page).classList.add("active"); <– This is the code I use to attempt to add a class to an element with a certain id, however I suspect that it it not referencing the code I want to manipulate. This line gives me the error, Uncaught TypeError: this.getElementById is not a function at navbarC.connectedCallback.

I tried have tried putting this code into the the constructor() function and have googled in search of how to reference the HTML code inside the element. I am new the JS, so this might be a trivial fix I am not used to.

React Msal is not redirecting to Azure if user is not authenticated

I am trying to implement Azure login with Msal and its just taking me right into the app whether the user is authenticated or not. I followed this documentation https://learn.microsoft.com/en-us/azure/active-directory/develop/single-page-app-tutorial-01-register-app and I got rid of the Sign-in button page. I like the app to redirect the user straight to Azure for authentication when I navigate to the app URL.

I am trying to test the login + redirect in incognito mode but is getting this error in chrome dev tool.

Uncaught (in promise) BrowserAuthError: uninitialized_public_client_application: You must call and await the initialize function before attempting to call any other MSAL API.

It isnt making a lot of sense to me when I tried to look up the error, Do I need to add wrap my instance.initailize in an async await function?. Below is my structure and code. Thank you for reading!

ReactApp
├── src
│   ├── App.jsx
│   └── main.jsx
│   └── authConfig.js
│   └── graph.js
├── index.html
├── vite.config.js
├── package.json
├── package-lock.json

main.jsx

import React from 'react';
import { createRoot } from 'react-dom/client';
import './index.css';
import App from './App';
import { PublicClientApplication, EventType } from '@azure/msal-browser';
import { MsalProvider } from '@azure/msal-react';
import { msalConfig, loginRequest } from './authConfig';

import 'bootstrap/dist/css/bootstrap.min.css';

const msalInstance = new PublicClientApplication(msalConfig);

const root = createRoot(document.getElementById('root'));

root.render(
  <React.StrictMode>
    <MsalProvider instance={msalInstance}>
      <App />
    </MsalProvider>
  </React.StrictMode>
);

msalInstance.addEventCallback((event) => {
  if (event.eventType === EventType.LOGIN_FAILURE) {
    msalInstance.loginRedirect(loginRequest);
  }
});

App.jsx

import React, { useEffect } from 'react';
import { useMsal } from '@azure/msal-react';
import { loginRequest, msalConfig } from './authConfig';

import './App.css';

export default function App() {
  const { instance, accounts } = useMsal();

  useEffect(() => {
    console.log('Checking accounts:', accounts);
    if (accounts.length === 0) {
      instance.initialize(msalConfig); 
      instance.loginRedirect(loginRequest);
    }
  }, [instance, accounts]);

  return <h2>Hello</h2>;
}

authConfig.js

import { LogLevel } from "@azure/msal-browser";


export const msalConfig = {
    auth: {
        clientId: "XXXXXX",
        authority: "https://login.microsoftonline.com/XXXXXX",
        redirectUri: "http://localhost:5173/",
    },
    cache: {
        cacheLocation: "sessionStorage", // This configures where your cache will be stored
        storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
    },
    system: {   
        loggerOptions: {    
            loggerCallback: (level, containsPii) => {   
                if (containsPii) {      
                    return;     
                }       
                switch (level) {
                    case LogLevel.Error:
                        return;
                    case LogLevel.Info:
                        return;
                    case LogLevel.Verbose:
                        return;
                    case LogLevel.Warning:
                        return;
                    default:
                        return;
                }   
            }   
        }   
    }
};


export const loginRequest = {
    scopes: ["User.Read"]
};

export const graphConfig = {
    graphMeEndpoint: "https://graph.microsoft.com/v1.0/me",
};

Uncaught ReferenceError: currentPriorityB is not defined

`<select name="builders" id="selectBuilders">
         <option value="1">Builder 1</option>
         <option value="2">Builder 2</option>
         <option value="3">Builder 3</option>
    </select>



   <div class="flexchild currentPriorityB**1**">1</div>
   <div class="flexchild currentPriorityB**2**">2</div>
   <div class="flexchild currentPriority**B3**">3</div>
const currentPriorityB1 = document.querySelector('.currentPriorityB1')
const currentPriorityB2 = document.querySelector('.currentPriorityB2')
const currentPriorityB3 = document.querySelector('.currentPriorityB3')


let num = 1
console.log(currentPriorityB+`${num})

I’m new in Javascript.
I’m trying to select a div using template literals but it says Undefined.

I am unable to submit my form after adding a javascript file to the html

I created a signup page, but I am unable to submit the form after it has been filled and validated to be correct by the .js file attached to it. Also, I am unable to make the error message that will be displayed when there is a wrong filling on the form disappear when it has been corrected, unless the form is submitted (i.e the success mark only shows when the submit button is clicked)

I created a page that will accept inputs and I used javascript to validate the form before it will be submitted. But after the javascript validates the form, it refuses to submit it to the action attached to the form. I also tried to make the error message which I set using the javascript to disappear when the correct data has been filled, but I was unable to do that.

const form = document.getElementById('form');
const firstname = document.getElementById('firstname');
const lastname = document.getElementById('lastname');
const email = document.getElementById('email');
const dob = document.getElementById('dob');
const phone = document.getElementById('phone');
const username = document.getElementById('username');
const password = document.getElementById('password');
const confpassword = document.getElementById('confpassword');

form.addEventListener('submit', (e) => {
e.preventDefault();

checkInputs();
});

function checkInputs(){
//to get values from inputs
const firstnameValue = firstname.value.trim();
const lastnameValue = lastname.value.trim();
const emailValue = email.value.trim();
const dobValue = dob.value.trim();
const phoneValue = phone.value.trim();
const usernameValue = username.value.trim();
const passwordValue = password.value.trim();
const confpasswordValue = confpassword.value.trim();

if(firstnameValue === '') {
setErrorFor(firstname, 'Please enter your name');
} else {
setSuccessFor(firstname);
}

if(lastnameValue === '') {
setErrorFor(lastname, 'Please enter your name');
} else {
setSuccessFor(lastname);
}

if (dobValue === '') {
setErrorFor(dob, 'Please enter your date of birth');
// } else if (!isValidDate(dobValue)) {
// setErrorFor(dob, 'Please enter a valid date in the format YYYY-MM-DD');
// } else if (isAgeLessThan16(dobValue)) {
// setErrorFor(dob, 'You must be 16 years or older');
} else {
setSuccessFor(dob);
}

if(phoneValue === '') {
setErrorFor(phone, 'Please enter your phone number');
} else if(phoneValue.length < 11) {
setErrorFor(phone, 'Please enter your 11 digits number');
}else {
setSuccessFor(phone);
}

if(usernameValue === '') {
setErrorFor(username, 'Please choose a username');
} else {
setSuccessFor(username);
}

if(passwordValue === '') {
setErrorFor(password, 'Please enter a strong password');
} else if(passwordValue.length < 8) {
setErrorFor(password, 'Your Password must be at least 8 characters');
// } else if(!isStrong(passwordValue)) {
// setErrorFor(password, 'Include letters(Upper and lower cases), numbers and special characters');
} else {
setSuccessFor(password);
}

if (confpasswordValue === '') {
setErrorFor(confpassword, 'Please enter your password');
} else if(confpasswordValue !== passwordValue){
setErrorFor(confpassword, 'Password not match!');
} else {
setSuccessFor(confpassword);
}

if(emailValue === '') {
setErrorFor(email, 'Please fill in your Email address');
} else if(!isEmail(emailValue)) {
setErrorFor(email, 'Please enter a valid Email address');
} else{
setSuccessFor(email);
}

}

function setErrorFor(input, message) {
const formControl = input.parentElement; // .input-part
const small = formControl.querySelector('small');

//add error message inside small
small.innerText = message;

//add form control class
formControl.className = 'input-part error';
return false;
}

function setSuccessFor(input) {
formControl = input.parentElement;
formControl.className = 'input-part success';
return true;
}

function isEmail(email) {
    return /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/.test(email);
}
*{
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
padding: 0;
margin: 0;
box-sizing: border-box;
}

body{
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
margin: auto;
padding: 20px;
background-color: white;
background-size: cover;
}

.logo {
position: absolute;
transform: translateY(-500px);
display: flex;
justify-content: center;
align-items: center;
width: 300px;
max-width: 300px;
}

.logo img {
width: 100%;
}

.signup {
overflow: hidden;
background-color: whitesmoke;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(172, 84, 84, 0.775);
width: 500px;
max-width: 100%;
margin-top: 200px;
}

.signup a {
text-decoration: none;
color: black;
}

.signup a:hover {
text-decoration: underline;
}

.header {
background-color: antiquewhite;
text-transform: uppercase;
font-size: 25px;
font-weight: bold;
padding: 20px 40px;
border-bottom: 1px solid #ffffff;
}

.form {
padding: 30px 40px;
}

.input-part {
margin-bottom: 10px;
padding-bottom: 20px;
position: relative;
}


.input-part label {
display: inline-block;
margin-bottom: 5px;
}

.input-part input {
border: 2px solid rgb(0, 0, 0);
display: block;
width: 100%;
padding: 10px;
font-size: 15px;
font-family: inherit;
background: transparent;
outline: none;
border-radius: 7px;
}

.input-part.success input {
border-color: #2fcd71;
}

.input-part.success i.fa-check-circle {
visibility: visible;
color: #2fcd71;
}

.input-part.error input {
border-color: red;
animation: shake 0.14s 3;
}

.input-part.error i.fa-exclamation-circle {
visibility: visible;
color: red;
animation: shake 0.14s 3;
}

.input-part.error small {
visibility: visible;
color: red;
animation: shake 0.14s 3;
}

@keyframes shake {
0%,100% {translate: 0;}
25% {translate: 8px 0;}
75% {translate: -8px 0;}
}

.btn {
width: 100%;
margin: 25x auto;
display: flex;
align-items: center;
justify-content: center;
background-color: rgb(95, 95, 223);
color: white;
font-size: 18px;
font-weight: bold;
letter-spacing: 2px;
text-transform: uppercase;
border: none;
border-radius: 5px;
padding: 15px 16px;
cursor: pointer;
outline: none;
}

.btn:active {
transform: scale(95%);
}

.input-part i {
visibility: hidden;
position: absolute;
top: 35px;
right: 10px;
}

.input-part small {
visibility: hidden;
position: absolute;
bottom: 0;
left: 0;
}

.login {
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
margin-bottom: 25px;
margin-top: -5px;
font-size: 13px;
}
<!DOCTYPE html>
<!-- removed -->
<body>

<div class="logo">
<a href="../index.html"><img src="../images/icons/_logo.png" alt=""></a>
</div>

<div class="signup">
<div class="header">signup</div>

<form action="signup.php" class="form" id="form" method="post">

<div class="input-part ">
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" placeholder="e.g Yusuf">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error</small>
</div>
<div class="input-part">
<label for="lastname">Last Name</label>
<input type="text" name="lastname" id="lastname" placeholder="e.g Olanrewaju">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error</small>
</div>
<div class="input-part">
<label for="email">Email Address</label>
<input type="email" name="email" id="email" placeholder="[email protected]">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error</small>
</div>
<div class="input-part">
<label for="dob">Birthday</label>
<input type="text" maxlength="10" id="dob" name="dob" placeholder="Enter your Birthday (YYYY/MM/DD)">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small id="dobError">Error</small>

<script defer src="date.js"></script>

</div>
<div class="input-part">
<label for="phone">Phone Number</label>
<input type="text" id="phone" maxlength="11" name="phone" placeholder="Enter Phone Number" oninput="validateNumericInput(this)">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error</small>

<script defer src="maxlenght.js"></script>
<script defer src="phone.js"></script>

</div>
<div class="input-part">
<label for="username">Username</label>
<input type="text" name="username" id="username" placeholder="Choose a Username">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error</small>
</div>
<div class="input-part">
<label for="password">Password</label>
<input type="password" name="password" id="password" placeholder="Enter a strong Password" oninput="checkPasswordStrength(this)">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small id="passwordStrength">Error</small>
</div>
<div class="input-part">
<label for="confpassword">Confirm Password</label>
<input type="password" name="confpassword" id="confpassword" placeholder="Re-enter Password">
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error</small>
</div>

<button class="btn" type="submit" >Signup</button>

</form>

<div class="login">
 <span>Have an account?</span> <a href="../index.html">Login</a>
</div>
</div>
</body>
</html>

Why is this not summing each column’s values on input field change?

Beginner question here:
As the user changes the input value, the column total should change, but I see the following error:
Uncaught TypeError: Cannot read properties of undefined (reading 'getElementsByTagName')

function updateColumnTotals(colIndex) {
  const tableBody = document.getElementById('tableRows');
  const rows = tableBody.getElementsByTagName('tr');
  let total = 0;
  console.log("Column Index: " + colIndex)

  for (let i = 0; i < rows.length; i++) {
    const row = rows[i];
    const cell = row.getElementsByTagName('td')[colIndex];
    const input = cell.querySelector('.size_qty');

    if (input) {
      const value = parseFloat(input.value) || 0;
      total += value;
    }
  }

  // Update the total row in the table for the specified column
  const totalRow = tableBody.getElementsByClassName('column-total-row')[0];
  const totalCell = totalRow.getElementsByTagName('td')[colIndex];
  totalCell.innerHTML = `<strong>${total.toFixed(2)}</strong>`;
}

// Use the DOMContentLoaded event listener to ensure the DOM is fully loaded
document.addEventListener("DOMContentLoaded", function() {
  const sizeQtyInputs = document.querySelectorAll(".size_qty");
  sizeQtyInputs.forEach((input) => {
    input.addEventListener("change", function() {
      const colIndex = Array.from(input.parentNode.parentNode.cells).indexOf(input.parentNode);
      updateColumnTotals(colIndex);
    });
  });
});
<table class="table table-hover table-vcenter" id="dtable">
  <thead>
    <tr>
      <th style="width:4%">L</th>
      <th style="width:4%">XL</th>
      <th style="width:4%">2XL</th>
    </tr>
  </thead>
  <tbody id="tableRows">
    <tr>
      <td><input class="size_qty" type="number" min="0" name="numberInputs" value="50" onchange="updateColumnTotals(1)"></td>
      <td><input class="size_qty" type="number" min="0" name="numberInputs" value="50" onchange="updateColumnTotals(2)"></td>
      <td><input class="size_qty" type="number" min="0" name="numberInputs" value="25" onchange="updateColumnTotals(3)"></td>
    </tr>
    <tr>
      <td><input class="size_qty" type="number" min="0" name="numberInputs" value="40" onchange="updateColumnTotals(1)"></td>
      <td><input class="size_qty" type="number" min="0" name="numberInputs" value="15" onchange="updateColumnTotals(2)"></td>
      <td><input class="size_qty" type="number" min="0" name="numberInputs" value="5" onchange="updateColumnTotals(3)"></td>
    </tr>

  </tbody>
  <tbody>
    <tr>
      <td class="column-total-row" align="middle"><strong>10</strong></td>
      <td class="column-total-row" align="middle"><strong>0</strong></td>
      <td class="column-total-row" align="middle"><strong>600</strong></td>
      <td class="total_title" align="middle"></td>
      <td id="totalValue" class="total"><strong></strong></td>
    </tr>
  </tbody>
</table>

JS fetch to python request

I am trying to use an API but all the examples are in JS, and my project is in python.

Here is the sample code they gave me.

const request = await fetch("https://api.tiktokenizer.dev/openai", {
  headers: { Authorization: "Bearer <OPENAI_API_KEY>" },
  method: "POST",
  body: JSON.stringify({
    email: "<APP_USER_EMAIL>",
    appId: "<APPID>",
    developerKey: "<KEY>",
    model: "gpt-3.5-turbo",
    messages: [
      {
        role: "user",
        content: "Hey ChatGPT, what's the capital of Portugal?",
      },
    ],
  }),
});
const response = await request.json();

I tried to solve this on my own with this code.

import requests

url = "https://api.tiktokenizer.dev/openai"
headers = {"Authorization": "Bearer <OPENAI_API_KEY>"}
data = {
    "email": "<APP_USER_EMAIL>",
    "appId": "<APPID>",
    "developerKey": "<KEY>",
    "model": "gpt-3.5-turbo",
    "messages": [
      {
        "role": "user",
        "content": "Hey ChatGPT, what's the capital of Portugal?",
      },
    ],
}

response = requests.post(url=url, headers=headers, json=data)

print(response.json())

With the above code I filled in all the needed info but I got this error.

{'error': 'Unexpected token o in JSON at position 1'}

What should happen is I get something like this back.

{
  message: "The capital of Portugal is Lisbon.",
  usage: {
    totalTokens: 25,
  },
  newUserCreated: false,
}

Pass by copy of reference may be causing unexpected behavior [closed]

I am trying to build a BabylonJS app inside of ObservableJS. I’ve already made an ObservableJS page with a working BabylonJS app inside, just by writing BabylonJS code inside a code cell. So I know that in principle this works. To get it working I included an HTML canvas element,

<canvas id="lib"></canvas>

and then in an OJS cell, used a jQuery to get the canvas and then write a BabylonJS app with it.

However, I’m also trying to abstract a bunch of the functions that I will be using over and over, into a library of helper functions. I’ve put them into an NPM module and published it has babylon-helper-lib. In particular, one of the helper functions is the following:

export let twodgrid = function(scene: Scene, width=20, height=20, name="box") {
    const box = MeshBuilder.CreateBox(name, {width:width,height:height,depth:.2}, scene);
    
    const boxmat = new GridMaterial(`${name}_mat`, scene);
    boxmat.majorUnitFrequency = 2;
    boxmat.useMaxLine = false;
    
    box.material = boxmat;

    return {box, boxmat};
}

I’ve tested this function outside the context of OJS and can confirm that it works as intended. Basically it draws a box with some styling.

Then in a webpage with OJS, I have included a canvas element with id lib:

{
    const LIB = await import("https://esm.sh/babylon-helper-lib");

    const bag = LIB.init("#lib");
    const scene = bag.scene;
    const planebag = LIB.twodgrid(scene);
    // console.log(planebag.box);

    bag.engine.runRenderLoop( () => {
        scene.render();
    });
}

Again this is code that I’ve tested outside of OJS and can confirm that it works as intended.

However, when run inside an OJS cell, I don’t get any console errors in the web browser, but it simply does not draw the box.


My best guess about why this might be happening, is that JavaScript is pass-by-copy-of-reference. So although I am passing the scene into CreateBox, maybe somewhere along the way the scene is getting copied and the box is created on the copy. I wouldn’t have thought so, because it should just be mutating the properties of the scene at the referenced address, so I would think that scene is the scene being mutated. But it’s still my best guess. I tried checking the docs on how CreateBox works, but I couldn’t find the source code and the given description doesn’t help me to understand how it works.

On the other hand, it just now occurs to me that actually my helper library is written in TypeScript, and compiled to JavaScript. But then again I’m pretty sure TypeScript is also pass-by-reference, so I’m not sure that explains anything.

Vue components displayed side by side despite each being se to 100% of window width

Vue components have width set to 100vw each.Despite this,they still display side by side as if the width:100vw was ignored.I have screenshot of what the website looks like.All I want is the 2 components to be displayed as Form on top and Main right below.
From component and Main component (both children of App component) are displayed side by side instead of Form on top and Main below

Form.vue

div
    {
        position:relative;
        margin:0;
        width:100%;
        text-align:center;
        height:75vh;
    }

    form
    {
        margin-top:0;
        padding:8px 0;
        margin:5px;
    }

Main.vue

div
    {
        width:92.5%;
        position:static;
        height:auto;
        overflow:auto;
        text-align: center;
        align-items: center;
        justify-content: space-evenly;
    }

I tried with every type of position but no change whatsoever.

Find JSON strings in big string – transform bigger string

There is this clever regex which is able to find all (kinda) valid json strings in the bigger string for PHP.

https://regex101.com/r/U6szh5/1

I’m looking for something like this for javascript.
I can’t translate it directly because javascript doesn’t seem to support recursion in regex.

Is there any library which helps with finding them?

Ideally I’m looking for solution which would allow me to iterate through the bigger string and to do something with those found strings – like format them differently.

const formattedString = myBigString.replace(magic_regex, (foundJsonSubstring) => {

    // example of doing "something" in this case formatting
    return JSON.stringify(foundJsonSubstring, null, 4);

})

trigger reflow but element value not updated

if (char >= 0x20 && char <= 0x7f) {

  if (data.charAt(i) == '*' && countString($('#row1').val(), '*') < qtyStars) {
    write(data.charAt(i))
    advance()
    reflow(document.getElementById('row1'))
  }
}

function reflow(elt) {
  console.log(elt.offsetHeight);
}

function countString(str, letter) {
  let count = 0;

  // looping through the items
  for (let i = 0; i < str.length; i++) {

    // check if the character is at that position
    if (str.charAt(i) == letter) {
      count += 1;
    }
  }
  return count;
}

  const Lcd = callback => {
    // https://dawes.wordpress.com/2010/01/05/hd44780-instruction-set/
        var display
        var pos
        var cmd = false
        var cursor = false
        var timer
        const show = () => {
            callback(display)
        }
        const write = char => {
            if (char >= ' ') {
                var row, col
                if (pos < 16) {
                    row = 0
                    col = pos
                } else {
                    row = 1
                    col = pos - 64
                }
                var previousChar = display[row].substr(col, 1)
                display[row] = display[row].substr(0, col) + char + display[row].substr(col + 1)
                return previousChar
            }
        }
        const advance = () => {
            pos++
        }

so this is part of a WebSocket implementation. The idea is am hacking a web interface to control some electronics which controls an alarm panel.

when you use the keypad, you can type into element row1. When you click on a number on the keypad, it gets sent off to the backend to control a burgular alarm panel. Then row1 gets updated with an asterisk. One asterisk per digit.

However the alarm panel sends multiple messages to update its own display. Dont ask me why stupid in my opinion. Therefore I need logic to ignore the extra messages so I dont get many many asterisks per key press.

The logic doesn’t work because the dom is Asyncronous. The first time it runs the value of $('#row1').val() is empty which is correct. but the second web socket message comes along and it’s still an empty string so i get infinite number of asterisks until the alarm panel times out then updates the display to the current date and time.

As you can see I tried to do a reflow but the value of row1 apparently doesn’t get updated.

Is what am trying to archieve even possible? I am using latest version of Firefox but wud like it to be cross browser compatible if possible.

window.getSelection() behaving weirdly

I am currently making a little chat app and I’ve wanted to make selected text bold or italic when pressing a button.
It never really worked and when debugging it I saw that it only outputs selected text when the selected text is in the button in which the function is called.
So basically it only works when I select the “Bold” in the button.

function test(){
    const selectedText = window.getSelection().toString();
    if (selectedText) {
        console.log(selectedText);
    }
}
<div class="formattingButton" id="boldButton" onclick="test()">Bold</div>

JSFiddle: https://jsfiddle.net/c7000/kjbmswcg/

I’ve tried window.getSelection().toString() in the console and it worked perfectly fine.
I’ve also tried using document.getSelection() but it of course didn’t work out as well.
Tried fixing it for probably 3 hours reading through documentations, asking ai, watching tutorials, etc.

why is ID undefined and how do I define it?

Stars.js

export default class Stars extends React.Component{
    constructor(props){
        super(props)
        this.state = {
            starLevel: 0
        }
        this.handleStars = this.handleStars.bind(this)
    }

    handleStars(props){
        if (`stars-${props.id}` > 0 && `stars-${props.id}` < 6){
            this.setState.starLevel = `stars-${props.id}.value`
        }
    }

    render(){
        return(
            <div>
                <h3>{this.state.starLevel}</h3>
                <input id={`stars-${this.props.movie.id}`}></input>
                <button onClick={this.handleStars}>Submit Stars</button>
            </div>
        )
    }
}

movielist.js

return(
            <div className="container">
                {movies.map((movie) => (
                    <div>
                        <Movie key={movie.id} movie={movie} title={movie.title} image={movie.image} description={movie.description} id={movie.id} />
                        <Stars id={movie.id}/>
                    </div>
                ))}
                
            </div>

In the input script in render()/stars.js, the id keeps coming up as undefined. I tried props.id, this.props.movie.id, movie.id, id. nothing works. I’m trying to get it to read the value of the input and set the starlevel to it. My full code is available for those who need it.