d3 json resulting in empty svg tag

I am trying to plot data from a geojson file inside an svg using d3. But I am getting a blank image. Developer tools shows that the geojson file was loaded but the svg element is empty

var svg = d3.select("#mainSvg");
        var projection = d3.geoMercator();
        var path = d3.geoPath().projection(projection);
        d3.json("static/geojson/roads.geojson").then(function(geojson) {
            svg.selectAll("path")
               .data(geojson.features)
               .enter()
               .append("path")
               .attr("d", path)
               .style("fill", "steelblue");
            }).catch(err => {
                console.error(err)
            });

I ave to solve som issue about one of my javascript classes, it may concern an issue concerning about internal variables scoping…?

I just created a counter class that seems to work almost okay.
Unfortunately there is an issue that I cannot identify.
I instance my class twice with a different name but the parameters remain the same in terms of the chrono max limit.
Thanks to anyone who could help me…

I’m trying to create a class that can display a counter but there is a problem with the parameters. Of course I could just create a simple function instead but that’s not what I’m trying to do. I would like to stay in the same perspective if possible… Thanks to anyone who could help me…

I’ll let you look at the code a little further down.

document.addEventListener("DOMContentLoaded", (event) => {
  console.log("DOM fully loaded and parsed");
});

class SuperCounter {
  constructor(cumul, limit) {
    this.cumul = cumul;
    this.limit = limit;
  }
  add() {
    if (this.cumul === this.limit) {
      console.warn('Counter just reached to the limit');
      clearInterval(ignition)
    };
    return {
      result: this.cumul++,
      //limit: this.limit,
    }
  }
}

const firstCounter = new SuperCounter(1, 50);
const secondCounter = new SuperCounter(1, 150);

const ignition = setInterval(displayCounter, 100);

function displayCounter() {
  document.querySelector("#chrono1").innerHTML = /*html*/ `<h2>Chrono #1 : ${firstCounter.add().result}</h2>`
  document.querySelector("#chrono2").innerHTML = /*html*/ `<h2>Chrono #2 : ${secondCounter.add().result}</h2>`
};
<h3 id="chrono1"></h3>
<h3 id="chrono2"></h3>

don’t understanding why my cookie doesn’t appear

i can’t see my cookie with the dev tool and don’t understand if its because my cookie is poorly set up or it is because it is set up but at a place I can’t see
i try using the mehtode of res.setHeader but I didnt work either so I run out of option know fore me

const express = require("express");
const cookieParser = require("cookie-parser");
const path = require("path");
const { createClient } = require("@supabase/supabase-js");
const { createServer } = require("node:http");
const { join } = require("node:path");
const { Server } = require("socket.io");
var cors = require("cors");
const { error } = require("console");

const app = express();
const server = createServer(app);
const io = new Server(server);

const supabaseUrl = "myurl";
const supabaseKey = "mykey";
const supabase = createClient(supabaseUrl, supabaseKey);

const port = process.env.PORT || 5000;
const corsOptions = {
    origin: "http://localhost:3000",
    optionsSuccessStatus: 200,
};

app.use(cookieParser());
app.use(cors(corsOptions));
app.use(express.json());

async function authenticate(userIdFromCookie) {
    console.log("appelle de la fonciton authenticate");
    if (userIdFromCookie !== undefined) {
        console.log("User ID found in cookie:", userIdFromCookie);
        return true;
    } else {
        return false;
    }
}

app.post("/chat", async function (req, res) {
    try {
        const userId = req.body.userId;
        const isAuthenticated = await authenticate(userId);
        if (!isAuthenticated) {
            const { data, error } = await supabase.from("post").select();
            if (error) {
                return res.status(500).json({
                    error: `Error fetching data from Supabase`,
                });
            }
            res.cookie("userId", 3);
            console.log("cookie setup");
            return res.json(data);
        } else {
            return res
                .status(500)
                .json({ error: "activer les cookies ou recharger la page svp" });
        }
    } catch (err) {
        console.error(err);
        res.status(500).json({ error: "Internal Server Error" });
    }
});

