Can’t call a value from inside an object dynamically based on a variable. ( Reference error: Not defined )

I have multiple objects set up within other objects and would like to call specific values inside of them based on the user input ( a preset value in this example for simplicity ) but I get an error whenever I try to call those values/numbers I want.

let creekchub = {
  islandWarrior: {
    iw2: {
      sb: 850,
      tgttos: 1670,
      hitw: 2300,
      bb: 1985
    },

    iw1: {
      sb: 600,
      tgttos: 1850,
      hitw: 2100,
      bb: 1650
    }
  }
}

let player = "creekchub";
let server = "islandWarrior";
let event = "iw1";

console.log(player.server.event.bb);

Is my first attempt. My expected output would have been 1650 however I get a error: “Reference Error: islandWarrior not defined” I tried something similar but with a function

typefunction printStats(player,server,event){
  console.log(player.server.event.bb);
}

printStats(creekchub,islandWarrior,iw1);
 here

but it has a similar issue, simply outputting the same error.

Is there a better/more efficient way to do this, and not get an error? Ty.

Javascript – Build an array of the parent ids of each element including its id

I would like to get the hierarchy of every single element of the array

I have this object array

[
    {
        "id": "1",
        "name": "Car",
        "parentId": "0",
        "parents": []
    },
    {
        "id": "2",
        "name": "Car > Steering wheel",
        "parentId": "1",
        "parents": []
    },
    {
        "id": "3",
        "name": "Car > Wheel",
        "parentId": "1",
        "parents": []
    },
    {
        "id": "4",
        "name": "Car > Wheel > Wheel rim",
        "parentId": "3",
        "parents": []
    },
    {
        "id": "5",
        "name": "Bus",
        "parentId": "0",
        "parents": []
    },
      {
        "id": "6",
        "name": "Bus > Wheel",
        "parentId": "5",
        "parents": []
    }
]

The result I need to get is the following array with the ‘parents’ key set

[
    {
        "id": "1",
        "name": "Car",
        "parentId": "0",
        "parents": ["1"]
    },
    {
        "id": "2",
        "name": "Car > Steering wheel",
        "parentId": "1",
        "parents": ["1","2"]
    },
    {
        "id": "3",
        "name": "Car > Wheel",
        "parentId": "1",
        "parents": ["1","3"]
    },
    {
        "id": "4",
        "name": "Car > Wheel > Wheel rim",
        "parentId": "3",
        "parents": ["1","3","4"]
    },
    {
        "id": "5",
        "name": "Bus",
        "parentId": "0",
        "parents": ["5"]
    },
      {
        "id": "6",
        "name": "Bus > Wheel",
        "parentId": "5",
        "parents": ["5","6"]
    }
]

As you can see, ‘parents’ contains its id and its parents ids

I tried with map but failed. What do you suggest I do?

Uncaught Error: ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: node_modules/whatwg-fetch/fetch.js

I separated my build and webpack scripts from project and changed as npm package bin executable files.

I linked to the project then changed the start script like :
start : ‘build-pkg-dev’

throw the below error
Uncaught Error: ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: ./node_modules/@tekion/tap-build/node_modules/exports-loader/index.js?self.fetch!./node_modules/@tekion/tap-build/node_modules/whatwg-fetch/fetch.js

Is it possible to fetch a yaml config using a variable name from typescript/javascript? [duplicate]

Lets say I have a yaml file like this:

country.yaml

country:
  India:
    State:"Delhi"
  USA:
    State:"Texas"

After I load yaml into my ts code:

const variable = fs.readFileSync('./path/country.yaml', 'utf-8');
const v2 = yaml.load(variable);

Can I fetch a config value using a variable like this:

const y = v2.country.insert-variable.State;

Is it possible to insert a variable and fetch config like this? and how?

I tried with no success:

const y = v2.country.$(insert-variable).State;

and

const y = v2.country.{{insert-variable}}.State;

Plotly delete shape function

I would like to replicate the operation of the ‘delete active shape’ button in the modebar with a function triggered by another button, but I cannot capture any associated event, nor understand what the function is triggered, can you help me?

Clearing react-calender value with react hooks and typescript

In the example below I am using React-Calander plug in. When a user clicks on a date it sets the state to the selected date but I want to also users to clear/reset the date value to an empty string. With typescript I want to be specific so I don’t want to make everything a string value and set it to an empty string. Does anyone know how to clear a react calender under these circumstances?

