chatbot reponse to increase progress bar

I working on a chatbot where I want to increase the progress bar depending on which intents the chatbot response comes from. The dataset is a JSON file containing responses for the chatbot. I want the progress bar to move accordingly by a certain percent depending on which “tag” the chatbot response comes from. I have used the fetch method to get the JSON data, looped through intents, and put them in different lists. The problem seems to be that the progress bar only moves once and then stops no matter what I type.

function botResponse(rawText) {
    const bot_rep = [];
    const bot_tag_1 = [];
    const bot_tag_2 = [];
    let counter = 0;
    let percent = document.getElementById('percent');
        let bar = document.getElementById('bar');
    //const i=0;
     fetch("http://127.0.0.1:5000/json") //fetch the json file
    .then(response=>response.json())
    .then(data=>{
          for (i in data.intents[0].responses){ //loop through intetnts
          bot_tag_1.push(data.intents[0].responses[i]); //push all responses from intents "greeting" [0] to list bot_tag_1
          //console.log(data.intents[0].responses)
          console.log(bot_tag_1.length);
          }
          if(bot_rep.indexOf(bot_tag_1 )){ //if the chatbot's response comes from/exists in bot_tag_1 increase by 2%
            //var count = 1;
            //console.log(bot_tag_2);
            console.log("from tag greeting "+ "points increase 2 pts");
            counter = 2;//count * 2;
            percent.innerHTML = `${counter}%`;
            bar.style.width = `${counter}%`;
        }

          for (i in data.intents[1].responses){  //loop through intents
          bot_tag_2.push(data.intents[1].responses[i]); //push all responses from intents "goodbye" [1] to list bot_tag_2
          //console.log(data.intents[1].tag)
          console.log(bot_tag_2.length);
          }
          if(bot_rep.indexOf(bot_tag_2 )){ //if the chatbot's response comes from/exists in bot_tag_2 increase by 10%
            //var count = 1;
            //console.log(bot_tag_2);
            console.log("from tag goodbye "+ "points increase 10pts");
            counter = 10;
            percent.innerHTML = `${counter}%`;
            bar.style.width = `${counter}%`;
        }
          //console.log(data);
          //console.log(data.intents[1].responses);
          //console.log(data.intents[0].tag);
         
    })
#progress {
 width: 500px;   
 border: 1px solid black;
 position: relative;
 padding: 3px;
 top: 16px; 
}

#percent {
 position: absolute;   
 left: 50%;
 bottom: 25px;
}

#bar {
 height: 20px;
 background-color: green;
 
 
 width: 0%;
}

