Angular: Input with a default value that cannot be cleared

I am new working with angular and I have this code

<mat-form-field appearance="outline" class="col-30" id="mat-identifier">
                <mat-label>{{'columns.dashboard.identifier' | translate}} {{selectedIdentifier?.mandatorieIdentifier ? '*' : ''}}</mat-label>
                <input matInput [value]="selectedIdentifier?.standardIdentifier" formControlName="identifier" maxlength="255" (input)="limitcarateres('identifier', 255, $event)" >
                <mat-hint *ngIf="showPackage!=true && selectedIdentifier && selectedIdentifier?.tag !== 'OTHERS'">{{selectedIdentifier?.standardIdentifier + (dataCorrespondenceForm.get('identifier').value !== null && dataCorrespondenceForm.get('identifier').value !== '' ? '-' + dataCorrespondenceForm.get('identifier').value : '')}}</mat-hint>
              </mat-form-field>

I want this input to show a default value equal to the variable I am using but this value cannot be deleted by the user, the user should be able to write from this default value but not be able to delete it, assuming that the # are the default values and the numbers are the values added by the user, it should be seen like this
####123456
The numbers can be deleted but the # cannot, since the numbers were entered by the user

How to add json data and show in particular tag

import React from "react";
import "./Body.css";
import { useState, useEffect } from "react";

const Body = () => {

    const [value, setValue] = useState("2");

    const handleClick = () => {
      setValue("3")
    }

    useEffect(() => {
        fetch("http://localhost:3000/delivery_centers")
            .then((res) => {
                return res.json();
            }).then((data) => {
                console.log(data);
            })
    }, [])


    return (
        <div className="container">
            <h1 id="myTD">To Be Dispatched</h1>
            <hr></hr>
            
            <button className="Dbtn" onClick= {handleClick}>LM</button>          
            <button className="Dbtn">FM</button>
            <button className="Dbtn">RT</button>
            <br></br><br></br>
            <div className="report">
                
                <span>    
                    <h2 id="r4">{value}</h2>
                    <label htmlFor="r4">Shipments</label>
                </span>
                <span className="rBtn">
                    <h2 id="r1">1</h2>
                    <label htmlFor="r1">WIP</label>
                </span>
                <span className="rBtn">
                    <h2 id="r2">1</h2>
                    <label htmlFor="r2">Flash</label>
                </span>
                <span className="rBtn">
                    <h2 id="r3">1</h2>
                    <label htmlFor="r3">Dispatch</label>
                </span>
            </div>
            <div className="graph">
                <ul className="status">
                    <li>
                        <span class="progress"></span>
                        Forward
                    </li>
                    <li>
                        <span class="progress"></span>
                        BFSI
                    </li>
                    <li>
                        <span class="progress"></span>
                        Reattempt
                    </li>
                    <li>
                        <span class="progress"></span>
                        Reverse
                    </li>
                    <li>
                        <span class="progress"></span>
                        KYC
                    </li>
                    <li>
                        <span class="progress"></span>
                        C2C
                    </li>
                </ul>
                <div className="dsbtn">
                    <h1 id="cdBtn">CREATE DISPATCH</h1>
                    <span id="arrow" class="material-symbols-outlined">arrow_forward_ios</span>
                </div>
            </div>
        </div>

    )
}

export default Body;

I want to show delivery center id in H2 tag above Shipments when I click on LM button with below json data

import React from "react";
import "./Body.css";
import { useState, useEffect } from "react";

