Can websites send hidden header information?

So I recently upgraded my services at a web hosting company and they migrated my website to a new server. Now, everything’s not working as it is supposed to do. My ajax calls are not working because it cannot identify the response from the server. Even though the code works as before.

Also, all my web pages that use TCPDF displays this error:

TCPDF ERROR: Some data has already been output, can’t send PDF file

which happens only when the web page display something before generating the PDF.

So is it possible that web pages can send a hidden header information that cannot be seen?

I tried creating a blank page just displaying a single PDF page, no data and all and it still displays the error.

Tidio Custom Chat Button Not Showing Chat Widget

I have been going round and round on this. I can’t seem to get the button to open the chat widget on my website. It works fine in the codepen I have.

<button class="chat-button">Live Chat</button>


<script src="//code.tidio.co/ryhpmtzyn1r8xzyyzpxo9a4d4tg8lkvl.js" async></script>

<script>document.querySelector(".chat-button").addEventListener("click", function() {
console.log("Button clicked");
window.tidioChatApi.show();
window.tidioChatApi.open(); });
</script>

Here is the codepen: https://codepen.io/tetonhiker/pen/oNVMrNQ

Here is my dev website: https://driftmediawebsite.com/

I am using a wordpress website and nothing seems to be working.

I’m using the same code on my website as in the codepen example. The button is within Rev Slider. Maybe that has something to do with it?

Javascript concatenate argument variable

I am attempting to add a variable to an argument and having no luck with it. Can someone help with this?

As you see, movePage function takes two arguments. The second argument is a variable but I’m having trouble with the proper quotes. I’ve tried a bunch of ways using single and double quotes with no success.

i.e. var country = “Canada”; (this will not be static)

$(".ap_a").first().prop("onClick","movePage(3,".country.")");

Problem using quaternion rotations in OGL Webgl library

I have a particle system spread in a spherical coordinate system. On every mouse click, I choose a random point from these points on sphere.

What I want (gif attached):
To smoothly rotate camera, on every click, so that its quaternion is equal to the random point’s. You can see in the gif how the particle placed at that random point smoothly ends up in front of the camera.

In the current state, a single click on the canvas sends the camera in a rotation frenzy. Could someone please help me why doesn’t the camera stop after reaching the destination?

Here’s the fiddle link: https://jsfiddle.net/k0tqujm8/

import {
    Renderer,
    Camera,
    Orbit,
    Geometry,
    TextureLoader,
    Program,
    Mesh,
    Vec3,
    Quat
} from 'https://unpkg.com/ogl';


// LERP
function lerp(n,r,e){return n*(1-e)+r*e};

const vertex = /* glsl */ `
attribute vec3 position;

uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;

void main() {
  vec3 pos = position;

  vec4 mvPos = modelViewMatrix * vec4(pos, 1.);
  gl_PointSize = 3. * (1./ -mvPos.z); 
  gl_Position = projectionMatrix * mvPos;
}
 `;

const fragment = /* glsl */ `
precision mediump float;

void main() {  
 gl_FragColor = vec4( 1. );
 }
`;

const renderer = new Renderer({ depth: false });
const gl = renderer.gl;
document.body.appendChild(gl.canvas);
gl.clearColor(0, 0, 0, 1);

const camera = new Camera(gl, {
  fov: 75,
  far: 300
});
camera.position.set(0, 0, 2);
camera.lookAt([0, 0, 0]);

function resize() {
  renderer.setSize(window.innerWidth, window.innerHeight);
  camera.perspective({ aspect: gl.canvas.width / gl.canvas.height });
}
window.addEventListener('resize', resize, false);
resize();

let n = 100;
let multiplier = 1;
const positions = [];

for (let i = 0; i <= n - 1; i++) {

    let v = new Vec3(
      ((Math.random() - 0.5) * 2) * multiplier,
      ((Math.random() - 0.5) * 2) * multiplier,
      ((Math.random() - 0.5) * 2) * multiplier
    ).normalize();

    positions.push(v);
    
}


