How to access it the persistence variable in authentication on firebase v9 react.js?

setPersistence(auth, browserSessionPersistence)
.then(() => {
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
setUser(userCredential.user.email.split(“@”)[0]);
})
.catch((error) => {
setError(error.message);
});
})
.catch((error) => {
setError(error.message);
});

// This is my code I’m using the setPersistence function what does it do? and how to access it?

setPersistence(auth, browserSessionPersistence)
.then(() => {
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
setUser(userCredential.user.email.split(“@”)[0]);
})
.catch((error) => {
setError(error.message);
});
})
.catch((error) => {
setError(error.message);
});

Passing a variable to another webpage using JavaScript

I am trying to pass a variable from one page to another using JavaScript so that the following works:

main.html:

<html>
<head>

</head>
<body>
<p>Links to worksheets: &nbsp
<a href="worksheets.html" >1 &nbsp
<a href="worksheets.html">2 &nbsp
<a href="worksheets.html">3 &nbsp

</body>
</html>


worksheets.html:

<html>
<head>

</head>
<body>
<p id="mainParagraph"></p>

<script>
document.getElementById("mainParagraph").innerHTML = "This is worksheet number " + localStorage.getItem("worksheetNumber");
</script>

</body>
</html>

What I am needing is a way for the main file to pass the worksheet number to local storage. I would like to do this without having a separate JavaScript method for each worksheet, as I intend to have hundreds of worksheets. Another option may be to have an inline JavaScript method for each link, but I can’t get anything to work.

Can anyone suggest a way to pass the worksheet number when the link is clicked? Local storage seems to be a good way to do it, but I’m open to other ways of doing it with JavaScript.

Thank you.

ERROR NullInjectorError: R3InjectorError(AppModule)[MessagingService -> AngularFireMessaging -> InjectionToken angularfire2.app.options

I’ve seen several answers to this question, none of which have helped. I’ve created a chat PWA and I’m trying to set up Firebase push notification using FCM. I’m following a tutorial and I’m currently receiving this error when loading the app after importing the service to be used in the app.component class.

Here’s the app.module.ts

import { AngularFireMessagingModule } from '@angular/fire/compat/messaging';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, 
    IonicModule.forRoot(), 
    provideFirebaseApp(() => initializeApp(environment.firebase)), 
    provideAnalytics(() => getAnalytics()), 
    provideAuth(() => getAuth()), 
    provideFirestore(() => getFirestore()), 
    provideFunctions(() => getFunctions()), 
    provideMessaging(() => getMessaging()), 
    providePerformance(() => getPerformance()), 
    provideStorage(() => getStorage()),
    AngularFireMessagingModule],
  providers: [{ provide: RouteReuseStrategy, 
    useClass: IonicRouteStrategy }, 
    ScreenTrackingService,
    Storage,
    UserTrackingService],

  bootstrap: [AppComponent],
})
export class AppModule {}

The actual messaging service:

import { Injectable } from '@angular/core';
import { getMessaging, getToken } from "firebase/messaging";
import { AngularFireMessaging } from '@angular/fire/compat/messaging';

@Injectable({
  providedIn: 'root'
})
export class MessagingService {

  constructor(private angularFireMessaging: AngularFireMessaging) { }

  async saveDeviceToken () {

    console.log('token', fcmToken);
    this.angularFireMessaging.requestToken.subscribe((token) => {
      console.log('token', token);
    }, (error) => {
        console.log('error', error)
    })
  }
}

and here’s the app.component.ts. When I import the messaging service in app.component.ts is when the error appears:

import { Component } from '@angular/core';
import { Storage } from '@ionic/storage';
import { MessagingService } from './services/messaging.service';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss'],

})
export class AppComponent {
  constructor(private storage: Storage,
              ) {}

  async ngOnInit() {
    await this.storage.create();
    this.messagingService.saveDeviceToken()
  }
}

enter image description here

    "firebase": "^9.18.0",
    "firebase-tools": "^8.0.0",
        "@angular/fire": "^7.5.0",

Uncaught ReferenceError ReferenceError: channel is not defined

I’m coding a discord bot that creates tickets

and I would like to know how I can send messages on the channel I just created

So I try the .then, but it doesn’t work, so I don’t understand why :/

I tried a lot of thing, just visiting the web or watching video on YouTube but no one works

Here is my code :

