Decoding in JavaScript, delta compression

I have encoded numbers that I now need to decode and I don’t know how to do this.

this is the code I was given for encoding:

process.stdin.resume();
process.stdin.setEncoding('utf8');

var stdin = '';
process.stdin.on('data', function (chunk) {
  stdin += chunk;
}).on('end', function() {
  var lines = stdin.trim().split('n');
  for(var i=0; i<lines.length; i++) {
    process.stdout.write(lines[i]);
  }
})

My answer was

let findResult = function(data){
  let result = '';
  for(let i =1 ; i<lines.length ; i++){
    result=(lines[i] + lines[i+1])
  } return result;
}

But it doesn’t work

The numbers are

28 2 3 -3 -2 1 2 35 -1 0 0 -1

the output should be

28 30 33 30 28 29 31 66 65 65 65 64

Problem transferring a json string from the client to the esp8266 server

As part of my WLAN Thermometer project, I am planning a small file management for the files stored on the ESP. In this context, I need to transfer a list of file names from the client to the server. Because there is also the wonderful ArduinoJSON library for the ESP 8266, I would like to pass the data as a JSON object. The first excerpt from the scripts.js of my webpage shows how to create the filelist (contains all available files at ESP Filesystem) and compile and transfer the deletelist (whose elements should be deleted).

let fileID = 0
for (i = 2; i < FDatas.length; i += 2) 
{
   let fileInfo = {
      name: FDatas[i], 
      size: FDatas[i+1], 
      fileID: fileID, 
      marked: false};
      fileList.push(fileInfo);
   };
}

function deleteFiles() {

   let deleteFileList = [];
   let fileID = 0;

   for (let i = 0; i < fileList.length; i++) {
      if (fileList[i].marked == true) {
          let keyname = 'fileID_' + String(fileID);
          fileID += 1;

          let newEntry = {[keyname]:fileList[i].name}

          deleteFileList.push(newEntry);
      }
   }

   if (deleteFileList.length > 0) {
    
       var xhttp = new XMLHttpRequest();
       var formData = JSON.stringify(deleteFileList);
       xhttp.open("POST", "/deleteFiles");
       xhttp.send(formData);
    }
 }

On the server side, communication is organized as follows:
In the setup part of the arduino code:

  webserver.on("/deleteFiles", HTTP_POST, deleteFiles);

In the handler:

  void deleteFiles() {
     String input = webserver.arg("plain");
     Serial println(input);

     DynamicJsonDocument doc(2048);

     DeserializationError err = deserializeJson(doc, input);

     if (err) {
        Serial.println(F("deserializeJson() failed with code "));
        Serial.println(err.f_str());
     }

     JsonObject obj = doc.as<JsonObject>();

     // Loop through all the key-value pairs in obj
     for (JsonPair p : obj) {
        Serial.println(p.key().c_str());
        if (p.value().is<const char*>()) {
           auto s = p.value().as<const char*>();
           Serial.println(s);
        }
     }
     webserver.send(200);
  }

The result of these efforts is sobering. Nevertheless, the Serial.println(input); – command outputs the following,

 [{"fileID_0":"/settings.json"},{"fileID_1":"/tdata.js"},{"fileID_2":"/scripts.js"}]

the passage through the JSON object does not result in key value pairs.

Where is my mistake? Thank you very much for your good advice.

Changing link color of sub menus being visited on a one-page website

I need some help again, I have a one-page website with a navbar, which has sub menus. There is some javascript code that changes color of links that are currently being visited, which I’ll provide below. Now, this works fine, but I really can’t figure out how to make it work for the ‘services’ link, which holds the sub menu. No matter what I try it just won’t change the color of that one link.

Here’s what I’d like to do:
If I click on any of the sub menus, it changes that link color to blue, and also the ‘services’ link, which is the one that holds all the sub menu links.
On scroll to other ID’s, makes it go back to white, both the ‘service’ and whatever was selected within it.

I already figured out how to make it work for the main class, but not for the sub menus…

Can someone please help?

Thank you!!

  <div class="container">
     <div class="header-main">
        <div class="logo">
           <a href="#"><img src="images/logo.png"></a>
        </div>
        <div class="open-nav-menu">
           <span></span>
        </div>
        <div class="menu-overlay">
        </div>
        <!-- navigation menu start -->
        <nav class="nav-menu">
           <div class="close-nav-menu">
              <img src="images/close.svg" alt="close">
           </div>

           <ul class="menu">

              <li class="menu-item">
                 <a href="#home"><i class="fa fa-home"></i> Home</a>
              </li>

              <li class="menu-item">
                 <a href="#About"><i class="fa fa-address-card"></i> About</a>
              </li>

              <li class="menu-item menu-item-has-children">
                 <a href="#services" data-toggle="sub-menu"><i class="fa fa-file-code"></i> Services<i
                       class="plus"></i></a>
                 <ul class="sub-menu">
                    <li class="menu-item"><a href="#service1">Service1</a></li>
                    <li class="menu-item"><a href="#service2">Service2</a></li>
                    <li class="menu-item"><a href="#service3">Service3</a></li>
                 </ul>
              </li>

              <li class="menu-item">
                 <a href="#prices"><i class="fas fa-money-check-alt"></i> Prices</a>
              </li>

              <li class="menu-item">
                 <a href="#portfolio"><i class="fa fa-th"></i> Portfolio</a>
              </li>

              <li class="menu-item">
                 <a href="#contacts"><i class="fa fa-envelope"></i> Contacts</a>
              </li>

           </ul>
        </nav>


