how to check if a string includes all array elements

how to check if a string includes all array elements, regardless of element’s position inside the string

for example:

var arr = ['lorem', 'ipsum', 'dolor'];
var str = 'lorem blue dolor sky ipsum';

I need something like this:

if(str.includesAll(arr)){console.log('string includes all elements');}
else{console.log('string does not include all elements');}

[Error: Query.Mutation defined in resolvers, but not in schema]

const { ApolloServer, gql } = require('apollo-server-express');
const express = require('express');

const port = process.env.PORT || 4000;
const notes = [
    { id: '1', content: 'This is a note', author: 'Adam Scott' },
    { id: '2', content: 'This is another note', author: 'Harlow Everly' },
    { id: '3', content: 'Oh hey look, another note!', author: 'Riley Harrison' }
   ];

const typeDefs = gql `
    type Note {
        id: ID
        content: String
        author: String
    }

    type Query {
        hello: String
        notes: [Note]
        note(id: ID!): Note
    }

    type Mutation {
        newNote(content: String!): Note
    }
`;
const resolvers = {
    Query:{
        hello: () => 'Hello World',
        notes: () => notes,
        note: (parent, args) => {
            return notes.find(note => note.id == args.id);
        },
    Mutation: {
        newNote: (parent, args) => {
            let noteValue = {
                id : String(notes.length + 1),
                content : args.content,
                author: 'Adam Scott',
            };
            notes.push(noteValue);
            return noteValue;
        }
    }
    },
}

Some people had naming issues but seems that I’m using the same in resolver as well as in schema.
Please bare with me, this is my second day in GraphQL and Express. I removed intentionally imports and assignment of express object, middleware since it does not let me post.

Using .map() method to render array items into their own separate divs, but comma is still displaying?

I’ve searched and searched but I’ve only found solutions to .join() the items into a single string..this is my first question so I’ll try my best to explain thoroughly.

const createCard = () => {
    const pokemonTypes = ['grass', 'fire', 'water'];
      return (
        `<div>
          ${pokemonTypes.map(type => `<div>${type}</div>`)}
        </div>`
      )
}

document.body.insertAdjacentHTML("beforeend", createCard());

For some context, I am using an API but I simplified the code so it’s quick and easy to read.

I am trying to display each string into its own div so that I can style each div separately…like color coded buttons: green for grass, blue for water, red for fire etc.

When I run the code the strings successfully display in their own div, however the comma remains. I’d like them to just display next to each without the comma separating them.

Thank you!

Access Alpine to create magic properties from standalone js file

I try to implement Alpine JS within a existing page.

For that, I’m using the CDN version of Alpine, which I’m loading within my :

<script defer src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>

Now I’m trying to access Alpine from a custom.js file, which is loaded automatically within the footer of my page:

Alpine.magic('post', function () {
    return function (url, data = {}) {
        return fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            redirect: 'follow',
            body: JSON.stringify(data)
        });
    }
});

Within my content I tried this:

<div x-data>
    <h1>Alpine Test</h1>
    <button type="button" @click="$post('/api/users', { name: 'John Doe' })">Add user</button>
</div>

By clicking the button, this error occurs:

Uncaught ReferenceError: $post is not defined

I’ve also tried it with window.Alpine, without success.

How can I add magic properties and stuff like that without using modules?

How can I setting Dynamic Serialport parameters? NodeJS

I’m using Node.js serialport for electron in raspberrypi4
https://serialport.io/docs/
but I can’t setting Dynamic parameters for serialport

Here is my code

var portname, baudrate, databits, stopbits, Parity, RTSCTS;
var portOpen = false;

const port = new serialport('COM4', {
    baudRate: baudrate,
    dataBits: databits,
    stopBits: stopbits,
    parity: Parity,
    rtscts: RTSCTS,
    autoOpen: false,
})

This code is error in electron “TypeError: “baudRate” must be a number: undefined at new SerialPort”

Baudrate is using port.update() for dynamic parameter,
but other things is not available.
Please help me

NodeJs calculation gone wrong

I have if statement like:

if((gotPrice * price.value).toFixed(0) >= answers.MINIMUM_BUY_AMOUNT) {
   ...
}

Results are

(gotPrice * price.value).toFixed(0) = 0

and

answers.MINIMUM_BUY_AMOUNT = 200

Then it fall to true! not sure in what world 0 is greater or equal to 200!!

I also tried this way but results was the same

if((gotPrice * price.value).toFixed(0) >= Number(answers.MINIMUM_BUY_AMOUNT).toFixed(0)) {
   ...
}

sample:

var x = 0.3431;
var y = 1.5467;
var z = '200';
console.log((x * y).toFixed(0) >= z); // false (but in my case says true!)

Any suggestions?

How do I backup or clone an array of objects in typescript? [closed]

I have tried all the examples listed here, and no matter which one I take including the JSON parse / stringify, when I modify an element in the original array, it is automatically reflected in the backup as is the case in a copy by reference. I need to find a way to break the link and reliably back up by value.

        this.backupPersons = JSON.parse(JSON.stringify(this.persons));
        this.backupPersons = this.persons.slice(0);
        this.backupPersons = this.persons.concat();
        this.backupPersons.concat(this.persons);
        this.backupPersons = angular.copy(this.persons);
        for (var i in this.persons) {
            this.backupPersons.concat(this.persons[i]);
        }
        this.persons.forEach(function (arrayItem) {
            this.backupPersons.concat(arrayItem);
        });
        for (const element of this.persons) {
            this.backupPersons.push(element);
          }