client.on("interactionCreate", async interaction =>  {
    if(interaction.isCommand()){
        if(interaction.commandName == "ticket"){

            const Embed = new EmbedBuilder()
                .setColor(0x0099FF)
                .setTitle('Do you need help ?')
                .setDescription('By clicking on the button,nModerators will answer your questions/reports!')
                .setFooter({ text: 'Created by Skorflex#9141', iconURL: 'https://cdn.discordapp.com/attachments/1082613588507766784/1082613661140537404/logo-transparent.png' });
            
            const row = new ActionRowBuilder()
                .addComponents(
                    new ButtonBuilder()
                        .setCustomId('button')
                        .setLabel('Open a ticket')
                        .setStyle(ButtonStyle.Primary),
                );

            await interaction.reply({ embeds: [Embed], components: [row] });

        }
    }
    if(interaction.isButton()){
        if(interaction.customId === "button"){

            const server = client.guilds.cache.get(guildId);

            

            server.channels.create({name:`ticket-${interaction.user.username}`})
            .then(channel => {
                let category = client.channels.cache.get(ticket_category);

                if (!category) throw new Error("Category channel does not exist");
                    channel.setParent(category.id);
                }).catch(console.error);

                interaction.reply({content: "Your ticket is available !", ephemeral: true})

                const Embed = new EmbedBuilder()
                .setColor(0x0099FF)
                .setTitle('Thank you for contacting support')
                .setDescription('Describe your problem')

                const row = new ActionRowBuilder()
                .addComponents(
                    new ButtonBuilder()
                        .setCustomId('closebutton')
                        .setLabel('Close the ticket')
                        .setStyle(ButtonStyle.Primary),
                );
                
                channel.send({embeds:[Embed], row:[row]})
        }
    }
})

Track location on background react native expo

I want to store the user location in firebase real-time database when there is a change in the user location.
I want it will work when the app running on foreground and background using react native expo

I tried to create a task running on background but didn’t succeed

I can’t see the dropzone tile in my blade view

I’m using dropzone with Laravel 9 for the first time.

Following the documentation at the following link:

Dropzone documentation

blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">Nuovo Annuncio</div>
                <div class="card-body">
                <div class="form-group row">
                    <label for="images" class="col-md-12 col-form-label text-md-right">Immagini</label>
                    <div class="col-md-12">

                        <div id="dropzone">
                            <form action="" class="dropzone" id="file-upload" enctype="multipart/form-data">
                                @csrf
                                <div class="dz-message">
                                    Drag and Drop Single/Multiple Files Here<br>
                                </div>
                            </form>

                            @error('images')
                            <span class="invalid-feedback" role="alert"> <strong>{{ $message }}</strong></span>
                            @enderror
                        </div>
                    </div>
                </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection
<script type="text/javascript">
const { Dropzone } = require("dropzone");
    if (document.getElementById('file-upload')) {
        let dropzone = new Dropzone('#file-upload', {
            thumbnailWidth: 200,
            maxFilesize: 1,
            acceptedFiles: ".jpeg,.jpg,.png,.gif"
        });
    }
</script>

Specifically I’m getting the following error:

Uncaught ReferenceError: require is not defined

Can you help me please?

Uncaught TypeError TypeError: Cannot set properties of null (setting ‘innerHTML’) at calculateBmi at onclick

Hi guys, I am trying to create a BMI calculator. Below is my code but when I do the onclick calling a function I am getting error. However, I checked by doing an alert and the alert did workout. I think there is something error which I do not understand. Please help!!

enter image description here

I did alert in function just to check and looking for a solution to surpass this error

Why is this code not awaiting import of modules?

I am trying to dynamically import modules when the nodejs server is in development environment. I have created an immediately-invoked async function for this which theoretically should work, but it simply doesn’t. The rest of the code following the import of modules runs without awaiting for the import to finish.

server.js

    import express from 'express'; // standard import
    
    if (process.env.NODE_ENV === 'development') {
    // IIFE to dynamically import modules required in dev
     (
      async () => {
            
         try {
         console.log(`About to import`)
         //simple destructuring used to get the default export out of the modules
         const {default: webpack} = await import('webpack');
         const {default: webpackDevMiddleware} = await import('webpack-dev-middleware');
         console.log(`FIRST: typeof webpack ${typeof Webpack} | typeof webpackdevmiddleware ${typeof WebpackDevMiddleware}`)
          } catch (error) {
             console.log(error)
          }
       })();
     }
    
    const server = express();
    
    if (process.env.NODE_ENV === 'development') {
    // Need to use imported modules here but this code does not wait for the webpack imports above to finish
    console.log(`SECOND: I must run after FIRST`)
    }
    
    ....
    server.listen(PORT, () => {
    console.log(`Server is listening on port 8080`);
});

