JS Bytes, strings, raw convert

I have a working Python code that send/receive messages by websocket. I had copied the message (prepared to be sending):

“x00x00Uxaax00x00x00x00x00x00x00nx00x00x00xxefx80nx14x90xdc2Qm9xc0xd0gTDxd9x9f%xfa «wxbdxecxf2xec`xf9x84x8cVFLx16xa6Kxd8xe2xbf$x8bxd5Pxa3xbbx0cxe6xaaxd5xd6x81Fx96xfdxc7Ex88x9bxdf(x87.x1dx00Ex9a%4XTxa0xf9dxafnxd2xe3xc6x86x02xbcx19V=xd8x8a[xf7xdbxbdNx1axbexee/xc7x10xa3xf3x02x016x13g}t=xdaxdc~xa9xd0x91xc9x0ex93x00x00xaaU”

Now I try to send it from javascript. How I can send it? Cause it’s string, but I need to send as raw bytes.

Can I change react state like this? [duplicate]

I want to change the value of the object in the array format, is it okay to change it as below?

It works, but I’m not sure if I can change state directly.

function Test() {
    const data = {
        a: ["hello", "world", "test", "data"],
    };
    const [state, setState] = useState(data);

    const changeHandler = (e: ChangeEvent<HTMLInputElement>, idx: number) => {
        state["a"][idx] = e.target.value;
        setState({ ...state });
    };

    return (
        <>
                {state.a.map((d, idx) => (
                    <input key={idx} value={d} onChange={(e) => changeHandler(e, idx)} />
                ))}
        </>
    );
}

How to get ajax responses from fast to slow?

  1. requests send simultaneously
  2. don’t need to wait all response resolved

example: there are 3 request sending simultaneously

axios.get(url1) needs 1s to get response
axios.get(url2) needs 2s to get response
axios.get(url3) needs 3s to get response
how to get responses like res1 then res2 then res3 ?
promise.all and promise.race can not do this(because all will wait the lowest response not return from fastest to slowest, and race will return the fastest not all)

how to call api recursively until nested stack keys are finished

here is my question how to call api recursively untill nested data stack keys are finished

here is my full explaination in image

enter image description here

i found this relatable code for recursion api call at this post recursive api call

function callFW() {
d3.json(url, async function(data) {
        Tree["uid"] = data.request.uid
        Tree["hid"] = data.firmware.meta_data.hid
        Tree["size"] = data.firmware.meta_data.size
        Tree["children"] = [];
        
        await BuildTree(data.firmware.meta_data.included_files,Tree["children"]);

        console.log(Tree)
    })

}

async function BuildTree(included_files, fatherNode) {
    if (included_files.length > 0) {

        let promises = included_files.map( item => {
            let url = endpoint + "file_object/" + item + "?summary=true";
            return axios.get(url)
        });

        const results = await Promise.all(promises);

        for(let response of results){

            var node = {}
            node["uid"] = response.data.request.uid
            node["hid"] = response.data.file_object.meta_data.hid
            node["size"] = response.data.file_object.meta_data.size
            node["children"] = []

            fatherNode.push(node)

            await BuildTree(response.data.file_object.meta_data.included_files, node["children"]);
        };
    }
};

this is im using custom useRecurseFetch for getting post api result
but i have no idea how to change this code for recursive api call

import React from 'react';

import qs from 'qs';
import axios from 'axios';

const useRecurseFetch = query => {
  const [status, setStatus] = React.useState('idle');
  const [result, setResult] = React.useState([]);
  const [findClass, setFindClass] = React.useState([]);

  // console.log(passVariable);

  var data;

  data = qs.stringify({
    query: `http://www.blabla{ ${query}/category}`,
  });

  // eslint-disable-next-line no-undef
  var Grant = process.env.REACT_APP_GRANT;
  // eslint-disable-next-line no-undef
  var Client = process.env.REACT_APP_CLIENT;
  // eslint-disable-next-line no-undef
  var Key = process.env.REACT_APP_KEY;
  // eslint-disable-next-line no-undef
  var Auth = process.env.REACT_APP_AUTH;
  // eslint-disable-next-line no-undef
  var Query = process.env.REACT_APP_QUERY;

  const queryCall = React.useCallback(
    async token => {
      if (!token) {
        return;
      } else {
        setStatus('Loading');

        var config = {
          method: 'POST',
          url: `${Query}`,
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            Authorization:
              token.data.token_type + ' ' + token.data.access_token,
          },
          data: data,
        };

        axios(config)
          .then(response => {
            setResult(response.data.results.bindings);
            let originalResult = response.data.results.bindings
              .filter(ek => ek.class !== undefined && ek)
              .map(el => el.obj.value);
            setFindClass(originalResult);

            setStatus('success');
          })
          .catch(function (error) {
            setStatus('error');
          });
      }
    },
    [data]
  );

  React.useEffect(() => {
    const authInitiate = () => {
      var data = qs.stringify({
        grant_type: `${Grant}`,
        client_id: `${Client}`,
        client_secret: `${Key}`,
      });
      var config = {
        method: 'POST',
        url: `${Auth}`,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        data: data,
      };
      axios(config)
        .then(response => {
          queryCall(response);
        })
        .catch(function (error) {
          console.log(error);
        });
    };

    authInitiate();
  }, [queryCall]);

  return [status, result, findClass];
};

