Destructure object, remove array when passing to component

I would like to pass the paging data to my component without passing the docs array.

   "docs": [
       
    ],
    "totalDocs": 18,
    "offset": 0,
    "limit": 10,
    "totalPages": 2,
    "page": 1,
    "pagingCounter": 1,
    "hasPrevPage": false,
    "hasNextPage": true,
    "prevPage": null,
    "nextPage": 2

I am setting the state from my axios get:

const queryFunction = async () => {
  setLoading(true)
  axios(configFetch)
  .then(res => {

   
    setData(res.data); // update state with response
  
  })

However, I am passing all of the data to my component, how can I just pass the paging data without the docs array?

 <Pager
{...data}
    
 />

Issue where adding new elements to the top of container pushes the viewport down (scrolls the page down)

I have this code where I have a container that I’m dynamically adding new elements to the top of the container (Like news comming in from the top).
The issue is that when the viewport is scrolled down slightly it is pushed down each time e new element is added – And i would really like for that not to happen.

Here is a very simplified version of the code:

HTML

<div class="container">
   <div id="newelementwrapper">
   </div>
</div>

CSS

body{
      min-height:2000px;
    }
    .container {
      height: 500px;
      width: 100%;
      overflow: hidden;
      background-color: green;
    }
    
    #newelementwrapper {
      height: 100%;
      overflow-y: scroll;
    }
    
    .element {
      height: 100px;
      background-color: red;
      width: 400px;
      margin: 20px;
    }

JS:

// Returns a Promise that resolves after "ms" Milliseconds
    const bubblesContainer = document.getElementById("newelementwrapper")
    
    const timer = ms => new Promise(res => setTimeout(res, ms))

    //Creates and ads the bubbles from data and calls map functions width dealy specified by the timer
    async function addBubbles () {
        for (let i = 0; i < 100; i++) {
            //Create bubble
            const bubble = '<div class="element">Element</div>'
            //Insert bubble
            bubblesContainer.insertAdjacentHTML('afterbegin',bubble);
            //Delay
            await timer(1500);
        }
    }
    
    addBubbles()

Here is a fiddle with the same example:
https://jsfiddle.net/cpzbmh79/2/

You need to scroll down a bit for the issue to appear.

How to Export Import Component On React Js

I’m just learning laravel & react js.
I tried to make project laravel + react js. I want to ask how to export component TextInput (className) to my Login page.

TextInput.jsx script :

import { forwardRef, useEffect, useRef } from "react";

export default forwardRef(function TextInput(
    { type = "text", className, isFocused = false, ...props },
    ref
) {
    const input = ref ? ref : useRef();

    useEffect(() => {
        if (isFocused) {
            input.current.focus();
        }
    }, []);

    return (
        <input
            {...props}
            type={type}
            className={
                "rounded-2xl bg-form-bg py-[13px] px-7 w-full focus:outline-alerange focus:outline-none"
            }
            ref={input}
        />
    );
});

Login.jsx script :

import React from "react";
import TextInput from "@/Components/TextInput";

export default function Login() {
    return (
        <div className="mx-auto max-w-screen min-h-screen bg-black text-white md:px-10 px-3">
            <div className="fixed top-[-50px] hidden lg:block">
                <img
                    src="/images/signup-image.png"
                    className="hidden laptopLg:block laptopLg:max-w-[450px] laptopXl:max-w-[640px]"
                    alt=""
                />
            </div>
            <div className="py-24 flex laptopLg:ml-[680px] laptopXl:ml-[870px]">
                <div>
                    <img src="/images/moonton-white.svg" alt="" />
                    <div className="my-[70px]">
                        <div className="font-semibold text-[26px] mb-3">
                            Welcome Back
                        </div>
                        <p className="text-base text-[#767676] leading-7">
                            Explore our new movies and get <br />
                            the better insight for your life
                        </p>
                    </div>
                    <form className="w-[370px]">
                        <div className="flex flex-col gap-6">
                            <div>
                                <label className="text-base block mb-2">
                                    Email Address
                                </label>
                                <input
                                    type="email"
                                    name="email"
                                    placeholder="Email Address"
                                />
                            </div>
                            <div>
                                <label className="text-base block mb-2">
                                    Password
                                </label>
                                <input
                                    type="password"
                                    name="password"
                                    placeholder="Password"
                                />
                            </div>
                        </div>
                        <div className="grid space-y-[14px] mt-[30px]">
                            <a
                                href="/"
                                className="rounded-2xl bg-alerange py-[13px] text-center"
                            >
                                <span className="text-base font-semibold">
                                    Start Watching
                                </span>
                            </a>
                            <a
                                href="sign_up.html"
                                className="rounded-2xl border border-white py-[13px] text-center"
                            >
                                <span className="text-base text-white">
                                    Create New Account
                                </span>
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    );
}

i want to replace className (email & password) from component/TextInput.jsx to pages/Login.jsx.

On this project i using laravel 10

Test is failing in Detox when the layout is overlayed

I get the following error in Detox when the test clicks on a button, the click works but after the component re-renders because of a state change, the test strangely wants to click on the button again but since the button is not in the view, the test fails.

