How to include custom validators and confirm password in an Angular form

I have this interface file:
userslist.ts

export interface Userslist {
    id: number;
    fname: string;
    lname: string;
    email: string;
    pas1: string;
    pas2: string;
}

I am using this interface to get form data including the field First Name, Last Name, email, password and confirm password.

The other two files:
ucreate.component.ts

import { Component, ViewChild, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Userslist } from '../userslist';
import { UserslistService } from '../userslist.service';

@Component({
  selector: 'app-ucreate',
  templateUrl: './ucreate.component.html',
  styleUrls: ['./ucreate.component.css']
})
export class UcreateComponent implements OnInit {

  // Declared the 'userForm' variable to store the user entered form data.
  userForm: Userslist = {
    id: 0,
    fname: '',
    lname: '',
    email: '',
    pas1: '',
    pas2: '',
  };


  // Injected the 'UserslistService' and 'Router'.
  constructor(private userlistService: UserslistService, private router: Router) { }

  ngOnInit(): void {
  }

  // Invoking the API call to post the data.
  create(){
    this.userlistService.create(this.userForm)
    .subscribe({
      next:(data) => {
        // On successful saving data to the server, we navigate to the adminhome page.
        this.router.navigate(["/userslist/adminhome"])
      },
      error:(err) => {
        console.log(err);
      }
    })
  }
}

ucreate.component.html

<div class="container">
    <legend>Create Item</legend>
    <form>
      <div class="mb-3">
        <label for="txtName" class="form-label">First Name</label>
        <input type="text" name="fname" [(ngModel)] = "userForm.fname" class="form-control" id="txtName" />
      </div>
      <div class="mb-3">
        <label for="txtName" class="form-label">Last Name</label>
        <input type="text" name="lname" [(ngModel)] = "userForm.lname" class="form-control" id="txtName" />
      </div>
      <div class="mb-3">
        <label for="txtName" class="form-label">e-mail</label>
        <input type="text" name="email" [(ngModel)] = "userForm.email" class="form-control" id="txtName" />
      </div>
      <div class="mb-3">
        <label for="txtName" class="form-label">Password</label>
        <input type="text" name="pas1" [(ngModel)] = "userForm.pas1" class="form-control" id="txtName" />
      </div>
      <div class="mb-3">
        <label for="txtName" class="form-label">Confirm Password</label>
        <input type="text" name="pas2" [(ngModel)] = "userForm.pas2" class="form-control" id="txtName" />
      </div>
      <button type="button" (click)="create()" class="btn btn-primary">Create Account</button>
    </form>
  </div>
  

How do I include custom validations into the input fields and also how do I show both the passwords are matching or not?

How to highlight a text in an array that is controlled by another array?

I want to develop a website that helps to practice English.

I have some videos and each video has some interesting English sentences that I want the website to read them out loud several times.

Say, video 1 has 3 sentences and each sentence has a start-time and end-time in the video

For example,

video 1-> “I turned on the tab” (1:02 to 1:04)

video 1-> “I signed up for piano lessons” (1:10 to 1:12)

video 1-> “Don’t be so dramatic” (2:10 to 2:11)

Say, video 2 has 5 sentences and each sentence has a start-time and end-time in the video

video 2-> “sentence 1” (1:02 to 1:03)

video 2-> “sentence 2” (1:05 to 1:06)
etc

I want this

when the system loads, it will list all the sentences in a table of 2 columns for each video like this

<href>Video 1 </href>

<table>
<tr>
 <td> <href> I turned on the tab </href></td>
  <td> <href> I signed up for piano lessons </href></td>
</tr>
<tr>
<td> <href> Don't be so dramatic </href></td>
 <td> </td>
</tr>
</table>

<href>video 2 </href>

<table>
<tr>
 <td> <href> Sentence 1 </href></td>
  <td> <href>Sentence 2 </href></td>
</tr>
<tr>
<td> <href> Sentence 3 </href></td>
 <td> <href> Sentence 4 </href> </td>
</tr>
<tr>
<td> <href> Sentence 5 </href> </td>
 <td> </td>