// Create one array out of all nested arrays in positions[] to feed Float32Array below
let flatPositions = positions.flat();


const geometry = new Geometry(gl, {
  position: { size: 3, data: new Float32Array(flatPositions) }
});

const program = new Program(gl, {
  vertex,
  fragment,
  uniforms: {
    t: { value: 0 },
    uTarget: {value: new Vec3()},
    uProgress: {value: 0}
  },
  transparent: true,
});

const particles = new Mesh(gl, { mode: gl.POINTS, geometry, program });



let clicked = false;
let randomPt, randomQuat, cameraQuat;

document.addEventListener('click', () => {
  
  randomPt = positions[ Math.floor(Math.random() * positions.length) ];  
  
    randomQuat = new Quat().fromEuler(randomPt);

  clicked = true;
})

////////////////////////////////////////////////////////////////



let newPos = new Vec3();

function update(t) {
  requestAnimationFrame(update);


  const progress = (t * 0.000007) % 1;

  if(clicked == true ){
    
    ////////////// QUATERNION TESTING //////////////
    
    camera.position.applyQuaternion(randomQuat, 1);

    ///////////////////////////////////////////////
  }
  
  camera.lookAt([0, 0, 0]);
  
  renderer.render({ scene: particles, camera });
}

update();

DESIRED RESULT:
enter image description here

Dropdown Menu doesnt stay when I hover over the tab so I cant navigate it – react app

My nav component has a Games tab where a dropdown menu appears when you hover over it. However, I can’t figure out how to keep the dropdown menu open as the user hovers from the games tab just below to the menu as there’s a small gap so the menu disappears before u can move from the games tab to the dropdown menu.

Here is the relevant jsx code:

                    <li className='navbar__link' onMouseEnter={() => setIsDropdownOpen(true)} onMouseLeave={() => setIsDropdownOpen(false)}>
                      <Link to="/games" className='link__styles'>Games</Link>
                      <div className={`dropdown-menu ${isDropdownOpen ? 'show' : ''}`} onMouseEnter={() => setIsDropdownOpen(true)} onMouseLeave={() => setIsDropdownOpen(false)}>
                        <span className="dropdown-column">
                          <h3>Games</h3>
                          <p>Word games, logic puzzles and crosswords, including an extensive archive.</p>
                        </span>
                        <span className="dropdown-column">
                          <h5>Play</h5>
                          <ul>
                            <a href="link">
                              <li>
                                <img src={WordleIcon} alt="" className="dropdown-tile" />
                                <span>Wordle</span>
                              </li>
                            </a>
                            <a href="link">
                              <li>
                                <img src={CrosswordIcon} alt="" className='dropdown-tile2'/>
                                <span>Crossword</span>
                              </li>
                            </a>
                            <a href="link">
                              <li>
                                <img src={WordsearchIcon} alt="" className='dropdown-tile2'/>
                                <span>Wordsearch</span>
                              </li>
                            </a>
                          </ul>
                        </span>
                      </div>
                    </li>

Here is the relevant css code:

.dropdown-menu {
    position: absolute;
    top: calc(100% - 4px);
    left: 0;
    width: 100%;
    background-color: white;
    display: none;
    z-index: 999;
    padding: 2% 8%;
    box-shadow: 0px 10px 10px rgba(0, 0, 0, 0.1);
}

.navbar__link:hover .dropdown-menu,
.dropdown-menu:hover {
    display: flex;
    gap: 2rem;
    justify-content: center;
}

.dropdown-column {
    max-width: 200px;
}

.dropdown-column > p {
    margin-top: 1rem;
}

.dropdown-tile {
    width: 25px;
    margin-right: 0.2rem;
}

.dropdown-tile2 {
    width: 17.5px;
    margin: 0 0.4rem 0 0.2rem;
}

