How to manually sign a transaction using Hedera Javascript SDK?

I’m trying to use a Hardware Security Module (HSM) to manually sign a Hedera transaction, but the Hedera JavaScript SDK requires me to pass my private key to the SDK for signing. Since my private key cannot leave the HSM and I can only use the HSM to sign transactions, I’m not sure how to proceed. Could someone please let me know how to do this? I couldn’t find any example code.

The flow I need to follow is:

  1. Create a transaction

  2. Serialize the transaction into transaction bytes

  3. Pass the transaction bytes to the HSM for signing

  4. Deserialize the signed transaction bytes back into a transaction object

  5. Submit the signed transaction to the network

How can I optimize three.js the rendering of a gltf model? I tried 4 ways, but the result is the same

I’m trying to find a way to optimize three.js . I have a gltf tree model with 2144 triangles. I am adding 1000 trees to the scene in different ways.

  1. I clone the tree in a simple loop. 2. I use InstancedMesh. 3. Using BatchedMesh 4. Clone instance tree in Blender and load all tree. All four methods give the same number of fps. I also tried 100 pieces, 1000 pieces and 5000 pieces of trees. I also tried WebGPURenderer and WebGLRenderer. The result is always about the same. Is there any way to speed up the rendering of gltf models, or is it already maximally optimized when loading into three.js . Thanks!

Issues with `setRulesChannel` and `setPublicUpdatesChannel` Not Updating Guild Object in Discord Library im creating

I’m developing a custom Discord JavaScript library, and I am encountering an issue when trying to update the rulesChannelId and publicUpdatesChannelId fields of a Guild object using the setRulesChannel and setPublicUpdatesChannel methods. These methods seem to execute without errors, but after the update, the Guild object remains unchanged as if the values were not updated at all.

This is my Guild.js file

'use strict';

const GuildMemberManager = require("../Managers/GuildMemberManager");
const GuildChannelManager = require("../Managers/GuildChannelManager");
const RoleManager = require("../Managers/RoleManager");
const PresenceManager = require("../Managers/PresenceManager");
const VoiceStateManager = require("../Managers/VoiceStateManager");
const StageInstanceManager = require("../Managers/StageInstanceManager");
const GuildInviteManager = require("../Managers/GuildInviteManager");
const GuildScheduledEventManager = require("../Managers/GuildScheduledEventManager");
const AutoModerationRuleManager = require("../Managers/AutoModerationRuleManager");
const GuildEmojiManager = require("../Managers/GuildEmojiManager");
const GuildStickerManager = require("../Managers/GuildStickerManager");
const Rest = require("../Rest");
const fetch = require("node-fetch")

class Guild {
    constructor(data, client) {
        Object.defineProperty(this, 'client', {
            value: client,
            enumerable: false,
            writable: false,
        });
        this.id = data.id;
        this.name = data.name;
        this.icon = data.icon ?? null;
        this.features = data.features ?? [];
        // put GuildApplicationCommandManager heres
        this.members = new GuildMemberManager(this, data.members ?? []);
        this.channels = new GuildChannelManager(this, data.channels ?? []);
        // put GuildBanManager here
        this.roles = new RoleManager(this, this.client);
        this.presences = new PresenceManager(this, data.presences ?? []);
        this.voiceStates = new VoiceStateManager(this, data.voice_states ?? []);
        this.stageInstances = new StageInstanceManager(this, data.stage_instances ?? []);
        this.invites = new GuildInviteManager(this, data.invites ?? []);
        this.scheduledEvents = new GuildScheduledEventManager(this, data.scheduled_events ?? []);
        this.autoModerationRules = new AutoModerationRuleManager(this, data.auto_moderation_rules ?? []);
        // put vailable: here
        // put shardId: here
        this.splash = data.splash ?? null;
        this.banner = data.banner ?? null;
        this.description = data.description ?? null;
        this.verificationLevel = data.verification_level ?? 0;
        this.vanityURLCode = data.vanity_url_code ?? null;
        // put nsfw level here
        this.premiumSubscriptionCount = data.premium_subscription_count ?? 0;
        // put discovery splash here
        this.memberCount = data.memberCount ?? 0;
        // put larger here
        // put premium progress bar here
        this.afkTimeout = data.afk_timeout ?? 0;
        this.afkChannelId = data.afk_channel_id ?? null;
        this.systemChannelId = data.system_channel_id ?? null;
        this.premiumTier = data.premium_tier ?? 0;
        this.widgetEnabled = data.widget_enabled ?? false;
        this.widgetChannelId = data.widget_channel_id ?? null;
        this.explicitContentFilter = data.explicit_content_filter ?? 0;
        this.mfaLevel = data.mfa_level ?? 0;
        this.joinedTimestamp = data.joined_timestamp ?? null;
        this.defaultMessageNotifications = data.default_message_notifications ?? 0;
        // put SystemChannelFlagsBitField here
        this.maximumMembers = data.maximum_members ?? 500000;
        this.maximumPresences = data.maximum_presences ?? null;
        this.maxVideoChannelUsers = data.max_video_channel_users ?? 0;
        this.maxStageVideoChannelUsers = data.max_stage_video_channel_users ?? 0;
        this.approximateMemberCount = data.approximate_member_count ?? 0;
        this.approximatePresenceCount = data.approximate_presence_count ?? 0;
        this.vanityURLUses = data.vanity_url_uses ?? 0;
        this.rulesChannelId = data.rules_channel_id ?? null;
        this.publicUpdatesChannelId = data.public_updates_channel_id ?? null;
        this.preferredLocale = data.preferred_locale ?? 'en-US';
        // put safetyAlertsChannelId here
        this.ownerId = data.owner_id ?? null;
        this.emojis = new GuildEmojiManager(this, data.emojis ?? []);
        this.stickers = new GuildStickerManager(this, data.stickers ?? []);
    }