</tr>

</table>

Now, when the website reads 3 times sentence 1 (I turned on the tab) of the video 1 , the “sentence 1” will highlight. Then it reads 3 times sentence 2 of video 1, the “sentence 1” will stop highlighting and the “sentence 2” will highlight. This will keep doing like that until the last sentence of the last video in the video list.

When users click on the sentence link, it will call the part of the video containing that sentence.

I did the first part, the video calls works

But I have not finished the highlight part and “clicking on the sentence link” part

var sentences = [
  ['https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4', [
      [1, 2],
      [5, 7]
    ],
    [
      ['sentence 1'],
      ['sentence 2']
    ]
  ],
  ['https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4', [
      [10, 12],
      [13, 17],
      [25, 36]
    ],
    [
      ['sentence 1'],
      ['sentence 2'],
      ['sentence 3']
    ]
  ],
  ['https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/WeAreGoingOnBullrun.mp4', [
      [13, 15],
      [15, 19],
      [21, 30]
    ],
    [
      ['sentence 1'],
      ['sentence 2'],
      ['sentence 3']
    ]
  ]
];

let video_index = 0;
let time_index = 0;
let repeat = 0;

var video;
var maxTime;

document.addEventListener('DOMContentLoaded', () => {
  video = document.getElementById("myVideo");

  video.addEventListener("timeupdate", function() {
    if (video.currentTime >= maxTime) {
      myLoop();
    }
  }, false);
});

function playVideo(myUrl, startTime, endTime) {
  document.getElementById("demo").innerHTML += myUrl + " start:" + startTime + " end: " + endTime + "<br>";

  // video.src = 'video/'+myUrl;
  video.src = myUrl;
  video.currentTime = startTime;
  video.play();
  maxTime = endTime;
}


function myLoop() {
  if (!sentences[video_index]) {
    video.src = null;
    return;
  }
  playVideo(sentences[video_index][0], sentences[video_index][1][time_index][0], sentences[video_index][1][time_index][1]);
  repeat++;
  if (repeat >= 3) {
    repeat = 0;
    time_index++;
    if (time_index >= sentences[video_index][1].length) {
      time_index = 0;
      video_index++;
    }
  }
}

function jumpToVideo(vid_index){
    
  let text = "Do you want to play this video?";
  if (confirm(text) == true) {
    video_index = vid_index;
    time_index = 0;
    repeat = 0;
    myLoop();
  } 
    
}
function listVideos() {
  var vid_index = 0;
  for (const sentence of sentences) {

    const [video, timers, englishSentences] = sentence
    var videoLink = "<a href='#' onclick='jumpToVideo(" + vid_index + ")' >" + video + "</a><br><br>";

    document.getElementById("allVideos").innerHTML += videoLink;
    vid_index++;
  }
}
window.addEventListener('DOMContentLoaded',listVideos); // better than onload
<video id="myVideo" width="500" height="400" controls autoplay loop>
    
          Your browser does not support the video tag.
        </video>

<br>
<a href="#" onclick="myLoop()"> Play </a>

<br>
<p id="demo"></p>
<p id="allVideos"></p>

How to bypass localhost mapping through web pack

I have the following scenario: I have the domain name setup as mysite-recon.xyz.
I have the /etc/host file setup which maps the above URL to localhost:8030. All the react JS bundle files are fetched from the localhost like
http://mysite-recon.xyz:8030/app.js

But I want to use the same URL for file upload which looks like mysite-recon.xyz/u/o/hash but I want to use the actual service but because it is mapped to localhost I am unable to upload the file. Is there any way in webpack I can do this.

I have tried webpack proxy config which looks like this but of no help

devServer: {
  historyApiFallback: true,
  allowedHosts: 'all',
  https: true,
  hot: true,
  proxy: {
    '/u/o': {
      agent: new HttpsProxyAgent('http://mysite-recon.xyz:8030'),
      target: 'https://mysite-recon.xyz',
      pathRewrite: { '^/u/o': '' },
      changeOrigin: true,
    },
  },
}