Limit orders by modifying dates

I’m facing an issue in finding a solution to this problem. The company wants to limit the orders to a certain quantity per day and carry over the excess orders to the next day. So far, I’ve managed to implement this logic. However, the problem arises when they want to change the date again if the following day exceeds a certain quantity. I’m struggling to achieve this. Currently, I limit the orders to 2, and by staying on the same date, I lose control over the orders for the next day unless I implement endless conditional statements calling functions to handle the following days. Can anyone provide some assistance?

Below are the functions providing the dates and also the code of the controller.

async function contarPedidosDelDia() {
    return await Order.countDocuments({
        order_date: {
            $gte: getStartTimeOfDay(),
            $lte: getEndTimeOfDay()
        }
    });
}

export const newOrder = async (req, res, next) => {
    try {
        // Llamar a la función para comenzar a controlar el límite de pedidos
        let currentDate = getCurrentISODate()
        const cantPedidosDelDia = await contarPedidosDelDia()

        if(cantPedidosDelDia >= 2) {
            currentDate = getDateTomorrowISO()
        }
        /* const user_orders = await Order.find({ user: req.user.id })
        user_orders.forEach((user_order) => {
            if (user_order.status === 'pendiente') {
                throw new ErrorResponse('You already have an outstanding order.', 400)
            }
        }) */

        const { quantity, promotion_id, payment_method, product_id, observation } = req.body
        const file = req.file
        let monto_descontado = 0
        let total_bidones_descontado = 0
        let total_bidones_sin_descuento = 0
        let comprobante = ""
        let user_balance = 0


        // Verifica si el usuario existe
        const user = await User.findById(req.user.id);
        if (!user) {
            throw new ErrorResponse('User not found', 404)
        }
        const product = await Product.findById(product_id);

        if (!product) {
            throw new ErrorResponse('No product found', 404);
        }
        if (!req.file) {
            comprobante = 'No disponible'
        }
        if (req.file && payment_method === "Transferencia") {
            comprobante = file.path
        }

        if (req.file && payment_method === "Efectivo") {
            await cloudinary.uploader.destroy(req.file.filename);
            comprobante = "No disponible"
        }
        if (user.balance > 0) {
            user_balance = user.balance
        }

        if (promotion_id !== "") {


            const promotion = await Promotion.findById(promotion_id)
            if (!promotion) {
                throw new ErrorResponse('Promotion not found', 404)
            }

            if (promotion.required_quantity > quantity) {
                throw new ErrorResponse('Promotion is not applicable', 400)
            }

            //calculo del descuento aplicado a los bidones
            const total_bidones_sin_descuento = product.price * quantity
            monto_descontado = (total_bidones_sin_descuento * promotion.discounted_percentage) / 100;
            total_bidones_descontado = total_bidones_sin_descuento - monto_descontado


            const newOrder = new Order({
                user: user.id,
                product: product_id,
                promotion: promotion_id,
                quantity,
                payment_method,
                proof_of_payment_image: comprobante,
                order_date: currentDate,
                order_due_date: getDateNextMonthISO(),
                observation,
                total_amount: total_bidones_descontado - user_balance,
            });

            const savedOrder = await newOrder.save();

            const populatedOrder = await Order.findById(savedOrder.id)
                .populate('user', '-password')
                .populate('product', '-img')
                .populate('promotion', '-img')

            res.status(201).json({
                success: true,
                populatedOrder,
                discounted_quantity: user_balance
            });


        }
        else {
            total_bidones_sin_descuento = product.price * quantity
            const newOrder = new Order({
                user: user.id,
                product: product_id,
                promotion: null,
                quantity,
                payment_method,
                proof_of_payment_image: comprobante,
                order_date: currentDate,
                order_due_date: getDateNextMonthISO(),
                observation,
                total_amount: total_bidones_sin_descuento - user_balance
            });

            const savedOrder = await newOrder.save();

            const populatedOrder = await Order.findById(savedOrder.id)
                .populate('user', '-password')
                .populate('product')

            res.status(201).json({
                success: true,
                populatedOrder,
                discounted_quantity: user_balance
            });
        }
    }

    catch (error) {
        next(error);
    }
}


