3JS – Create Table, How to attach legs

    import * as THREE from 'three';

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(80, window.innerWidth / window.innerHeight, 1, 10000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

const geometry = new THREE.BoxGeometry(8, 0.5, 4);

// Correcting texture loading
const textureLoader = new THREE.TextureLoader();
const texture = textureLoader.load('http://localhost:3000/wood-texture-vector-eps10-illustration-600nw-206847232.webp');
const material = new THREE.MeshBasicMaterial({ map: texture });

const cube = new THREE.Mesh(geometry, material);


const legGeometry = new THREE.BoxGeometry(0.4, 4, 0.4);

const cubeLeg = new THREE.Mesh(legGeometry, material);



scene.add(cube);
scene.add(cubeLeg);
cubeLeg.position.x=12;
scene.add(cubeLeg);
cubeLeg.position.x=-12;
scene.add(cubeLeg);
cubeLeg.position.x=6;
scene.add(cubeLeg);
cubeLeg.position.x=-6;

camera.position.x = 2;
camera.position.y = 4;
camera.position.z = 13;

function animate() {
    requestAnimationFrame(animate);

     //cube.rotation.x += 0.01;
     //cube.rotation.y += 0.01;

    renderer.render(scene, camera);
}

animate();

The four legs should be part of table, and I think should not be added to scene like its added.

Also what is good way to create new instances of legs and attach them. and the attachment should be such that the back side legs should look smaller than front. Current I am seeing only single leg, instead of 4.

If you run this code in your local you will know what I am asking.

Unable to move points inside a polygon when dragging the polygon with OpenLayers Translate Interaction

I am working with a map application using OpenLayers and I’ve encountered an issue with moving points inside a polygon using the Translate Interaction.

I have an array of points and a polygon, all represented as Features on the map. My goal is to have all the points inside the polygon move the same distance as the polygon when it is dragged. Here is the code snippet I am using to attempt this:

if (feature.getProperties().gisObjectMetaDto.objTypeCd === '04') {
    var translateInteraction = new Translate({ features: new Collection([feature]) });
    //find point constraints with polygon
    const objCd = feature.getProperties().gisObjectMetaDto.objCd;
    const objectConstraint = globalContext['objInstRel'].filter((o) => o.trgtObjCd === objCd && o.gisObjectMetaDto.useYn === 'Y').map((item) => item.gisObjectMetaDto.objCd);

    let ListPoints = [];
    FeatureApis.findPointInsidePolygon(feature.getProperties().polygonObjectDto.objId, objectConstraint).then((res) => {
        res.forEach((o) => {
            if (o.geometry != null) {
                o.geometry = JSON.parse(o.geometry);
                const feature = new Feature({
                    geometry: new Point(o.geometry.coordinates),
                    properties: o.properties,
                });
                feature.setId(o.id);
                const layer = getLayerByName(o.properties.gisObjectMetaDto.objCd);
                if (layer) {
                    layer.getSource().addFeature(feature);
                    feature.set("layer", layer);
                    ListPoints.push(feature);
                }
            }
        });
    });

    translateInteraction.on('translatestart', function (event) {
        ListPoints.forEach(function (pointFeature) {
            var originalCoord = pointFeature.getGeometry().getCoordinates();
            pointFeature.set('originalCoord', originalCoord);
        });
    });

    translateInteraction.on('translating', function (event) {
        var deltaX = event.coordinate[0] - event.startCoordinate[0];
        var deltaY = event.coordinate[1] - event.startCoordinate[1];
        ListPoints.forEach(function (pointFeature) {
            var originalCoord = pointFeature.get('originalCoord');
            var newCoord = [originalCoord[0] + deltaX, originalCoord[1] + deltaY];
            pointFeature.getGeometry().setCoordinates(newCoord);
            console.log(pointFeature.getGeometry().flatCoordinates, 'newCoord');
        });
    });

    translateInteraction.on('translateend', function (event) {
        ListPoints.forEach(function (pointFeature) {
            pointFeature.unset('originalCoord');
        });
    });

    globalContext['map'].addInteraction(translateInteraction);
}

The issue I am facing is that when I perform the drag action on the polygon, the points inside do not move accordingly. I’ve checked to ensure that all points are accessible and there are no errors logged in the console.
Would anyone be able to provide guidance or suggestions on how to resolve this issue? Thank you!

AbortError Occurs When Calling google.accounts.id.prompt

I am implementing the Sign In With Google feature on a webpage, following the guidance on this page: https://developers.google.com/identity/gsi/web/reference/js-reference.

I wanted to make it so that when our custom-styled button is pressed, the Sign In With Google popup would appear. Thus, I’ve made it so that google.accounts.id.prompt is called upon button click as follows:

<html>
  <body>
    <script src="https://accounts.google.com/gsi/client" async></script>
    <script>
      function handleCredentialResponse(response) {
        console.log("Encoded JWT ID token: " + response.credential);
      }
      window.onload = function () {
        google.accounts.id.initialize({
          client_id: "XXXXXXXXX.apps.googleusercontent.com",
          callback: handleCredentialResponse
        });
        document.getElementById("buttonDiv").onclick = function() {
          google.accounts.id.prompt();
        };
      }
    </script>
    <div id="buttonDiv">test</div>
  </body>
</html>

Recently, I’ve noticed that this functionality has stopped working. When calling google.accounts.id.prompt, the following error message is outputted to the Dev Console, and the login popup does not appear:

[GSI_LOGGER]: FedCM get() rejects with AbortError: Request has been aborted.

I noticed this error on April 7 2024. I do not know when it started occurring, but as of March 20 2024, it was working without issues. Moreover, this issue occurs on Google Chrome, but not on Firefox.

Could there be any potential causes and solutions for this issue?

React Tanstact Table

I got a component for a datatable in react made with Tanstack Table. this is the code.

import React from "react";
import { useReactTable } from "@tanstack/react-table";
import data from "../../Utils/MOCK_DATA.json";

const SimpleTable = () => {
  const columns = [
    {
      Header: "Id",
      accessorKey: "id",
    },
    {
      Header: "Amount",
      accessorKey: "amount",
    },
    {
      Header: "Currency",
      accessorKey: "currency",
    },
    {
      Header: "Date",
      accessorKey: "date",
    },
  ];

  const table = useReactTable({ data, columns });

  return (
    <>
      <table>
        <thead>
          {
            table.getHeaderGroups().map(headerGroup => (
              <tr key={headerGroup.id} className="text-cyan-300">
                {
                  headerGroup.headers.map(header => (
                    <th key={header.id}>
                      {header.column.columnDef.header}
                    </th>
                    ))
                }
            </tr>
            ))
          }
        </thead>
        <tbody>
          <tr>
            <td>1</td>
          </tr>
        </tbody>
        <tfoot></tfoot>
      </table>
    </>
  );
};
export default SimpleTable;

when i start the server and call the component i get this error

Warning: Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.
at th
at tr
at thead
at table
at SimpleTable (http://localhost:5173/src/components/Tables/SimpleTable.jsx?t=1712628648080:34:19)
at App

Nested Dropdown opens automatically when I open parent dropdown

I created multilevel dropdown in bootstrap 5 but when i hover on parent dropdown it automatically child dropdown.

<li class="nav-item dropdown"><a class="nav-link" aria-expanded="false" data-bs-toggle="dropdown" href="#" style="color: rgb(255,255,255);font-size: 0.875rem;font-weight: bold;font-family: Roboto, sans-serif;text-align: center;">Canvas &amp;<br />Surfaces</a>
    <div class="dropdown-menu" style="border-radius: 0px;margin: 7px 0px 0px;">
        <div class="nav-item dropend"><a class="dropdown-toggle" aria-expanded="false" data-bs-toggle="dropdown" href="#">Dropdown </a>
            <div class="dropdown-menu"><a class="dropdown-item" href="#">First Item</a><a class="dropdown-item" href="#">Second Item</a><a class="dropdown-item" href="#">Third Item</a></div>
        </div><a class="dropdown-item" href="#">First Item</a><a class="dropdown-item" href="#">Second Item</a><a class="dropdown-item" href="#">Third Item</a>
    </div>
</li>

CSS

.dropdown:hover > .dropdown-menu {
  display: block;
  margin-top: 0.125em;
  margin-left: 0.125em;
}

.dropend:hover > .dropdown-menu {
  display: block;
  margin-top: 0.125em;
  margin-left: 0.125em;
}

@media screen and (min-width: 769px) {
  .dropend:hover > .dropdown-menu {
    position: absolute;
    top: 0;
    left: 100%;
  }
}

@media screen and (min-width: 769px) {
  .dropend .dropdown-toggle {
    margin-left: 0.5em;
  }
}


I want to create a multilevel dropdown which opens on hover.

why the console.log(score.textcontent) does not print to the console when I click the button?

    'use strict';
        let newGame = document.querySelector('.btn--new');
        let Score = document.querySelectorAll('.score');
        let currentScore = document.querySelectorAll('.current-score');

        function initializeGame() {
          for (let i = 0; i < Score.length; i++) {
             Score[i].textContent = '0';
             console.log(Score[i].textContent);
      }
    }

    newGame.addEventListener('click', initializeGame);

    <html>
      <body>
           <h2 class="name" id="name--0">Player 1</h2>
            <p class="score" id="score--0">43</p>
            <h2 class="name" id="name--1">Player 2</h2>
            <p class="score" id="score--1">24</p>
          <button class="btn btn--new">New game</button>
        <script src="script.js"></script>
      </body>
    </html>

// when i press the new game button it does not print the context of the paragraph with score class in it

Tailwind CSS Responsive Design

I am currently doing a web design challenge. I am using REACT and Tailwind CSS for styling.

enter image description here

I am basically making a responsive page, the image shows the layout of how the final product should look like.

So far this is what i have, the large screen layout I was able to work but I have problems with the smaller/medium screen sizes.

This is what I have right now for the medium screen which is wrong

and here is my code(this is the page file, i have split up the components):

Anyone have any ideas? I have tried using breakpoints but its messing up.

Deleting an element inside an Iframe that is using an external website. HTML, JS/Jquery

For example, I have an iframe in which id="myFrame" and src="https://google.com".
How can I remove/hide the google logo image using javascript or jquery. The id of the Google logo image is "hplogo". I also don’t know if this is possible or not.

I used this code to try to delete the logo image, however did this didn’t work:

$("#myFrame").contents().find($("#hplogo")).remove()

How can I fix this?

Why my method not returning the string with char case toggled

This is my method, it was returning the same string as the input.
for ex: toggleEveryCharCases(‘character’) => ‘character’

Please answer me guys…

export function toggleEveryCharCases(str: string): string {
  const strArr = str.split('');

  for (let i = 0; i < strArr.length; i++) {
    if (strArr[i] >= 'A' && strArr[i] <= 'Z') strArr[i] = strArr[i].toLowerCase();
    else if (strArr[i] >= 'a' && strArr[i] <= 'z') strArr[i] = strArr[i].toUpperCase();
  }

  return strArr.join('');
}

I have tried my best. I want to get the char case togggled string

confused by CSS precedence

I have 2 css rule sets applying to a cell of a table. I thought one set of rules would override the other, but it is picking and choosing some from each. the rules contradict each other.

the html is generated by javascript

const toDoArray = {
  test: true,
}

var toDoElements = "<table style="width: 100%;">";

for (var k in toDoArray) { // Loop through the object
  var trS = "";
  if (toDoArray[k]) {
    trS = `class="taskChecked"`
  }
  toDoElements +=
    `<tr ${trS} id="${k}-tr">
      <td onclick="checkOffToDo('${k}')" id = "${k}-td" border=none > ${k}</td>
      <td onclick="removeToDo('${k}')" class="toDoDeleteButton">&times;</td>     
    </tr>`
}

toDoElements += "</table>";

document.getElementById("toDoList").innerHTML = toDoElements;
#toDoList { width: 200px; font-size: 3rem; }

.taskChecked {
  text-decoration: line-through;
  text-decoration-color: violet;
  color: purple;
  background: orange;
}

.toDoDeleteButton {
  border: none;
  width: 8%;
  height: auto;
  text-decoration: none !important;
  text-decoration-color: aqua;
  color: yellow;
  background-color: blue;
}
<div id="toDoList"></div>

A yellow "x" with a violet strikethrough on a blue background

I found this StackOverflow Answer describing precedence (https://stackoverflow.com/a/25105841), but this doesn’t seem follow it.
If it followed all one, or all the other, I thought I could get it to work right, but now I’m just really confused.

My chief aim is to not give it a line through. the rest of the colors and stuff are me testing options trying to figure out what’s going on, and why its not working.

This is in Chrome.

JavaScript fetch() Syntax Error: “missing ) after argument list”

I’m encountering a “missing ) after argument list” error in my JavaScript code when trying to use the fetch() function to retrieve JSON data. Despite thorough review, I can’t pinpoint the source of the issue. Here’s the relevant code snippet:

fetch(myString)
  .then(response => response.json())
  .then(data => {
    initializeChat(data.chatMessages);
  })
  .catch(error => console.error("Failed to load chat messages:", error));

Prevent user from unselecting option in selectizeInput

The default behavior for selectizeInput allows the user to click on a choice and delete it by hitting the Backspace or Delete key.

Is there any way of disabling that behavior?.

I have an app that allows users to add and remove groupings from the selectizeInput via ‘add’ and ‘remove’ action buttons. I don’t want users to remove choices with the selectizeInput widget but rather by using the ‘remove’ action button.

Why angular (or perhaps any UI framework) rounds incorrectly?

So I detected this in angular, but then I’m trying the chrome console like this and I get the same problem. Can somebody explain why this happens?

Open console in your browser and type: 14.9 divided by 100

Result: 0.149 which is ok

enter image description here

Now, do the opposite:
0.149 x 100 it should be 14.9 right?!

enter image description here

Well no, you get 14.8999999999999999999 instead….

In C# this is clear for me, some data types (decimal vs double) has a binary calculation that could lead to precision loss, but here I’m not able to pick another numeric type rather than NUMBER, so what can I do to have precision in these cases?

How to implement *paginated* fuzzy matching on a Trie data structure (in JavaScript or TypeScript)?

I asked how to paginate a trie a while back, and got this elegant and simple Trie structure in the answer:

class TrieNode {
  constructor(key) {
    // the "key" value will be the character in sequence
    this.key = key;

    // we keep a reference to parent
    this.parent = null;

    // we have hash of children
    this.children = {};

    // check to see if the node is at the end
    this.end = false;

    // count how many words are at this node or below.
    this.count = 0;

    // Ensure children are in the right order.
    this.lastChildKey = '';
  }

  getWord() {
    let output = [];
    let node = this;

    while (node !== null) {
      output.unshift(node.key)
      node = node.parent
    }

    return output.join('')
  }
}

class Trie {
  constructor() {
    this.base = new TrieNode(null)
  }

  insert(word) {
    let node = this.base

    const points = Array.from(word)

    for (const i in points) {
      const point = points[i]
      node.count++
      if (!node.children[point]) {
        const child = node.children[point] = new TrieNode(point)
        child.parent = node
      }

      node = node.children[point]

      if (i == word.length - 1) {
        node.end = true
      }

      // If words were inserted out of order, fix order of children.
      if (node.lastChildKey <= point) {
        node.lastChildKey = point
      }
      else {
        // Need to fix order of children.
        let keys = Object.keys(node.children)
        keys.sort()
        let orderedChildren = {}
        for (const key in keys) {
          orderedChildren[key] = node.children[key]
        }
        node.children = orderedChildren
      }
    }
  }

  contains(word) {
    let node = this.base

    const points = Array.from(word)

    for (const i in points) {
      const point = points[i]

      if (node.children[point]) {
        node = node.children[point]
      } else {
        return false
      }
    }

    return node.end;
  }
  find(prefix, startAt, maxCount) {
    let node = this.base
    let output = []

    const points = Array.from(prefix)

    for (const i in points) {
      const point = points[i]

      // make sure prefix actually has words
      if (node.children[point]) {
        node = node.children[point]
      } else {
        // there's none. just return it.
        return output
      }
    }

    const stack = [node]
    while (stack.length) {
      if (maxCount <= output.length) {
          return output
      }
      node = stack.shift()
      if (node.count < startAt) {
        startAt -= node.count
      }
      else {
        // base case, if node is at a word, push to output
        if (node.end) {
          if (0 < startAt) {
            startAt--;
          }
          else {
            output.push(node.getWord())
          }
        }

        // iterate through each children, call recursive findAllWords
        for (var child in node.children) {
          stack.push(node.children[child])
        }
      }
    }

    return output
  }
}

You can use it like this:

const fs = require('fs')
const Trie = require('./Trie')

const words = fs.readFileSync('tmp/scrabble.csv', 'utf-8')
  .trim()
  .split(/n+/)
  .map(x => x.trim())

const trie = new Trie.Trie()

words.forEach(word => trie.insert(word))

console.log(trie.find('a', 0, 12))

console.log(trie.find('a', 6, 6))

Asking AI about fuzzy string matching on Tries, they gave this implementation:

class TrieNode {
    children: Map<string, TrieNode> = new Map();
    isEndOfWord: boolean = false;
    word: string | null = null; // To store the word at leaf nodes
}

class Trie {
    root: TrieNode = new TrieNode();

    insert(word: string) {
        let node = this.root;
        for (const char of word) {
            if (!node.children.has(char)) {
                node.children.set(char, new TrieNode());
            }
            node = node.children.get(char)!;
        }
        node.isEndOfWord = true;
        node.word = word; // Store the complete word at the end node
    }

    fuzzySearch(query: string): {word: string, score: number}[] {
        let results: {word: string, score: number}[] = [];
        // Initial call with max distance, here it's set to a portion of the query length for flexibility
        const maxDistance = Math.floor(query.length / 2); 
        this.searchRecursive(this.root, query, "", 0, maxDistance, results);
        // Sort results based on score, higher first
        return results.sort((a, b) => b.score - a.score);
    }

    private searchRecursive(node: TrieNode, query: string, currentWord: string, currentScore: number, maxDistance: number, results: {word: string, score: number}[]): void {
        if (query.length === 0 || node.isEndOfWord) {
            let finalScore = currentScore;
            if (node.word) {
                // Adjust score based on the length difference, assuming a penalty for each missing character
                finalScore -= Math.abs(node.word.length - currentWord.length) * 5;
                if (query.length === 0 && node.isEndOfWord) {
                    results.push({ word: node.word, score: finalScore });
                }
            }
        }

        if (maxDistance < 0) return; // Stop if max edits exceeded

        for (let i = 0; i < query.length; i++) {
            const char = query[i];
            if (node.children.has(char)) {
                // Exact match, continue with the rest of the query
                const nextNode = node.children.get(char)!;
                this.searchRecursive(nextNode, query.substring(i + 1), currentWord + char, currentScore + 10, maxDistance, results);
            }

            // Edit operations with penalties
            node.children.forEach((childNode, childChar) => {
                // Substitution (replace char)
                if (childChar !== char) {
                    this.searchRecursive(childNode, query.substring(i + 1), currentWord + childChar, currentScore - 5, maxDistance - 1, results);
                }

                // Insertion (add a char)
                this.searchRecursive(childNode, query.substring(i), currentWord + childChar, currentScore - 5, maxDistance - 1, results);
            });

            // Deletion (skip a char in query)
            this.searchRecursive(node, query.substring(i + 1), currentWord, currentScore - 5, maxDistance - 1, results);
            break; // Only apply one edit per recursion level
        }
    }
}

// Example enhanced usage
let trie = new Trie();
trie.insert("VisualStudioCode");
trie.insert("VisualStudioCommunity");
trie.insert("VerySimpleCode");
trie.insert("VisualSpaceCoordinator");

const searchResults = trie.fuzzySearch("VSC");
console.log(searchResults);

If you implement “pruning” of the scored results (sorted by score), how can you also implement pagination, without going through the entire set of trie nodes? That is, say I want to return 100 results, if I use the second Trie example, it will return possibly 1000’s of results (assuming a large dictionary like the 100k+ scrabble dictionary, or a million word dictionary). Then I can paginate those results, but that is a waste of computational effort. How can you avoid processing all the nodes in the trie, while implementing VSCode-like fuzzy text matching (with scoring), AND implementing pagination, where you can jump to a specific page and get say 100 nodes from that point forward?

Note: It appears to get really high quality fuzzy matching you need machine learning, AI, and user data input (like most recently accessed files, for VSCode), etc.. I don’t intend on creating the perfect paginated fuzzy matching Trie out there, just something that works reasonably well with your standard algorithms. Just not sure yet how / if it’s possible to combine pagination with the fuzzy matching scoring aspect, on a Trie.

Sending data to API, getting CORS error on preflight using XHR

I am currently trying to send data to an API on a subdomain, but it is failing.

In devtools I can see there is a CORS error relating to a redirect:

Access to XMLHttpRequest at 'https://api.example.com/v1/dashboard/images/upload.php' from origin 'https://example.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

I assume the redirect is caused by lack of credentials even though I have withCredentials on my xhr object:

let endpoint = form.action,
    xhr = new XMLHttpRequest();

xhr.open('POST', endpoint);
xhr.withCredentials = true;

xhr.upload.addEventListener('progress', ({loaded, total}) => {
    ... stuff here ...
});

let data = new FormData(form);
xhr.send(data);

My API has these headers set in the Nginx config:

add_header "Access-Control-Allow-Origin" "https://example.com" always;
add_header "Access-Control-Allow-Credentials" "true";

Other APIs in use work fine but use fetch rather than XHR – the reason for using XHR for this request is I want to feedback to the user upload progress, which I understand isn’t a feature of fetch?