Problem populating Street Address field using javascript in console on USPS Click-N-Ship web site

I am having a problem populating one field on the USPS Click-N_Ship web site from the console using Javascript.

I can populate First, Middle and Last Names, City, State, and Zip code, and even the Apartment field, but cannot populate the Street Address field. I suspect this is because the Street Address is a lookup field.

This code:

document.querySelector('input[name="recipient.firstName"]').value = "Jay";
document.querySelector('input[name="recipient.middleInitial"]').value = "A";
document.querySelector('input[name="recipient.lastName"]').value = "Talbott";
document.querySelector('input[name="recipient.addressLine2"]').value = "Apt 3.";
document.querySelector('input[name="recipient.city"]').value = "Denver";
document.getElementById('recipient-state').value = 'CO'
document.querySelector('input[name="recipient.zip9"]').value = "80601";

Will produce the expected results filling in the appropriate fields.

The elements of the Street Address are shown in the image.

Can someone tell me what javascript I need to use to populate the Street Address field?

Thank you.

I have tried document.getElementById(‘recipient-addressLine1’) and variations thereof without any luck..

[elements of Street Address field]
: https://i.sstatic.net/AbC69M8J.png

Using .scale() in HTML canvas causes hit detection issues

NOTE

Here is a link to a video I made demonstrating the issue at hand on Dropbox: https://www.dropbox.com/scl/fo/p19oite64o22sh9bl8s1b/ALnUvrJzNbK7QixHrgHGgdY?rlkey=gpxahqur1kmfdqr1ulow4bk04&st=hybj5h8y&dl=0

CONTEXT

I’m trying to create an agario-type game where the player spawns in as a circle and is able to eat small, circular foods to get bigger. I’m using HTML canvas on the client side and Node.js on the server side.

PROBLEM

I’ve been having great difficulty figuring out how to correctly scale the world as the player eats more food. In this game, when the player touches the food at all, they eat it. I’m using the .scale() method to slowly zoom out, so that as the player gets bigger, they don’t eventually totally overtake the screen so that they can’t see anything but themselves. However, as the player gets bigger, the hit detection gets worse — the player will be on top of a food and won’t eat it or will eat it before they touch it. It also seems that this poor hit detection corresponds to the direction: when the player moves upwards, the food is eaten late, as in the food will overlap the player and not be eaten. The same happens when the players moves left, where the food will overlap the player and not be eaten. Oppositely, when the player moves either right or down, the food will be eaten before the player makes contact with food. It’s as if I just have to move the player to the right a certain amount, but I don’t know which code to change or why it is causing issues in the first place.

CODE

I’ve removed code that does not seem to be relevant to the issue.

The Node.js server currently handles everything (spawning foods, calculating collisions between players, foods, etc.) except for giving player coordinates, as the client sends their coordinates to the server on every frame.

The “Player” class creates the structure for player objects. Within the Player class, I have the draw() method, which looks like this: 



draw(viewport) {
    if (this.isLocal) { //if it's the local player, send coordinates to server
        socket.emit('currentPosition', {
            x: this.x / zoom,
            y: this.y / zoom,
            radius: this.radius / zoom,
            speedMultiplier: this.speedMultiplier,
            vx: this.vx, //update these on server side?
            vy: this.vy
        });
    }

    ctx.save();
    ctx.translate(-viewport.x, -viewport.y);

    //scale the player
    ctx.scale(zoom, zoom);

    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
    ctx.fillStyle = this.color;
    ctx.fill();
    ctx.strokeStyle = this.strokeColor;
    ctx.lineWidth = 5;
    ctx.stroke();
    ctx.closePath();
    ctx.restore(); 
}

Within this draw() method, I use ctx.scale(zoom, zoom) to scale the player. My understanding is that this essentially multiplies the x/y position and the radius by the zoom factor. 

I also have a Food class, which creates food objects. The Food class’s draw() method looks like this: 



