ThreeJS not animating glb file. stuck on first frame

Trying to animate glb file within 8th wall using ThreeJS for an Augmented Reality experience.

    // Load 3D model
    loader.load(
      // resource URL
      modelFile,
      // loaded handler
      (gltf) => {
        model = gltf.scene
        scene.add(model)
        // Hide 3D model until image target is detected.
        model.visible = false
        
      }
    )


  // Places content over image target
  const showTarget = ({detail}) => {
    // When the image target named 'model-target' is detected, show 3D model.
    // This string must match the name of the image target uploaded to 8th Wall.
    if (detail.name === 'model-target') {
      model.position.copy(detail.position)
      model.quaternion.copy(detail.rotation)
      model.scale.set(detail.scale, detail.scale, detail.scale)
      model.visible = true
      model.play = true
    }

Thanks for your help.

Why does JavaScript automatically sort the number keys in an object? How can I get around it? It messes up the index order that is important to me [duplicate]

let arr = [10,23,45,64,69,12,446,565,75,456];

let obj = {};

for (let i = 0; i < arr.length; i++) {
    obj[arr[i]] = arr[i]
}

let values = Object.values(obj)

console.log(values)

i was expection values array to be:- [10, 23, 45, 64, 69, 12, 446, 565, 75, 456]

But I am Getting sorted values :- [
10, 12, 23, 45, 64,
69, 75, 446, 456, 565
]

React Native TV: Focus issue when 2 text inputs are align vertical

hope you have a great day.

Currently my project is working on have this issue. On my screen, i have 2 TextInput, i can’t use the d-pad to move up or down while text is empty but once it have been filled at least 1 character, the d-pad’s up and down button work normally. I’m still looking for a solution for this, any ideas on what can cause this problem and how to fix it?
(https://i.stack.imgur.com/Nz77y.png))

Cause:

  1. TextInput default width is 270
  2. Press up and down on D-pad, it wont work

Expected:
When both TextInput‘s width is 270, it should be able to lose focus and shift to next TextInput

While debugging i noticed that: when i set height to 108 (width/2.5), i can be able to move up and down by using the d-pad

how to reload an array(texts) in jquery?

Array of product_name and how to location.reload using jquery.

<tr>
            <td>
            <select name='product_name[]' id='tbl_product_name1' class='product_name' onchange='onsize(this.value);'>
                <?php
                    echo $product_page;
                ?>
            </select>
            </td>
            <td>
                <input type="text" name="product_size[]" class="product_size" id='tbl_product_size1' />
            </td>
            <td>
                <input type="text" name="product_pcs[]" class="product_pcs" id='tbl_product_pcs1' value="1" />
            </td>
            <td>
                <button name='addBtn' tabindex="54" type="button" id='tbl_addBtn'>+</button>
            </td>
        </tr>```


in ajax
$(‘#tbl_addBtn’).on(‘click’,function(){
count++;
var html = “-“;
$(“#product_list”).append(html);
});“`

Please help me… i get stuck

Array of product_name and how to location.reload using jquery.

ejs contentFor is not defined error when using renderFile

I needed to add html tags in then block of ejs therefore rendered ejs file using ejs.renderFile like this:

index.html

import APP from "./app.js"
import ejs from 'ejs'

APP.set('layout', 'layout')
APP.get('', async (req, res) => {
  const html = await ejs.renderFile('contents/ejs_pages/index.ejs', {async: true});
  res.send(html);
})

layout.ejs

<body>

<section>
<%- section %>
</section>

</body>

index.ejs

<%- contentFor('section') %>
<h1>This is section</h1>

Then below error that didn’t occur when I was using res.render instead of ejs.renderFile occured.

Uncaught ReferenceError ReferenceError: ejs_pages/index.ejs:1
...
contentFor is not defined

Can’t I use contentFor in ejs when I’m using ejs.renderFile?
If so, is there any alternative?

Click event fires on different button control in Javascript

I have following HTML code, where I add items to cart and then finally click submit.

 <div class="form-group">
   <div>
     <select id="available-options" multiple>
         <option value="option1">Option 1</option>
         <option value="option2">Option 2</option>
         <option value="option3">Option 3</option>
      </select>
     <button id="add-button" aria-label="Add">Add</button>
   </div>
 </div>
<div class="box-footer">
     <button type="submit" class="btn btn-default">Cancel</button>
     <button type="submit" class="btn btn-info pull-right">Update</button>
</div>

I have below Javascript

  window.onload = function () {
      const addButton = document.getElementById("add-button");

       addButton.addEventListener("click", () => {
       const selected = availableOptions.selectedOptions;
       for (let i = 0; i < selected.length; i++) {
          const option = selected[i];
          selectedOptions.appendChild(option);
         }
     });
   }

When I click add button, both button events are getting fired!

Cannot calculate price for offer (Next.js) (Javascript)

So my client want to create an offer so every 3 Tops is 1000EGP.
So if i have 2 then its normal price
3 its 1000
4 is 1000 for 3 and 1 for normal price
6 for 2000
and so on.

if (offer3Tops) {
  const tops = productDetails.filter((product) => product.category[0] === 'Tops');
  const setsOf3 = Math.ceil(tops.length / 3);
  const remainingTops = tops.length % 3;

  const discountedTotal = setsOf3 * 1000 + remainingTops * tops[0].price;

  cartTotal -= discountedTotal;
}

Tried using ceil but it rounds up so 2 is 1000 and so on.
tried using floor but i get 900 per set instead of 1000.

Edit :
Full Code :

async function getProducts() {
        let cartTotal = 0;
      
        const productPromises = cart.map(async (item) => {
          const product = await getProduct(item._id);
          cartTotal += product.price * item.quantity;
          return {
            ...product,
            quantity: item.quantity,
            color: item.color,
            size: item.size,
          };
        });
      
        const productDetails = await Promise.all(productPromises);
      
        if (offer3Tops) {
          const tops = productDetails.filter((product) => product.category[0] === 'Tops');
          const discountedSets = Math.floor(tops.length / 3) 
          const remainingTops = tops.length % 3;
          console.log(discountedSets, remainingTops);

          const discountedTotal = discountedSets * 1000 + remainingTops * tops[0].price;
          console.log(discountedTotal);
          cartTotal -= discountedTotal;
        }
      
        setProducts(productDetails);
        setCartTotal(cartTotal);
        setOrderTotal(Math.ceil(cartTotal + shipping ));
        setLoading(false);
      }
  
      async function getCities() {
          const statesApi = await getAllStates();
          setStates(statesApi);
      }
  
      getCities();
      getProducts();
  }, [cart, shipping]);

