Lodash _.isEquals method returns true even the comparing two objects are equal

I am trying to compare two objects with Lodash. One is getting as input and the other one is from db.Below is my method.


    console.log(`isDataChanged - fromDbData : ${JSON.stringify(fromDbData)}`);
    console.log(`isDataChanged - inputData : ${JSON.stringify(inputData)}`);

    if(_.isEqual(fromDbData, inputData)){
        console.log("isDataChanged - equal data found");
        return false;
    }else{
        console.log("isDataChanged - different data found");
        return true;
    }

};

the object is looks like below

{
...
"data": {
    "type": "Date",
    "name": "test",
    "tag": "sample",
    "category": null,
    "time": null,
    "caption": "the caption",
    "value": "none"
}
}

As the input parameter i’m sending the data property of both objects.
So when the values inside the data object for both I am expecting false. But it’s returning true.
Can someone please help me to understand what’s happening here?
Thanks!

Subtracting seconds from the time in Javascript

I need to create a second function that will subtract recorded time from this in seconds. Currently, this function will display time as event_time: 02:24:25 which is great, I just need to take my recorded time in seconds e.g. 85 seconds and subtract from this value.

so if DateTimeFun is 02:24:25 and recordedTime = 60, the new function would return 02:23:25, subtracting 1 minute.

let recordedTime = parseInt(inputData.new_value) - parseInt(inputData.previous_value);

let dateTimeFun = function (d) {
    let h = d.getHours();
    let m = d.getMinutes();
    let s = d.getSeconds();

    if (h < 10) h = '0' + h;
    if (m < 10) m = '0' + m;
    if (s < 10) s = '0' + s;

    return h + ':' + m + ':' + s;
}

Javascript Boolean check [duplicate]

I have a list of boolean

let x = [true,false,false,true,false]

I want to return true if at least 1 items is true

i.e. returns a value of false if every value is false

let y = [false,false,false,false,false] // should return false

I can’t seem to understand the use of array.every(function) to return false. It seems simple but I can’t figure the logic

Error when trying to use Material Top Tabs

im using react native for a project and im trying to use a component that react navigation offers, its the top tabs, everytime i use this though a error comes up, mostly one that says
“Invariant Violation: Tried to register two views with the same name RNCViewPager”, ive looked up what could cause this and some people said that it was because of the react-native-pager-view package itself so i tried to switch it out but i still have no resolved it .

if you need any code or anything let me know, and thanks in advanced

How to use API Keys stored in Google Firebase Cloud Functions

I am trying to use the MailChimp API in my react website that is hosted on Google Firebase. I am trying to store my API keys using cloud function and the environment configuration. However, I am not entirely certain how to access those configuration variables after I set them. Are those variables made global throughout my entire react app, or do I need to import them somehow?

I am trying to the follow the documentation listed here: https://firebase.google.com/docs/functions/config-env

Here is what my file structure looks like:

enter image description here

How can I add a setTimeOut() to run a function and insert data multiple times?

A few days ago I did a project and I had some problems, which where solved in this question, let me try to resume it.

I need to insert multiple objects into a DB in SQLServer, for that, I did a function that loops another function, which opens a connection, inserts and closes the connection, then, repeats it over and over again.

It worked fine, till today that was tested in a collegue PC, in the server of the job, I get this error:

Error: Requests can only be made in the LoggedIn state, not the LoggedInSendingInitialSql state

Here’s the code we tested (the same in my last question), it works in my PC, but not in the other:

var config = {
   ...
};