Encrypt and decrypt function from nodejs to java

i have a function like this write with javascript, how to i rewrite with JAVA ? i have try many function but still not working

const crypto = require('crypto');
const algorithm = 'aes-256-cbc';
const iv = Buffer.from('c080b0f7c7f8e7fbadfa74cda8ac0c29', "hex");
const key = crypto.createHash('sha256').update(String(process.env.ENCRYPTION_KEY)).digest('base64');
const key_in_bytes = Buffer.from(key, 'base64')

const controller = {}

controller.encrypt = (text) => {

    let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key_in_bytes), iv);
    let encrypted = cipher.update(text);
    encrypted = Buffer.concat([encrypted, cipher.final()]);
    return encrypted.toString('hex').toString();
}

controller.decrypt = (text) => {
    let encryptedText = Buffer.from(text, 'hex');
    let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key_in_bytes), iv);
    let decrypted = decipher.update(encryptedText);
    decrypted = Buffer.concat([decrypted, decipher.final()]);
    return decrypted.toString();
}

module.exports = controller

Compare an Array to a Array in an Array

I Wish to Compare array A with Array C but Array C is inside of Array B.

I have tried doing something like this but the results vary:

a.forEach(var => {
 if(var.C.includes(A)){
 //Do Something
 }
});

Minor Idea of what the Arrays look like:

A = day: "10"; 

B= {
someRandom: "Something",

C: [{
 day: "15"
}]
}

What is a right way to work with classes and OOP

I am working with classes right now and I got curious about the way the work with them should look like.

Maybe if you can recommend some good and descriptive books on the topic it would be great!

Questions:

  1. Now I am working on the backend and I am trying to use classes everywhere I find it appropriate – services, endpoints, others. I have some Angular experience and there I always provide new services or whatsoever it is via constructor making kinda injection into the class. Is that the pattern I should always inject the stuff into the class using the constructor?

  2. Let’s say I’ve got a very simple class imageService:

import { PutObjectRequest } from "@aws-sdk/client-s3"
import { Upload } from "@aws-sdk/lib-storage"
import { Types } from "mongoose"
import env from "../env"
import { logMethod } from "../helpers"
import { debug } from "../utils/debug"
import { S3Client } from '@aws-sdk/client-s3'

export interface ImageUploadParams {
    Body: PutObjectRequest["Body"],
    Key: string,
    ContentType: string,
    Bucket?: string,
    ACL?: string,
}

class ImageService {

    private readonly s3: S3Client

    constructor() {

        this.s3 = new S3Client({
            credentials: {
                accessKeyId: env.s3.accessKeyId,
                secretAccessKey: env.s3.secretAccessKey,
            },
            region: env.s3.region,
        })

    }

    private readonly allowedTypes: string[] = [
        'image/jpeg',
        'image/png',
    ]

    private generateName({ id, prefix }: { id: string | Types.ObjectId, prefix?: string }) {
        return `${prefix ? prefix + '-' : ''}image-${id}-${Date.now()}`
    }

    generate({ id, prefix }: { id: string | Types.ObjectId, prefix?: string }) {
        const name = this.generateName({ id, prefix })

        return {
            key: name,
            link: `https://${env.s3.bucket}.s3.${env.s3.region}.amazonaws.com/${name}`
        }
    }

    extractKey(link: string) {
        return link.split('/').pop()
    }

    checkType(mimetype: string) {
        return this.allowedTypes.includes(mimetype)
    }

    @logMethod
    async uploadImage({ Body, Key, ContentType, Bucket, ACL }: ImageUploadParams) {

        const upload = new Upload({
            client: this.s3,
            params: {
                Body,
                Key,
                ContentType,
                Bucket: Bucket ?? env.s3.bucket,
                ACL: ACL ?? 'public-read',
            },
        })

       if(!env.isProd) {
            upload.on("httpUploadProgress", (progress) => {
                if(progress && progress.loaded && progress.total) {
                    const percent = (progress.loaded / progress.total) * 100
                    debug(`image '${Key}' uploaded: ${percent}%`)
                }
            })
       }

        await upload.done()
    }
}

export const imageService = new ImageService()

As you can see I am always instantiating the class and exporting outside (making it available for others). Is it a good practice to use classes like this? Or there is some kind of other flows or technics to make classes available?

  1. Every method in a class should encapsulate some unit logic. What about the way of working with the class. Let’s say I am using the class above and I need to upload an image and I should interact with the class imageService making three different requests – imageService.generate, imageService.checkType, imageService.uploadImage, and so on, and putting all the things together in the class it requires all of that. Am I right? So the class provides the abstractions the little unit tools you can cooperate with and put up some own stuff, without anything concrete like the whole operation from a to z. Maybe there are some principals or something

  2. What about errors? Let’s say I am checking the image type and it is not valid. Should I throw an Error right away, or in this pattern I should just return the error to the class that invoked the method and it should decide what to do? If the last, there is a change of a bug or something. Do classes responsible for throwing errors, or just responding and delegating that on the classes that invoked them?

The questions must be very silly and vague, but any thoughts are welcomed

NextJS: 404 page not rendered for [store]/account/details route

I’m trying to implement 404 pages in my react-next project,
i have a route [store]/account where [store] is dynamic. till the account page the 404 is properly thrown, but when i try to load [store]/account/asdasdasd(random page to trigger 404) the screen is blank and shows nothing.

note: i have handled 404 in the getStaticProps for both [store],/account page.

Please help with this, stuck on this for quite sometime.