Server-side redirect in JSP with javascript (MVC structure)

Background:
I’m running my jsp webpage with javascript in apache tomcat server. I used Model-View-Controller(MVC) structure, controller use java. I also use ajax and Servlet.

Issue:
I want to redirect client from 1.jsp to 2.jsp using server-side redirect to avoid the redirect url being modified on client side. The result should not expose the redirect url in browser dev mode inspection, breakpoint and watch.

Example (pseudocode):

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <title>Page Title</title>
    </head>
    <body>
        <script type="text/javascript">
            move();
            function move() {
                if (width >= 100) {
                    // I want to trigger a server-side redirect here.
                } else {
                    // continue javascript code
                }
            }
        </script>
    </body>
</html>

Ideas (correct me if I’m wrong):
javascript in jsp is in client leval and unable to directly call server-side to work on something. Trying to pass the job to controller to trigger the server side redirect, but AJAX requests donโ€™t automatically follow redirects.

I tried to used JSTL core library in a JSP file (example code below) and it kind of works individually but not work inside <script>. I know there’s also when and otherwise tag that can simulate if else but I just can’t make it work.

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title><c:redirect> Tag Example</title>
</head>
<body>
<c:redirect url="http://www.google.com"/>
</body>
</html>

Any solution and ideas are welcome. Thanks!

How to use PrimeVue with Vue 3 and ES6 import map?

I want to use PrimeVue as a ES6 import map. But not sure how that would look.

What I have so far.

<script type="importmap">
    {
        "imports": {
            "primevue": "https://unpkg.com/primevue/core/core.min.js"
        }
    }
</script>
<script>
 import PrimeVue from 'primevue/config';

 const LeftPanel = createApp({

 }).use(PrimeVue).mount("#left-panel");
</script>

Filter and return multiple values from JSON nested List [duplicate]

I have a JSON file contains the name of the US state and cities-

[
  {
    "state": "Iowa ",
    "id": "IA",
    "places": [
      {
        "city": "Ames",
        "description": "ames-description"
      },
      {
        "city": "Davenport ",
        "description": "davenport-description"
      }
    ]
  },
  {
    "state": "Illinois ",
    "id": "IL",
    "places": [
      {
        "city": "Chicago",
        "description": "chicago-description"
      },
      {
        "city": "Elgin ",
        "description": "elgin-description"
      },
      {
        "city": "Joliet ",
        "description": "joliet-description"
      }
    ]
  }
]

I would like to filter out the list by city name and return the description, corresponding state, and state id. Here is my code for the filtering the list-

const cityname = Elgin;

//Filter array which matches the constant
const filterPosts = stateNames.map((filterPlaces) => {
  return filterPlaces.places.filter((getArray) => getArray.city === cityname);
});

//Get the name
const getCity = filterCity.map((topicCityArray) =>
  topicCityArray.map((getCityTitle) => {
    return getCityTitle.city;
  }),
);

While it returns the city name, I could not figure out how to return the corresponding description, state name, and state id. Any suggestion would be appreciated. Thanks in advance.

It is difficult to implement the function to stop the wheel at the desired location using JavaScript

(I’m not good at English, so I’m posting my question through a translator. Please understand that the English sentences are not smooth as we used a translator.)