When I run the server.js code I get the following output in this order:

About to import

SECOND: I must run after FIRST

Server is listening on port 8080

FIRST: typeof webpack function | typeof webpackdevmiddleware function

The correct order needs to be:

About to import

FIRST: typeof webpack function | typeof webpackdevmiddleware function

SECOND: I must run after FIRST

Server is listening on port 8080

I cannot understand where/why it is going wrong?

How can I create a session to store the WhatsApp QR Code? (Javascript)

So, I’m running an aplication kinda like a chatbot with WhatsApp but whenever I start the program I always have to read the QRCode. This is the beginning of the code:

const { Client } = require('whatsapp-web.js');
const qrcode = require('qrcode-terminal');
require('dotenv').config()

const client = new Client();

client.on('qr', (qr) => {
    qrcode.generate(qr, {small: true});
});

client.on('ready', () => {
    console.log('Client is ready!');
});

For example, what should I use to store the session so whenever I start the program it doens’t require me to read the QR Code again?
I tried to use:

create({
    session: 'Chat-WhatsApp',
    multidevice: true
})
    .then((client) => start(client))
    .catch((error) => {
        console.log(error);
    });

But it failed.

Store the QRCode without the need of reading it again.

When the mouse is hovering over a table row, how can I change both the row’s background color and the fill color of a corresponding SVG path?

My webpage dynamically generates a table with table rows of the class tableTr and contains a SVG image within the HTML code with paths of the class pathClass.

Using JavaScript, upon hovering the mouse over a table row, the background color of the row should change, as well as the fill color of the corresponding cell; both revert back to normal once the mouse is moved off the table row.

The paths should not change fill color when the mouse hovers over them; this does not work in reverse.

I am totally stumped about what approach to use.

Flatpickr year disapear when english locale

I experience a weird result with flatpickr when I try to define the default language (English). The year disappear from date picker

function getUserLanguage() {
        const userLang = window.navigator.language || window.navigator.userLanguage;
        return userLang.substring(0, 2);
    }

    const lang = getUserLanguage();

    const locales = {
        'fr': French.fr,
        'it': Italian.it
    };

    flatpickr('.flatpickr', {
        allowInput: true,
        altFormat: 'd-m-Y',
        altInput: true,
        altInputClass: 'form-control flatpickr-input',
        dateFormat: 'Y-m-d',
        locale: locales[lang] || 'en',
        onClose(dates, currentdatestring, picker){
          picker.setDate(picker.altInput.value, true, picker.config.altFormat)
        }
    });

My browser is in english

Result in english:

english

Result in french (with French.fr)

french

Error “TypeError: this.options.files?.map is not a function”

so I have a Discord Bot and I wanted to create a memberInfo slashcommand. So I made this code for it:

const { ChatInputCommandInteraction, SlashCommandBuilder, EmbedBuilder, AttachmentBuilder } = require("discord.js");

const { profileImage } = require("discord-arts");