function insertOffice(index) {
    var connection = new Connection(config);
    connection.on("connect", function (err) {
        console.log("Successful connection");
    });
    connection.connect();
    
    let url = `https://api.openweathermap.org/data/2.5/weather?lat=${offices[index].latjson}&lon=${offices[index].lonjson}&appid=${api_key}&units=metric&lang=sp`;
    fetch(url)
        .then((response) => { return response.json(); })
        .then(function (data) {
            var myObject = {
                Id_Oficina: offices[index].IdOficina,
                ...
            };

            const request = new Request(
                "EXEC USP_BI_CSL_insert_reg_RegistroTemperaturaXidOdicina @IdOficina, ...",
                function (err) {
                    if (err) {
                        console.log("Couldnt insert data (" + index + "), " + err);
                    } else {
                        console.log("Data with ID: " + myObject.Id_Oficina +" inserted succesfully(" + index + ").")
                    }
                }
            );
            request.addParameter("IdOficina", TYPES.SmallInt, myObject.Id_Oficina);
            ...
            request.on("row", function (columns) {
                columns.forEach(function (column) {
                    if (column.value === null) {
                        console.log("NULL");
                    } else {
                        console.log("Product id of inserted item is " + column.value);
                    }
                });
            });
            request.on("requestCompleted", function () {
                connection.close();
            });
            connection.execSql(request);
        });
}

function functionLooper() {
    for (let i = 0; i < offices.length; i++) {
        let response = insertOffice(i);
    }
}

functionLooper();

So, I thought it would be a good idea to use a setTimeOut, to:

  1. Run functionLooper().
  2. Open connection, insert and close.
  3. Wait a few seconds.
  4. Repeat.

So, I changed to this:

setTimeout(functionLooper, 2000);

function functionLooper() {
    for (let i = 0; i < offices.length; i++) {
        let response = insertOffice(i);
    }
}

It works, but, as you can see, only waits when I first run it, so tried to make a function that runs setTimeout(functionLooper, 2000); like functionLooper() does, but it didn’t work either.

function TimerLooper() {
    for (let i = 0; i < offices.length; i++) {
        setTimeout(functionLooper, 500);   
    }
    
}

function functionLooper() {
    for (let i = 0; i < offices.length; i++) {
        let response = insertOffice(i);
    }
}

TimerLooper();

This shows me this error:

Error: Validation failed for parameter ‘Descripcion’. No collation was set by the server for the current connection.
file:///…:/…/…/node_modules/node-fetch/src/index.js:95
reject(new FetchError(request to ${request.url} failed, reason: ${error.message}, ‘system’, error));
^ FetchError: request to https://api.openweathermap.org/data/2.5/weather?lat=XX&lon=XX&appid=XX&units=metric&lang=sp failed, reason: connect ETIMEDOUT X.X.X.X:X

So, I have some questions

  1. How can I use properly setTimeOut? I did this function based on what I watch here in SO, but I just can’t get it and I don’t know what I’m doing wrong.
  2. Why it works in my PC and the other don’t? Do we have to change some kind of config or something?
  3. Using setTimeOut, is the correct way to solve this problem? if not, what would you sugegst me?

If any extra explanation needed, let me know and I’ll edit my question.

Admob plus, apache cordova, android- headache