// DATE UTILS

// Función para obtener el inicio del día en el formato ISO 8601
export function getStartTimeOfDay() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0'); // Asegurar que tenga 2 dígitos
    const day = String(now.getDate()).padStart(2, '0'); // Asegurar que tenga 2 dígitos
    const startOfDay = `${year}-${month}-${day}T00:00:00.000Z`;
    return startOfDay;
}

// Función para obtener el final del día en el formato ISO 8601
export function getEndTimeOfDay() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0'); // Asegurar que tenga 2 dígitos
    const day = String(now.getDate()).padStart(2, '0'); // Asegurar que tenga 2 dígitos
    const endOfDay = `${year}-${month}-${day}T23:59:59.999Z`;
    return endOfDay;
}




// Función para obtener la fecha actual en formato ISO 8601
export function getCurrentISODate() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0'); // Asegurar que tenga 2 dígitos
    const day = String(now.getDate()).padStart(2, '0'); // Asegurar que tenga 2 dígitos
    const hours = String(now.getHours()).padStart(2, '0'); // Asegurar que tenga 2 dígitos
    const minutes = String(now.getMinutes()).padStart(2, '0'); // Asegurar que tenga 2 dígitos
    const seconds = String(now.getSeconds()).padStart(2, '0'); // Asegurar que tenga 2 dígitos
    const milliseconds = String(now.getMilliseconds()).padStart(3, '0'); // Asegurar que tenga 3 dígitos
    const currentISODate = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${milliseconds}Z`;
    return currentISODate;
}

// Función para obtener la fecha actual más un día en formato ISO 8601
export function getDateTomorrowISO() {
    const now = new Date();
    const tomorrow = new Date(now);
    tomorrow.setDate(now.getDate() + 1);

    const year = tomorrow.getFullYear();
    const month = String(tomorrow.getMonth() + 1).padStart(2, '0'); // Asegurar que tenga 2 dígitos
    const day = String(tomorrow.getDate()).padStart(2, '0'); // Asegurar que tenga 2 dígitos

    const tomorrowISODate = `${year}-${month}-${day}T00:00:00.000Z`;
    return tomorrowISODate;
}

// Función para obtener la fecha actual más un mes en formato ISO 8601
export function getDateNextMonthISO() {
    const now = new Date();
    const nextMonth = new Date(now);
    nextMonth.setMonth(now.getMonth() + 1);

    const year = nextMonth.getFullYear();
    const month = String(nextMonth.getMonth() + 1).padStart(2, '0'); // Asegurar que tenga 2 dígitos
    const day = String(nextMonth.getDate()).padStart(2, '0'); // Asegurar que tenga 2 dígitos

    const nextMonthISODate = `${year}-${month}-${day}T00:00:00.000Z`;
    return nextMonthISODate;
}

help me pls, its my first job

How do I get asynchronous results in a synchronous node.js function

I have looked at lots of different posts, most of which devolve into a “synchronous is bad” lecture, and none of them have helped me with my problem.

I have a node.js REST service that we use to manage our application servers. The service runs on each server, and each REST request contains a credential so that the service can verify that the requestor is authorized to perform the desired action.

The service uses LDAP to verify the user before continuing. This functionality has been working for several years.

The problem is that our single LDAP service is being replaced by two services ( A and B ) in different network compartments. Unfortunately, some of our servers can only reach the A service and others can only reach the B service. Instead of manually configuring each server to point to a specific service, I have created a list of LDAP services and am trying to write a function that will go through the list and find which service is available.

This authentication step needs to be done synchronously before any actions are executed. I have found two potential libraries that will let me ping a specific port on a server, and then return true or false based on the result, but since these are asynchronous libraries I am having a hard time getting them to return in my synchronous function. The two libraries are “tcp-ping-port” and “tcp-ping-node”.

In both cases their sample code shows using “.then” to wait for the response such as:

function CheckServer(server, port)
{

    result = false;
    var tcpp = require("tcp-ping-port");
    var options = {
        socketTimeout: 2000,
        dnsTimeout: 2000
    }

    tcpp(server, port, options).then(res => {
        result = res.online
    });
    return result;

}

Unfortunately, the block of code inside .then is never reached, and instead the REST request is immediately terminated with a “(500) Internal Server Error” message

How can I get the result into my function?

ThreeJS r160 ShaderMaterial Texture Renders Black

I’m trying to add a texture into this shader, but when I do it renders black. I’m probably missing something small, but I couldn’t find any info on this for ThreeJS version r160. The shader code is all default right now, by the way, but I plan to customize it.

This is the JS code.

let standard = THREE.ShaderLib['standard'];
let dirtMaterial = new THREE.ShaderMaterial({
    lights: true,
    vertexShader: document.getElementById( 'dirtVS' ).textContent,
    fragmentShader: document.getElementById( 'dirtFS' ).textContent,
    uniforms: THREE.UniformsUtils.clone( standard.uniforms )
});
dirtMaterial.defines.PHYSICAL = "";
dirtMaterial.defines.USE_MAP = "";
// dirtMaterial.uniforms.diffuse.value = new THREE.Color( 0x91773d );
dirtMaterial.uniforms.roughness.value = 1.0;
dirtMaterial.uniforms.metalness.value = 0.0;
dirtMaterial.uniforms.ior.value = 0.0;

let dirtTexture = new THREE.TextureLoader();
dirtTexture.load(
'textures/fieldDirtTexture.jpg',
function ( mapT ) {     
    // dirtTexture.wrapS = THREE.RepeatWrapping;
    // dirtTexture.wrapT = THREE.RepeatWrapping;
    dirtMaterial.map = mapT;        
});

This is the shader code.

<script id="dirtVS" type="GLSL">
        #define STANDARD

        varying vec3 vViewPosition;

        #ifdef USE_TRANSMISSION

            varying vec3 vWorldPosition;

        #endif

        #include <common>
        #include <batching_pars_vertex>
        #include <uv_pars_vertex>
        #include <displacementmap_pars_vertex>
        #include <color_pars_vertex>
        #include <fog_pars_vertex>
        #include <normal_pars_vertex>
        #include <morphtarget_pars_vertex>
        #include <skinning_pars_vertex>
        #include <shadowmap_pars_vertex>
        #include <logdepthbuf_pars_vertex>
        #include <clipping_planes_pars_vertex>

        void main() {

            #include <uv_vertex>
            #include <color_vertex>
            #include <morphcolor_vertex>
            #include <batching_vertex>

            #include <beginnormal_vertex>
            #include <morphnormal_vertex>
            #include <skinbase_vertex>
            #include <skinnormal_vertex>
            #include <defaultnormal_vertex>
            #include <normal_vertex>

            #include <begin_vertex>
            #include <morphtarget_vertex>
            #include <skinning_vertex>
            #include <displacementmap_vertex>
            #include <project_vertex>
            #include <logdepthbuf_vertex>
            #include <clipping_planes_vertex>

            vViewPosition = - mvPosition.xyz;

            #include <worldpos_vertex>
            #include <shadowmap_vertex>
            #include <fog_vertex>

            #ifdef USE_TRANSMISSION

                vWorldPosition = worldPosition.xyz;

            #endif
        }
    </script>

<script id="dirtFS" type="GLSL">
        #define STANDARD

    
        #ifdef PHYSICAL
            #define IOR
            #define USE_SPECULAR
        #endif
        

        uniform vec3 diffuse;
        uniform vec3 emissive;
        uniform float roughness;
        uniform float metalness;
        uniform float opacity;

        #ifdef IOR
            uniform float ior;
        #endif
    
        #ifdef USE_SPECULAR
            uniform float specularIntensity;
            uniform vec3 specularColor;

            #ifdef USE_SPECULAR_COLORMAP
                uniform sampler2D specularColorMap;
            #endif

            #ifdef USE_SPECULAR_INTENSITYMAP
                uniform sampler2D specularIntensityMap;
            #endif
        #endif

        
        #ifdef USE_CLEARCOAT
            uniform float clearcoat;
            uniform float clearcoatRoughness;
        #endif

        #ifdef USE_IRIDESCENCE
            uniform float iridescence;
            uniform float iridescenceIOR;
            uniform float iridescenceThicknessMinimum;
            uniform float iridescenceThicknessMaximum;
        #endif

        #ifdef USE_SHEEN
            uniform vec3 sheenColor;
            uniform float sheenRoughness;

            #ifdef USE_SHEEN_COLORMAP
                uniform sampler2D sheenColorMap;
            #endif

            #ifdef USE_SHEEN_ROUGHNESSMAP
                uniform sampler2D sheenRoughnessMap;
            #endif
        #endif


        #ifdef USE_ANISOTROPY
            uniform vec2 anisotropyVector;

            #ifdef USE_ANISOTROPYMAP
                uniform sampler2D anisotropyMap;
            #endif
        #endif

        varying vec3 vViewPosition;

        #include <common>
        #include <packing>
        #include <dithering_pars_fragment>
        #include <color_pars_fragment>
        #include <uv_pars_fragment>
        #include <map_pars_fragment>
        #include <alphamap_pars_fragment>
        #include <alphatest_pars_fragment>
        #include <alphahash_pars_fragment>
        #include <aomap_pars_fragment>
        #include <lightmap_pars_fragment>
        #include <emissivemap_pars_fragment>
        #include <iridescence_fragment>
        #include <cube_uv_reflection_fragment>
        #include <envmap_common_pars_fragment>
        #include <envmap_physical_pars_fragment>
        #include <fog_pars_fragment>
        #include <lights_pars_begin>
        #include <normal_pars_fragment>
        #include <lights_physical_pars_fragment>
        #include <transmission_pars_fragment>
        #include <shadowmap_pars_fragment>
        #include <bumpmap_pars_fragment>
        #include <normalmap_pars_fragment>
        #include <clearcoat_pars_fragment>
        #include <iridescence_pars_fragment>
        #include <roughnessmap_pars_fragment>
        #include <metalnessmap_pars_fragment>
        #include <logdepthbuf_pars_fragment>
        #include <clipping_planes_pars_fragment>

        void main() {

            #include <clipping_planes_fragment>

            vec4 diffuseColor = vec4( diffuse, opacity );
            ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );
            vec3 totalEmissiveRadiance = emissive;

            #include <logdepthbuf_fragment>
            #include <map_fragment>
            #include <color_fragment>
            #include <alphamap_fragment>
            #include <alphatest_fragment>
            #include <alphahash_fragment>
            #include <roughnessmap_fragment>
            #include <metalnessmap_fragment>
            #include <normal_fragment_begin>
            #include <normal_fragment_maps>
            #include <clearcoat_normal_fragment_begin>
            #include <clearcoat_normal_fragment_maps>
            #include <emissivemap_fragment>

            // accumulation
            #include <lights_physical_fragment>
            #include <lights_fragment_begin>
            #include <lights_fragment_maps>
            #include <lights_fragment_end>

            // modulation
            #include <aomap_fragment>

            vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse;
            vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular;

            #include <transmission_fragment>

            vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance;

            #ifdef USE_SHEEN

                // Sheen energy compensation approximation calculation can be found at the end of
                // https://drive.google.com/file/d/1T0D1VSyR4AllqIJTQAraEIzjlb5h4FKH/view?usp=sharing
                float sheenEnergyComp = 1.0 - 0.157 * max3( material.sheenColor );

                outgoingLight = outgoingLight * sheenEnergyComp + sheenSpecularDirect + sheenSpecularIndirect;

            #endif

            #ifdef USE_CLEARCOAT

                float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) );

                vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc );

                outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat;

            #endif

            #include <opaque_fragment>
            #include <tonemapping_fragment>
            #include <colorspace_fragment>
            #include <fog_fragment>
            #include <premultiplied_alpha_fragment>
            #include <dithering_fragment>

        }
    </script>

Im trying to render a some pokemon svgs in my react app

react is not rendering the 15 pokemons i have gotten and stored in the array called urls which i’ve then set to the state pokemons in order to map them in the return statement. I want to know what i’ve missed or where the problem is, please help

here is my code:

import { useEffect, useState } from 'react';
import './Game.css';

export default function Game() {
    // const [id, setId] = useState(1);
    const [pokemon, setPokemon] = useState([]);


    useEffect(() => {

        const urls = [];

        for (let i = 1; i <= 15; i++) {
            fetch(`https://unpkg.com/[email protected]/sprites/pokemon/other/dream-world/${i}.svg`)
                .then((response) => response.blob())
                .then((response) => {
                    let url = URL.createObjectURL(response)

                    urls.push(url)
                })
        }
       
        setPokemon(urls);
       
       

        return () => { urls.forEach((url) => { URL.revokeObjectURL(url) }) }
    }, []);

   

    return (
        <>
            <div className="score-board">
                <h1>Score Board</h1>
                <div className="borderoutline">
                    <div className="innerdiv1">
                        <h2>count</h2>
                        <h2>high score</h2>
                    </div>
                    <div className="innerdiv2">
                        <h2>1</h2>
                        <h2>2</h2>
                    </div>
                </div>
            </div>
            <div>
                {pokemon.map((item, index) => {
                    <img src={item} key={index} />
                })}
            </div>
        </>
    );
}

