Regex find first instance of word after keyword

I am trying to match the first instance of a word after a certain word has been listed. There could be whitespace and many lines.

Here is an example of desired outcomes with the requirement of the word “before” coming before the word “after” and then only matching the first instance.

beforeafter - match

before after - match

beforeafterafter - matches only first after

beforeafter something after - matches only first after

before
(whitespace)
after - match

befafter -no match

before bar foo baz after - match

I believe I am close with this regex

(?<=(before([^after]*)))(after) which utilizes a positive lookbehind.
But the [^after] negates the characters in the set rather than the whole word itself (which leads to the final example above not matching).

It’s almost like I want a “positive look behind” (aka look for “before”) and then between that and the word I desire, I want a negative look behind of my initial word (i.e. “after”).

When I tried that, I also got something close but not quite: (?<=(before(.|s)*(?<!(after))))after. This results in wrongly selecting an “after” that is not connected to the initial after.

Disable tooltip effect in specific pointer (echarts gauge)

I have this code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/5.3.0/echarts.min.js"></script>
  <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
  <title>Gauge Chart</title>
</head>
<body>

<div id="gaugeChartIncDropdown1" style="width: 250px; height: 250px; margin: 0 auto; margin-top: 10%"></div>
<input type="range" id="sizecluslider" min="0" max="100" step="1" value="50" style='position:absolute; top: 60%; left: 41.5%; cursor: pointer; width: 100px; accent-color: #008cba;'>
<div id="valor1" style="display: none;">123</div>