    /**
     * Edits the guild using PATCH.
     *
     * Available options to update:
     * - `name` *(string)*: The new name of the guild.
     * - `afkChannelId` *(string|null)*: The ID of the voice channel where AFK users are moved.
     * - `afkTimeout` *(number)*: The AFK timeout in seconds.
     * - `systemChannelId` *(string|null)*: The ID of the system channel.
     * - `systemChannelFlags` *(number)*: System channel flags (bitfield).
     * - `verificationLevel` *(number)*: The verification level (0–4).
     * - `explicitContentFilter` *(number)*: The explicit content filter level (0–2).
     * - `defaultMessageNotifications` *(number)*: Default message notification level (0–1).
     * - `icon` *(string|null)*: A data URI or base64 string of the guild icon. `null` to remove.
     * - `splash` *(string|null)*: A data URI or base64 string of the guild splash image. `null` to remove.
     * - `discoverySplash` *(string|null)*: A data URI or base64 string for the guild’s discovery splash. `null` to remove.
     * - `banner` *(string|null)*: A data URI or base64 string of the guild banner. `null` to remove.
     * - `rulesChannelId` *(string|null)*: The ID of the rules channel.
     * - `publicUpdatesChannelId` *(string|null)*: The ID of the public updates channel.
     * - `preferredLocale` *(string)*: The preferred locale (e.g., "en-US").
     * - `description` *(string|null)*: The description for the guild (shown in server discovery).
     * 
     * @param {Object} options - The guild settings to update.
     * @param {string} [options.name]
     * @param {string|null} [options.afkChannelId]
     * @param {number} [options.afkTimeout]
     * @param {string|null} [options.systemChannelId]
     * @param {number} [options.systemChannelFlags]
     * @param {number} [options.verificationLevel]
     * @param {number} [options.explicitContentFilter]
     * @param {number} [options.defaultMessageNotifications]
     * @param {string|null} [options.icon]
     * @param {string|null} [options.splash]
     * @param {string|null} [options.discoverySplash]
     * @param {string|null} [options.banner]
     * @param {string|null} [options.rulesChannelId]
     * @param {string|null} [options.publicUpdatesChannelId]
     * @param {string} [options.preferredLocale]
     * @param {string|null} [options.description]
     * 
     * @returns {Promise<Guild>} The updated Guild instance.
     */

    async edit(options) {
        const validProperties = [
            'name',
            'afkChannelId',
            'afkTimeout',
            'systemChannelId',
            'systemChannelFlags',
            'verificationLevel',
            'explicitContentFilter',
            'defaultMessageNotifications',
            'icon',
            'splash',
            'discoverySplash',
            'banner',
            'rulesChannelId',
            'publicUpdatesChannelId',
            'preferredLocale',
            'description'
        ];

        for (const key in options) {
            if (!validProperties.includes(key)) {
                throw new Error(`Invalid property: ${key}`);
            }
        }

        const requestData = {
            name: 'name' in options ? options.name : this.name,
            afk_channel_id: 'afkChannelId' in options ? options.afkChannelId : this.afkChannelId,
            afk_timeout: 'afkTimeout' in options ? options.afkTimeout : this.afkTimeout,
            system_channel_id: 'systemChannelId' in options ? options.systemChannelId : this.systemChannelId,
            system_channel_flags: 'systemChannelFlags' in options ? options.systemChannelFlags : this.systemChannelFlags,
            verification_level: 'verificationLevel' in options ? options.verificationLevel : this.verificationLevel,
            explicit_content_filter: 'explicitContentFilter' in options ? options.explicitContentFilter : this.explicitContentFilter,
            default_message_notifications: 'defaultMessageNotifications' in options ? options.defaultMessageNotifications : this.defaultMessageNotifications,
            icon: 'icon' in options ? options.icon : this.icon,
            splash: 'splash' in options ? options.splash : this.splash,
            discovery_splash: 'discoverySplash' in options ? options.discoverySplash : this.discoverySplash,
            banner: 'banner' in options ? options.banner : this.banner,
            rules_channel_id: 'rulesChannelId' in options ? options.rulesChannelId : this.rulesChannelId,
            public_updates_channel_id: 'publicUpdatesChannelId' in options ? options.publicUpdatesChannelId : this.publicUpdatesChannelId,
            preferred_locale: 'preferredLocale' in options ? options.preferredLocale : this.preferredLocale,
            description: 'description' in options ? options.description : this.description
        };


        const updatedData = await Rest.patch(this.client.token, `/guilds/${this.id}`, requestData);

        Object.assign(this, {
            name: updatedData.name,
            afkChannelId: updatedData.afk_channel_id,
            afkTimeout: updatedData.afk_timeout,
            systemChannelId: updatedData.system_channel_id,
            systemChannelFlags: updatedData.system_channel_flags,
            verificationLevel: updatedData.verification_level,
            explicitContentFilter: updatedData.explicit_content_filter,
            defaultMessageNotifications: updatedData.default_message_notifications,
            icon: updatedData.icon,
            splash: updatedData.splash,
            discoverySplash: updatedData.discovery_splash,
            banner: updatedData.banner,
            rulesChannelId: updatedData.rules_channel_id,
            publicUpdatesChannelId: updatedData.public_updates_channel_id,
            preferredLocale: updatedData.preferred_locale,
            description: updatedData.description
        });

        return this;
    }