draw(viewport) {
        ctx.save();
        ctx.translate(-viewport.x, -viewport.y);
        ctx.scale(zoom, zoom); //scale foods
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
        ctx.fillStyle = this.color;
        ctx.fill();
        ctx.strokeStyle = this.strokeColor;
        ctx.lineWidth = 3.5;
        ctx.stroke();
        ctx.closePath();
        ctx.restore();
}

Both of these draw() methods are meant to scale the player and foods according to how many foods the player has eaten. When the player eats an individual food, the zoom rate decreases. The server tells the player when they have eaten food:



socket.on('foodEaten', (data) => {
    const player = gamePlayers.get(data.playerId);
    if (player.id == localPlayer.id) {
        zoom *= 0.9999;
    }
…

So, for each food the player eats, they zoom out by 0.9999.

The player’s movement is determined by where their mouse moves. When they move their mouse, this event listener calculates the direction the mouse is pointing in and sets the player on that path: 



canvas.addEventListener('mousemove', (event) => {
    const rect = canvas.getBoundingClientRect(); 
    mouse.x = (event.clientX - rect.left) / zoom; 
    mouse.y = (event.clientY - rect.top) / zoom; 

    // Update player's target position
    localPlayer.targetX = (mouse.x + viewport.x / zoom);
    localPlayer.targetY = (mouse.y + viewport.y / zoom);

    const dx = (localPlayer.targetX - localPlayer.x) * zoom;
    const dy = (localPlayer.targetY - localPlayer.y) * zoom;
    const distance = Math.sqrt(dx * dx + dy * dy); 

    ...does some other stuff in between...

    const xMovingDirection = dx / distance;
    const yMovingDirection = dy / distance;

    localPlayer.movingDirection = { x: xMovingDirection, y: yMovingDirection};
});

I mentioned in the draw() method of the Player class that they emit their current position to the server before the player is drawn:



socket.emit('currentPosition', {
    x: this.x / zoom,
    y: this.y / zoom,
    radius: this.radius / zoom,
    speedMultiplier: this.speedMultiplier,
    vx: this.vx,
    vy: this.vy
});

I divide the x and y coordinates and the radius by the zoom level to allow the server to disregard individual player’s zoom levels, so that every other player in the game is being sent non-zoomed coordinates.

After the server receives this information, it evaluates the player’s position against every food in the game, checking if they are colliding: 



socket.on('currentPosition', (data) => { //get player's current x/y coordinates and update them
    const player = room.players.get(socket.id);
    if (player) {
        player.x = data.x; //update player x position
        player.y = data.y; //update player y position

        room.foods.forEach((food, foodId) => { //check for foods being eaten
            if (checkCollision(player, food)) {
                player.radius += food.radius * normalRadiusIncreaseRate; //increase player radius

                let newFood; //add food back in
                newFood = new Food(); //add new food item
                room.foods.set(newFood.id, newFood);

                //let player know that they ate food
                io.to(room.roomId).emit('foodEaten', {
                    food: food,
                    playerId: player.id,
                    radius: player.radius,
                    newFood: newFood
                });

                room.foods.delete(food.id); //delete eaten food
            }

        //send this player’s data to other players
        socket.to(room.roomId).emit('updatePlayerTarget', {
            id: socket.id,
            x: player.x,
            y: player.y
            // radius: player.radius
        });                   
    }
});

If a player collides with a food, they should eat it. Node.js emits ‘foodEaten’ to the client, which allows the client to update the radius of the player who ate the food. It also gives the player’s x and y coordinates at the end of the block.

QUESTION

Why is it that, when using .scale(), the synchronization between the player and the food gets worse over time?

How do I create an array out of specific parts of JSON data?

After calling an API, I have some data in JSON format. Within that format, there is an array with sub-parts (I apologize, I don’t know the terminology) that exist inside each key of the array.

{
  "id": "<my id>",
  "bots": [],
  "avatar": "https://static-cdn.jtvnw.net/jtv_user_pictures/1c1c09ef-3937-4408-8f31-04ec6bec2238-profile_image-300x300.png",
  "channelEmotes": [],
  "sharedEmotes": [
    {
      "id": "<emote id>",
      "code": "<emote name>",
      "imageType": "<filetype>",
      "animated": true,
      "user": {
        "id": "<emote creator id>",
        "name": "<emote creator username>",
        "displayName": "<emote creator display name>",
        "providerId": "<not sure what this field is actually>"
      }
    },
    {
      "id": "<emote id>",
      "code": "<emote name>",
      "imageType": "<filetype>",
      "animated": true,
      "user": {
        "id": "<emote creator id>",
        "name": "<emote creator username>",
        "displayName": "<emote creator display name>",
        "providerId": "<not sure what this field is actually>"
      }
    }
  ]
}

Specifically, I want to make separate arrays for all the emote name, emote id, and filetypes like (I plan to have many more than these two)

var emotecodes = [code0, code1, ...];
var emoteids = [id0, id1, ...];
var emotefiletypes = [imageType0, imageType1, ...];

I’ve tried various other things I’ve found around the internet but have had no success.

compile shared library that contains low-level static library

I have a tool that is compiled on Ubuntu 22.04, but this tool needs to run on a Centos 7 system. Ubuntu has a higher version of glibc and when running the compiled tool on Centos 7, it has error:

ImportError: /lib64/libm.so.6: version `GLIBC_2.27' not found

This error is from a shared library file that is needed in the tool. So I want to include the required low-level library into my tool. I do have libm.a file in the compile system and I want to merge it into the shared library.

I tried to merge it with command like:

  find_library(M_LIBRARY m REQUIRED)
  find_library(Z_LIBRARY z REQUIRED)
  target_link_options(onnx_cpp2py_export PRIVATE "-Wl,-Bstatic" "-lm" "-lc" "-lz")

and

target_link_libraries(onnx_proto PRIVATE "/usr/lib/x86_64-linux-gnu/libz.a"
                                         "/usr/lib/x86_64-linux-gnu/libm.a"
                                         "/usr/lib/x86_64-linux-gnu/libc.a"
                                         "-Wl,-fPIC")

and neither worked. I say it did not work based on the fact that onnx_cpp2py_export.so still repy on libm.so.6

root@75b3e00f1508:/static/build# ldd onnx_cpp2py_export.so
        linux-vdso.so.1 (0x00007ffeae184000)
        libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f68d55fd000)
        libm.so.6 => /usr/lib/x86_64-linux-gnu/libm.so.6 (0x00007f68d5516000)
        libgcc_s.so.1 => /usr/lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f68d54f6000)
        libc.so.6 => /usr/lib/x86_64-linux-gnu/libc.so.6 (0x00007f68d52cd000)
        /lib64/ld-linux-x86-64.so.2 (0x00007f68d5fb9000)

What should I do here?

Jekyll not serving files correctly when manually refreshing page

When running command jekyll serve --no-watch . to run a server for testing, whenever I make changes to “test.txt” and refresh the page, the changes are not captured (for example, when “hello” is in test.txt and I erase the text and refresh the page, “hello” is still present). Is there a way to reverse this behavior? I understand that --no-watch means the site won’t automatically regenerate when files change, however, my understanding is that it should still serve the files correctly when manually refreshing the page. Code snippet below:

<script>
  function bannerUpdate() {
    const url = 'http://127.0.0.1:4000/test.txt'
    let bannerText = ''

    let bannerInit = {
      method: 'GET',
      cache: 'no-cache',
    };

    fetch(url, bannerInit)
      .then(response => {
        response.text().then(text => {
          bannerText = text;
          console.log("banner text is: "+bannerText);
          done();
        });
      });

    function done() {
      banner.textContent = bannerText;
      if (bannerText.trim() !== '') {
        banner.style.backgroundColor = '#fff691';
        banner.textContent = bannerText;
        banner.style.display = 'block';
      }
    }
  }

  window.onload = bannerUpdate;
</script>

Why is this the variable not set?

Why is nonce undefined while debugging both in Chrome and Edge?

enter image description here

enter image description here

Setup:

  • Chrome(127.0.6533.101)
  • Edge(127.0.2651.98)
  • CSP header(s) NOT enabled.

Libraries:

  • “style-loader”: “^2.0.0”,
  • “url-loader”: “^4.1.1”,
  • “webpack”: “^4.41.2”,

Need to refresh Wix-Stores gallery based on drop-down selections that are separate from Wix-Stores products

I currently have the following code that works on a repeater (see laketoads.com). Currently, the user selects drop-down values and clicks ‘Shop Now’ to be directed to our lake-apparel-showcase page. The user can change the state and/or lake here as well.

I want to move this same strategy to my ‘Shop All’ page instead but can’t figure out how to refresh the gallery (instead of repeater). The Wix-Stores Product Collection does not have a field called state or lake and I’m unable to add it so I created a separate database called ‘Import791’ that contains all the states, lakes and product names. Is there a way we can “link” the Product Name in the Wix-Stores Product Collection to my database (Import791) by Product Name then write the code to say (If the selected state equals this and the lake equals that, display associated products within the Wix-Stores Product Collection after linking the product name across the 2 sources?

Code I’m using that’s working on my lake-apparel-showcase page: AND… I truely appreciate anyone’s help as it’s soooo close!!

import wixData from 'wix-data';
import {session} from 'wix-storage';

$w.onReady(async function () {
    $w('#stateDropdown').options = [];
    $w('#lakeDropdown').options = [];

    const savedState = session.getItem("selectedState");
    const savedLake = session.getItem("selectedLake");

    try {
        await populateStateData();
        
        if (savedState) {
            $w('#stateDropdown').value = savedState;
            await populateLakeData(savedState);
            
            if (savedLake) {
                $w('#lakeDropdown').value = savedLake;
            }
        }
        
        await refreshRepeater();
    } catch (error) {
        console.error("Error in initialization:", error);
    }

    $w('#stateDropdown').onChange(async (event) => {
        await populateLakeData(event.target.value);
        await refreshRepeater();
    });

    $w('#lakeDropdown').onChange(() => {
        refreshRepeater();
    });
});

async function populateStateData() {
    try {
        const results = await wixData.query("Import791")
            .ascending("state")
            .limit(1000)
            .find();
        const uniqueTitles = getUniqueItems(results.items, "state");
        $w("#stateDropdown").options = buildOptions(uniqueTitles);
    } catch (error) {
        console.error("Error populating states:", error);
        throw error;
    }
}

async function populateLakeData(state) {
    try {
        const results = await wixData.query("Import791")
            .ascending("lakeName")
            .limit(1000)
            .eq("state", state)
            .find();
        const uniqueTitles = getUniqueItems(results.items, "lakeName");
        $w("#lakeDropdown").options = buildOptions(uniqueTitles);
    } catch (error) {
        console.error("Error populating lakes:", error);
        throw error;
    }
}

function getUniqueItems(items, property) {
    const uniques = items.map(item => item[property]);
    return [...new Set(uniques)];
}

function buildOptions(uniqueList) {
    return uniqueList.map(curr => {
        return { label: curr, value: curr };
    });
}

async function refreshRepeater() {
    const selectedState = $w('#stateDropdown').value;
    const selectedLake = $w('#lakeDropdown').value;
    
    let query = wixData.query("Import791");
    
    if (selectedState) {
        query = query.eq("state", selectedState);
    }
    
    if (selectedLake) {
        query = query.eq("lakeName", selectedLake);
    }
    
    try {
        const results = await query.find();
        $w("#listRepeater").data = results.items;
    } catch (error) {
        console.error("Error refreshing repeater:", error);
    }
}

I’ve been working with Claude AI to try to figure this out; however, the program keeps adding code that doesn’t work with my version and I’m already up to 50 questions with Claude:(

ThreeJS how to get the Y value off a spline curve from the X value. Not based on the path however

I’m trying to use a spline curve to make a graph and then reference a Y value based on a given X value. I can get x and y based on where I am on the curve based on the position (length) I’m on the curve shown in the last line of the code here. But this isn’t accurate. What I want is to give an X value to get the Y value from the curve. Is this possible?

const curveEnergy = new THREE.SplineCurve( [
    new THREE.Vector2( 405, 100 ),
    new THREE.Vector2( 450, 50 ),
    new THREE.Vector2( 500, 75 ),
    new THREE.Vector2( 550, 100 ),
    new THREE.Vector2( 600, 0 ),
    new THREE.Vector2( 650, 100 ),
    new THREE.Vector2( 700, 50 ),
    new THREE.Vector2( 750, 25 ),
    new THREE.Vector2( 800, 0 ),
    new THREE.Vector2( 850, 25 ),
    new THREE.Vector2( 900, 250 ),
    new THREE.Vector2( 950, 25 ),
    new THREE.Vector2( 1064, 0 )
 ]);
const pointsEnergy = curveEnergy.getPoints( 1064-405 );  //100 represents the kHz I'll be calculating to give me the Average Power
const geometryEnergy = new THREE.BufferGeometry().setFromPoints( pointsEnergy );
const material = new THREE.LineBasicMaterial( { color: 0xffffff } );
const splineEnergy = new THREE.Line( geometryEnergy, material );
scene.add(splineEnergy);

console.log(pointsEnergy[1064].x); 

Why does build fail after attempting to create a development build after installing sentry for expo app?

⚠️  ld: ignoring duplicate libraries: '-lc++'

› Generating debug somaticsFrontend » somaticsFrontend.app.dSYM
› Executing somaticsFrontend » Bundle React Native code and images
Bundler cache is empty, rebuilding (this may take a minute)

❌ error: Auth token is required for this request. Please run sentry-cli login and try again!

⚠️ Script has ambiguous dependencies causing it to run on every build.
To fix, go to: Xcode » somaticsFrontend/somaticsFrontend » Build Phases » ‘Upload Debug Symbols to Sentry’
Either: Uncheck “Based on dependency analysis”, or select output files to trigger the script
▸ ** ARCHIVE FAILED **
▸ The following build commands failed:
▸ PhaseScriptExecution Bundle React Native code and images /Users/expo/Library/Developer/Xcode/DerivedData/somaticsFrontend-dgdupxvzovrlqbajsudymjphqwdc/Build/Intermediates.noindex/ArchiveIntermediates/somaticsFrontend/IntermediateBuildFilesPath/somaticsFrontend.build/Release-iphoneos/somaticsFrontend.build/Script-00DD1BFF1BD5951E006B06BC.sh (in target ‘somaticsFrontend’ from project ‘somaticsFrontend’)
▸ (1 failure)
** ARCHIVE FAILED **
The following build commands failed:
PhaseScriptExecution Bundle React Native code and images /Users/expo/Library/Developer/Xcode/DerivedData/somaticsFrontend-dgdupxvzovrlqbajsudymjphqwdc/Build/Intermediates.noindex/ArchiveIntermediates/somaticsFrontend/IntermediateBuildFilesPath/somaticsFrontend.build/Release-iphoneos/somaticsFrontend.build/Script-00DD1BFF1BD5951E006B06BC.sh (in target ‘somaticsFrontend’ from project ‘somaticsFrontend’)
(1 failure)
Exit status: 65

HTML and Javascript: Clock number orbit animation is lagging after 1s

First time poster (please be gentle)

Using HTML/Javascript canvas I have drawn the 12 numbers of the clock face, and I am now making them rotate in a circle, like orbiting planets. The code is silky smooth for about 0.5 seconds with console.log showing 7ms interval between logs, but then it slows until it logs at 30ms intervals after just two rotations, with further lag beyond this. I have also tried with setTimeout and setInterval but I can’t figure out how to stop this lag and get a consistent timing.

Thank you <3

HTML:
<canvas id="clock" width="400px" height="400px"></canvas>

const clk = document.getElementById("clock").getContext("2d");

clk.font = "20px Arial";
clk.strokeStyle = "black";
clk.textAlign = "center";

let rotationCounter = 0;       // increment rotation for each function call

function drawNumbers() {
    clk.clearRect(0, 0, 400, 400);      // draw the clock base
    clk.fillStyle = "lightgrey";
    clk.arc(200, 200, 180, 0, Math.PI * 2);
    clk.fill();

    clk.fillStyle = "black";
    clk.translate(200, 200);       // set origin to center, for drawing numbers
        
                                        // draw the 12 numbers
    for (let i = 1; i < 13; i++) {
        let ang = (i * 30) + rotationCounter;
        clk.rotate((ang * Math.PI) / 180);    
        clk.translate(0, -150);                 
        clk.rotate((-ang * Math.PI) / 180)       
        clk.fillText(i.toString(), 0, 0);        
        clk.rotate((ang * Math.PI) / 180)
        clk.translate(0, 150);
        clk.rotate((-ang * Math.PI) / 180);

    }

    clk.translate(-200, -200);      // return canvas to original position

    rotationCounter += 1;

    if (rotationCounter >= 720) {
        return;                         // escape
    }

    window.requestAnimationFrame(drawNumbers);

}

window.requestAnimationFrame(drawNumbers);      // initialise

what does “Uncaught ReferenceError: createCookie is not defined,” mean?

On my website, when I press the submit button it spits back this error “Uncaught ReferenceError: createCookie is not defined” at line 61, what do I do to fix it? for context,
this is the full HTML script:

gggggggg.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Mestre de Inglês - Curso Completo</title>
</head>
<body>
  <h1 align=center style="height: 20px;">Mestre de Inglês - Curso Completo</h1>
  <h2 align=center style="height: 25px;">Simples, Facil, e Grátis</h2>
  <h1 align=center style="height: 75px;">Aprenda Inglês dentro de um ano</h1>
  
  <div>
    <div>
      <h2 align=center style="height: 20px;">Aplicar para participação</h2>
    </div>
    <div>
      <h3 align=center style="height: 10px;">Email</h2>
    </div>
    
    <Email>
      <div style="height: 10px; display: flex; flex-direction: row; align-items: center; justify-content: center;">
        <input type="email" name="Email" id="Email" autocomplete="on">
      </div>
    </Email>

    <div>
      <h3 align=center style="height: 10px;">Username</h2>
    </div>

    <Username>
      <div style="height: 10px; display: flex; flex-direction: row; align-items: center; justify-content: center;">
        <input type="text" name="Username" id="Username" maxlength="20" minlength="5" autocomplete="on">
      </div>
    </Username>
    
    <div>
      <h3 align=center style="height: 10px;">Password</h2>
    </div>

    <Password>
      <div style="height: 10px; display: flex; flex-direction: row; align-items: center; justify-content: center;">
        <input type="text" name="Pass" id="Password" maxlength="20" minlength="5">
      </div>
    </Password>
    
    <div>
      <h3 align=center style="height: 10px;">Skill Level</h2>
    </div>

    <Skill style="height: 10px; display: flex; flex-direction: row; align-items: center; justify-content: center;">
      <select name="Skill Level" id="Skill">
      <option value="Noob">Noob</option>
      <option value="Beginner">Beginner</option>
      <option value="Intermidiate">Intermidiate</option>
    </select>
    </Skill>
    
    <Button>
      <div style="display: flex; flex-direction: row; align-items: center; justify-content: center;">
        <input type="button" onclick="createCookie()" value="submit">
      </div>
    </Button>
    
    
  </div>
    
</body>
</html>

this is the script responsible for user login and cookies
gggggggg.js

function createCookie(email,username,pwd,skill){
    let email = document.getElementById("Email");
    let username = document.getElementById("Username");
    let pwd = document.getElementById("Password");
    let skill = document.getElementById("Skill");
  
  
    today = new Date();
    var expire = new Date();
    expire.setTime(today.getTime() + 3600000*24*15);
   
  
    document.cookie = "email="+encodeURI(email.value)+";path=/" + ";expires="+expire.toUTCString();
    document.cookie = "username="+username.value+";path=/" + ";expires="+expire.toUTCString();
    document.cookie = "password="+encodeURI(pwd.value)+";path=/" + ";expires="+expire.toUTCString();
    document.cookie = "skill="+skill.value+";path=/" + ";expires="+expire.toUTCString();
    //can only write one entity at a time (name, pass, skill)
  }  
  
  
  //event handler for page load - runs on every refresh
  window.onload = function(){
  
    document.getElementById('Username').value = uname;
    document.getElementById('Password').value = pass;
    document.getElementById('Skill').value = skill;
    
    console.log(email,username,pwd,skill)
  }

I used a truck load of research for the html and copy-pasted an answer I found here with some edits for the javascript, but when I press the submit button I get back an error saying the function is undefined, any help would be appreciated

i didnt really try much, I emmidiately thought “I should go to stack overflow”

Next.js (React) Component Filter table results without re-rendering input

I have a Next.js client component which shows a data table and has a search bar which can be used to filter the table. The issue is that whenever I type in the search bar, it causes the whole component to re-render, which means the search loses focus and interrupts typing. I have the search debounced but it still has an effect for longer queries.

'use client'

import { useEffect, useState } from "react";
import { PartsTable as PartsRow } from "@/app/lib/definitions";
import PartsTable from "@/app/ui/parts/table";
import NoQueryParamSearch from "../no-query-param-search";

export default function PartSearch({
    onPartSelected
}: {
    onPartSelected?: any
}) {
    const [parts, setParts] = useState([] as PartsRow[]);
    const [search, setSearch] = useState('');
    useEffect(() => {
        fetch(`/api/parts?query=${search}`).then(async (response) => {
            const parts = await response.json();
            setParts(parts);
        });
    }, [search]);
    const handlePartRowClicked = (part: any) => {
        onPartSelected(part);
    }
    const handleQueryChanged = (query: string) => {
        setSearch(query);
    }
    return (
        <div>
            <NoQueryParamSearch placeholder="Search ID, description, year, etc..." onChange={handleQueryChanged} />
            <div className="border border-solid border-gray-200 rounded-md my-2">
                <PartsTable parts={parts.slice(0, 5)} onRowClick={handlePartRowClicked} disableControls />
            </div>
        </div>
    );
}
'use client';

import { MagnifyingGlassIcon } from '@heroicons/react/24/outline';
import { useDebouncedCallback } from 'use-debounce';

export default function NoQueryParamSearch({ placeholder, onChange, autoComplete = true }: { placeholder: string, onChange: any, autoComplete?: boolean }) {

    const handleSearch = useDebouncedCallback((term) => {
        onChange(term);
    }, 300);

    return (
        <div className="relative flex flex-shrink-0">
            <label htmlFor="search" className="sr-only">
                Search
            </label>
            <input
                className="peer block w-96 rounded-md border border-gray-200 py-[9px] pl-10 text-sm outline-2 placeholder:text-gray-500"
                placeholder={placeholder}
                onChange={(e) => {
                    handleSearch(e.target.value);
                }}
                autoComplete={autoComplete ? undefined : 'off'}
                autoCorrect={autoComplete ? undefined : 'off'}
            />
            <MagnifyingGlassIcon className="absolute left-3 top-1/2 h-[18px] w-[18px] -translate-y-1/2 text-gray-500 peer-focus:text-gray-900" />
        </div>
    );
}

This needs to be a client component because of onPartSelected. When a row is selected it needs to send that to the parent component.

How can I update this app script to send SMS from rotating Twilio phone numbers?

Currently, I have app script that texts a column of phone numbers, “PHONE_NUMBER” from 1 Twilio number,+18778516645.

I would like to update this apps script to send from a column of Twilio Phone Numbers on a rotating basis. The “Send From” phone number is in column B. The “Send To” phone number is in Column C. The “Send To” number is already implemented in the script. How do I implement the “Send From” numbers?

Also is it necessary to implement a “pause” after ‘X’ messages to respect rate limits? Or would Twilio account for this already? If I should add a pause, how do I add Utilities.Sleep()?

Finally, I would like the script to start with a message box that reminds me of several “checks” to be completed. If I click “yes”, the the script runs. If “no”, then the script is cancelled. How can I do this?

I’m just getting started in coding. Sorry if this is not a great question. Thank you for your help!

// Spreadsheet column names mapped to 0-based index numbers.
var TIME_ENTERED = 0;
var PHONE_NUMBER = 1;
var MESSAGE = 2;
var STATUS = 3;

// Enter your Twilio account information here.
var TWILIO_ACCOUNT_SID = '';
var TWILIO_SMS_NUMBER = '+18778516645';
var TWILIO_AUTH_TOKEN = '';

/**
 * Installs a trigger in the Spreadsheet to run upon the Sheet being opened.
 * To learn more about triggers read: https://developers.google.com/apps-script/guides/triggers
 */
function onOpen1() {
  // To learn about custom menus, please read:
  // https://developers.google.com/apps-script/guides/menus
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('Send SMS')
      .addItem('Send to all', 'sendSmsToAll')
      .addToUi();
};  

function onOpen() {
  // To learn about custom menus, please read:
  // https://developers.google.com/apps-script/guides/menus
  var ui = SpreadsheetApp.getUi();
  ui.createMenu('GetReplies')
      .addItem('GetReplies', 'GetReplies')
      .addToUi();
};  

/**
 * Sends text messages listed in the Google Sheet
 *
 */
function sendSmsToAll() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange().getValues();
  
  // The `shift` method removes the first row and saves it into `headers`.
  var headers = rows.shift();
  
  // Try to send an SMS to every row and save their status.
  rows.forEach(function(row) {
    row[STATUS] = sendSms(row[PHONE_NUMBER], row[MESSAGE]);
  });
  
  // Write the entire data back into the sheet.
  sheet.getRange(2, 1, rows.length, headers.length).setValues(rows);
}


/**
 * Sends a message to a given phone number via SMS through Twilio.
 * To learn more about sending an SMS via Twilio and Sheets: 
 * https://www.twilio.com/blog/2016/02/send-sms-from-a-google-spreadsheet.html
 *
 * @param {number} phoneNumber - phone number to send SMS to.
 * @param {string} message - text to send via SMS.
 * @return {string} status of SMS sent (successful sent date or error encountered).
 */
function sendSms(phoneNumber, message) {
  var twilioUrl = 'https://api.twilio.com/2010-04-01/Accounts/' + TWILIO_ACCOUNT_SID + '/Messages.json';

  try {
    UrlFetchApp.fetch(twilioUrl, {
      method: 'post',
      headers: {
        Authorization: 'Basic ' + Utilities.base64Encode(TWILIO_AUTH_TOKEN)
      },
      payload: {
        To: phoneNumber.toString(),
        Body: message,
        From: TWILIO_SMS_NUMBER,
      },
    });
    return 'sent: ' + new Date();
  } catch (err) {
    return 'error: ' + err;
  }
}

How to make the same request multiple times?

I have to make an API request to an endpoint and see if it returns a specific object. How can I make the same API request multiple times over a 60 second period until it returns that object using playwright? Here’s what I tried

await this.page.waitForResponse(
    async resp =>
        resp.url().includes("test") &&
        resp.status() === 200 &&
        ((await resp.json()) as any).libraries.some((lib: { name: string }) => lib.name === libraryName),
        {
            timeout: 60000
        }
);

But I am pretty sure it doesn’t make the same request multiple times

Persist dark mode in Nuxt 3

I use useDark from VueUse to implement the dark mode. When I go to another route the dark mode doesn’t persist, possibly due to SSR, since the server doesn’t know about the current mode.

I tried to solve the issue by using useCookie to store the mode in cookie, but it doesn’t seem to work:

const darkModeCookie = useCookie("dark-mode", {
  path: "/",
  sameSite: "lax",
});

const isDark = useDark({ disableTransition: false });
const toggleDark = useToggle(isDark, () => {
  darkModeCookie.value = isDark.value ? "true" : "false";
});

if (darkModeCookie.value === true) {
  isDark.value = true;
} else {
  isDark.value = false;
}

I’m looking for a possible solution.