javascript(node js) new date is giving wrong current datetime [closed]

In my nodejs project, new Date() function is giving me a datetime that is six hours behind from my local datetime. Suppose if my local time is 2023-05-11T10:00:00.070Z its giving me 2023-05-11T04:00:00.070Z. There is nothing wrong with the datetime of my pc. Then why is it happening ? How can I get the actual datetime ?

My current timezone is Asia/Dhaka

code:

var current_date = new Date()
console.log(current_date)

Please help.

Mybutton prev and next is not working | Next js Owl Carousel

I can’t use my button prev and next, how do i get the button to work.

This my code


export const Slider = () => {
  const carouselRef = useRef(null);

  const handlePrev = () => {
    carouselRef.current.prev();
  };

  const handleNext = () => {
    carouselRef.current.next();
  };

  const options = {
    responsive: Responsive,
    loop: true,
    autoplay: true,
    autoplayTimeout: 3500,
    autoplayHoverPause: true,
    dots: true,
    nav: true,
    navText: ["<", ">"],
  };

  return (
    <div className=' items-center justify-center content-center flex flex-row py-44'>
      <button onClick={handlePrev}>prev</button>
      <div className='mx-auto w-5/6'>
        <OwlCarousel ref={carouselRef} {...options}>
          {images.map((item, index) => (
            <div
              key={index}
              className='bg-white shadow-lg rounded-xl overflow-hidden md:m-5 m-3 md:p-6 px-2 py-3'>
              <div className='h-36 flex flex-col items-center justify-center text-center'>
                <img src={item.images} className='object-contain h-full' />
                <div className='w-full'>
                  <h2 className='title-font font-semibold text-lg text-green-400'>
                    {item.name}
                  </h2>
                  <h3 className='text-gray-700 mb-3'>{item.role}</h3>
                </div>
              </div>
            </div>
          ))}
        </OwlCarousel>
      </div>
      <button onClick={handleNext}>next</button>
    </div>
  );
};

I tried to using useRef but give me an error
“TypeError: carouselRef.current.prev is not a function”
enter image description here

I want to fix the button, like is there a way to link it with navtext or is there some other way? please help

Error: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it) in next.js 13.4.1

I am working in the next.js new version 13.4.1 App route , I made a api route.js I want to get something but I getting error ,

- error ./node_modules/bson/lib/bson.mjs
Module parse failed: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)
Error: The top-level-await experiment is not enabled (set experiments.topLevelAwait: true to enabled it)      
Import trace for requested module:

when I installed next.js ever after that next.config.js file was empty
. if I tried write some code inside the next.config.js then i getting anther error

 warn Invalid next.config.js options detected: 
- warn     The root value has an unexpected property, topLevelAwait, which is not in the list of allowed properties (amp, analyticsId, assetPrefix, basePath, cleanDistDir, compiler, compress, configOrigin, crossOrigin, devIndicators, distDir, env, eslint, excludeDefaultMomentLocales, experimental, exportPathMap, generateBuildId, generateEtags, headers, httpAgentOptions, i18n, images, modularizeImports, onDemandEntries, optimizeFonts, output, outputFileTracing, pageExtensions, poweredByHeader, productionBrowserSourceMaps, publicRuntimeConfig, reactStrictMode, redirects, rewrites, sassOptions, serverRuntimeConfig, skipMiddlewareUrlNormalize, skipTrailingSlashRedirect, staticPageGenerationTimeout, swcMinify, target, trailingSlash, transpilePackages, typescript, useFileSystemPublicRoutes, webpack).

how to solve it !

next.config.js

/** @type {import('next').NextConfig} */
const nextConfig = {
    
}

module.exports = nextConfig;

Api Route when i tried to get something , app/api/user/route.js
its code not working showing error.

import dbConnect from "../../../../lib/connect";

export async function GET(req, res) {
      dbConnect()
    return new Response('Hello, Next.js! I can make twitter clone',  {
      status: 200,  
    });
   
  }
  

