Filtering two arrays based on another array values and also push the unavailable values into another array

I have 2 arrays one is “searchEachIndex” and another one is “data”.

Based on “searchEachIndex” array i want to filter the “data” array. i.e,

Here in searchEachIndex array i have 123 value that matches with data array’s employeId.

should push the object into res array here { id: 2, employeId: 123 }, { id: 3, employeId: 123 }, If both values matches.

otherwise push the mismatching searchEachIndex values here 1234, 12 into another array i.e, noData array.

let searchEachIndex = [123, 1234, 12]

let data = [
{
  id: 1,
  employeId: 121
},
{
  id: 2,
  employeId: 123
},
{
  id: 3,
  employeId: 123
 }
];

let res=[];

let noData = [];

searchEachIndex.forEach(val => {
   data.map(item => {
      if(item.employeId === val) {
       res.push(item)
      }
   })
})

console.log('Both emp id and searchEachIndex value matched array', res);

consolelog('Ids not found array', noData);

NodeJs & React.Js & PassportJs GET http://localhost:5001/login?error=1 404 (Not Found)

I hope you are well.

I’m developing a web application by NodeJs and ReactJs. When I try to Login by formik with using axios, passportjs cannot redirect me to successLink even if my info are correct.
Gives me 404 not found.

When I don’t use formik and use regular html form passportjs works but this time I can’t use request.isAuthenticated() and I cannot manage users in react.

isAuthenticated() always gives me false in react “localhost:5001” but when I use nodejs “localhost:5000” it gives me true.

Thank you for your answers. Have a great day.

Node.js Backend

commonController.js

const login = async (req, res, next) => {
    
    // form request
    // let data = await req.body

    // axios request
    let data = await JSON.parse(Object.keys(req.body)[0])

    const _responsible = await Responsible.findOne({ email: data.email });
    console.log(_responsible)

    if (!_responsible) {
        passport.authenticate('local', {
            successRedirect: `${process.env.LOGIN_SUCCESS_URL}`,
            failureRedirect: `${process.env.LOGIN_FAIL_URL}1`,
        })(req, res, next)
    }
    else {
        if (_responsible && _responsible.isActive == true) {
            passport.authenticate('local', {
                successRedirect: `${process.env.LOGIN_SUCCESS_URL}`,
                failureRedirect: `${process.env.LOGIN_FAIL_URL}1`,
            })(req, res, next)
        }
        else if(_responsible && _responsible.isActive == false){
            passport.authenticate('local', {
                successRedirect: `${process.env.LOGIN_FAIL_URL}2`,
            })(req, res, next)
        }
    }
}

React

Login.js

{error && error == 1 ?
    <p style={{ color: "red" }}>{strings.loginError}</p> : null
}
{error && error == 2 ?
    <p style={{ color: "orange" }}>{strings.loginAuthorizationError}</p> : null
}

{/* FORMIK FORM */}

<Formik initialValues={{ email: "", password: "" }}
    validationSchema={loginValidationSchema}
    onSubmit={async (values) => {
        axios.post(`${process.env.REACT_APP_SERVER_URL}/login`, JSON.stringify(values))
            .then(response => console.log(response.data))
            .catch(err => console.log(err.message))
        values.email = "";
        values.password = "";
    }}
>
    {({ errors, touched }) => (
        <Form className='loginForm'>
            <Field className="loginFormField" name="email" type="email" placeholder={strings.formEmail} />
            {errors.email && touched.email ? (
                <div className='formErrorMessage'>{errors.email}</div>
            ) : null}
            <Field className="loginFormField" name="password" type="password" placeholder={strings.formPassword} />
            {errors.password && touched.password ? (
                <span className='formErrorMessage'>{errors.password}</span>
            ) : null}
            
            <button type="submit">{strings.submitForm}</button>
        </Form>
    )}
</Formik>

The error I got

How do I render a video on sphere in THREEJS

We can render an image on a sphere as seen in the code below

Example: Create a glob out of world map

import * as THREE from 'https://cdn.skypack.dev/[email protected]';
const scene = new THREE.Scene();

      const camera = new THREE.PerspectiveCamera( 
        75, 
        window.innerWidth / window.innerHeight,
        0.1,
        1000 );

      const renderer = new THREE.WebGLRenderer();
      renderer.setSize( window.innerWidth, window.innerHeight );
      document.body.appendChild( renderer.domElement );

      const sphere = new THREE.Mesh(new THREE.
        SphereGeometry(5,50,50),new THREE.
        MeshBasicMaterial({
          map: new THREE.TextureLoader().load('./img/img1.jpg')
        })
        );
      scene.add( sphere );

      camera.position.z = 15;

      function animate() {
        requestAnimationFrame( animate );
        renderer.render( scene, camera );
      };

      animate();

I need to a video tag in html page to play a video in threejs VideoTexture

How do I do the same but with a video?

Modify array in observable with rxjs, return whole object

I have observable like this:

currentPage: 1
items: (6) [{…}, {…}, {…}, {…}, {…}, {…}]
pageSize: 10
totalItems: 6
totalPages: 1