module.exports = {
    data: new SlashCommandBuilder()
    .setName("memberinfo")
    .setDescription("View your or any member's information.")
    .setDMPermission(false)
    .addUserOption((option) => option
        .setName("member")
        .setDescription("View a member's information. Leave empty to view your own")
    ),
    /**
     * @param {ChatInputCommandInteraction} interaction
     */
    async execute(interaction) {
        await interaction.deferReply()
        const member = interaction.options.getMember("member") || interaction.member;

        if(member.user.bot) return await interaction.editReply({
            embeds:
            [
                new EmbedBuilder()
                .setDescription("At the moment, bots are not supported for this command.")
            ],
            ephemeral: true
        });

        try {
            const fetchedMembers = await interaction.guild.members.fetch();

            const profileBuffer = await profileImage(member.id);
            const imageAttachment = new AttachmentBuilder(profileBuffer, 
            {name: 'profile.png'});

            const joinPosition = Array.from(fetchedMembers
            .sort((a, b) => a.joinedTimestamp - b.joinedTimestamp)
            .keys())
            .indexOf(member.id) + 1;

            const topRoles = member.roles.cache
            .sort((a, b) => b.position - a.position)
            .map(role => role);

            const userBadges = member.user.flags.toArray()

            const joinTime = parseInt(member.joinedTimestamp / 1000);
            const createdTime = parseInt(member.createdTimestamp / 1000);

            const Booster = member.premiumSince ? "<:discordboost7:1086751631221211247>" : "❌";

            const Embed = new EmbedBuilder()
            .setAuthor({name: `${member.user.tag} | General Information`, iconURL: member.displayAvatarURL()})
            .setColor(member.displayColor)
            .setDescription(`On <t:${joinTime}:D>, ${member.user.username} joined as the **${addSuffix(joinPosition)}** member of this guild.`)
            .setImage("attachment://profile.png")
            .addFields([
                {name: "Badges", value: `${addBadges(userBadges).join("")}`, inline: true},
                {name: "Booster", value: `${Booster}`, inline: true},
                {name: "Top Roles", value: `${topRoles.join("")}`, inline: false},
                {name: "Created", value: `<t:${createdTime}:R>`, inline: true},
                {name: "Joined", value: `<t:${joinTime}:R>`, inline: true},
                {name: "Identifier", value: `${member.id}`, inline: false},
                {name: "Avatar", value: `[Link](${member.displayAvatarURL()})`, inline: true},
                {name: "Banner", value: `[Link](${(await member.user.fetch()).bannerURL})`, inline: true},
            ]);

            await interaction.editReply({embeds: [Embed], files: {imageAttachment}});
        } catch (error) {
            await interaction.editReply({content: "An error occured: Contact the Developer (MrAplex#9627)"});
            throw error;
        }
    }
}

function addSuffix(number) {
    if(number % 100 >= 11 && number % 100 <= 13)
        return number + "th";

    switch(number % 10) {
        case 1: return number + "st";
        case 2: return number + "nd";
        case 3: return number + "rd";
    }
    return number + "th";
}

function addBadges(badgeNames) {
    if(!badgeNames.length) return ["X"];
    const badgeMap = {
        "ActiveDeveloper": "<:activedeveloper:1086751628423606383>",
        "BugHunterLevel1": "<:discordbughunter1:1086751635860115476>",
        "BugHunterLevel2": "<:discordbughunter2:1086751637416181821>",
        "PremiumEarlySupporter": "<:discordearlysupporter:1086751640410923028>",
        "Partner": "<:discordpartner:1086751645712535723>",
        "Staff": "<:discordmod:1086751641887314013>",
        "HypeSquadOnlineHouse1": "<:hypesquadbravery:1086751651479687199>", // bravery
        "HypeSquadOnlineHouse2": "<:hypesquadbrilliance:1086751653585244202>", // brilliance
        "HypeSquadOnlineHouse3": "<:hypesquadbalance:1086751649810370652>", // balance
        "Hypesquad": "<:hypesquadevents:1086751902542331975>",
        "CertifiedModerator": "<:discordmod:1086751641887314013>",
        "VerifiedDeveloper": "<:discordbotdev:1086751632903131306>",
    };
  
    return badgeNames.map(badgeName => badgeMap[badgeName] || '❔');
}

My problem here is that when I type use the slashcommand in Discord, I get an error in Terminal saying the following:

/Users/Aplex/Documents/Royal Bot/node_modules/discord.js/src/structures/MessagePayload.js:187
    const attachments = this.options.files?.map((file, index) => ({
                                            ^

TypeError: this.options.files?.map is not a function
    at MessagePayload.resolveBody (/Users/Aplex/Documents/Royal Bot/node_modules/discord.js/src/structures/MessagePayload.js:187:45)
    at InteractionWebhook.editMessage (/Users/Aplex/Documents/Royal Bot/node_modules/discord.js/src/structures/Webhook.js:336:50)
    at ChatInputCommandInteraction.editReply (/Users/Aplex/Documents/Royal Bot/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:158:36)
    at Object.execute (/Users/Aplex/Documents/Royal Bot/Commands/Public/memberInfo.js:69:31)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

How do I fix this? I have no Idea what to do. I am guessing the problem is when I typed in code this (inside the try-catch):

await interaction.editReply({embeds: [Embed], files:{imageAttachment}});

Incorrect output from getMonthlyBalances function calculating stock balances

I have a function called getMonthlyBalances that takes two arrays, stocks and trades, as input and calculates the monthly balance of a user’s stock holdings based on their trade history. The stocks array contains objects with stock id, prices, and dates, while the trades array contains objects with stock id, quantity, price, type (buy/sell), and timestamp.

Here’s the code for the function:

function getMonthlyBalances(stocks, trades) {
  if (!stocks || !trades) {
    return [];
  }

  if (trades.length === 0) {
    return {};
  }

  // Sort trades by timestamp
  trades.sort((a, b) => a.timestamp.seconds - b.timestamp.seconds);

  // Get the first trade month and create a date object
  const firstTradeDate = new Date(trades[0].timestamp.seconds * 1000);
  firstTradeDate.setDate(1); // Set the date to the first day of the month
  firstTradeDate.setHours(0, 0, 0, 0); // Set the time to midnight

  const monthlyBalances = {};
  let currentDate = firstTradeDate;

  // Initialize the user's stock holdings
  const userStocks = {};

  while (currentDate <= new Date()) {
    const currentMonth = currentDate.getMonth();
    const currentYear = currentDate.getFullYear();
    const currentMonthStr = `${currentYear}-${currentMonth + 1}`;

    trades.forEach(trade => {
      const tradeDate = new Date(trade.timestamp.seconds * 1000);
      if (tradeDate.getFullYear() === currentYear && tradeDate.getMonth() === currentMonth) {
        if (trade.type === "buy") {
          userStocks[trade.id] = (userStocks[trade.id] || 0) + trade.quantity;
        } else if (trade.type === "sell") {
          userStocks[trade.id] = (userStocks[trade.id] || 0) - trade.quantity;
        }
      }
    });

    let balance = 0;
    for (const stockId in userStocks) {
      const stock = stocks.find(stock => stock.id === parseInt(stockId));
      const stockPrice = stock.prices.find(price => {
        const priceDate = new Date(price.date.seconds * 1000);
        return priceDate.getFullYear() === currentYear && priceDate.getMonth() === currentMonth;
      });

      if (stockPrice) {
        balance += userStocks[stockId] * stockPrice.price;
      }
    }

    monthlyBalances[currentMonthStr] = balance;

    currentDate.setMonth(currentDate.getMonth() + 1);
  }

  return monthlyBalances;
}

And here are the input data examples:

// trades
[
  {
    "id": 1, // stock_1
    "quantity": 10,
    "price": 120,
    "type": "buy",
    "timestamp": {
      "seconds": 1672589479,
      "nanoseconds": 858000000
    }
  },
  {
    "id": 1, // stock_1
    "quantity": 10,
    "price": 110,
    "type": "buy",
    "timestamp": {
      "seconds": 1675354636,
      "nanoseconds": 858000000
    }
  }
]

// stocks
[
  {
    "id": 1,
    "prices": [
      {
        "price": 120,
        "date": {
          "seconds": 1678860000,
          "nanoseconds": 267000000
        }
      },
      {
        "price": 100,
        "date": {
          "seconds": 1672552800,
          "nanoseconds": 32000000
        }
      }
    ]
  },
  {
    "id": 2,
    "prices": [
      {
        "price": 120,
        "date": {
          "seconds": 1677650400,
          "nanoseconds": 12000000
        }
      },
      {
        "price": 90,
        "date": {
          "seconds": 1672552800,
          "nanoseconds": 145000000
        }
      }
    ]
  }
]

The problem is that the function produces incorrect output for certain months. For example, in February, the balance should be 1000, but the function returns 0. I can’t figure out why this is happening.

Can anyone help me understand what’s wrong with the function, and how to fix it to get the correct balance for each month?

Desired output:

[{2023-1: 1000, 2023-2: 1000, 2023-3: 2400}]

Align text next to image when everything is wrapped in tags

I am pulling some markdown through an API (via contentful) and then using ReactMarkdown to convert it to html. The issue is that this then produces the following html

<p>Some text content</p>
<p>
  <img src="myImage.png" alt="my image">
</p>
<p>Multiple lines of text that I want to have next to the image</p>

I want to be able to put the “Multiple lines of text…” to the right of the image, as the image isn’t the full width of the parent div. The problem is that the

tag the image is inside is filling the full width.

How can I place the text next to the image.

Things to note:
Depending on how the content is put into contentful it can be returned as:

<p>Some text content
  <img src="myImage.png" alt="my image">
Multiple lines of text that I want to have next to the image</p>

I have no ability to add class names to the different

tags