Split Scrolling in React

I have been trying to simulate the same effect as https://replit.com/ has with their split scrolling.

Here is what I got so far: https://codesandbox.io/s/silly-goldberg-o18f3t?file=/src/App.js

I cant seem to get the left side to scroll with the right side.

So when I scroll from the right side, it seems to be fine but when I scroll from the left side it goes straight to the next section of my website without scrolling through the images.

Basically I need them to be scroll at the same time regardless where the cursor is until the right side is done scrolling.

Am I going about this all wrong? Should I be using a library like gsap?

Thanks for your time

turbolinks:load eventlistener in rails 7 partial not executing

I have a partial with some radio buttons and a submit button.

    <div class="row align-items-center h-100">
      <div class="col-md-6 mx-auto">
              <form>
        <% @options.each_with_index do |option, index| %>
          <div class="mb-3 text-center custom-radio">
            <input class="form-check-input" type="radio" name="exampleRadios" id="exampleRadios<%= index + 1 %>" value="<%= index %>">
            <label class="form-check-label" for="exampleRadios<%= index + 1 %>"><%= option %></label>
          </div>
        <% end %>
      </form>
      </div>
    </div>
  </div>

<div class = "container text-center" style = "padding-top:20px">
    <button id="submit-answer-button" class="btn btn-primary" disabled> Submit </button>
  </div>

I also have this script underneath the same partial file:

<script>
console.log('test')
document.addEventListener('turbolinks:load', function() {
console.log('test1')
  let submitButton = document.getElementById('submit-answer-button');
  let radioButtons = document.querySelectorAll('input[type="radio"]');

  for (let i = 0; i < radioButtons.length; i++) {
    radioButtons[i].addEventListener('change', function() {

      if (this.checked) {

        submitButton.disabled = false;
      }
    });
  }
});
</script>

I confirmed that the console produces ‘test’ but not ‘test1’ so something is wrong with turbolinks. I’ve tried a lot of different things like using DomContentLoad instead and placing this in the application view. Nothing works! The turbolinks:load simply refuses to execute.

In ES6 classes why exported class can’t call nested methods?

I have this test class, whenever i call methodfinal in my controller.js the console.log doesn’t show up? why is that happening?

class Test {
  methodFinal() {
    this.method1and2();
  }

  method1and2() {
    this.method1();
    this.method2();
  }

  method1() {
    console.log('test');
  }

  method2() {
    console.log('test');
  }
}

export default new Test();

This is my my controller

import Test from './test.js';

Test.methodFinal();

How to migrate R software-based program to SPA?

I have a program that is based on R software to get a glicko analysis.

enter image description here

The program requires some packages like RPostgres and stringr to manage the database connection, and also dbplyr, tidyverse, playerRatings, ggplot2, GGally.

I am trying to migrate this kind of program over to a JavaScript-based one like Vue or React using highcharts.

It is my first time touching R software, so I am feeling very difficult to read the lines.

I don’t feel any difficulties with DB management or SQL queries used in the R program, but the most difficult thing is to read R software libraries and the functions.

tmp <- glicko2(subdat %>% 
                 filter(class == "5th") %>%
                 select(Week,Person,Question,Score), 
               status = questions %>% rename(Player = Question))$ratings %>%
  select(Player,Rating,Deviation,Volatility) %>%
  filter(str_starts(Player,"p_")) %>%
  rename(Person = Player)

Is there any way to integrate the R software directly in an SPA without updating the code or how can I migrate it over to SPA easily?

Child div 1 overflows Parent div and I can’t get Child div 2 (child div 1s sibling) to be same width as child div 1

I have a codesandbox here that shows what I mean. I want the blue table to be as wide as the width of all the cards. The cardsData length will vary, and don’t want to add complexity by calculating its width. is there a way for parent’s width (or sibling width) to become the same as overflowing cards width?

Thanks in advance. If it’s easier, here’s the same code pasted

import "./styles.css";
import React, { useEffect, useState } from "react";