Vue 3 creating completely custom checkbox and a radio group wrapper

I have been trying to create a completely custom checkbox/radio group component that does not depend on the native/vue input elements. One reason to have complete freedom of styling it, second for learning purposes. (Vue 3)

It should work similary to what the vue checkbox provides, so that:

a) I can bind the v-model to an array of selected values: ["1", "2", "3"]

<checkbox value="1" v-model="selected"></checkbox>
<checkbox value="2" v-model="selected"></checkbox>
<checkbox value="3" v-model="selected"></checkbox>

b) I can bind it to a v-model boolean:

<checkbox v-model="checked"></checkbox>

My checkbox implementation while not the prettiest seems to work ok (barring any edge cases).

//<Checkbox> component
import {defineComponent} from 'vue';

export default defineComponent({
    props: {  
        value:          {type: null, default: null},
        modelValue:     {type: [Array,Boolean], default: () => []}, 
    },
    emits: ['update:modelValue'],  
    data() { 
        let _checked;
        if (typeof this.modelValue == 'boolean') {
            _checked = this.modelValue == true;
        } else { 
            _checked = this.modelValue.indexOf(this.value) != -1;
        } 
        return {
            checked: _checked
        }
    },
    computed: { 
        class() {
            return {'checked': this.checked}
        },  
    },
    watch: { 
        modelValue: {  
          deep: true,
          handler(newv, oldv) {    
              if (typeof newv == 'boolean') {
                  this.checked = newv == true;
              } else { 
                  if (newv) {  
                      this.checked = newv.indexOf(this.value) != -1;
                  }
              }
            }
        },
        value(newv, oldv) {
           if (newv == oldv) return;
           let arr = [...this.modelValue];
           let idx = arr.indexOf(oldv);
           if (idx != -1) {
                arr[idx] = newv;
           }
           this.$emit("update:modelValue", arr);
         }, 
         checked(newv, oldv) {  
             if (newv == oldv)  return;
             if (typeof this.modelValue == 'boolean') {
                this.$emit("update:modelValue", newv);
             } else {
                let arr = [...this.modelValue];
                if (newv) {
                    arr.push(this.value);
                } else {
                    arr.splice(arr.indexOf(this.value), 1);
                }
                this.$emit("update:modelValue", arr);
            } 
         }
    }
})
</script>

<template>
    <div @click.stop="checked = !checked" :class="this.class">  
        <slot></slot>
    </div> 
</template>

Now, with the checkbox working I wanted to have a way to provide a radio like functionality so only one component can be checked at a time. My idea was to wrap it in a parent component that will orchestrate it, like so:

<group v-model="selected">
    <checkbox value="1"></checkbox>
    <checkbox value="2"></checkbox>
    <checkbox value="3"></checkbox>
</group>

First thing, I need to have a way for the individual checkboxes to register with the group component. I achieved it with using provide and inject.

//<Group> component
export default defineComponent({
    props: {
        modelValue: { type: [Boolean, Array], default: () => []}
    },
    provide() {
        // provide this instance to the child checkbox components
        return {
            'group': this
        }
    },
    data() {
        return {
            checkboxes: []
        }
    },
    mounted() { 
           // got this.checkboxes filled with <checkbox> components at this point
    }, 
});

In the child checkboxes components, I have added code to receive the injected group component and register the component with the parent.

//rest of <checkbox> component code...
inject: ['group'],
mounted() {
    this.group.checkboxes.push(this);
}
//...rest of <checkbox> component code... 

Now at this stage I am pretty much stuck. My <Group> component has all the available child <Checkbox> components in it’s mounted lifecycle. But I have no idea how can I register for the <checkbox> events or how to pass a modelValue. There is no API for listening to events, and I can’t pass the Groups component modelValue to a checkbox.

