slick slide in jquery website showing blank after last slide and then starting from begining

i have a website done in html, i have used slick slide to move some products in two sections, at a time i want to display 5 products and then loop it infinitely, i have 10 products exact for both sections, yet after the last product, its showing white space and then again starting from begining:

$(document).ready(function() {
  $('.customer-logos5').slick({
    slidesToShow: 5,
    slidesToScroll: 1,
    autoplay: true,
    autoplaySpeed: 4500,
    arrows: false,
    dots: false,
    slidesToScroll: 1,

    autoplaySpeed: 0,
    speed: 8000,
    infinite: true,
    pauseOnHover: true,
    cssEase: 'linear',

    responsive: [{
      breakpoint: 768,
      settings: {
        slidesToShow: 1
      }
    }, {
      breakpoint: 520,
      settings: {
        slidesToShow: 1
      }
    }]
  });
});

my live website is : live section names Trendy collections and New arrivals, can anyone please tell me what could wrong in here, thanks in advance

How to use JS push() method in Node SQL query [duplicate]

I am trying to push the result from a DB query in Node JS.
The result is displayed fine in the console.log() but is not pushed to the array outside the SQL query.

I think the promlem is related to promises? But i cannot figure out a workaround.

Here is the code block:

let arr = []

router.post('/getfavorites', utils.isLoggedIn, (req, res) => {
    const data = req.user
    const customerId = data.customerid

    try {
        db.query('SELECT * FROM favorites WHERE customerid = ?', [customerId], async (error, results) => {
            if (error) {
                console.log(error)
            } else {
                // console.log(results)
                    let index = 0
                    results.forEach(result => {
                        db.query('SELECT * FROM recepies WHERE recepieid = ?', [result.recepieid], async (err, resultsRes) => {
                            console.log("DB query 2:" + result.recepieid)
                            if (err) {
                                console.log(`Secound db result: error`)
                            } else {
                                let recepieObj = {
                                                recepieid: resultsRes[index].recepieid,
                                                portions: resultsRes[index].portions,
                                                type: resultsRes[index].type,
                                                health: resultsRes[index].health,
                                                recepie: resultsRes[index].recepie
                                            }
                                arr.push(recepieObj)
                                console.log(`Secound db result: ${recepieObj.recepie}`)
                            }
                        })
                    })
    
        }

        res.json({message: arr})
        })
        } catch (error) {
        if (error.response) {
            res.json(error.response.status);
            res.json(error.response.data);
        } else {
            res.json(error.message);
        }
        }
})

Is there a way to return onSnapshot data from a method without using hooks

I am building a react app with a Firestore Database and I am stuck on using onSnapshots.

When I use getDocs, it works well and returns the data from that collection.

const getAircraft = async () => {
    const q = query(aircraftCollection, orderBy('series', 'asc'));
    const aircraft = await getDocs(q);

    const aircraftData = aircraft.docs.map((doc) => ({
        id: doc.id,
        ...doc.data()
    }));

    return aircraftData;
}

However, when I use onSnapshot, the return gives me null:
The console log shows the data and even pushes to console when I make changes in Firestore.

const getAircraftOnSnapshot = () => {
    const q = query(aircraftCollection, orderBy('series', 'asc'));
    const unsubscribe = onSnapshot(q, (snapshot) => {
        const aircraftData = snapshot.docs.map((doc) => ({
            id: doc.id,
            ...doc.data()
        }));
        // console.log(aircraftData);
        return aircraftData;
    });
    
    return () => unsubscribe();
}

I have tried

return unsubscribe; 

But still doesnt work.

Please help.

Why does gtag.js specify the same ID twice in the installation code?

The GA4 gtag.js installation code is as follows:

<!-- Google tag (gtag.js) -->
<script
  async
  src="https://www.googletagmanager.com/gtag/js?id=G-ZQA9CN2Q3Z"
></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag() {
    dataLayer.push(arguments);
  }
  gtag('js', new Date());
  gtag('config', 'G-ZQA9CN2Q3Z');
</script>

Why was G-ZQA9CN2Q3Z mentioned twice?

Is it necessary to load the <script /> tag twice if I want to install two ga4 at the same time?

How do you convert this DES encryption code from Java code to JS?

How to convert this Java code to js?

public static String getSignature(String skey, String iv, String data) throws Exception {
  IvParameterSpec β…£ = new IvParameterSpec(iv.getBytes("utf-8"));
  DESKeySpec desKey = new DESKeySpec(skey.getBytes("utf-8"));
  SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
  SecretKey key = keyFactory.generateSecret(desKey);
  Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
  cipher.init(Cipher.ENCRYPT_MODE, key, β…£);
  byte[] databyte = cipher.doFinal(data.getBytes("utf-8"));
  return new String(Base64.getEncoder().encode(databyte));
}