import {
  Box,
  Grid,
  TableContainer,
  Paper,
  Table,
  TableHead,
  TableRow,
  TableCell
} from "@mui/material";
export default function App() {
  const cardsData = [{}, {}, {}, {}, {}];

  const TableData = () => (
    <TableContainer
      component={Paper}
      sx={{ width: "100%", background: "blue" }}
    >
      <Table id='would like table to extand same width as width of cards' sx={{ ".MuiTableCell-root": { minWidth: "20%" } }}>
        <TableHead>
          <TableRow>
            <TableCell></TableCell>
          </TableRow>
        </TableHead>
      </Table>
    </TableContainer>
  );

  const Cards = ({ i }) => (
    <Box
      sx={{
        background: i === 0 ? "#f6f7f7" : "#f5f7fe",
        minWidth: "20%",
        maxWidth: "250px",
        borderRadius: "4px",
        display: "flex",
        flexDirection: "column",
        gap: 3,
        pt: 0,
        pb: 4,
        pl: 4,
        pr: 4
      }}
    />
  );

  return (
    <div className="App">
      <Box
        sx={{
          display: "flex",
          gap: "16px",
          minHeight: "250px"
        }}
      >
        {cardsData?.map((c, i) => (
          <Cards cardData={c} i={i} key={i} />
        ))}
        {/* extra card just cuz */}
        <Cards />
      </Box>
      <TableData />
    </div>
  );
}

Add Event Listener to elements inside jsrender

I have an HTML template inside a text/x-jsrender (this is just a part of it):

<script type="text/x-jsrender" id="js-true-up-location-items-list-template">
    <input name="actualSalesCount"
       id="actual-sales-count-input-{{:id}}"
       class="numeric-input"
       type="text"
       value="{{:actualSalesCount}}"
       data-id="{{:id}}">
</script>

I want to attach an event listener to all of the input text that have the numeric-input class.

I added the following code:

<script type="text/javascript">
window.onload = function () {
  console.log("Page has been loaded");
  $(document).ready(function () {
        console.log('enabling arrow navigation from the page!');
        $('.numeric-input').keyup(function (e) {
        console.log('keyup!');
        if (e.which == 39) { // right arrow
            $(this).closest('td').next().find('input').focus();

        } else if (e.which == 37) { // left arrow
            $(this).closest('td').prev().find('input').focus();

        } else if (e.which == 40) { // down arrow
            $(this).closest('tr').next().find('td:eq(' + $(this).closest('td').index() + ')').find('input').focus();

        } else if (e.which == 38) { // up arrow
            $(this).closest('tr').prev().find('td:eq(' + $(this).closest('td').index() + ')').find('input').focus();
        }
        });
 });
};
</script>

So, the “Page has been loaded” log is displayed, also the “enabling arrow navigation from the page!”, but when I press keys inside the input, nothing happens.

Any idea?

Thanks!

Opening a computed document using window.open() and data: scheme

I have a webpage running in a browser that generates a computed HTML document, and I want to open that document in a new browser tab.

The simple and dirty method is to do this:

const w = window.open('', '_blank');
w.document.open();
w.document.write(htmlContents);
w.document.close();

Easy enough. But this has some awkward consequences that I do not like. Namely, the URL of the new tab has to point somewhere, but there is nowhere to point it at since the new document is computed on the fly. If I specify no URL, it uses the URL of my webpage. So if someone refreshed the tab containing the generated document, the document disappears and a new instance of my webpage loads in its place. This would be confounding to the user.

What I believe better suits my needs is to use a data URI instead. I would simply encode the entire contents of my webpage into the URI itself, and use window.open() to open that URI. It’s ugly, but semantically aligned with my goal: a standalone computed document that can’t accidentally be navigated out of due to page refreshing.

I constructed what I thought was a trivially simple concept for this, like so:

const doc = encodeURIComponent('<html><body><p>Hello, world!</p></body></html>');
window.open(`data:text/html;charset=utf-8,${doc}`, '_blank');