I am a student slowly studying JavaScript, CSS, and HTML.
We are implementing it so that only items with a checkmark in the checkbox on the wheel can win.
I’m writing code under the assumption that there is only one checked item. I’ve searched and implemented it for several days, but I’m not sure what the problem is.

I wrote the JavaScript code below, but it doesn’t work as I want.

roulette.js

Array.prototype.remove = function(elem) {
   this.some(function(e, i, a) {
      if (e === elem) {
         a.splice(i, 1);
         return true;
      }
      return false;
   });
   return this;
};
Array.prototype.removeAll = function(elem) {
   this.forEach(function(e, i, a) {
      if (e === elem) {
         a.splice(i, 1);
      }
   });
   return this;
}

var colorPalette = [
   // ~~~
];
(function() {
   var startColorIdx = Math.floor(Math.random() * colorPalette.length);
   var startColor = colorPalette[startColorIdx];
   colorPalette.remove(startColor);
   window.getColor = function(i) {
      if (i == 0) return startColor;
      return colorPalette[ Math.floor(startColorIdx + 4 * i) % colorPalette.length ];
   };
})();

var noname = 'noname';
var font = '32px Hanna';
var font2 = font; //'36px Sans-serif';
var line_color = '#37474f';
var bgColor = '#ffffff';
var pinColor = '#37474f';
var fontStrokeStyle = '#37474f';

function isChecked(item) {
   var checked = $(item).find('.item-checkbox').is(':checked');
    // Add a log to output the status of the checkbox to the console
    console.log('Item checked:', checked);
   if (checked) {
        var text = $(item).find('.item-title').text();
        var index = $(item).index();
        console.log('Item text:', text);
        console.log('Item index:', index);
    }
    return checked;
}

function DEG2RAD(degree) {
   return (degree * Math.PI) / 180;
}

$(document).ready(function() {
   var $li = $('li.item');
   var $cl = $li.clone();
   window.createItem = function() {
      $('ul').append($cl.clone());
   }
});


function updateData() {

   var items = [];
   var angleSum = 0;
   var weightSum = 0;

   $('li.item').each(function(i, e) {
      var $e = $(e);
      var $title = $e.find('.item-title');
      if ($title.text()) {
         $e.removeClass('empty');
      } else {
         $e.addClass('empty');
         return;
      }
      var weight = parseFloat($e.find('.item-weight').attr('data-weight')) || 0;
      weightSum += weight;
   });
   $('li.item:not(.empty)').each(function(i, e) {
      var $e = $(e);
      
      var title = $e.find('.item-title').text();
      if (!title) {
         return;
      }
      var weight = parseFloat($e.find('.item-weight').attr('data-weight')) || 0;
      var chance = weight / weightSum;
      $e.attr('data-chance', (chance * 100).toFixed(2));

      var angle = 360 * chance;
      angleSum += angle;

      var color = getColor(i)
      items.push({
         name: title,
         angle: angle,
         angleSum: angleSum,
         color: color
      });

      $e.css('background', 'linear-gradient(to right, ' + color + ' 11%, rgba(0, 0, 0, 0) 0%)');
   });

   R.Items = items;
   R.dirty = true;
   R.checkedAngle = null;
   if (R.Items.length > 0) { // Check if the array is not empty
      R.Items.forEach(function(item) {
         if (item.name === R.current) {
            R.checkedAngle = {
               start: item.angleSum - item.angle,
               end: item.angleSum
            };
         }
      });
   }
}

function cleanList() {
   var empty = [];
   $('li').each(function() {
      var $this = $(this);
      var $title = $this.find('.item-title');
      var text = $title.text().trim();
      $title.text(text);
      if (!text) {
         empty.push($this);
      }
   });

   if (empty.length === 0) {
      // create new li
      createItem();
   } else if (empty.length > 1) {
      empty.pop();
      empty.forEach(function($e) {
         $e.remove();
      });
   }
}

$(document).on('blur', '.item-title', function(evt) {
   cleanList();
   updateData();
});
$(document).on('keyup', '.item-title', function(evt) {
   updateData();
});

$(document).on('click', 'li.item', function(evt) {
   $(evt.currentTarget).find('.item-title').focus();
});

$(document).on('click', '.item-weight-add, .item-weight-sub', function(evt) {
   evt.stopPropagation();
   var $this = $(evt.currentTarget);
   var sign = $this.is('.item-weight-add') ? +1 : $this.is('.item-weight-sub') ? -1 : 0;
   var $w = $this.focus().siblings('.item-weight');
   var amount = evt.ctrlKey && !evt.shiftKey &&  evt.altKey ? 1000 :
            !evt.ctrlKey && !evt.shiftKey &&  evt.altKey ? 100 :
             evt.ctrlKey && !evt.shiftKey && !evt.altKey ? 10 :
            1;
   var w = Math.floor(Math.max(1, Math.min(9999, (parseInt($w.attr('data-weight')) || 1) + sign * amount)));
   $w.attr('data-weight', w);
   updateData();
});