const Body = () => {

    const [value, setValue] = useState("2");

    const handleClick = () => {
      setValue("3")
    }

    useEffect(() => {
        fetch("http://localhost:3000/delivery_centers")
            .then((res) => {
                return res.json();
            }).then((data) => {
                console.log(data);
            })
    }, [])


    return (
        <div className="container">
            <h1 id="myTD">To Be Dispatched</h1>
            <hr></hr>
            
            <button className="Dbtn" onClick= {handleClick}>LM</button>          
            <button className="Dbtn">FM</button>
            <button className="Dbtn">RT</button>
            <br></br><br></br>
            <div className="report">
                
                <span>    
                    <h2 id="r4">{value}</h2>
                    <label htmlFor="r4">Shipments</label>
                </span>
                <span className="rBtn">
                    <h2 id="r1">1</h2>
                    <label htmlFor="r1">WIP</label>
                </span>
                <span className="rBtn">
                    <h2 id="r2">1</h2>
                    <label htmlFor="r2">Flash</label>
                </span>
                <span className="rBtn">
                    <h2 id="r3">1</h2>
                    <label htmlFor="r3">Dispatch</label>
                </span>
            </div>
            <div className="graph">
                <ul className="status">
                    <li>
                        <span class="progress"></span>
                        Forward
                    </li>
                    <li>
                        <span class="progress"></span>
                        BFSI
                    </li>
                    <li>
                        <span class="progress"></span>
                        Reattempt
                    </li>
                    <li>
                        <span class="progress"></span>
                        Reverse
                    </li>
                    <li>
                        <span class="progress"></span>
                        KYC
                    </li>
                    <li>
                        <span class="progress"></span>
                        C2C
                    </li>
                </ul>
                <div className="dsbtn">
                    <h1 id="cdBtn">CREATE DISPATCH</h1>
                    <span id="arrow" class="material-symbols-outlined">arrow_forward_ios</span>
                </div>
            </div>
        </div>

    )
}

export default Body;

I tried

import React from "react";
import "./Body.css";
import { useState, useEffect } from "react";

const Body = () => {

    const [value, setValue] = useState(null);

    const handleClick = (id) => {
        const Cname = value.delivery_centers.filter(val => val.id !== id);
        setValue(Cname);
    }

    useEffect(() => {
        fetch("http://localhost:3000/delivery_centers")
            .then((res) => {
                return res.json();
            }).then((data) => {
                setValue(data);
            })
    }, [])


    return (
        <div className="container">
            <h1 id="myTD">To Be Dispatched</h1>
            <hr></hr>
            {value && value.delivery_centers && value.delivery_centers.map((val) =>
                <button className="Dbtn" key={val.id} onClick={() => handleClick(val.id)}>LM</button>
            )}            
            <button className="Dbtn">FM</button>
            <button className="Dbtn">RT</button>
            <br></br><br></br>
            <div className="report">
                <span className="rBtn">
                    {value && value.delivery_centers && value.delivery_centers.map((val) =>
                        <h2 id="r4" key={val.id}>{val.name}</h2>
                    )}

                    <label htmlFor="r4">Shipments</label>
                </span>
                <span className="rBtn">
                    <h2 id="r1">1</h2>
                    <label htmlFor="r1">WIP</label>
                </span>
                <span className="rBtn">
                    <h2 id="r2">1</h2>
                    <label htmlFor="r2">Flash</label>
                </span>
                <span className="rBtn">
                    <h2 id="r3">1</h2>
                    <label htmlFor="r3">Dispatch</label>
                </span>
            </div>
            <div className="graph">
                <ul className="status">
                    <li>
                        <span class="progress"></span>
                        Forward
                    </li>
                    <li>
                        <span class="progress"></span>
                        BFSI
                    </li>
                    <li>
                        <span class="progress"></span>
                        Reattempt
                    </li>
                    <li>
                        <span class="progress"></span>
                        Reverse
                    </li>
                    <li>
                        <span class="progress"></span>
                        KYC
                    </li>
                    <li>
                        <span class="progress"></span>
                        C2C
                    </li>
                </ul>
                <div className="dsbtn">
                    <h1 id="cdBtn">CREATE DISPATCH</h1>
                    <span id="arrow" class="material-symbols-outlined">arrow_forward_ios</span>
                </div>
            </div>
        </div>

    )
}

export default Body;

