Random moving animation

I need to make random smooth moving animation relative to parent. I have 3 images and i need to make them randomly moving all the time. I need to make this on vanilla js.
example

Any thoughts?

I googled for a long time and i found answers only on jquery or other libraries. Also i tried to write random position function

function moveElmRand(elm) {
   elm.style.position = "absolute";

   elm.style.top = Math.floor(Math.random() * elm.offsetWidth) + "%";
   elm.style.left = Math.floor(Math.random() * elm.offsetHeight) + "%";
}

but it doesnt work.

Dynamic percentage in number range

I have a range of prices for multiple products from 1$ to 100$. As well, as I have understanging that for product with cost of 1$ is 15% of margin will apply and for 100$ product – 5%.

Mean that:
1. 1$ product will cost 1 + 1 * 0.15 = 1.15$
2. 100$ product will cost 100 + 100 * 0.05 = 105$

Question is how to calculate margin percentage for all range of numbers between 1$ and 100$?

I have tried to different approaches but in the end I just don’t understand how to make this calculation dynamic, so I will apply formula to a big data range and get the result

how to write below regex without catastrophic backtracking

I’m trying to use a regex in javascript where special characters and leading and trailing spaces are not allowed in an input element. Maximum character length is 50.

The regular expression I’m using is

/^[a-zA-Z0-9]+([ ]?[a-zA-Z0-9]+)*$/

But this is causing issues when the string is large and there is a special character in the end. On research I found that this is happening due to catastrophic backtracking but I’m unable to optimise the regex. Kindly help me find an optimum solution to this issue.

I tried debouncing the keyup event for the input element but that is also not solving the issue.

Scroll into view on click issue vanilla js

I am usually doing this sort of function in react but, my scroll into view only works for the first click event listener function but none of the others. why is this? error shows: cannot read properties of null reading (‘addEventListener’)

note: I am using a linked script file at the bottom of page if that is helpful in any way.

HTML

<section class="navbarBox">

    <div class="logoTextBox">
      <div>
      </div>
    </div>
    <nav class="anchorBox">
      <div>
        <a id="mission" class="navTag">Our Mission</a>
      </div>
      <div>
        <a id="#services" class="navTag">Services</a>
      </div>
      <div>
        <a id="#team" class="navTag"> Our Team</a>
      </div>
      <div>
        <a class="navTag">New Patients</a>
      </div>
      <div>
        <a id="#contact" class="navTag">Get In Touch</a>
      </div>
    </nav>

  </section> 


  <!-- QUOTE -->
  <section id="scrollToMission" class="quoteBox">

    <p class="quote">"hello this is my quote."</p>
    <p class="source">- SMARTY PANTS</p>
  </section>

  <!-- BUILDING WEBSITES -->
  <section id="scrollToServices" class="buildingWebsitesBox">

</services>

JS

// SCROLL ON CLICK:
// navbar ids
let mission = document.querySelector('#mission')
let services = document.querySelector('#services')
let team = document.querySelector('#team')
let contact = document.querySelector('#contact')

// section ids
let scrollToMission = document.querySelector('#scrollToMission')
let scrollToServices = document.querySelector('#scrollToServices')
let scrollToTeam = document.querySelector('#scrollToTeam')
let scrollToContact = document.querySelector('#scrollToContact')

// scroll to click
mission.addEventListener('click', () => {
  scrollToMission.scrollIntoView({behavior: 'smooth'})
  console.log('clicked');
})

services.addEventListener('click', () => {
  scrollToServices.scrollIntoView({behavior: 'smooth'})
  console.log('clicked');
})

team.addEventListener('click', () => {
  scrollToTeam.scrollIntoView({behavior: 'smooth'})
})

contact.addEventListener('click', () => {
  scrollToContact.scrollIntoView({behavior: 'smooth'})
})

My Responsive Navbar toggle doesn’t work (javascript)

I am trying to make a responsive navbar for my project (I am still a newbie learning this). I want to get a dropdown-like nav anchors when I click on the menu bar (3 horizontally parallel lines). I used the Eventlistener and it is not setting that toggle_button to ‘active’. I have been going through YouTube videos, some questions on here, and references all over the internet and I cannot seem to find the solution.

Here is my code block.


const toggleButton = document.getElementsByClassName('toggle_btn')[0];
 const navbarLinks = document.getElementsByClassName('navbar_links')[0];

 toggleButton.addEventListener('click', () => {
    navbarLinks.classList.toggle('active')
 });
/*General Styling*/
body {
    overflow: hidden;
    background-color: grey;
    color: #d4af37 ;
    font-size: 20px;
    display: flex;
    justify-content: center;
    min-height: 90vh;
    background: url("images/background.png") no-repeat;
    background-size: cover;
    background-position: center;
    font-family: Baskerville, "Palatino Linotype", Palatino, "Century Schoolbook L", "Times New Roman", "serif";
  }

