useRef not working as expected, in react-three-fiber. Ref elements not unmounting?

I am trying to animate this group of trees inside component. But the treeRefs keeps on increasing by 2 times on each frame and results in very wonky behaviour filled with glitches.
Logic – I have components which is a 3D Mesh. I am spwaning these trees on a random position and moving them along z-axis and when the mesh hits z = 0 I change it’s position around some starting point. This way trees should simulate moving animation. I am using useRef to keep track of each component and animate it’s position.
Also I have ScrollControls wrapped around and when I scroll this animation starts acting weird and useRefs starts to multiplying.
Example logs before scroll
enter image description here

Example logs after scroll
enter image description here

import { Detailed, useGLTF } from '@react-three/drei';
import { useFrame } from '@react-three/fiber';
import React, { createRef, useEffect, useMemo, useRef, useState } from 'react';
import { useStore } from './store/store';

function map_range(value, low1, high1, low2, high2) {
    return low2 + ((high2 - low2) * (value - low1)) / (high1 - low1);
}

export const Forest = () => {
    const treeRefs = useRef([]);
    const [positions, setPositions] = useState([]);
    const { acceleration, setAcceleration, currentAction, setCurrentAction } = useStore();

    // Move each tree towards starting when reaches the end line
    useFrame((state, delta) => {
        console.log('Delta', delta);
        console.log('Length ', treeRefs?.current?.length);
        console.log('Length Pos ', positions?.length);
        treeRefs?.current?.map((TreeMesh) => {
            // console.log('TreeMesh', TreeMesh.position.z);

            if (TreeMesh?.position?.z) {
                // console.log('Inside useFrame ', currentAction);
                TreeMesh.position.z = TreeMesh.position.z - delta;
                if (TreeMesh.position.z <= 0) {
                    TreeMesh.position.z = Math.random() * 50;
                }
            }
            return TreeMesh;
        });
    });

    useEffect(() => {
        // Create 30 objects with random position and rotation data
        const positions = [...Array(30)].map(() => {
            const randomPositionAmplitude = map_range(Math.random(), 0, 1, 2, 10);

            const randomPositionDirection = Math.sign(map_range(Math.random(), 0, 1, -1, 1));

            const xPosition = randomPositionAmplitude * randomPositionDirection;

            return {
                position: [xPosition, 1.7, Math.random() * 50],
                // rotation: [Math.random() * Math.PI * 2, Math.random() * Math.PI * 2, Math.random() * Math.PI * 2],
                rotation: [0, 0, 0],
                ref: createRef(),
            };
        });
        setPositions(positions);
    }, []);

    return (
        <>
            {positions.map((props, i) => (
                <Tree innerRef={(el) => treeRefs.current.push(el)} key={i} {...props} />
            ))}
        </>
    );
};

function Tree({ innerRef, ...props }) {
    // This will load 4 GLTF in parallel using React Suspense

    const { nodes, materials, animations, scene } = useGLTF('/Tree.glb');
    const copiedScene = useMemo(() => scene.clone(), [scene]);
    // By the time we're here these GLTFs exist, they're loaded
    // There are 800 instances of this component, but the GLTF data is cached and will be re-used ootb
    return (
        <Detailed ref={innerRef} distances={[300]} {...props}>
            {/* All we need to do is dump them into the Detailed component and define some distances
          Since we use a JSX mesh to represent each bust the geometry is being re-used w/o cloning */}

            <primitive object={copiedScene} />

            {/* <group /> */}
        </Detailed>
    );
}

What can be done to fix this?

Not sure what to try, I have other workarounds for this. But I want to know what’s wrong with my code.

Twitter embed timeline ‘data-tweet-limit’ attribute doesn’t work anymore

the ‘data-tweet-limit’ attribute doesn’t work anymore in my Twitter timeline, it shows all the tweets and don’t take into account the ‘data-tweet-limit’ attribute (it should display only 6 tweets in this case), can you guys help me? Here’s the code:

<a class='twitter-timeline' data-width="350" data-tweet-limit='6' data-chrome='noheader noborders noscrollbar transparent' data-partner='tweetdeck' href='https://twitter.com/TwitterDev/lists/national-parks?ref_src=twsrc%5Etfw'>tweet link</a>