$(document).on('keydown', function(evt) {
   var $target = $(evt.target);
   if (evt.key === 'Enter') {
      evt.preventDefault();
      cleanList();
      if ($target.is('.item-title')) {
         $target.blur()
         .closest('li')
         .next('li')
         .find('.item-title').focus();
      }
      if ($target.is('[contenteditable]')) {
         $target.blur();
      }
   } else if (evt.key === 'Escape') {
      if ($target.is('[contenteditable]')) {
         $target.blur();
      }
   }
});

function Roulette() {

   var R = {
      dirty: true,
      rotation: 0,
      $button: $('#roll')
   };
   window.R = R;

   function OnStart() {
      try {
         $(document.body).css('background', bgColor);
         R.canvas = document.querySelector('canvas');
         R.ctx = R.canvas.getContext('2d', true);
         R.size = { width: R.canvas.width, height: R.canvas.height };
         R.center = { x: R.size.width / 2 , y: R.size.height / 2 };

         window.radius = Math.min(Math.min(R.size.width, R.size.height) * 0.5 * 0.9, R.size.height / 2 - 40);

         R.bufferCanvas = document.createElement('canvas');
         R.bufferCanvas.width = R.size.width;
         R.bufferCanvas.height = R.size.height;
         R.buffer = R.bufferCanvas.getContext('2d', true);
         R.buffer.textAlign='center';

         requestAnimationFrame(OnUpdate);
      } catch(e) { console.log(e); }
   }

   function OnUpdate(timestamp) {
      R.deltaTime = timestamp - (R.lastTimestamp || timestamp);

      requestAnimationFrame(OnUpdate);
      if (0 < R.deltaTime && R.deltaTime < 17) {
         return;
      }

      if (R.stopping) {
         if (Date.now() - R.stopping > 15 * 1000) {
            R.angularVelocity = 0;
            delete R.stopping;
         }
         else
         {
            // Check if the pin is within the angle range of the checked item
            if (R.checkedAngle && (R.currentAngle < R.checkedAngle.start || R.currentAngle > R.checkedAngle.end)) {
            // If not, keep rotating slowly until you get within the angle
               R.angularVelocity = Math.max(10, R.angularVelocity);
            } else {
            // If within range, roulette stops
               R.angularVelocity -= Math.max(20, Math.min(R.angularVelocity * 0.5, R.angularDamping)) * (R.deltaTime / 1000);
            }
         }
      }
      if (R.angularDamping) {
         R.angularVelocity -= Math.max(20, Math.min(R.angularVelocity * 0.5, R.angularDamping)) * (R.deltaTime / 1000);
      }
      if (R.angularVelocity <= 0) {
         R.angularVelocity = 0;
         if (R.launched && typeof R.onStop === 'function') {
            R.launched = false;
            R.onStop();
         }
      }
      if (R.angularVelocity) {
         R.rotation += R.angularVelocity * (R.deltaTime / 1000);
         while (R.rotation < 0) R.rotation += 360;
         while (R.rotation >= 360) R.rotation -= 360;
      }
      if (R.prevRotation != R.rotation) {
         R.dirty = true;
      }
      R.prevRotation = R.rotation;

      // render
      OnRender();
      R.lastTimestamp = timestamp;
   }

   function drawArc(option, name, split) {
      if (!split || (split && !name)) {
         R.buffer.save();
         R.buffer.translate(option.x, option.y);
         R.buffer.rotate(DEG2RAD(option.rotation - 90));

         R.buffer.beginPath();
         R.buffer.moveTo(0, 0);
         R.buffer.arc(0, 0, option.radius, 0, DEG2RAD(option.angle));
         R.buffer.closePath();
         R.buffer.fillStyle = option.color;
         R.buffer.fill();

         R.buffer.beginPath();
         R.buffer.arc(0, 0, option.radius, 0, DEG2RAD(option.angle));
         R.buffer.strokeStyle = window.line_color;
         R.buffer.lineWidth = 3;
         R.buffer.stroke();

         R.buffer.restore();
      }
      if (!split || (split && name)) {
         // text
         R.buffer.save();
         R.buffer.translate(option.x, option.y);
         R.buffer.rotate(DEG2RAD(option.rotation - 90 + option.angle / 2));

         R.buffer.beginPath();
         R.buffer.moveTo(0, 0);
         R.buffer.font = window.font2;
         R.buffer.trokeStyle = fontStrokeStyle; // 'black';
         R.buffer.lineWidth = 5;
         R.buffer.strokeText(name, option.radius / 2, 8);
         //R.buffer.fillStyle = window.line_color;
         R.buffer.fillStyle = 'white';
         R.buffer.fillText(name, option.radius / 2, 8);

         R.buffer.restore();
      }
   }

   function OnRender() {
      if (!R.dirty) return;
      R.dirty = false;
      
      // clear
      R.buffer.fillStyle = bgColor;
      R.buffer.fillRect(0, 0, R.size.width, R.size.height);
      //R.buffer.clearRect(0, 0, R.size.width, R.size.height);

      if (R.FPS) {
         R.buffer.font = window.font;
         R.buffer.fillStyle = window.line_color;
         R.buffer.fillText(R.FPS + 'FPS', 50, R.center.y - window.radius - 7);
      }

      // shadow
      R.buffer.shadowBlur = 15;
      R.buffer.shadowColor = 'black';
      drawArc({ x: R.center.x, y: R.center.y + 15 + 5, radius: window.radius - 5, rotation: 0, angle: 360, color: bgColor }, '');
      R.buffer.shadowBlur = 0;
      drawArc({ x: R.center.x, y: R.center.y + 15, radius: window.radius, rotation: 0, angle: 360, color: bgColor }, '');

      //
      R.current = null;
      if (R.Items && R.Items.length > 0) {
         R.lastAngle = 0;
         R.Items.forEach(function(item) {
            R.currentAngle = 360 - R.rotation;
            while (R.currentAngle < 0) R.currentAngle += 360;
            while (R.currentAngle >= 360) R.currentAngle -= 360;
            // if (item.angleSum - item.angle <= R.currentAngle && R.currentAngle <= item.angleSum) {
            //    R.current = item.name;
            // }

            drawArc({ x: R.center.x, y: R.center.y + 15, radius: window.radius,
               rotation: R.rotation + R.lastAngle, angle: item.angle, color: item.color }, null, true);
            R.lastAngle += item.angle;
            //if (R.lastAngle >= 360) R.lastAngle -= 360;
         });
         R.lastAngle = 0;
         R.Items.forEach(function(item) {
            R.currentAngle = 360 - R.rotation;
            while (R.currentAngle < 0) R.currentAngle += 360;
            while (R.currentAngle >= 360) R.currentAngle -= 360;
            if (item.angleSum - item.angle <= R.currentAngle && R.currentAngle <= item.angleSum) {
               R.current = item.name;
               R.currentColor = item.color;
            }

            drawArc({ x: R.center.x, y: R.center.y + 15, radius: window.radius,
               rotation: R.rotation + R.lastAngle, angle: item.angle, color: item.color }, item.name, true);
            R.lastAngle += item.angle;
            //if (R.lastAngle >= 360) R.lastAngle -= 360;
         })
         
         //Assigned to an object with two properties: checkedAngle and start, end
         R.checkedAngle = null;
         R.Items.forEach(function(item) {
            if (item.name === R.current) {
            R.checkedAngle = {
               start: item.angleSum - item.angle,
               end: item.angleSum
            };
         }
      });

      } else {
         drawArc({ x: R.center.x, y: R.center.y + 15, radius: window.radius,
            rotation: R.rotation-45, angle: 180, color: getColor(0) }, 'Spin the');
         drawArc({ x: R.center.x, y: R.center.y + 15, radius: window.radius,
            rotation: R.rotation-45+180, angle: 180, color: getColor(1) }, 'Wheel!');
      }
      // pin
      R.buffer.beginPath();
      R.buffer.moveTo(R.size.width / 2    , R.center.y - window.radius + 20);
      R.buffer.lineTo(R.size.width / 2 - 5, R.center.y - window.radius + 5 );
      R.buffer.lineTo(R.size.width / 2 - 5, R.center.y - window.radius + 0 );
      R.buffer.lineTo(R.size.width / 2 + 5, R.center.y - window.radius + 0 );
      R.buffer.lineTo(R.size.width / 2 + 5, R.center.y - window.radius + 5 );
      R.buffer.closePath();
      R.buffer.fillStyle = window.pinColor;
      R.buffer.fill();
      R.buffer.stroke();

      if (R.current) {
         R.buffer.font = window.font;
         if (R.currentColor) {
            R.buffer.strokeStyle = window.line_color; // 'black';
            R.buffer.lineWidth = 5;
            R.buffer.strokeText(R.current, R.size.width / 2, R.center.y - window.radius - 7);
         }
         R.buffer.fillStyle = R.currentColor || window.line_color;
         R.buffer.fillText(R.current, R.size.width / 2, R.center.y - window.radius - 7);
      }
      R.ctx.drawImage(R.bufferCanvas, 0, 0);
   }

   R.Launch = function() {
      var items = $('#items .item');
      var checkedItems = items.filter(isChecked);
      var selectedIndex = Math.floor(Math.random() * checkedItems.length);
   
      // Set the winning item
      R.current = $(checkedItems[selectedIndex]).find('.item-title').text();
   
      
      R.launched = true;
      R.angularVelocity = 4 * 360; // 4 * 360;
      R.angularDamping = 0;
      delete R.stopping;
   }


   R.Stop = function() {
      R.stopping = Date.now();
      //R.angularDamping = 360 * (0.5 + 0.1 * Math.random()); // 360 * (2 + Math.random());
      R.angularDamping = 360 * (0.1 + 0.05 * Math.random());
   }

   OnStart();
}