Is anyone willing to walk me through how to use admob plus (https://admob-plus.github.io/docs/cordova) with Apache Cordova, using cordova run android as my testing grounds(android device).. I am not able to emulate a device and this all is a massive headache. This has been a very confusing process. I have this application on an app store and am just trying to put an ad on it…

for starters I’m not sure where this code goes in my application files:

let banner

document.addEventListener('deviceready', async () => {
  banner = new admob.BannerAd({
    adUnitId: 'ca-app-pub-xxx/yyy',
  })

  banner.on('impression', async (evt) => {
    await banner.hide()
  })

  await banner.show()
}, false)

I Know I have to fill in my ad unitID here in the code above but I left it blank for the purpose of this post.

I ran this command successfully and added my own appID here too : npx admob-plus install -p cordova

I would like to see ads on my application when I run it in cordova using run android and I would like to put them onto my play store app that is already published. (same app)

I tried to edit files and follow the directions on the abmob website but to no avail. It’s seems to be a very complicated process and there’s not a lot of references for it.

Thank you.

Eventstore client for NodeJs(@eventstore/db-client) stops the execution when ‘maxCount’ for reading the events from stream is increased more than 20

The program run fines when I have the following configuration:

let events = eventstoreClient.readStream(
       streamName,
       {
         fromRevision: END,
         direction: BACKWARDS,
         maxCount: 20
       }
     );

However, the program stucks(i.e. could not read the streams/events further) when maxCount is set to 100 or 1000 or maxCount option is not supplied!

Word Search Game Javascript

I’m creating a Word Search Game and I’m trying to figure out how to generate my chosen words onto the HTML grid I created. Somebody already helped me find a way to randomly generate the words into a row and column, but it generates the whole word into a cell, whereas I need each letter of the word to be randomly placed in an individual cell (If that makes sense).

const myWords = ["LOL", "HEY", "TOYS", "YES", "SIR", "JOY"]; 

for (let i = 0; i <myWords.length; i++) 
    {
const randomIndex = length => Math.floor(Math.random()*length);
const table = document.querySelector('table');
const randomRow = table.rows[randomIndex(myWords.length)];
const randomCell = randomRow.cells[randomIndex(myWords.length)];
const randomWord = myWords[Math.floor(Math.random() * myWords.length)];
randomCell.innerText = randomWord;   
    }

I planned on having the words horizontal, vertical and diagonal. I tried searching through Stack Overflow and Github, with no success. Can someone help?

Expected 15; but got 3: this is the bouncingBalls question from codewars

Here is the question:
A child is playing with a ball on the nth floor of a tall building. The height of this floor, h, is known.

He drops the ball out of the window. The ball bounces (for example), to two-thirds of its height (a bounce of 0.66).

His mother looks out of a window 1.5 meters from the ground.

How many times will the mother see the ball pass in front of her window (including when it’s falling and bouncing?

Three conditions must be met for a valid experiment:
Float parameter “h” in meters must be greater than 0
Float parameter “bounce” must be greater than 0 and less than 1
Float parameter “window” must be less than h.
If all three conditions above are fulfilled, return a positive integer, otherwise return -1.

Note:
The ball can only be seen if the height of the rebounding ball is strictly greater than the window parameter.

Here is my function:

function bouncingBall(h,  bounce,  window) {
  if(h>0 && bounce>0 && bounce<1 && window<h){
   let count=1;
    while(h>window){
      h=h*bounce;
      count=count+2;
      return count;
    }
    }else{
    return -1;
  }
}

The first testcase :(bouncingBall(3.0, 0.66, 1.5), 3) passes
This one (bouncingBall(30.0, 0.66, 1.5), 15) fails. Expected is 15 but function returns 3
Can someone point out my mistake in the function?

Divide a number into n parts by percentage

Trying to come up with a function to correctly split a given number into n parts, with each part split by percentage.

Let’s say I need to split 12 into 3 parts. The first part should be 50% of 6, second 30% of 6 and third 20% of 6. With rounding, this would result in:
[6,5,2] totalling 13.

Is there a way to run this calculation so it can correctly split 12 into 3 parts by the %, whereby it reduces the last item in the array by 1, then the second to last item in the array by 1 and so on until all 3 numbers total 12? In the example above, the end result would be [6,5,1].

Trying to avoid calculating the 3 parts individually then calculating the difference to manually reduce each, so attempting to work out a function to handle it.

why is my minimax recursion not looping through all possible outcomes

I’m not sure where I’m wrong with my function but it doesn’t check every possible out it seems to check a few and I don’t know how to fix it here’s my code

basic variables

const defaultScore = {0:0,1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0}
const [boardState,setBoardState] = useState(defaultScore)
const winArray = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,6,4]]
const AI = side
const human = (side == 'X') ? 'O' : 'X'

a function to copy the current state of the board without changing the actual state

const copyBoard=(original :Object,index ?:any, newValue?:any)=>{
            const copiedBoard = {...original} 
            index = Number(index)
            if(index != null && newValue != null){
                copiedBoard[index] = newValue
            }
            return copiedBoard
        }     