import React, { Ref, useState } from 'react';
import Calendar from 'react-calendar';
import { DropdownContent, Button } from 'vapi-ui-common';
import styles from './dropdownDatepicker.module.scss';

interface DropdownAssignProps {
  open: boolean;
  onClose: () => void;
  updateDate: (date: Date) => void;
  currentDate?: Date;
}

const DropdownDatepicker = React.forwardRef(
  ({ open, updateDate, onClose, currentDate }: DropdownAssignProps, ref: Ref<any>) => {
    const [goLiveDate, setGoLiveDate] = useState(currentDate || new Date());
    // goal to set goLiveDate to '' or undefined ^^

    const onSave = () => {
      updateDate(goLiveDate);
    };

    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);

    return (
      <DropdownContent open={open} ref={ref}>
        <div className={styles.calendarContainer}>
          <Calendar
            className={styles.calendar}
            value={goLiveDate}
            onChange={setGoLiveDate}
            minDate={tomorrow}
          />
          <div className={styles.buttonContainer}>
            <Button className={styles.cancelButton} variant="transparent" onClick={onClose}>
              Cancel
            </Button>
            <Button className={styles.saveButton} variant="primary" onClick={onSave}>
              Queue Live Date
            </Button>
            <Button className={styles.saveButton} variant="primary" onClick={}>
              Clear Queued Live Date
            </Button>
          </div>
        </div>
      </DropdownContent>
    );

I tried explaining my problem and gave example code of the issue

Scaling large images in browser causes frame-rate drop

We have a zoomable canvas that contains images that users upload. Zooming is done using transform in CSS.

When zooming in, the page will often hang for a second, seemingly while it loads the image.

This is easiest to see through a screen recording:
https://www.loom.com/share/7d007e92fd8445889a47f2e28a2165a3

Note this image is 2880 × 16564 pixels. But what’s actually going on here? Why is it slowing down when scaling up?

Note, we’ve tried adding will-change: transform; to the layer that will change, however this does not solve it.

React Dynamic Router / works in dev mode but not in build mode

main.jsx:

import {
  createBrowserRouter,
  createRoutesFromElements,
  RouterProvider,
  Route,
} from "react-router-dom";

const router = createBrowserRouter(
  createRoutesFromElements(
    <Route path='/'>
      <Route index element={<App />} />
      <Route path="blog/:id" element={<BlogArticle />} />
    </Route>
  )
);

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>   
        <RouterProvider router={router} />
  </React.StrictMode>,
)

My link to BlockArticle looks like this:

<Link to={`/blog/id=${blog.id}`} reloadDocument={true}>

I map over the blog array and add the ID to the link

and in BlockArticle I catch the ID:

const lastField = document.location.pathname.split("=");

return <div key={blog.id}>
    { blog.id == lastField[1] ? ... : ... }
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.14.1"

and in dev mode everything works, but if I build and upload the project I get (only when I try to open some of the BlogArticles) a “Server Error 404 Page Not Found” appears.

I’m completely new to React, maybe it’s very simple.
But after half day of googling I’m still lost.

I want to use a result from an api call in another file

I am using langchain to send openai api some information and a question. I am new to javascript and react, and I would like to input that quesion as a variable from another file and save the output that I receive as a variable and also use that in another file.

import { OpenAIEmbeddings } from "langchain/embeddings/openai";
import { OpenAI } from "langchain/llms/openai";
import { loadQAStuffChain } from "langchain/chains";
import { Document } from "langchain/document";

// 1. Export the queryPineconeVectorStoreAndQueryLLM function
export const queryPineconeVectorStoreAndQueryLLM = async (
  client,
  indexName,
  question
) => {
  // 2. Start query process
  console.log("Querying Pinecone vector store...");

  // 3. Retrieve the Pinecone index
  const index = client.Index(indexName);

  // 4. Create query embedding
  const queryEmbedding = await new OpenAIEmbeddings().embedQuery(question);

  // 5. Query Pinecone index and return top 10 matches
  let queryResponse = await index.query({
    queryRequest: {
      topK: 5,
      vector: queryEmbedding,
      includeMetadata: true,
      includeValues: true,
    },
  });

  // 6. Log the number of matches
  console.log(`Found ${queryResponse.matches.length} matches...`);

  // 7. Log the question being asked
  console.log(`Asking question: ${question}...`);
  if (queryResponse.matches.length) {
    // 8. Create an OpenAI instance and load the QAStuffChain
    const llm = new OpenAI({});
    const chain = loadQAStuffChain(llm);

    // 9. Extract and concatenate page content from matched documents
    const concatenatedPageContent = queryResponse.matches
      .map((match) => match.metadata.pageContent)
      .join(" ");

    // 10. Execute the chain with input documents and question
    const result = await chain.call({
      input_documents: [new Document({ pageContent: concatenatedPageContent })],
      question: question,
    });

    // 11. Log the answer  (eventually make this show up on the screen)
    console.log(`Answer: ${result.text}`);
  } else {
    // 12. Log that there are no matches, so GPT-3 will not be queried
    console.log("Since there are no matches, GPT-3 will not be queried.");
  }
};