Implementation of async function rate limiter using javascript

I am working on a problem of rate limiter, the context is we have to implement this in javascript,

  1. can allow N asycn functions work in the same time.
  2. have to execute all the functions in order.

For example, if we have tasks of [1,2,3,4,5], each function is async, we have the limit of 2. Now we have to execute 1,2 first, then wait until one of the tasks has been finished, we can execute next task, which is 3.

I have done the following code, however, not sure how to continue to execute the 3 once 1, 2 has been done. Can anyone help?

let activeFunc = 0;
const mapLimit = (inputs, limit, iteratee, finalCallback) => {
    // code

    for (let i = 0; i < limit - activeFunc && inputs.length > 0; i++) {
        activeFunc++; // add a thread
        let cur = inputs.shift();
        call(cur, iteratee)
            .then(done(cur, finalCallback));
    }
}

const done = (val, finalCallback) => {
    finalCallback(val + "user");
    activeFunc--;
}

const call = (val, iteratee) => {
    console.log(`Starting ${val}`);
    return new Promise(resolve => iteratee(val, resolve));
}

const mockFunction = (input, callback) => {
    setTimeout(() => {
        callback(input);
    }, Math.random() * 500);
}

mapLimit([0,1,2,3,4,5,6,7,8,9,10], 3, mockFunction, (result) => console.log(result))

I have tried to use the Promise to solve the problem, but it seems like the for loop can not go back to execute?

How can I install leaflet on npm properly

I am trying to install leaflet library on npm but for some reason it gives error. And I have reinstalled npm, cleared cache, removed node_modules and tried again but still didnt work.

nasersobhan@Nasers-MacBook-Pro Library % npm i leafl
et
npm ERR! code EEXIST
npm ERR! syscall mkdir
npm ERR! path /Users/nasersobhan/.npm/_cacache/content-v2/sha512/20/8f
npm ERR! errno EEXIST
npm ERR! Invalid response body while trying to fetch https://registry.npmjs.org/leaflet: EACCES: permission denied, mkdir ‘/Users/nasersobhan/.npm/_cacache/content-v2/sha512/20/8f’
npm ERR! File exists: /Users/nasersobhan/.npm/_cacache/content-v2/sha512/20/8f
npm ERR! Remove the existing file and try again, or run npm
npm ERR! with –force to overwrite files recklessly.

npm ERR! Log files were not written due to an error writing to the directory: /Users/nasersobhan/.npm/_logs
npm ERR! You can rerun the command with --loglevel=verbose to see the logs in your terminal

I wanted to install leaflet but got an error.

TypeError: is not a function in typescript class method calling

class AppError extends Error {
     statusCode: number;
     message: string;
     stacktrace?: any;

constructor(statusCode: number, message?: string, stacktrace?: any) {
    super(message);
    this.statusCode = statusCode;
    this.message = message? message: APIResponse.DEFAULT_RESPONSE[statusCode];
    this.stacktrace = stacktrace;
    }

sendResponse(res: Response) {
    res.status(200).json({
        response_code: this.statusCode,
        message: this.message,
        error: this.stacktrace
    })
   }
 }

   export default AppError;

When I called

const error = new AppError(400,'not found')   ;  error.sendResponse(res)

It throws the error

TypeError: error.sendResponse is not a function

I was expecting that the method is called without any errors. However, it throws the error

TypeError: error.sendResponse is not a function

this.props.map is not a function when trying to modify state component

I have an input and a button. When button is clicked I expect it to add the data inside the states, and then display it at the screen. I created states in the parent constructor and also added one sample in the arrays to be sure that function is working. And the problem is that when web-app is launched – everything renders fine. But when I click on button and try to add text in these arrays – it crashes and says : “this.props.elements.map is not a function”. But at the time of launch everything worked fine. Here is the code :

class Request_template extends Component {
    constructor() {
        super();
        this.state = {
            logs : [{id : uuidv4(), text : "Hello world"}],
            notes : [{id : uuidv4(), text : "Hello world"}],
            textfield : ""
        }
    }

