Custom Fragments in AstroJS

Currently, starting to learn AstroJS. I was looking into the templates from github and I found this <Fragment> tag and referred astro documentation and that says it can be used for directives. I’ve provided the code below for reference.

    <Fragment slot="title">
      Free template for <span class="hidden xl:inline">creating websites with</span>
      <span class="text-accent dark:text-white highlight"> Astro 4.0</span> + Tailwind CSS
    </Fragment>

Here I see a parameter as slot. So I tried to see the definition of the Fragment and got into this file env.d.ts

/// <reference path="./client.d.ts" />

// Caution! The types here are only available inside Astro files (injected automatically by our language server)
// As such, if the typings you're trying to add should be available inside ex: React components, they should instead
// be inside `client.d.ts`

type Astro = import('./dist/@types/astro.js').AstroGlobal;

// We have to duplicate the description here because editors won't show the JSDoc comment from the imported type
// However, they will for its properties, ex: Astro.request will show the AstroGlobal.request description
/**
 * Astro global available in all contexts in .astro files
 *
 * [Astro documentation](https://docs.astro.build/en/reference/api-reference/#astro-global)
 */
declare const Astro: Readonly<Astro>;

declare const Fragment: any;

declare module '*.html' {
    const Component: (opts?: { slots?: Record<string, string> }) => string;
    export default Component;
}

Here I don’t see any slot parameter but how come this is working. Currently the slot is title and the font is also big but if it’s subtitle the font size reduces. I also don’t see any declaration from tailwind with title.
I have provided tailwind.config.cjs file

import defaultTheme from 'tailwindcss/defaultTheme';
import typographyPlugin from '@tailwindcss/typography';

module.exports = {
  content: ['./src/**/*.{astro,html,js,jsx,json,md,mdx,svelte,ts,tsx,vue}'],
  theme: {
    extend: {
      colors: {
        primary: 'var(--aw-color-primary)',
        secondary: 'var(--aw-color-secondary)',
        accent: 'var(--aw-color-accent)',
        default: 'var(--aw-color-text-default)',
        muted: 'var(--aw-color-text-muted)',
      },
      fontFamily: {
        sans: ['var(--aw-font-sans, ui-sans-serif)', ...defaultTheme.fontFamily.sans],
        serif: ['var(--aw-font-serif, ui-serif)', ...defaultTheme.fontFamily.serif],
        heading: ['var(--aw-font-heading, ui-sans-serif)', ...defaultTheme.fontFamily.sans],
      },
    },
  },
  plugins: [typographyPlugin],
  darkMode: 'class',
};

Can someone please explain this? Also provided the repo link

the discord bot, which records information in the embed

I wanted to write a bot that adds a value to embed with the /add command to get a sheet with values, if the /del command then it removes 1 value from embed and if I call the /list command Then embed is output with values in a column, please help.
I wanted to write a bot that adds a value to embed with the /add command to get a sheet with values, if the /del command then it removes 1 value from embed and if I call the /list command Then embed is output with values in a column, please help.

I wanted to write a bot that adds a value to embed with the /add command to get a sheet with values, if the /del command then it removes 1 value from embed and if I call the /list command Then embed is output with values in a column, please help.

require('dotenv').config();
const {Client, Events, GatewayIntentBits, EmbedBuilder, SlashCommandBuilder, PermissionsBitField, Permission } = require ("discord.js")
const client = new Client ({intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });

client.on(Events.ClientReady, (x) => {
    console.log(`${x.user.tag} is ready!`);
    client.user.setActivity(`Coding Discord Bot for reply`);

     const add = new SlashCommandBuilder()
    .addSubcommand((subcommand) =>
        subcommand
          .setName("add")
          .setDescription("Adds points to the user.")
      )
    .addNumberOption(option =>
        option
        .setName ("id 2")
        .setDescription ("second value")
        .setRequired(true)
    )

    const del = new SlashCommandBuilder()
    .setName ("del")
    .setDescription ("delete stroke")

    const embed = new SlashCommandBuilder()
    .setName ("embed")
    .setDescription ("embed")

client.application.commands.create(add);
client.application.commands.create(del);
client.application.commands.create(embed);

});

client.on("interactionCreate", (interaction) => {


        if (interaction.commandName === "embed") {
            const embed = new EmbedBuilder()
            .setAuthor({
              name: "Info",
              url: "https://example.com",
            })
            .setTitle("Example Title")
            .setURL("https://example.com")
            .setImage("https://cubedhuang.com/images/alex-knight-unsplash.webp")
            .setThumbnail("https://dan.onl/images/emptysong.jpg")
            .setColor("#00b0f4")
            .setFooter({
              text: "Example Footer",
              iconURL: "https://slate.dan.onl/slate.png",
            })
            .setTimestamp();

            interaction.reply({embeds: });
    }

});