$(document).ready(function() {
   Roulette();

   var $result = $('#result');
   var $roll = $('#roll');
   var it;

   R.onStop = function() {
      $result.removeClass('out').text(R.current || 'Spin the wheel!').show().addClass('play');
      clearTimeout(it);
      it = setTimeout(function() {
         $roll.fadeIn(600, function() {
            lock(false);
            $result.hide();
         });
      }, 1500);
   }
});

function lock(b) {
   if (b) {
      $('[contenteditable]').attr('contenteditable', false);
      $('ul').addClass('lock');
   } else {
      $('[contenteditable]').attr('contenteditable', true);
      $('ul').removeClass('lock');
   }
}

//Checkbox!
$(document).on('change', '.item-checkbox', function() {
   // The 'this' keyword refers to the checkbox itself.
   var checked = $(this).is(':checked');
   console.log('Checkbox checked state:', checked);
   
   if (checked) {
       var item = $(this).closest('.item');
       var text = item.find('.item-title').text();
       var index = item.index();
       console.log('Item text:', text);
       console.log('Item index:', index);
   }
});

$(document).on('click', '#roll', function(evt) {
   if (!R.isRolling) {
      R.isRolling = true;
      R.Launch();
      $(evt.currentTarget).focus().addClass('active');
      lock(true);
   } else {
      R.isRolling = false;
      R.Stop();
      $(evt.currentTarget).focus().removeClass('active').hide();
   }
});