<script>
  const gaugeChartIncDrop1 = echarts.init(document.getElementById('gaugeChartIncDropdown1'));
  
  function updateGaugeDropIncFinal1(value, value2, maxValueInputSize1, customValue) {
    option = {
    tooltip: {
    show: true,
    trigger: 'item',
    formatter: function(params) {
      return params.name + ': ' + params.value + '%' + '<br>' + 'Custom Value: ' + customValue;
    }
    },
      series: [
        {
          type: 'gauge',
          min: 0,
          max: 100,
          splitNumber: 10,
          radius: '80%',
          axisLine: {
            lineStyle: {
              color: [[1, '#008cba']],
              width: 3
            }
          },
          splitLine: {
            distance: -10,
            length: 10,
            lineStyle: {
              color: '#008cba'
            }
          },
          axisTick: {
            distance: -10,
            length: 10,
            lineStyle: {
              color: '#008cba'
            }
          },
          axisLabel: {
            distance: -25,
            formatter: function (value) {
              return value.toFixed(0) + '%';
            },
            color: '#008cba',
            fontSize: 11,
            fontFamily: 'Lato'
          },
          anchor: {
            show: true,
            size: 20,
            itemStyle: {
              borderColor: '#020202',
              borderWidth: 2
            }
          },
          pointer: {
            offsetCenter: [0, '10%'],
            icon: 'path://M2090.36389,615.30999 L2090.36389,615.30999 C2091.48372,615.30999 2092.40383,616.194028 2092.44859,617.312956 L2096.90698,728.755929 C2097.05155,732.369577 2094.2393,735.416212 2090.62566,735.56078 C2090.53845,735.564269 2090.45117,735.566014 2090.36389,735.566014 L2090.36389,735.566014 C2086.74736,735.566014 2083.81557,732.63423 2083.81557,729.017692 C2083.81557,728.930412 2083.81732,728.84314 2083.82081,728.755929 L2088.2792,617.312956 C2088.32396,616.194028 2089.24407,615.30999 2090.36389,615.30999 Z',
            length: '125%'
          },
          title: {
            fontSize: 11,
            fontWeight: 'bold',
            fontFamily: 'Lato'
          },
          detail: {
            valueAnimation: true,
            width: 50,
            height: 20,
            fontSize: 14,
            precision: 1,
            formatter: '{value}%',
            fontFamily: 'Lato',
            borderWidth: 2,
            padding: [0, 0, 0, 0],
            backgroundColor: '#92a192',
            borderRadius: 8,
            color: '#020202'
          },
          data: [
            {
              value: value,
              name: 'Segm. 1',
              title: {
                color: '#008cba',
                offsetCenter: ['0', '20%']
              },
              detail: {
                offsetCenter: ['0', '40%'],
                borderColor: '#008cba'
              },
              itemStyle: {
                color: '#f00',
                borderWidth: 1,
                borderColor: '#020202'
              }
            },
             {
    value: value2, 
    itemStyle: {
      color: 'cyan',
      borderWidth: 1,
      borderColor: '#020202'
    },
    pointer: {
      offsetCenter: [0, '0%'],  // Ajuste conforme necessário
      icon: 'path://M-20,0 L0,-20 L20,0 L0,20 Z'  // Ajuste o caminho do ícone conforme necessário
    }
  }
          ]
        },
        {
          type: 'gauge',
          min: 0,
          max: 100,
          splitNumber: 6,
          axisLine: {
            lineStyle: {
              color: [[1, '#858383']],
              width: 3
            }
          },
          splitLine: {
            distance: -2,
            length: 10,
            lineStyle: {
              color: '#858383'
            }
          },
          axisTick: {
            distance: -2,
            length: 10,
            lineStyle: {
              color: '#858383'
            }
          },
          axisLabel: {
            distance: 5,
            fontSize: 11,
            color: '#858383',
            formatter: function (value) {
              return value.toFixed(0) + '%';
            }
          },
          pointer: {
            show: false
          },
          title: {
            show: false
          },
          anchor: {
            show: true,
            size: 14,
            itemStyle: {
              color: '#f00'
            }
          }
        }
      ]
    };
    
    gaugeChartIncDrop1.setOption(option);
  }
  
  function updateIncDropFunc1() {
    let value = Number($('#sizecluslider').val());
    let maxValueInputSize1 = Number($('#maxValueInputSample1').val());
    let customValue = Number($('#valor1').text())
    
    updateGaugeDropIncFinal1(value, maxValueInputSize1, customValue);
  }
  
  updateIncDropFunc1();
  
  $('#sizecluslider, #maxValueInputSample1').on('input', function() {
    updateIncDropFunc1();
  });
  
    gaugeChartIncDrop1.on('mouseenter', { dataIndex: 0 }, function(params) {
    $(this).css('pointer-events','none');
  });
  </script>

</body>
</html>

I need to disable hover only for the first pointer (red), but leave the other pointers enabled for hover in order for a tooltip to appear for them. In other words, when you hover the mouse over the red pointer, the tooltip should not appear, but only for the rest of the pointers present on the gauge.

I try this:

emphasis: {
  silent: true,
  disable: true
}

But not work.

How to update the changes in the field of a sub schema as soon as the data is entered in the same field in main Schema in mongoDB

This is my sub schema.

const bioSchema = new Schema({
  full_name: { type: String, default: "" },
  headline: { type: String, default: "" },
  highlight: { type: String, default: "" },
});

This is my user Schema or main Schema.

var UserSchema = new Schema(
  {
    full_name: { type: String, default: "" },
    email: { type: String, default: "" },
    phone: { type: String, default: "" },
    password: { type: String, default: "" },
    bio: bioSchema,
  }
);

I want the full_name field in bioSchema to get updated immediately with the same value as soon as the full_name field in the user Schema is changed and vice versa. Please help me with this problem.

HTML components not loading jquery lazy component

I am building a small website for myself and I am using almost vanilla HTML, CSS + JS. I have a footer that I want to reuse across all the HTML pages.

So instead of copying and pasting everywhere every time I make a modification, I decided to make some HTML components.

The issue is, I can’t seem to be able to use the lady loading jquery script. Sometimes, some of my images might take a while to load so I am trying to use the lazy loading as a small delay.

However, the only thing being displayed is the “src” tag from the <img> element.