I’m working on a React component that displays delivery center information and allows users to choose a center. I’m facing an issue where clicking the “LM” button isn’t showing the corresponding delivery center ID above the “Shipments” label as intended.

Expected behavior:

When the “LM” button is clicked, the delivery center ID associated with “LM” should be displayed above the “Shipments” label.
Actual behavior:

Nothing happens, or the “LM” button disappears, or the ID is not displayed correctly.
Additional information:

Backend server provides JSON data containing delivery center details.
Any relevant error messages or debugging efforts.
What I’m asking for:

Help identifying the root cause of the issue and any specific code changes needed to achieve the desired behavior.
Suggestions for improving the code structure or handling data fetching effectively.

Narrow type of T[K] when using K extends keyof T, while also making a property optional based on the type of T[K]

I’m trying to define an interface with 2 properties:

  1. The key of a generic type (T)
  2. A function that accepts arguments matching only the type of the generic value at this key (i.e. T[K])

This is fine to do, and plenty of answers exist to solve this problem (e.g. here)

Where it gets a little more tricky is that I also want to make the 2nd property (the sort function) optional only if the inferred value for T[K] is a string or number.

Here is a TS Playground link of what I currently have.

Is there a way to fix npm ERR! code ECONNRESET

I tried to install Parcel using npm install parcel –save-dev , but it failed always

npm ERR! code ECONNRESET
npm ERR! syscall read
npm ERR! errno -4077
npm ERR! network read ECONNRESET
npm ERR! network This is a problem related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'

All went well and finally it was stucked for some time and this error popped up

How to avoid duplication in VSCode intellisense when exporting defaults?

I have a directory structure like so:

  • lib/assets/thing/index.ts
  • lib/assets/thing/stuff/A.svelte
  • lib/assets/thing/stuff/B.svelte
  • lib/assets/thing/stuff/C.svelte
  • lib/assets/thing/stuff/D.svelte

One of these thing/stuff files is just a normal component with markup.

In index.ts i have:

export { default as A } from './stuff/A.svelte';
export { default as B } from './stuff/B.svelte';
export { default as C } from './stuff/C.svelte';
export { default as D } from './stuff/D.svelte';

This way from elsewhere I can import like:

import { A, B, C, D } from '$lib/assets/thing';

rather than:

import A from '$lib/assets/thing/stuff/A.svelte';
import B from '$lib/assets/thing/stuff/B.svelte';
// .etc

The only issue is that VSCode intellisense will show 2 results when auto-completing A, one from $lib/assets/thing and one from $lib/assets/thing/stuff/A.svelte. Without resorting to a vscode setting like typescript.preferences.autoImportFileExcludePatterns, is there a way to structure my asset folder to avoid the suggestion in the thing/stuff folder?

Multiple TinyMCE 6 editors go blank after calling preventDefault() on submit event

I have a use case for multiple TinyMCE 6 editor instances on one page, and as part of the specific validation of content I need to be able to alert the user to a problem without actually submitting the data.

The following code works for a page with a single editor instance:

editor.on('submit', function(event) {
    if (!condition) {
        alert('Notify the user...');
        event.preventDefault();
    }
});

However, on any page with more than one editor instance, the notification occurs and upon clicking through it, all editors go blank and become non-interactive (even editors that do not have this event observed).

I have tried tracing the event stack for individual editors but haven’t had much luck, nor can I find any reference to this in the documentation. I am using the hosted Cloud instance on a paid commercial subscription, and have not tried it with the self-hosted (e.g. npm, yarn) version.

Capture div element animation on top of a video