export default useRecurseFetch;

please any one can help me out with this code, im unable to figure out whats going in this code
anyhelp is really saved my day and really so appreciatable

here i called useRecurseFetch custom function in app.js

 const [loadingStatus, mainData, addDataToPostItemArray] = useRecurseFetch(
        `<kk:cat>`
      );

please any one can help me out please im stuck with this process of calling api

How to get max number from Array in TS orJS

I’d like to create like this function in JS or TS but I couldn’t.
Please teach me …!
It is better if its function is made by functional-programming.

・Input type:Array(String)
・Output type:string or undefined

ex.
Input => Output
[“”,”0″,”3″] => “3”
[“”,””,””] => undefined
[“0″,”0″,”0”] => “0”
[“1″,”3″,”2”] => “3”

HTML Form onsubmit

In HTML5, returning false in a form gives the red line, indicating there is an error, even though I am able to achieve my expected output. Is there any way to fix this line and have a bug free code as it is triggering my OCD.
Also, I am a big beginner with my code so please try to keep it as simple as possible. i do not understand JQUERY at all.

return false here brings a red line. even tried it with the "return <function()> and that also gave red line

Update field if change in other field Firestore

I’m new to Firestore. I have two collections (users and tasks). Both collections have a field called status. I need tasks.status to update to ‘complete’ when users.status = complete. We should also listen for any current changes in the DB to update previously created tasks. What is the best way to write that?

Custom sorting inside array of array

I have an array given below, every element of this array consists of another array.

var array={[201,Tom,EES,California],[189,Charlie,EE,New Jersey],[245,Lisa,EEF,New Jersey],[743,Niall,EEC,Chicago],[653,Tim,EES,Miami],[333,Dev,EE,Washington],[333,Rhonda,EEC,Washington]}

I want it to be sorted on the basis of 3rd value and in this order[EE,EES,EEC,EEF].

New Sorted Array ={[189,Charlie,EE,New Jersey],[333,Dev,EE,Washington],[201,Tom,EES,California],[653,Tim,EES,Miami],[743,Niall,EEC,Chicago],[333,Rhonda,EEC,Washington],[245,Lisa,EEF,New Jersey]}

Thanks in advance.

setting localStorage for multiple items

I am having trouble setting up local storage to save the textArea input for each of the time blocks. I have commented out 3 different sections where I was playing with different techniques to try and make it work. However, I was not able to set it to save the text in local storage and get it so that it stay on the page when you revisit it. Please let me know if you can help me with a solution to fix it. I have provided a link to my repository. please look at the feature/calendar branch because that is where my code resides. I also snippet the code into here for you to look at. I am new to coding so please be patient with me. I am still learning the terminology and different ways to reach the objective/goal.

saveBtn = document.getElementsByClassName('saveBtn');

//  creates a new instance for time and date.
const currentDay = luxon.DateTime.now().toLocaleString(luxon.DateTime.DATETIME_MED);
//  format's the date and time.
var newFormat = {
    //  The selected date format from luxon documentation.
    ...luxon.DateTime.DATETIME_MED,
    //  added the day of the week.
    weekday: 'long'
};

// creates a new instance for time and date.
const newCurrentDay = luxon.DateTime.now().toLocaleString(newFormat);
//  checks if time works.


//  creates a new instance to parse the date and time into the header html.
var ol = document.querySelector('header');
//  creates the ol element.
const list = document.createElement('ol');
//  styles the <ol> element.
list.setAttribute('style', 'color: white; background-color: black; display: flex; flex-direction: column; justify-content: center; align-items: center;');
//  displays newCurrentDay variable in the header as readable text.
list.innerText = newCurrentDay;
//  appends the newCurrentDay variable to the ol element.
ol.appendChild(list);