client.login(process.env.TOKEN);

ReactJS can scroll in Chrome but can’t in Safari

Weird thing happen to my React website. I’ve set style={maxHeight:…., overflow: ‘auto’} to enable scrolling. It’s working fine in Chrome but have an issue in Safari. After state changed, scroll is locked but I still can use mouse to scroll. Also, if I adjust browser size, scrolling will back to work again.

Please see example below. Sorry for the quality.
Example

I’m trying to make scrolling works in Safari. Any ReactJS expert please help!

Vitest faster testing approach?

I am using vitest for testing on my project. But it takes up a lot of time(~20 min) for every PR made.

I was thinking if there is a way I could run tests for only the files that are changed? Will this work or create problems. Also How should I go about implementing this, I couldn’t find any CLI command for this specific purpose.

I checked around vitest docs, and found out this

maxConcurrency

  • Type: number

  • Default: 5

  • CLI: --max-concurrency=10, --maxConcurrency=10

A number of tests that are allowed to run at the same time marked with test.concurrent.

Test above this limit will be queued to run when available slot appears.

Will this work? This would still run for the entire codebase?

Which approach should I go with?

ECMA spec – “member” === “child”?

I’m reading the ECMA spec right now to answer some build / execution questions I have long held about js. Funny enough, the spec starts by giving definitions (very standard white paper stuff), but they keep using the word “member” in a context that is odd to me:

4.4.5 primitive value – member of one of the types Undefined, Null, Boolean, Number, BigInt, Symbol, or String as defined in clause

Another example

4.4.6 object – member of the type Object

I’ve always understood these words to be defined as:

  1. Member: a reference within a type or class – such as a method or property.
  2. Child: a type or class that inherits from the current type or class.

So do I have the correct understanding of the ECMA spec, that when they say member they mean child? It doesn’t make sense that an object derived from Object, connected by type chain would be a “member” of the “Object” type.

Learning FLask: Stuck at OpenAI api

from flask import Flask, request, jsonify, send_from_directory
import openai
from openai import OpenAI
import os

app = Flask(__name__)


openai.api_key = 'sk-' # I added my key here.

@app.route('/')
def index():
    return send_from_directory('.', 'index.html')

@app.route('/analyze', methods=['POST'])
def analyze_cv():
    if 'cv' not in request.files or 'job_description' not in request.files:
        return jsonify({'error': 'CV and Job Description files are required'}), 400

    cv = request.files['cv'].read()
    job_description = request.files['job_description'].read()

    try:
        cv = cv.decode('utf-8')
    except UnicodeDecodeError:
        cv = cv.decode('latin-1')

    try:
        job_description = job_description.decode('utf-8')
    except UnicodeDecodeError:
        job_description = job_description.decode('latin-1')


    prompt = f"Given the following job description:n{job_description}nnAssess the suitability of the candidate based on the CV:n{cv}nnScore the candidate from 1 to 10 and provide an explanation."


    try:
        client = OpenAI(api_key = os.environ.get("OPENAI_API_KEY"),)
        openai.Completion.create
        response = client.Completions.create(
            engine="text-davinci-003",
            prompt=prompt,
            temperature=0.7,
            max_tokens=1024
        )

        score = int(response.choices[0].text.split()[0])
        explanation = response.choices[0].text.split('n')[1]

        return jsonify({'score': score, 'explanation': explanation}), 200
    
    except Exception as e:
        print(e)  
        return jsonify({'error': 'An error occurred while analyzing the CV'}), 500

if __name__ == '__main__':
    app.run(debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CV Analyzer</title>
</head>
<body>
    <h1>CV Analyzer</h1>
    <input type="file" id="cv" accept=".pdf,.doc,.docx">
    <input type="file" id="job_description" accept=".pdf,.txt,.doc,.docx">
    <button onclick="analyze()">Analyze</button>
    <div id="result"></div>

    <script>
        function analyze() {
            var cvFile = document.getElementById('cv').files[0];
            var jobDescriptionFile = document.getElementById('job_description').files[0];

            if (!cvFile || !jobDescriptionFile) {
                alert('Please upload both CV and Job Description files.');
                return;
            }

            var formData = new FormData();
            formData.append('cv', cvFile);
            formData.append('job_description', jobDescriptionFile);

            fetch('/analyze', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                document.getElementById('result').innerHTML = `
                    <h2>Score: ${data.score}</h2>
                    <p>${data.explanation}</p>
                `;
            })
            .catch(error => console.error('Error:', error));
        }
    </script>