header{
    display: flex;
    justify-content: space-between;
    align-content: center;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 50px;
    padding: 20px 100px;
}


a{
    padding-right: 10px;
}

nav ul {
    margin: 0;
    padding: 0;
    display: flex;
}
nav li {
    list-style: none;
}
nav li a {
    padding: 1rem;
    display: block;
}


/*Styling using class*/
.nav {
    text-decoration: none;
    color: #d4af37;
    position: relative;
    font-weight: 500;
}

.nav::after{
    content: '';
    position: absolute;
    left: 0;
    bottom: -6px;
    width: 90%;
    height: 1px;
    background: #d4af37;
    border-radius: 5px;
    transform: scaleX(0);
    transition: transform .5s;
}

.nav:hover::after{
    transform: scaleX(1);
}

/*responsive button*/
.toggle_btn {
    position: absolute;
    top: 4.5rem;
    right: 1rem;
    display: none;
    flex-direction: column;
    justify-content: space-between;
    width: 30px;
    height: 21px;
    margin-right: 200px;
}

.toggle_btn .bar{
    height: 3px;
    width: 100%;
    background-color: #a1852b;
    border-radius: 10px;
}


/*responsive nav bar*/
@media only screen and (max-width: 600px) {
    .toggle_btn{
        display: flex;
    }
    .navbar_links{
  display:none;
  }
  
  header{
        flex-direction: column;
        align-items: flex-start;
    }

    nav ul{
        width: 100%;
        flex-direction: column;

    }

    nav li{
        padding-left: 4rem;
    }

    nav li a{
        padding: .5rem 1rem;
    }

    nav.active {
        display: flex;
    }
  nav.active .nav{
        display:block;
        width: 100%;
    }
}
<!--Logo and Nav-->
    <header> 
            <!--Logo and brandName-->
            <div id="logo_div"> 
                <img class="images" id="logo" src="images/logo+name.png" alt="Crux Logo and Brand Name here.">
            </div>
                <!--Nav bar-->
            <div id="nav_div">
                
                <!--Nav-bar toggle-->
                <a href="#" class="toggle_btn"> 
                    <span class="bar"> </span>
                    <span class="bar"> </span>
                    <span class="bar"> </span>
                </a>

                <nav class="navbar_links">
                    <ul> 
                        <li><a class="nav" href="#">Home</a></li>
                        <li><a class="nav" href="#">About Us</a></li>
                        <li><a class="nav" href="#">Services</a></li>
                        <li><a class="nav" href="#">Contact</a></li>
                    </ul>
                </nav>
            </div>
    </header>

How to filter array by the key?

I need filter array by bookmakers.key === ‘bovada’. I need data on this. This question is important to me for studing arrays.

const array = [
    {
        "id": "9ee1340b779938f9a7f829f22d41534d",
        "sport_key": "soccer_argentina_primera_division",
        "sport_title": "Primera División - Argentina",
        "commence_time": "2023-03-30T23:00:00Z",
        "home_team": "Defensa y Justicia",
        "away_team": "Velez Sarsfield BA",
        "bookmakers": [
            {
                "key": "foxbet",
                "title": "FOX Bet",
                "last_update": "2023-03-30T14:01:13Z",
                "markets": [
                    {
                        "key": "h2h",
                        "last_update": "2023-03-30T14:01:13Z",
                         "outcomes": [
                            {
                                "name": "Argentinos Juniors",
                                "price": 1.74
                            },
                            {
                                "name": "Godoy Cruz",
                                "price": 5.4
                            },
                            {
                                "name": "Draw",
                                "price": 3.25
                            }
                        ]
                    }
                ]
            },
            {
                "key": "bovada",
                "title": "Bovada",
                "last_update": "2023-03-30T13:58:23Z",
                "markets": [
                    {
                        "key": "h2h",
                        "last_update": "2023-03-30T13:58:23Z",
                         "outcomes": [
                            {
                                "name": "Argentinos Juniors",
                                "price": 1.74
                            },
                            {
                                "name": "Godoy Cruz",
                                "price": 5.4
                            },
                            {
                                "name": "Draw",
                                "price": 3.25
                            }
                        ]
                    }
                ]
            }
        ]
    },
    {
        "id": "6253cf45de6b5050c44505812e12f5fd",
        "sport_key": "soccer_argentina_primera_division",
        "sport_title": "Primera División - Argentina",
        "commence_time": "2023-03-31T00:30:00Z",
        "home_team": "Argentinos Juniors",
        "away_team": "Godoy Cruz",
        "bookmakers": [
            {
                "key": "foxbet",
                "title": "FOX Bet",
                "last_update": "2023-03-30T14:01:13Z",
                "markets": [
                    {
                        "key": "h2h",
                        "last_update": "2023-03-30T14:01:13Z",
                         "outcomes": [
                            {
                                "name": "Argentinos Juniors",
                                "price": 1.74
                            },
                            {
                                "name": "Godoy Cruz",
                                "price": 5.4
                            },
                            {
                                "name": "Draw",
                                "price": 3.25
                            }
                        ]
                    }
                ]
            },
            {
                "key": "bovada",
                "title": "Bovada",
                "last_update": "2023-03-30T13:58:23Z",
                "markets": [
                    {
                        "key": "h2h",
                        "last_update": "2023-03-30T13:58:23Z",
                        "outcomes": [
                            {
                                "name": "Argentinos Juniors",
                                "price": 1.74
                            },
                            {
                                "name": "Godoy Cruz",
                                "price": 5.4
                            },
                            {
                                "name": "Draw",
                                "price": 3.25
                            }
                        ]
                    },
                    {
                        "key": "spreads",
                        "last_update": "2023-03-30T13:58:23Z",
                        "outcomes": [
                            {
                                "name": "Argentinos Juniors",
                                "price": 1.95,
                                "point": -0.75
                            },
                            {
                                "name": "Godoy Cruz",
                                "price": 1.87,
                                "point": 0.75
                            }
                        ]
                    }
                ]
            }
        ]
    },
]