<!-- JSON file 
{"intents": [
            {"tag": "greeting",
            "patterns": ["Hi", "How are you?", "Hello", "Whats up?", "hiii"],
            "responses": ["Hello!", "Hi there, how can I help?"],
            "context_set": ""
            },
            {"tag": "goodbye",
                "patterns": ["cya", "See you later!", "Bye Bye!", "Goodbye", "Peace out"],
                "responses": ["Will miss you!", "Okay, talk to you later!", "Goodbye!"],
                "context_set": ""
            },
            {"tag": "language",
                "patterns": ["What language are you written in??"],
                "responses": ["Im written in Python"],
                "context_set": ""
            },
<html lang="en">

<head>

</head>

<body>
    <div class="progress">
            progress Bar
    <div id="progress">
           <span id="percent">0%</span>
           <div id="bar"></div>
    </div>


</body>

</html>

Regular expression not supported by Javascript? [duplicate]

I’m trying to use a regular expression, I tried several changes and searches but none worked correctly.

regular expression
https://regex101.com/r/lK1tD6/1

var reg = '(?:(?<=^)|(?<=D))((00|+)?55(s|.|-)*)?((()?0 ?d{2}(?(5))|)(s|.|-)*)?(9(s|.|-)*)?d{4}(s| .|-)*d{4}(?=D|$)'gm
var search = value => value && value.match(reg);

var content = '+55 55 55555-5555';
var phones = search(content);
console.log(phones);

Thanks in advance 🙂

State not Rendering to UI, Element is added in array

Hi I have created a react application, I am passing an array of object that renders in the UI , When I am adding an element to it using useState , The element is added but it doesn’t render in the UI , I am adding the jsx code for refrence, I need a suggestion on what is causing the issue.

App.jsx

import logo from "./logo.svg";
import "./App.css";
import Expense from "./components/ExpenseComponent/Expense";
import NewExpense from "./components/AddExpenseComponent/NewExpense";
import React,{useState} from "react";

const expenseItem = [
  { title: "furniture", ammount: 568, date: new Date(2022, 2, 23) },
  { title: "books", ammount: 30, date: new Date(2022, 2, 24) },
  { title: "Electronics", ammount: 468, date: new Date(2022, 2, 23) },
  { title: "sports", ammount: 340, date: new Date(2022, 2, 24) },
  { title: "virtual media", ammount: 268, date: new Date(2022, 2, 23) },
];

const App=()=> {
  
  const[expenses,newExpenseItem] = useState(expenseItem);
  const addExpense = (expense) =>{
    newExpenseItem((prevExpense) =>{
      return [expense,...prevExpense];
    });
    
  };
  return (
    <div id="root">
      <NewExpense addExpenseToArray={addExpense}/>
      <Expense items={expenseItem} />
    </div>
  );
}

export default App;

Expense.jsx

import "../ExpenseComponent/Expense.css";
import ExpenseItem from "../ExpenseComponent/ExpenseItem";
import ExpenseFilter from "../AddExpenseComponent/ExpenseFilter";
export const Expense = (props) => {
  //let item = props.items;
  const getYear = (targetYear) => {
    console.log(targetYear);
    //console.log(item);
  };
  return (
    <div className="expenses">
      <ExpenseFilter getTargetYear={getYear} />
      {props.items.map((expense) => (
        <ExpenseItem
          title={expense.title}
          ammount={expense.ammount}
          date={expense.date}
        />
      ))}
    </div>
  );
};

export default Expense;

NewExpense.jsx

import React from "react";
import ExpenseForm from "./ExpenseForm";
import "./NewExpense.css";
const NewExpense = (props) => {
  const getNewExpenseData = (newExpenseData) => {
    //const expenseData = newExpenseData;
    props.addExpenseToArray(newExpenseData);
    //console.log(expenseData);
  };

  return (
    <div>
      <div className="new-expense">
        <ExpenseForm getExpenseData={getNewExpenseData} />
      </div>
    </div>
  );
};

export default NewExpense;

Challenge: Predict what an element’s calculated CSS property would fall back to if it’s effective value was deleted – without causing style flickers?

Let’s say we have an HTMLElement that is styled inline relative to a given CSS property and that window.getComputedStyle(HTMLElement).getPropertyValue(theCSSProperty) returns the value reflecting the inline styling.

If we did: HTMLElement.style.removeProperty(theCSSProperty), window.getComputedStyle(HTMLElement ).getPropertyValue(theCSSProperty) would show the fallback value (not necessarily the same as the default value).

I would like to be able to predict that fallback value without actually deleting the effective value, but with my current take at it, it seems quite difficult because the process of calculating the effective style, as this post hints at, is not at all that simple.

I have thought about other hackish solutions such as cloning the element out of sight and manipulating the clone instead, but that is not a bullet proof solution – due to possible nth-child styling for one thing.

So my conclusion is: It ain’t easy (not the same as undoable). But before I leave it at that, I thought I might as well check with the community that there isn’t some obvious solution I have missed. How would you approach this if you had to?

How to convert string from ENV to hex in JavaScript? [duplicate]

In my .env file I have such environmental variable:

CRYPTO_KEY_SHORT=x12x34x56x78x9Ax12x32xE3

I use this string as a key in code, like this:

const decryptedHash = cryptoService.decryptHex(confirmToken, `${process.env.CRYPTO_KEY_SHORT}`, null)

And here is the problem, it doesn’t work this way, every time I get error – Error: Invalid key length, but if I hardcode this it work:

const decryptedHash = cryptoService.decryptHex(confirmToken, "x12x34x56x78x9Ax12x32xE3", null)

So, after putting such variable to .env how can I use it?

Possibility of Downloading a file with a specified content length slightly bigger than actual file

I want to know if it’s possible to download a file that has a file size lesser than the specified content length.
For example, let’s say it has an actual size of

size: 3165076 Bytes

And the specified content length is

3336523 Bytes

From my previous experience this results in an infinite download loop. So i want to know if it’s possible to round off the download when it has reached its total size or better still specify a size range

Python or C++ Program to Find LHS = RHS

I’ve been Given a Question to find If 23=5 LHS ..i.e 2+3 = 5 … Since it’s true it should return true else Return -1

Note that the Input is single input 23=5 in a single sentence.

I have no idea how to differentiate the left side of = and right side of the =.

closure and settimeout question in for loop [duplicate]

Can someone tell the outputs of the following code.
I just want to print 1 2 3 4 5 on the console after 1s

1)

for (var i = 0; i < 5; ++i){
    setTimeout(() =>{
        console.log(i);
    }, 1000);
}

for (let i = 0; i < 5; ++i){
    setTimeout(() =>{
        console.log(i);
    }, 1000);
}

for (let i = 0; i < 5; ++i){
    setTimeout((i) =>{
        console.log(i);
    }, 1000);
}

All of them are giving different answer and i dont know why. Please help!!

net::ERR_CONNECTION_REFUSED, RapidAPI, trying to fetch the solveSudoku API

I’m using an API that solves the Sudoku game. If I understand it right my issue is fetching the data from the API. The API is returning data. I have also tried without the backend and received the 400 bad request error. I’m quite new to programming and would need your help, please.

Here is the link to the error message https://imgur.com/a/brFk7Oo

Here is the link to the network error https://imgur.com/PsBsefW

app.js

    // Selectors
const puzzleBoard = document.querySelector('#puzzle');
const solveButton = document.querySelector('#solve-button');
const solutionDisplay = document.querySelector('#solution');
const squares = 81;
let submission = [];

//functions
for (let i = 0; i < squares; i++) {
    const inputElement = document.createElement('input');
    inputElement.setAttribute('type', 'number');
    inputElement.setAttribute('min', '1');
    inputElement.setAttribute('max', '9');
    if (
        ((i % 9 == 0 || i % 9 == 1 || i % 9 == 2) && i < 21) ||
        ((i % 9 == 6 || i % 9 == 7 || i % 9 == 8) && i < 27) ||
        ((i % 9 == 3 || i % 9 == 4 || i % 9 == 5) && (i > 27 && i < 53)) ||
        ((i % 9 == 0 || i % 9 == 1 || i % 9 == 2) && i > 53) ||
        ((i % 9 == 6 || i % 9 == 7 || i % 9 == 8) && i > 53) 
    ) {
        inputElement.classList.add('odd-section')
    }

    puzzleBoard.appendChild(inputElement);
}

// wrapped the document in a new div
const wrapper = document.createElement('div')
puzzleBoard.parentNode.insertBefore(wrapper, puzzleBoard)
wrapper.appendChild(puzzleBoard)

wrapper.className = "puzzle"


const joinValues = () => {
    const inputs = document.querySelectorAll('input');
    inputs.forEach(input => {
        if (input.value) {
            submission.push(input.value);
        } else {
            submission.push('.');
        }
    })
    console.log(submission)
}


const populateValues = (isSolvable, solution) => {
    const inputs = document.querySelectorAll('input');
    if (isSolvable && solution) {
        inputs.forEach((input, i) => {
            input.value = solution[i];
        })
        solutionDisplay.innerHTML = 'Here is the answer!';
    } else {
        solutionDisplay.innerHTML = 'You made a mistake, this is not solvable';
    }

}

const solve = () => {
    joinValues()
    const data = {numbers: submission.join('')}
    console.log('data', data)

    fetch('http://localhost:8000/solve', {
        method: 'POST', 
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }, 
        body: JSON.stringify(data)
    })  .then(response => response.json())
        .then(data => {
            console.log(data)
            populateValues(data.solvable, data.solution)
            submission = []
    })
    .catch((error) => {
        console.error('Error:', error)
    })
}