Test Failed: Wait for
[com.wix.detox.reactnative.idlingresources.AnimatedModuleIdlingResource]
to become idle timed out

My test script:

await element(by.id("post-1-cm")).tap();

await waitFor(element(by.id("comment-error")))
  .not.toExist()
  .withTimeout(5000);

The Button component:

<AppButton
          onPress={() => toggleComments(true)}
          disabled={disabled || submitting}
          inverted
          testID={`${testID}-cm`}
          buttonStyles={styles.button}>

Code of the component that gets rendered when the button is clicked and toggleComments changes the showComments state to True:

  {showComments && (
    <CommentsModal
      reloadPosts={props.reload}
      visible={showComments}
      blockUser={blockUser}
      close={() => toggleComments(false)}
    />
  )}

How to convert Observable radial chart code to plain Javascript?

I am trying to convert observable notebook (https://observablehq.com/@d3/radial-area-chart) to vanilla Javascript using d3 SVG elements. You can find the ‘sfo-temperature.csv’ by clicking on paper clip symbol on the link above.

I am still beginner in HTML, JS and D3. I am stuck in an error. I would appreciate any alternative solutions as well. Below, you can find my attempt.

Here is my index.HTML file:

<html>
  <head>
    <script src="https://d3js.org/d3.v6.min.js"></script>
    <script src="d3Chart.js"></script>
    <!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
  </head>
  <body>
    <div id="chart-container"></div>
    <div class="container"></div>
    <script>

            // Call the drawChart function with the container and data
      const container = d3.select("#chart-container");

      // Upload local CSV file
      d3.csv("sfo-temperature.csv").then(function(data) {
        drawChart('.container', data);
      });
      <!--drawChart('.container',data)-->
    </script>
  </body>
</html>

Here is my d3Chart.js file:

async function drawChart(container, data) {
    const rawdata = await d3.csv("sfo-temperature.csv");
    data = Array.from(d3.rollup(
        rawdata,
        v => ({
            date: new Date(Date.UTC(2000, v[0].DATE.getUTCMonth(), v[0].DATE.getUTCDate())),
            avg: d3.mean(v, d => d.TAVG || NaN),
            min: d3.mean(v, d => d.TMIN || NaN),
            max: d3.mean(v, d => d.TMAX || NaN),
            minmin: d3.min(v, d => d.TMIN || NaN),
            maxmax: d3.max(v, d => d.TMAX || NaN)
        }),
        d => `${d.DATE.getUTCMonth()}-${d.DATE.getUTCDate()}`
    ).values())
        .sort((a, b) => d3.ascending(a.date, b.date))

    const width = 954;
    const height = width;
    const margin = 10;
    const innerRadius = width / 5;
    const outerRadius = width / 2 - margin;

    const x = d3.scaleUtc()
        .domain([Date.UTC(2000, 0, 1), Date.UTC(2001, 0, 1) - 1])
        .range([0, 2 * Math.PI]);

    const y = d3.scaleLinear()
        .domain([d3.min(data, d => d.minmin), d3.max(data, d => d.maxmax)])
        .range([innerRadius, outerRadius]);

    const xAxis = g => g
        .attr("font-family", "sans-serif")
        .attr("font-size", 10)
        .call(g => g.selectAll("g")
            .data(x.ticks())
            .join("g")
            .each((d, i) => d.id = DOM.uid("month"))
            .call(g => g.append("path")
                .attr("stroke", "#000")
                .attr("stroke-opacity", 0.2)
                .attr("d", d => `
              M${d3.pointRadial(x(d), innerRadius)}
              L${d3.pointRadial(x(d), outerRadius)}
            `))
            .call(g => g.append("path")
                .attr("id", d => d.id.id)
                .datum(d => [d, d3.utcMonth.offset(d, 1)])
                .attr("fill", "none")
                .attr("d", ([a, b]) => `
              M${d3.pointRadial(x(a), innerRadius)}
              A${innerRadius},${innerRadius} 0,0,1 ${d3.pointRadial(x(b), innerRadius)}
            `))
            .call(g => g.append("text")
                .append("textPath")
                .attr("startOffset", 6)
                .attr("xlink:href", d => d.id.href)
                .text(d3.utcFormat("%B"))));

    const yAxis = g => g
        .attr("text-anchor", "middle")
        .attr("font-family", "sans-serif")
        .attr("font-size", 10)
        .call(g => g.selectAll("g")
            .data(y.ticks().reverse())
            .join("g")
            .attr("fill", "none")
            .call(g => g.append("circle")
                .attr("stroke", "#000")
                .attr("stroke-opacity", 0.2)
                .attr("r", y))
            .call(g => g.append("text")
                .attr("y", d => -y(d))
                .attr("dy", "0.35em")
                .attr("stroke", "#fff")
                .attr("stroke-width", 5)
                .text(y.tickFormat(5, "f")))
            .call(g => g.append("text")
                .attr("y", d => -y(d))
                .attr("dy", "0.35em")
                .text(y.tickFormat(5, "f"))));

    const line = d3.lineRadial()
        .angle(d => x(d.date))
        .radius(d => y(d.avg));

    const svg = d3.select(container)
        .append("svg")
        .attr("viewBox", [-width / 2, -height / 2, width, height])
        .attr("font-family", "sans-serif")
        .attr("font-size", 12)
        .attr("text-anchor", "middle");

    svg.append("g")
        .attr("fill", "none")
        .attr("stroke-opacity", 0.6)
        .selectAll("path")
        .data(data)
        .join("path")
        .style("mix-blend-mode", "multiply")
        .attr("stroke", "steelblue")
        .attr("d", d => line(d.values));

    svg.append("g")
        .call(xAxis);

    svg.append("g")
        .call(yAxis);

    svg.append("g")
        .selectAll("g")
        .data(data)
        .join("g")
        .attr("transform", d => `
          rotate(${((x(d.date) + x(d3.utcMonth.offset(d.date, 1))) / 2 * 180 / Math.PI - 90)})
          translate(${innerRadius},0)
        `)
        .append("line")
        .attr("x2", -5)
        .attr("stroke", "#000");

    svg.append("g")
        .selectAll("g")
        .data(data)
        .join("g")
        .attr("transform", d => `
          rotate(${((x(d.date) + x(d3.utcMonth.offset(d.date, 1))) / 2 * 180 / Math.PI - 90)})
          translate(${outerRadius},0)
        `)
        .append("line")
        .attr("x2", 5)
        .attr("stroke", "#000");
}

When I run my code, I encounter the following error: Uncaught (in promise) TypeError: d.DATE.getUTCMonth is not a function I tried replacing d.DATE.getUTCMonth with d.getUTCMonth, however, it still did not work. How should I modify my code so that I can create the radial area chart deined on obsrvable run using vanilla JS and d3 SVG elements?

DragControls not working properly on smaller and bigger spheres

I’m working on a 3D project where I have several spheres of different sizes, and I’m using DragControls to allow users to drag and move the spheres around the screen. However, I’ve noticed some issues with the dragging behavior that I’m hoping to get some help with.

First, DragControls seems to work properly on regular sized spheres such as Venus, Earth, Mars, Uranus, and Neptune. However, on larger spheres, the dragging only works if I set my mouse on their edges. I would like to make the dragging of the larger spheres easier, but I don’t want to change the radius of each sphere.

Second, I have a smaller sphere (Mercury) with a radius of 0.383, and DragControls doesn’t seem to register the drag event at all for this sphere.
I’ve tried using bigger/more segments on the spheres, grouping the body and mesh of the sphere into a THREE.Object3D(), and tweaking the draggingThreshold, but none of these approaches have worked.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <style>
        html,
  body {
    margin: 0;
    padding: 0;
    overflow: hidden;
  }
  canvas {
      position: fixed;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      display: block;
    }
  
    </style>
    <title>Vite App</title>
  </head>
  <body>
    <div id="app"></div>
    <script type="module">
      import * as THREE from 'https://cdn.skypack.dev/[email protected]/build/three.module.js';
import * as CANNON from 'https://cdn.skypack.dev/cannon-es@latest/dist/cannon-es.js';

import { DragControls } from 'https://cdn.skypack.dev/[email protected]/examples/jsm/controls/DragControls.js';

let planets = []
// Set up the scene
const scene = new THREE.Scene();
const camera = new THREE.OrthographicCamera(
    window.innerWidth / -21, // left
    window.innerWidth / 21, // right
    window.innerHeight / 21, // top
    window.innerHeight / -21, // bottom
    -130, // near
    14000 // far
  );
  
  camera.position.set(0, 0, 5);
  camera.lookAt(scene.position);
  
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

// Set up Cannon.js
const world = new CANNON.World();
world.gravity.set(0, 0, 0);



const light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(0, 0, 5);
scene.add(light);

// Function to create planet
function createPlanet(radius, mass, position, color) {
  const shape = new CANNON.Sphere(radius);
  const body = new CANNON.Body({ mass: mass, linearDamping: 0.5, angularDamping: 0.5 });

  
  body.addShape(shape);

  world.addBody(body);

  const geometry = new THREE.SphereGeometry(radius, 32, 32);
  const material = new THREE.MeshLambertMaterial({ color: color });
  const mesh = new THREE.Mesh(geometry, material);
  mesh.position.copy(position);
  scene.add(mesh);
  planets.push({mesh: mesh, body: body})
  return { shape, body, mesh };
}

console.log(planets)
// Create planets
const sun = createPlanet(109, 0, new THREE.Vector3(-125, 0, 0), 0xffff00);

const mercury = createPlanet(0.383, 0, new THREE.Vector3(-15.5, 0, 15), '#A9A9A9');

const venus = createPlanet(0.72, 0, new THREE.Vector3(-13.2, 0, 0), 0xffa500);

const earth = createPlanet(1, 0, new THREE.Vector3(-10.4, 0, 0), 'blue');

const mars = createPlanet(0.532, 0, new THREE.Vector3(-7, 0, 0), 'red');

const jupiter = createPlanet(11.21, 0, new THREE.Vector3(7, 0, 0), 'orange');

const saturn = createPlanet(9.45, 0, new THREE.Vector3(30, 0, 0), 'pink');

const uranus = createPlanet(4.01, 0, new THREE.Vector3(45.8, 0, 0), 'green');

const neptune = createPlanet(3.88, 0, new THREE.Vector3(55.9, 0, 0), 'orange');

let dragControls = new DragControls(planets.map(planet => planet.mesh), camera, renderer.domElement);
dragControls.draggingThreshold = 0.1;





function render() {
  requestAnimationFrame(render);

  // Update physics
  world.step(1 / 60);


  renderer.render(scene, camera);
}

// Start the render loop
render();

    </script>

  </body>
</html>

Can anyone suggest how I can make the dragging for the smaller sphere work and make the dragging of the larger spheres easier without changing the radius of each sphere? Any help would be greatly appreciated. Thanks in advance!

how to get access to window object of current website in chrome extension

I’m working on a browser extension that needs access to the “login” key from the “window” object of the active tab.

There is my manifeset.json

 {...}
"permissions": [
    "activeTab",
    "storage",
    "scripting",
    "tabs"
  ],
  "background": {
    "service_worker": "background.js",
    "type": "module"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ],

Additional I have popup.js attached to popup.html, and I need to have window.login in that file.
Currently everytime when I tried to get access to window, there is a window before all react loaded so there is almost empty window. I used window.onload and it didn’t work,

Exception java.lang.RuntimeException ERROR APP CRASHING ON GOOGLE PLAY

My app works on test device but crashes on playstore with this ERROR:

Exception java.lang.RuntimeException:
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:4048)
  at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:4312)
  at android.app.servertransaction.LaunchActivityItem.execute (LaunchActivityItem.java:101)
  at android.app.servertransaction.TransactionExecutor.executeCallbacks (TransactionExecutor.java:135)
  at android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:95)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:2571)
  at android.os.Handler.dispatchMessage (Handler.java:106)
  at android.os.Looper.loopOnce (Looper.java:226)
  at android.os.Looper.loop (Looper.java:313)
  at android.app.ActivityThread.main (ActivityThread.java:8741)
  at java.lang.reflect.Method.invoke
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:571)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1067)
Caused by java.lang.ClassNotFoundException:
  at dalvik.system.BaseDexClassLoader.findClass (BaseDexClassLoader.java:259)
  at java.lang.ClassLoader.loadClass (ClassLoader.java:379)
  at java.lang.ClassLoader.loadClass (ClassLoader.java:312)
  at android.app.AppComponentFactory.instantiateActivity (AppComponentFactory.java:95)
  at androidx.core.app.CoreComponentFactory.instantiateActivity (CoreComponentFactory.java:45)
  at android.app.Instrumentation.newActivity (Instrumentation.java:1328)
  at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:4035)

