Issue in implementing median cut algorithm using Javascript

I am trying to implement a code that picks out colors from an image and then gets a pallet of certain colors from all the colors of the image. I am trying to use the Median Cut Algorithm for implementing this.

Currently, I am following the steps for the Median Cut algorithm mentioned here:

Here’s a code snippet from my POC:

const getColor = () => {
  const canvas = document.createElement('canvas');
  canvas.width = displayImage.width;
  canvas.height = displayImage.height;
  const ctx = canvas.getContext('2d');
  ctx.drawImage(displayImage, 0, 0);
  const pixelData = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
  getPallete(pixelData);
};
const getPallete = (data) => {
  // data contains image data (r,g,b,a)
  if (data.length != 0) {
    for (let i = 0; i < data.length; i += 4) {
      let [red, green, blue] = [data[i], data[i + 1], data[i + 2]];

      if (red < channelProperties.minRed) {
        channelProperties.minRed = red;
      }
      if (red > channelProperties.maxRed) {
        channelProperties.maxRed = red;
      }

      // Update minimum and maximum values for green channel
      if (green < channelProperties.minGreen) {
        channelProperties.minGreen = green;
      }
      if (green > channelProperties.maxGreen) {
        channelProperties.maxGreen = green;
      }

      // Update minimum and maximum values for blue channel
      if (blue < channelProperties.minBlue) {
        channelProperties.minBlue = blue;
      }
      if (blue > channelProperties.maxBlue) {
        channelProperties.maxBlue = blue;
      }
    }
    // gets the channel with highest range
    let highestChannel = getChannel();
    //This sorts the image data based on highest channel
    let sortedData = sortImageData(data, highestChannel);
    //This gives back the middle index
    let median = getMedian(sortedData);
    //Here I break the array from median and resend it
    const lowerPart = data.slice(0, median);
    const upperPart = data.slice(median + 1);
    getPallete(lowerPart);
    getPallete(upperPart);
  }
};

I have implemented the first 4 steps mentioned in the link. However, I am messing up in the last step or rather I am unable to figure out how to get my final pallet. Can anyone help in correcting this code/telling me what I missed?

create slider with progress bar

I am creating a slider with timer pagination on dots, like https://www.samsung.com/africa_en/. I used pure Js instead of slick.js. I need to make a progress bar stope with slider pause without Lage or delay ( progress not reset correctly ).

How can I stop pagination buttons with progress bars ?I

const slider = document.querySelector('.slider');
const slides = document.querySelector('.slides');
const slideImages = document.querySelectorAll('.slides img');
const pagination = document.querySelector('.pagination');
const playPauseBtn = document.querySelector('.play-pause'); // select the play/pause button

let slideIndex = 0;
let isPaused = false; // added variable to track pause state
const pausedDotAttribute = 'data-paused';

const prevBtn = document.querySelector('.prev');
const nextBtn = document.querySelector('.next');

// Set active dot
const dots = document.querySelectorAll('.dot');
dots[slideIndex].classList.add('active');

const progressContainer = document.querySelectorAll('.dot');
const progressBar = document.querySelectorAll('.progress-bar');
let isPausedd = false;
let progressWidth = 0;
let currentProgress = 0;

function startProgress() {
  let timerId = setInterval(() => {
    if (!isPausedd) {
      progressWidth++;
      if (progressWidth >= 100) {
        progressWidth = 0;
        progressBar[currentProgress].style.width = `${progressWidth}%`;
        clearInterval(timerId);
        currentProgress++;
        if (currentProgress >= progressBar.length) {
          currentProgress = 0;
        }
        startProgress();
      } else {
        progressBar[currentProgress].style.width = `${progressWidth}%`;
      }
    }
  }, 50);

  progressContainer[currentProgress].addEventListener('mouseenter', () => {
    isPausedd = true;
  });

  progressContainer[currentProgress].addEventListener('mouseleave', () => {
    isPausedd = false;
  });
}

startProgress();


// --------------------------------------------

// Set timer
let timerId = setInterval(() => {
  slideIndex++;
  if (slideIndex >= slideImages.length) {
    slideIndex = 0;
  }
  showSlide();
}, 5000);

// Show slide function
function showSlide() {
  slides.style.transform = `translateX(-${slideIndex * 100 / slideImages.length}%)`;
  dots.forEach(dot => dot.classList.remove('active'));
  dots[slideIndex].classList.add('active');
  if (isPaused) {
    dots[slideIndex].classList.add('paused'); // add paused class to active dot when paused
   } else {
    dots[slideIndex].classList.remove('paused'); // remove paused class when resumed
   }
}