i asked bard.ai but it couldn’t give a reason as to why my code wasn’t working it only gave me a solution which isn’t different from my code except for the fact that i didn’t use async and await but everything else is the same, well at least to me

here is the code from bard:

import { useEffect, useState } from 'react';
import './Game.css';

export default function Game() {
  const [pokemonUrls, setPokemonUrls] = useState([]); // Use a clearer variable name

  useEffect(() => {
    const fetchPokemons = async () => {
      const urls = []; // Create an empty array to store URLs

      for (let i = 1; i <= 15; i++) {
        try {
          const response = await fetch(`https://unpkg.com/[email protected]/sprites/pokemon/other/dream-world/${i}.svg`);
          const url = await response.blob(); // Retrieve only the URL
          urls.push(URL.createObjectURL(url)); // Add URL to the array
        } catch (error) {
          console.error('Error fetching image:', error);
          // Handle errors gracefully, e.g., log, display fallback image
        }
      }

      setPokemonUrls(urls); // Update state with all URLs at once
    };

    fetchPokemons();

    return () => {
      pokemonUrls.forEach(url => URL.revokeObjectURL(url)); // Revoke URLs on cleanup
    };
  }, []); // Run effect only once on mount

  return (
    <>
      <div className="score-board">
        <h1>Score Board</h1>
        <div className="borderoutline">
          <div className="innerdiv1">
            <h2>count</h2>
            <h2>high score</h2>
          </div>
          <div className="innerdiv2">
            <h2>1</h2>
            <h2>2</h2>
          </div>
        </div>      
      </div>
      <div>
        {pokemonUrls.map((url, index) => (
          <img src={url} key={index} alt={`Pokemon ${index}`} /> // Add alt text for accessibility
        ))}
      </div>
    </>
  );
}