    async setName(name) {
        if (typeof name !== 'string' || name.length < 1 || name.length > 100) {
            throw new Error("Name must be a string between 1 and 100 characters.");
        }

        return await this.edit({ name });
    }

    async setAFKChannel(channel) {
        const channelId = typeof channel === 'string' ? channel : channel?.id;

        if (!channelId || typeof channelId !== 'string') {
            throw new Error("[Vunsh]");
        }

        const fullChannel = await this.channels.fetch(channelId);

        if (!fullChannel || fullChannel.type !== 2) {
            throw new Error("AFK channel must be a voice channel.");
        }

        return await this.edit({ afkChannelId: channelId });
    }

    async setAFKTimeout(timeout) {
        const validTimeouts = [60, 300, 900, 1800, 3600];
        if (!validTimeouts.includes(timeout)) {
            throw new Error("Timeout must be one of the following values in seconds: 60, 300, 900, 1800, or 3600.");
        }

        const updatedData = await Rest.patch(this.client.token, `/guilds/${this.id}`, {
            afk_timeout: timeout
        });

        Object.assign(this, {
            afkTimeout: updatedData.afk_timeout
        });

        return this;
    }

    async setIcon(icon) {
        if (icon !== null && typeof icon !== 'string') {
            throw new Error("Icon must be a string (data URI, URL) or null to remove it.");
        }

        if (icon === null) {
            return await this.edit({ icon: null });
        }

        if (icon.startsWith('http')) {
            try {
                const res = await fetch(icon);
                if (!res.ok) throw new Error(`Failed to fetch image from URL: ${res.statusText}`);
                const contentType = res.headers.get('content-type');
                const buffer = await res.buffer();
                const base64 = buffer.toString('base64');
                icon = `data:${contentType};base64,${base64}`;
            } catch (err) {
                throw new Error(`Failed to process image URL: ${err.message}`);
            }
        }

        return await this.edit({ icon });
    }

    async setBanner(banner) {
        if (banner !== null && typeof banner !== 'string') {
            throw new Error("Banner must be a string (data URI, URL) or null to remove it.");
        }

        if (banner === null) {
            return await this.edit({ banner: null });
        }

        if (banner.startsWith('http')) {
            try {
                const res = await fetch(banner);
                if (!res.ok) throw new Error(`Failed to fetch image from URL: ${res.statusText}`);
                const contentType = res.headers.get('content-type');
                const buffer = await res.buffer();
                const base64 = buffer.toString('base64');
                banner = `data:${contentType};base64,${base64}`;
            } catch (err) {
                throw new Error(`Failed to process banner image URL: ${err.message}`);
            }
        }

        return await this.edit({ banner });
    }

    async setSplash(splash) {
        if (splash !== null && typeof splash !== 'string') {
            throw new Error("Splash must be a string (data URI, URL) or null to remove it.");
        }

        if (splash === null) {
            return await this.edit({ splash: null });
        }

        if (splash.startsWith('http')) {
            try {
                const res = await fetch(splash);
                if (!res.ok) throw new Error(`Failed to fetch splash image from URL: ${res.statusText}`);
                const contentType = res.headers.get('content-type');
                const buffer = await res.buffer();
                const base64 = buffer.toString('base64');
                splash = `data:${contentType};base64,${base64}`;
            } catch (err) {
                throw new Error(`Failed to process splash image URL: ${err.message}`);
            }
        }

        return await this.edit({ splash });
    }

    async setDiscoverySplash(splash) {
        if (splash !== null && typeof splash !== 'string') {
            throw new Error("Discovery splash must be a string (data URI, URL) or null to remove it.");
        }

        if (splash === null) {
            return await this.edit({ discovery_splash: null });
        }

        if (splash.startsWith('http')) {
            try {
                const res = await fetch(splash);
                if (!res.ok) throw new Error(`Failed to fetch discovery splash image from URL: ${res.statusText}`);
                const contentType = res.headers.get('content-type');
                const buffer = await res.buffer();
                const base64 = buffer.toString('base64');
                splash = `data:${contentType};base64,${base64}`;
            } catch (err) {
                throw new Error(`Failed to process discovery splash image URL: ${err.message}`);
            }
        }

        return await this.edit({ discovery_splash: splash });
    }

    async setSystemChannel(channel) {
        let channelId = null;

        if (typeof channel === 'string') {
            channelId = channel;
        } else if (typeof channel === 'object' && channel !== null && 'id' in channel) {
            channelId = channel.id;
        } else if (channel !== null) {
            throw new Error("Channel must be a string (channel ID), an object with an 'id' property, or null.");
        }

        return await this.edit({ systemChannelId: channelId });
    }

    async setSystemChannelFlags(flags) {
        if (typeof flags !== 'number') {
            throw new Error("Flags must be a number representing a bitfield.");
        }

        return await this.edit({ systemChannelFlags: flags });
    }

    async setPublicUpdatesChannel(channel) {
        const channelId = typeof channel === 'string' ? channel : channel?.id;

        if (!channelId || typeof channelId !== 'string') {
            throw new Error("Invalid channel provided. Must be a string ID or a channel object with an ID.");
        }

        const fullChannel = await this.channels.fetch(channelId);
        if (!fullChannel) {
            throw new Error("Channel not found in this guild.");
        }

        return await this.edit({ publicUpdatesChannelId: channelId });
    }

