How can I remove line breaks from lines that only start with a specific character in JavaScript?

I am trying to remove line breaks from a string that only begin with a specific character and am having trouble finding a solution. In my scenario I’m am trying to remove all line breaks where the line starts with a quotation mark. Heres an example:

Input:

const str = `
    Test
    "How" +
    "Can" +
    "I" +
    Do This?
`;

Desired Result:

const desiredResult = `
    Test
    "How" + "Can" + "I"
    Do This?
`;     

I’ve only been able to find a way to remove all line breaks. Still unable to find a solution to only remove them if a conditional is met.

Uncaught TypeError in Vanilla Javascript

I’m getting an uncaught type error in my console when I click my button, I was wondering why this is happening? It says null but I thought its pointing to my button with id button. Kudos to anyone who can shed some light on what I am doing wrong

ERROR:

main.js:22 Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')
    at main.js:22:5
(anonymous) @ main.js:22

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="main.css">
    <script src="main.js"></script>
</head>
<body>
    <main>
        <div class="container">
          <h2>background color : <span class="color">#f1f5f8</span></h2>
          <button class="btn btn-hero" id="btn">click me</button>
        </div>
    </main>
</body>
</html>

JS:

var hexDisplay = document.getElementById("hex-display");

function colorFlipper() {
  var chars = "0123456789ABCDEF"; // Defining HEX Characters
    var result = ""; // Having an empty string to store the result
    for (var i=0; i<6; i++) {       // A loop, that runs until i is smaller than 6, so.. 6 times
        var num = Math.floor(Math.random() * chars.length);   // It defines a variable num, which generates a random number between 0 and the length of our HEX Characters string
        result += chars.substring(num,num+1); // The result then takes that number and the next one, and extracts a character in our HEX Character string that is in between those 2 numbers 
    }
    hexDisplay.textContent = "#" + result; // Then we display the result and set the background color
  document.body.style.backgroundColor = "#" + result;
}

CSS:

@import url('https://fonts.googleapis.com/css2?family=Ranchers&display=swap');

main {
  min-height: calc(100vh - 3rem);
  display: grid;
  place-items: center;
}
.container {
  text-align: center;
}
.container h2 {
  background: #222;
  color: #fff;
  padding: 1rem;
  border-radius: 0.25rem;
  margin-bottom: 2.5rem;
}
.color {
  color: hsl(205, 78%, 60%);
}

.btn-hero {
  font-family: "Ranchers", sans-serif;
  text-transform: uppercase;
  background: transparent;
  color: #222;
  letter-spacing: 0.1rem;
  display: inline-block;
  font-weight: 700;
  transition: all 0.3s linear;
  border: 2px solid #222;
  cursor: pointer;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
  border-radius: 0.25rem;
  font-size: 1rem;
  padding: 0.75rem 1.25rem;
}
.btn-hero:hover {
  color: #fff;
  background: #222;
}

I’ve tried googling and searching through the code and can’t find what is wrong

Error 403 with POST using ActiveCampaign API- trying to add contact, valid API key

enter image description here

From my understanding by Googling the 403 error means the API key is right but access is forbidden? But I’m not really 100% sure what that means or how to resolve it.

Below is my code that triggers when I press a button (I’ve manually added the contact data for testing).

Any help is greatly appreciated.

My code:

$.ajax({
      async: true,
      crossDomain: true,
      url: 'https://myactivehost.api-us1.com/api/3/contacts',
      method: 'POST',
      headers: {
        accept: 'application/json',
        'content-type': 'application/json',
        'Api-Token': 'myAPIkey'
      },
      processData: false,
      data: '{"contact":{"email":"[email protected]"}}',
      success: function() {
        console.log('success');
      },
      error: function() {
       console.log('failed'); 
      }
    });

Is there a reason why my API response success block is not executing my function calls?

Relatively new to web development and I am currently taking a course which builds a face recognition application using React and Clarifai API. The application has a search box where the user pastes an image URL, which is then supplied to the Clarifai API. I have created a function called ‘calculateFaceLocation’ that should accept the API response and perform an action on. My issue is that I am receiving the required response from the Clarifai API (Which I can confirm by console logging ‘response’ in my success block) but when I call ‘this.calculateFaceLocation(response)’ it appears that my function is not being excecuted. I seems like it has to be something trivial that I am missing but any help would be appreciated. Just to note I have removed my personal API key from the below code block

import React, { Component } from 'react';
import ParticlesBG from './components/Particles/Particles.js';
import Navigation from './components/Navigation/Navigation.js';
import Logo from './components/Logo/Logo.js';
import Rank from './components/Rank/Rank.js';
import ImageLinkForm from './components/ImageLinkForm/ImageLinkForm.js';
import FaceRecognition from './components/FaceRecognition/FaceRecognition.js';
import Clarifai from 'clarifai';