Keycloak CORS Error: No ‘Access-Control-Allow-Origin’ Header Present

i have encountered a CORS issue that I’m struggling to resolve. I’m hoping someone here might have some insight or suggestions on how to address this.

When trying to access Keycloaks admin API from my frontend application, I’m facing a CORS policy error. Specifically, the browser is blocking the request due to the absence of the ‘Access-Control-Allow-Origin’ header in the response from Keycloak.

GET https://keycloak.server.de/admin/realms/realm/users net::ERR_FAILED 401 (Unauthorized)

Here are the details of the request and the error (error occurs both local and deployed):

  • Request URL: https://keycloak.server.de/admin/realms/realm/users
  • Frontend Origin: https://frontend.de
  • Error Message:
    Access to XMLHttpRequest at ‘https://keycloak.server.de/admin/realms/realm/users’ from origin ‘https://frontend.de’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

KEYCLOAK REALM SETTINGS

I know that i need to add rules to nginx (or whatever proxy) to overwrite all CORS headers which Keycloak respond with on OPTIONS calls, am I right about that?

I am appreciative of any support!

NodsJS Interface with Terminal Process

I am trying to build a WebUI for a Minecraft server. The goal here is to pass the output of the server jar file to the website, while also being able to send commands to it.

Searching Google yields wildly different results with everyone using completely different approaches with everyone using different libraries and specifically crafted tools.