(() =>{
// Active links
  $('.header .menu > .menu-item > a').click(function () {
    $('.header .menu > .menu-item > a.activenavlink').removeClass('activenavlink');
    $(this).addClass('activenavlink');
});

$(window).scroll(function () {
    var href = $(this).scrollTop();
    $('.header .menu > .menu-item > a').each(function (event) {
        if (href >= $($(this).attr('href')).offset().top - 1) {
            $('.header .menu > .menu-item > a.activenavlink').removeClass('activenavlink');
            $(this).addClass('activenavlink');
        }
    });
});


/*header*/
.header{
    position: fixed;
    width: 100%;
    left:0;
    top:0;
    z-index: 99;
}
.header-main {

    background-color: black;
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 0;
    width: 100%;
    min-height: 8vh;
    opacity: .9;
    box-shadow: 2px 2px 5px black;
    border-bottom: 2px solid;
    border-image: linear-gradient(45deg, #88ff00, #006aff) 1;

}
.header .logo{
    padding: 15px;
    margin-bottom: -15px;
}
.header .nav-menu{
    padding: 0 15px;
}
.header .menu > .menu-item{
    display: inline-block;
    margin-left: 30px;
    position: relative;
}
.header .menu > .menu-item > a{
    display: block;
    padding: 12px 0;
    font-size: 16px;
    color: white;
    text-transform: capitalize;
    font-weight: 600;
    transition: all 0.3s ease;
}
/************************SUB MENUS********************************/

.header .menu > .menu-item > a .plus{
    display: inline-block;
    height: 12px;
    width: 12px;
    position: relative;
    margin-left:5px; 
    pointer-events: none;
}
.header .menu > .menu-item > a .plus:before,
.header .menu > .menu-item > a .plus:after{
    content:'';
    position: absolute;
    box-sizing: border-box;
    left: 50%;
    top:50%;
    background-color: white;
    height: 2px;
    width: 100%;
    transform: translate(-50%,-50%);
    transition: all 0.3s ease;
}
.header .menu > .menu-item:hover > a .plus:before,
.header .menu > .menu-item:hover > a .plus:after{
   background-color: #88ff00;
}
.header .menu > .menu-item > a .plus:after{
   transform: translate(-50%,-50%) rotate(-90deg);    
}

.header .menu > .menu-item > .sub-menu{

    border-bottom: 1px solid;
    box-shadow: 2px 2px 5px black;
    width: 220px;
    position: absolute;
    left:0;
    top:100%;
    background-color: black;
    opacity: .8;
    padding: 10px 0;
    border-top: 3px solid #88ff00;
    transform: translateY(10px);
    transition: all 0.3s ease;
    opacity:0;
    visibility: hidden;
}
@media(min-width: 992px){
.header .menu > .menu-item-has-children:hover > .sub-menu{
    transform: translateY(0);
    opacity: 1;
    visibility: visible;
 }
 .header .menu > .menu-item-has-children:hover > a .plus:after{
    transform: translate(-50%,-50%) rotate(0deg);       
 }
}
.header .menu > .menu-item > .sub-menu > .menu-item{
    display: block;
}
.header .menu > .menu-item > .sub-menu > .menu-item > a{
    display: block;
    padding: 10px 20px;
    font-size: 16px;
    font-weight: 600;
    color: white;
    transition: all 0.3s ease;
    text-transform: capitalize;
}

/************************LINK STATES********************************/

.header .menu > .menu-item > .sub-menu > .menu-item > a:hover,
.header .menu > .menu-item:hover > a{
    color: #88ff00;
}

.header .menu > .menu-item > .sub-menu > .menu-item > a:active,
.header .menu > .menu-item > a:active{
color: #006aff;
}

.header .menu > .menu-item > a.activenavlink{
color: #006aff;
}

Get values from array inside object using ES6 [duplicate]

I am giving interview for frontend development(React JS), I am doing my final year. Today I gave one interview, in that interviewer asked me to go to lodash site and asked to search for get, and I get below example. For the below example he asked to write JS function by uisng es6. I couldn’t get the question, I tried hard to understand it, most of the solution is inside either array or in object of array. Here the values are like Array inside object. Could any help me to understand this. Kindly teach me how to access the value of {c} by using ES6 or vanilla JS. Thanks in advance.

var object = { 'a': [{ 'b': { 'c': 3 } }] };

_.get(object, 'a[0].b.c');

// => 3

Requests unexpectedly delayed in Javasript

My axios request is taking too much time in sending the request to the server. I have the same issue like this https://github.com/axios/axios/issues/2609

What is this line saying and how can we avoid this mistake in Javascript while sending the request wrapped in promise.

Line: “axios creating a promise under the hood (before sending the request), and the main thread being busy with JavaScript execution”

Can you please tell me some scenerio while when we are doing the same mistake while sending a http request, means keeping the main thread busy?

I don’t know how to access Rate Inquiry tab of RCLGROUP site using Puppeteer

This is the analyzed page https://eservice.rclgroup.com/

I want to use Puppeteer to access the RATE INQUIRY tab but it seems to be rendered by a callGetrate() function;
I tried to use
await page.click(querySelectorAll('a[onclick^="callGetrate"]')) and try another way to access that callGetrate function by page.evalute(). Everything is not working. It just stops at the Booking Tab.

Screen of the RCLGROUP page

This is the function of the website

The callgetRate function of the RCLGROUP site

This is my code

try{
  const browser = await puppeteer.launch({
    headless: false,
    args: [
      "--disable-gpu",
      "--disable-dev-shm-usage",
      "--disable-setuid-sandbox",
      "--no-sandbox",
    ],
    defaultViewport: null,
  });
  const page = await browser.newPage();

  await page.goto(`${constants.BASE_URL}e-commerce/`);



  await page.waitForSelector('#userId');
  await page.type('#userId', constants.userAccount.username , { delay: 100 });
  await page.type('#password', constants.userAccount.password , { delay: 100 });

  await page.click('input[type=submit]');

  await page.evaluate(() => {
    callGetrate();
  })


    
  const cookie = await page.cookies();
  console.log(cookie);


  return cookie.map((x) => `${x.name}=${x.value}`).join("; ");  

  }catch(error){
    console.log("Failed to Login RCL ", error);
  }
}

Please help me!

Looping two separate arrays. Array 1 is the array of answers which length is unknown and Array 2 is the array of options which length is 4

Looping two separate arrays. Array 1 is the array of answers which length is unknown and Array 2 is the array of options which length is 4.

var array1 = ["a", "b", "d", "c","a","b",...] //Depending on the number of questions received

var array2 = ["a", "b", "c", "d"]

This is what I am doing

var array1 = ["a", "b", "d", "c","a","b"]
var array2 = ["a", "b", "c", "d"]

array1.forEach((rightAnswer, i) => {

    console.log(rightAnswer)

    array2.forEach((ele, i) => {
       console.log(ele)

       if (ele == rightAnswer) {
           console.log(true)
         }
     })
})

My console output from the condition is true for all the elements in array2 because the same are in array1.

What am I doing wrong?

why does javascript render removed components

Guys I’m working on a project now and I have a component that is returned by antd Menu item. It has 4 components: Home, Username, Login, and Register:

const items = [
        {
          label: <Link to='/'>Home </Link>, //- {JSON.stringify(user)}
          key: 'home',
          icon: <AppstoreOutlined />,
        },
        {
          label: 'Username',
          key: 'SubMenu',
          icon: <SettingOutlined />,
          children: [
            {
              label: 'Option 1',
              key: 'setting:1',
            },
            {
              label: 'Option 2',
              key: 'setting:2',
            },
            {
              label: <item onClick={logout}>Logout</item>,
              key: 'setting:3',
              icon: <LogoutOutlined />
          },
          ],
        },
        {
          label: <Link to='/register'>Register</Link>,
          key: 'register',
          icon: <UserAddOutlined />,
          style: { marginLeft: 1030},   // problem: hard-coded margin
        },
        {
          label: <Link to='/login'>Login</Link>,
          key: 'login',
          icon: <UserOutlined />,
          style: { marginLeft: 'auto'},
        },      
      ];
    
    useEffect(() => {
      if (user) {  // "user" is an object returned by userSelector
        items.splice(2, 2);
      }
    }, [user]);
    console.log(items);
    
    return <Menu  onClick={handleClick} selectedKeys={[current]} mode="horizontal" items={items} />;

As you can see, I’m useing a useEffect hook here. If the user is not logged in (so user === null), then the if statements in useEffect will not be executed; otherwise the Login and Register components in array itemswill be removed and hided, and only the first 2 are left.

From console.log(items); we can see what items is like currently. When a user is logged in, it does have only two components:
enter image description here

However we can still see Login and Register are there in such a circumastance:
enter image description here

So why do js and react render removed components?