I thought it might have something to do with proguard so I tried disabling it by creating a proguaurd-rules.pro file in platform>android>app so the app file contains the proguard-rules.pro. I honestly copied and pasted it there from another project so maybe this has caused an issue but I didn’t think it would.

After I added that file I went in to the build.gradle and added this code:

            release {
                signingConfig signingConfigs.release
                minifyEnabled true
                proguardFiles 'proguard-rules.pro'
            }
            debug {
                minifyEnabled false
                proguardFiles 'proguard-rules.pro'
            }
        }

That did nothing for the crash so I went back and changed the code to this:

            release {
                signingConfig signingConfigs.release
                minifyEnabled false
                useproguard false
                proguardFiles 'proguard-rules.pro'
            }
            debug {
                minifyEnabled false
                useproguard false
                proguardFiles 'proguard-rules.pro'
            }
        }

the crashes are still occurring and I am still getting the same error message on the play console, what am I doing wrong? Is this even a proguard issue or maybe something else?

Thank you.

How to perform unit testing on function invoked by event using Jest in React project

component.js

    import {React,useState} from 'React'
    import Container from 'react-bootstrap/Container'
    import Row from 'react-bootstrap/Row'
    import Col from 'react-bootstrap/Col'
    import Form from 'react-bootstrap/Form'
    import DatePicker from 'react-datepicker'
    import Row from 'react-bootstrap/Row'
    ...
    ...
    function Details (){
    const[initialDate, setInitialDate] = useState(new Date());
    ...
    ...
    
    return(
    <DatePicker test-id="dPicker" selected = {initialDate} onChange={(date) => setInitialDate(date)}
    )
    }