solveButton.addEventListener('click', solve);

server.js

    const PORT = 8000
const axios = require('axios').default
const express = require('express')
const cors = require('cors')
require('dotenv').config()
const app = express()
app.use(cors())
app.use(express.json())

app.post('/solve', (req, res) => {
    const options = {
        method: 'POST',
        url: 'https://solve-sudoku.p.rapidapi.com/',
        headers: {
            'content-type': 'application/json',
            'x-rapidapi-host': 'solve-sudoku.p.rapidapi.com',
            'x-rapidapi-key': process.env.RAPID_API_KEY 
        },
        data: {
            puzzle: req.body.numbers
        }
    }

    axios.request(options).then((response) => {
        console.log(response.data)
        res.json(response.data)
    }).catch((error) => {
        console.error(error)
    })
})

app.listen(PORT, () => console.log(`server listening on PORT ${PORT}`))

Would really appreciate any help

How to load the code from page 2 on page 1 when the button is clicked?

code page1.html:

<script class="scriptthis">
some code
</script>
<div id="content">
<div class="card"></div>
<div class="card"></div>
<div class="card"></div>
<div class="card"></div>
</div>
<button id="load-more">Load More Button</button>
<script>
$( "#load-more" ).click(function() {
  $('script... or near').load('page2.html... script code or script
  $('#content').load('page2.html... content
});
</script>

code page2.html:

<script class="scriptthis">
some code another
</script>
<div id="content">
<div class="card"></div>
<div class="card"></div>
<div class="card"></div>
<div class="card"></div>
</div>

How to load the code from page 2 on page 1 when the button is clicked?
Script to script or near – is the main problem.
and content to the end #content div

Please help with a working solution.