Please see here some test files I put together:

test.html
https://pastebin.pl/view/25c07265

test.js
https://pastebin.pl/view/df9d3e50

Sorry for the pastebin links, I have no idea why stackoverflow doesn’t let me just use normal code blocks. It keeps telling me it’s formatted wrong. I guess the backticks are throwing it off

I am really not sure what I’m missing here

I tried moving the script tag for the layz load around but that didn’t help…

Why is my onClick function adding two entries to mySQL database?

I’ve been learning how to use a React.js front end combined with a PHP server backend and making a simple project that has to do with adding, editing, and displaying recipes in a recipe-book database. My AddRecipe.js almost works, but there’s one big problem where everytime I click the “Add Recipe” button, it adds two entries into my database: one empty and one with all parameters correctly inside. I’ve tried everything that I know but I don’t know what my problem is. This is what is added when I press my “Add Recipe” button:(https://i.stack.imgur.com/2TmAH.png) Here is my code

//AddRecipe.js
import React, { useState, useEffect, useRef } from 'react';
import axios from 'axios';

const AddRecipe = () => {
  const [title, setTitle] = useState('');
  const [ingredients, setIngredients] = useState('');
  const [instructions, setInstructions] = useState('');
  const isSubmittingRef = useRef(false);

  useEffect(() => {
    console.log('Rendering AddRecipe component');
  }, []);

  const addRecipe = () => {
    isSubmittingRef.current = true;
    console.log('Data to be sent:', { title, ingredients, instructions });
    axios
      .post('http://localhost/add_recipe.php', {
        title,
        ingredients,
        instructions,
      })
      .then((response) => {
        console.log('Successful response:', response.data);
      })
      .catch((error) => {
        console.error('There was an error!', error);
      })
      .finally(() => {
        isSubmittingRef.current = false;
      });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!isSubmittingRef.current) {
      addRecipe();
    }
  };

  return (
    <div>
      <h2>Add Recipe</h2>
      <form onSubmit={handleSubmit}>
        <label>Title:</label>
        <input type="text" value={title} onChange={(e) => setTitle(e.target.value)} />

        <label>Ingredients:</label>
        <textarea value={ingredients} onChange={(e) => setIngredients(e.target.value)}></textarea>

        <label>Instructions:</label>
        <textarea value={instructions} onChange={(e) => setInstructions(e.target.value)}></textarea>

        <button type="submit" disabled={isSubmittingRef.current}>
          Add Recipe
        </button>
      </form>
    </div>
  );
};

export default AddRecipe;
#add_recipe.php
<?php
include 'db_connection.php';

$data = json_decode(file_get_contents("php://input"));

$title = $data->title;
$ingredients = $data->ingredients;
$instructions = $data->instructions;

$sql = "INSERT INTO recipes (title, ingredients, instructions) VALUES ('$title', '$ingredients', '$instructions')";
if ($conn->query($sql) == TRUE) {
    echo json_encode(["message" => "Recipe added successfully"]);
} else {
    echo json_encode(["error" => "Error: " . $sql, "<br>" . $conn->error]);
}

$conn->close();
?>

Thank you in advance for any help you can give me.

I’ve tried changing the button type to “submit” but the same thing happens and debugging every step, but I just don’t know where the issue is.

Javascript in browser, how to call function when 1 script file fully loaded, but do not care about other resources

In my html I have 2 script tags:

<script src="first.js"></script> 
<script src="second.js"></script>

first.js is a large library file, and would make funcFromFirstJs available. I want to call this func when it becomes ready. I currently use this recursive strategy like so:

// second.js

function callIfReady() {
  if (typeof funcFromFirstJs === 'function') {
    funcFromFirstJs();
  } else {
    // wait for a few seconds and callIfReady() again
  }
}