I wanted to unit test the onchange function code for above datepicker using Jest . What piece of code will help me?

How to adjust the schema of a child based on a siblings child with `yup`?

I have the following yup schema:

const schema = y.object({
  foo: y.object({
    label: y.string().required(),
    value: y.boolean().required(),
  }),
  bar: y.object({
    label: y.string().required(),
    value: y.number().positive())
  }),
});

How can I make bar.value required when foo.value is true, and bar.value not required and stripped away when foo.value is false?


I’ve found I can use when with dot-notation, but I have to use it on bar, not bar.value, to access the sibling foo, and I don’t know how to adjust a “sub-schema”, and haven’t been able to find any examples of this from searching or in the yup docs either.

const schema = y.object({
  foo: y.object({
    label: y.string().required(),
    value: y.boolean().required(),
  }),
  bar: y.object({
    label: y.string().required(),
    value: y.number().positive())
  }).when('foo.value', {
    is: true,
    /**
     * Here `schema` is the object-schema for `bar`, but how do I
     * adjust/change one of its "child"-schemas, in this case the `value` one?
     */
    then: (schema) => schema.???.required(),
    otherwise: (schema) => schema.???.notRequired().strip(),
  }),
});

HTML/CSS/JS Multiple pages of HTML in one file

I’m fairly new to HTML/CSS/JS (about 3 months now). I’m currently trying to create an e-commerce website but i’m having an issue with my products page. Whenever you click a product, It’s supposed to take you to a product details page showing things such as the name, price, a picture, and an add to cart button. I have a quite a few products (~25 products) so it wouldn’t be Ideal to create a .html file for every single product. So i wanted to know if it was possible to have all the product pages in one HTML file.