//<Group component 
props: {
    modelValue: {type: [Boolean, Array], default: () => []}
},
mounted() {
  // can't set the modelValue like this on each checkbox, props are readonly!
  //for(let checkbox of this.checkboxes) {
  //   checkbox.modelValue = this.modelValue;   
  //}
  // no `$on` event listener available in Vue 3!
  //for(let checkbox of this.checkboxes) {
  //      checkbox.$on("update:modelValue", () => {
  //               //do something with it...
  //      });
  //}
}

Null is popping up when it shouldn’t be

New JavaScript coder here, self taught. Learning for fun and very confused along the way.

Anyway when I check my code on the browser, “null” comes up for “computerSelection”. Here is my code:

    let choices = ["Rock", "Paper", "Scissors"];

    function getComputerChoice(){
    let choice = choices[Math.floor(Math.random())];
    let computerSelection = (choices[choice]);
    return computerSelection
    }

How do I go about doing this properly so that it works?

I tried programming it in the way I thought was correct with variables in the function and I expected it to return a choice of rock, paper or scissors. Instead, all I get is “null” :/

How to maintain the scroll position when i closes the pop up container

when i click the close button in the pop up container the scroll position goes back at the top

this is my html code for the pop up container

<div id="popup-container" class="popup-container">
            <div class="popup-content">
            <!-- Add content for exercises -->
            <h3 id="popup-title">Exercise Details</h3>
            <p id="Exercise1"></p>
            <p id="Exercise2"></p>
            <p id="Exercise3"></p>
            <p id="Exercise4"></p>
            <p id="Exercise5"></p>
            <p id="Exercise6"></p>
            <!-- Close button -->
            <a href="#" class="close-btn" onclick="closePopup()">Close</a>
            </div>
        </div>
var scrollPosition;

function openPopup(title, Exercise1, Exercise2, Exercise3, Exercise4, Exercise5, Exercise6) {
    // Save the current scroll position
    scrollPosition = window.scrollY || window.pageYOffset || document.documentElement.scrollTop;

    // Set the content of the popup
    document.getElementById('popup-title').textContent = title;
    document.getElementById('Exercise1').textContent = 'Exercise: ' + Exercise1;
    document.getElementById('Exercise2').textContent = 'Exercise: ' + Exercise2;
    document.getElementById('Exercise3').textContent = 'Exercise: ' + Exercise3;
    document.getElementById('Exercise4').textContent = 'Exercise: ' + Exercise4;
    document.getElementById('Exercise5').textContent = 'Exercise: ' + Exercise5;
    document.getElementById('Exercise6').textContent = 'Exercise: ' + Exercise6;

    // Display the popup
    document.getElementById('popup-container').style.display = 'flex';

    // Add an event listener to track changes in the scroll position
    window.addEventListener('scroll', handleScroll);
}

function closePopup() {
    // Hide the popup
    document.getElementById('popup-container').style.display = 'none';

    // Remove the scroll event listener
    window.removeEventListener('scroll', handleScroll);
}

function handleScroll() {
    // Restore the scroll position
    window.scrollTo(0, scrollPosition);
}

this is my javascript for my pop up container

I want that wehn i close the button, it stays at its scroll position

Lambda & fetch w/ signal timeout not timing out

Trying to get to the bottom of this problem. I’ve got a lambda function that is just supposed to fire off a fetch request to an arbitrary invalid URL from an SQS record. Occasionally the ‘fetch’ will hang for about ten seconds, even though the code is demanding that it cut it off at one second. Most of the time though it works as intended. Attached:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.handler = void 0;
require("dd-trace/init"); //Needs to come before any instrumented code
const handler = async (event) => {
    const failures = [];
    for (const r of event.Records) {
        let webhookMessage;
        try {
            webhookMessage = JSON.parse(r.body);
        }
        catch (e) {
            console.log("Error in parsing body", r);
        }
        if (!webhookMessage) {
            failures.push({
                itemIdentifier: r.messageId,
            });
            continue;
        }
        try {
            console.time("fetch_url");
            console.log("Fetching URL: ", webhookMessage.configuration.url);
            const res = await fetch(webhookMessage.configuration.url, {
                method: "POST",
                body: JSON.stringify(webhookMessage.data),
                signal: AbortSignal.timeout(1000),
            });
            if (!res.ok) {
                console.log("URL fetch failed: ", res.status);
                failures.push({
                    itemIdentifier: r.messageId,
                });
            }
        }
        catch (e) {
            console.log("URL fetch failed without response: ", e);
            failures.push({
                itemIdentifier: r.messageId,
            });
        }
        console.timeEnd("fetch_url");
    }
    return {
        batchItemFailures: failures,
    };
};
exports.handler = handler;