$(document).on('click', '.item-delete', function(evt) {
   $(evt.currentTarget).closest('li').remove();
   updateData();
   cleanList();
});



$(document).on('keydown', 'h1[contenteditable]', function(e) {
   if (e.key === 'Enter') {
      e.preventDefault();
   }
});

(function() {
   var $t = $('#button-tooltip');
   var $u = $('ul');

   function show() {
      $t.show();
   };
   function hide() {
      $t.hide();
   };
   function move() {
      var o = $u.offset();
      o.top -= 100;
      o.left += 100;
      $t.offset(o);
   };

   $(document).on('mouseenter mousemove', '.item-weight-sub, .item-weight-add', function(e) {
      move();
      show();
   }).on('mouseleave', '.item-weight-sub, .item-weight-add', function(e) {
      hide();
   });

})();

Run screen

I wanted to implement it so that if you check the box to the right of the 3rd item, the 3rd item will continue to win.

When I press the ‘์‹œ์ž‘’ button below, the wheel starts rotating, and when I press the ‘Stop’ button, the wheel starts to slow down, and ultimately I wanted the wheel to stop at my desired location.

      if (R.stopping) {
         if (Date.now() - R.stopping > 15 * 1000) {
            R.angularVelocity = 0;
            delete R.stopping;
         }
         else
         {
            // Check if the pin is within the angle range of the checked item
            if (R.checkedAngle && (R.currentAngle < R.checkedAngle.start || R.currentAngle > R.checkedAngle.end)) {
            // If not, keep rotating slowly until you get within the angle
               R.angularVelocity = Math.max(10, R.angularVelocity);
            } else {
            // If within range, roulette stops
               R.angularVelocity -= Math.max(20, Math.min(R.angularVelocity * 0.5, R.angularDamping)) * (R.deltaTime / 1000);
            }
         }
      }

So, I wrote the code above so that the pin position stops at the checked item, but it doesn’t work properly. I would appreciate some help as to what the problem is.

https://codepen.io/vrywexho-the-lessful/pen/LYaVLap
I have attached js, css, and html code to the link above.
thank you happy new year!

Oracle APEX – how to call a function

I’d like to call a function based on a text input. This is my code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        .message {
            margin-top: 10px;
            color: red;
        }
    </style>
</head>
<body>   
    <div id="uppercase" class="message">Must contain at least one uppercase letter</div>
    <div id="lowercase" class="message">Must contain at least one lowercase letter</div>
    <div id="numeric" class="message">Must contain at least one numeric digit</div>
    <div id="specialchar" class="message">Must contain at least one special character</div>
    
    <script>
        function checkPassword() {
            var password = document.getElementById("P99_NEW_PASSWORD").value;
            var uppercaseMessage = document.getElementById("uppercase");
            var lowercaseMessage = document.getElementById("lowercase");
            var numericMessage = document.getElementById("numeric");
            var specialcharMessage = document.getElementById("specialchar");

            // Reset messages
            uppercaseMessage.style.color = "red";
            lowercaseMessage.style.color = "red";
            numericMessage.style.color = "red";
            specialcharMessage.style.color = "red";

            // Check conditions
            if (/[A-Z]/.test(password)) {
                uppercaseMessage.style.color = "green";
            }
            if (/[a-z]/.test(password)) {
                lowercaseMessage.style.color = "green";
            }
            if (/d/.test(password)) {
                numericMessage.style.color = "green";
            }
            if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) {
                specialcharMessage.style.color = "green";
            }
        }
    </script>