<div class="small-container single-product">
                <div class="row">
                    <div class="col-2 col-6" id="gpu1">
                        <img src="Images/strix3080.png" width="70%">
                    </div>
                    <div class="col-2 col-6" id="gpu1">
                        <p>Home / Products / ROG STRIX GeForce RTX 3080</p>
                        <h1>ASUS ROG STRIX GeForce RTX 3080 V2 10GB</h1>
                        <h4>&euro;800.00</h4>
                        <input type="number" value="1" max="5">
                        <a href="" class="btn add-cart">Add To Cart</a>
                        <h3>Specifications<i class="fa fa-indent" onclick="toggleSpecs()"></i></h3>
                        <br>
                        
                        <div id="specs">
                        <p>
                        Bus Standard: PCI Express 4.0<br>
                        Video Memory: 10GB GDDR6X<br>
                        Engine Clock: 1440 MHz (Base Clock)
                                      1935 MHz (Boost Clock)<br>
                        CUDA Core:    8704<br>
                        Memory Speed: 19 Gbps<br>
                        Interface:    Yes x2 (Native HDMI 2.1),
                                      Yes x3 (Native DisplayPort 1.4a),
                                      HDCP Support Yes (2.3)<br>
                        Resolution:   Digital Max Res. 7680 x 4320<br>
                        Dimensions:   12.53" x 5.51" x 2.27" Inch
                                      31.85 x 14.01 x 5.78 Centimeter<br>
                        Recommended PSU: 850W<br>
                        Power Connectors: 3 x 8-Pin
                        </p>
                        </div>
                    </div>
                </div>
            </div>

This is what contains all the details for the product details page and what is loaded when you click on a product’s picture.

This is how im making the picture clickable (This is in a seperate HTML file):

<div class="row">
                    <div onclick="window.location.href='product-details.html'" class="col-4">
                        <img src="Images/asus3080.png">
                        <h4>ASUS ROG STRIX GeForce RTX 3080 V2 10GB</h4>
                        <p>&euro;800.00</p>
                    </div>

I’ve tried looking up how to do this but most of them are to use plugins (which im not rlly sure how to use).

I would really appreciate some help.

Thank you.

Dropdown dynamic update list – apps script / javascript / googlesheet

https://i.stack.imgur.com/JRjue.jpg

Hi,
as a title,
I have on C:C 14 dropdowns menu with F:F list,
I create via Apps script

actlist = main.getRange('F10:F24')

let dropdownPosition = main.getRange(10,3,15)
dropdownAct = SpreadsheetApp.newDataValidation().requireValueInRange(actList).build();
dropdownPosition.setDataValidation(dropdownAct) ;

I’m a real beginner and my problem that I can’t solve is “how to remove/hide from the list the values already used in the previous dropdown, to avoid entering the same value twice

I tried to create two columns and using FILTER AND COUNTIF I was going to remove the values already used, but obviously the dropdown came back to me
“Invalid: Input must fall within specified range”
because the value was no longer included in the list

Is there a quicker system, perhaps in javascript / app script to solve this problem without errors?

Thanks in advance

actlist = main.getRange('F10:F24')

let dropdownPosition = main.getRange(10,3,15)
dropdownAct = SpreadsheetApp.newDataValidation().requireValueInRange(actList).build();
dropdownPosition.setDataValidation(dropdownAct) ;

I tried to create two columns and using FILTER AND COUNTIF I was going to remove the values already used, but obviously the dropdown came back to me
“Invalid: Input must fall within specified range”
because the value was no longer included in the list

It can’t receive Object ID

I have a problem with showing Object ID from MongoDB in the console in VS Code. I want to get ObjectID for the user , who is log in in the my application and I create input tag , which is hidden and with id = ObjectID .

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Car Rental</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
     <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="/style.css">
    <script src="https://code.jquery.com/jquery-3.6.4.js" integrity="sha256-a9jBBRygX1Bh5lt8GZjXDzyOB+bWve9EiO7tROUtj/E=" crossorigin="anonymous"></script>
    <script src="/socket.io/socket.io.js"></script>
    <script src="/script.js"></script>
</head>
<body>
    {{> navbar}}
    {{{body}}}
    <input type="hidden" id="ObjectID" value="{{user._id}}">
</body>
</html>

When I run the apllication and log in with user, in the console in the browser , I see that it gets ObjectId for current User.

Then I make a little code for this ObjectID in the file, where i connect socket.io. There I use ‘#ObjectID’ to find this ObjectID.