I want ${result.text} to be able to be accessed in another file.

Get parent current state from child callback function | React

I’m trying to get history state from my callback function onRestore and when I log the history it’s logging only the history untill the id of the clicked snapshot

Why my callback function show incorrect state..

I’ve already tried single thing I could so please help me

import React, { useState, useEffect, useRef } from "react"
import Board from "./Board"
import Snapshot from "./Snapshot"



export default function Game(){
  const [ history, setHistory ] = useState([makeSnapshot(0, EMPTY_BOARD, true, onRestore)])
  const [ offset, setOffset ] = useState(0)

  function makeSnapshot(index, board, currentPlayer, onRestore){
    const snapshot = { index, board, currentPlayer, onRestore }
    return <Snapshot key={index} {...snapshot}/>
  }

  function onRestore(snapshot){
    console.log(snapshot) // #2 snapshot item
    console.log(history) // log only 2 snapshot items (if snapshot item id is #3 so 3 items in history)
  }

  function drawPlayer(index){
    const nextMove = makeSnapshot(history.length, newBoard, currentPlayer, onRestore)
    setHistory(prevHistory => ([...prevHistory, nextMove]))
    
    setOffset(history.length + 1)
  }



  return(
    <div className="Game">
      <h1>History: { history.map(snapshot => snapshot) } </h1>
    </div>
  )
}
export default function Snapshot(snapshot){ 

  const move = !snapshot.index ? `game start` : `move #${snapshot.index}`
  const disableClass = snapshot.isDisabled ? " disabled" : ""

  return(
    <div id={snapshot.index} className="snapshot" onClick={() => snapshot.onRestore(snapshot)}> Go to {move} </div>
  )
}

enter image description here

Live log:

enter image description here

How do you create React Native Stack Navigator screens based on the length of an array?

I have been trying to dynamically render React Native Stack Navigator screens based on how many foods there are in a database, I have tried several approaches but none have worked,to be clear the desired behavior is for one screen to render for each food in the database, with both the food name and food brand included in the screen, currently nothing is rendering. Any and all help would be greatly appreciated.

import { StyleSheet, Text, View, TouchableOpacity, useEffect } from 'react-native';
import { SafeAreaView } from "react-native-safe-area-context";
import { initializeApp } from "@firebase/app";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import { getDatabase, ref, push, onValue } from "@firebase/database";

const appSettings = {
  databaseURL: "" //My url
};

const app = initializeApp(appSettings);
const db = getDatabase(app);
const foodsInDb = ref(db, "foods");

const HomeStack = createNativeStackNavigator();

export default function Search() {
    useEffect(() => {
        const handleData = (snapshot) => {
            let foodList = [];
            foods = Object.values(snapshot.val())
            for (let i = 0; i < foods.length; i++) {
              let foodBrand = foods[i][0]
              let foodName = foods[i][1]
              let screen = (<SafeAreaView key={Object.keys(foods[i])}>
              <Text>{foodName}</Text>
              <Text>{foodBrand}</Text>
              </SafeAreaView>)
              foodList.push(<HomeStack.Screen key={index} name={"Screen" + index} component={screen} />)
        }
        }
        onValue(foodsInDb, handleData())
    }, [])
    return (
            <HomeStack.Navigator>
                {foodList}
            </HomeStack.Navigator>
    );
}

const styles = StyleSheet.create({
    button: {
        backgroundColor: "blue",
        padding: 10,
        borderRadius: 5,
        marginTop: 10,
    },
    buttonText: {
        color: "white",
        fontSize: 16,
        fontWeight: "bold",
        textAlign: "center",
    },
});

