How to return an Object Value if you have a specific key in your Object? [duplicate]

// If successfully created
let sampleObject = {
response: ‘Generated ID from the application’
}

// If error
let sampleObject = {
errorLog: ‘Generated error message from the application’
}

I have an object that returns different keys depending if it is successful or an error (see above sample code). If it is successful, it has a key of ‘response’ and has a value of ID generated, otherwise it has a key of ‘errorLog’ and has a value of the error message. Now I want to run an if statement with those keys. For example, if the key ‘response’ is present, I want to alert the user for the generated ID for successfully creating the data. But if the key ‘errorLog’ is present, I want to alert the user for the error message.

Can someone help me?

Rearrange divs – Place each div under each image (javascript – jQuery)

I have the following structure example:

<div class="main">
    <div class="image">Image1</div>
    <div class="image">Image2</div>
    <div class="image">Image3</div>
</div>
<div class="side">
    <div class="Banner">Banner1</div>
    <div class="Banner">Banner2</div>
    <div class="Banner">Banner3</div>
    <div class="Banner">Banner4</div>
</div>

I want to make a script that will take each banner and placed under each image.

    <div class="main">
        <div class="image">Image1</div>
        <div class="Banner">Banner1</div>
        <div class="image">Image2</div>
        <div class="Banner">Banner2</div>
        <div class="image">Image3</div>
        <div class="Banner">Banner3</div>
        <div class="Banner">Banner4</div>
    </div>
 <div class="side"></div>

Basically there are some images placed one after another and then some banners placed one after another.

Image1
Image2
Image3
Banner1
Banner2
Banner3
Banner4

I need to take each banner and place it under each image so I can have:

Image1
Banner1
Image2
Banner2
Image3
Banner3
Banner4

I cannot change the html to manually placed the banners, I need to use a more advanced script JS and or jquery ..

.content {display:flex; max-width:800px;min-width:300px;gap:20px;margin:auto;}
.main { flex: 70%;}.main2 {max-width:400px;} 
.side { flex: 30%;  padding:10px;}.img {    background:blue;}.banner {  background:red;}
.img, .banner { width:100%; min-width:50px; height:50px;display:grid;place-items:center;    color: #fff;    margin:10px auto;}
<h2>Rearrange content - Place each div (banner) under each image </h2>
<div class="content">
    <div class="main">
        <div class="img">Image 1</div>
        <div class="img">Image 2</div>
        <div class="img">Image 3</div>
        <div class="img">Image 4</div>
        <div class="img">Image 5</div>
        <div class="img">Image 6</div>
        <p> Multiple DIVs with images ...
        <br>    ...
    </div>
    <div class="side">
        <div class="banner">Banner1</div>
        <div class="banner">Banner2</div>
        <div class="banner">Banner3</div>
        <div class="banner">Banner4</div>
        <div class="banner">Banner5</div>
        <div class="banner">Banner6</div>
        <div class="banner">Banner7</div>
        <div class="banner">Banner8</div>
        <div class="banner">Banner9</div>
        <div class="banner">Banner10</div>
        </div>
    </div>
<hr>
    <h2> This is how it should look </h2>
    <div class="main2">
  <div class="img">Image 1</div>
        <div class="banner">Banner1</div>
        <div class="img">Image 2</div>
        <div class="banner">Banner2</div>
        <div class="img">Image 3</div>
        <div class="banner">Banner3</div>
        <div class="img">Image 4</div>
        <div class="banner">Banner4</div>
        <div class="img">Image 5</div>
        <div class="banner">Banner5</div>
        <div class="img">Image 6</div>
        <div class="banner">Banner6</div>
        <div class="banner">Banner7</div>
        <div class="banner">Banner8</div>
        <div class="banner">Banner9</div>
        <div class="banner">Banner10</div>
    </div>

Is there a way to compress the Chunk that is written to the response?

I want to reduce the size of the response by compressing the chunks written to the API response.
However, I’m not used to working with Node.js, so I’m not sure of the solution or keywords that might be relevant to the solution.


I use Node.js to write chunks in the response, and use it as an arrayBuffer on the client side.

API

const path = req.body.path;

try {
  for await (chunk of stream(path)) {
    res.write(chunk);
  };
  res.status(200).end();
}

Client

const res = await fetch("/api/get-buffer", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ path }),
});
const arrayBuffer = await res.arrayBuffer();

Currently, the above code can be used to get an ArrayBuffer from the API.
However, we would like to reduce the size of the response if it is possible.

Node.js error message while working through tutorial

I am working through https://medium.com/@mbostock/command-line-cartography-part-2-c3a82c5c0f3 but I am hitting this error:

C:tmpgeo-tutorial>ndjson-map -r d3 "(d.properties.fill=d3.scaleSequential(d3.interpolateViridis).domain([0,4000])(d.properties.density),d)" <ca-albers-density.ndjson >ca-albers-color.ndjson C:UserserwinAppDataRoamingnpmnode_modulesndjson-clirequires.js:6 module = require(resolve(module));
           ^

Error [ERR_REQUIRE_ESM]: require() of ES Module C:tmpgeo-tutorialnode_modulesd3srcindex.js from C:UserserwinAppDataRoamingnpmnode_modulesndjson-clirequires.js not supported. Instead change the require of index.js in C:UserserwinAppDataRoamingnpmnode_modulesndjson-clirequires.js to a dynamic import() which is available in all CommonJS modules.
    at module.exports (C:UserserwinAppDataRoamingnpmnode_modulesndjson-clirequires.js:6:12)
    at Command.<anonymous> (C:UserserwinAppDataRoamingnpmnode_modulesndjson-clinode_modulescommanderindex.js:412:13)
    at Command.emit (node:events:390:28)
    at Command.parseOptions (C:UserserwinAppDataRoamingnpmnode_modulesndjson-clinode_modulescommanderindex.js:730:14)
    at Command.parse (C:UserserwinAppDataRoamingnpmnode_modulesndjson-clinode_modulescommanderindex.js:471:21)
    at Object.<anonymous> (C:UserserwinAppDataRoamingnpmnode_modulesndjson-clindjson-map:15:6) {   code: 'ERR_REQUIRE_ESM' }

What does this mean and how can I fix this?

How to improve WebGL batch render speed

I am writing a small sprite sheet renderer in WebGL, where I render quad with set with and height then I take one big sprite sheet and use the texture coordinates to pick what sprite should be shown on what quad. I do this all in one big object with position and texture coordinates array where i push new items in. I’m also using TWGL library to make WebGL a bit less verbose. Currently this system of batching items into one draw per frame isn’t working that well, how can it be improved?

class Render {

  constructor(selector) {
    this.vertexShaderSource = `#version 300 es
    in vec2 position;
    in vec2 texcoord;

    uniform vec2 u_resolution;

    out vec2 v_texCoord;

    void main() {
      vec2 zeroToOne = position / u_resolution;

      vec2 zeroToTwo = zeroToOne * 2.0;

      vec2 clipSpace = zeroToTwo - 1.0;

      gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);

      v_texCoord = texcoord;
    }`;

    this.fragmentShaderSource = `#version 300 es
    precision highp float;

    uniform sampler2D u_image;

    in vec2 v_texCoord;

    out vec4 outColor;

    void main() {
      outColor = texture(u_image, v_texCoord);
    }`;

    this.bufferInfo;
    this.gl = document.querySelector(selector).getContext("webgl2");
    this.programInfo = twgl.createProgramInfo(this.gl, [this.vertexShaderSource, this.fragmentShaderSource]);
    this.textures = [];
    this.uniforms = {
      u_resolution: [innerWidth, innerHeight],
      u_image: null,
    }

    this.arrays = {
      position: [],
      texcoord: [],
    };

    this.gl.canvas.width = innerWidth;
    this.gl.canvas.height = innerHeight;
  }

  loadImage(url, callback) {
    const texture = twgl.createTexture(this.gl, { src: url, mag: this.gl.NEAREST }, () => { callback ? callback() : "" });
    this.textures.push(texture);
    return {
      texture: texture,
      index: this.textures.length - 1
    };
  }

  clearBuffer() {
    this.arrays.position = [];
    this.arrays.texcoord = [];
  }

  setTexture(texture) {
    this.uniforms.u_image = texture;
  }

  addQuad(x, y, width, height, srcWidth, srcHeight, srcX, srcY, realWidth, realHeight) {
    const x1 = x;
    const x2 = x + width;
    const y1 = y;
    const y2 = y + height;

    this.arrays.position.push(
      x1, y1, 0,
      x2, y1, 0,
      x1, y2, 0,
      x1, y2, 0,
      x2, y1, 0,
      x2, y2, 0,
    );

    this.arrays.texcoord.push(
      srcX / srcWidth / 1, srcY / srcHeight / 1,
      (srcX + realWidth) / srcWidth / 1, srcY / srcHeight / 1,
      srcX / srcWidth / 1, (srcY + realHeight) / srcHeight / 1,
      srcX / srcWidth / 1, (srcY + realHeight) / srcHeight / 1,
      (srcX + realWidth) / srcWidth / 1, srcY / srcHeight / 1,
      (srcX + realWidth) / srcWidth / 1, (srcY + realHeight) / srcHeight / 1,
    );
  }