    async setRulesChannel(channel) {
        const channelId = typeof channel === 'string' ? channel : channel?.id;
    
        if (!channelId || typeof channelId !== 'string') {
            throw new Error("Invalid channel ID.");
        }
    
        const fullChannel = await this.channels.fetch(channelId);
    
        if (!fullChannel || ![0, 5].includes(fullChannel.type)) {
            throw new Error("Rules channel must be a text or announcement channel.");
        }
    
        return await this.edit({ rulesChannelId: channelId });
    }
}

module.exports = Guild;

This is my Rest.js file

/**
 * A utility class for making HTTP requests to the Discord API.
 */
module.exports = class Rest {
    /**
     * Makes a GET request to the Discord API.
     * 
     * @param {string} authorization - The bot token.
     * @param {string} endpoint - The API endpoint to send the GET request to (e.g., `/guilds/{guildId}`).
     * @returns {Promise<Object>} A promise that resolves to the parsed JSON response from the API.
     * @throws {Error} Throws an error if the API request fails or returns an invalid response.
     * @private
     */
    static async get(authorization, endpoint) {
        const response = await fetch(`https://discord.com/api/v10${endpoint}`, {
            method: 'GET',
            headers: {
                'Authorization': `Bot ${authorization}`,
                'Content-Type': 'application/json'
            }
        });

        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }

        return await response.json();
    }

    /**
     * Makes a PATCH request to the Discord API.
     * 
     * @param {string} authorization - The bot token.
     * @param {string} endpoint - The API endpoint to send the PATCH request to (e.g., `/guilds/{guildId}`).
     * @param {Object} data - The JSON body data to send with the PATCH request.
     * @returns {Promise<Object>} A promise that resolves to the parsed JSON response from the API.
     * @throws {Error} Throws an error if the API request fails or returns an invalid response.
     * @private
     */
    static async patch(authorization, endpoint, data) {
        const response = await fetch(`https://discord.com/api/v10${endpoint}`, {
            method: 'PATCH',
            headers: {
                'Authorization': `Bot ${authorization}`,
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });

        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }

        return await response.json();
    }
};

Shift data associated with an array’s index based on filter data

I have an array of any values, as well as data associated with each value.
This data is stored as Record<string,FooData> where the key is generated using the index within the array.

However, I am struggling to implement a correct solution for shifting the meta back to their correct place after the array has been filtered.