// Toggle play/pause button and stop/restart timer
playPauseBtn.addEventListener('click', () => {
  if (playPauseBtn.textContent === 'Pause') {
    clearInterval(timerId);
    playPauseBtn.textContent = 'Play';
  } else {
    timerId = setInterval(() => {
      slideIndex++;
      if (slideIndex >= slideImages.length) {
        slideIndex = 0;
      }
      showSlide();
    }, 5000);
    playPauseBtn.textContent = 'Pause';
  }
});

 // Pause slider on slide hover
slides.addEventListener('mouseenter', () => {
clearInterval(timerId);
  playPauseBtn.textContent = 'Play';
    isPaused = true;
  dots[slideIndex].setAttribute(pausedDotAttribute, isPaused);   // ?
});

// Resume slider on slide mouse leave
slides.addEventListener('mouseleave', () => {
  isPaused = false;
   timerId = setInterval(() => {
      slideIndex++;
      if (slideIndex >= slideImages.length) {
        slideIndex = 0;
      }
      showSlide();
    }, 5000);
 playPauseBtn.textContent = 'Pause';
});


 // Navigate to previous slide
prevBtn.addEventListener('click', () => {
  slideIndex--;
  if (slideIndex < 0) {
    slideIndex = slideImages.length - 1;
  }
  showSlide();
});

// Navigate to next slide
nextBtn.addEventListener('click', () => {
  slideIndex++;
  if (slideIndex >= slideImages.length) {
    slideIndex = 0;
  }
  showSlide();
});
<!-- HTML code -->
<div class="slider">
  <div class="slides">
    <img
      src="https://online.marvansmobile.com/assets_2/images/demos/demo1/slides/slide1.jpg"
    />
    <img
      src="https://jssors8.azureedge.net/demos/image-slider/img/px-bloom-blossom-flora-65219-image.jpg"
    />
    <img
      src="https://jssors8.azureedge.net/demos/image-slider/img/px-action-athlete-athletes-848618-image.jpg"
    />
  </div>
  <div class="pagination">
    <div class="dot active" data-index="0">
      <div class="progress-bar"></div>
    </div>
    <div class="dot" data-index="1">
      <div class="progress-bar"></div>
    </div>
    <div class="dot" data-index="2">
      <div class="progress-bar"></div>
    </div>
  </div>
</div>
<button class="prev">&#10094;</button>
<button class="next">&#10095;</button>

<button class="play-pause">Pause</button>

<style>
  /* CSS code */
  .slider {
    position: relative;
    width: 100%;
    height: 300px;
    overflow: hidden;
  }
  .slides {
    display: flex;
    width: 300%;
    height: 100%;
    transition: transform 0.5s ease;
  }
  .slides img {
    width: 100%;
    height: 100%;
  }
  .pagination {
    position: absolute;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
  }
  .dot {
    width: 300px;
    height: 5px;
    margin: 0 5px;
    /* border-radius: 50%; */
    background-color: gray;
    cursor: pointer;
  }
  .dot.active {
    background-color: black;
  }
  .dot.active::after {
    content: '';
    background-color: cyan;
    height: 5px;
    position: absolute;
    top: 50%;
    /* right: 0; */
    transform: translateY(-50%);
    animation: progress;
    animation-duration: 5s;
    animation-timing-function: linear;
    animation-iteration-count: infinite;
  }
  .dot.active.paused::after {
    animation-play-state: paused; /* added property */
  }

  @keyframes progressj {
    0% {
      width: 0;
    }
    100% {
      width: 300px;
    }
  }
  .prev,
  .next {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    background: transparent;
    color: #fff;
    border: none;
    outline: none;
    font-size: 24px;
    cursor: pointer;
  }
  .prev {
    left: 0;
  }
  .next {
    right: 0;
  }
  .dot {
        width: 300px;
        height: 10px;
        background-color: black;
      }
      .progress-bar {
        width: 0%;
        height: 100%;
        background-color: red;
        transition: width 1s linear;
      }
</style>

I am creating a slider with timer pagination on dots, like https://www.samsung.com/africa_en/. I used pure Js instead of slick.js. I need to make a progress bar stope with slider pause without Lage or delay ( progress not reset correctly ).

How can I stop pagination buttons with progress bars ?I

I am unable to see addEventListener event in dev tools MicrosoftEdge Version 112.0.1722.34 (Official build) (64-bit)

let x = document.createElement('p');
x.style.background = "aqua";
x.textContent = ' Click inside the box to Change background color ';
x.id = "para1";
console.log(x);
document.body.appendChild(x);