I was trying to render captions on top of a video (to generate a video with captions on top).
Captions is a simple <p/> tag they are filled fully in width and height with transparent background on top of a video <video/> tag. They are being displayed by 3 word. As the video plays they change accordingly to the words being told in a video.
I needed to get the video of the ongoing Captions with the same length as the video. Because then captionsVideo is being overlayed on top of inputVideo with FFmpeg and i get the video with captions.
But capturing is the problem. I wrote a simple function to capture them html2canvas.

  // Export video
  const exportVideo = async () => {
    const video = videoRef.current; // Define the video element
    const fps = 60; // frames per second
    const interval = 1 / fps; // interval of capturing in seconds
    const frames = []; // array to store the frames (captured screenshots)
    const captureFrame = async () => {
      // If the video has reached the end, remove the event listener and send the frames to the server to convert them to a video
      if (video.currentTime >= video.duration) {
        video.removeEventListener('seeked', captureFrame);
        // Send the frames and video URL to the server
        const response = await fetch('http://127.0.0.1:5000/api/convert', {
          method: 'POST',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify({ frames, width: video.videoWidth, height: video.videoHeight }),
        });
        // If the server returns an error, throw an error
        if (!response.ok) {throw new Error(`Server error: ${response.statusText}`);}
        // If the server returns a success response, download the video
        const blob = await response.blob();
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = 'output.mp4';
        document.body.appendChild(link);
        link.click(); // Click the link to download the end video
        document.body.removeChild(link); // Clean up and remove the link
      }
      // Capture the captions using html2canvas with increased scale and transparent background
      const canvas = await html2canvas(document.querySelector('#captionsContainer'), { scale: 5, backgroundColor: null });
      const dataUrl = canvas.toDataURL(); // Convert the canvas to a data URL
      frames.push(dataUrl); // Push the data URL to the frames array
      video.currentTime += interval; // Move the video's current time forward by the interval
    };    
    video.addEventListener('seeked', captureFrame); // Add the event listener to the video
    video.currentTime = 0; // start at the beginning of the video
  }

They care capturing good but animations (there is a simple popup text animation made with motion.div by framer motion) are rough

<motion.div
  key={currentLine}
  initial={{ opacity: 0, scale: 0.5 }}
  animate={{ opacity: 1, scale: 1 }}
  transition={{
    duration: 0.3,
    ease: [0, 0.71, 0.2, 1.01],
    scale: {
      type: "spring",
      damping: 5,
      stiffness: 100,
      restDelta: 0.001
    }
  }}
>
  <p id="popupText" style={{fontFamily: fontMode, fontWeight: myWeight, textTransform: caseMode,textShadow: `${offsetX}px ${offsetY}px ${blur}px ${shadowColor}`,textAlign: "center"}} className='captions-words' dangerouslySetInnerHTML={{ __html: currentLine }} />
</motion.div>