I expected get the array without foxbet information. I can only filter simple arrays. I can’t filter this array for two days now…

I tried array.filter(i => i.bookmakers.filter(k => k.key === “bovada”)) but, no.

My connection to Mosquitto via PHP works in Visual Studio Code but not in browser. Should I change my apache2 configuration?

I want to connect to my Mosquitto broker running on my VPS with ubuntu 22.04.
I am using the library php-mqtt/clients and my code works fine in visual studio code but when I upload it to my web server (Apache2 and PHP 8.2.4) it does not work. Something is happening as if there is an error the code will disconnect and then I will see some of the json messages on the screen
I am using a javascript AJAX to retrieve the JSON but without success. I am under the impression that my Apache 2 configuration is the issue. Port 1883, 8883 (TLS) and 9001 (TLS Websocket) all work with MQTTX and 9001 works via javascript.

Chat GPT advises this but I do not trust it

<VirtualHost *:443>
    ServerName example.com

    # SSL configuration
    SSLEngine on
    SSLCertificateFile /path/to/certificate.pem
    SSLCertificateKeyFile /path/to/key.pem

    # PHP Mosquitto configuration
    MosquittoTLSVersion tlsv1.2
    MosquittoCACertificateFile /path/to/ca.crt
    MosquittoClientCertificateFile /path/to/client.crt
    MosquittoClientKeyFile /path/to/client.key

    # PHP application configuration
    DocumentRoot /path/to/app
    <Directory /path/to/app>
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

Here is my PHP named “testweb.php”

<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/shared/config.php';

use PhpMqttClientConnectionSettings;
use PhpMqttClientExamplesSharedSimpleLogger;
use PhpMqttClientExceptionsMqttClientException;
use PhpMqttClientMqttClient;
use PsrLogLogLevel;

// Create an instance of a PSR-3 compliant logger. For this example, we will also use the logger to log exceptions.
$logger = new SimpleLogger(LogLevel::INFO);


// Define your MQTT authorization credentials.
$username = 'name';
$password = 'password';

try {
    // Create a new instance of an MQTT client and configure it to use the shared broker host and port.
    $client = new MqttClient(MQTT_BROKER_HOST, MQTT_BROKER_TLS_PORT, 'test-publisher', MqttClient::MQTT_3_1, null, $logger);

    // Create and configure the connection settings as required.
    $connectionSettings = (new ConnectionSettings)
        ->setUseTls(true)
        ->setTlsSelfSignedAllowed(true)
        ->setTlsClientCertificateFile("client.crt")
        ->setTlsClientCertificateKeyFile("client.key")
        ->setTlsClientCertificateKeyPassphrase("certificatepasswd1!*")
        ->setUsername($username)
        ->setPassword($password);

    // Connect to the broker with the configured connection settings and with a clean session.
    $client->connect($connectionSettings, true);

    // Subscribe to a topic.
$client->subscribe('sensor/data', function ($topic, $message){ 

        echo $message;
}, 0);

$client->loop(true);


    // Gracefully terminate the connection to the broker.
    $client->disconnect();
} catch (MqttClientException $e) {
    // MqttClientException is the base exception of all exceptions in the library. Catching it will catch all MQTT related exceptions.
    $logger->error('Connecting with TLS or publishing with QoS 0 failed. An exception occurred.', ['exception' => $e]);
}

and my very basic javascript for test purposes:

<html>
    <head>
        <title> MQTT Test via PHP and AJAX</title>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

    </head>
    <body>
        <p id="temperature">Temperature =  </p>
        <p id="humidity">Humidity =  </p>
        <p id="latitude">Latitude =  </p>
        <p id="longitude">Longitude =  </p>
        <p id="date">Date =  </p>
        <p id="status"> Status =</p>
     

        <script>
            // Send an AJAX request to the PHP script to get the latest message