</body>
</html>

And this is how it looks like:
enter image description here

What I want to do is, when a user enter a password in the New Password field (which is P99_NEW_PASSWORD), checkPassword() will be called. However, I don’t know what/where to put to call checkPassword() function.
Could anyone help to solve this? Thanks in advance.

I need to accurately calculate the brightness of specific area of image data pixels to select the corresponding image

I have a program that creates Lego mosaics from input images. To choose the right Lego brick color, I calculate the average brightness of the image data pixels in a specific area and then select the corresponding Lego brick. However, this approach often does not yield the correct brick color.

`calculateAverageBrightness(data) {
let totalBrightness = 0;
let count = 0;

    for (let i = 0; i < data.length; i += 4) {
        const r = data[i];
        const g = data[i + 1];
        const b = data[i + 2];

        const brightness = 0.21 * r + 0.72 * g + 0.07 * b;
        totalBrightness += brightness;
        count++;
    }

    return totalBrightness / count;
}`

Input image – (https://i.stack.imgur.com/Hcxpy.png)
Result image – (https://i.stack.imgur.com/f2RZz.png)

I want the algorithm to somehow pick right pixel from area of pixels to calculate brightness of it.

Creating a Dynamic Spin and Win Wheel in WordPress: How to Integrate Wallet Transactions and Probability-based Rewards?

I’m working on implementing a dynamic Spin and Win wheel within WordPress, aiming to integrate wallet transactions and probability-based rewards. The goal is to create an engaging feature where users can spin the wheel, choose stake amounts, and receive rewards based on the section they land on.

Specifically, I’m seeking guidance on integrating this wheel with wallet transactions, such as deducting stakes from the user’s balance and instantly crediting winnings. Additionally, I’m looking to understand how to set up the wheel’s probability distribution for different stake amounts (#100, #200, and #300) and dynamically change the reward percentages based on these stakes.

Any insights, code samples, or recommended plugins/APIs to achieve this interactive and rewarding spin wheel

PHP code

<?php
/**
 * Plugin Name: Spin and Win Wheel
 * Description: A custom spin and win wheel plugin for TaraWallet integration.
 * Version: 1.0
 * Author: Anzolo Hope
 */

// Plugin code will go here.

// Include TaraWallet functions or API integration here.

// Function to handle spinning the wheel, processing results, and wallet integration
function spin_and_win_wheel() {
  // Simulate winning sections based on probabilities (replace with actual logic)
  $winning_sections = [
    1 => 2000,
    2 => 500,
    3 => 50,
    4 => 'try again',
    5 => 'try again',
    6 => 'try again'
  ];

  // Simulate deduction logic using TaraWallet API (replace with actual API calls)
  $deduction_successful = true; // Placeholder for successful deduction

  if ($deduction_successful) {
    // Simulate spinning logic to determine the winning section
    $winning_section = array_rand($winning_sections); // Randomly select a section (replace with actual logic)

    // Check if the user wins or tries again
    if ($winning_sections[$winning_section] !== 'try again') {
      $winning_amount = $winning_sections[$winning_section];

      // Simulate credit logic using TaraWallet API (replace with actual API calls)
      $credit_successful = true; // Placeholder for successful credit

      if ($credit_successful) {
        return "Congratulations! You won $winning_amount credits!"; // Return success message
      } else {
        return "Sorry, there was an issue crediting your winnings. Please try again."; // Return error message
      }
    } else {
      return "Better luck next time!"; // Return try again message
    }
  } else {
    return "Insufficient balance. Please add funds to your wallet."; // Return insufficient balance message
  }
} // Added closing curly brace for the function

// Hook the function into WordPress
add_action('wp_ajax_spin_and_win', 'spin_and_win_wheel');
add_action('wp_ajax_nopriv_spin_and_win', 'spin_and_win_wheel');

// Enqueue scripts and styles (these remain unchanged)
// Shortcode for displaying the spin and win wheel (this remains unchanged)

// Simulated functions (these remain unchanged)

// Shortcode for displaying the spin and win wheel
function spin_and_win_shortcode() {
  ob_start(); // Removed extra semicolon
  ?>
  <div id="spin-and-win-container">
    </div>
  <?php
  return ob_get_clean(); // Removed extra semicolon
} // Added closing curly brace for the function

add_shortcode('spin_and_win', 'spin_and_win_shortcode');
?>

JS Code

jQuery(document).ready(function($) {
    // Add JavaScript/jQuery for frontend interactions here
    jQuery(document).ready(function($) {
        // Function to handle stake selection
        $('.stake-button').on('click', function() {
            var selectedStake = $(this).data('stake'); // Get the selected stake amount
            $('.stake-button').removeClass('selected'); // Remove 'selected' class from all buttons
            $(this).addClass('selected'); // Add 'selected' class to the clicked button
        });
    
        // Function to simulate spinning the wheel and display result
        $('#spin-button').on('click', function() {
            var selectedStake = $('.stake-button.selected').data('stake'); // Get the selected stake
            if (selectedStake) {
                // AJAX call to backend logic for spinning the wheel
                $.ajax({
                    url: ajax_object.ajax_url,
                    type: 'POST',
                    data: {
                        action: 'spin_and_win',
                        selected_stake_amount: selectedStake
                    },
                    success: function(response) {
                        // Display the result to the user
                        $('#spin-result').text(response);
                        // Add styling based on win or try again (modify as needed)
                        if (response.includes('won')) {
                            $('#spin-result').addClass('winning-result');
                        } else if (response.includes('luck')) {
                            $('#spin-result').addClass('try-again-result');
                        }
                    },
                    error: function(xhr, status, error) {
                        // Handle error response
                        console.log(error); // Log the error for debugging
                    }
                });
            } else {
                alert('Please select a stake amount.');
            }
        });
    });
    
});

css code

#spin-and-win-container {
    /* Add styles for the wheel container */
    /* CSS for the wheel container */
#spin-and-win-container {
    width: 300px; /* Adjust as needed */
    height: 300px; /* Adjust as needed */
    border: 2px solid black; /* Wheel border */
    border-radius: 50%; /* Create a circular shape */
    margin: 20px auto;
    position: relative;
    overflow: hidden;
    background-color: white; /* Wheel background color */
}

/* CSS for individual wheel sections */
#spin-and-win-container .section {
    position: absolute;
    width: 0;
    height: 0;
    border-style: solid;
    border-width: 150px 75px; /* Adjust size */
    border-color: transparent transparent green transparent; /* Different shades of green */
    transform-origin: 0 100%;
}

/* Adjust styles for different sections */
#spin-and-win-container .section:nth-child(1) {
    transform: rotate(0deg);
}