the function for checking end state

 const tryWin=(board :Object)=>{
                let win
                let check = true
                for (const i in winArray){
                    const v = winArray[i]                 
                    if(compareWin(board[v[0]],board[v[1]],board[v[2]])){
                        check = false
                        if(board[v[0]] == AI){
                            win = 10
                        }else{
                            win = -10
                        }
                    }  
                }
                if(!Object.values(board).includes(0) && check){
                    win = 0
                } 
                return win
            }

the minimax

        const miniMax = (board:Object, depth:number, isMax :Boolean ) =>{           
           
            if(typeof(tryWin(board)) == 'number'){
                return tryWin(board)
            }
      
            if(isMax){
                for (const v in board){              
                    if(board[v] === 0){
                        const outcome = -100
                        let simBoard = copyBoard(board,v,AI)
                        const newOutcome = miniMax(simBoard,depth+1,!isMax)
                        return (typeof(newOutcome) == 'undefined') ? outcome : Math.max(outcome,newOutcome) - depth
       
                    }
                }
            }else{
                for (const v in board){
                    if(board[v] === 0){
                        const outcome = 100
                        let simBoard = copyBoard(board,v,human)
                        const newOutcome = miniMax(simBoard,depth+1,!isMax)
                        return (typeof(newOutcome) == 'undefined') ?  outcome : Math.min(outcome,newOutcome) + depth
                       
                    }
                }
            }
        }
        const AImove =()=>{
            let move
            let bestOutcome = -100
            for(const v in boardState){
                if(boardState[v] === 0){
                    let simBoard = copyBoard(boardState,v,AI)
                    const outcome = miniMax(simBoard,0,true)
                    console.log('move',v,'outcome',outcome)
                    if(outcome > bestOutcome){
                        bestOutcome = outcome
                        move = Number(v)
                    }
                }          
            }
            return {move:move,outcome:bestOutcome}
        }

what am I getting wrong?

Reactjs mui spacing Stack and Grid

I used Stack, Divider Box and Grid, I am having trouble when spacing, please see the result below

<Stack direction="row"  spacing={1}>
  <Divider>
     <Box py={3} sx={{width: '100%', border: 1}}>
          <Stack
            direction="row"
            justifyContent="flex-end"
            alignItems="center"
            spacing={3}
            sx={{ marginBottom: '9px', width: 150 }}
          >

           <Grid container spacing={3} sx={{float: 'right'}} justify="flex-end">
                <Grid item xs sx={{float: 'right'}}>
                <LocalFireDepartmentIcon
                color={selectedThreat ? '#E01C1C' : 'disable'}
              />
                <Typography
                variant="subtitle2"
                sx={{ letterSpacing: '1.5px', marginLeft: '4px' }}
                className={classes.upperCase}
              >
                {name}
              </Typography>
                </Grid>
                <Grid item xs sx={{float: 'right'}}>
                <Typography
                variant="p"
                sx={{ letterSpacing: '1.5px', textDecoration: "underline", color: '#191F25', fontSize: '14px', lineHeight: '20px'  }}
                onClick={handleOpen}
              >
                Cancel
              </Typography>
                </Grid>
            </Grid>

          </Stack>
     </Box>
  </Divider>
</Stack>

Expected Result

enter image description here

current result

enter image description here

Don’t read this comment, I did this because I can submit question,
Don’t read this comment, I did this because I can submit question,
Don’t read this comment, I did this because I can submit question,
Don’t read this comment, I did this because I can submit question,

How running JavaScript function in order?

What am I doing?
I’m try running two function in order but JavaScript is calling and running two function in same time.

What’s the problem?
The setModalBox function give undefined error if is called before setProjects function.

What have I already tried?
I tried used Promise with setTimeout it work, but can sometimes setModalBox function be called before and give of same error.