    update_textfield = (event) => {
        this.setState(() => {
            return {textfield : event.target.value}
        })
    }

    add_note_and_log = () => {
        const value = this.state.textfield;
        this.setState({
            logs : this.state.logs.push({
                id : uuidv4(),
                desc : value
            }),
            notes : this.state.notes.push({
                id : uuidv4(),
                desc : value
            }),
            textfield : ""
        });
    }

    render() {
        return (
            <div className='request-grid-holder'>
                <span className='request-grid-holder__id'>1</span>
                <Status_selector/>
                <span className='request-grid-holder__name'>Vin</span>
                <span className='request-grid-holder__email'>[email protected]</span>
                <span className='request-grid-holder__self'>I am the customer</span>
                <span className='request-grid-holder__added'>2024-03-29 10:53:08</span>
                <NoteAdd updater={this.update_textfield} writer={this.add_note_and_log}/>
                <DoubleListFlex logs={this.state.logs} notes={this.state.notes}/>
            </div>
        )
    }
}

In this part in constructor I initialize state for textfield + logs + notes. And create a function add_note_and_log() so it would modify the states and pass it as props to the NoteAdd component.

class NoteAdd extends Component {
    render() {
        return (
            <div className="note-field-flex-box">
                <input type="text" className="note-field-flex-box__input" onChange={this.props.updater}/>
                <button
                    className="note-field-flex-box__button"
                    onClick={this.props.writer}>Add
                </button>
            </div>
        )
    }
}

In this component I create an input and a button, when button is clicked – I try to change states using input value.

class DoubleListFlex extends Component {
    render() {
        return (
            <div className="double-collapsible-holder">
                <ListFlexDisplay newElements={this.props.notes} buttonTitle="Пометки"/>
                <ListFlexDisplay newElements={this.props.logs} buttonTitle="Логи"/>
            </div>
        )
    }
}

It’s a holder for lists which are holding and present elements from state.

class ListFlexDisplay extends Component {
    render() {
        return (
            <div className="collapsible-container">
                <button className="collapsible-container__activator" onClick={
                    console.log(this.props.elements)
                }>{this.props.buttonTitle}</button>
                <div className="collapsible-container__content">
                    {
                        this.props.newElements.map(object => {
                            return (
                                <h1 key={object.id} className='styled-content'>{object.text}</h1>
                            )
                        })
                    }
                </div>
            </div>
        )
    }
}

It’s the most problematic part. When I try to add elements from input, “this.props.newElements.map” is crashing with error “this.props.map is not a function”.

I’ve been sitting and trying to solve it for 3-4 hours. Googled and tried other answers with the same problem – it didn’t help. The main problem is that when I launch it with “npm start” it displays the elements correctly and works fine. But it breaks when I try to add a new element and update the state.

Promise.race() in javascript does not work as intended

I’m currently working on optimizing the execution time of my script to ensure it doesn’t exceed 5 seconds. To achieve this, I’m utilizing Promise.race([]) to enforce a timeout mechanism. My code includes a recursive function named recursive, which is designed to process an object and its nested fields. Given that this function might encounter deeply nested objects, its execution could potentially extend beyond the desired timeframe. My objective is to cap the processing time to avoid long execution durations.

Below is a snippet of my implementation. The promise p is set to resolve after 5 seconds, signaling the maximum allowed time for execution. The function myFunction is designed to perform some validations on the input object obj before invoking the recursive function to process the object.

const p = new Promise((resolve, reject) => {
    setTimeout(() => {
        console.log('The 5 sec promise has resolved');
        resolve(10);
    }, 5000); // 5 seconds timeout
});

async function myFunction(obj) {
    await validate(obj);
    recursive(obj);
}

Promise.race([p, myFunction(obj)])
    .then(value => console.log(`Resolved: ${value}`))
    .catch(reason => console.log(`Rejected: ${reason}`));

