Solving leetcode #46 Permutations

I’m trying to solve leetcode #46 Permutations. The question is:

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order:

Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

Here is a solution in JavaScript to the problem:

let permute = function(nums) {
    if(nums.length === 0) return [nums];
    let res = [], len = nums.length,used = new Array(len).fill(false);

    let backtrack = function(currPermutation){
        if(currPermutation.length === nums.length){
            res.push([...currPermutation]);
            return;
        }

        for(let i = 0; i < len; ++i){
            if(used[i]) continue;

            currPermutation.push(nums[i]);
            console.log("curr perm = ",currPermutation);
            used[i] = true;
            backtrack(currPermutation);
            currPermutation.pop();
            used[i] = false;
        }
    }

    backtrack([]);
    return res;
};

For the Input: nums = [1,2,3] here is the result of the console.log("curr perm = ",currPermutation:

curr perm =  [ 1 ]
curr perm =  [ 1, 2 ]
curr perm =  [ 1, 2, 3 ]
curr perm =  [ 1, 3 ]
curr perm =  [ 1, 3, 2 ]
curr perm =  [ 2 ]
curr perm =  [ 2, 1 ]
curr perm =  [ 2, 1, 3 ]
curr perm =  [ 2, 3 ]
curr perm =  [ 2, 3, 1 ]
curr perm =  [ 3 ]
curr perm =  [ 3, 1 ]
curr perm =  [ 3, 1, 2 ]
curr perm =  [ 3, 2 ]
curr perm =  [ 3, 2, 1 ]

What I don’t understand is when curr perm = [1,2,3] why does it pop the number 2 instead of number 3, same thing when curr perm = [2,1,3] why does it pop 1 instead of 3 and obviously same thing when curr perm = [3,1,2] why does it pop 1 instead of 2?

How do I destructure a json file to show all content in a site? There are thousands of objects and chrome crashes every time I load everything at once

There are thousands of objects and chrome crashes every time I load everything at once.

btn.addEventListener('click', function(){
    event.preventDefault();

async function getData(){
    const response=await fetch(url)
    const data= await response.json();
    info(data)
}

getData();

function info(x){
    x.messages.forEach(element => {
        console.log(element.creator.name+": "+element.text)
    // console.log(x.element.text)
    con.innerHTML += "<p>"+element.creator.name+": "+element.text+"</p>";
    });
}

This is the code im using rn

I need help understanding why I can’t map over a response object from an API as it is in ReactJS?

I have got what I need working but I do not fully understand why it is working.

I am using ReactJS and I have some code that requests an API from a server and displays it on my screen. I have this code:

let [responseData, setResponseData] = React.useState([])

   const response = async (e) => {
       e.preventDefault()
       await axios.get('https://newsdata.io/api/1/news?apikey=<api_key>&q=tennis ')
       .then(response => {
           console.log((response.data.results))
           setResponseData((response.data.results))
       }).catch(function (error) {
           if (error.response) {
             console.log(error.response.data);
             console.log(error.response.status);
             console.log(error.response.headers);
} 
       })
   }
   return (
       <div>
         
           <button onClick={(e) => response(e)} type='button'>Click Me For Data</button>
           {
               responseData.map(( data, i ) => (
                   <div key={i}>
                       <h2>{data.title}</h2> 
                       <h3>{data.link}</h3>
                       </div>
               ))
           }

This works as I want it to, however, previously I had my useState set to this:

let [responseData, setResponseData] = React.useState('')

I had seen that in my console that the response data that it was returning was already an array of objects. So I figured all I would have to do was to map over it since its already an array. But I was getting an error that “responseData.map is not a function”. After some thinking I thought it was because the useState was not starting off as an array to store each new responseData entry.

I changed it to React.useState([]) and it started working.

But now I’m confused because when I was console logging my response data, it was already appearing as “(10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]” and when I used the “typeOf” operator it was saying that this is an object. But isn’t it showing an array of objects because of the square brackets? Thats why I thought the map() function would work on it. But now it seems I’m storing these entries in an array from useState. So I thought I would be making an array of an array of objects. But this is obviously not the case as it is working normally.

Can anyone explain please why the above is an object and not an array and why my code works now? Apologies if this is something really easy but I’m just not seeing it.

How Service Worker Scope works

I have a library written in JavaScript that helps to intercept HTTP requests called Wayne. It works the same as a normal worker but the code is much simpler. The API is similar to that in the Express.js Node.js framework.

This is my code for the Offline detection demo:

service worker (sw.js)

importScripts('https://cdn.jsdelivr.net/npm/@jcubic/wayne/index.umd.min.js');

const app = new wayne.Wayne();

app.get('*', async (req, res) => {
    if (navigator.onLine) {
        const path = req.params[0];
        console.log({path});
        const _res = await fetch('.' + path);
        const type = _res.headers.get('Content-Type') ?? 'application/octet-stream';
        res.send(await _res.arrayBuffer(), { type });
    } else {
        res.html(`<!DOCTYPE HTML><html><body><h1>You're offline</h1></body></html>`);
    }
});

index.html

<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <meta name="Description" content=""/>
    <link rel="shortcut icon" href=""/>
    <!--[if IE]>
    <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script>
     if ('serviceWorker' in navigator) {
         var scope = location.pathname.replace(//[^/]+$/, '/');
         navigator.serviceWorker.register('sw.js', { scope })
                  .then(function(reg) {
                      reg.addEventListener('updatefound', function() {
                          var installingWorker = reg.installing;
                          console.log('A new service worker is being installed:',
                                      installingWorker);
                      });
                      // registration worked
                      console.log('Registration succeeded. Scope is ' + reg.scope);
                  }).catch(function(error) {
                      // registration failed
                      console.log('Registration failed with ' + error);
                  });
     }
    </script>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
</head>
<body>
  <h1>Offline Wayne Demo</h1>
  <p>Disconnect the internet connection and refresh the page</p>
</body>
</html>

I have jQuery added because it’s the default in my template when I create a new file.

The code works fine but I have weird results because it intercepts call to the jQuery file. In logs I see:

{path: '/jquery-3.4.1.min.js'}
jquery-3.4.1.min.js:1 Uncaught SyntaxError: Unexpected token '<' (at jquery-3.4.1.min.js:1:1)
(index):29 Registration succeeded. Scope is http://localhost/~kuba/jcubic/wayne/offline/
sw.js:8
{path: '/favicon.ico'}

The order means that the previous worker (I have auto-reload in dev tools) intercepts the jQuery call to a different domain, not in the scope of the service worker.

I’ve uploaded the code to my shared hosting:

https://jcubic.pl/offline/

I don’t get the path in the console but got an error because the jQuery returns HTTP response from the server:

<p>Sorry, but the file "/<wbr/>offline/<wbr/>jquery-3.4.1.min.js"
   was not found on the jcubic.pl server.</p>

The same happens in Firefox and Google Chrome (tested on GNU/Linux).

So my question is how exactly the service worker scope works?

I was asking ChatGPT but he says that scope determines which path can be intercepted. Then why request for the jQuery file got intercepted?

How to return multiple images back to client

I have an API that must return a set of images equally sized grayscale images back to a web client. The user should be able to show layers side-by-side, or like a slideshow. How to do this?

Why downloading multiple images as once? Because the action has to be atomic. The state may have changed between two separate requests. Since the application is run locally the main constraint is CPU resources rather than bandwith. I think it would be easy to solve the problem if there were a blit method. That is: Assume I have RGBA data with a certain width and height, channel depth and gamma, I would like to push it to an image element. Using a colormap would be a bonus.

Option 0

The ideal way would be to deliver the image in a format that

  1. Supports multiple layers (such as TIFF or OpenEXR)
  2. Is supported by the web browser

But at the time of writing (1) And (2) always evaluates to false, because these sets are disjoint. Is the proper workaround to

Option 1

Server-side:

  1. Encode the layers into multiple PNG:s
  2. Encode the pngs as base64
  3. Pass the layers in an JSON array
  4. Send the JSON array back to the client

Client-side:

Create images from a base64-encode URI

Option 2

Server-side:

  1. Encode the layers into a lossless video format such as ffv1 (is that supported by browsers)
  2. Send the video the client

Client-side:

Have some form of frame-step control (Obviously it must step exactly one frame, and the entire video must have been downloaded)

Option 3

Not RESTful. Send a POST request to generate all images, and then use multiple GET requests to download individual layers.

How to stop cleanly stop code from executing after res.send()

On one of my api endpoints I’ve got a middleware function that checks whether the session is still valid (verifySession). That function calls another function (validateObjectId) that checks whether the passed-in (mongodb) Id is a valid ObjectId. I would like to be able to exit verifySession() if validateObjectId() detects an invalid Id.

However, the console.log and the rest of the code that runs in a normal scenario, where the Id is valid, still runs and obviously complains that the HTTP response has ended and can’t add to it.

What am I doing wrong?

// EDIT 1 BEGIN
/**
 * 
 * @param {mongoose.Types.ObjectId} objectId Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer.
 * @returns A rejected Promise if the value passed is not a valid MongoDB ObjectId.
 */
const validateObjectId = async (objectId) => {
  return new Promise((resolve, reject) => {
    // Check if the passed-in id is a valid MongoDB ObjectId. Return with an error of it's not.
    if (!mongoose.Types.ObjectId.isValid(objectId)) {
      reject({
        error: ERROR_MESSAGES.INVALID_OBJECTID,
        errorCode: ERROR_CODES.INVALID_OBJECTID
      });
    }
    resolve(objectId);
  })
}

// EDIT 1 END


// Verify Refresh Token Middleware (which will be verifying the session)
let verifySession = async (req, res, next) => {
  // Grab the refresh token from the request header.
  let refreshToken = req.header('x-refresh-token');

  // Grab the _id from the request header.
  let _id = req.header('_id');

  console.log('ObjectId: ', _id);

  await validateObjectId(_id)
    .catch((err) => {
      console.log('GOT HEREEEEEEEEEEEEEE', err);
      // return res.send(err);
      return res.status(STATUS_CODES.UNAUTHORIZED).send(err);
    });

    console.log('GOT HERE BUT SHOULD NOT HAVE');
  // Verify the session.
}

I’ve tried adding and removing the ‘return’ keyword.

I know that I could put the rest of the functionality in the .then() of the validateObjectId(), but I consider that affects the readability of the code.

If I have a clause at the top of the function that could end the whole function, I’d like to keep it there as well as the part that ends that function (the .catch() block).

What is the jargon or area of study for this type of code (non-compliant, non-conforming)?

What is the technical jargon for a module/library that’s considered bad because it strays from or changes standard behavior (especially implicitly)?

For example, if I have module.js with the following contents…

document.querySelectorAll("a").forEach((a) => {
  a.addEventListener("click", (e) => {
    e.preventDefault();
    // something else...
  });
});

…consumers of the module could end up confused when their links stop working.

Also, what’s the area(s) of study that this falls under? I want to know what to search so I can read about it.

How do I make React app as server side using express?

I am trying React18 + express to make my react as server rendered application.

I have created a very simple express server that is supposed to send an HTML code to the browser.

import express from "express"
import React from "react"
import { renderToPipeableStream } from "react-dom/server"

const app = express()

app.get("/", (req, res) => {
  const { pipe } = renderToPipeableStream(<h1>Hello World</h1>, {
    onShellReady() {
      res.setHeader("content-type", "text/html")
      pipe(res)
    },
  })
})

app.listen(3000, () => {
  console.log("RUNNING..")
})

The Hello World doesn’t get printed and i am stuck with this error –

const { pipe } = renderToPipeableStream(<h1>Hello World</h1>, {
                                          ^

SyntaxError: Unexpected token '<'
    at Loader.moduleStrategy (node:internal/modules/esm/translators:147:18)
    at async link (node:internal/modules/esm/module_job:64:21)

However, when i send a plain string as “Hello World” it does rendered on the browser at the given PORT.

Why it cannot send a simple h1 tag as an HTML?

How to create an array within a class in JS? [closed]

// Create a class that can be used to create multiple farms. Each farm must contain an id, a location and an array of animals. Each animal must have a name and quantity (so basically an animal will be an object)

// The class will also contain two methods:
// 1. listAnimals: the method will display on the console a string containing all the animals on the farm.
// EX: farm1.listAnimals() => “The farm contains the following animals: horse, chicken, cat” (obviously, horse, chicken and cat are values ​​of the names of the animals in the array received as a parameter of the object farm1)
// 2. listRareAnimals: the method will display on the console a string of characters, which will list all the animals whose quantity is less than 5.

Building a full stack photo gallery web using NodeJs

I am fairly new to NodeJS and currently undertaking a full stack project where I build a photo display website that allows photographers to save their photos into a database and display them. While it is fairly simple to load the uploaded images from a database and display them in containers of equal size on the website like Instagram, what I want is to allow users to choose the position on the grid where the image will be displayed, the length and the height of the container it is displayed in, and add customisation to the container (like changing the border radius, border thickness, etc). Do you guys have any idea on what node packages or Javascript methods or functions I should take a look in? Thank you very much

Currently, I have no idea what I should use

Подключение к серверу, работа с API [closed]

У меня отключено стандартное поведение сабмита у формы: evt.preventDefault(); – но при добавлении, удалении карточки или изменения аватара с информацией о пользователе, меняется только тогда, когда я перезагружу страницу. Не могу понять, как реализовать, чтобы любые изменения добавлялись сразу в DOM. 1 – эти методы в классе Api

    postUserAvatar(forInput) {
        return fetch(`${this._baseUrl}/users/me/avatar`, {
            method: 'PATCH',
            headers: this._headers,
            body: JSON.stringify({
                avatar: forInput.linkAvatar
            })
        })
         .then(this._checkResponse)
    }
 
    getUserInfo() {
        return fetch(`${this._baseUrl}/users/me`, {
            headers: this._headers,
        })
         .then(this._checkResponse)
    }

    getInitialCards() {
        return fetch(`${this._baseUrl}/cards`, {
            headers: this._headers
        })
         .then(this._checkResponse)
    }

    addCard(values) {
        return fetch(`${this._baseUrl}/cards`, {
            method: 'POST',
            headers: this._headers,
            body: JSON.stringify({
                name: values.name,
                link: values.link
            })
        })
         .then(this._checkResponse)
    }

2 – это класс PopupWithForm

import Popup from './Popup.js'

export default class PopupWithForm extends Popup {
    constructor (popup, submitCallback) {
        super(popup);
        this._popupForm = this._popup.querySelector('.popup__form')
        this.inputList = this._popupForm.querySelectorAll('.popup__form-input')
        this._submitButton = this._popup.querySelector('.popup__form-submit-button')
        this._submitCallback = submitCallback; // это функция
    }

    _getInputValues = () => {
        this._values = {}
        this.inputList.forEach((input) => {
            this._values[input.name] = input.value;
        });
        
        
        return this._values
    }

    setEventListeners() {
        super.setEventListeners();

        this._popupForm.addEventListener('submit', (evt) => {

            evt.preventDefault();

            if(this._submitButton.textContent === 'Сохранить') {

                this._submitButton.textContent = 'Сохранение...';
            } else {
                this._submitButton.textContent = 'Создание...';
            }
            
            this.forInput = this._getInputValues();
            this._submitCallback(this.forInput); 
        
            this.close()
            
        });

    }
      

    close() {
        super.close()
        this._popupForm.reset();
    }
}

3 – в корневом файле проекта

const api = new Api({
  baseUrl: 'https://mesto.nomoreparties.co/v1/cohort-69',
  headers: {
    authorization: '68ba550e-5b32-4477-ae61-93c3a6a6c328', 
    'Content-Type': 'application/json'
  }
});





const createCard = (cardElement) => { 
  const card = new Card (cardElement, elements, cardTemplateSelector, classPopupWindowImg, popupDeleteCard, api, userInfo.getUserInfo());
  return card
}

const cardList = new Section({
  renderer: (cardElement) => {
    const card = createCard(cardElement);
    const fullCard = card.fillCard();
    cardList.addItem(fullCard);
  }
}, selector);

const submitCallbackImg = (forInput) => { 

    const values = {
      name: forInput.commentImg,
      link: forInput.linkImg
    }

    api.addCard(values)
     .then((res) => {
      console.log(res);
     })
     .catch(err => console.log(err));

}

Promise.all([api.getUserInfo(), api.getInitialCards()])
  .then(([userData, cards]) => {
    userInfo.downloadUserInfo(userData);
    cardList.drawElement(cards)
    
  })
  .catch(err => {
    console.log(err);
  });

после этого запроса обновятся данные о карточках, чтобы отобразить новую карточку на странице

Nestjs using accessToken on another route return Unauthorized

Consider that I have two routes in NestJS called “signUp” and “validate-code”, both of which are inside the SignupModule. For the signUp route, I return an accessToken using JWT. Here’s the code:

const payload = {
    mobileNumber: user.mobileNumber
};

return [
    {...userData,accessToken: this.jwtService.sign(payload),}
];

After sending the mobile number as a request using Postman to the server, everything works fine and I get an accessToken.

Now, I want to use this accessToken to authorize the validate-code route and check if the user has already registered and their information exists in the database. I have to send the mobileNumber and code to this route along with the accessToken that I received previously through the signUp route. I set the accessToken in Postman as Bearer, but it gives me the following message:

{
    "statusCode": 401,
    "message": "Unauthorized"
}

The classes written for JWT are as follows:

import {Injectable} from "@nestjs/common";
import {AuthGuard} from "@nestjs/passport";

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
}


//---------------------------------------------------------------
import {AuthGuard} from '@nestjs/passport';
import {Injectable} from "@nestjs/common";

@Injectable()
export class LocalAuthGuard extends AuthGuard('local') {
}


//---------------------------------------------------------------
import {PassportStrategy} from "@nestjs/passport";
import {ExtractJwt} from "passport-jwt";
import {Strategy} from "passport-local";

export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
    constructor() {
        super({
            jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
            secretOrKey: `${process.env.JWT_SECRET}`,
            ignoreExpiration: false,
            passReqToCallback: true,
        });
    }

    async validate(payload: any) {
        return {
            mobileNumber: payload.mobileNumber
        };
    }
}


//---------------------------------------------------------------
import {Injectable, UnauthroziedException} from "@nestjs/common";
import {PassportStrategy} from "@nestjs/passport";
import {Strategy} from 'passport-local';
import {SignupService} from "./signup.service";

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
    constructor(private readonly signupService: SignupService) {
        super();
    }

    async validate(mobileNumber: string) {
        const user = await this.signupService.validateUser(mobileNumber);
        if (!user) {
            throw  new UnauthroziedException();
        }

        return user;
    }
}

The signUp route in the SignupController:

@Post('signup')
async signUp(@Body() dto: SignupDto, @Res() res: Response):Promise<Response<any,Record<string, any>>> {
    const result = await this.authService.signUp(dto.mobileNumber);
    return res.status(result ? HttpStatus.CREATED : HttpStatus.INTERNAL_SERVER_ERROR).json({'message':result});
}

The validate-code route in the SignupController:

@UseGuards(LocalAuthGuard)
@Post('validate-code')
async validateCode(@Body() dto:VerifyCodeDto,@Res() res:Response):Promise<Response<any,Record<string, any>>>{
    const [statusCode,data] = await this.authService.verifyCode(dto);
    return res.status(statusCode).json(data);
}

Finally, the SignupModule is implemented to use JWT and Passport:

@Module({
    imports: [
        JwtModule.register({
            secret: `${process.env.JWT_SECRET}`,
            signOptions: { expiresIn: '60s' },
        }),
        ThrottlerModule.forRoot(
            {
                ttl: 30,
                limit: 6
            }
        ),
        PrismaModule,
        ApiModule
    ],
    controllers: [AuthController],
    providers: [
        JwtStrategy,
        LocalStrategy,
        SignupService,
        {
            provide: APP_GUARD,
            useClass: ThrottlerGuard
        }
    ]
})
export class SignupModule {
}

So, I have no problem with the signUp route and getting the accessToken, but I cannot use it for the validate-code route. What could be the problem?

firestore is rejecting the type of my array values

0

I have a div and, inside that div, I’m generating dynamically input tags depending on a number wrote by the user. When the user clicks on the submit button, i have to get all the values of the inputs in an array and store it in the database. I’m using the firestore database. My problem is that whenever I tried to save the values of the inputs in the db, I have an error saying that the values of the inputs are UNDEFINED. I think the problem is in the values i’m getting from the inputs. They are not strings but objects.

Here’s my htlm code :

<div>
    <div id='dates' ref={myRef} className='fields_container'>
        {
            array.map(index => (<input key={index} type="date"/>))
        }
    </div>
    <div className="btn">
        <Button 
        variant="contained" 
        size="large" 
        onClick={handleClick}
        sx={
            {
                fontSize: 25,
                color: "black",
                backgroundColor: "#d19c97",
                fontFamily: "'Caveat', cursive",
                boxShadow: "2px 2px 52px black",
                '&:hover': {
                    backgroundColor: "black",
                    color: "white",
                    boxShadow: "2px 2px 52px black"
                }
            }
        }
        >
            Suivant
        </Button>
    </div>
</div>

and here is my handleClick function that is responsible of saving in the db:

const handleClick = async () => {
    // initialize array for the input values
    let values = []

    // save input values in array
    array.map(index => values.push(myRef.current.children[index].value))
    
    try {
        console.log('entré')
        await setDoc(doc(db, "SEANCES_COLLECTIONS", clientName), {values}, {merge: true})

        console.log('réussie !')
        setLoading(false)
    } catch (error) {
        console.log(values)
        console.log(error)
    }
}

and here is the values and the error the console is displaying:

enter image description here

How to assign a set of sequence of string with variable length like, “APNX”, “NP”,”HPNX”, to an interval of date, like 13 days period, or 21 days?

I want a function in java script which takes in day’s interval as number i.e from may-10 to may-23 is (13), So function takes 13 as one argument. Another, it also takes a sequence of strings with variable length like mentioned in question, i.e "APNX", "NP", "HPNX".

Now, What i want is, to assign the sequence APNX to that 13 days period, So mathematically i can apply 3 times completely and the first string of sequence i.e “A” to the last day.
So it would be like ,
10 => A, 11 => P, 12 => N, 13 => X, .................. 22 => X, 23 => A

note : the sequence could start from any of the character, say if it starts from “N” then the initial day would be assigned as “N” and then “X” and then the next day would be “A” and similarly

haven’t given any thought really, just wanted help