function changeBackgroundColor(e) {
  e.target.style.background = "yellow";
}
document.getElementById("para1").addEventListener("click", changeBackgroundColor);
debugger;
p {
  border: solid green 2px;
  margin-right: 65em;
  margin-top: 24px;
}

I have put a debugger after the addEventListener and paused code execution but still it shows No event Listeners.

Where did I go wrong?

pic1

pic2

Loop contract deploy function for each different wallet using nodejs

How to repeat contract deploy function for next wallet(privatekey2,privatekey3)?

I am using the following code but running only 1 wallet (PRIVATEKEY1) and the function stop, I want each wallet to create one contract. Thank you for help.

const Web3 = require("web3");

// Loading the contract ABI and Bytecode
// (the results of a previous compilation step)
const fs = require("fs");
const { abi, bytecode } = JSON.parse(fs.readFileSync("Demo.json"));

async function main() {
  // Configuring the connection to an Ethereum node
  const network = process.env.ETHEREUM_NETWORK;
  const web3 = new Web3(
    new Web3.providers.HttpProvider(
      `https://${network}.infura.io/v3/${process.env.INFURA_API_KEY}`
    )
  );
  // Creating a signing account from a private key
  const signer = web3.eth.accounts.privateKeyToAccount("PRIVATEKEY1","PRIVATEKEY2","PRIVATEKEY3"
  );
  web3.eth.accounts.wallet.add(signer);

  // Using the signing account to deploy the contract
  const contract = new web3.eth.Contract(abi);
  contract.options.data = bytecode;
  const deployTx = contract.deploy();
  const deployedContract = await deployTx
    .send({
      from: signer.address,
      gas: await deployTx.estimateGas(),
    })
    .once("transactionHash", (txhash) => {
      console.log(`Mining deployment transaction ...`);
      console.log(`https://${network}.etherscan.io/tx/${txhash}`);
    });
  // The contract is now deployed on chain!
  console.log(`Contract deployed at ${deployedContract.options.address}`);
  console.log(
    `Add DEMO_CONTRACT to the.env file to store the contract address: ${deployedContract.options.address}`
  );
}

require("dotenv").config();
main();

Loop contract deploy function for each different wallet using nodejs

CSS styled dropdown menus that initiate various JavaScript functions

Assignment instructions provided

In my HTML file I’ve created various drop down menus styled in CSS. The task that I’m having trouble wrapping my head around, is that each drop down option should initiate a different java script function, using one .js file.

<div id="nav">
        <ul>
            <li><a href="browser">Browser Test</a></li>
            <li><a href="html">HTML Feature Test</a></li>
            <li class="dropdown">
              <a href="javascript:void(0)" class="dropbtn">Mobile Tests</a>
              <div class="dropdown-content">
                <a href="#">Screen Resolution</a>
                <a href="#">Screen Orientation</a>
              <li class="dropdown">
              <a href="javascript:void(0)" class="dropbtn">Canvas Test</a>
              <div class="dropdown-content">
                <a href="#">General Support</a>
                <a href="#">Text Support</a>
                <a href="#">Draw Canvas</a>
              </div>

Here is what the instructions are looking for:
Instructions

I’ve started with the following js code in an attempt to get the browser information requested. I’m attempting to work through getting the other information but haven’t come close to anything that’s complete.