Is there a better way?
I am aware of window event 'load' which is supposed to fire when all sources in html including images have finished loading completely. I’m also aware of document event DOMContentLoaded which happens when tags are loaded, but may happen before their content completely finishes loading.
Because first.js is a library file, so I also do not want to add my js code at the bottom of first.js.
So specifically, I just want to wait for first.js to finish loading completely, then run this code in second.js. I certainly do not care about the loading progress of other things like images or other script tags; this is why I do not want to use window event: load.

¿Como recorrer un arreglo dentro de otro para que quede solo uno? ( Angular, typescript, javascript) [closed]

Tengo el siguiente problema. Estoy resiviendo una respuesta de un servicio, la cual a su vez recorro con un for para que me devuelva solo ciertos resultados.

El problema es que lo que obtengo son varios array con la informacion en cada uno, como se ve en la imagen, en el primero tengo 5, en el segundo tengo 7 resultados y asi.

Lo que necesitaria es que todo este dentro de un solo array y no dentro de “x” cantidad como se ve en la imagen

Como podria hacer?

enter image description here

De esta manera estoy recorriendo el objeto que recibo como respuesta desde el servicio.

enter image description here

After clicking Add button item name is not showing on Selected Items section why?

let selectedItems = [];
let outputDiv = document.getElementById("output");

function showSection(sectionId) {
    document.querySelectorAll('section').forEach(section => {
        section.classList.remove('active');
    });

    const selectedSection = document.getElementById(sectionId);
    if (selectedSection) {
        selectedSection.classList.add('active');
    }
}

function addItem(item) {
    const quantityInputId = `quantity-${item.toLowerCase()}`;
    const quantity = document.getElementById(quantityInputId).value;

    if (quantity > 0) {
        const price = parseFloat(document.querySelector(`#${item.toLowerCase()} .price`).innerText.replace('$', ''));

        selectedItems.push({
            item: item,
            quantity: quantity,
            price: price
        });

        updateSelectedItemsList();
        outputDiv.innerHTML = `<p>Selected Item: ${item}</p>`;
    }
}

function updateSelectedItemsList() {
    const selectedItemsList = document.getElementById('selected-items-list');
    selectedItemsList.innerHTML = '';

    selectedItems.forEach(item => {
        const listItem = document.createElement('li');
        listItem.innerHTML = `
            <span class="name">${item.item}</span>
            <span class="quantity">Quantity: ${item.quantity}</span>
            <span class="price">Price: $${item.price.toFixed(2)}</span>
            <button class="remove-button" onclick="removeItem('${item.item}')">Remove</button>
        `;
        selectedItemsList.appendChild(listItem);
    });
}

function removeItem(item) {
    selectedItems = selectedItems.filter(selectedItem => selectedItem.item !== item);
    updateSelectedItemsList();
}

document.getElementById('sections').addEventListener('change', function () {
    showSection(this.value);
});

const addButtons = document.querySelectorAll('.add-button');
addButtons.forEach(button => {
    button.addEventListener('click', function () {
        const itemName = this.parentElement.parentElement.querySelector('.name').innerText.trim();
        addItem(itemName);
    });
});
body {
    font-family: 'Arial', sans-serif;
    margin: 0;
    padding: 0;
    background-color: #f4f4f4;
}

header {
    background-color: #333;
    color: #fff;
    text-align: center;
    padding: 1em;
}

section {
    padding: 1em;
    display: none;
}

section.active {
    display: block;
}

h2 {
    color: #333;
}

ul {
    list-style-type: none;
    padding: 0;
    margin: 0;
}