How can I connect Vanilla JS Frontend to Python Backend?

I am a newer programmer and I am creating a chrome extension using Vanilla JS, CSS, and HTML. I am trying to integrate OpenAI’s Whisper Model using Python. When a button is clicked in the extension, I want to transcribe what is said into the mic and place it into a textarea word by word.

I’ve tried following ChatGPT’s instructions for this but I am utterly confused.

Caesar Cipher – decrypt letter formula

beginner here. I am currently working on a decrypt function but encountering a “Uncaught ReferenceError: decryptLetter is not defined” error. There is two function, one encryptLetter function and one decryptLetter function.

encryptLetter function takes a letter and a shiftValue, find out the index of the letter in a alphabet list, then shift the index by adding the shiftValue to come out a new index. It returns an encrypted letter.

const alphabet = "abcdefghijklmnopqrstuvwxyz"
function encryptLetter(letter, shiftValue)
{
    const letterLowerCase = letter.toLowerCase() 

    const index = alphabet.indexOf(letterLowerCase)

// Ensuring the shift wraps around the alphabet if it exceeds.
    const newIndex = (index + shiftValue) % alphabet.length

    return alphabet[newIndex]
}

decryptLetter function takes a encrypted letter and a shiftvalue as well, find out the index of encrypted letter, then shift back the index by subtracting the shiftValue, and returns a decrypted letter.

function decryptLetter(letter, shiftValue)
{
    const index = alphabet.indexOf(letter.toLowerCase())

    // Use the modulus operator to ensure wrapping around the alphabet if necessary.
    // Remember to handle negative values correctly by adding the length of alphabet to add rotation
    const newIndex = (index - shiftValue + alphabet.length) % alphabet.length

    return alphabet[newIndex]
}

When it comes to decrypting letters between “a” to “p”, I get a negative newIndex value and lead to undefined. And not able decrypt.

I reached to my mentor, she suggested to add a if statement below the newIndex variable in the decryptLetter function but it did not work.

Here is my repo for the project.

Thank you in advance for any input/comment. Additional advice will be appreciated.

javascript document.getElementById is not working (traditional Domino form) [duplicate]

In my attempt to update our submit process, I have switched to using javascript behind a “SUBMIT” button that is on the form.

Trying to get the contents of a computed (or computed for display) field during the javascript that is called it is returning null when trying to get a handle on the field element.

The id is added to the field properties. The getElementId works fine to get DIVs on the form, just not these two fields. They are NOT hidden fields.

Reading around I see mention of the DOM not being fully loaded, but this form is sitting here fully loaded and a button displayed. Ideas?