// connect Socket.io

$(document).ready(function(){
    var socket = io();

    // connect client to server
    socket.on('connect', function(socket){
        console.log('Connected to server');
    });

    // emit user id
    var ObjectID = $('#ObjectID')
    socket.emit('ObjectID', ObjectID);

    // disconnect from server
    socket.on('disconnect', function(socket){
        console.log('Disconnected from server');
    });
});

After that , I want to create Object ID event in server file “app.js” and I want to see this ObjectId in the console of Node.js .

// socket connection
const server = http.createServer(app);
const io = socketIO(server);
io.on('connection',(socket)=>{
    console.log('Connected to client');
    // listen to object ID event
    socket.on('ObjectIO',(ObjectID)=>{
        console.log('User ID is: ', ObjectID);
    });

    // listen to disconnection
    socket.on('disconnect',(socket)=>{
        console.log('Disconnected from Client');
    });
});

But after run the application and after log in a user , I don’t see in the console to print current ObjectID .

Please help me to fix this problem.

De Serialise Json Object to pass to JS function Interop from Blazor

I am using Blazor WASM and am wanting to accept payments using a JS drop-in from Adyen.
I have actually managed to make it work, see this question: My previous question

But to some extent I don’t understand why?.

A (what looks like good JSON) response comes back from the server. This was copied from the browser debug windown into a VSCode file and formatted:

{
"channel": 3,
"recurringProcessingModel": null,
"shopperInteraction": null,
"accountInfo": null,
"additionalAmount": null,
"additionalData": null,
"allowedPaymentMethods": null,
"amount": {
    "currency": "GBP",
    "value": 300
},
"applicationInfo": null,
"authenticationData": null,
"billingAddress": null,
"blockedPaymentMethods": null,
"captureDelayHours": null,
"company": null,
"countryCode": "GB",
"dateOfBirth": null,
"deliverAt": null,
"deliveryAddress": null,
"enableOneClick": null,
"enablePayOut": null,
"enableRecurring": null,
"expiresAt": "2023-04-17T11:28:00+01:00",
"id": "CS2387F156F0520AB5",
"lineItems": [
    {
        "amountExcludingTax": 0,
        "amountIncludingTax": 300,
        "description": "Site Credit",
        "id": null,
        "imageUrl": null,
        "itemCategory": null,
        "productUrl": null,
        "quantity": 1,
        "taxAmount": 0,
        "taxPercentage": 0
    }
],
"mandate": null,
"mcc": null,
"merchantAccount": "xxxxxxxxxxxxxxxx",
"merchantOrderReference": null,
"metadata": null,
"mpiData": null,
"recurringExpiry": null,
"recurringFrequency": null,
"redirectFromIssuerMethod": null,
"redirectToIssuerMethod": null,
"reference": "000000276",
"returnUrl": "yyyyyyyyyyyyyyyyyyyyyyyyyy",
"riskData": null,
"sessionData": "Ab02b4c0!BQABAgCZiH8XQ1HvzCtIGU56spUsUSSi6w21FzE3cIeiuAV6mQApaanuRgK2bg00m0NAwz53ZEyQbjHbuV1o7SF4BT5R2DqE1J4EM4Qm+Ma7MU5r+xg21ovnetvBzZpd3iGVH0mykv0uVLCD2bEP1oKgVqLnMuNxkYaSZtJYbMvo/fm4rCl1lJbL2A0AMcJPXXvk0rUZmVj1UaPgjjW9WW0mS1mur53RDEjh/ZFT1YaWTz9oKXh8Rf91xUJcQW6FNjVLjkto4UGNx718EeINTWCxR3Jhg2vD+qonDqBlmIEvfe1XBxI7x5nQoGdtPIhzb+N9q4HAPiyMRevTTFR3NfguhUDOoq6sFMNaFVRnhTCiW+Z7kwEuBbZbxcAbRNbtH1wxFVDQkANR2WG7vYo5FAvCY0PelElvwtIyQEQUXnKlpPUZ9ZMQF4j0kA5viXMm7WPuYK7KfIhIJWNi08+qHTP375OPV6hx+YyBw086KWuLm0DFqlNj3v1MxutG8O/5woC0+I4DUhRVH1yyYlvKGZ6X+/JDzzCuxOwJZqo4bljEswd4enQ/o0bThNh1lCLw5m0qajRsIpS0miu4pZaHHT7cmFsJ38cbaD2iXa1+RixF74aj6DcN2DzIWi5vdIIi4/jZ7tK6ndCmEwo+xLQEh27AtsMV45xfFE5Fd3L9YhtoQQRclgya2hdiq2XG6YFbeoIASnsia2V5IjoiQUYwQUFBMTAzQ0E1MzdFQUVEODdDMjRERDUzOTA5QjgwQTc4QTkyM0UzODIzRDY4REFDQzk0QjlGRjgzMDVEQyJ9o2b4ks1eNtAVAlIx/fdZWd65Jl36f6HbFsTK5LNMX2JKUdx3gWLtuIkJklKMlFm34/mFzn+55AK1/VFjIgatR9rK8xEnp60bS9yXZjpvjskcmVdAfZ9MiHlZC+NrngY30i73eRl4kg+zq039HNJ0lTcKIxNClOlkn/qrGuIU11hfYxHId5pnaV3oZB4N4Dkf2PJm1o5raY0jUdsuyYl3EzKjtyPk4T93DhtBZjQbKHgsOYL2UewWesPTsnx+0kt3+iVJEoZwWlhxDWiMrb/TIYSCZxmN6rIR1rIA8ZsxeOy62mir3xaywxGKnUlUKD6sC4+IwhDgBtYcxMh9ygx/7CynqBjJ3knhPDxCQxvT26MkT5AmRm++7fdEIdb2RbjOU8TPRwVGVRr+m+1GFhE+e3NhT9tRh/nKyxLVvH1G1MJ6jBq0cDxzrvtKJNHDt1oCdkBI9JIkYEzEKvc9tp0/nD7ZUbfhvfJm6EcJOezRzDO5+2aDlqoWsyjGncbPWd2qXGGFPfIkh/PpZAjbeWp17HzmjjBaox4luOUhnJxSkKSAmDdV5d40MgCkPkjsVmqBCPWG0Elutlw2EQSsr/P+HEoOUTrU4BQDkJlyXTpPn7RYEmXfQ+w3ueAwAgY5BlVCsyw00HgCbmacpe2KKfj8TJAI24wUF1XY9seKsQn3Z5TzVgPZm0lGV9Ju8IzOt2qf97iB20LfTTg4it0/Es4+yl9HK4mNEvfean1tEQPxDfO+Elhq69lygul4x1RKFINMnDtL5ejQ0hU=",
"shopperEmail": null,
"shopperIP": null,
"shopperLocale": "en-US",
"shopperName": null,
"shopperReference": null,
"shopperStatement": null,
"socialSecurityNumber": null,
"splitCardFundingSources": false,
"splits": null,
"store": null,
"storePaymentMethod": null,
"telephoneNumber": null,
"threeDSAuthenticationOnly": false,
"trustedShopper": null
}