scroll(function() not working until page is reduced to 1279px

Any ideas why the script I use to go back to the top of a page is not working unless the screen size is reduced to less than 1279px? I simply have a button appearing at the bottom of the screen when I scroll down the screen.
I don’t have any breakpoint set up in my CSS file and the script used to work until some point.

Here is the script I use:

var btn = $('#backtotop-button');
            
$(window).scroll(function() {
  if ($(window).scrollTop() > 300) {
    btn.addClass('show');
  } else {
    btn.removeClass('show');
  }
});

btn.on('click', function(e) {
  e.preventDefault();
  $('html, body').animate({scrollTop:0}, '300');
});

Thanks a lot,
Cheers

Normally the button I configured should appear when I scroll down the page. Now it only appears when I reduce the size of the page bellow 1279px.

VS Code snippets capitalize placeholder first letter

I’m building code snippets for VS Code. For a specific angular directive I need to lowercase the first letter of a previous placeholder:

<ng-container [bsInstanceof]="item">
  <ng-container *bsInstanceofCase="Ava; let ava">{{ Ava.a }}</ng-container>
  <ng-container *bsInstanceofCase="Bebe; let bebe">{{ Bebe.b }}</ng-container>
  <ng-container *bsInstanceofCase="Cece; let cece">{{ Cece.c }}</ng-container>
  <ng-container *bsInstanceofDefault>No match</ng-container>
</ng-container>

At the moment, I have the following code snippet (Marketplace):

"InstanceOf": {
    "prefix": "bs-instance-of",
    "description": "Template-driven `instanceof` switch-case",
    "body": [
        "<ng-container [bsInstanceof]="${1:item}">",
        "t<ng-container *bsInstanceofCase="${2:A}; let ${2/(.*)/${1:/uncapitalize}/}">{{ ${2/(.*)/${1:/uncapitalize}/}.${3:a} }}</ng-container>",
        "t<ng-container *bsInstanceofCase="${4:B}; let ${4/(.*)/${1:/uncapitalize}/}">{{ ${4/(.*)/${1:/uncapitalize}/}.${5:b} }}</ng-container>",
        "t<ng-container *bsInstanceofCase="${6:C}; let ${6/(.*)/${1:/uncapitalize}/}">{{ ${6/(.*)/${1:/uncapitalize}/}.${7:c} }}</ng-container>",
        "t<ng-container *bsInstanceofDefault>${8:No match}</ng-container>",
        "</ng-container>"
    ]
},

which, according to this answer and comments, should totally work. But the value of the placeholder is just being copied as-is:

VS Code snippet placeholder not transformed

Note that the comments in the linked question, state that the index before /uncapitalize is the regex match group index.
Why is this not working as expected?

MongoDB removed collback from its driver, help solve the problem

How can I fix this code so that it works correctly? If you enter a post id, it should be deleted.

I tried adding ‘promises’, async/await – didn’t help. In Postman I entered everything correctly (tokens, links, etc.), the same error:

Cannot DELETE /posts/(id)

export const remove = async(req, res) => {
  try {
    const postId = req.params.id;
    PostModel.findOneAndDelete({
      _id: postId,
    }, (err, doc) => {
      if (err) {
        console.log(err);
        return res.status(500).json({
          message: "Failed to delete post",
        });
      }

      if (!doc) {
        return res.status(404).json({
          message: "Post was not found",
        });
      }

      res.json({
        success: true,
      });
    });
  } catch (err) {
    console.log(err);
    res.status(500).json({
      message: "Failed to get the posts",
    });
  }
};

Hide Header of Bottom tab bar inside nested stack screen in react native

I have a Bottom tab bar navigator with three Tabs:
HomeStack
History
Account
the HomeStack is a a stack navigator of two screens:
HomeScreen
TestScreen

I would like to hide the header of the stack navigator in both screens , which is done
and i would like to hide the header of the bottom tab navigator only in TestScreen

here’s my code
BottomTabBar component

<Tab.navigator
   screenOptions={{headerShown: true}
  <Tab.screen name='home' component={HomeStack}/>
  <Tab.screen name='history' component={HistoryScreen}/>
  <Tab.screen name='account' component={AccountScreen}/>
</Tab.navigator>

the stack navigator:

<Stack.navigator
    screenOptions={{headerShown: false}}>
  <Stack.screen name='home' component={HomeScreen}/>
  <Stack.screen name='history' component={TestScreen}/>
</Stack.navigator>

The problem is that the header of the bottom navigator is shown in both HomeScreen and TestScreen
how an i achieve this behavior ?

The tiktok video that I embed in fanctbox disappears

The tiktok video that I embed in fanctbox disappears

I need to embed videos from different sources into fancybox. I’m using “@fancyapps/ui”: “^5.0.17”. I get the data for the video by api and insert it into the fancybox depending on the resource from which I get the video. I add videos from YouTube, VK and TikTok.
Videos from YouTube and VK are inserted without problems, but a video from TikTok, although it is inserted, disappears immediately after opening the fancybox. The video is still on the page as seen in the browser’s code inspector. If I open this video in fancybox and then reload the page, then after reloading the video does not disappear and I can watch it. Or if I open this video very quickly in the fancybox, then I can also watch it. But in both cases, if I close the fancybox, the video will disappear

Here is the code in which I get data from tiktok:

$apiUrl = "https://www.tiktok.com/oembed?url={$link}";

try {
    $response = $client->get($apiUrl);
    $jsonResponse = json_decode($response->getBody(), true);
    
    $html = $jsonResponse['html'];
    $preview = $jsonResponse['thumbnail_url'];
} catch(Exception $exception) {
    $html = false;
    $preview = '';
}

return view('widgets.index_iframe_tik_tok_widget', [
    'html' => $html,
    'masterJob' => $this->config['index'],
    'key' => $this->config['key'],
    'preview' => $preview
]);

$html contains iframe(blockquote) for video:

<blockquote class="tiktok-embed" cite="https://www.tiktok.com/@world_walkerz/video/7218998983937625349" data-video-id="7218998983937625349" data-embed-from="oembed" style="max-width: 605px;min-width: 325px;" id="v62804243901872250">  </blockquote>
<script async="" src="https://www.tiktok.com/embed.js"></script>

$preview contains thumbnail url

Code from widgets.index_iframe_tik_tok_widget:

@if($html)
    <div>

    <span data-thumb="{{ $preview }}" data-fancybox="{{ $index->id }}" data-src="#dialog-content-{{ $index->id }}-{{ $key }}"></span>
        <div style="display: none" id="dialog-content-{{ $index->id }}-{{ $key }}">
            {!! $html !!}
        </div>
    </div>
@endif

To prevent the video from being displayed under the fancibox open button, I added style=”display: none”. If this attribute is removed, nothing will change.

HTML/PHP prevent single quotes from converting to double quotes

I’m running into an issue when trying to put onclick="javascript:ReverseDisplay('divId')" in a <href> within php print_r.

The single quotes used with divId gets converted to double quotes when rendered in the browser. This breaks the onClick.

I have tried to put javascript:ReverseDisplay('divId') in a php variable called $showHideDiv and included this in the print_r with htmlspecialchars_decode as in the code below. I also tried using addslashes instead of htmlspecialchars_decode, but with the same result.

<script type="text/javascript" language="JavaScript">
    function HideContent(d) {
      document.getElementById(d).style.display = "none";
    }
    function ShowContent(d) {
      document.getElementById(d).style.display = "block";
    }
    function ReverseDisplay(d) {
      if(document.getElementById(d).style.display == "none") { document.getElementById(d).style.display = "block"; }
    else { document.getElementById(d).style.display = "none"; }
    }
  </script>

<?php $showHideDiv = "javascript:ReverseDisplay('divId')"; ?>

<div class="addressWrapper">
  <?php for( $i=0; $i < count($arr); $i++) {

  print_r ("<div class='addressBoxes'><b><a href='#' class='map-navigation' data-zoom='16' data-position='".$arr[$i]['lat'].", ".$arr[$i]['lon']."' onclick='" . htmlspecialchars_decode($showHideDiv) . "'>".$arr[$i]['name']."</a></b> &nbsp;&nbsp; <a href='https://www.google.com/maps/search/?api=1&query=".$arr[$i]['lat'].",".$arr[$i]['lon']."'><i class='fas fa-map-marked-alt' style='font-size:1.5em;'></i></a>
    <i>".$arr[$i]['street']."<br>".$arr[$i]['zip']." ".$arr[$i]['city']."</i>
    </div>"
  );

  }


  ?>

<div id="divId" style="display:none">
List of addresses
</div>

This results in the following html output (note the double quote and the trailing ="" in (" divId')'=""):

<a href="#" class="map-navigation" data-zoom="16" data-position="58.99889685225431, 5.61696675933428" onclick="javascript:ReverseDisplay(" divId')'="">Toggle Div</a>

When I edit the link in chrome debugger and change the double quote to a single quote, the onClick works.
I tried to force the single quote to stay that way by using &#39;.
This makes the html output look correct, but the onClick still does not fire.

<a href="#" class="map-navigation" data-zoom="16" data-position="58.99889685225431, 5.61696675933428" onclick="javascript:ReverseDisplay('divId')">Toggle Div</a>

Is there another approach to this?

How to replace value in javascript or ecmascript?

I need to replace All in s2data Emp_Id with the response data’s values(expected output appended), ignore 0 and 1 in response they are not required.

I can’t use inbuilt function like Object.fromEntries because they are not working in apache nifi execute script. So I have to do this with foreach or with loop so that it can work in nifi.
I tried it but it didn’t work.

var response = {
    "status": "success",
    "data": [[123, 0], [124, 0], [446, 0], [617, 1], [620, 0], [470 ,1]]
};

var s3data = {
    "Emp_Id": "All",
    "Emp_loc": 523,
    "Emp_dept": "Management",
    "Emp_sub_dept": "Finance",
    "Emp_sub_dept2": "Accountant"
};
var result={}
var dataName = s3Data[0].Emp_Id;
   response.data.forEach(function(elem, index) {
      if(dataName==='All'){
        result[0].Emp_Id=elem[0];
      }
      
    });

console.log(result);

EXPECTED OUTPUT:

[
  {
    Emp_Id: 123,
    Emp_loc: 523,
    Emp_dept: 'Management',
    Emp_sub_dept: 'Finance',
    Emp_sub_dept2: 'Accountant'
  },
  {
    Emp_Id: 124,
    Emp_loc: 523,
    Emp_dept: 'Management',
    Emp_sub_dept: 'Finance',
    Emp_sub_dept2: 'Accountant'
  },
  {
    Emp_Id: 446,
    Emp_loc: 523,
    Emp_dept: 'Management',
    Emp_sub_dept: 'Finance',
    Emp_sub_dept2: 'Accountant'
  },
  {
    Emp_Id: 617,
    Emp_loc: 523,
   Emp_dept: 'Management',
    Emp_sub_dept: 'Finance',
    Emp_sub_dept2: 'Accountant'
  },
  {
    Emp_Id: 620,
    Emp_loc: 523,
    Emp_dept: 'Management',
    Emp_sub_dept: 'Finance',
    Emp_sub_dept2: 'Accountant'
  },
  {
    Emp_Id: 470,
    Emp_loc: 523,
    Emp_dept: 'Management',
    Emp_sub_dept: 'Finance',
    Emp_sub_dept2: 'Accountant'
  }
]

Why is my logout route in Express.js failing to redirect and how can I fix it?

Logout route doesn’t work, even if another route is used, it fails to render or redirect to that route. But the console.log("am clicked"); works

const express = require('express')
const app = express()
const path = require('path')
const fs = require('fs')
const port = 7000
const sqlite3 = require("sqlite3").verbose();
const session = require('express-session');
const cookieParser = require('cookie-parser');
const bodyparser = require('body-parser');

let fdata = require('./fashion.json');
fdata = fdata.Sheet1;


app.use(session({
  secret: 'keyboardwarrior',
  resave: false,
  saveUninitialized: true,
  cookie: {
      maxAge: 30 * 60 * 1000 // 30 minutes
  }
}));


app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));
app.use(express.static(path.join(__dirname, "public")));
app.use(express.urlencoded({ extended: false }));
app.use(bodyparser.json());
app.use(cookieParser());

app.get('/', (req, res) => {
  res.render('shop');
})

app.get('/shop', (req, res) => {
  res.render('shop');
})

app.get('/checkout', (req, res) => {
  res.render('checkout')
})

app.get('/fashion', (req, res) => {
res.send(fdata)
})

// Loggedin
app.get('/loggedin', (req, res) => {
  res.render("shop")
})

// Blank
app.get('/blank', (req, res) => {
  res.render("blank")
})


// Register
app.post('/register', async (req, res) => {
  const {firstname, lastname, usermail, password} = req.body; 
  if (!usermail || !password) return res.status(400).send({error: "Email or password missing."});

  db.serialize(() => {
    db.each('SELECT COUNT(*) as count FROM user WHERE email = ?', [usermail], (err, row) => {
      console.log(row)
      if(err) {
        console.log(err.message);
      } else if(row.count > 0) {
        console.log('there is a match');
      } else {
        db.run('INSERT INTO user (fname, lname, email, pass) VALUES(?,?,?,?)', [firstname, lastname, usermail, password], (err) => {
          if (err) {
            return console.log(err.message);
          }
          console.log("User successfully registered.");
        })
      
        res.redirect('/')
      } 
    }); 
  
  });


})


// const isLoggedIn = (req, res, next) => {
//   if(req.session.currentUser){
//       next();
//   }else{
//       res.redirect("/");
//   }
// };

// app.get("/", isLoggedIn, (req, res) => {
//   res.render("/", {currentUser: req.session.currentUser});
// });


app.get('/user/:id', function(req,res){
  const id = req.params.id;

  db.serialize(()=>{
    db.each('SELECT * FROM user WHERE _id = ?', [id], (err, row) => {     
    
      try {
        console.log(`${row._id}`);
        res.send(row);
      }catch (err) { 
        res.status(400).send(err);
      }
    
    })
  })
});


// login
app.post('/', async (req, res) => {
  const {usermail, password} = req.body; 

  db.serialize(()=>{
    db.each('SELECT _id ID, email USEREMAIL, pass USERPASS FROM user WHERE email = ?', [usermail], (err, row) => {     
      if(err){
        return console.error(err.message);
      }else {
       
        try {
          if(row.USEREMAIL && row.USEREMAIL === usermail) {
            console.log(`${row.ID}`);
            req.session.isLoggedIn = true;
            req.session.currentUser = `${row.USEREMAIL}`;
            res.render('shop', {uid: `${row.ID}`});
          }
        } catch (err) { 
            res.status(400).send(err);
        }

      } 
    })
  })
  
})

app.post('/logout', (req, res) => {
console.log("am clicked");
  if (req.session) {
    req.session.destroy();
    console.log('have been clicked');
  }
  return res.render('shop', {uid: ``});
});

const db = new sqlite3.Database('users.db', err => {
  if (err) {
    return console.error(err.message);
  }
  console.log("Successful connection to the database 'users.db'");
});

app.all('*', (req, res) => {
  res.render('404');
})

app.listen(port, () => {
  console.log(`Listening on port ${port}`)
})


Am expecting it to re-render the home route

Upload excel file in javascript and get the object

I want to upload ecel read the content and add those content in the data table .

This is how i am trying to do using this reference https://javacodepoint.com/convert-excel-file-data-to-json-in-javascript/

    $('#uploadFile').on('click', async function () {
      var files = document.getElementById('stocksform').files;
      if(files.length==0){
        alert("Please choose any file...");
        return;
      }
      var filename = files[0].name;
      var extension = filename.substring(filename.lastIndexOf(".")).toUpperCase();
      if (extension == '.XLS' || extension == '.XLSX') {
        var jsonResult  =  excelFileToJSON(files[0]);
        console.log(jsonResult);
      }else{
          alert("Please select a valid excel file.");
      }
    
    $('#exampleModal').modal('toggle');
    });

The excelFileToJSON

    function excelFileToJSON(file){
     try {
       
        var reader = new FileReader();
        reader.readAsBinaryString(file);
        reader.onload = function(e) {
            var data = e.target.result;
            var workbook = XLSX.read(data, {
                type : 'binary'
            });
            var result = {};
            workbook.SheetNames.forEach(function(sheetName) {
                var roa = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
                if (roa.length > 0) {
                    result[sheetName] = roa;
                }
            });
            console.log(result);
            return result ; 
           }
        }catch(e){
            console.error(e);
        }
    }       

Issue is when i am running it the below code gets (from the above code) executed with ‘undefined’ in the console

    var jsonResult  =  excelFileToJSON(files[0]);
        console.log(jsonResult);

and there after i can see the result printed from this line inside the excelFileToJSON .

        console.log(result);

There is some issue with reader.onload , that returns undefined but after sometime it provides the result . What can be the issue.

Which is the naming convention in software development to use in this case [closed]

Am writing an SRS document and am stuck in in the users names.
The system is a fleet management system and it has 4 users driver, user (end user who request for transport), transport officer (who manages the vehicles and drivers), manager (who is the boss and need to see the overall functionality of the system).
So my question is what better names can I give them as I was told to user the name, transport officer and manger as the roles can change and be assigned to another person who is not part of the transport team?

Am thinking of using names like super admin and admin how is that?