, because when animation fires it lasts for a certain period of time, and capturer can’t be on time and is capturing only the remains of animation.[enter image description here](https://i.stack.imgur.com/RwlD8.png)

I have tried to use not only html2canvas but also domtoimage, rasterizehtml, canvas2image.
Domtoimage, rasterizehtml, canvas2image provide bad quality during capturing and reset fonts.
Html2canvas resets the position of the captions container.

I tried to use GSAP to sync video and caption’s animation to not hurry the capturer and capture all animations on time. But there is no solution in gsap for that as well as in FRAMER MOTION (in which i am creating all animations)

I have tried to use SCREENCAPTURER API but it requires user’s permission to record an actual video. Hence im taking screenshots.

I expected to get the captions captured with animations perfectly but animations are still rough.

trying to get my public and private key from seed Phrase on solana

I’m trying to get my public and private key from my seed Phrase on solana but they are different and I don’t understand why and can’t find a solution and I really need your help please. here’s my code:

`import { Keypair } from ‘@solana/web3.js’;

const SEED_STRING = “I paste my seed Phrase here”;

const seed = Uint8Array.from(SEED_STRING.split(“,”)).slice(0, 32);

const keypair = Keypair.fromSeed(seed);

console.log(“Private Key:”, keypair.privateKey);
console.log(“Public Key:”, keypair.publicKey);`

this is the error that I get: enter image description here

Test Net Connection from the browser (client side) to AWS servers

How do I build an application where I can run NetConnection tests from my browser to AWS servers? I have the URLs and ports already. I want that any user will be able to have a URL where there is a button with ‘Run Tests’ and it will run automatically on the tests and display the results at the end of the browser. Can I use only JavaScript and HTML?

I build this app on Python and HTML but it is a bad way to implement it.

main.py - 
from flask import Flask, render_template, request
import subprocess

app = Flask(__name__)


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


@app.route('/test_connection', methods=['POST'])
def test_connection():
    results = ''
    connection_tests = {'http://example.com': 80}

    for url, port in connection_tests.items():
        command = f'Test-NetConnection -Port {port} -ComputerName {url}'
        try:
            result = subprocess.run(['powershell', command], capture_output=True, text=True)
            pass_or_fail = 'TcpTestSucceeded : True' in result.stdout.strip().split('n')

            if pass_or_fail:
                results += f"{url} on port {port}: pass n n"
            else:
                results += f"{url} on port {port}: fail n n"
        except Exception as e:
            results += f"An error occurred for {url}:{port}: {str(e)}"

    return render_template('result.html', results=results)


if __name__ == '__main__':
    app.run(debug=True)


results.html - 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Test Connection Result</title>
</head>
<body>
<h1>Test Connection Result</h1>
<pre>{{ results }}</pre>
<a href="/">Back to Home</a>
</body>
</html>

index.html- 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Carbyne Test Connection</title>
</head>
<body>
<h1>Test Connection</h1>
<form method="post" action="/test_connection">
    <button type="submit">Run Tests</button>
</form>
</body>
</html>```

Is there a way to execute order placements immediately in the Binance API?

So I have a Node application that automatically trades for me since those are often very short trades it needs to place orders as fast as possible. Using Node Binance Api only the trades which are being received are accurate and the orders being placed take more than 100ms which is getting a lot in the way. I know that 100ms isnt much but it still ruins my calculations. Therefore I want to ask if it is maybe possible, since I think it repeats connecting each time to the api, when a new order is being placed, to have an already connected api which only needs to receive some signal to place orders. Which I think would be faster or am I missing something here? Could it maybe be that there are different api locations which I can connect to, to reduce the delay.
I am in now way knowledgeable in Apis, so I would thank everyone that can help me out here.

Code Snippet:

   binance.order({
    symbol: 'BTCFDUSD',
    side: 'BUY',
    type: 'MARKET',
    quantity: BuyQuantity,
   });
   
   const Binance = require('binance-api-node').default
   // Authenticated client, can make signed calls
   const binance = Binance({
    apiKey: 'APIKEY',
    apiSecret: 'APISECRET',
   })

How to get precise position of HTML element after scrolling

I’m writing a tampermonkey script to add speed buttons next to Facebook videos. The script get all the video elements in the page, get their position, and bases on that position to place the button next to them. The script runs fine at the beginning. But as I scroll and the page loads more videos, the button position doesn’t match their video anymore. As a result, videos won’t have speed buttons next to them. I suspect that by loading more videos, the code messed up somewhere and calculate the video position from the top of the page wrong, so that the button is placed wrong consequently. Can someone suggest a way to fix this? My code is as below:

function addButton(){

function getOffset( el ) {//get the position of the element respective to the top and the left of the page

    var _x = 0;
    var _y = 0;
    while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
        _x += el.offsetLeft - el.scrollLeft;
        _y += el.offsetTop - el.scrollTop;
        el = el.offsetParent;
    }
    return { top: _y, left: _x };
}

    function setButton(video){//add buttons next to the videos
      var elDistanceToTop = window.pageYOffset + video.getBoundingClientRect().top
      var y=elDistanceToTop;//get the distance from the element to the TOP of the page
        //var y = getOffset( video ).top;
        var x=getOffset( video ).left;//get the distance from the element to the LEFT of the page
      var button1 = document.createElement('button');
      button1.textContent = '1x';
      // Set button position
      button1.style.position = 'absolute';
      button1.style.left = x+video.getBoundingClientRect().width+ 'px';//place button to the left of video
      button1.style.top = y+ 'px';//position from the top of the page to place the button
        button1.style.width='58px';
        button1.style.height=video.getBoundingClientRect().height/3+'px';
        button1.addEventListener('click', function () {
      // Increase speed by 1, maximum speed is 4.0
                video.playbackRate = 1;
    });
      // Add button to the document body
      document.body.appendChild(button1);

        var button2 = document.createElement('button');
      button2.textContent = '1.5x';
      // Set button position
      button2.style.position = 'absolute';
      button2.style.left = x+video.getBoundingClientRect().width+ 'px';
      button2.style.top = y+video.getBoundingClientRect().height/3+ 'px';
        button2.style.width='58px';
        button2.style.height=video.getBoundingClientRect().height/3+'px';
        button2.addEventListener('click', function () {
      // Increase speed by 1.5, maximum speed is 4.0
                video.playbackRate = 1.5;
    });
      // Add button to the document body
      document.body.appendChild(button2);

         var button3 = document.createElement('button');
      button3.textContent = '2x';
      // Set button position
      button3.style.position = 'absolute';
      button3.style.left = x+video.getBoundingClientRect().width+ 'px';
      button3.style.top = y+video.getBoundingClientRect().height*2/3+ 'px';
        button3.style.width='58px';
        button3.style.height=video.getBoundingClientRect().height/3+'px';
        button3.addEventListener('click', function () {
      // Increase speed by 2, maximum speed is 4.0
                video.playbackRate = 2;
    });
      // Add button to the document body
      document.body.appendChild(button3);
    }
   const videoElement = document.querySelectorAll('video');

       videoElement.forEach((video, index) => {
    //check to see if the video had had buttons
    const loadedBefore = video.getAttribute('data-loaded') === 'true';

    if (loadedBefore) {//if it has, do nothing

    } else {//if it doesn't have buttons, add them
       setButton(video);
    }
});

       videoElement.forEach((video, index) => {//mark all exsisting video on the page as button-having,
           //so as not to add button to them again
    video.setAttribute('data-loaded', 'true');
    
});

   }

setInterval(addButton, 3000);//the loop to check and add button again and again

I attached 2 image of how the button looks like at the beginning and how they look after a few scrolls on the page
before
After

iOS – getItem when device locked react-native-sensetive-info

I have a React Native project, and I’m using react-native-sensitive-info. My main problem arises from the iOS side. Our application includes a podcast feature where users can lock their screens and continue listening to podcasts. However, when the screen is locked, we’re unable to access stored values such as access tokens or other data. We’ve tried many things to fix it, but we still haven’t found a solution.
The library documentation is outdated, and they haven’t updated it with the new version. When you check the pull requests, you can see that there have been attempts.

We tried
in this issue suggestiaon
and also we tried many combination with this file
https://github.com/mCodex/react-native-sensitive-info/blob/master/index.d.ts

any suggestion or solution could be awesome for us

How can I override and redefine a function from an external JS script in a local script?

I am trying to redefine a function in an external JS file. (https://cdn.searchspring.net/search/v3/lts/searchspring.catalog.js?7hkez9)

The function I want to redefine (take some parts out) is “Da”. Both scripts (external and local override) can be held in the head html element, and I believe this is possible if I place the overriding script second?

I tried to access the function from the console (window.Da) but it is coming back as undefined. Maybe if I know what object holds this func I can override?

How to put a js promise inside a function that resolves the promise? [duplicate]

Promises are thenable but I want the value returned as a value not a promise.

promiseFulfilled = arg => { // this function CANNOT return a promise !
let definiteAnswer = ‘unresolved’
crazyPromse(arg) // this promise (elsewhere) has a 1 sec timeout and always resolves with ‘desired result’
.then( neededAnswer => {
definiteAnswer = neededAnswer
})
return definiteAnswer
}
console.log(promiseFulfilled(arg)) // do I get ‘desired result’ or ‘unresolved’