Since this is a lambda I’ve got limited insights, but the logs show (cleaned up)…

Fetching URL:  http://174.129.145.242/
URL fetch failed without response:  TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:11730:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async handler (/var/task/index.js:30:25) {
  cause: ConnectTimeoutError: Connect Timeout Error
      at onConnectTimeout (node:internal/deps/undici/undici:6869:28)
      at node:internal/deps/undici/undici:6825:50
      at Immediate._onImmediate (node:internal/deps/undici/undici:6857:13)
      at process.processImmediate (node:internal/timers:476:21)
      at process.callbackTrampoline (node:internal/async_hooks:128:17) {
    code: 'UND_ERR_CONNECT_TIMEOUT'
  }
}
fetch_url: 10.262s //<- this is the amount of time the console.time -> console.timeEnd took, in case it wasn't obvious

I thought this might have had something to do with the datadog integration, but I just verified it was happening before we added that – just so happened that the integration helped show that the hang was happening on the fetch, which led to additional commenting and such.

Typescript: Reduce computational complexity of types

I am working on a API for a library and I am using types that infer the keys of objects to a string and pick those back based on it. I was able to achieve it thanks to this and this threads, that I used as a starting point. Basically, given the following object

interface Obj {
  prop0: string;
  prop1: {
    prop2: {
      prop3: {prop4: "I am excluded"; prop5: string}[]
    };
    prop6: "I am excluded";
  };
  prop7: "I am excluded";
}

I am able to write a function like this

getAttributes(["prop0", "prop1.prop2.prop3[0].prop5"])

That returns

{
  prop0: string;
  prop1: {
    prop2: {
      prop3: [{prop5: string}?]
    }
  }
}

This is very nice and handy typing to have, BUT it is also very heavy. Using this with more intersections and unions gets to the point that sometimes the Language server crashes/hangs in IDEs (VSCode) and I am working on a relatively powerful machine. I am sure there is something that could be done to slim down those type I am using and get some performance benefit, but I don’t seem to find a way to do it. Here is what my code looks like:

type Divider<T> = T extends unknown[] ? `[${number}]` : ".";

type Paths<T> = T extends Record<string, unknown>
  ? {[K in keyof T]: `${Exclude<K, symbol>}${"" | `${Divider<T[K]>}${Paths<T[K]>}`}`}[keyof T]
  : T extends (infer X)[]
    ? "" | `${Divider<X>}${Paths<X>}`
    : never;

type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (k: infer I) => void ? I : never;

type DeepPick<TObject, TKey extends string> = UnionToIntersection<TObject extends object
  ? TKey extends `${infer Head}.${infer Tail}` | `${infer Head}[${number}].${infer Tail}`
    ? {
      [P in Head & keyof TObject]: TObject[P] extends (infer A)[]
        ? [DeepPick<A, Tail>?]
        : DeepPick<TObject[P], Tail>
    }
    : TKey extends `${infer Head}[${number}]`
      ? {
        [P in Head & keyof TObject]: TObject[P] extends (infer A)[] ? [A?] : never
      }
      : TKey extends keyof TObject
        ? Pick<TObject, TKey>
        : never
  : TObject>;

declare function getAttributes<T, P extends Paths<T>>(attributes: P[]): DeepPick<T, P>;

playground link.