//  creates an array to change the blocks bases on their time in the text area element.
const timeBlocks = Array.from(document.getElementsByClassName('description'));
// assigning timeBlocks based on time.
for (var i = 0; i < timeBlocks.length; i++) {
    //  gets the current hour to connect the color changing feature in the text area element based on the 24hr format.
    const now = luxon.DateTime.now().hour.toLocaleString();
    //  if statement's to change the color of the blocks based on time using the 24hr time format.
    if (timeBlocks[i].id < now) {
        timeBlocks[i].classList.add('past');
    }
    if (timeBlocks[i].id > now) {
        timeBlocks[i].classList.add('future');
    }
    if (timeBlocks[i].id === now) {
        timeBlocks[i].classList.add('present');
    }
}


// // * testing
// saveBtn = document.getElementsByClassName('saveBtn');

// var save = addEventListener('click', function () {
//     //  creates a new instance to parse the date and time into the header html. 
//     var textarea = document.querySelector('textarea');

//     this.window.localStorage.setItem('textarea', textarea.value);

//     this.window.localStorage.getItem('textarea');
// });




//  TODO: can  use save button for event text to persist even when refreshed.

// $('.saveBtn').on("click", function () {
//     window.localStorage.setItem('task', $(this).siblings('.description').val());
// })

// loadTask = function () {
//     return window.localStorage.getItem('task');
// }


// let taskArray = [{
//     21: "",
//     22: "",
//     23: "",
// }];

// $('.saveBtn').on("click", function () {
//     window.localStorage.setItem('tasks', JSON.stringify(taskArray));

//     JSON.parse(window.localStorage.getItem('tasks'));

// var storedData = window.localStorage.getItem(taskArray);

// if (storedData) {
//     taskArray = JSON.parse(storedData);
//     alert(taskArray);
// }
// });


// TODO:  event is saved into time block using local storage


// TODO:  have my minutes actively change. 
body {
  font-family: 'Open Sans', sans-serif;
  font-size: 16px;
  line-height: 1;
}

textarea {
  background: transparent;
  border: none;
  resize: none;
  color: #000000;
  border-left: 1px solid black;
  padding: 10px;
}

.jumbotron {
  text-align: center;
  background-color: transparent;
  color: black;
  border-radius: 0;
  border-bottom: 10px solid black;
}

.description {
  white-space: pre-wrap;
}

.time-block {
  text-align: center;
  border-radius: 15px;
}

.row {
  white-space: pre-wrap;
  height: 80px;
  border-top: 1px solid white;
  ;
}

.hour {
  background-color: #ffffff;
  color: #000000;
  border-top: 1px dashed #000000;
}

.past {
  background-color: #d3d3d3;
  color: white;
}

.present {
  background-color: #ff6961;
  color: white;
}

.future {
  background-color: #77dd77;
  color: white;
}

.saveBtn {
  border-left: 1px solid black;
  border-top-right-radius: 15px;
  border-bottom-right-radius: 15px;
  background-color: #06AED5;
  color: white;
}