Part of JavaScript:

  init() {
    this.setProjects();
    // this.setModalBox();
  }

  setProjects() {
    let response_promise = fetch("contents/projects.json")

    document.addEventListener("DOMContentLoaded", function() {
      response_promise.then(response => response.json().then(projects => {
        // ? Gradient in border for each color language

        for(let project in projects){
          // Div project
          var div = document.createElement("div");
          div.className = "project";
          div.id = `project-${projects[project].name}`
          document.querySelector(".projects").appendChild(div);

          // Tittle project
          var h1 = document.createElement("h1");
          h1.className = "tittle-project";
          h1.innerHTML = projects[project].name;
          document.querySelector(`#project-${projects[project].name}`).appendChild(h1);

          // Paragraph project
          var p = document.createElement("p");
          p.className = "about-project";
          p.innerHTML = projects[project].about;
          document.querySelector(`#project-${projects[project].name}`).appendChild(p);
        }
      }))
    }, false)

    return new Promise((resolve, reject)=>{
      setTimeout(()=>{
        this.setModalBox()
      }, Math.random() * 2000)
    })
  };

  setModalBox(){
    let projectsLength = document.querySelectorAll(".projects")[0].children.length;
    let modalBox = this.modalBox;

    for(let i = 0; i <= projectsLength; i++){
      let projectsAll = document.querySelectorAll(".projects")[0].children[i];

      // That "try" is for not to show error in console
      try{
        // Open Modal Box
        projectsAll.onclick = function(){
          modalBox.style.display = "block"
        };
      }catch{}

      // Close Modal Box, when click at "X"
      this.modalBoxClose.onclick = function(){
        modalBox.style.display = "None"
      };

      // Close Modal Box, when click out of Modal Box
      window.onclick = function(){
        if(event.target == modalBox){
          modalBox.style.display = "None"
        }
      }

      // Close Modal Box, when press esc key
      document.addEventListener("keydown", function(event){
        if(event.key == "Escape"){
          modalBox.style.display = "None"
        }
      })
    }
  }

HTML:

<!DOCTYPE html>
<html lang="pt-br">
  <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>Projetos - Vitor Hugo's Portifolio</title>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js" defer></script>
  </head>

  <body>
    <header>
      <div id="wrapperJS" style="position: relative; overflow: hidden">
      <nav>
        <a class="logo" href="/">Vitor Hugo</a>
        <div class="mobile-menu">
          <div class="line-1"></div>
          <div class="line-2"></div>
          <div class="line-3"></div>
        </div>
          <ul class="nav-list">
            <li><a href="index.html">Home</a></li>
            <li><a href="sobre.html">Sobre</a></li>
            <li><a href="projetos.html">Projetos</a></li>
            <li><a href="contatos.html">Contato</a></li>
          </ul>
        </nav>
      </div>
    </header>
    <script src="mobile-screen.js"></script>

    <!-- Boxes -->
    <div class="projects"></div>

    <!-- Modal Boxes -->
    <div class="modal-box">
      <div class="modal-box-contents">
        <span class="modal-box-close">&times;</span>
        <p>test</p>
      </div>
    </div>
  </body>
</html>

What I have to do? please help me. If need more information,ask. And sorry for any error orthography and grammar I am studing English.

Renaming ID of all child elements after dynamically deleting line in table