i = 0;            
setInterval(function() {
  
  $.ajax({
    url: 'testweb.php',
    dataType: 'json',
    success: function(data) {
      // Update the HTML elements with the new data
      document.getElementById('temperature').innerHTML = data.temperature;
      document.getElementById('humidity').innerHTML = data.humidity;
      document.getElementById('latitude').innerHTML = data.latitude;
      document.getElementById('longitude').innerHTML = data.longitude;
      document.getElementById('date').innerHTML = data.date + "/" + data.month + "/" + data.year + "  " + data.hours + ":" + data.minutes + ":" + data.seconds;
    }
  });
  document.getElementById('status').innerHTML = "Status = Javascript has been running " + i + " time";
  i = i+1;
  
}, 1000); // Poll every second

        </script>
    </body>
</html>

Does anybody have an idea how to make this work and if I have to change something in Apache2?

When I try opening the testweb.php in the browser it keeps loading non stop and sometimes (I can not figure what trigggers this) I get an Error that indicate could not connect to socket.

I do not know what to try next as I would just be trying stuff without knowing what I am doing at this stage.

Everything works, but I’m getting a console error

This is the Script:

This is the page: https://intro-component-sign-up-five.vercel.app/

  const spanContainer = document.querySelectorAll(".form-container span");
  const spanImg = document.querySelectorAll(".errorIcon")
  const submitBtn = document.querySelector(".submit");
  const inputAll = document.querySelectorAll("form input");
  const input = document.querySelector("input");
  let formData = {}; // objeto para armazenar os dados do formulário

  input.addEventListener("input", function(event) {
    formData[input.name] = input.value; // atualiza o valor do objeto com o valor atual do input
  });

  //input.addEventListener("input", errorForm);


  function handleClick(event) {
    inputAll.forEach((input) => {
      if(input.value === "") {
        event.preventDefault();
        errorForm();  
      }
    }) 
  }

  function errorForm() {
    
    spanContainer.forEach((span) => {
      if(span.innerText === ""){
        span.classList.add("errorMessage"); 
      } 
      if(span.classList.contains("errorMessage")) {
        span.classList.add("error");
      }
      spanImg.forEach((img) => {
      if(img.classList.contains("errorIcon")) {
        img.classList.add("selected");
      }
      })
    inputAll.forEach((input) => {
      if(input.classList.contains("submit") === false && input.value === "") {
        input.classList.add("error");
        input.nextElementSibling.nextElementSibling.classList.add("error");
      } else {
        input.classList.remove("error");
        input.nextElementSibling.classList.remove("errorMessage");
        input.nextElementSibling.classList.remove("selected");
        input.nextElementSibling.nextElementSibling.classList.remove("error");

      }
    })  
    })
  }


  submitBtn.addEventListener("click", handleClick);

Things work fine, just the way I want it to work, but I keep getting this console error:


Uncaught TypeError: Cannot read properties of null (reading 'classList')
at script.js:41:51
at NodeList.forEach (<anonymous>)
at script.js:35:12
at NodeList.forEach (<anonymous>)
at errorForm (script.js:23:17)
at script.js:16:7
at NodeList.forEach (<anonymous>)
at HTMLInputElement.handleClick (script.js:13:12)

I tried to fix it by removing the second “nextElementSibling”, but when I do it the page doesn’t work the way I want anymore. The errorMessage is not removed once I submit again after I fulfill the respective input.

connect HTML to Appjs React

can i connect my index.html into App.js (React)

<div class="content">
          <form action="v2/v2.html" class="form">
            <label for="user">Nama</label>
            <input type="text" name="user" id="user" />
            <button type="button" id="load-app">Load App</button>
          </form>
        </div>
<script src="v3-website/src/App.js"></script>

so when i click the button i want it to direct into App.js
can someone tell me how to do that?

i use tag it dont work
i have ask chatGPT and the solution still dont work

Recursive function returns correctly and array of objects but the function which calls it receives undefined [duplicate]

I would like to ask for some help. I have to work with a recursive function in order to traverse a tree in DFS manner. The algorithm works fine, despite the function still in development so please have mercy on me with that in mind.
I, however, need to use axios in my recursion because under some condition I must pull my data from the database, therefore my recursive function becomes async + it has a for loop.
Here is the code. A small walk-through:

  • traverse traverses the tree in DFS manner and calls my API under some condition
  • trversewrapper calls the function in a for loop
  • getMaxCia values calls the api for the values

Why is the result array in the traversWrapper equal to [null] and therefore undefined instead of returning my array of objects? I console log the return of the recursive function an it indeed returns an array of valid objects.