window.process = {
    env: {
        NODE_ENV: 'development'
    }
}

const app = new Clarifai.App({
  apiKey: " "
});

class App extends Component {
  constructor() {
    super()
    this.state = {
      input: "",
      imageURL:"",
      box:{}
    }
  }

  calculateFaceLocation = (data) => {
    console.log(data);
  };

  onInputChange = (event) => {
    this.setState({input: event.target.value});
  };

  onButtonClick = () => {
    this.setState({imageURL: this.state.input});
    app.models.predict({ 
                 id: 'face-detection', 
                 name: 'face-detection', 
                 version: '6dc7e46bc9124c5c8824be4822abe105', 
                 type: 'visual-detector', 
             },
             this.state.input
            )
    .then(
      function(response) {
        this.calculateFaceLocation(response);
      },
      function(err) {
        console.log(err);
      }
    );
  };

  render() {
    return (
      //My JSX code is in here but not required to show.
}

export default App;

Tried to console.log(response) in my response success block which worked and confirmed response was received. However, any function I attemt to run withing the success block appears not to excecute.

Passing functions as function parameters in JavaScript

im trying to change functions that are called in if else condition of handleIntersect function through parameters of called observeElement function like this:

window.addEventListener("load", (event) => {
  observeElement('.menu-nav-area', 1st funtion to call, 2nd function to call );
  observeElement('.menu-quick-area', 3rd funtion to call, 4th function to call );
}, false);

Can’t figure out how to pass these params as functions, so they are called instead isObserved and isNotObserved functions in handleIntersect.

Here is the code, that works, but calls only functions specified in handleIntersect:

window.addEventListener("load", (event) => {
  observeElement('.menu-nav-area');
}, false);

function observeElement(element) {
  let target = document.querySelectorAll(element);
  let observer;
  createObserver();

  function createObserver() {
    let options = {
      root: null,
      rootMargin: '0px',
      threshold: 1.0
    }
    observer = new IntersectionObserver(handleIntersect, options);
    target.forEach(function (k){
    observer.observe(k);
    });
  }

  function handleIntersect(entries, observer) {
    entries.forEach(entry => {
            document.querySelectorAll(element).forEach(function (e) {
      if (entry.intersectionRatio === 1) {
        isObserved();
    } else {
        isNotObserved();
    }
            });
    });
  }

  
  
  

  
  function isObserved() {
            console.log('menu is up');
  }
  function isNotObserved() {
            console.log('menu is down');
  }
}

Can it be done?
Thanks!

Discord.js Voice Not Playing Audio While AudioPlayerStatus is Playing

I can’t seem to figure out why my bot isn’t playing audio. I have installed all the necessary dependencies and below is the dependency log and code. Incase it was the audio files, I tried different paths and youtube links and nothing seems to be working.

The block of code is confirmed getting ran as console logs but no audio comes through. Bot joins vc with no issue.

Core Dependencies
- @discordjs/voice: 0.14.0
- prism-media: 1.3.4

Opus Libraries
- @discordjs/opus: 0.8.0
- opusscript: 0.0.8

Encryption Libraries
- sodium-native: 4.0.1
- libsodium-wrappers: 0.7.11
- tweetnacl: not found

FFmpeg
- version: 5.0.1-essentials_build-www.gyan.dev
- libopus: yes

voiceStateUpdate.js event file below

const { Events } = require('discord.js');
const { joinVoiceChannel, AudioPlayerStatus } = require('@discordjs/voice');




module.exports = {
    name: Events.VoiceStateUpdate,
    async execute(oldState, newState) {

        //Check if muting / unmuting
        //Check if deafening / undeafening
        //Check if channel Id is null i.e. if I'm leaving not arriving
        if (newState.selfMute == oldState.selfMute && newState.selfDeaf == oldState.selfDeaf && newState.channelId != null && newState.member.user.id == '188765194246291468'){
            console.log("Syan has entered");

            const fs = require('node:fs');
            const path = require('node:path');

            const seinPath = path.join(__dirname, '../seinfeld_bites');
            const seinFiles = fs.readdirSync(seinPath).filter(file => file.endsWith('.mp3'));

            const { createAudioResource } = require('@discordjs/voice');

            //const { generateDependencyReport } = require('@discordjs/voice');

            const connection = joinVoiceChannel({
                channelId: newState.channelId,
                guildId: newState.guild.id,
                adapterCreator: newState.guild.voiceAdapterCreator,
            });

            const { createAudioPlayer } = require('@discordjs/voice');

            const player = createAudioPlayer();

            const resource = createAudioResource(seinFiles[1]);
            player.play(resource);
            connection.subscribe(player);

            player.on(AudioPlayerStatus.Playing, () => {
                console.log('Playing');
            })

            //console.log(generateDependencyReport());

            //console.log(connection);
        }

    },
};

I’ve gone over all the dependencies, tried different audio resources and tried it on different servers. Any help would be fantastic. I have the GUILD_VOICE_STATES in my index.js and the bot is joining vc so I don’t think it could be that.

Javascript, Vue: stopwatch is too slow, seconds elapsed too low (code fiddle included)

I have code that starts a stopwatch, updates milliseconds variable every 1 millisecond, and displays the number of hours, minutes, seconds, and milliseconds elapsed.

However the displayed elapsed seconds aren’t realistic – 10 seconds can pass, while the stopwatch would only show 3 seconds elapsed

enter image description here

This it the code:

<template>
  <div>
    {{ this.duration(this.milliseconds) }}
  </div>
</template>

<script>
export default {
  name: "App",
  components: {},

  data() {
    return {
      timeValue: String,
      milliseconds: Number,
    };
  },

  created() {
    this.milliseconds = 0;

    setInterval(() => {
      this.milliseconds++;
    }, 1);
  },

  methods: {
    duration(millisecondsData) {
      let milliseconds = millisecondsData % 1000;
      millisecondsData = (millisecondsData - milliseconds) / 1000;

      let seconds = millisecondsData % 60;
      millisecondsData = (millisecondsData - seconds) / 60;

      let minutes = millisecondsData % 60;
      let hours = (millisecondsData - minutes) / 60;

      return [
        this.format(hours),
        this.format(minutes),
        this.format(seconds),
        this.format(milliseconds),
      ].join(":");
    },

    format(n) {
      return (~~n).toString().padStart(2, "0");
    },
  },
};
</script>

Code fiddle: https://codesandbox.io/s/little-forest-tckk57?file=/src/App.vue:0-964

I’ve also tried running pure JS code in an IDE, and it runs fine (the seconds elapsed match real time), however running the same JS code inside browser console shows the same result as the Vue code.

I cant get my table to update using tabledit.js

HTML and PHP

I have tried just making a simple editing table for people to easily edit colums and I am using newest version of tabledit and the form just wont post to my update file.

<table id = "data_table" class="table table-bordered table-striped"  >
    <thead>
        <tr>
            <th scope="col">#</th>
            <th scope="col">Item Name</th>
            <th scope="col">Originl Barcode #</th>
            <th scope="col">Compnay Name</th>
            <th scope="col">Location</th>
            <th scope="col">Details On Item</th>
            <th scope="col">Barcode Image</th>
            <th scope="col">inventory Count</th>
            <th scope="col">Labeled Barcode</th>
            <th scope="col">Actions</th>

        </tr>
    </thead>   
<?php
include 'serverconn.php';
$itemid = '';
$sql = "SELECT id, ItemName, ItemBarcode, CompanyName, OurBarcode, 
                DetailsOnItem, barcodeimg, count, combindedBarcode 
        FROM items";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
    $itemid = $row['id'];    
?>
    <tbody>
    <tr id="<?php echo $row['id']; ?>" >
        <th> <?php echo $row['id']; ?></th>
        <td data-column='ItemName' id="ItemName"><?php echo $row['ItemName']; ?></td>
        <td data-column='ItemBarcode' id="ItemBarcode"><?php echo $row['ItemBarcode']; ?></td>
        <td data-column='CompanyName' id="CompanyName"><?php echo  $row['CompanyName']; ?></td>
        <td data-column='OurBarcode' id="OurBarcode"><?php echo $row['OurBarcode']; ?></td>
        <td data-column='DetailsOnItem' id="DetailsOnItem"><?php echo $row['DetailsOnItem']; ?></td>
        <td data-column='barcodeimg' id="barcodeimg"><image src='<?php echo $row['barcodeimg']; ?>'></img></td>
        <td data-column='count' id="count"><?php echo $row['count']; ?></td>
        <td data-column='combindedBarcode' id="combindedBarcode"><?php echo $row['combindedBarcode']; ?></td>
      </tr> 
<?php 
    } 
?>
    </tbody>
  
<?php 
} else { 
    echo 'No results found';
}
$conn->close();
?>
</table>`

Java Script File

$('#data_table').Tabledit({
    url:'update.php',
    editButton: false,
    deleteButton: false,
    inputClass: 'form-control input-sm',
    eventType:'click',      
    identifier: false,  
    autoFocus: true,
    columns:{
       identifier:[0, 'id'], editable: [[1, 'ItemName'], [2, 'ItemBarcode'], 
                    [3, 'CompanyName'], 
                    [4, 'OurBarcode'], 
                    [5, 'DetailsOnItem'], 
                    [7, 'count'],
                ]
        },  
        onSuccess:function(data, textStatus, jqXHR){
        },
});

I have just been looking up things to fix the problem. Its not saving my edits. I will share what my update file looks like rq

<?php  
//action.php
$connect = mysqli_connect('localhost', 'root', '', 'database_solarmax');

$input = filter_input_array(INPUT_POST);

$itemname = htmlspecialchars(mysqli_real_escape_string($conn, $input['ItemName']));

$itembarcode = htmlspecialchars(mysqli_real_escape_string($conn, $input['ItemBarcode']));

$companyname = htmlspecialchars(mysqli_real_escape_string($conn, $input['CompanyName']));

$ourbarcode = htmlspecialchars(mysqli_real_escape_string($conn, $input['OurBarcode']));

$detailsonitem = htmlspecialchars(mysqli_real_escape_string($conn, $input['DetailsOnItem']));

$inventoryCount = htmlspecialchars(mysqli_real_escape_string($conn, $input['count']));

if($input["action"] === 'edit')
{
    $query = "UPDATE `items` 
                SET `ItemName`= '  ".$input['ItemName']. "', 
                    `ItemBarcode` ='  ".$input['ItemBarcode']."  ', 
                    `CompanyName`=' ".$input['CompanyName']."  ', 
                    `OurBarcode` = '".$input['OurBarcode']."', 
                    DetailsOnItem='".$input['DetailsOnItem']."',  
            WHERE id= '".$input['id']."'";


    mysqli_query($connect, $query);
}
if($input["action"] === 'delete')
{
    $query = "DELETE FROM items 
                WHERE id = '".$input["id"]."' ";
    mysqli_query($connect, $query);
}
echo json_encode($input);
?>

But I have tried a numerious amount of things from changing my php update file and also messed with the javascript just wont auto save like it supposed to. :/

How can I get Graal.js to handle a custom numeric Java type?

To dive in, we have an app where we have had Nashorn embedded.
With 17 I’m replacing it with GraalJS and there are some issues.
The current one is where I want GraalJS treat a custom class as an int (or double)for the purpose of basic arithmetic (+,- and so on). Right now, Graal.js can’t make head or tails of it so it just calls the toString method which isn’t optimal.
With Nashorn it sufficed to extend java.lang.Number but that doesn’t seem to work here.
I’ve looked in the interpreter code (I can’t find any relevant docs) and that shows that Graal.js can handle the various java.lang classes but I can’t figure out how to make it use custom classes.

The custom class has a lot of other func as well so I can’t throw it away and we have a large installed base of JS code that uses the custom class(es).

The JS code : function(e){print(e.id + 1)} where e is an object and id is a custom type (JSNumber that extends Number).

With Nashorn this worked (ie if id = 1, the result would be 2).
But, id is treated like a String and we get string concatenation instead, the result is 12.

Any links, hints or tips welcome!

Chevrotain CST to string

How can I reconstruct the original text from a Chevrotain CstElement or CstNode object? (These objects represent a concrete syntax tree.)

The documentation suggests that this should be possible, as it says the following about differences between ASTs and CSTs:

the exact original text can not always be re-constructed from the AST.

JAvascript nested IF within an IF within an IF [closed]

I am having an issue getting the results I want concerning a nested if. I am accustomed to being able to set an if statement based on a previous if statement. Is this not possible in JavaScript?

I have the following code and am not getting the desired response. I want to set the variable PFF to a string based on several conditions. If the filename has a string in the name then check if a the value of another variable is P/F do something different for each occurrence. Then return to the first if and if is NOT then perform another if and and so on.

I have the code below that I am working with:

            var PFF

            if (file.indexOf('string of file variable') >= 0) {
                if (result_P_F = 'P') {
                    PFF = pVEN + file;
                } else {
                    PFF = fVEN + file;
                }
            } else
            if (CustomerCode = 'A') {
                if (result_P_F = 'P') {
                    if (TYPE = 'X') {
                        PFF = 'p5' + file;
                    } else {
                        PFF = 'p4' + file;
                    }
                } else if (TYPE = 'X') {
                    PFF = 'f5' + file;
                } else {
                    PFF = 'f4' + file;
                }
            }  else
            if (CustomerCode = 'B') { 
                if (result_P_F = 'P') { 
                    if (TYPE = 'X') {
                        PFF = 'pC5' + file;
                    } else {
                        PFF = 'pC4' + file;
                    }
                } else if (TYPE = 'X') {
                        PFF = 'fC5' + file;
                    } else {
                        PFF = 'fC4' + file;
                }
            }

Please let me know your solution.