Consider that the function signature above is heavily simplified. In my actual getAttributes function I pass further computed and conditional types to Paths and DeepPick that I didn’t include to avoid making the reading even more complex. I want to add that I am not getting excessive type instantiation or too complex errors. This works, but I can feel (and sometimes see) the compiler struggling with it, with random crashes.

Trying to make a javascript bookmark to add date of last sunday and date of next saturday

Im trying to make a javascript booklet and the web address stays mostly constant, just the date changes

I HAVE THIS by adapting an old bookmark to work for this:

javascript:function url(){          
var date = new Date();                
var m = date.getMonth()+1;         
var d = date.getDate();     
var y = date.getYear();   
var h = date.getHours();   
var hs = date.getHours()-1;      
if(m < 10){m = '0' + m;}         
if(d < 10){d = '0' + d;}          
return 'XXXXXX'+ y +'-' + m + '-' + d + 'XXXXX' + y + '-' + m + '-' d + 'xxxxxx';  } window.open(url(),"_parent");

I need the output to be EXAMPLE: website.com/2024-02-04/info/2024-02-10/stuff
where the only things that need to be updated are the dates and if they can auto load this weeks first day of the week (sunday) and this weeks last day of the week (saturday)

javascipt and booklets are new to me so please forgive my knowledge gaps

How to access a common object or variable in different files in ts (next.js)?

I use Next.js. I have one file with code:

export let counter = 0;

In the first file of api route /api/test1 I add number to counter:

counter += 5;

In the seconds file of api /api/test2 I want to get updated a value of counter:

console.log('counter', counter); // 5

But I get 0;

How can I get the current counter value in seconds file?

p.s. I simplified the task, using the example of a counter.

Trouble Displaying Tube Geometry in Three.js

I’m new to Three.js and I’m having trouble getting a tube to show up on the screen. I’m using a basic material to keep the lighting simple, but it’s not working. Can someone help me figure out why it’s not appearing?

const scene = new THREE.Scene()

var points = []
for (var i = 0; i<5; i++){
    points.push(new THREE.Vector3(0,0,2.5*(i/4)))
}
var   = new THREE.CatmullRomCurve3(points)

var tubeGeometry = new THREE.TubeGeometry(curve, 70, 10, 50, false);

var tubeMaterial = new THREE.MeshBasicMaterial({ color: 0xff0000 });
console.log(tubeMaterial)

// Create a mesh based on tubeGeometry and tubeMaterial
var tube = new THREE.Mesh(tubeGeometry, tubeMaterial);
console.log(tube)
// Add the tube into the scene
scene.add(tube);

/**
 * Sizes
 */
const sizes = {
    width: window.innerWidth,
    height: window.innerHeight
}

var light = new THREE.HemisphereLight( 0xffffbb, 0x887979, 0.9);
scene.add( light );

const camera = new THREE.PerspectiveCamera(75, sizes.width / sizes.height)
camera.position.set(0, 0, 10);
scene.add(camera)

/**
 * Renderer
 */
const renderer = new THREE.WebGLRenderer({
    canvas: canvas
})

renderer.setSize(sizes.width, sizes.height)
renderer.setClearColor(0x8FBCD4);

renderer.render(scene, camera)

Initially I was trying with a texture on the standard material but I switched to basic material for simplification.

Dynamic list not displaying data

I have included a search bar in my wordpress site using html, css, php and js code to parse and extract data from a two-column csv file. The data is text: first column, company stock ticker; second column, company name. The livesearch works and displays matching data in the browser console but fails to display it in a drop down menu beneath the search bar. Instead the conditional logic in the js file reports that:

Received data: {success: true, data: Array(9)}
HR_livesearch.js?ver=1.0.0:14 Type of data: object
HR_livesearch.js?ver=1.0.0:15 Data length: N/A
HR_livesearch.js?ver=1.0.0:36 No data to display, hiding results.
HR_livesearch.js?ver=1.0.0:12 Received data: {success: true, data: Array(1)}
HR_livesearch.js?ver=1.0.0:14 Type of data: object
HR_livesearch.js?ver=1.0.0:15 Data length: N/A
HR_livesearch.js?ver=1.0.0:36 No data to display, hiding results.