async traverse(
    assetDto: NestedAssetDto,
    direction: string,
    startNodeChildren: NestedAssetDto[],
    useOverwritten: boolean,
    accountId: string,
    traversedTree: NestedAssetDto[] = [],
    alreadyTraversed: NestedAssetDto[] = [],
    ): Promise<NestedAssetDto[]>{
      if(!assetDto && !isObject(assetDto)){
      console.log('Asset is undefined or is not an object')
      return [];
      }

      if(!startNodeChildren ||  startNodeChildren.length === 0 && assetDto.identifier === traversedTree[0].identifier){
        console.log(`Traversed array in the traverse function: ${JSON.stringify(traversedTree)}`)
        console.log("This is the end of the recursive function. Goodbye.")
        return traversedTree;
      }

      const startNodePushed = traversedTree.find(asset => asset.identifier === traversedTree[1].identifier);
      if(!startNodePushed){
        traversedTree.push(assetDto)
        alreadyTraversed.push(assetDto);
      };

      const visitedAsset = traversedTree.find(asset => asset.identifier === assetDto.identifier);
      !visitedAsset && traversedTree.push(assetDto);
      alreadyTraversed.push(assetDto);

      if(traversedTree && traversedTree.length > 1 && traversedTree[0].identifier === assetDto.identifier){
        console.log("We are back at the starting node for a next iteration")
        assetDto.hasNestedAsset = startNodeChildren;
      }
      
      console.log(`Direction: ${direction} for ${assetDto.identifier}. Should use overwritten ${useOverwritten}`);
      let confidentialityFromDb;
      let integrityFromDb;
      let availabilityFromDb;

      if(useOverwritten && traversedTree[0].identifier === assetDto.identifier){
        if(!assetDto.props.overwrittenConfidentiality || !assetDto.props.overwrittenIntegrity || !assetDto.props.overwrittenAvailability){
          console.log('Asset overwritten flags are true but overwritten props are undefined. Returning the tree as it is now')
          return traversedTree;
        }
      }

      if(assetDto.assetType !== AssetType.BusinessProcess && direction === Direction.Top){
        console.log('Asset is not of type BP but direction is up. By law, this can not be true.')
        return [];
      }

      if(!assetDto.hasNestedAsset || assetDto.hasNestedAsset.length === 0){
        const isFirstElement = traversedTree && traversedTree.length === 0;
        console.log( `Asset ${JSON.stringify(assetDto)} does not have nested assets. This is the ${isFirstElement ? 'first and only' : 'last'} element in the tree.`);
        console.log(`Starting again with ${traversedTree[0].identifier}`)
        return this.traverse(traversedTree[0], direction, startNodeChildren, useOverwritten, accountId, traversedTree, alreadyTraversed);
      }

      const filteredNestedAssets = assetDto.hasNestedAsset.reduce((acc, nestedAsset) => {
        if ( (assetDto.assetType === AssetType.BusinessProcess && nestedAsset.assetType === AssetType.BusinessProcess && direction === Direction.Top) || (assetDto.assetType === AssetType.BusinessProcess && nestedAsset.assetType !== AssetType.BusinessProcess && direction === Direction.Bottom)
          || (assetDto.assetType !== AssetType.BusinessProcess && nestedAsset.assetType !== AssetType.BusinessProcess && direction === Direction.Bottom)
        ) { acc.push(nestedAsset) }
        return acc;
      }, []);

      const nodeConfidentiality = useOverwritten ? assetDto.props.overwrittenConfidentiality : assetDto.props.calculatedConfidentiality;
      const nodeIntegrity = useOverwritten ? assetDto.props.overwrittenIntegrity : assetDto.props.calculatedIntegrity;
      const nodeAvailability = useOverwritten ? assetDto.props.overwrittenAvailability :  assetDto.props.calculatedAvailability;

      for(let [index, element] of filteredNestedAssets.entries()){
        {
          if(assetDto.identifier === traversedTree[0].identifier){
            startNodeChildren.splice(index, 1);
          }

          if(element.calculateUsingOverwrittenValues && element.overwriteValues){
            if(!element.props.overwrittenConfidentiality || !element.props.overwrittenAvailability || !element.props.overwrittenIntegrity){
              return
            }
          }

          const nestedNodeConfidentiality = useOverwritten ? element.props.overwrittenConfidentiality : element.props.calculatedConfidentiality
          const nestedNodeIntegrity = useOverwritten ? element.props.overwrittenIntegrity : element.props.calculatedIntegrity
          const nestedNodeAvailability = useOverwritten ? element.props.overwrittenAvailability :  element.props.calculatedAvailability
          
          if(nestedNodeConfidentiality > nodeConfidentiality || nestedNodeIntegrity > nodeIntegrity || nestedNodeAvailability > nodeAvailability){
            if(useOverwritten){
             {
                const ciaFromDb = await this.getCiaMaxValues(accountId, element.identifier, direction)
                console.log(`Values from db: ${JSON.stringify(ciaFromDb)}`)
                confidentialityFromDb = ciaFromDb.maxConfidentiality;
                integrityFromDb = ciaFromDb.maxIntergrity;
                availabilityFromDb = ciaFromDb.maxAvailability;
              }         
            } else{
              {
                const ciaFromDb = await this.getCiaMaxValues(accountId, element.identifier, direction)
                console.log(`Values from db: ${JSON.stringify(ciaFromDb)}`)
                confidentialityFromDb = ciaFromDb.maxConfidentiality;
                integrityFromDb = ciaFromDb.maxIntergrity;
                availabilityFromDb = ciaFromDb.maxAvailability;
              }         
            }
          }
          let alreadyCalculatedAsset = traversedTree.find(asset => asset.identifier === element.identifier);

          if(alreadyCalculatedAsset){
            console.log(`This asset is an already visted asset: ${JSON.stringify(alreadyCalculatedAsset)}`)

            const visitedAssetConfidentiality = useOverwritten ? alreadyCalculatedAsset.props.overwrittenConfidentiality 
            : alreadyCalculatedAsset.props.calculatedConfidentiality;
            const visitedAssetIntergrity  = useOverwritten ? alreadyCalculatedAsset.props.overwrittenIntegrity 
            : alreadyCalculatedAsset.props.calculatedIntegrity;
            const visitedAssetAvailability  = useOverwritten ? alreadyCalculatedAsset.props.overwrittenAvailability 
            : alreadyCalculatedAsset.props.calculatedAvailability;
            const { value: maxConfidentiality } = confidentialityFromDb ? confidentialityFromDb : calculateCIAMaxValue(visitedAssetConfidentiality, nodeConfidentiality);
            const { value: maxIntergrity } =  integrityFromDb ? integrityFromDb : calculateCIAMaxValue(visitedAssetIntergrity, nodeIntegrity);
            const { value: maxAvailability } = availabilityFromDb ? availabilityFromDb : calculateCIAMaxValue(visitedAssetAvailability, nodeAvailability);

            alreadyCalculatedAsset = {
              ...alreadyCalculatedAsset,
              props: 
              {
                [useOverwritten ? 'overwrittenConfidentiality' : 'calculatedConfidentiality']: maxConfidentiality, 
                [useOverwritten ? 'overwrittenIntegrity' : 'calculatedIntegrity']: maxIntergrity,
                [useOverwritten ? 'overwrittenAvailability' : 'calculatedAvailability']: maxAvailability,
                overwriteValues: useOverwritten ? true : false,
                calculatedUsingOverwrittenValues: useOverwritten ? true : false
              },
              oldProps: 
              {
                [useOverwritten ? 'overwrittenConfidentiality' : 'calculatedConfidentiality']: nestedNodeConfidentiality, 
                [useOverwritten ? 'overwrittenIntegrity' : 'calculatedIntegrity']: nestedNodeIntegrity,
                [useOverwritten ? 'overwrittenAvailability' : 'calculatedAvailability']: nestedNodeAvailability,
              }
            };

            
            console.log(`The asset is visited again. Here is the result after the mutate: ${alreadyCalculatedAsset}`)
            this.traverse(element, direction, startNodeChildren, useOverwritten, accountId, traversedTree);
          }

          const { value: maxConfidentiality } = confidentialityFromDb ? confidentialityFromDb : calculateCIAMaxValue(nestedNodeConfidentiality, nodeConfidentiality);
          const { value: maxIntergrity } =  integrityFromDb ? integrityFromDb : calculateCIAMaxValue(nestedNodeIntegrity, nodeIntegrity);
          const { value: maxAvailability } = availabilityFromDb ? availabilityFromDb : calculateCIAMaxValue(nestedNodeAvailability, nodeAvailability);

          element = {
            ...element,
            props: 
            {
              [useOverwritten ? 'overwrittenConfidentiality' : 'calculatedConfidentiality']: maxConfidentiality, 
              [useOverwritten ? 'overwrittenIntegrity' : 'calculatedIntegrity']: maxIntergrity,
              [useOverwritten ? 'overwrittenAvailability' : 'calculatedAvailability']: maxAvailability,
              overwriteValues: useOverwritten ? true : false,
              calculatedUsingOverwrittenValues: useOverwritten ? true : false
            },
            oldProps: 
              {
                [useOverwritten ? 'overwrittenConfidentiality' : 'calculatedConfidentiality']: nestedNodeConfidentiality, 
                [useOverwritten ? 'overwrittenIntegrity' : 'calculatedIntegrity']: nestedNodeIntegrity,
                [useOverwritten ? 'overwrittenAvailability' : 'calculatedAvailability']: nestedNodeAvailability,
              }
          }

          //For debbuging at any time
          console.log(`current node id: ${element.identifier}, parent node id: ${assetDto.identifier},`)
          console.log(`current node c: ${nestedNodeConfidentiality}, parent node c: ${nodeConfidentiality}, max c: ${maxConfidentiality}`)
          console.log(`current node i: ${nestedNodeIntegrity}, parent node i: ${nodeIntegrity}, max i: ${maxIntergrity}`)
          console.log(`current node a: ${nestedNodeAvailability}, parent node a: ${nodeAvailability}, max a: ${maxAvailability}`)
                 
          traversedTree.push(element);
          this.traverse(element, direction, startNodeChildren, useOverwritten, accountId, element.oldProps, traversedTree);
        }
      };
  }

  async getAssetTreePath(accountId: string, assetId: string) {
    const url = `${process.env.BASE_URL}/accounts/${accountId}/assets/${assetId}/assetsTree`;
    const secretKey = process.env.LAMBDA_SECRET_KEY;
    const secretBase64Hash = generateSecretBase64Hash(secretKey, url)
    const config = {
      headers: {
        'x-lambda-hash': secretBase64Hash,
      }
    }
    const { data } = await axios.get(url, config);
    return data;
  }

  async traverseWrapper(nestedAssetArray: NestedAssetDto[], accountId: string) {
    if (nestedAssetArray.length > 2) {
      const errMessage =
        "Received an array which includes more than two elements. Cannot proceed in more than 2 directions.";
      console.log(errMessage);
      throw new Error(errMessage);
    }

    const result: NestedAssetDto[][]=[]
    for(const el of nestedAssetArray){
      const useOverwritten = el.overwriteValues && el.calculateUsingOverwrittenValues;
      const arrayOfTraversedEl = el ? await this.traverse(el, el.direction, el.hasNestedAsset, useOverwritten, accountId) : [];
      console.log(`result ${JSON.stringify(arrayOfTraversedEl)}`)

      result.push(arrayOfTraversedEl);
    }
    console.log(`result ${JSON.stringify(result)}`)
    if(result.length === 2){
      return result[0].concat(result[1])
    }else if(result.length === 1){
      return result[0]
    }
    return [];

  }
  async updateCiaInDb(accountId: string, assetId: string, ciaToUpdate?: AssetDto[]) {
    console.log(`C I A flattened array with elements to update: ${JSON.stringify(ciaToUpdate)}`)

    if(!ciaToUpdate || ciaToUpdate.length === 0){
      console.log("Array of elements to update is empty, therefore will not send a request.")
      return;
    }
    const url = `${process.env.BASE_URL}/accounts/${accountId}/assets/${assetId}/updateCia`;
    const secretKey = process.env.LAMBDA_SECRET_KEY;
    const secretBase64Hash = generateSecretBase64Hash(secretKey, url)
    const config = {
      headers: {
        'x-lambda-hash': secretBase64Hash,
      },
    }
    await axios.put(url, ciaToUpdate, config);
  }

  getCiaMaxValues = async (accountId: string, assetId: string, direction: String) => {
    const secretKey = process.env.LAMBDA_SECRET_KEY;
    const url = `${process.env.BASE_URL}/accounts/${accountId}/assets/${assetId}/nestedAssetsMaxValues?useOverwritten=${direction}`
    const secretBase64Hash = generateSecretBase64Hash(secretKey, url)
    const config = {
      headers: {
        'x-lambda-hash': secretBase64Hash,
      }
    }
    const response = await axios.get(url, config)
    const { data } = response;
    return data
  }