I’m trying to modify every element in items array, and then return a whole object.

   getAllGifts(): Observable<PagedListDTO<GiftIdeaDTO>> {
    return this.http.get<PagedListDTO<GiftIdeaDTO>>(this.urlAPI + '/GiftIdeas/GetAll').
      pipe(
        map(x => x.items.map
          (y => ({ ...y, imageContentB64: y.imageContentB64 + 'Bob' })))
        ,
        tap(console.log)
      );
  }

but i only get a modified array of items, no currentPage property, page Size etc.

How can i modify items array and return whole object?

Jtoken for a specific case in JS array

[
   [
      {
         "id":1000000000026,
         "name":"ONE COMPANY",
         "desc":"one has one",
         "partner":"one one"
      },
      {
         "id":2589,
         "name":"TWO COMPANY",
         "desc":"two has two",
         "partner":"two two"
      },
      {
         "id":1000000000005,
         "name":"THREE COMPANY",
         "desc":"three has three",
         "partner":"three three"
      }
   ],
   [
      {
         "id":1000000000005,
         "name":"PREMIUM COMPANY",
         "desc":"premium has vip",
         "partner":"premium premium"
      }
   ]
]

So have a look at this JSON.

Here I want a Jtoken to parse two arrays here

one array has ONE, TWO, THREE companies
and second, has PREMIUM COMPANY

I want to receive two array items in JS, all of the descriptions in one array value and the description of 2nd array in another array value

Example output I need →

var description = ["one has one, two has two, three has three" , "premium has VIP"];

I am sure there is a way for this in Jtoken but I am not getting it! if anyone here is pro in Jtoken Please try the solution!

but here it’s merging both of the arrays in one, and the point to note is that no.of arrays are dynamic

Click to see image

what I want is to get description of each company i an array to combine and get all the descriptions in others arrays in another array item. Please if i am being too confusing try to have a look at the example i mentioned above!

Not able to understand the difference between the node versions which is resulting the difference between asserts

When i run the below statements using different node versions I see a difference in the assert outcome.
I am using v10.15.1 where the assert passes. But the same code in v14.18.1 throws error.

const assert = require('assert')
var err = new Error('some error');
var d = [{
    'error':[err]
}]
var expected = [{
    'error':[{}]
}]
assert.deepEqual(d,expected)

Error is as below:

    assert.js:118
  throw new AssertionError(obj);
  ^

AssertionError [ERR_ASSERTION]: Expected values to be loosely deep-equal:

[
  {
    error: [
      Error: some error
          at Object.<anonymous> (/Users/username/Desktop/repos/temp_files/test.js:2:11)
          at Module._compile (internal/modules/cjs/loader.js:1085:14)
          at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
          at Module.load (internal/modules/cjs/loader.js:950:32)
          at Function.Module._load (internal/modules/cjs/loader.js:790:12)
          at Function.executeUserEntryPoint [as r...

should loosely deep-equal

[
  {
    error: [
      []
    ]
  }
]
    at Object.<anonymous> (/Users/username/Desktop/repos/temp_files/test.js:9:8)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
    at internal/main/run_main_module.js:17:47 {
  generatedMessage: true,
  code: 'ERR_ASSERTION',
  actual: [
    {
      error: [
        Error: some error
            at Object.<anonymous> (/Users/username/Desktop/repos/temp_files/test.js:2:11)
            at Module._compile (internal/modules/cjs/loader.js:1085:14)
            at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
            at Module.load (internal/modules/cjs/loader.js:950:32)
            at Function.Module._load (internal/modules/cjs/loader.js:790:12)
            at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
            at internal/main/run_main_module.js:17:47
      ]
    }
  ],
  expected: [ { error: [ [] ] } ],
  operator: 'deepEqual'
}

I referred to the documentation for both the version but didn’t find it useful.

v10

v14

I understand of course that the error object is empty in one but not in the other. But cannot find the reason why v10 ignores it and what changed later because of which the error is now caught

How to get thrown errors in service task implemented with JavaScript SDK in my code?

I have a process definition which whenever my web app client sends a specific request to my server, I start an instance of it. In this process, I have a service task that I have implemented it using javascript SDK. In this service task under some conditions, I throw a BPMN error like this:

export const checkTimePeriod = () => {
 client.subscribe("checkTimePeriod", async function ({ task, taskService }) {
  const requestTime = task.variables.get("requestTime");

  if (requestTime < 20) {
     // complete the task
     await taskService.complete(task);
  } else {
    const errorMessage = "Not in allowed time period";
    await taskService.handleBpmnError(task, errorMessage);
  }
});
};

Now since this is a callback and runs whenever my process reaches this state, how can I get this error in my own code in the upper function? Thanks.

Function can’t get Object from Class

I have a forEach method that has a function(displayBook) where it displays details of a book from an Array created from a Constructor class.

myLibrary.forEach(Book => {
    displayBook(Book)
})

function displayBook (item) {
    let div = document.createElement("div")
    let listName = document.createElement("li")
    let listPages = document.createElement("li")
    let listRead = document.createElement("li")
    let removeButton = document.createElement("button")
    
    document.body.appendChild(div)
    div.className = "bookCard"
    listName.textContent = item.name
    listPages.textContent = item.pages
    listRead.textContent = item.read
    div.appendChild(listName)
    div.appendChild(listPages)
    div.appendChild(listRead)

    div.appendChild(removeButton)
    removeButton.className = "removeButton"
    removeButton.textContent = "Remove Book"
}

I have another function(addBookToLibrary) that asks for new data and add it into the array. Then calls the function(displayBook) to display the new data. This function creates another div as written but it does not get thew item.name, item.pages, and item.read of the new data. It also says

Uncaught TypeError: item is undefined
function addBookToLibrary(item) {
        let bookName = prompt("Enter book name.")
        let pageNumber = prompt("Enter number of pages.")
        let readStatus = prompt("Have you read it?")
        const newBook = new Book(bookName, pageNumber, readStatus)
        myLibrary.push(newBook)
        displayBook(item)
    }

Accessing an javascript object by its index [duplicate]

I try to access this object. I want the value of property “city” from index [0] and save it in a variable. But I just found solutions for other constructions of an object.

var distance_to_each_city = [{
    'distance': [123],
    'city': 'Mannheim'
  },
  {
    'distance': [654],
    'city': 'Berlin'
  },
  {
    'distance': [342],
    'city': 'München'
  },
  {
    'distance': [444],
    'city': 'Hamburg'
  },
  {
    'distance': [442],
    'city': 'Köln'
  }
]

How to sort embed fields in order (Discord.js)

const { writeFileSync, readFileSync } = require('fs');

let json = JSON.parse(readFileSync('./json.json', 'utf-8'));
client.on('message', (message) => {
  if (message.content.startsWith(`${prefix}test`)) {
    if (json[message.guild.id]?.slot >= 17)
      return message.channel.send(`**Lobby 1 IS FULL!, use 1checkin2`);
    let s =
      message.member.roles.cache.find((r) => r.name === 'Tier1') ||
      message.member.roles.cache.find((r) => r.name === 'Tier2');

    let msg = '933343245725999134';
    let channel = message.guild.channels.cache.get('932431084132646942');
    channel.messages.fetch(msg).then((msg) => {
      let embed = msg.embeds[0];
      var arg = message.content.split(' ').slice(1).join(' '); //
      if (!arg) return message.reply('mention first');
      if (!json[message.guild.id]) {
        json[message.guild.id] = { slot: 1 };
      }

      embed.addField(
        `> `SLOT ${json[message.guild.id].slot}:``,
        `${arg}` + `${s}`,
      );
      json[message.guild.id].slot++;
      writeFileSync('./json.json', JSON.stringify(json, null, 2));
      msg.edit(embed);
    });
  }
});

I need to sort them:

so Tier 1 be on top
and Tier 2 be in the bottom
and SLOT number changes with it

how it should look:

I tried using embed.fields.sort but I couldn’t do it

how to retrieve the last unique object in an array

Hey guys is there a way i can retrieve the last unique object in an array
in the code below the id at the first and second index are the same is there a way i can retrieve the last occurrence of the id with the corresponding object

0: {id: 'tra.528555295', name: 'heart'}
1: {id: 'tra.528555295', name: 'heart-outline'}
2: {id: 'tra.528555301', name: 'heart'}
3: {id: 'tra.528555301', name: 'heart-outline'}

Passsing props from App.js to Stack.Screen React Native

I’m again asking a question regarding ReactNative: I have the following App.js:

export default function App() {

  function Tabs() {
    return <TabBar />;
  }

  const styles = StyleSheet.create({
    backButton: {
      color: global.GUI.ORANGE,
    },
  });

  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen
          name="Tabs"
          component={Tabs}
          ..
        />
        <Stack.Screen
          name="Impostazioni"
          component={Settings}
          ...
        />
        <Stack.Screen
          name="Registrati"
          component={Signup}
         ...
        />
        <Stack.Screen
          name="Login"
          component={Login}
          ...
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

I want to pass to each component some values declared in App.js,but doing something like:

            <Stack.Screen
              name="Impostazioni"
              component={Settings}
              currentUser={"name":"test"}
            />

Return undefined in:

import React from 'react';
import {View,Text} from 'react-native';

const Settings = (props) => {
  --> console.log(props.currentUser) // here is undefined
  return (
    <View >
     <Text>This is Settings!</Text>
    </View>
  );
};

export default Settings

So, how can I correctly pass props to App.js to all other components?

Thanks

How can I generate line number from css or javascript based on height of container

I have a situation where I have to make something that looks like a code editor and to acheive this I have to use HTML, CSS and Js without any libraries.

I have achieved pretty much everything except the line numbers and I am not sure how to do it.

So far I have achieved this:
enter image description here

and this is what actually is my target:
enter image description here

supposing that I have this html structure:

<html>
    <head>
    </head>
    
    <body>
        <div class="lines"></div>
        <div class="code"></div>
    </body>
</html>

enter image description here

how do I populate lines based on the height of content in code using CSS or JavaScript?