li {
    background-color: #fff;
    margin-bottom: 10px;
    padding: 10px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.name {
    flex: 1;
    font-size: 28px;
    font-weight: bold;
    font-family: 'Comic Sans MS', cursive;
}

.price {
    color: #888;
    font-size: 14px;
}

.quantity-container {
    display: flex;
    align-items: center;
}

.quantity {
    margin-left: 10px;
    width: 40px;
    padding: 5px;
    border: 1px solid #ccc;
    border-radius: 5px;
    box-sizing: border-box;
}

.add-button {
    background-color: #4CAF50;
    color: #fff;
    border: none;
    padding: 5px 10px;
    border-radius: 5px;
    cursor: pointer;
}

.remove-button {
    background-color: #FF6347;
    color: #fff;
    border: none;
    padding: 5px 10px;
    border-radius: 5px;
    cursor: pointer;
}

#selected-items {
    background-color: #eee;
    padding: 1em;
    margin-bottom: 20px;
}

#selected-items h2 {
    color: #333;
    margin-bottom: 0.5em;
}

#selected-items-list {
    list-style-type: none;
    padding: 0;
    margin: 0;
    display: flex;
    flex-wrap: wrap;
}

#selected-items-list li {
    flex: 0 0 48%;
    margin-right: 2%;
    margin-bottom: 10px;
}

#selected-items-list li span {
    display: inline-block;
    margin-right: 10px;
}
<header>
    <h1>Restaurant Menu</h1>
    <label for="sections">Select Section:</label>
    <select id="sections" onchange="showSection(this.value)">
        <option value="indianBreads">Indian Breads</option>
        <option value="rolls">Rolls</option>
        <option value="momo">Momo</option>
        <option value="salads">Salads</option>
        <option value="iceCream">Ice Cream</option>
        <option value="starters">Starters</option>
    </select>
</header>

<section id="indianBreads" class="active">
    <h2>Indian Breads</h2>
    <ul>
        <li>
            <span class="name">Naan</span>
            <span class="price">$2.99</span>
            <div class="quantity-container">
                <input type="number" id="quantity-naan" class="quantity-input quantity" min="0" value="0">
                <button class="add-button" onclick="addItem('Naan')">Add</button>
            </div>
        </li>
        <li>
            <span class="name">Roti</span>
            <span class="price">$1.99</span>
            <div class="quantity-container">
                <input type="number" id="quantity-roti" class="quantity-input quantity" min="0" value="0">
                <button class="add-button" onclick="addItem('Roti')">Add</button>
            </div>
        </li>
        <li>
            <span class="name">Paratha</span>
            <span class="price">$3.49</span>
            <div class="quantity-container">
                <input type="number" id="quantity-paratha" class="quantity-input quantity" min="0" value="0">
                <button class="add-button" onclick="addItem('Paratha')">Add</button>
            </div>
        </li>
    </ul>
</section>

<!-- Add other sections for different menu categories -->

<div id="selected-items">
    <h2>Selected Items</h2>
    <ul id="selected-items-list"></ul>
</div>

<div id="output"></div>

if add button clicked i want to show selected item name rate price total price and at the end grand total price inside Selected Items.
my current code is not working. and plese tell me where im making mistake.
im working on a user interface where i want to display selected items, their rates, prices, and calculate the grand total when a button is clicked.

get language of a string [closed]

on a website, I use some script in JavaScript to automate actions using Chrome console. I was wondering if, given a string, there is a way to know what language the text is written in.

Do you have any suggestions? Maybe are there any free API that I can use?

function with “this” javascript [closed]

I need to get mass from object but I don’t know how.

This is my code:

const object = {
  name: "Sphere",
  density: 10,
  volume: 6,
  mass: function() {
    return this.density * this.volume;
  }
};

console.log(object.mass);

I tried to run the function with mass() and function mass() and then console.log,but it didn’t work

Async await 3 promises seems to be running in parallel, whats happening?

I have 3 promises which I have created using new Promise() constructor, after 5000 ms of delay the promise resolves.

In a function: runPromises(), I am awaiting those 3 promises without using Promise.all().

const promise1 = new Promise((resolve) => {
  setTimeout(() => {
    resolve(1);
  }, 5000);
});

const promise2 = new Promise((resolve) => {
  setTimeout(() => {
    resolve(2);
  }, 5000);
});