  setBuffer() {
    this.bufferInfo = twgl.createBufferInfoFromArrays(this.gl, this.arrays);
  }

  resizeCanvas() {
    twgl.resizeCanvasToDisplaySize(this.gl.canvas);
    this.gl.viewport(0, 0, this.gl.canvas.width, this.gl.canvas.height);
  }

  render() {
    this.gl.useProgram(this.programInfo.program);
    twgl.setUniforms(this.programInfo, this.uniforms);
    twgl.setBuffersAndAttributes(this.gl, this.programInfo, this.bufferInfo);
    twgl.drawBufferInfo(this.gl, this.bufferInfo);
  }
}

const render = new Render("#game");
const texture = render.loadImage("https://i.imgur.com/TQnyNHU.png", () => {

    requestAnimationFrame(renderStuff);

    render.resizeCanvas();
    
    function renderStuff() {
        render.clearBuffer();
        render.setTexture(texture);
        for(let y = 0; y < 100; y++) {
          for(let x = 0; x < 100; x++) {
          render.addQuad(x * 48, y * 48, 48, 48, 512, 512, 32, 0, 16, 16);
          }
        }
        render.setBuffer();
        render.render();

        requestAnimationFrame(renderStuff);
    }
});
* {
    margin: 0px;
    padding: 0px;
}

body, html {
    width: 100%;
    height: 100%;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twgl.js/4.19.5/twgl.min.js"></script>
    <script src="main.js" type="module" defer></script>
    <link rel="stylesheet" href="style.css">
    <title>Prometeus</title>
</head>

<body>
    <canvas id="game"></canvas>
</body>

</html>

How to create element with absolute position

I want Date to appear above Second section. plz guide how to achieve it

    var sectionTwo = document.getElementById("sectionTwo");
    var x = sectionTwo.getBoundingClientRect();
    var b = document.createElement("div");
    b.style.position = 'fixed';
    b.innerHTML = new Date();
    document.body.appendChild(b);
    b.style.top = (x.top - b.style.height) + 'px';

Filter Array of objects with nested array

so I am trying to set up a nested filter on an array of objects.
The thing is that the filter is applied inside the object on a key that is another array of objects.

here is the code:

const items = [
  { name: "123", id: 1, value:  true, arr: [{ id: 1 }] },
  { name: "456", id: 2, value: false, arr: [{ id: 2 }] },
  { name: "456", id: 2, value: false, arr: [{ id: 3 }] },
  { name: "456", id: 2, value: false, arr: [{ id: 4 }] },
  { name: "456", id: 2, value: false, arr: [{ id: 5 }] },
  { name: "456", id: 2, value: false, arr: [{ id: 6 }] },
];

const newArray = items.filter((objects) => {
  objects.arr.filter((item) => {
    if (item.id === 2) {
      return objects;
    }
     
  });
});
console.log(newArray);

I ‘m not sure where to put the return because in this situation i just get an empty array.

Multiply javascript generated number by another number

How can i get the current number in a span and multiply it by 0.95? The number in the span is gotten from a range slider that starts from 0.003 to 0.075 below is the code i have

const uaaz = +document.querySelector("#maaz").textContent
const result = document.querySelector(".result")

function ug(ue) {
  up = ue * 0.95
  result.textContent = up
}
ug(uaaz)
<span id="maaz" class="aaz">number generated from range slider shows here</span>
<span class="result"></span>

The problem i have is that 0.003 is always the number being multiplied by 0.95 even if the number from the slider is higher. How can i make sure the current value in the span is used?

i want two make compare in foreach loop to compare if value of branch from jquery equal to value from foreach then selected it

I have a select and get value from jquery and want to compare it with value in foreach if two value id is similar then active the selected value how can i do this this is the foreach in blade:

i want two make compare in foreach loop to compare if value of branch from jquery equal to value from foreach then selected it

<select name="branch">
@foreach($branchs as $branch)
    <option value="{{$branch->id}}">{{$branch->title}} 
    </option>                                              
@endforeach
</select>

$.ajax({
url:getHref,
data:{id:id},
}).done(function(data) {
$.each(data, function(index,employee){
$( “input[name*=’name’]” ).val(employee.name );
$( “select[name=’branch’]”).val(employee.branch_id);
$( “select[name=’role_id’]” ).val(employee.role_id);
});
});
});

React: How do I prevent the usage of useRef and useState to keep track of a same value in order to prevent useEffect from triggering?

currently I am making a navbar that only shows when you scroll up, to prevent useEffect to run everytime when the visible state get changed, I had to use both a ref and a state that is synced together to do comparison in the useEffect, using ref and a state to keep track of a same value seems extremely fishy, is there another way of doing this? one that does not involve triggering useEffect from creating the event handlers everytime the state changes?