Corrupted Excel file getting downloaded through API gateway

I am using a lambda function to generate a excel file. I am accessing this generated excel file in my react frontend via API gateway. However when I am trying to download this file in through my frontend, I can’t seem to open it. It says that “the given file format does not match its extension”. I saw a few related question here in stackoverflow and tried the configuration but I am still not able to resolve this error.

Also my excel file is getting created correctly as just for testing, I tried to save my excel file in my s3 bucket first and download manually from there. I was able to download the correct excel file with expected output in it. However when I send it to the frontend through the API gateway it gets corrupted.

Here is my lambda function code

import json

import io
import base64
import pandas as pd
from openpyxl import Workbook
from openpyxl.worksheet.datavalidation import DataValidation

data = [
    ["HEAD1", "Head2"],
    ["hello", "operating_system"],
    ["durablility", "material"],
    ["longevity", "item_name"],
    
]

def lambda_handler(event, context):
    # i generate my workbook correctly using openpyxl
    wb = Workbook()
    ws = wb.active
    for r in data:
      ws.append(r)
    buffer = io.BytesIO()
    wb.save(buffer)
    excel_final = buffer.getvalue()
    buffer.close()
    return {
        'statusCode': 200,
        'headers': {
        'Access-Control-Allow-Origin': '*',
        },
        'body': base64.b64encode(excel_final),
        'isBase64Encoded': True
    }