If I run this code, a new window flashes on my screen for one frame before immediately closing. No error raised.

What am I doing incorrectly?

Getting more info about showAlert

I run into some tutorial video, but the problem is they dont explain what thus the function do, can I ask about this code or can explain what thus the code thus

function showAlert(message, className) {
    const div = document.createElement("div");
    div.className = `alert alert-${className}`;
    div.appendChild(document.createTextNode(message));
    const container = document.querySelector(".container");
    const main = document.querySelector(".main");
    container.insertBefore(div, main);

    setTimeout(() => document.querySelector(".alert").remove(), 3000);

}

Im still learning JavaScript, thank you

When I compile my short and simple C code I get “stack smashing detected”, while the same code in JavaScript runs fine, why is that?

This is part of a bigger project, but I isolated the culprit for the error as being this specific snippet and adapted it so it would run by itself (including having the value for number predefined).

#include <stdio.h>

int main() {
    unsigned number = 4;
    int array[] = {};
    for (int j = 0; j < number; j++) {
        for (int i = number; i > j; i--) {
            array[j] = i;
        }
        printf("%d ", array[j]);
    }
    return 0;
}

I’m just starting to learn C, so to check if it was a problem with the code itself, and not specific to C, so I adapted it into JavaScript:

var number = 4;
var array = [];
for (var j = 0; j < number; j++){
    for (var i = number; i > j; i--){
            array[j] = i;
        }
        console.log(array[j]);
    }

It ran and gave me the result I expected. What’s the problem with the C code that’s making me get the error?
I tried running the C code, expecting to get the numbers 1, 2, 3 and 4 printed.
I got a “stack smashing detected” error message instead.

Want form not to submit when confirm command on submit button returns false

I have a simple form. When the form’s submit button is pressed, I want a JS confirm statement to capture if the user really wants to submit the form. The dialog comes up. confirm() does return false if Cancel is pressed in the confirm dialog, but the form is still submitted. The other buttons can submit the form. What am I doing wrong?

<!DOCTYPE html>
<html>
<head>
<style>
.bg2 {background-color: #E1EBF2;}
html, body {
  color: #536482;
  background-color: #F5F7FA;
  label: font-weight: 800;
}
</style>
<script>
function confirm_check() {
    return confirm('Does this post conform to the board rules? If unfamiliar with the board rules, click Cancel then read the Board rules on the navigation bar. If it complies, submit the form again and select OK.')
}
</script>
</head>
<body>
<title>Posting form</title>
<h1>Posting form</h1>
<div class="bg2">
<form action="./thanks.html" method="get">

<div>

<dl>
<dt><label for="subject">Subject:</label></dt>
<dd><input type="text" name="subject" id="subject" size="45" maxlength="120" tabindex="2" value="" class="inputbox autowidth" /></dd>
</dl>
</div>

<div>
<textarea name="message" id="message" rows="15" cols="76" tabindex="4" onselect="storeCaret(this);" onclick="storeCaret(this);" onkeyup="storeCaret(this);" onfocus="initInsertions();" class="inputbox" style="position: relative;">
</textarea>
</div>
<input type="submit" accesskey="k" tabindex="7" name="save" value="Save draft" class="button2">&nbsp;
<input type="submit" tabindex="5" name="preview" value="Preview" class="button1">&nbsp;
<input type="submit" accesskey="s" tabindex="6" name="post" onclick="confirm_check();" value="Submit" class="button1 default-submit-action">&nbsp;
        
</form>

</body>
</html>

buttons on User list. update and delete button on Android Studio software

I wanted to put Delete button on a specifc user on the user list but i keep getting red lines. And i want to put update button to update the user on the user list. How do i do it?

here is the file: https://drive.google.com/drive/folders/1JYNScWAROzo3QXYFMKVW5zrg4oX7T2dG?usp=sharing

everything but idk if I did it right I keep getting red lines. I was expecting to have a delete button and update button on my userlist