Elements over a sphere only appear when they are behind it

I am actually making a rotating globe, with points of interest on it. The globe is rotating so it should show points of interest whenever the point is visible on the globe.

My problem is that I only see the points of interest when they are “behind” the globe when it rotates, like on the picture below (you can only see a thin red line on the right):

A piece of a globe with

Here is the code:

<script setup>
import * as THREE from 'three';

const points = [
  {
    name: 'Paris',
    latitude: 48.864716,
    longitude: 2.349014,
  },
  {
    name: 'New York',
    latitude: 40.73061,
    longitude: -73.935242,
  },
  {
    name: 'Beijing',
    latitude: 39.9042,
    longitude: 116.407396,
  },
];

const wrapper = ref(null);
let renderer = null;
let scene = null;
let camera = null;
let sphere = null;
let clouds = null;

const rotationSpeed = 0.005;
const markers = [];
let animationFrameId = null;
let isMounted = false;

function render() {
  if (isMounted) {
    sphere.rotation.y += rotationSpeed;
    animationFrameId = requestAnimationFrame(render);
    renderer.render(scene, camera);
  }
}

function createSphere(radius, segments) {
  return new THREE.Mesh(
    new THREE.SphereGeometry(radius, segments, segments),
    new THREE.MeshBasicMaterial({ color: 0x0000ff })
  );
}

function initialize() {
  const width = window.innerWidth;
  const height = window.innerHeight;

  // Earth params
  const radius = 0.5;
  const segments = 32;
  const rotation = 6;

  scene = new THREE.Scene();

  camera = new THREE.PerspectiveCamera(45, width / height, 0.01, 1000);
  camera.position.z = 1.5;

  renderer = new THREE.WebGLRenderer({
    antialias: true,
    alpha: true,
  });
  renderer.setSize(width, height);

  scene.add(new THREE.AmbientLight(0x333333));

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

  sphere = createSphere(radius, segments);
  sphere.rotation.y = rotation;
  scene.add(sphere);

  for (const point of points) {
    const marker = new THREE.Mesh(
      new THREE.RingGeometry(0.01, 0.02, 32),
      new THREE.MeshBasicMaterial({ color: 0xff0000 })
    );

    const phi = (90 - point.latitude) * (Math.PI / 180);
    const theta = (point.longitude + 180) * (Math.PI / 180);

    marker.position.x = -((radius + 0.001) * Math.sin(phi) * Math.cos(theta));
    marker.position.y = (radius + 0.001) * Math.cos(phi);
    marker.position.z = (radius + 0.001) * Math.sin(phi) * Math.sin(theta);

    marker.lookAt(sphere.position);

    sphere.add(marker);
  }

  wrapper.value.appendChild(renderer.domElement);

  render();
}

function onResize() {
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
}

onMounted(() => {
  isMounted = true;
  initialize();
  window.addEventListener('resize', onResize);
});

onUnmounted(() => {
  isMounted = false;
  cancelAnimationFrame(animationFrameId);
  window.removeEventListener('resize', onResize);
});
</script>

<template>
  <div ref="wrapper">
    <!--  -->
  </div>
</template>

Here is a reproduction of my problem on Stackblitz: https://stackblitz.com/edit/nuxt-starter-ewsydq?file=app.vue. I removed anything superfluous (textures for instance) so the reproduction is the lightest as possible.

Thanks for your help 🙂

What should I do so my points of interest are visible when they are on the visible side of the globe?

How to request/execute a command on a web page without using a web browser?

I’m trying to get the commentary of a football match from the William Hill website.
To get them I need the child elements of id=”box_commentaries” to appear.

enter image description here

To make them appear I need to simulate a click on class=”_commentary”.

enter image description here

There are two ways to do this: by clicking directly or calling this function in the console.

enter image description here

My question is how can I do this without having to open a web browser? I don’t want to open a web browser because I’m going to be getting comments from dozens of matches simultaneously every minute and I don’t want to consume too much memory since I need to do more things.

The function I used was this:

(function() {
  setTimeout(function() {
    document.getElementsByClassName('_commentary')[0].click();
  }, 3000);
})();

To go directly to the page where the scoreboard is, just follow this link:

f’https://sports.whcdn.net/scoreboards/app/football/index.html?eventId={match_id}&sport=football&locale=en-gb&streamingAvailable=false&showSuggestions=true&expandDetails=true&showStreaming=false&referrer=https%3A%2F%2Fsports.williamhill.com’