</body>
</html>

So I coded the above two file. But I am unable to get the “Score”.
On console this error pops up again and again:

The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable

127.0.0.1 - - [04/May/2024 20:55:38] "POST /analyze HTTP/1.1" 500 -

Could someone please help me here?

I have tried what was given by some on SO. But it just does not work.

I want to know who submitted the form [closed]

I want to know who submitted the form by just letting the user login to the system. Once logged in user can access the submission form then I want to know by just seeing its username.

var insertBtn = document.getElementById('insert');

function InsertData(){
  var IDInp = document.getElementById('IDInp').value;
  var ReqInp = document.getElementById('ReqInp').value;
  var InqInp = document.getElementById('InqInp').value;
  var SubInp = document.getElementById('SubInp').value;
  var locInp = document.getElementById('locInp').value;
  var DesInp = document.getElementById('DesInp').value;



  set(ref(db,'RequestSet/' + IDInp ),{
       Request: ReqInp, 
       Inquiry: InqInp, 
       Subject: SubInp, 
       Location: locInp, 
       Description: DesInp 
  }).then(()=>{
      alert("Data Added Successfully");
  })
  .catch((error)=>{
      alert("Unsuccessful");
      console.log("Error:", error);
  })
}

This is my code using firebase as my database. Code doesn’t work.

How to call again a function when I change the value of the input when I click on button?

I wanted to build the fibonacci sequence using DOM. I used an input where you type a number and then result the last number of the sequence and then display all the sequence.The problem is when I want to change the number from the input, it continues to display the next sequence instead of changing the previous one and also continues with “Type a positive number.” if I type a negative number, keeping the previous sequence.I want to cancel the previous results and run the function again when I change the number from the input and click on the button, but I don’t understand how to do it.

Here’s the html:

<label for = 'number'>Type a number: </label>
<input type = 'number' id = 'input'>
<button id = 'btn1'>Click me</button>
<p id = 'para1'>The <span id = 'span1'>_</span> number from the sequence is: 
<span id = span2></span></p>
<p id = 'para2'>Your fibonacci sequence is: 
<ul id = 'list'></ul> </p>
</div>

And the javascript code:

var btn1 = document.querySelector('#btn1');                
var input = document.querySelector('#input');            
var span1 = document.querySelector('#span1');           
var span2 = document.querySelector("#span2");           
var para1 = document.querySelector('#para1');          
var para2 = document.querySelector('#para2');        
var list = document.querySelector('#list');           
btn1.addEventListener('click', fibonacci);