{document.getElementById(“#”).innerHTML = “navigator.appCodeName is ” +
navigator.appCodeName;

}

{document.getElementById(“#”).innerHTML = navigator.appVersion;
}

{document.getElementById(“#”).innerHTML =
“navigator.appName is ” + navigator.appName;

}

{document.getElementById(“#”).innerHTML =
“cookiesEnabled is ” + navigator.cookieEnabled;

}

{document.getElementById(“#”).innerHTML = navigator.language;

}

{document.getElementById(“#”).innerHTML = navigator.platform;

}

{document.getElementById(“#”).innerHTML = navigator.userAgent;

}

Web framework: How to build an html template from nested classes/views?

So I’ve been trying to make a very basic web framework using typescript and classes, just as a way to improve my understanding of both. I wanted to have parent classes instantiate their nested children, and then at the bottom of the tree pass their templates back to their parents.

At a basic level, when instantiated the parent class constructor calls functions that create:

  • a template of the code to be inserted for that particular child class
  • a regions object that holds references to its nested div elements
  • a nestedViews object that holds references to the child views
  • it then creates its children, repeating the above steps
  • finally, starting with the deepest nested child, each view should attempt to pass its template back up to the parent, having attached listeners

^ it’s the last item that I’m stuggling massively with, and I’m feeling out of my depth tbh:

    // select a nested div, and insert the related template
    this.regions.element1.innerHTML =
      this.nestedViews['element1'].templateElement.innerHTML;
  }

At present this function is taking the template of an object’s nested view, and inserting it as html into the relevant div in the parent’s regions object.

But this is definitely lucky that it “works” rather than well designed or thought out. Which is why I can’t add event listeners – each of the templates, outside of the top level parent, aren’t actually present in the DOM once render is eventually called. And I can’t get my head around it.

If anyone can suggest a way to build a documentFragment or template as I create views, which is then passed back to the parent, I’d appreciate it!

View:

export abstract class View<T> {
  regions: { [key: string]: Element } = {};
  templateElement: HTMLTemplateElement = document.createElement('template');
  nestedViews: { [key: string]: View<T> } = {};

  abstract stringTemplate(): string;
  abstract insertNestedTemplates(): void;
  abstract createNestedViews(): void;
  abstract eventsMap(): { [key: string]: () => void };
  abstract regionsMap(): { [key: string]: string };

  constructor(public parentElement: Element, public model: T) {
    // Set the templateElement to the view's string literal
    this.templateElement.innerHTML = this.stringTemplate();

    // Find the selectors in the templateElement and create div elements for each
    this.mapRegions(this.templateElement.content);

    // Create the nested view objects
    this.createNestedViews();

    this.insertNestedTemplates();

    this.bindEvents(this.templateElement.content);

  }

  bindEvents(fragment: DocumentFragment): void {
    const eventsMap = this.eventsMap();
    for (let eventKey in eventsMap) {
      const [eventName, selector] = eventKey.split(':');
      fragment.querySelectorAll(selector).forEach((element) => {
        element.addEventListener(eventName, eventsMap[eventKey]);
      });
    }
  }

  mapRegions(fragment: DocumentFragment): void {
    const regionsMap = this.regionsMap();

    for (let key in regionsMap) {
      const selector = regionsMap[key];
      const element = fragment.querySelector(selector);

      if (element) {
        this.regions[key] = element;
      }
    }
  }

  render() {
    this.parentElement.appendChild(this.templateElement.content);
  }
}

An example Child View:

export class ChildView extends View<ChildModel> {
  constructor(parentElement: Element, model: ChildModel) {
    super(parentElement, model);
  }

  update(): void {}

  regionsMap(): { [key: string]: string } {
    return {
      element1: '.element1',
    };
  }

  eventsMap(): { [key: string]: () => void } {
    return {
      'click:.child-view': () => console.log('child view'),
    };
  }

  createNestedViews(): void {
    const element1 = new Element1(this.regions.element1, new Element1Model());
    this.nestedViews['element1'] = element1;
  }

  insertNestedTemplates(): void {
    this.regions.element1.innerHTML =
      this.nestedViews['element1'].templateElement.innerHTML;
  }

  stringTemplate(): string {
    return `
      <div class="child-view border-2">
        <h1>${this.model.name}</h1>
        <p>${this.model.description}</p>
        <div class="element1"></div>
      </div>
    `;
  }
}

How Can I Go About Writing A Javascript/PHP Parser To Transfer Data In Buttons To My Database?

I’m working on creating a tag system for users to be able to tag their profiles, the visual end of the system is working and is really simplistic, it’s a 2 divs, one for selectedTags one for unselectedTags, there’s like 30+ tags that appear in the unselectedTags div from the start, and on click if there is less than 5 tags currently selected it will move unselectedTags to selectedTags, users can click selected tags to 1) if the tag was originally in the unselectedTags div, move it back to the unselectedTags div, or 2) if it was user entered, it simply deletes the tag. I want to simply store the text data from the tags that are within the selectedTags div into the database, hopefully within like a single tags[] array, the user can enter tags so it’d be best if the parser would be able to access the innerHTML of the buttons, the issue is I’m really unsure of how to go about this, can I write a javascript parser to extract this data on submit button click? And how should I go about storing the tags[] until the submit button is pressed/how can I extract the tags[] when the submit button is pressed? The database doesn’t have a user entry for this user yet because the DB entry isn’t created until form submission so, I may be very wrong here and if I am that’d be lit, but I don’t think I can simply directly push the data on click of the buttons to the database bc there isn’t an entry for the user yet.

This is the setup for what I have working:

<form action="includes/artistRegister.inc.php" class="inputGroup" id="artistRegister" method="post">
<div class="tagSelect">
   <h2 class="tagHeader">Select Up To 5 Tags That Describe Your Style, Or</h2>
   <input type="text" name="inputTag" id="inputTag" class="inputTag" placeholder="Enter Your Own...">
   <div class="selectedTags" id="selectedTags">

   </div>

   <div class="unselectedTags smooth" id="unselectedTags">
      <button type="button" class="artistTag grafitti">Grafitti</button>
      <button type="button" class="artistTag minimalism">Minimalism</button>
      <button type="button" class="artistTag abstract">Abstract</button>
      <button type="button" class="artistTag flowers">Flowers</button>
      <button type="button" class="artistTag modern">Modern</button>
      <button type="button" class="artistTag street">Street</button>
      <!--...-->

      <!--I've been looking for help on this problem as well and got the recommendation to try
       setting the buttons up like checkboxes with a specific name and value to no avail-->
   </div>
</div>

<!--More form...-->

<button type="submit" name="submit" class="artistRegisterBtn">Register</button>
</form>
.selectedTags {
    max-width: 360px;
    overflow-x: scroll;
    overflow-y: hidden;
    white-space: nowrap;
    min-height: 0px;
    max-height: 65px;
    margin-top: 5px;
    display:none;
}

.selectedTags::-webkit-scrollbar {
    height: 4px;
}

.selectedTags::-webkit-scrollbar-thumb {
    background: white;
    border-radius: 10px;
}

#inputTag {
    width: 100%;
    background: none;
    border: none;
    box-shadow: none;
    border-bottom: 1px solid white;
    color: white;
    outline: none;
    user-select: none;
    padding: 10px 0px;
}

#inputTag::placeholder {
    color: white;
}

.tagHeader {
    color: white;
    padding-bottom: 10px;
    user-select: none;
}

.artistTag {
    background-color: rgb(25, 34, 58);
    padding: 5px 20px;
    border-radius: 20px;
    color: white;
    border: none;
    margin-top: 2px;
    margin-bottom: 2px;
    user-select: none;
}

.artistTag:hover {
    cursor: pointer;
}

.unselectedTags {
    margin-top: 10px;
    max-height: 70px;
    min-height: 40px;
    overflow-y: scroll;
    user-select: none;
}

.unselectedTags::-webkit-scrollbar {
    width: 4px;
}

.unselectedTags::-webkit-scrollbar-thumb {
    background: white;
    border-radius: 4px;
}

.tagSelect {
    max-height: 176px;
}
var list1 = document.getElementById("selectedTags");
var list2 = document.getElementById("unselectedTags");

document.addEventListener("DOMContentLoaded", function() {
    var tags = document.querySelectorAll(".artistTag");
    var userTags = document.querySelectorAll(".userEntry");

    function moveItem(e) {
        userTags = document.querySelectorAll(".userEntry");
        var moveTo = this.parentElement == list1 ? list2 : list1;
        if(moveTo == list1 && list1.childElementCount < 5) {
            if(list1.childElementCount <= 1) {
                list1.style.borderBottom = "1px solid white";
                list2.style.height = "40px";
                list1.style.display = "block";
            }
            moveTo.insertBefore(this, list1.firstChild);
            this.style.margin = "2px";
        } else if(moveTo == list2) {
            if(list1.childElementCount == 1) {
                list1.style.borderBottom = "0px solid white";
                list2.style.height = "70px";
                list1.style.display = "none";
            }
            moveTo.insertBefore(this, list2.firstChild);
            this.style.margin = "2px";
        }
    }

    for (var i = 0; i < tags.length; i++) {
        tags[i].addEventListener("click", moveItem);
    }
});

function deleteItem(e) {
    userTags = document.querySelectorAll(".userEntry");
    if(list1.childElementCount == 1) {
        list1.style.borderBottom = "0px solid white";
        list2.style.height = "70px";
        list1.style.display = "none";
    }
    this.remove();
}

$(document).on("keydown", ":input:not(textarea)", function(event) {
    return event.key != "Enter";
});

$(".inputTag").on('keyup', function (e) {
    if (e.key === 'Enter' || e.keyCode === 13) {
        if(list1.childElementCount < 5) {
            if(list1.childElementCount <= 1) {
                list1.style.borderBottom = "1px solid white";
                list2.style.height = "40px";
            }
            list1.style.display = "block";
            var input = document.createElement("button");
            input.innerHTML = inputTagText.value.charAt(0).toUpperCase() + inputTagText.value.slice(1);
            input.classList = "artistTag userEntry";
            input.type = "button";
            input.style.margin = "2px";
            list1.insertBefore(input, list1.firstChild);
            document.getElementById("inputTag").value = "";
            input.addEventListener("click", deleteItem);
        }
    }
});


$('.smooth').on('mousewheel', function(e){
    wheel(e.originalEvent, this)
  })
  
  function wheel(event, elm) {
      var delta = 0;
      if (event.wheelDelta) delta = event.wheelDelta / 120;
      else if (event.detail) delta = -event.detail / 3;
  
      handle(delta, elm);
      if (event.preventDefault) event.preventDefault();
      event.returnValue = false;
  }
  
  function handle(delta, elm) {
      const time = 250;
        const distance = 20;
      
      $(elm).stop().animate({
          scrollTop: $(elm).scrollTop() - (distance * delta)
      }, time );
  }

WordPress. Is it possible to programmatically determine if a website is located on a local computer (for example, on Denwer or Open Server)?

General information: I am developing a plugin for WordPress that needs to send requests. They are sent on real websites, but on a local computer, they need to be sent bypassing CORS.

In this regard, the question arose: is it possible to programmatically determine if a website is located on a local computer (for example, on Denwer or Open Server) in order to enable a CORS bypass workaround on local computers and disable it on real websites? And how safe is it?

The CORS bypass mechanism for a local computer, if necessary, is:

// The file "proxy.php" for proxying requests.
<?php
$api_url = 'https://WEBSITE.COM';
$headers = array('X-Auth-Key: CONFIDENTIAL API KEY INFORMATION');

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$response = curl_exec($ch);
curl_close($ch);

echo $response;
// The file "script.js" to make a request.
const url = 'proxy.php'
fetch(url)
  .then((response) => response.text()) // getting a text response
  .then((data) => JSON.parse(data))
  .then((json) => console.log(json))
  .catch((error) => console.error(error))

FabricJs aligning an object to the left of another object

I have an object that I need another object aligned left within.

  const handleToLeft = () => {
   const obj = c.c.getActiveObject();
   const canvasArea = c.c.getObjects()[0];

   obj.set({ left: canvasArea.left });
   obj.setCoords();
   c.c.renderAll();
   c.c.fire("object:modified"); 
 };

The code above works fine until I rotate ‘obj’ and call the function. At this point, the object gets cut off. Screenshot below:

enter image description here

Tasker: Copy GPT-chat to clipboard?

I am using the GPT-chat for tasker
Using the ‘WebVieW element in Tasker in local fil in the Document directory.

I am trying to create a ‘Copy’ Copy to clipboard button inside the chat bubble from GPT-chat Screenshot But after all I’ve read, mostly old posts, I can’t figure out how to do it? somehow this script should correspond with the GPT-chat. But I don’t know where to paste it. nor where I put the link inside the answers from GPT.

<script> function copyToClipboard(text) { var dummy = document.createElement("textarea"); document.body.appendChild(dummy); dummy.value = text; dummy.select(); document.execCommand("copy"); document.body.removeChild(dummy); }

Here’s what I’ve done so far:

  1. First, I added the necessary permissions to Tasker project. Preferences > Misc. In the “enable “Allow External Access” and “Tasker Web Server”.
  2. Next, created a new task and added “HTTP request” action. and added “Path” to the ‘/Document/chat.html‘.
    But I don’t know where in this chat.html file I should put the code or the link??

How do I add this function to chat.html? to the answers that GPT chat gives?

Fetch POST requests in JavaScript failing “stress” test. Refreshing the page several times and making large requests causes fetch requests to fail

When loading the page, the site makes several small POST requests to my API made with PHP. The first several requests fetch a couple things from the SQL database and using that data makes a final set of requests for a json file for each object the user has.

The first request gets the users data (SQL Database), the second request gets a list of IDs of the objects they have connected to their user (SQL Database), then using the list of IDs it loops through however many they have making a fetch call to get the json data for each object.

If the user has only a couple objects connected it will fail after 15-20 times of refreshing, and the more objects the user has the sooner and more likely it is to fail.

The error isn’t very descriptive and nowhere in dev tools or in my cpanel can I find a descriptive error. All of them get the same error. I just happened to catch the error on the one before it started getting the json objects.
Console Error
Request headers

Here is the Javascript code for the fetch request.

` var url = api_url + “GetStayByID.php”;

var formData = new FormData();
formData.append("id", id);

fetch(url, {
    method: 'POST',
    body: formData
})
.then(response => response.text())
.then(responseText => OnStayDataReceived(responseText, index))
.catch(error => {
    ConfirmMessage("Error connecting to the server. Please wait a few minutes, refresh, and try again. If the issue persists please contact us at XXX-XXX-XXXX.");
    console.log("Error connecting to the server: " + error);
});`

This is the fetch request code for each of the objects (stays). I thought swtiching it to a GET request might fix it assuming the POST request was slower. But at some point I may have to pass other more sensitive data and would prefer to use POSTs of GETs. Unless GETs are the solution I could do some kind of work around.

The request above is essentially a copy of the other requests just a different URL.

Here is the PHP request for the json data above at /api/GetStayData.php
`<?php

header("Access-Control-Allow-Origin: *");

//Get the stay ID
$ID="";
if (isset($_POST["id"])){
    $ID=$_POST["id"];
}else{
    echo("ID not recognized.");
    return;
}

$source = "../stays/".$ID."/data.json";
$rawData = file_get_contents($source);

echo($rawData);

?>`

This problem only happens every so often and more often the larger the user is. This would not be the end of the world but there are other requests that need to succeed all the way through or not at all for proper error handling and I assume whatever concept I am missing here would apply to those as well.

Each json object is no more than 500 bytes. With 20-30 objects this can happen in as little as 3-5 refreshes.

I am fairly new to web development and don’t quite understand stress testing and cacheing and only seems to happen with a lot of data being fetched from the server wether through several requests or a couple “large” ones.

Please let me know if I am missing any important info or need to explain something better. Like I said I am fairly new to web development and could very well be missing info.

Solutions I have tried:
-Upgrading the web hosting package on my cpanel assuming it just needed more bandwidth
-Retreiving just the JSON file directly (It sometimes fails before it even gets to the stay fetches so I do not think it is that)

All of these resulted in the same error shown above.

Possible solutions I have not tried:
-Wrapping all of the requests into a single request
-Something with Cors? This is being run on a live server on my personal machine and accessing my actual public domain

Validation Status

I am trying to do a status validation with nodejs and mongodb, if the status is “unverified” I should not be able to access, however if the status is “verified” it allows me to access the account. note: The state is saved in the database

My verification code is this (controller)

exports.usuario_verify = function (req, res) { 
  let usuario = req.body.username;
  let pass = req.body.password;
  let datos = "Usuario: " + usuario + " Pass: " + pass;
  if (usuario && pass) {
    //Hay datos en usuario y password
    User.find({ Username: usuario, Password: pass }, function (error, results) {
      if (error) {
        let data = {
          title: "Ingreso al sistema",
          message: "Hubo un error contacte a soporte",
        };
        res.render("login", data);
      }

      if (results.length > 0) {
        let roles;
        results.forEach((element) => {
          roles = element.Roles;
        });
        req.session.usuario = usuario;
        req.session.role = roles;
        if (roles === "admin") {
          res.render("admin_home");
        } else if (roles === "user") {
          res.render("coleccion"); //next();
        }
      } else {
        let data = {
          title: "Ingreso al sistema",
          message: "Usuario o contraseƱa no son correctos",
        };
        res.render("login", data);
      }
    });
  } else {
    let data = {
      title: "Ingreso al sistema",
      message: "Usuario o contraseƱa no son correctos",
    };
    res.render("login", data);
   
    
}};

exports.usuario_add = function (req, res) {
  res.send("Ruta controlada");
};

I am trying to do a status validation with nodejs and mongodb, if the status is “unverified” I should not be able to access, however if the status is “verified” it allows me to access the account. note: The state is saved in the database

Vite-PWA-plugin how to add webpush (notifications)

I had the sw.js which receive webpush notifications.
But recently I intalled vite-PWA-plugin and now i can’t add notifications by default config.

How can i configure this vite.config.ts to add to generated serviceWorker.js webpush implementation?

vite.config.ts:

import {defineConfig} from 'vite';
import laravel from 'laravel-vite-plugin';
import react from '@vitejs/plugin-react';

import path from 'path';
import {VitePWA} from "vite-plugin-pwa";

const manifest = {
    "theme_color"     : "#2B2B2B",
    "background_color": "#2B2B2B",
    "display"         : "standalone",
    "scope"           : "/",
    "start_url"       : "/farm",
    "name"            : "ColorBit",
    "short_name"      : "Mining",
    "description"     : "...",
    "icons"           : [
        {
            "src"  : "icons/icon-192x192.png",
            "sizes": "192x192",
            "type" : "image/png"
        },
        // ...
        {
            "src"    : "icons/maskable_icon.png",
            "sizes"  : "682x682",
            "type"   : "image/png",
            "purpose": "maskable"
        }
    ]
};

const getCache = ({ name, pattern, strategy = "CacheFirst" }: any) => ({
    urlPattern: pattern,
    handler: strategy,
    options: {
        cacheName: name,
        expiration: {
            maxEntries: 500,
            maxAgeSeconds: 60 * 60 * 24 * 60 // 2 months
        },
        cacheableResponse: {
            statuses: [0, 200]
        }
    }
});

export default defineConfig({
    plugins: [
        laravel({
            input  : [ 'resources/js/app.tsx',],
            refresh: true,
        }),
        react({
            fastRefresh: false
        }),
        VitePWA({
            registerType: 'autoUpdate',
            outDir      : path.resolve(__dirname, 'public'),
            manifest    : manifest,
            manifestFilename: 'manifest.webmanifest', // Change name for app manifest
            injectRegister  : false, // I register SW in app.ts, disable auto registration

            workbox         : {
                globDirectory: path.resolve(__dirname, 'public'), // Directory for caching
                globPatterns : [
                    '{build,images,sounds,icons}/**/*.{js,css,html,ico,png,jpg,mp4,svg}'
                ],
                navigateFallback: null, // Say that we don't need to cache index.html
                swDest       : 'public/serviceWorker.js',
                runtimeCaching: [
                    // Google fonts cache
                    getCache({
                        pattern: /^https://fonts.googleapis.com/.*/i,
                        name: "google-fonts-cache",
                    }),
                    // Google fonts api cache
                    getCache({
                        pattern: /^https://fonts.gstatic.com/.*/i,
                        name: "gstatic-fonts-cache"
                    }),
                    // Dynamic cache for assets in storage folder
                    getCache({
                        pattern: /.*storage.*/,
                        name: "dynamic-images-cache",
                    }),

                ]
            }
        })
    ],
    resolve: {
        alias     : {
            '@'          : path.resolve(__dirname, 'resources/js'),
            '@hooks'     : path.resolve(__dirname, 'resources/js/hooks'),
            '@assets'    : path.resolve(__dirname, 'resources/js/assets/'),
            '@components': path.resolve(__dirname, 'resources/js/components')
        },
        extensions: ['.js', '.ts', '.tsx', '.jsx'],
    },
});

Old webpush implementation in sw.js:

// ^^^ Activate, Install, Fetch... ^^^

/* Webpush Notifications */

// Receive push notifications
self.addEventListener('push', function (e) {
    if (!(
        self.Notification &&
        self.Notification.permission === 'granted'
    )) {
        //notifications aren't supported or permission not granted!
        return;
    }

    if (e.data) {
        let message = e.data.json();
        e.waitUntil(self.registration.showNotification(message.title, {
            body: message.body,
            icon: message.icon,
            actions: message.actions
        }));
    }
});

// Click and open notification
self.addEventListener('notificationclick', function(event) {
    event.notification.close();

    if (event.action === 'farm') clients.openWindow("/farm");
    else if (event.action === 'home') clients.openWindow("/");
    else if (event.action === 'training') clients.openWindow("/mining-training");
    else if (event.action === 'dns') clients.openWindow("/shops/dns");
    else if (event.action === 'ali') clients.openWindow("/shops/aliexpress");
    else clients.openWindow("/farm");
}, false);

Render Error while using React Router Native

I have this App.js file with this content:

import { StyleSheet } from 'react-native';
import Main from './src/components/Main';

export default function App() {
  return <Main />;
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

And the Main.jsx file with this code:

import React from 'react';
import { Text, View } from 'react-native';
import { NativeRouter, Switch, Route, Redirect } from 'react-router-native';

const HomeScreen = () => (
    <View>
        <Text>Welcome to the home screen!</Text>
    </View>
);

const AboutScreen = () => (
    <View>
        <Text>Welcome to the about screen!</Text>
    </View>
);

const NotFoundScreen = () => (
    <View>
        <Text>Sorry, this page was not found.</Text>
    </View>
);

const Main = () => {
    return (
        <NativeRouter>
            <Switch>
                <Route exact path="/" component={HomeScreen} />
                <Route exact path="/about" component={AboutScreen} />
                <Redirect from="/old-about" to="/about" />
                <Route component={NotFoundScreen} />
            </Switch>
        </NativeRouter>
    );
}

export default Main;

It’s a simple example, but I experiment this error:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely to export your component from the file it’s defined in, or you might have mixed up default and named imports.

This is a screenshot with the error:

Error in Expo

Thanks in advance for your attention and help.

Dynamic module import in React Native Expo

If my React Native Expo app (running in Expo Go app) currently does an import/from

import Foo, {Bar} from "foo";

How can it be converted to be imported dynamically, where it is imported only when a certain condition is met, such as when hello === "world"?

Doing the following causes it to crash with error non-std C++ exception.

if (hello === "world") {
    import Foo, {Bar} from "foo";
}

Tried this alternative and it still crashes with non-std C++ exception:

if (hello === "world") {
    const Foo = import('foo')
    const Bar = Foo.Bar
}