I created a form in Google Apps Script, to send data to a sheet, but I wanted a way to dynamically add rows by clicking a button. I found this article (https://www.geeksforgeeks.org/how-to-dynamically-add-remove-table-rows-using-jquery/) that uses jquery that works well great, even shows how to delete a line, whilst also renaming the <tr> tag id to the correct number as well as the text content of the first <td> tag.

However, I added an autocomplete input using materialize, and thought I could use the same method to change the <input> ID when deleting a row, but, seem to be failing miserably.

To see what I’m talking about, I’d invite you to run the code snippit, and add a few rows. If you delete any of the rows (apart from the last one), then all the Row numbers go down by one, the <tr> tag ids go down by one, but the <input> tag ids don’t.

I apologize if my query isn’t clear, and would be happy to try and explain more, if needed.

Here is all the code to recreate the project in a “normal” code editor :

JS in first snippit, html in second

let rowIdx = 1;

//This list would be generated from a google sheet on page load for the autocomplete input
let listRecettes = {
  "Banana": null,
  "Orange": null,
  "Mango": null,
}

//ON LOAD  
document.addEventListener('DOMContentLoaded', function() {

  var elems = document.querySelectorAll('.autocomplete');
  var instances = M.Autocomplete.init(elems);

  // Load words into autocomplete
  populateWordsRecettes();
});


//Autocomplete initialize
function populateWordsRecettes() {
  var autocomplete = document.getElementById("recettes1");
  var instances = M.Autocomplete.init(autocomplete, {
    data: listRecettes
  });
}

//autocomplete initialize for added rows
function newLineAutocomplete() {
  var autocomplete = document.getElementById(`recettes${rowIdx}`);
  var instances = M.Autocomplete.init(autocomplete, {
    data: listRecettes
  });
  console.log(`Row ${rowIdx} initialized`);
}

document.getElementById('btnAjouterLigne').addEventListener('click', addLine);

function addLine() {
  // jQuery button click event to add a row.
  // Adding a row inside the tbody.
  $('#tableBodyCasse').append(`<tr id="R${++rowIdx}">
          <td class = "row-index">Row ${rowIdx}</td>
          <td><div class = "input-field"><input type="text" id="recettes${rowIdx}" class="autocomplete"></div></td>
          <td>Lorum Ipsum</td>
          <td>Lorum Ipsum</td>
          <td>Lorum Ipsum</td>
          <td><button class="btn waves-effect red darken-4 waves-light btnSupprimerLigne">Delete</button></td>
           </tr>`);

  //Initialize the autocomplete for new row
  newLineAutocomplete();
}


//delete line
$('#tableBodyCasse').on('click', '.btnSupprimerLigne', function() {

  // Getting all the rows next to the 
  // row containing the clicked button
  let child = $(this).closest('tr').nextAll();

  // Iterating across all the rows 
  // obtained to change the index
  child.each(function() {

    // Getting <tr> id.
    let id = $(this).attr('id');

    // Getting the <p> inside the .row-index class.
    let idx = $(this).children('.row-index');

    // Gets the row number from <tr> id.
    let dig = parseInt(id.substring(1));

    // Modifying row index.
    idx.html(`Row ${dig - 1}`);

    // Modifying row id.
    $(this).attr('id', `R${dig - 1}`);
  });



  //MY PROBLEM STARTS HERE
  let childInput = $(this).find('input').nextAll();
  childInput.each(function() {
    let idInput = $(this).attr('id');
    let digInput = parseInt(idInput.substring(9));
    console.log(digInput);
    $(this).attr('id', `recettes${digInput - 1}`);
  });

  // Removing the current row.
  $(this).closest('tr').remove();

  // Decreasing the total number of rows by 1.
  rowIdx--;
});
<!DOCTYPE html>
<html>

<head>
  <base target="_top">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
  </script>

</head>

<body>

  <div class="container">
    <!-- CONTAINER START -->
    <table class="striped">
      <thead>
        <tr>
          <th>Row num</th>
          <th>Product</th>
          <th>Type</th>
          <th>Qty</th>
          <th>Total</th>
          <th>Delete line</th>
        </tr>
      </thead>

      <tbody id="tableBodyCasse">
        <tr id="R1">
          <td class="row-index">Row 1</td>
          <td>
            <div class="input-field"><input type="text" id="recettes1" class="autocomplete"></div>
          </td>
          <td>unknown</td>
          <td>2</td>
          <td>5,4</td>
          <td><button class="btn waves-effect red darken-4 waves-light btnSupprimerLigne">Delete</button>
          </td>
        </tr>
      </tbody>
    </table>

    <button class="btn waves-effect waves-light" id="btnAjouterLigne">Add line
    <i class="material-icons left">add_circle_outline</i>
  </button>


  </div>
  <!--CONTAINER END -->






  <?!= include("page-casse-js"); ?>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</body>

</html>