function fibonacci() {

if(input.value <= 0) {
para1.textContent = 'Type a positive number.';
para2.remove();
> }

if (input.value == 1) {
span1.textContent = 1;
span2.textContent = 1;
list.textContent = '1';
> }

if (input.value == 2) {
span1.textContent = 2;
span2.textContent = 1;
list.textContent = '1, 1'
> }

if (input.value >= 3) {
let array = [1, 1];
span1.textContent = input.value;

for (let i = 2; i < input.value; i++) {
var item = array[i-2] + array[i-1];
array.push(item);
> };

span2.textContent = array[input.value-1]

for (let j = 0; j < array.length; j++) {
var li = document.createElement('li');
li.textContent = array[j];
list.appendChild(li);


input.focus();
> }

Is mapping response data by doing loops or map function acceptable in Node.js?

I’m working on a Node.js application where I receive a response from an API and need to process the data before sending it to the client. I’m wondering if it’s acceptable to use loops (like for or while loops) to iterate over the response data and manipulate it, or if it’s better practice to use the map function provided by JavaScript.

I just want to ensure that i will not block the event loop, so i want to know if it is acceptable to do so.

For example, let’s say I have an array of objects in the response data and I want to extract a specific property from each object and create a new array with just those properties.

Would it be acceptable to do something like this using a loop:

let newData = [];
for (let i = 0; i < responseData.length; i++) {
    newData.push(responseData[i].propertyName);
}

Or should I use the map function like this:

let newData = responseData.map(item => item.propertyName);

I want to ensure that my code follows best practices and is efficient. Any insights or advice on this would be greatly appreciated.

DOM Manipulation cloning nodes and placing values

I am trying to dynamically create a list, by cloning a li item, and then dynamically fill in the values of that list. Strangely, I get only the second item out of my object in that list. I have tried to review the code I wrote, but I cannot seem to find the issue?

<ul>
    <li>{name},{price}</li>
</ul>
    
<script>

    function loop(node) {
        
        value =  [
            {name: 'Bananas', price: '4'},
            {name: 'Candy', price: '2'},
            {name: 'Oranges', price: '2'},
            {name: 'Vegetables', price: '5'}]
        
        let obj = Object.entries(value);
        let len = Object.entries(value).length;

                for(let k=0;k<value.length;k++) {
                    
                    let object = Object.entries(obj[k][1]);
                            
                    for (const property in object) {
                        
                        let search = `${object[property]}`;
                        let values = Object.entries(search.split(','));

                                    
                        let textName = values[0][1];
                        console.log(textName + ':' + values[1][1]);
                                    
                        let regex = new RegExp("{\s*" + textName+ "[0-9]*\s*}", "i");                             
                                    
                        if(node.childNodes[k].innerHTML) {
                            node.appendChild(node.childNodes[k].cloneNode(true));
                            node.childNodes[k].innerHTML = node.childNodes[k].innerHTML.replace(regex, values[1][1]);
                        }
                    }
                }
    }

    function nodeParentList() {
        let parentList = [];
        var docElements = document.getElementsByTagName("*")
        for (var i = 0; i < docElements.length; i++) {
            parentList.push(docElements[i]);
        }
        return parentList;
    }


    var docElements = nodeParentList();
        for (var i = 0; i < docElements.length; i++) {
            loop(docElements[i]);
        }
    
</script>

Expected:

  • Bananas
  • Candy
  • Oranges
  • Vegetables
  • when page is resize the page becomes blank three js

    import * as THREE from 'three';
    import "./style.css"
    
    //scene
    const scene = new THREE.Scene();
    
    //create our sphere
    const geometry =new THREE.SphereGeometry(3,64,64);
    const material = new THREE.MeshStandardMaterial({
    color:"#00ff83",
    })
    
    //mesh is combination of geometery and material 
    const mesh = new THREE.Mesh(geometry,material);
    scene.add(mesh)
    //sizes
     const sizes = {
    width: window.innerWidth,
     height:window.innerHeight,
    
     }
    
     //Lights
    
     const light = new THREE.PointLight(0x00ff00,100,100)
     light.position.set(0,10,10)
     scene.add(light)
    
    
    
    
    //renderer
    const canvas = document.querySelector(".webgl");
    const renderer = new THREE.WebGLRenderer({canvas})
    
    //now define how big canvas is and where to render this thing out
    renderer.setSize(sizes.width,sizes.height)
    renderer.render(scene,camera)
    
    window.addEventListener('resize',() =>{
    
    sizes.width = window.innerWidth
    sizes.height = window.innerHeight
    
    //up camera
    renderer.setSize(sizes.width,sizes.height)
    camera.aspect = sizes.width/sizes.height
    
     })
    

    I am trying to create a ball animation in html with three js.It was working perfectly fine but when is add resize event listner and resize the page then the page become blank what should i do,any solutions

    i was expecting for the ball to resize with the page but the page becomes blank

    Best Practices for structuring CSS to not go insane [closed]

    Working on an FS application for the first time, learning HTML, CSS, and web development for the first time in 10 years of software engineering, 2 days and already going insane.

    The application I am trying to create is an image uploader from devchallenges.io. Attaching images below in case no ones to login.

    Here is my HTML bit for the center most div which is for upload image and image preview.

            <main class="main-container">
                <div class="container">
                    <div id="innercontainer" class="innercontainer">
                        <img
                            id="file-upload-logo-small"
                            src="./images/logo-small.svg"
                            alt="Upload logo"
                        />
                        <p id="file-upload-text" class="text">
                            Drag &amp; drop a file or <span>browse files</span>
                        </p>
                        <input
                            id="file-upload-input"
                            type="file"
                            style="display: none"
                            accept="image/jpeg, image/png, image/gif"
                        />
                        <p id="file-upload-subtext" class="subtext">
                            JPG, PNG or GIF - Max file size 2MB
                        </p>
                        <img
                            id="preview"
                            class="preview display-none"
                            src=""
                            alt="Image preview"
                        />
                    </div>
                    <div class="control display-none">
                        <button type="button">
                            <div class="controlcontainer">
                                <img src="./images/Link.svg" alt="Share Link" />
                                <p>Share</p>
                            </div>
                        </button>
                        <button type="button">
                            <div class="controlcontainer">
                                <img src="./images/download.svg" alt="Download Link" />
                                <p>Download</p>
                            </div>
                        </button>
                    </div>
                </div>
            </main>
    

    CSS:

    .control {
        display: flex;
        flex-direction: row;
        justify-content: center;
        margin: 20px;
        column-gap: 10px;
    }
    
    .control button {
        width: fit-content;
        padding: 8px 10px;
        background-color: var(--blue-primary);
        border: none;
        color: var(--white-smoke);
        font-weight: 400;
        font-size: 10px;
        border-radius: 5px;
    }
    
    .controlcontainer {
        display: flex;
        flex-direction: row;
        justify-content: center;
        align-items: center;
        column-gap: 5px;
    }
    
    .display-none {
        display: none;
    }
    
    

    Now, this works fine, first time load just shows the info to click and upload a file, and when upload done, it displays the control buttons.

    I was facing an issue where even with display-none added to the div after control, it was still showing up. The main reason being, display-none class was declared above the control class in the CSS file and then I realised, CSS is applied according to order of definition in the CSS file and not on the element. The fix I tried was moving display-none to the end of the file and adding !important, which works.

    Question is what is the standard way of dealing with such issues without spending an hour pulling your hair apart.

    What is the best practice industry follows for such issues? How would this work out, if I have separate CSS into smaller files, would it depend on order of file load, when classes are common among files?

    Firebase: google authentication suddenly not working anymore

    Not sure if firebase changed anything or my code has bug now it is exposed.
    When debug in the script.js, the call back returned user as null. What could be the cause? This is the code in script.js. It is standard from firebase doc.

    window.addEventListener('load', function () {
    
      // FirebaseUI config.
      var uiConfig = {
        signInSuccessUrl: '/',
        signInOptions: [
          // Comment out any lines corresponding to providers you did not check in
          // the Firebase console.
          firebase.auth.GoogleAuthProvider.PROVIDER_ID,
          //firebase.auth.EmailAuthProvider.PROVIDER_ID,
          //firebase.auth.FacebookAuthProvider.PROVIDER_ID,
          //firebase.auth.TwitterAuthProvider.PROVIDER_ID,
          //firebase.auth.GithubAuthProvider.PROVIDER_ID,
          //firebase.auth.PhoneAuthProvider.PROVIDER_ID
    
        ],
        // Terms of service url.
        tosUrl: '<your-tos-url>'
      };
    
      firebase.auth().onAuthStateChanged(function (user) {
        if (user) {
          // User is signed in, so display the "sign out" button and login info.
          //document.getElementById('sign-out').hidden = false;
    
          console.log(`Signed in as ${user.displayName} (${user.email})`);
          user.getIdToken().then(function (token) {
            // Add the token to the browser's cookies. The server will then be
            // able to verify the token against the API.
            // SECURITY NOTE: As cookies can easily be modified, only put the
            // token (which is verified server-side) in a cookie; do not add other
            // user information.
            document.cookie = "token=" + token;
          });
        } else {
          // User is signed out.
          // Initialize the FirebaseUI Widget using Firebase.
          var ui = new firebaseui.auth.AuthUI(firebase.auth());
          // Show the Firebase login button.
          ui.start('#firebaseui-auth-container', uiConfig);
          // Update the login state indicators.
    
    
          // Clear the token cookie.
          document.cookie = "token=";
        }
      }, function (error) {
        console.log(error);
        alert('Unable to log in: ' + error)
      });
    });```
    

    Why is PHP or jQuery removing a concatanated end tag in an inline JS script, and closing tags itself?

    I have this PHP code, which outputs some headings and an inline jQuery script:

    <?php
    echo '<h2>Test</h2>';
    ?>
    
    <div>
    <form>
    <input type="hidden" name="test">
    <div id="placeholder"></div>
    <script>
    jQuery( document ).ready( function( $ ) {
        var testVar = 'Some info from a variable.';
        $( '<div id="test-id" class="test-class">' + testVar + ' <a href="/test?test=1">Test?</a></div>' ).insertAfter( $( '#placeholder' ) );
    });
    </script>
    </form>
    </div>
    
    <?php
    echo '<h2>End of test</h2>';
    ?>
    

    This inserts a test-id div with a link inside to after the placeholder div.

    This works locally, but when I test this on a live server, if I view source, I see the line under testVar has been changed to this, it’s like the PHP or jQuery is stripping the end </a> tag and closing off the script and form:

    $( '<div id="test-id" class="test-class">' + testVar + ' <a href="/test?test=1">Test?</script>
    </form>
    </div>' ).insertAfter( $( '#placeholder' ) );
    

    Dealing with leaflet’s lack of promises

    I’m using the leaflet CDN script in a server-rendered app. The library’s methods do not involve promises, so I often get weird UI glitches.

    For example, when I use setView() it returns immediately; the only workaround is to set a timeout and hope for the best.

    Is there a way to wait for that method to actually complete? (Maybe I didn’t find that bit in the docs?) Or perhaps there’s some trick I could use to overcome this problem?