.saveBtn i:hover {
  font-size: 20px;
  transition: all .3s ease-in-out;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css"
    integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous" />
  <link href="https://fonts.googleapis.com/css?family=Open+Sans&display=swap" rel="stylesheet" />
  <link rel="stylesheet" href="./assets/css/style.css" />
  <title>Work Day Scheduler</title>
</head>

<body>
  <header class="jumbotron">
    <h1 class="display-3">Work Day Scheduler</h1>
    <p class="lead">A simple calendar app for scheduling your work day</p>
    <p id="currentDay" class="lead"></p>
  </header>
  <div class="container">
    <!-- Time blocks go here -->
    <div class="row">
      <div class="col-2 border-top border-dark">
        9:00PM
      </div>
      <textarea class="description col-8" id="21">Event</textarea>
      <button class="btn saveBtn col-2"><i class="fas fa-save"></i></button>
    </div>
    <div class="row">
      <div class="col-2 border-top border-dark">
        10:00PM
      </div>
      <textarea class="description col-8" id="22">Event</textarea>
      <button class="btn saveBtn col-2"><i class="fas fa-save"></i></button>
    </div>
    <div class="row">
      <div class="col-2 border-top border-dark">
        11:00PM
      </div>
      <textarea class="description col-8" id="23">Event</textarea>
      <button class="btn saveBtn col-2"><i class="fas fa-save"></i></button>
    </div>
    <div class="row">
      <div class="col-2 border-top border-dark">
        12:00AM
      </div>
      <textarea class="description col-8" id="0">Event</textarea>
      <button class="btn saveBtn col-2"><i class="fas fa-save"></i></button>
    </div>
    <!-- <div class="row">
      <div class="col-2 border-top border-dark">
        1:00PM
      </div>
      <textarea class="description col-8" id="13">Event</textarea>
      <button class="btn saveBtn col-2"><i class="fas fa-save"></i></button>
    </div>
    <div class="row">
      <div class="col-2 border-top border-dark">
        2:00PM
      </div>
      <textarea class="description col-8" id="14">Event</textarea>
      <button class="btn saveBtn col-2"><i class="fas fa-save"></i></button>
    </div>
    <div class="row">
      <div class="col-2 border-top border-dark">
        3:00PM
      </div>
      <textarea class="description col-8" id="15">Event</textarea>
      <button class="btn saveBtn col-2"><i class="fas fa-save"></i></button>
    </div>
    <div class="row">
      <div class="col-2 border-top border-dark">
        4:00PM
      </div>
      <textarea class="description col-8" id="16">Event</textarea>
      <button class="btn saveBtn col-2"><i class="fas fa-save"></i></button>
    </div>
    <div class="row">
      <div class="col-2 border-top border-dark">
        5:00PM
      </div>
      <textarea class="description col-8" id="17">Event</textarea>
      <button class="btn saveBtn col-2"><i class="fas fa-save"></i></button>
    </div> -->


    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script> -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/build/global/luxon.min.js"></script>
    <script src="/assets/javascript/script.js"></script>
</body>

</html>

how to fix a pizza order calculation code in javascript

Finally I have made a most of the code work, but still run into the issue with subtotal and adding the toppings to subtotal. When I choose the size of pizza, it shows the price of pizza in subtotal(correct); it shows pst and gst as a +7% of subtotal(correct); it shows its total(correct~~~). It doesn’t do anything (not adding 0.50 per topping to subtotal) when I select the toppings.
How to fix it?
enter image description here

const priceSmall = 4.00;
const priceMedium = 5.00;
const priceLarge = 7.00;
const priceToppings = 0.50; 
const pst = .07;
const gst = .07
let subtotal = 0;
let toppingPrice = 0;

function calculateSize(element) {
  if (element == null) {
    return;
  }

  switch(element.value) {
    case "10":
      subtotal = priceSmall;
      break;
    case "12":
      subtotal = priceMedium;
      break;
    case "15":
      subtotal = priceLarge;
      break;
  }
    recalculateTotal();
}

function toppingOptionPrice(element) {
  if (element.checked) {
      toppingPrice += priceToppings;
  } else {
      toppingPrice -= priceToppings;
  }
    recalculateTotal();
}

function recalculateTotal() {
  let pstToPay = subtotal * pst;
  let gstToPay = subtotal * gst;
  let total = subtotal + pstToPay + gstToPay;
  document.getElementById("subtotal").value = subtotal;
  document.getElementById("pstToPay").value = pstToPay;
  document.getElementById("gstToPay").value = gstToPay;
  document.getElementById("total").value = total;
}

Getting Undefined value for JavaScript object in React forms

I am new to React, I am trying out forms in React, After I submit the form data, the object I am storing data in has undefined values. I am using React states as well, For CSS classes I have used Bootstrap, please find the code below

import React, { useState } from "react";

const NewExpenseForm = () => {

const [enteredTitle,setEnteredTitle] = useState('');
const [enteredAmount,setEnteredAmount] = useState('');
const [enteredDate,setEnteredDate] = useState('');

const titleEventHandler = (event) => {
    setEnteredTitle(event.target.input);
};

const amountEventHandler = (event) => {
    setEnteredAmount(event.target.input);
};

const dateEventHandler = (event) => {
    setEnteredDate(event.target.input);
};

const submitHandler = (event) =>{
    event.preventDefault();
    
    const data = {
        title: enteredTitle,
        amount: enteredAmount,
        date: new Date(enteredDate)
    };

    console.log(data);

};   


return (
    <form onSubmit={submitHandler}>
        <div className="row gx-0 mt-5">
            <div className="col-6">
                <div className="ms-5 me-5">
                    <label className="form-label">Title</label>
                    <input onChange={titleEventHandler} type="text" value={enteredTitle} className="form-control" id="title_id" required/>
                </div>
            </div>
            <div className="col-6">
                <div className="ms-5 me-5">
                    <label className="form-label">Amount</label>
                    <input onChange={amountEventHandler} type="number" className="form-control" id="amount_id"/>
                </div>
            </div>
            <div className="col-6">
                <div className="ms-5 me-5">
                    <label className="form-label">Date</label>
                    <input onChange={dateEventHandler} type="date" className="form-control" id="date_id"/>
                </div>
            </div>
        </div>
        <button type="submit" className="btn btn-primary m-5">Submit</button>
    </form>
);
}

export default NewExpenseForm;

and in data in console, I am getting this

{title: undefined, amount: '', date: Invalid Date}

and I am calling this component in another component like so

import NewExpenseForm from "./NewExpenseForm";

function NewExpense(){

return(
    <div>
        <NewExpenseForm/>
    </div>
);
}

export default NewExpense;

Where am I going wrong?

display Happy numbers Javascript

hi im trying to give the first 5 happy numbers but it dont work , if someone can help me, thanks

here my code `let display = 0;
for (let i = 0; i < 5;) {

if (happy(display) == true) {

    i++;
    display++;
} else {

    display++;
}

}

function happy(x) {

let x2 = Math.pow(x, 2);
let result = 0;
let numbers = parseInt(x2.toString().length) - 1;

if (numbers < 0) {
    numbers = 0;
}


let count = 0;


while (result != 1) {

    for (; numbers >= 0; numbers--) {

        //            console.log(result)
        result += (Math.pow(parseInt(String(x2)[numbers]), 2));
        //            console.log((Math.pow(parseInt(String(x2)[0]), 2)))

        if (result == 1) {
            console.log(x + " is a happy number");
            return true;

        }


    }



    x2 = result;
    numbers = parseInt(x2.toString().length) - 1;

// console.log(“result : ” + result + ” —- x2 : ” + x2 + “—” + numbers)

    count++;
    if (count > 100) {
        return false;
    }

}

}
`

Is there a way to get values of only resolved promises?

I’m calling multiple services which includes network calls and other asynchronous services in my JavaScript application.

At first I was invoking these promises one by one. In the long run it’s getting hard to maintain since I’m invoking more services.

I read somewhere in the internet that we can use Promise.all() to group all promises and execute everything at a time.

The issue is, if any one of the promise is getting rejected all other promises are also getting rejected, this is not what I need.

I’m working in a status dashboard where I need to ping multiple services and show whether the service is up or not. By using Promise.all, it’s not working in a way I wished.

Tried another method Promise.any(), but it just resolves when any one is resolved.

Took a look at MDN docs, there are many functions for promise it’s overwhelming to me because I’m a beginner in JavaScript.

Currently I’ve created a very own service which takes care of calling all the promises and counts with the response. Is there any cleaner way to do it?

trying to push into a newly created array inside an object using function but it’s returning numbers instead of what was pushed [duplicate]

I tried to push into an array I just created within an object using function but it keeps returning numbers instead of the value pushed.

  const recordCollection ={
    5439: {
      albumTitle: 'ABBA Gold'
    }
  }
  function updateRecords(records, id, value){
    records[id].track = [];
    return  records[id].track.push(value)
  }
  console.log(updateRecords(recordCollection, 5439,'ABBA'));

according to my code, my result is supposed to be ‘ABBA‘ but it keeps returning the size of the array instead

image of what i got

Scroll element up instead of scrolling page down

I have a page that currently consists of a nav bar, a page header and the body/content. I’ve been looking for a way to have the body scroll up into/over the header instead of the entire page scrolling down. I’m not sure if that’s the right way to word it as I’m sure someone would have asked this before but I can’t find anything related to it.

As it is now, the header has text in the center and, when a user scrolls, loses space above the text. What I’d like is for the header to lose space below the text, effectively having scroll pull the body content up over the header.

Although it may not be of help, this is the code I’m working with

<Page>
  <Header>
      <h1 className={styles.titleText}>HEADER TITLE</h1>
      <p>Header sub text</p>
  </Header>
  <Body>
    <h1>This is where I would put some content ... if I was even slightly creative</h1>
  </Body>
</Page>

Where Page, Header and Body are arbitarily styled componets for reuse on most pages and the navbar is inside _app as it’s wanted on every page. I understand this may not be the best way, or even a very good way of doing things but I’m still learning and making mistakes as I go.