I tried it myself, and I got:

  function getSignature(
    skey,
    iv,
    data,
  ) {
    const IV = Buffer.from(ivString, 'utf-8');
    const desKey = Buffer.from(skey, 'utf-8');

    const cipher = crypto.createCipheriv('des-cbc', desKey, IV);
    let encrypted = cipher.update(data, 'utf-8', 'base64');
    encrypted += cipher.final('base64');
    return encrypted;
  }

But I got an ERR_CRYPTO_INVALID_KEYLEN error because my key is not 8 in length. I’m guessing that my js code is missing this part of the java code, but I don’t know how to translate this part into js..:

  SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
  SecretKey key = keyFactory.generateSecret(desKey);

Having difficulty accessing the .contentDocument of an svg when running Cypress

If I run my app in the browser normally (Chrome), everything is fine, but if I try in Chrome with a Cypress test (just a basic one that opens the app in localhost:3000 and so far does nothing else), I get the following error during the page load:

Uncaught TypeError: Cannot read properties of null (reading 'querySelector')
    at ui.js:203:19
    at i ((index):4:1616)
    at (index):4:1989

Upon further investigation, the function that causes the problem is the one that sets up the svg file and returns a variable set to true, that is periodically checked to resolve a promise elsewhere in the app to signify the app is ready. So, if I put a breakpoint on the line in my app that sets the value of svgMap, I can see when I step over it in the Cypress run, that it returns null, but in the normal browser run without Cypress it returns the document of the #svg-map element perfectly well:

export function svgMapLoaded() {
  //-------------GLOBAL SVG CONSTANTS AFTER SVG LOADED---------------//
  svg = document.getElementById('svg-map');
  svgMap = document.getElementById('svg-map').contentDocument; // <-- this line returns null in Cypress
  svgTag = svgMap.querySelector('svg');
  paths = Array.from(svgMap.querySelectorAll('path'));
//rest of function

Incidentally, the #svg-map element is an object element:
<object id="svg-map" data="resources/svgMaster.svg" type="image/svg+xml" tabindex="0"></object>

This function is called as follows on page load:

<head>
    <script type="module" src="initialData.js"></script>
    <!-- <script src="resources/SVGPathData.cjs"></script> -->
    <script type="module" src="transferAndAttack.js"></script>
    <script type="module" src="resourceCalculations.js"></script>
    <script type="module" src="gameTurnsLoop.js"></script>
    <script type="module">
    import {
        svgMapLoaded
    } from "./ui.js";
    const svg = document.getElementById("svg-map");
    svg.addEventListener("load", () => {
        svgMapLoaded();
    });
    </script>
    <script type="module" src="ui.js"></script>
    <script type="module" src="music.js"></script>
    <script type="module" src="manualExceptionsForInteractions.js"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
    <title>Domination: World Conquest</title>
</head>

Obviously this variable returning null means that the rest of the function fails, and therefore the cypress test. Please can someone inform me of any special ways to configure Cypress to work correctly? I will gladly provide any further information.

I tried adding a timeout of one second to the function in my app to see if that might help, but it seems like it has already been doomed to failure before the timeout is executed, as stepping over the line still returns null.

Raytracing sphere diffuse reflection bug

I made this ray tracer in javascript to run on html with imageData. I have been using the book “Ray Tracing in One Weekend” as a reference (https://raytracing.github.io/books/RayTracingInOneWeekend.html) and I am on the step where I create a diffuse material (essentially the surfaces with diffuse materials pick up the color of another object through randomly generated rays in a recursive process) Apparently, the diffuse material works on the plane I created but it doesn’t work on the sphere. All the normal calculations work fine on the sphere and it does seem to respond to light a little bit but the color returned appears to be the same for the entire sphere. What are possible explanations for this kind of bug? I have attached the runnable js code snippet below.

var cvs = document.getElementById("viewport");
var ctx = cvs.getContext("2d");
var h = cvs.height;
var w = cvs.width;
var data = ctx.getImageData(0,0, w, h);
var scene ={};
//object for all the stuff and parameters in the scene
scene.skybox = {
  color: {
    x:150,
    y:200,
    z:250,
  }
}
scene.camera = {
    point: {
      x: 0,
      y: 0,
      z: 10,
    },
    fieldOfView: 45,
    vector: {
      x: 0,
      y: 0,
      z: 0,
    },
  };

scene.lights = [
  {
    point:{
      x: 0,
      y: -5,
      z: 0,
    },
    j:50,
  },
  // {
  //   x:5,
  //   y:-5,
  //   z:-5,
  // }
]; 
scene.objects = [
    {
      type: "sphere",
      point: {
        x: 0,
        y: 0,
        z: 0,
      },
      color: {
        x: 0,
        y: 0,
        z: 0,
      },
      radius: 1,
      ambient:0,
      lambert:0.5,
      specular:0,
      diffuse:0,
    },
    {
      type: "plane",
      point: {
        x: 0,
        y: 1,
        z: 0,
      },
      vector:{
        x:0,
        y:-1,
        z:0,
      },
      color: {
        x: 255,
        y: 255,
        z: 255,
      },
      ambient:0,
      lambert:0.5,
      specular:0,
      diffuse:0,
    },
    // {
    //   type: "triangle",
    //   a:{x:3,y:1,z:-3},
    //   b:{x:-2,y:0,z:-2},
    //   c:{x:2,y:-2,z:-2},
    //   color:{
    //     x:0,
    //     y:100,
    //     z:100
    //   },
    //   ambient:0.1,
    //   lambert:1,
    //   specular:0,
    // },
  ];
window.onload=init();
function init(){
  var left_arrow = 37;
  var right_arrow = 39;
  var up_arrow = 38;
  var down_arrow = 40;
  var w_key = 87;
  var a_key = 65;
  var s_key = 83;
  var d_key = 68;
  render();
  window.onkeydown= function(gfg){
    if(gfg.keyCode === a_key){
      scene.camera.point.x-=1;
      render();
    };
    if(gfg.keyCode === d_key)
    {
      scene.camera.point.x+=1;
      render();
    };
    if(gfg.keyCode === w_key){
      scene.camera.point.y-=1;
      render();
    };
    if(gfg.keyCode === s_key)
    {
      scene.camera.point.y+=1;
      render();
    };
    if(gfg.keyCode === left_arrow){
      scene.lights[0].point.z+=1;
      render();
    };
    if(gfg.keyCode === right_arrow)
    {
      scene.lights[0].point.z-=1;
      render();
    };
    if(gfg.keyCode === up_arrow){
      scene.lights[0].point.x-=1;
      render();
    };
    if(gfg.keyCode === down_arrow)
    {
      scene.lights[0].point.x+=1;
      render();
    };
  };
}
function render(){
  var start = performance.now();
  var camera = scene.camera;
  var eVec = unitVector(subtract(camera.vector, camera.point));
  var eVecRight = unitVector(crossProduct(eVec, {x:0, y:1, z:0}));
  var eVecUp = unitVector(crossProduct(eVecRight, eVec));
  var halfFOV = (Math.PI * (camera.fieldOfView / 2)) / 180;
  var halfW = Math.tan(halfFOV);
  var halfH = (h/w)*halfW;
  var W = halfW*2;
  var H = halfH*2;
  var Wpx = W/(w-1);
  var Hpx = H/(h-1);
  var index;
  var spx = 50;
  var ray = {
      point: camera.point,
  };
  for (var i=0; i<scene.objects.length; i++){
    var object = scene.objects[i];
    if (object.type == "plane"){
      object.vector = unitVector(object.vector);
    }else if (object.type == "triangle"){
      object.vector = unitVector(crossProduct(subtract(object.b, object.a),subtract(object.c,object.a)));
    }
  }
  for (var x =0; x<w; x++){
      for(var y =0; y<h; y++){
        var color = {x:0,y:0,z:0};
        for (var i=0; i<spx; i++){
          var xcomp = scaleVector(eVecRight, (x+Math.random()) * Wpx - halfW);
          var ycomp = scaleVector(eVecUp, (y+Math.random()) * Hpx - halfH);
          ray.vector = unitVector(add3Vectors(eVec, xcomp, ycomp));
          color = addVectors(gamma(scaleVector(trace(ray, scene, 2), 1/spx)),color);
        }
        // console.log(color);
        index = (y*w+x)*4;
        data.data[index]=clamp(color.x, 0, 255);
        data.data[index+1]=clamp(color.y, 0, 255);
        data.data[index+2]=clamp(color.z, 0, 255);
        data.data[index+3]=255;
      }
  }
  ctx.putImageData(data, 0,0);
  var end = performance.now();
  console.log(end-start);
}

function trace(ray, scene, iter){
  // if(iter>3) return;
  var distObj = SceneIntersect(ray, scene);
  // if (distObj[0] === Infinity){
  //   return scene.skybox.color;
  // }else{
  //   pointOfIntersect = addVectors(scene.camera.point, scaleVector(ray.vector, distObj[0]));
  //   return surface(ray, scene, distObj[1], pointOfIntersect, iter);
  // }
  if (distObj[0] === Infinity){
    var pointOfIntersect = null;
  }else{
    var pointOfIntersect = addVectors(scene.camera.point, scaleVector(ray.vector, distObj[0]));
  }
  // console.log(distObj);
  return surface(ray, scene, distObj[1], pointOfIntersect, iter);
  // return {x:distObj[0]*10, y:0, z:0};
}

function SceneIntersect(ray, scene){
  var closest = [Infinity, null];
  for (var i=0; i<scene.objects.length; i++){
    var object = scene.objects[i];
    if (object.type == "sphere"){
      var dist = raySphereIntersect(object, ray);
    }else if(object.type == "plane"){
      var dist = rayPlaneIntersect(object, ray);
    }else if(object.type == "triangle"){
      var dist = rayTriangleIntersect(object,ray);
    }
    if (dist !== undefined && dist < closest[0]){
      closest = [dist, object];
    }
  }
  return closest;
}

function isLightVisible(pt, scene, light) {
  var distObject = SceneIntersect(
    {
      point: pt,
      vector: unitVector(subtract(pt, light)),
    },
    scene
  );
  return distObject[0] > -0.005;
}

function gamma(a){
  return {
    x:Math.sqrt(a.x),
    y:Math.sqrt(a.y),
    z:Math.sqrt(a.z),
  };
}
function dotProduct(a,b){
    return a.x*b.x+a.y*b.y+a.z*b.z;
}

function unitVector(a){
    m = Math.sqrt(dotProduct(a,a));
    return {
        x: a.x/m,
        y: a.y/m,
        z: a.z/m
    };
}

function scaleVector(a, m){
  return {
    x:a.x*m,
    y:a.y*m,
    z:a.z*m
  }
}

function subtract(a,b){
    return {
        x: a.x- b.x,
        y: a.y- b.y,
        z: a.z - b.z
    };
}

function crossProduct(a,b){
    return {
       x: a.y*b.z-a.z*b.y,
       y: a.z*b.x-a.x*b.z,
       z: a.x*b.y-a.y*b.x
    };
}

function add3Vectors(a,b,c){
  return {
    x:a.x+b.x+c.x,
    y:a.y+b.y+c.y,
    z:a.z+b.z+c.z
  }
}

function addVectors(a,b){
  return{
    x:a.x+b.x,
    y:a.y+b.y,
    z:a.z+b.z
  }
}

function reflect(a,n){
  return subtract(scaleVector(n, 2*dotProduct(n,a)),a);
}

function clamp(x, min, max){
  if(x<min) return min;
  if (x>max) return max;
  return x;
}

// function raySphereIntersect(sphere, ray){
//     var ec = subtract(ray.point, sphere.point);
//     // var v = dotProduct(ray.vector, ec);
//     // var ecDot = dotProduct(ec, ec);
//     // var s2 = sphere.radius * sphere.radius - ecDot + v*v;
//     var a = dotProduct(ray.vector, ray.vector);
//     var b = dotProduct(ec, ray.vector);
//     var c = dotProduct(ec, ec) - sphere.radius*sphere.radius;
//     var d = b*b -a*c;
//     if (d <0){
//         return;
//     }else{
//         // var dist = v - Math.sqrt(s2);
//         var dist = (-b-Math.sqrt(d))/a;
//         // return v - Math.sqrt(s2);
//         // return (-b-Math.sqrt(d))/a;
//         // console.log(dist);
//         return dist;
//     }
// }

// function raySphereIntersect(sphere, ray){
//   var oc = subtract(ray.point, sphere.point);
//   var p = dotProduct(ray.vector, oc);
//   var q = dotProduct(oc, oc) - sphere.radius*sphere.radius;
//   var d = (p*p)-q;
//   if (d<0){
//     return;
//   }else{
//     var droot = Math.sqrt(d);
//     d1 = -p-droot;
//     // d2 = -p+droot;
//     return d1;
//   }
// }

function raySphereIntersect(sphere, ray){
  var ec = subtract(sphere.point, ray.point);
  var v = dotProduct(ray.vector, ec);
  var ecDot = dotProduct(ec, ec);
  var s2 = sphere.radius * sphere.radius - ecDot + v*v;
  // console.log(s2);
  if (s2 <0){
      return;
  }else{
      return v - Math.sqrt(s2);
  }
}

function rayPlaneIntersect(plane, ray){
  // var npNormal = unitVector(scaleVector(subtract(plane.vector, plane.point),-1));
  // var ep = subtract(plane.point, ray.point);
  // var a = dotProduct(npNormal,ep);
  // var u = scaleVector(npNormal, a);
  // var v = dotProduct(ray.vector, u);
  // var d = (a*a)/v;
  var n = unitVector(plane.vector);
  var d = dotProduct(n,subtract(plane.point,ray.point))/dotProduct(ray.vector,n);
  if (d<0){
    return;
  }else{
    return d;
  }
}

function rayTriangleIntersect(triangle, ray){
  var a = triangle.a,
  b = triangle.b,
  c = triangle.c;
  var n = triangle.vector;
  var d = dotProduct(n,subtract(a,ray.point))/dotProduct(ray.vector,n);
  var p = addVectors(ray.point,scaleVector(ray.vector,d));
  if (dotProduct(n,crossProduct(subtract(b,a),subtract(p,a)))>=0 &&
      dotProduct(n,crossProduct(subtract(c,b),subtract(p,b)))>=0 &&
      dotProduct(n,crossProduct(subtract(a,c),subtract(p,c)))>=0){
    return d;
  }else{
    return;
  }
}

function surface(ray, scene, object, p, iter){
  var tLambert=0;
  var tSpecular = {x:0,y:0,z:0};
  var tDiffuse = {x:0,y:0,z:0};
  // var c = object.color;
  // if(object.lambert>0){
  //   for (var i = 0; i<scene.lights.length; i++){
  //     var lightPoint = scene.lights[i].point;
  //     if (!isLightVisible(p, scene, lightPoint))continue;
  //     var r2 = dotProduct(subtract(lightPoint,p), subtract(lightPoint, p));
  //     var toLight = unitVector(subtract(lightPoint,p));
  //     // var intensity = dotProduct(toLight,unitVector(addVectors(normal,scaleVector(subtract(randSphere(p, normal), p),0.5))));
  //     var intensity = (scene.lights[i].j/r2)*dotProduct(toLight, normal);
  //     if (intensity>0) tLambert+=intensity;
  //   }
  // }
  // if(object.diffuse >0){
  //   var target = randSphere(p, normal);
  //   var rColor = trace({point:p, vector: unitVector(subtract(target, p))}, scene, ++iter);
  //   console.log(rColor);
  //   if(rColor){
  //     tDiffuse = addVectors(tDiffuse, scaleVector(rColor, object.diffuse));
  //   }else{
  //     tDiffuse = addVectors(scaleVector(scene.skybox.color,0.5),tDiffuse);
  //   }
  //   // console.log(tDiffuse);
  // }
  // if(object.specular>0){
  //   var rRay = {point: p, vector: reflect(ray.vector, normal)}
  //   // var rRay = {point:p, vector: unitVector(subtract(randSphere(p, normal), p))};
  //   var rColor = trace(rRay, scene, ++iter);
  //   if(rColor){
  //     tSpecular = addVectors(tSpecular, scaleVector(rColor,object.specular));
  //   }
  // }
  // return add3Vectors(
  //   scaleVector(c, tLambert*object.lambert),
  //   tSpecular,
  //   scaleVector(c, object.ambient)
  // );
  if (iter <= -1) {
    // console.log("yo")
    // return {x:255,y:0,z:0};
    return scene.skybox.color;
  }
  if (p == null){
    return scene.skybox.color;
  }else{
    if (object.type == "sphere"){
      // console.log(object);
      var normal = sphereNormal(object, p, ray);
      var target = add3Vectors(p, normal, randSphere());
      // return scaleVector(scaleVector(addVectors(normal, {x:1,y:1,z:1}),0.5),255);
      // console.log(Math.sqrt(dotProduct(subtract(p,object.point),subtract(p,object.point))));
      // return {x:subtract(p,object.point), y:0, z:0};
      return scaleVector(trace({point:p, vector: unitVector(subtract(target, p))}, scene, --iter), 0.5);
      // console.log(normal);
    }else{
      var normal = object.vector;
      var target = add3Vectors(p, normal, randSphere());
      // return {x:255*normal.x,y:255*normal.y, z:255*normal.z};
      return scaleVector(trace({point:subtract(p,{x:0.005, y:0.005, z:0.005}), vector: unitVector(subtract(target, p))}, scene, --iter), 0.5);
    }
  }
}

function sphereNormal(sphere, p, ray){
  var normal = scaleVector(subtract(p, sphere.point), 1/sphere.radius);
  var front = dotProduct(ray.vector, normal) < 0;
  // console.log(front);
  normal = front ? normal : scaleVector(normal, -1);
  return normal;
}

function randSphere(){
  var a = Math.random()*2*Math.PI;
  var b = Math.random()*2*Math.PI;
  var x = Math.sin(a)*Math.cos(b);
  var y = Math.sin(a)*Math.sin(b);
  var z = Math.cos(a);
  return {x:x,y:y,z:z};
}

// function test2() {
//   var start = performance.now();
//   for (var i=0; i<100000; i++){
//     do {
//       var d, x, y, z;
//       x = Math.random() * 2.0 - 1.0;
//       y = Math.random() * 2.0 - 1.0;
//       z = Math.random() * 2.0 - 1.0;
//       d = x*x + y*y + z*z;
//     } while(d > 1.0);
//   }
//   var end = performance.now();
//   return end-start;
// }
<!DOCTYPE html>
<html>
<head>
    <title>raytracing</title>
    <canvas id='viewport' width = '256' height = '256'></canvas>
    <script type="text/javascript" src="main.js"></script>
</head>
<body>

</body>
</html>

Implementing a Dynamic Filterable Carousel

Details:

I’m currently working on building a carousel without any frameworks, and I’m facing some challenges in making it display correctly. Here’s an overview of what I’m trying to achieve:

  • Initially, the carousel is empty.
  • Upon clicking a button (which would act like a filter), I want to populate the carousel with divs that contain images. When a button is clicked (e.g., “cars”), only images of cars should be added to the carousel. Clicking a button labeled “all” should add all available images to the carousel.

Requirements:

  • Display four tiles at a time in the carousel.
  • I want the dynamic carousel to respond similarly to the normal carousel, rotating through all entities. For example, 1, 2, 3, 4, 5, 1, 2, 3… etc.
  • Add elements to the carousel based on the button clicked.

What i have tried:

I have a functioning normal carousel that you can find here: jsfiddle link
HTML:

<!--Carousel-->
<div class="desktop-carousel">
  <div class="container text-center">
    <div class="row mx-auto my-auto">
      <div id="myCarousel" class="carousel slide w-100" data-ride="carousel">
        <div class="carousel-inner w-100" role="listbox">
          <div class="carousel-item active">
            <div class="col-lg-3 col-md-5">
              <a href="#">
                <img class="img-fluid" src="http://via.placeholder.com/272x192?text=1" loading="lazy" onerror="imgError()">
              </a>
            </div>
          </div>
          <div class="carousel-item">
            <div class="col-lg-3 col-md-5">
              <a href="#">
                <img class="img-fluid" src="http://via.placeholder.com/272x192?text=2" loading="lazy">
                <p class="name items">Self care</p>
              </a>
            </div>
          </div>
          <div class="carousel-item">
            <div class="col-lg-3 col-md-5">
              <a href="#">
                <img class="img-fluid" src="http://via.placeholder.com/272x192?text=3" loading="lazy">
                <p class="name items">Pain</p>
              </a>
            </div>
          </div>
          <div class="carousel-item">
            <div class="col-lg-3 col-md-5">
              <a href="#">
                <img class="img-fluid" src="http://via.placeholder.com/272x192?text=4" loading="lazy">
                <p class="name items">Self care</p>
              </a>
            </div>
          </div>
          <div class="carousel-item">
            <div class="col-lg-3 col-md-5">
              <a href="#">
                <img class="img-fluid" src="http://via.placeholder.com/272x192?text=5" loading="lazy">
                <p class="name items">Hepilor</p>
              </a>
            </div>
          </div>
        </div>
        <a class="carousel-control-prev bg-dark w-auto" href="#myCarousel" role="button" data-slide="prev">
          <span class="carousel-control-prev-icon" aria-hidden="true"></span>
          <span class="sr-only">Previous</span>
        </a>
        <a class="carousel-control-next bg-dark w-auto" href="#myCarousel" role="button" data-slide="next">
          <span class="carousel-control-next-icon" aria-hidden="true"></span>
          <span class="sr-only">Next</span>
        </a>
      </div>
    </div>
  </div>
</div>

JavaScript:

// Carousel //

$('#myCarousel').carousel({
  interval: 2500
});

$('.carousel .carousel-item').each(function() {
  var minPerSlide = 4;
  var next = $(this).next();
  if (!next.length) {
    next = $(this).siblings(':first');
  }
  next.children(':first-child').clone().appendTo($(this));

  for (var i = 0; i < minPerSlide; i++) {
    next = next.next();
    if (!next.length) {
      next = $(this).siblings(':first');
    }

    next.children(':first-child').clone().appendTo($(this));
  }
});

However, I’m struggling to make the dynamic carousel work as intended.
Here is a link to it: jsfiddle link
HTML:

<button id="addItemButton" onclick="filterSelection()">Add Items to Carousel</button>

<button id="clearCarousel" onclick="clearCarousel()">Clear Items From Carousel</button>

<div class="container text-center">
  <div class="row mx-auto my-auto">
    <div id="myCarousel" class="carousel slide w-100" data-ride="carousel">
      <div class="carousel-inner w-100" role="listbox"></div>
      <a class="carousel-control-prev" href="#myCarousel" role="button" data-slide="prev">
        Previous
      </a>
      <a class="carousel-control-next" href="#myCarousel" role="button" data-slide="next">
        Next
      </a>
    </div>
  </div>
</div>

JavaScript:

// Create Carousel //
function filterSelection() {
  var carouselData = [{
      imageUrl: "http://via.placeholder.com/272x192?text=1",
      name: "Hannon"
    },
    {
      imageUrl: "http://via.placeholder.com/272x192?text=2",
      name: "Self care"
    },
    {
      imageUrl: "http://via.placeholder.com/272x192?text=3",
      name: "Pain"
    },
    {
      imageUrl: "http://via.placeholder.com/272x192?text=4",
      name: "Self care"
    },
    {
      imageUrl: "http://via.placeholder.com/272x192?text=5",
      name: "Hepilor"
    }
  ];

  var carouselInner = $('.carousel-inner');
  var count = 0;
  // Add items to carousel
  carouselData.forEach(function(item, index) {
    if (count == 0) {
      console.log('Inside If');
      var isActive = (index === 0) ? "active" : "";
      var itemHtml = `
      <div class="carousel-item ${isActive}">
        <div class="carousel-item-content col-lg-3 col-md-5">
          <a href="#">
            <img class="img-fluid" src="${item.imageUrl}" alt="${item.name}">
          </a>
        </div>
      </div>
      `;
      carouselInner.append(itemHtml);
    } else {
      console.log('In Else')
      var isActive = (index === 0) ? "active" : "";
      var itemHtml = `
      <div class="carousel-item">
        <div class="carousel-item-content col-lg-3 col-md-5">
          <a href="#">
            <img class="img-fluid" src="${item.imageUrl}" alt="${item.name}">
          </a>
        </div>
      </div>
      `;
      carouselInner.append(itemHtml);
    }
    count++;
  });

  // Initialize the carousel
  $('#myCarousel').carousel();
}


// Run carousel //
$('#myCarousel').carousel({
  interval: 1500
});

$('.carousel .carousel-item').each(function() {
  var minPerSlide = 4;
  var next = $(this).next();
  if (!next.length) {
    next = $(this).siblings(':first');
  }
  next.children(':first-child').clone().appendTo($(this));

  for (var i = 0; i < minPerSlide; i++) {
    next = next.next();
    if (!next.length) {
      next = $(this).siblings(':first');
    }

    next.children(':first-child').clone().appendTo($(this));
  }
});

function clearCarousel() {
  $('.carousel-inner').empty();
  $('#myCarousel').carousel('dispose');
}

I would greatly appreciate any suggestions, alternative approaches, solutions, or guidance you can provide.

String replace in mat-autocomplete in Angular

I am beginner webdeveloper. I have this code:

<input id="street{{sid}}" name="street{{sid}}" type="text" placeholder="" class="form-control"
               [(ngModel)]="adres.street" #street="ngModel" required="" (keydown)="this.removeSpecialCharactersFromStreet($event)" (keyup)="this.removeSpecialCharactersFromStreet($event)"
               capitalize-first="true">

removeSpecialCharactersFromStreet(event) {
    this.adres.street = event.target.value.replace(/[&/\#,+()$~%.]'":*?<>{}@^&=;'"_![]/g, '');
  }

abd it’s work fine πŸ™‚

Now i need add this function to mat-autocomplete:

removeSpecialCharactersFromCity(event) {
    this.adres.city = event.target.value.replace(/[&/\#,+()$~%.]'":*?<>{}@^&=;'"_![]/g, '');
  }

<mat-autocomplete autoActiveFirstOption #auto="matAutocomplete" (keydown)="this.removeSpecialCharactersFromCity($event)" (keyup)="this.removeSpecialCharactersFromCity($event)">
          <mat-option *ngFor="let option of cityFilteredOptions" [value]="option" (keydown)="this.removeSpecialCharactersFromCity($event)" (keyup)="this.removeSpecialCharactersFromCity($event)">
            {{option}}
          </mat-option>
        </mat-autocomplete>

And it’s not work πŸ™
How can i repair it?

Please help me

How to connect AWS OpenSearch Serverless to Lambda to inject data?

I’m trying to do a PUT request to upload data to a collection I have created. However, I’m getting a ‘403’ error; ‘User does not have permissions for the requested resource’.

I believe I have granted full IAM access to the user but I’m still getting the same error.

Here is the IAM and function within my serverless file:

   iam:
    role:
        statements:
            - Effect: Allow
              Action:
                  - aoss:*
              Resource:
                  - '*'

functions:
    lambdaFunction:
        handler: src/controllers/lambdaFunction.handler
        description: create a lambda 
        events:
            - http:
                  path: /lambda
                  method: post
                  cors: ${self:custom.cors-settings}
                  private: false
                  authorizer:
                      type: CUSTOM
                      authorizerId: ${self:provider.environment.authorizer_ref}
                      resultTtlInSeconds: 0
        memorySize: 256
        logRetentionInDays: 30
        iamRoleStatementsInherit: true
        iamRoleStatements:
            - Effect: Allow
              Action:
                  - aoss:*
              Resource:
                  - '*'

Data Validation of React State 400 [closed]

This is my code:

  const [search, setSearch] = useState("");

    let params = {
      search: {
        query: search,
      },

Here the search is already a string but it is still throwing the error:

Object { hasError: true, message: "ERROR: Data Validation 
Failed.", error: {…} }

​ error: Object { error: “‘search’ must be a string.” }
​ ​error: “‘search’ must be a string.”
​​ hasError: true
​ message: “ERROR: Data Validation Failed.”

This is where I’m using the setSearch:

 <ZokiTextField
   value={search}
   onChange={(e) => setSearch(e.target.value)}
   content="Search Available Hotels"
 />

Which mistake am I doing at here?

How to save csv file to localstorage and restore it? [duplicate]

I want to save the file csv to the localStorage but when I check the variable fileJson it returns empty.
How to save the csv file to localStorage and restore it to the file csv again?
Thank you before

file html

<input type="file" #fileInput style="display: none" accept=".csv" (change)="saveData($event.target.files)">

file js

saveData(files: FileList) {
 if (files && files.length > 0) {
      this.file = files[0];
      const fileJson  = JSON.stringify(this.file);
      localStorage["dataCsv"] = fileJson
 }

How to flip an image without moving it

In the example below, click on logo and you’ll see – it is flipped but also moved
How to flip it without moving ?
I also tried this, without success:

.flip{transform:scaleX(-1) translatex(-50%);}

$('img').on('click', function(){
    $(this).addClass('flip');
 });
.flip{transform:scaleX(-1);}

.wrap{
  position:relative;
  width:50%;
  height:100px;
  background:darkorange;
 }
img{
  position:absolute;
  bottom:0;
  width:140px;
  left:50%;
  transform:translatex(-50%);
 }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class='wrap'>
<img src='https://abuena.net/img/logo_01.png' alt='img'>
</div>

On hover data fluctuation issue in chart.js graph react js .How can i fix this?

If i use event:[] then hover issue will fix, but i also want tooltip.

import Chart from "chart.js";


const Component1 = ({productData,truncatedNames}) => {
  useEffect(() => {
        const canvas = document.getElementById("myChart1");
    // Create the chart context
    const ctx = canvas.getContext("2d");
  
  
    // Define the chart data
    const data = {
      labels: truncatedNames,
      datasets: [
        {
          label: "Products",
          data: productData,
          backgroundColor: "#FA7070",
        },
      ],
    };

    // Configure the chart options
    const options = {
      responsive: true,
      scales: {
        yAxes: [
          {
            display: true,
            ticks: {
              suggestedMin: 0,
              beginAtZero: true,
              callback: productData ? yAxisLabelCallback : emptyFunction,
            },
          },
        ],
      },
      onHover: function (event, chartElements) {},
      hover: false,
    };

    // Create the bar chart
    const myChart = new Chart(ctx, {
      type: "bar",
      data: data,
      options: options,
    });
  }, []);
  return (
   
      <Box>
        <canvas width={"70%"} height={"40%"} id="myChart1"></canvas>
      </Box>
  
  );
};

export default Component1;

Please tell or give any example how I destroy my chart after displaying another customer data.
I am unable to destroy this in useEffect because if i console myChart then it gives undefined value.