An example scenario:
[ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' ]

The array is then filtered outside of my function. The old array is unknown, all that remains is the following data:

  • The new array is [ 'a', 'b', 'd', 'e', 'h', 'i', 'j' ]. Remember that it’s unknown[] and not sorted.
  • The indeces of the removed elements from before the filter. In this case, it would be [ 2, 5, 6 ] (corresponding to [ 'c', 'f', 'g' ])
  • The length of the array before it was filtered. In this case 10

Knowing this information, how can I shift all records to their new location? ('h' moved from index 7 to 4)

I do not need to remove dangling data from the end of the array. All data in the record is from before the filter.

Reproducible Example

function getKey(i: number) {
   return `unknownProcess[${i}]`;
}

// Array before the filter
const originalArray = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j' ]
// Associated data is the upper case variant of the letter
const associatedData: Record<string, string> = {}
originalArray.forEach((letter, i) => {
  associatedData[getPath(i)] = letter.toUpperCase();
});
// data[getKey(0)] === 'A'
// data[getKey(2)] === 'C'

// Array after filter
// [ 'a', 'b', 'd', 'e', 'h', 'i', 'j' ]
// data[getKey(0)] === 'A'
// data[getKey(2)] === 'C' // should be 'D' now
// data[getKey(4)] === 'E' // should be 'H' now

type FooData = any

// separate file, cannot access data above
function shiftDataFromFilter(filteredArray: unknown[], data: Record<string, FooData>, removedIndeces: number[], lengthBeforeFilter: number) {
  // to get data of index 0
  const fooData = data[getKey(0)];
}

how to solve valiadation in javascrpt?

I have found this type of error in my code
: Duplicate entry ” for key ‘new_serial_number’
: HHH000010: On release of batch it still contained JDBC statements
: /hardware/update (queryCount: 17)
: Exception occured. in validation when there is not required validation, still error is showing. using HTML,THYMleaf spring

                                        <label><span class="text-danger"><strong>* </strong></span>資産の種類:</label>
                                        <div class="form-inline">
                                            <label class="radio-inline">
                                                <input type="radio" value="true" id="machineTrue"
                                                        th:field="${hardwareForm.machine}"
                                                        th:checked="${hardwareForm.machine}" />マシン
                                            </label>
                                            <label class="radio-inline">
                                                <input type="radio" value="false" id="machineFalse"
                                                        th:field="${hardwareForm.machine}"
                                                        th:checked="${hardwareForm.machine}" />マシン以外
                                            </label>
                                        </div>
                                    </div></div>

                                


                                        <div class="form-group col-md-5">
                                            <label><span class="text-danger"><strong>* </strong></span>製造番号:
                                            </label>
                                            <input type="hidden" id="tmp_newSerialNumber"></input>
                                            <input class="form-control" th:field="*{newSerialNumber}"
                                                th:id="newSerialNumber"></input>
                                            <span class="error_frontSide" style="color: red;"></span>
                                            <span class="errorField" th:if="${#fields.hasErrors('newSerialNumber')}"
                                                th:errors="*{newSerialNumber}" style="color: red"></span>

                                        </div>  here number is depependant on マシン. i wnat to show マシン when number is clicked only, not for マシン以外,.

Backend development [closed]

I’m a systems engineering student in Mexico. I’m interested in backend engineering because of a project I need to develop. So, if anyone could give me advice or recommend tutorials so I can learn more about this and pursue it professionally, I’d be very grateful

I expect help from developers

Why is my CSS Grid code not working on my HTML form even though it should be working? What’s wrong with it?

Trying to implement CSS grids for this “Job Application” page for an assignment and I’ve been stuck for a good 3 hours trying to figure out what’s wrong with it even though I’ve followed like 5 different tutorials and I’ve followed their instructions and it’s not working.
here is the code

* {
  font-family: Cambria, Cochin, Georgia, Times, 'Times New Roman', serif;
}

body,
html,
h1,
h2 {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

h1,
h2 {
  color: #46767E;
}

.job-title {
  background-color: #EBC4BB;
  padding: 12px;
  margin: 0;
}

h3 {
  padding-left: 20px;
}

/* Grid Boxes for Application */
fieldset {
  border: 0
}

.container {
  display: grid;
  grid-template-rows: repeat(6, auto);
  /* Changed to auto for flexibility */
  grid-template-columns: repeat(3, 1fr);
  /* Using fr units for better responsiveness */
  gap: 5px;
  padding: 5px;
  text-align: center;
}

.job-number {
  background-color: #EBC4BB;
  padding: 20px;
  border: solid #46767E;
  text-align: center;
  grid-row: 1 / 2;
  grid-column: 1 / 3;
}

.job-personalinfo {
  background-color: #EBC4BB;
  padding: 20px;
  border: solid #46767E;
  text-align: center;
  grid-row: 2 / 4;
  grid-column: 1 / 2;
}
<h1 id="page-title">Job Application Form</h1>
<hr>
<main>
  <div class="container">

    <form action="https://mercury.swin.edu.au/it000000/formtest.php" method="POST" enctype="multipart/form-data"> <!-- Action needs to handle submissions -->
      <div class="job-number">
        <label for="job-ref">Job Reference Number:</label>
        <select id="job-ref" name="job_ref" required>
          <option value="" disabled selected>Select your job reference</option>
          <option value="001">001-Front-End Developer</option>
          <option value="002">002-Back-End Developer</option>
          <option value="003">003-Full-Stack Developer</option>
          <option value="004">004-Web Designer</option>
          <option value="005">005-Data Analyst/option>
          <option value="006">006-UX/UI Designer</option>
          <option value="007">007-Software Engineer</option>
          <option value="008">008-Project Manager</option>
          <option value="009">009-Quality Assurance Tester</option>
          <option value="010">010-DevOps Engineer</option>
          <!-- Add more options as necessary -->
        </select>
      </div>

      <br><br>

      <div class="job-personalinfo">
        <fieldset>
          <h3>Personal information</h3>

          <label for="first-name">First Name:</label>
          <input type="text" id="first-name" name="first_name" maxlength="20" required placeholder="Luke">

          <label for="last-name">Last Name:</label>
          <input type="text" id="last-name" name="last_name" maxlength="20" required placeholder="Skywalker">

          <!-- <br><br> -->

          <label for="dob">Date of Birth:</label>
          <input type="date" id="dob" name="dob" required>
          <p>Gender</p>
          <input type="radio" id="male" name="gender" value="male" required>
          <label for="male">Male</label>
          <input type="radio" id="female" name="gender" value="female">
          <label for="female">Female</label>
          <input type="radio" id="other" name="gender" value="other">
          <label for="other">Other</label>
        </fieldset>
      </div>
      <br>

      <br>

      <div class="job-address">
        <fieldset>
          <legend>Address</legend>

          <label for="address">Street Address:</label>
          <input type="text" id="address" name="address" maxlength="40" required>

          <label for="suburb">Suburb/Town:</label>
          <input type="text" id="suburb" name="suburb" maxlength="40" required>

          <label for="state">State:</label>
          <select id="state" name="state" required>
            <option value="" disabled selected>Select your state</option>
            <option value="VIC">VIC</option>
            <option value="NSW">NSW</option>
            <option value="QLD">QLD</option>
            <option value="NT">NT</option>
            <option value="WA">WA</option>
            <option value="SA">SA</option>
            <option value="TAS">TAS</option>
            <option value="ACT">ACT</option>
          </select>

          <label for="postcode">Postcode:</label>
          <input type="text" id="postcode" name="postcode" pattern="[0-9]{4}"  maxlength="4" required title="Exactly 4 digits.">
        </fieldset>
      </div>

      <br>

      <fieldset>
        <legend>Contact information</legend>

        <label for="email">Email Address:</label>
        <input type="email" id="email" name="email" required placeholder="[email protected]">

        <label for="phone">Phone Number:</label>
        <input type="tel" id="phone" name="phone" pattern="[0-9 ]{8,12}" required title="8 to 12 digits or spaces." placeholder="(000) 000-0000">
      </fieldset>

      <br>

      <fieldset>
        <legend>Required Technical Skills:</legend>
        <label for="skill1">HTML/CSS</label>
        <input type="checkbox" id="skill2" name="technical_skills" value="skill2">
        <label for="skill2">JavaScript</label>
        <input type="checkbox" id="skill3" name="technical_skills" value="skill3">
        <label for="skill3">Node.js</label>
        <label for="skill1">Python</label>
        <input type="checkbox" id="skill1" name="technical_skills" value="skill1">
        <label for="skill1">SQL</label>
        <label for="skill1">Version Control (Git)</label>
        <label for="skill1">Graphic Design (Adobe XD, Figma)</label>
        <!-- Add more skills as necessary -->
      </fieldset>

      <br>

      <fieldset>
        <legend>Other skills</legend>
        <textarea id="other-skills" name="other_skills" rows="4" placeholder="Please list any other skills you may have..."></textarea>
      </fieldset>

      <br>

      <button type="submit">Submit Application</button>
      <button type="reset">Re-do application</button>
    </form>

  </div>
</main>

here is what it currently looks like vs what im aiming for

here is what it currently looks like vs what im aiming for

I’d really appreciate any help I can get. I have no idea how to do this since this is my first time using grid.

TypeError: i.map is not a function

I’ve just added a new functionality to my project that needs .map(), in the dev environment all went well with no errors, but when I deployed the code to production, in the live environment this error appeared for some reason in the console of the browser. Uncaught TypeError: i.map is not a function.

this is the code that uses .map() I added:

function DisplayAutoSearchCompany({ autoSearch, input, handleClick }) {
  const companiesArray = [
    "GMS",
    "RT Colors",
    "Potência",
    "Kaitos",
    "Papel Safra",
  ];

  return (
    <>
      <ul
        className="autosearch"
        style={{ visibility: autoSearch ? "visible" : "hidden" }}
      >
        {companiesArray
          .sort()
          .filter((item) => item.toLowerCase().includes(input.toLowerCase()))
          .map((item, index) => (
            <textarea
              onClick={handleClick}
              key={index}
              value={item}
              name="company"
              readOnly
            >
              {item}
            </textarea>
          ))}
      </ul>
    </>
  );
}

export default DisplayAutoSearchCompany;

and this is the code where the props are coming:

import { useState } from "react";
import DisplayAutoSearchCompany from "./DisplayAutoSearchCompany.jsx";
import DisplayAutoSearchProduct from "./DisplayAutoSearchProduct.jsx";

function DisplayInput({ addCollect }) {
  const [autoSearchCompany, setAutoSearchCompany] = useState(false);
  const [autoSearchProduct, setAutoSearchProduct] = useState(false);
  const [input, setInput] = useState({
    company: "",
    date: "",
    product: "",
  });

  function handleInput(event) {
    setInput((i) => ({ ...i, [event.target.name]: event.target.value }));
  }

  function handleMouseDown(event) {
    if (event.target.name == "company") {
      setAutoSearchCompany(true);
      setAutoSearchProduct(false);
    }
    if (event.target.name == "product") {
      setAutoSearchProduct(true);
      setAutoSearchCompany(false);
    }
  }

  function handleClick(event) {
    setInput((i) => ({ ...i, [event.target.name]: event.target.value }));
    setAutoSearchCompany(false);
    setAutoSearchProduct(false);
  }

  return (
    <tbody>
      <tr>
        <td>
          <input
            onChange={handleInput}
            onMouseDown={handleMouseDown}
            value={input.company}
            type="text"
            name="company"
            placeholder="Empresa"
            required
            autoComplete="off"
          />
        </td>
        <td>
          <input
            onChange={handleInput}
            value={input.date}
            type="text"
            name="date"
            placeholder="Data"
            required
            autoComplete="off"
          />
        </td>
        <td>
          <input
            onChange={handleInput}
            onMouseDown={handleMouseDown}
            value={input.product}
            type="text"
            name="product"
            placeholder="Material"
            required
            autoComplete="off"
          />
        </td>
        <td>
          <img
            src="/assets/images/add.png"
            alt="add button"
            onClick={() => addCollect(input)}
          />
        </td>
      </tr>
      <tr>
        <td>
          <DisplayAutoSearchCompany
            autoSearch={autoSearchCompany}
            input={input}
            handleClick={handleClick}
          />
        </td>
        <td></td>
        <td>
          <DisplayAutoSearchProduct
            autoSearch={autoSearchProduct}
            input={input}
            handleClick={handleClick}
          />
        </td>
      </tr>
    </tbody>
  );
}

export default DisplayInput;

How can I know if there is another item with same property value with map JavaScript

I want to know how can I see if there is already an element with the same ia value and based on that asign the same posicion value

let data = [
    {
        "idMiembro": 6,
        "ia": "21.13"
    },
    {
        "idMiembro": 175,
        "ia": "20.89"
    },
    {
        "idMiembro": 165,
        "ia": "19.52"
    },
    {
        "idMiembro": 101,
        "ia": "18.83"
    },
    {
        "idMiembro": 51,
        "ia": "17.88"
    },
    {
        "idMiembro": 86,
        "ia": "17.83"
    },
    {
        "idMiembro": 195,
        "ia": "17.79"
    },
    {
        "idMiembro": 161,
        "ia": "17.65"
    },
    {
        "idMiembro": 103,
        "ia": "17.65"
    },
    {
        "idMiembro": 187,
        "ia": "17.57"
    },
    {
        "idMiembro": 178,
        "ia": "17.50"
    },
    {
        "idMiembro": 163,
        "ia": "17.42"
    },
    {
        "idMiembro": 28,
        "ia": "17.29"
    },
    {
        "idMiembro": 7,
        "ia": "17.21"
    },
    {
        "idMiembro": 104,
        "ia": "17.19"
    },
    {
        "idMiembro": 100,
        "ia": "17.12"
    },
    {
        "idMiembro": 84,
        "ia": "16.90"
    },
    {
        "idMiembro": 152,
        "ia": "16.89"
    },
    {
        "idMiembro": 184,
        "ia": "14.48"
    }
]

      data.map((item, index) => {
// here is where I want to add the same value if there is already an element with the same ia value but i dont know how to do it
        item.posicion = index + 1;
        item.totalPromocion = data.length;

        return null;
      });

The idea is that after that maps the array looked like this

let data2 = [
    {
        "idMiembro": 6,
        "ia": "21.13",
        "posicion": 1,
        "totalPromocion": 19
    },
    {
        "idMiembro": 175,
        "ia": "20.89",
        "posicion": 2,
        "totalPromocion": 19
    },
    {
        "idMiembro": 165,
        "ia": "19.52",
        "posicion": 3,
        "totalPromocion": 19
    },
    {
        "idMiembro": 101,
        "ia": "18.83",
        "posicion": 4,
        "totalPromocion": 19
    },
    {
        "idMiembro": 51,
        "ia": "17.88",
        "posicion": 5,
        "totalPromocion": 19
    },
    {
        "idMiembro": 86,
        "ia": "17.83",
        "posicion": 6,
        "totalPromocion": 19
    },
    {
        "idMiembro": 195,
        "ia": "17.79",
        "posicion": 7,
        "totalPromocion": 19
    },
    {
        "idMiembro": 161,
        "ia": "17.65",
        "posicion": 8,
        "totalPromocion": 19
    },
    {
        "idMiembro": 103,
        "ia": "17.65",
// this element has the same 'posicion' value than the previous one
        "posicion": 8,
        "totalPromocion": 19
    },
    {
        "idMiembro": 187,
        "ia": "17.57",
        "posicion": 10,
        "totalPromocion": 19
    },
    {
        "idMiembro": 178,
        "ia": "17.50",
        "posicion": 11,
        "totalPromocion": 19
    },
    {
        "idMiembro": 163,
        "ia": "17.42",
        "posicion": 12,
        "totalPromocion": 19
    },
    {
        "idMiembro": 28,
        "ia": "17.29",
        "posicion": 13,
        "totalPromocion": 19
    },
    {
        "idMiembro": 7,
        "ia": "17.21",
        "posicion": 14,
        "totalPromocion": 19
    },
    {
        "idMiembro": 104,
        "ia": "17.19",
        "posicion": 15,
        "totalPromocion": 19
    },
    {
        "idMiembro": 100,
        "ia": "17.12",
        "posicion": 16,
        "totalPromocion": 19
    },
    {
        "idMiembro": 84,
        "ia": "16.90",
        "posicion": 17,
        "totalPromocion": 19
    },
    {
        "idMiembro": 152,
        "ia": "16.89",
        "posicion": 18,
        "totalPromocion": 19
    },
    {
        "idMiembro": 184,
        "ia": "14.48",
        "posicion": 19,
        "totalPromocion": 19
    }
]

Thanks

where to store jwt tokens with angular [closed]

i have a web app and im using JWT token to identify users, for the moment im savng the token within the state using ngrx like this:

 export const authReducer = createReducer(
  initialAuthState,
  on(LoginSuccess, LoginSuccessNotEnabled, ValidationSuccess, LoginSuccessNotSetUp, (state, action) => ({
    ...state,
    isLoggedIn: true,
    token: action.token
  }))
);

but since the state gets lost when reloading pages, what is a more durable way of storing said token. i see localStorage floating around but that is exposed to XSS, and cookies are cumbersome since my backend is set to verify auth headers and not cookies.

Combining Multiple Toggle Functions

I have three clunky ‘open div/aside’ functions that I’d like to condense into one simple, streamlined function that will take any number of aside elements as arguments. I am only using Vanilla JS for this project, so any vanilla advice is appreciated.

Here is my clunky JS:

const buttonOne = document.querySelector("#toggle1");
const buttonTwo = document.querySelector("#toggle2");
const buttonThree = document.querySelector("#toggle3");    
const windowOne = document.querySelector("#window1");
const windowTwo = document.querySelector("#window2");
const windowThree = document.querySelector("#window3");
const windows = document.querySelectorAll("aside");

function toggleOne() {
    if (windowOne.style.display === "none") {windowOne.style.display = "block"; for (i = 0; i < windows.length; i++) {
        windows[i].classList.remove('active');
    }; windowOne.classList.add('active')} else {  
        windowOne.style.display = "none";}
}

function toggleTwo() {
    if (windowTwo.style.display === "none") {windowTwo.style.display = "block"; for (i = 0; i < windows.length; i++) {
        windows[i].classList.remove('active');
    }; windowTwo.classList.add('active')} else {  
        windowTwo.style.display = "none";}
}

function toggleThree() {
    if (windowThree.style.display === "none") {windowThree.style.display = "block"; for (i = 0; i < windows.length; i++) {
        windows[i].classList.remove('active');
    }; windowThree.classList.add('active')} else {  
        windowThree.style.display = "none";}
}

And here is my non-functioning attempt at a general function; 100% chance I’m missing something obvious:

function toggle(event) {
    if (event.target.style.display === "none") {event.target.style.display = "block"; for (i = 0; i < windows.length; i++) {
        windows[i].classList.remove('active');
    }; event.target.classList.add('active')} else {  
        event.target.style.display = "none";}
}

This is the body of my HTML, with toggle() as the onclick function:

<div id="frame">
      <button id="toggle1" onclick="toggle()">toggle 1</button>
      <button id="toggle2" onclick="toggle()">toggle 2</button>
      <button id="toggle3" onclick="toggle()">toggle 3</button>
      <aside
        draggable="true"
        id="window1"
        onclick="bringForward(this)"
        style="display: none"
      >
        I'm on the move!
      </aside>
      <aside
        draggable="true"
        id="window2"
        onclick="bringForward(this)"
        style="display: none"
      >
        Here we go!
      </aside>
      <aside
        draggable="true"
        id="window3"
        onclick="bringForward(this)"
        style="display: none"
      >
        All together now!
      </aside>
    </div>

How to go about converting Node.js Add-On bindings in C++ to target compilation to WASM?

Context

There’s an existing HTTP/3 and WebTransport library written exclusively for Node.js, using Node-API. The server implementation works with Chromium and Firefox as clients. node runs the server just fine. bun can run the server though exists with an error

E0413 22:42:56.932056   82865 quic_connection.cc:2613] quic_bug_12714_21: ProcessUdpPacket must not be called while processing a packet.
terminate called after throwing an instance of 'Napi::Error'
  what():  ReadableStream is not readable
Aborted

deno starts the server, then errors when client tries to connect

terminate called after throwing an instance of 'Napi::Error'
  what():  this.socketInt.getSendQueueCount is not a function
Aborted

Deno’s HTTP/3 WebTransport implementation works for deno and chrome as clients, does not work when Firefox is the client.

So I’m selecting the Node.js, Node-API implementation for my purposes, due to the broadest reach for usage among JavaScript runtimes.

Chore

Figure out a way to convert the Node-API bindings in C++ to WASM (with or without WASI support) for the capability to run the same server code using node, deno, bun, and eventually in chrome.

The binding look like this

    void Http3WTSessionJS::processStream(bool incom, bool bidi, uint64_t sendOrder, uint64_t sendGroupId, Http3WTStream *stream)
    {
        Napi::HandleScope scope(Env());
        Http3Constructors *constr = Env().GetInstanceData<Http3Constructors>();
        Napi::Object strobj = constr->stream.New({});
        Http3WTStreamJS *strjs = Napi::ObjectWrap<Http3WTStreamJS>::Unwrap(strobj);
        strjs->setObj(stream);
        if (!stream->gone())
            strjs->Ref();

        stream->setJS(strjs);

        Napi::Object objVal = Value().Get("jsobj").As<Napi::Object>();

        Napi::Object retObj = Napi::Object::New(Env());
        retObj.Set("stream", strobj);
        retObj.Set("incoming", incom);
        retObj.Set("bidirectional", bidi);
        retObj.Set("sendOrder", sendOrder);
        retObj.Set("sendGroupId", sendGroupId);

        objVal.Get("onStream").As<Napi::Function>().Call(objVal, {retObj});
    }

and there’s a bunch of them

Here are some pointers for http/3: https://github.com/fails-components/webtransport/blob/master/transports/http3-quiche/src/http3wtsessionvisitor.cc

all these use NAPI for node binding and would need a replacement, if compiled to wasm. (Including the mechanims for alarams and napialarmfactory and sockerjswriter.cc.

There’s a tsconfig.json and an existing build roadmap that uses cmake-js that includes lines such as

switch (argv[2]) {
    case 'prebuild':
      try {
        await prebuild([
          '-t',
          '6',
          '-r',
          'napi',
          '--strip',
          ...pbargspre,
          '--backend',
          'cmake-js',
          '--',
          ...pbargs
        ])
      } catch (error) {
        console.log('prebuild failed')
        process.exit(1)
      }
      break
    case 'install': 
      try {
        const pbres = await prebuildInstall([
          '-r',
          'napi',
          '-d',
          '-t',
          '6',
          '--verbose'
        ])

Status, options

If no one has encountered this case and documented their steps, then the default answer is do the necessary conversions in preparation for compilation to WASM, and eventually JavaScript, using Binaryen’s wasm2js, by hand.

Question

Has anybody encountered this kind of exiting code, and used some automated existing build system that converts Napi bindings, to exported functions which a tool such as WASI-SDK’s clang, or even Emscripten; if yes, what’s your roadmap?

Unable to read properties of document.body.style [duplicate]

I’m trying to set the style of a body element, but I’m getting this error:

Uncaught TypeError: Cannot read properties of null (reading 'style')
    at updateColour (coloured_fade.html:15:22)

I thought that this might be because the body element hasn’t loaded yet but it is scheduled in (and thus runs after) the onload event handler, which means the body should have loaded.

This is my code:

<!DOCTYPE html>
<html>
    <head>
        <title>Coloured Fade</title>
        <style>
            html, body {
              height: 100%;
            }
        </style>
        <script>
            let body = document.body;
            var i = 0;
            var timerId;
            function updateColour() {
                body.style.backgroundColor = "hsl(${i}, 100, 45)";
                i++;
            }
            window.onload = function() {timerId = setInterval(updateColour, 20);};
        </script>
    </head>
    <body>
        <!-- blank, this is where the colour should be -->
    </body>
</html>

If it’s relevent, I’m viewing the page in the Chromium browser.