#spin-and-win-container .section:nth-child(2) {
    transform: rotate(60deg);
}

/* Repeat for other sections */

/* Additional styling for winning or try again sections (modify as needed) */
.winning-result {
    background-color: #ffc107; /* Example winning background color */
}

.try-again-result {
    background-color: #f44336; /* Example try again background color */
}

}

/* Add additional styles for the spinning wheel, buttons, etc. */
/* Additional styles for the spinning wheel */
#spin-and-win-container {
    /* Existing styles */

    /* Center the wheel within its container */
    display: flex;
    justify-content: center;
    align-items: center;
}

/* Styles for the spin button */
#spin-button {
    display: block;
    width: 150px;
    padding: 10px;
    margin: 20px auto;
    border: none;
    border-radius: 5px;
    background-color: #4caf50; /* Green button color */
    color: white;
    font-size: 16px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

#spin-button:hover {
    background-color: #388e3c; /* Darker green on hover */
}

/* Styles for stake buttons */
.stake-button {
    display: inline-block;
    padding: 8px 16px;
    margin: 10px;
    border: none;
    border-radius: 5px;
    background-color: #4caf50; /* Green button color */
    color: white;
    font-size: 14px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.stake-button.selected {
    background-color: #2e7d32; /* Darker green for selected button */
}

.stake-button:hover {
    background-color: #388e3c; /* Darker green on hover */
}


I use the above code but the wheel is not showing up, its return a blank page.

Swiper react.js

i want to ask why class does not working if I want control swiper is active class(.swiper-slide-active) work I put class put does not work there is code

Component Code:

import styles from './styles.module.css';

export default function SwiperProduct() {
  
  return (
    <Swiper
      modules={[Navigation, Pagination, Scrollbar, A11y, Autoplay, EffectFade]}
      spaceBetween={50}
      slidesPerView={1}
      navigation
      autoplay={{ delay: 4000, disableOnInteraction: true }}
      effect="fade"
      pagination={{ clickable: true }}
    // scrollbar={{ draggable: true }}
      
    >
      <SwiperSlide className='p-5 d-flex justify-content-center'>
        <img className='object-fit-cover' src={phones} width='100%' height='400px' alt='' />
this class i put

        <article className={`position-absolute text-start ${styles.swiperSlide}`}>
          <article className={`p-5 ${styles.collection}`}>
            <p className={'pt-5'}>NEW COLLECTION</p>
            <button className='btn btn-outline-warning'>Shop Now</button>
          </article>
        </article>
      </SwiperSlide>

css code:

.swiperSlide {
    background-color: rgba(240, 248, 255, 0.212); 
    height: 400px;
    width: 820px;
    opacity: 0;
}
.swiper-slide-active .swiperSlide {
    opacity: 0;
    transition: 1s ease;
}
.collection {
    transform: translate(-85px);
    opacity: 0;
    transition: 1s ease;
    height: 400px;
    width: 820px;
}

.swiper-slide-active .collection {
    opacity: 1;
    transition: 1s ease;
    transform: translateX(0);
}

I tried to target this class and search I don’t found solution.