import React, { useState, useRef, useEffect } from 'react';
import Link from 'next/link';

const NavbarLink = ({ name, href }: { name: string, href: string }) => {
  return (
    <Link href={href}>
      <a>{ name }</a>
    </Link>
  );
}

const Navbar = () => {
  const scrollYRef = useRef(0);
  const visibleRef = useRef(true);
  const [visible, setVisible] = useState(true);

  useEffect(() => {
    const onScroll = (event: Event) => {
      event.preventDefault();
      if ((window.scrollY < scrollYRef.current) != visibleRef.current) {
        visibleRef.current = !visibleRef.current;
        setVisible(x => !x);
      }
      scrollYRef.current = window.scrollY;
    }

    window.addEventListener('scroll', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
    }
  }, []);

  return (
    <div className={`${!visible && '-translate-y-full'} fixed flex w-full h-32 font-bold text-white transition-all`}>
      <NavbarLink name="home" href='/'/>
    </div>
  );
}

javascript nested object and arrays adding new element problem

here is my code piece

const date = new Date()
let exactTime = date.toLocaleString('en-KL', { hour: 'numeric', minute: 'numeric', hour12: true })

const signUp = (username,email,password,isLoggedIn) => {
    let obj = {
        _id: 'ddfcd',
        username: username,
        email: email,
        password: password,
        createdAt:`${date.getDate()}/${date.getMonth()}/${date.getFullYear()} ${exactTime}`,
        isLoggedIn: isLoggedIn
    }
    let arr = [`${users2.length}`, obj]
    let collection = Object.entries(users2)
    collection.push(arr)
    users2 = collection
}

signUp('ali','[email protected]','123',false)
signUp('kerem','[email protected]','456',false)
signUp('johndoe','[email protected]','789',true)

when i get new user data at first the new one is exacrly similar with the rest however when add second one (or more) it misses an array it just turns array into object

here is the example what i mean when i add one more user then the previous one gets normal

what’s the problem here

Unable to get graphql response from server that’s running on local

I have a mongodb server setup which on running the below command starts on port 3000

npm run start 

I also a graphql server which on running the below command starts at port 4000

npm run start-graphql

the scripts of my package.json is as below

"scripts": {
    "start": "nodemon server.js",
    "start-graphql": "nodemon graphqlserver.js",
    "test": "echo "Error: no test specified" && exit 1"
  },

server.js

require('dotenv').config();
const express = require('express');
const app = express();
const mongoose = require('mongoose');
mongoose.connect(process.env.DATABASE_URL);
const db = mongoose.connection;


db.on('error', (err) => console.log(err));
db.once('open', () => {
    console.log("Backend Database connected");
});


app.use(express.json({ limit: '2mb'}));

const photosRouter = require('./routes/photos');
app.use('/images', photosRouter)


app.listen(3000, () => {
    console.log('Server started at port 3000');
})

graphqlserver.js

const express = require('express');
const path = require('path');
const express_graphql = require('express-graphql').graphqlHTTP;
const { loadSchemaSync } =  require('@graphql-tools/load');
const { GraphQLFileLoader } = require('@graphql-tools/graphql-file-loader');
const { addResolversToSchema } = require('@graphql-tools/schema');

const getResolvers = require('./graphql/resolvers');

// GraphQL schema
const combinedSchema = loadSchemaSync(
    path.join(__dirname, './graphql/schemas/*.graphql'),
    {
      loaders: [new GraphQLFileLoader()],
    }
  );
const schema = addResolversToSchema({
    schema: combinedSchema,
    resolvers: Object.assign({}, getResolvers())
  });

// Create an express server and a GraphQL endpoint
const app = express();

app.use('/graphql', express_graphql({
    schema: schema,
    graphiql: true
}));
app.listen(4000, () => console.log('Express GraphQL Server Now Running On localhost:4000/graphql'));

when I call the rest api’s normally either through postman or curl it returns the response as expected.

For eg: http://localhost:3000/images returns me an array of objects

But When I want to call (using axios) the same via the graphql server (which is running on port 4000 ),
I get response as null.
I have no clue why this is happening.
Please check the below screenshot for your reference
enter image description here

Note: For better clarity please check the codebase link
https://github.com/yaswankar/G-photos-backend

Any help would be appreciated.

Thanks in advance

VueJS Style Guide – Coding Standard

I’m coming from PHP and Laravel and I know there is coding standard for different frameworks like PSR. However, when I searched the internet I can not find proper way to stylize my code or any standard. I know there is some style guides like Airbnb style guide but it is just a guide. I like to see how to chain, where to split the code, when it exceeds 120 chars or 80 chars, things like that.

I like to my code persistent and properly formatted. Do you have any recommendation about it?