Here is how I am fetching it from my frontend , I have tried this multiple options in the request none of them seem to work

const requestOptions = {
    method: 'GET',
    headers: {
       'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    }, 
    
  };  

     fetch(url,requestOptions)
     .then(response => {
      if (response.ok) {
        return response.arrayBuffer();
      }
    })
    .then(blob => {
      const file = new File([blob], "demo.xlsx",{type:"application/xml"})
      const link = document.createElement('a')
      const url = URL.createObjectURL(file)

      link.href = url
      link.download = file.name
      document.body.appendChild(link)
      link.click()

Also in my API gateway I have enabled binary media types and set it to application/vnd.openxmlformats-officedocument.spreadsheetml.sheet still no help.

I am unable to understand what is causing my file to get corrupted. Any help will be appreciated.

Google drive API – ClientError – insufficientFilePermissions

I want to have access to a user’s google drive, create a folder and save files in the user’s drive. I have a client request where I get a token and save it on my db, then use it to create a Google drive service and then hopefully create a folder and a file.
I created a project on google cloud, created and enabled API key, created Auth2.0 credentials and set authorized js origins and Authorized redirect URIs
to http://localhost:3000, and http://localhost for developing, got Client Id and Client secret.

I got a pop up window that asks me to sign in for google, and another pop up that asks confirm you want to sign to the app as the user. (I never got a pop up that asks for google drive permissions). after allowing, I get the token, creating the server, I do have the @service object which seems ok, but when I try to create a folder I have insufficient permission error.
I tried to change the scope but I can see that /drive is the least restricting.

Didn’t find any other solution for my problem, would be happy for help for what is missing. Thanks!

This is my client request, first I’m getting the user’s token –

  google.accounts.id.initialize({
    client_id: '<%= ENV["GOOGLE_CLIENT_ID"] %>',
    scope: 'https://www.googleapis.com/auth/drive',
    callback: handleCredentialResponse,
    error_callback: myErrorCallback
  });
  google.accounts.id.prompt();

Then in handleCredentialResponse I save the token in my DB successfully.

This is my Google drive service –

require 'googleauth'
require 'google/apis/drive_v3'
class GoogleDriveService  
 def initialize
  @drive = Google::Apis::DriveV3 # Alias the module
  @service = @drive::DriveService.new
  @client_id = ENV['GOOGLE_CLIENT_ID']
  @client_secret = ENV['GOOGLE_CLIENT_SECRET']
  @service.key = ENV['GOOGLE_API_KEY']
  @user_token = User.current.company.properties.dig(:content_definitions, :google_token)
  @service.authorization = get_credentials(@client_id, @client_secret, @user_token)
 end
...
  def get_credentials(client_id, client_secret, user_token)
    client_secrets = Google::Auth::ClientId.new(client_id, client_secret)
    
    # Create an access token from the user token
    token = Google::Auth::UserRefreshCredentials.new(
      client_id: client_secrets.id,
      client_secret: client_secrets.secret,
      scope: 'https://www.googleapis.com/auth/drive',
      access_token: user_token
    )
    
    # Authorize the Drive service using the access token
    @service.authorization = token
    
    # Return the authorized Drive service object
@service

end

Then here, when I try @service.list_files I get an insufficient permissions error –

  def get_or_create_folder(folder_name)
    # Check if the folder already exists
    query = "mimeType='application/vnd.google-apps.folder' and trashed=false and name='#{folder_name}'"
    debugger
    results = @service.list_files(q: query, fields: 'nextPageToken, files(id, name)')
    files_list = results.files
    
    if results.any?
      # Return the existing folder
      return results.first.id
    else
      # Create a new folder
      folder_metadata = Google::Apis::DriveV3::File.new(name: folder_name, mime_type: 'application/vnd.google-apps.folder')
      folder = service.create_file(folder_metadata, fields: 'id')
      return folder.id
    end

end

WebView 3D loading SVG only, not updating the SVG in the page

I have been trying to assist a friend in troubleshooting a problem with the Android version of WebView 3D. Basically, a URL click should load a new svg image within the page content, and it does so for every other device OS. However on Android, the svg loads and page redirects to just that svg.

Here is the onLoad function:

function onLoad() {
    findPhase();
}
function highlightImages(placement, item) {
    if (item.contentDocument) {
        var images = item.contentDocument.getElementsByTagName("svg")
        for (var j = 0; j < images.length; j++) {
            images[j].style.setProperty('--color-' + placement, '#FFFF00')
        }
    }
}

And this is what code it builds in the page:

<div class="finder-image" id="find-ascent-1" style="display: block">
   <div class="spacer"></div>
   <object class="image" type="image/svg+xml" onload="highlightImages('B9-1', this)" data="../location_images/Location_9.svg"></object>
   <div class="note">NOTE: Something must happen here</div>
</div>

I tried looking through the source code to determine the problem. My suspicion is that it has something to do with the call but I can’t seem to prove it.