In this setup, Promise.race is used to race the 5-second timer against the execution of myFunction. The goal is for myFunction to complete its task before the timer expires. If the function takes longer than 5 seconds, the promise p will resolve first, effectively limiting the execution time of the script. However, this is not what happens. In case of deeply nested objects, the 5-seconds promise never resolves. Am I using the Promise.race Incorrectly?

What is the difference between Authentication Types, Methods, Strategies and Patterns

I have been surfacing the internet for hours now trying to find clear differences between these terms but I cannot find any.

Can someone please clearly explain these terms to me?

I have read several blog posts and queried ChatGPT and Gemini.

I keep seeing similar examples like:

  • Token-based authentication
  • Multi-factor authentication
  • OAuth

The answers given by ChatGPT and Gemini do not match.

useInfiniteQuery breaks array order in get request and missing returned data

In my api, all data is ordered according to timestamp and when client request that data it also returns based on pagination. For example, below I request 15 items from the api but useInfiniteQuery return first 7 items then returns 5 items. Also those items are unordered in the array whereas I have an ordered data at the api.


   const fetchEvents = async ({ pageParam }): Promise<NFTHistory[]> => {
   let apiUrl = `myApi/histories?skip=${pageParam * 15}&take=15`;
    
   const result = await axios.get(apiUrl);
   return result.data;
  };

  const { data, fetchNextPage, hasNextPage } = useInfiniteQuery({
    queryKey: [`${queryKey}_${chainId}`],
    queryFn: fetchEvents,
    initialPageParam: 0,
    getNextPageParam: (lastPage, pages, lastPageParam) => {
      if (lastPage.length === 0) {
        return undefined;
      } else {
        return lastPageParam + 1;
      }
    },
  });

enter image description here

Expected behavior

I expect like normal axios request where I can get correct data without useInfiniteQuery

useEffect(() => {
    const fetchResult = async () => {
      const result = await axios.get(
        'myApi?skip=0&take=15'
      );

      console.log(result.data); //return 15 items as ordered
    };
    fetchResult();
  }, []);

how to import functions inside /static/ dir Django

When i make script for my django project i made a few functions but when i started optimising it and divide for few files i encounter a problem with the importing of function
** cart_methods.js**

export function cartFunction() {
    console.log("work");
}

** home_script.js**

import { cartFunction } from './cart_methods.js';
cartFunction();

with this part of code
my .js not work at all
not even small part of code not working. it stop everything

every files is in same folder

static> 
       shop>
             asstets>
                     js>
                         cart_methods.js
                         home_script.js
    

 

I am trying to connect google spreadsheets with discord.js though javascript

I am using the code from https://theoephraim.github.io/node-google-spreadsheet/#/
However when I try to load the data I get an error:
“Error: You must initialize some kind of auth before making any requests”

What am I doing wrong?

Before I was using doc.useServiceAccountAuth(credentials); and all worked perfectly, but now that the credentials form has changed this does not work anymore.

`import { GoogleSpreadsheet } from 'google-spreadsheet';
import { JWT } from 'google-auth-library';


// Initialize auth - see https://theoephraim.github.io/node-google-spreadsheet/#/guides/authentication
const serviceAccountAuth = new JWT({
// env var values here are copied from service account credentials generated by google
// see "Authentication" section in docs for more info
email: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL,
key: process.env.GOOGLE_PRIVATE_KEY,
scopes: [
'https://www.googleapis.com/auth/spreadsheets',
 ],
});

const doc = new GoogleSpreadsheet(”, serviceAccountAuth);

await doc.loadInfo();`

I have tried all the authentication methods from https://theoephraim.github.io/node-google-spreadsheet/#/guides/authentication

React Native app crashes after installing on the splash screen

I have a react native app created with expo SDK 50. My app working fine in debug mode. But in release mode it is not working. After installing the app it crashes after splash screen.

I saw the bug report from my mobile ui showing this error.

com.facebook.react.common.JavascriptException:
TypeError: Cannot read property
'getAllKeysWithPrefix' of undefined, js engine:
hermes,

I tried changing module versions and also tried solution from React Native app crashes after splash screen.

I also added the error msg screenshot.enter image description here

But no luck, Any help would be appreciated.