const promise3 = new Promise((resolve) => {
  setTimeout(() => {
    resolve(3);
  }, 5000);
});

async function runPromises() {
  const value1 = await promise1;
  console.log(value1);
  const value2 = await promise2;
  console.log(value2);
  const value3 = await promise3;
  console.log(value3);
}

runPromises();

My expectation is to see the program run for 15 seconds in total, rather what is happening is, it is running for 5 seconds and seems like the promises are running in parallel.

What’s going on?

How to show child element outside of parent on x axis and have y axis scrollable?

I want to show elements outside of parent dimensions on the x axis while allowing the parent element to scroll on the y axis.

Foolish me, I thought “I’ll just set the parent to overflow-x:visible and overflow-y:auto”. Of course, it doesn’t work as I intended, instead it makes the x axis scrollable thereby hiding the child element behind a scroll.

Example html:

<div class="parent">
  <div class="child"></div>
</div>

and css:

.parent {
  position: relative;
  height: 120px;
  width: 50px;
  background: black;
  overflow-y: auto;
  overflow-x: visible;
}

.child {
  position: absolute;
  top: 10px;
  right: -85px;
  height: 40px;
  width: 80px;
  background: purple;
}

https://jsfiddle.net/xphc0qyo/

This seems to be a known issue but I’m unaware of a good and easy solution or is the best option to go the Javascript route?

So, how to show child elements outside of a parent on the x axis and have the y axis scrollable?

sendSlash Issue [discord.js-selfbot-v13]


(random string so I can even post this message, please ignore.)

Code:

const { Client } = require('discord.js-selfbot-v13');
const client = new Client({
    checkUpdate: false,
});

client.on('ready', async () => {
    const channelId = '1190781950944886870';
    const channel = client.channels.cache.get(channelId);
  
    if (channel) {
      console.log(`Channel found: ${channel.name}`);
      channel.sendSlash('1190781950944886867', 'about');
    } else {
      console.error('Channel not found.');
    }
  });

client.login('my token');

Error:

Channel found: general
C:Userssirnode_modulesdiscord.js-selfbot-v13srcerrorsDJSError.js:40
  if (!msg) throw new Error(`An invalid error message key was used: ${key}.`);
                  ^

Error: An invalid error message key was used: botId is not a bot or does not have an application slash command.
    at message (C:Userssirnode_modulesdiscord.js-selfbot-v13srcerrorsDJSError.js:40:19)
    at new DiscordjsError (C:Userssirnode_modulesdiscord.js-selfbot-v13srcerrorsDJSError.js:16:13)
    at TextChannel.sendSlash (C:Userssirnode_modulesdiscord.js-selfbot-v13srcstructuresinterfacesTextBasedChannel.js:497:13)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Node.js v20.10.0

I were expecting my Account to Trigger the Slash Command (/about) of a Bot in the channel by the ID 1190781950944886870

new FormData() not populated with data from a form [duplicate]

MDN’s page on the FormData constructor says explicitly:

Syntax: new FormData(form)

form (optional)
An HTML element — when specified, the FormData object will be populated with the form’s current keys/values using the name property of each element for the keys and their submitted value for the values.

Here’s my barebones implementation of this, but the result of new FormData(form) is empty. What is it that I have failed to understand?

document.querySelector("form").addEventListener("submit", (event) => {
  event.preventDefault()

  const form = event.target
  const formData = new FormData(form)
  console.log("result:", JSON.stringify(formData));
  
  const input = form.querySelector("input")
  const { name, value } = input        
  console.log("expected:", JSON.stringify({[name]: value}))
}, false) 
<form>
  <input type="text" name="test" value="exists" />
  <button type="submit">Submit</button>
</form>

Show one or more errors

show me this message omly apdate recored…

One or more errors have occurred since the page loaded. Open the Browser’s JavaScript console to see the errors.

One or more errors have occurred since the page loaded. Open the Browser’s JavaScript console to see the errors.