You just need to change the match_id by the id of any live match

enter image description here

Ex: https://sports.whcdn.net/scoreboards/app/football/index.html?eventId=**28174073**&sport=football&locale=en-gb&streamingAvailable=false&showSuggestions=true&expandDetails=true&showStreaming=false&referrer=https%3A%2F%2Fsports.williamhill.com

P.S. I know how to use Selenium and I’ve written code with it that was very slow. Now I’m looking for other ways to make this request

What data type is [ a: [ 100, 360 ] ] in JavaScript?

I have a program in JavaScript where I have an array and I render a page using Express.JS and show the array as a local variable.
The problem is whenever I try stringifying this array it doesn’t work.
Then I realised that the so-called array ([ a: [ 100, 360 ] ]) is not even an array.
What data type is this and how can I stringify it without it being “”.

I used JSON.stringify() to turn it to a string, but it showed up as an empty string.
I also used .toString() and that also showed up as an empty string.

Problem saving attachment in azure blob storage

I have a problem with the code because the first java script function displays the selected attachment and the second function connects to the method that is supposed to save the attachment in the blob sotrage
javascript function

<div class="file-input-container">
        <label for="fileInput" class="file-label">Wybierz załącznik</label>
        <br />
        <input type="file" id="fileInput" class="file-input" name="file" />
        
    </div>

    <ul id="attachment-list"></ul>
    <hr />
    <script>
        const fileInput = document.getElementById('fileInput');
        const attachmentList = document.getElementById('attachment-list');
        let selectedAttachments = [];

        fileInput.addEventListener('change', handleFileUpload);

        function handleFileUpload(event) {
            const file = event.target.files[0];
            const fileName = file.name;
            const fileType = file.type;

            const reader = new FileReader();
            reader.onload = (e) => {
                const fileContent = new Uint8Array(e.target.result);
                const attachment = {
                    name: fileName,
                    content: fileContent,
                    type: file.type
                };
                selectedAttachments.push(attachment);
                saveAttachmentsToServer(selectedAttachments);
            };
            reader.readAsArrayBuffer(file);


            const listItem = document.createElement('li');
            listItem.classList.add('attachment-item');

            const attachmentName = document.createElement('span');
            attachmentName.classList.add('attachment-name');
            attachmentName.textContent = fileName;

            const attachmentDelete = document.createElement('span');
            attachmentDelete.classList.add('attachment-delete');
            attachmentDelete.addEventListener('click', () => {
                listItem.remove();
            });

            listItem.setAttribute('data-name', fileName);
            listItem.setAttribute('data-type', file.type);

            listItem.appendChild(attachmentName);
            listItem.appendChild(attachmentDelete);
            attachmentList.appendChild(listItem);
         

            event.target.value = '';
        }
        function saveAttachmentsToServer(attachments) {
            
            $.ajax({
                url: "?handler=SaveAttachments&attachments=" + JSON.stringify({ attachments: attachments }),
                success: function () {
                    console.log('Załączniki zapisane');
                },
                error: function (error) {
                    console.error('Wystąpił błąd podczas zapisu załączników', error);
                }
            });
        }
    </script>

C# function

        public async Task<IActionResult> OnGetSaveAttachments(List<AttachmentData> attachments)
        {
            foreach (var attachmentData in attachments)
            {
                var attachmentContent = attachmentData.Content;
                if (attachmentContent != null && attachmentContent.Length > 0)
                {
                    string attachmentName = attachmentData.Name;
                    string attachmentType = attachmentData.Type;

                    string blobName = Guid.NewGuid().ToString();

                    BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
                    BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);
                    BlobClient blobClient = containerClient.GetBlobClient(blobName);

                    await blobClient.UploadAsync(attachmentContent, overwrite: true);

                    // Zapisz informacje o załączniku w bazie danych lub innym miejscu, np. na podstawie identyfikatora

                    Console.WriteLine("Załącznik zapisany: " + attachmentName);
                }
                else
                {
                    Console.WriteLine("Błąd: Brak zawartości załącznika.");
                }
            }
            return Page();
        }
    }

    public class AttachmentData
    {
        public string Name { get; set; }
        public Stream Content { get; set; }
        public string Type { get; set; }
    }

why in the method a attachment is always found count 0 how can it be done better