From the previous question, I was desrialising this as ASCII and passing it in to my JS interop code as follows:

    ...
    Stream? jsonresponse = await response.Content.ReadAsStreamAsync();
    string res;
    using (var reader = new StreamReader(jsonresponse, Encoding.ASCII))
    {
        res = reader.ReadToEnd();
    }
    return res;

The calling function does this: (AdyenSession is a string, ObjRef is to allow the JS to callback)

    AdyenSession = await _transactionService.GetAdyenPaymentSessionAsync(_userService.CurrentUser.Id, amount);
    objRef = DotNetObjectReference.Create(this);
    await _JS.InvokeVoidAsync("setAdyenCheckoutConfiguration", AdyenSession, _transactionService.AdyenPublicClientKey, objRef);

For completeness, the JavaScript code starts with this:

var AdyenJsonObject;
var RawAdyenJsonObject;
var checkout;
var dropinComponent;

async function setAdyenCheckoutConfiguration(AdyenSessionResponse, passedKey, dotnethelper) {

console.log(AdyenSessionResponse);
RawAdyenJsonObject = AdyenSessionResponse;
AdyenJsonObject = JSON.parse(AdyenSessionResponse);
...

When I break at the JSON.parse line above, the value (again formatted in VSCode) is:

{
"environment": "test",
"clientKey": "test_AGQHLB7CRNA3BMHWPBIUOBNI4QZGVK6F",
"analytics": {
    "enabled": true
},
"session": {
    "id": "CS55FA4A6E3BD028CB",
    "sessionData": "Ab02b4c0!BQABAgAM99zP6G+EdFKBlr0D1qTzVM3+8zR6WA8DVh0CFXIADwvqWKLQyqy7BkbsJyXYhVHE9nCAvcgNxGQNDICdida1uiLe5CDu4ZctcnTvRR1mTYKj7wTrM0GI704yoonGRHgqBQPVMKMaxtwM5kWDqgJaCjXp/G4ITRIIgVjcqJ0sWRjNHjbxOJnvzpV+9Yf2fr15JPRHPzhir3UFSRt4Ssd8dL4xs+zT+2MMx3oGHMZELuHsCKikeT7iT/CPXpiiWMitIOz5+SR+kTWHMlv80/VCFuHxM/vktyBss4pF2MDLJC3VKK/YwuuScH2MJDXA5dzu55fOZ+OEeVABvmrC62jHW8XmXAMsoM15zfU3l9jWB95f+nEMcWEzGeIRpwBgT4dzzMUBrUOhZMatn2UKIb9HtcZTDC9uN7JTeJOJM+XctEm355qsH5whuddES/VFwUPMhdRMOcLD7zGkgdFR/d1zoOWsU+0x75HkaMlEN7U5PSyA+Lvw05YlxaVFwBmpWsRwBErj7BdfrcqGhBm+TsLeLXKPn6c2ISj8sSNYIgvVZ5r9/wOF/1A4BQr6T1ABZp4Pl9zMRwlIU4qKijtsFOUPH9K4LE/K+j/dBMVJUlqlkAqlPNx09b3bq3+WxH0u5rVlQfmScKufrGckxLzTFwz8OPXnE00Oui/KniMO1MfeaQzi7ZET4syG5ju35l8ASnsia2V5IjoiQUYwQUFBMTAzQ0E1MzdFQUVEODdDMjRERDUzOTA5QjgwQTc4QTkyM0UzODIzRDY4REFDQzk0QjlGRjgzMDVEQyJ9j4GFx5SuviF4EGuOhNfRfLSc5V4QaTAdixvvgyUgmy80QbtrdiHo1vpFPIyB42HVk7Kjnwyeg+g73G8wrHn/9z6/52xCOeXh4I2bT3IYpv5CDCnR9N+kp9AUIZ4aUQHird0QajSIZ9ybLrp2X1RnLWvUD4dL7HI2ek5rHE8Kvgng+N0iH7Ag4/jlra4lGF7x8BSOLhHHsLjTOnMN54xVT3QJ8ETXJdXlLx4sIeneY7x0ck5/11TsV8NkDH9ehjG8hyZG74IffujpKAxuiWck1FR/3GCKg5lXIOICfgCxsTfgDPMqmYXUCSxP582oma2bfblq7scELXHlbe8yDk6EndHS9rJXrLQHQ59UzYnqCEyh/sfKM8Q1IfyWC9Do1s16ZXjl32kRVnTtRPMBulaChTNOTqxvF8ECpuNfcypLziBBxFk4ki3K+qRk9HI4edMx2APXhUwu1d2ihJKh7gKDYu+LagJRjoQlEvWTKWNvJoHxuGR0DXueAsrPF3bTcv3259lUr04S6dpIudSYl/rjhcZhf7KrQ68laHOLImCcmnNvp+qJLz2sD5SbwCe6Y+Mu4yGSMYa6kDcLyn38kj7kwSljZLdaFYkMSbM2cber8sB4R/Zhy9MreOaxwmayFMU/+OH+daScyA9IkliLLkAvW/Xf7TuyD1WmkqP0MSv0P4YAarsNleN1zmLldTMLelYO/PcuJlU9hg0P3popX26GoqcZH/1EqROP80qpa4sU27NRfp8uftJHiDpRBm6N3rs7vJ4pCBTYjVzKRg=="
},
"paymentMethodsConfiguration": {
    "card": {
        "hasHolderName": true,
        "holderNameRequired": true,
        "billingAddressRequired": false
    }
}

}

Which again looks like good json, except a lot of it is missing.

The input string to this looks like this:

'{
"channel": 3,
"recurringProcessingModel": null,
"shopperInteraction": null,
"accountInfo": null,
"additionalAmount": null,
"additionalData": null,
"allowedPaymentMethods": null,
"amount": {
    "currency": "GBP",
    "value": 300
},
"applicationInfo": null,
"authenticationData": null,
"billingAddress": null,
"blockedPaymentMethods": null,
"captureDelayHours": null,
"company": null,
"countryCode": "GB",
"dateOfBirth": null,
"deliverAt": null,
"deliveryAddress": null,
"enableOneClick": null,
"enablePayOut": null,
"enableRecurring": null,
"expiresAt"…/ToM4g9D/DcEDzm6xqKEzNVIMPmWtFtaXILQlOsn1q9LNSojuJYXTVxv12hfNb/s0yYDae3YXzS7et5rdLYvzS5aeeCUsj+Yajy3x9+f/OwqKLpqXVGIOkQ4hijH85jusgxxbW35yaWgHQfEjOdbtTX200VlvbsajGSdLKEMWtLcTHtb","shopperEmail":null,"shopperIP":null,"shopperLocale":"en-US","shopperName":null,"shopperReference":null,"shopperStatement":null,"socialSecurityNumber":null,"splitCardFundingSources":false,"splits":null,"store":null,"storePaymentMethod":null,"telephoneNumber":null,"threeDSAuthenticationOnly":false,"trustedShopper":null}'

If I look at the ‘expiresAt’ field it doesn’t look particularly out of the ordinary does it?
From the raw data above…

"enableRecurring": null,
"expiresAt": "2023-04-17T11:28:00+01:00",
"id": "CS2387F156F0520AB5",

Something odd is deffinitely going on, or just that I don’t understand.

Other things I have tried:
Reading as a byte[] array:

    byte[]? arrayres = await response.Content.ReadAsByteArrayAsync();

This reads the array, but again when I try to decode it into ascii or utf-8 string it I get the same result (breaking at expiresAt – or the JSON.parse just barfs…)

I also tried using c# JsonNode object but again a similar problem.

In an Ideal world the Adyen.Model.Checkout c# object ‘CreateCheckoutSessionResponse’ would just read back from the response, but it doesn’t.

Ideas anyone?
Thanks in advance.

Set attribute checked to checkbox if its value is not empty – javascript

Javascript successfully copies table row along with input’s value, however checkbox does not keep attribute “checked”.

Here is the part of code.

var i = 0;

$(".add-row").click(function(){
++i;
var cA = $('#cA-'+i+'').val();
var markup = '<tr>...<input type="checkbox" id="cA-'+i+'" name="cA-'+i+'" value="'+cA+'" >...</tr>'
$('table tbody tr:first').after(markup);
});

How can I set condition to keep / set attribute “checked” if input’s value is not empty?