Here is the js code I am using:

document.addEventListener('DOMContentLoaded', function() {
    console.log("DOMContentLoaded event triggered.");
    const searchBox = document.getElementById('liveSearchBox');
    const resultsDiv = document.getElementById('searchResults');

    searchBox.addEventListener('input', function() {
        const searchText = this.value;
        if (searchText.length > 1) {
            fetch(tickerSearchData.ajaxurl + '?action=perform_live_search&search=' + encodeURIComponent(searchText))
            .then(response => response.json())
            .then(responseObject => {
                console.log("Received data:", responseObject); // Confirming the received data structure
                
                if (responseObject.success) {
                    console.log("Success flag is true.");

                    // Directly working with the data array
                    let data = responseObject.data;
                    if (data && Array.isArray(data) && data.length > 0) {
                        console.log("Data array is present and has length:", data.length);
                        resultsDiv.innerHTML = ''; // Clear previous results
                        resultsDiv.style.display = 'block'; // Ensure results div is shown

                        const ul = document.createElement('ul');
                        data.forEach(item => {
                            const li = document.createElement('li');
                            li.textContent = item; // Assuming 'item' is directly usable as text
                            ul.appendChild(li);
                        });
                        resultsDiv.appendChild(ul);
                    } else {
                        console.log("Data array is empty or not present.");
                        resultsDiv.style.display = 'none'; // Hide results div if no data
                    }
                } else {
                    console.log("Success flag is not true.");
                    resultsDiv.style.display = 'none';
                }
            })
            .catch(error => {
                console.error('Fetch error:', error);
                resultsDiv.style.display = 'none';
            });
        } else {
            resultsDiv.style.display = 'none';
        }
    });
});

I’ve replaced the dynamic segment with static data and the drop down menu appears with the expected list of static data items. There’s something in the dynamic conditional logic that is failing to recognize the presence of data in the array and I am at a loss as to what it might be. I am new to this, so forgive me if the answer is elementary.

how to change background color of the select box on select2 (bootstrap theme)

the javascript ofc

$(document).ready(function() {
          $('.js-example-basic-single').select2({
            theme: "bootstrap-5"
          });
       });

the HTML

<select class="js-example-basic-single bg-dark" style="background-color: #343a40 !         important;" name ="state"></select>

its missing just around the block, heres what it currently looks like. i just cant find the tag name to change the background color

Uncaught TypeError: Cannot read properties of null (reading ‘value’) getElementById

I’m getting this error when clicking on the button.

Uncaught TypeError: Cannot read properties of null (reading ‘value’)

What am I doing wrong? Here’s the code:

 <table>
                <tr>
                    <th>Height (inches)</th>
                    <th>Width (inches)</th>
                    <th>Length (inches)</th>
                    <th>Pieces</th>
                    <th>Bd Ft</th>
                    <th>Lineal Ft</th>
                    <th>Sqare Ft</th>
                </tr>
                <tr>
                    <td>
                        <input type="text" value="1" id="height" /></td>
                    <td>
                        <input type="text" value="1" id="width" /></td>
                    <td>
                        <input type="text" value="1" id="length" /></td>
                    <td>
                        <input type="text" value="1" id="pieces" /></td>
                    <td>
                        <input type="text" value="" id="bdft" /></td>
                    <td>
                        <input type="text" value="" id="linealft" /></td>
                    <td>
                        <input type="text" value="" id="sqft" /></td>
                </tr>
            </table>
            <input type="button" value="Calculate" onclick="calculate()" />
            <script type="text/javascript">
                function calculate() {
                   
                    var heightVar = document.getElementById(height);
                    var widthVar = document.getElementById(width);
                    var lengthVar = document.getElementById(length);
                    var piecesVar = document.getElementById(pieces);

                    alert(document.getElementById(height).value);
                  
                }

            </script>

What am I doing wrong? I would expect to get ‘height’ value in an alert window.