While uploading image files to cloudinary I am getting this error

enter image description here

I don’t know the issue and getting this error from no where while uploading files from server to cloudinary

tell me what could possibly throw this error

I have a upload function that returns and resolves promise to upload and I got this error

route handler

this is my express route handler

const uploadMedia = asyncHandler(async (req, res) => {
  const { media } = req.body;

  let results;

  if (!media) return sendErrorResponse({ res, statusCode: 400 });

  results = await uploadFiles(media, { folder: "instagram_clone" });

  sendSuccessResponse({ res, data: { results } });
});

uploader function

that i used to upload a function

const cloudinary = require("cloudinary").v2;
const async = require("async");

const uploadFile = (file, options) => {
  return new Promise((resolve, reject) => {
    cloudinary.uploader.upload(file, options, (error, result) => {
      if (error) {
        reject(error);
      } else {
        resolve(result);
      }
    });
  });
};

const uploadFiles = async (media, options) => {
  try {
    const uploadTasks = media.map((mediaFile, index) => {
      return (callback) => {
        uploadFile(mediaFile, options)
          .then((result) =>
            callback(null, {
              publicId: result.public_id,
              secureUrl: result.secure_url,
              type: result.resource_type,
              index,
            })
          )
          .catch((error) => callback(error));
      };
    });

    const results = await new Promise((resolve, reject) => {
      async.parallel(uploadTasks, (error, results) => {
        if (error) {
          reject(error);
        } else {
          resolve(results);
        }
      });
    });
    return results;
  } catch (error) {
    throw error;
  }
};

I keep having issues with setting multiple layouts in Next.js 13

enter image description here

The current folder structure is like this:

I want to use a different layout only on the register page.

According to the official document, if you want to apply different multiple layouts, you need to create layout.tsx for each page.

So I’m trying to apply it like that

You are mounting a new body component when a previous one has not first unmounted. It is an error to render more than one body component at a time and attributes and children of these components will likely fail in unpredictable ways. Please only render a single instance of and if you need to mount a new one, ensure any previous ones have unmounted first.
at body

with this error

Hydration failed because the initial UI does not match what was rendered on the server.

This error appears.

After searching, it was said that the body and html should not overlap, so I changed the code in the layout.tsx folder in the register folder like this

import "../globals.css";

import ContentCard from "@/components/Card/ContentCard";

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return <ContentCard>{children}</ContentCard>;
}

This brings up the header component in the main layout.tsx.

It wasn’t even loaded from register layout.tsx.

How should I solve it?

Looking at the official documentation, no matter how much I change these settings, it doesn’t apply. help..

How can I learn Web Development and from where? [closed]

Hello Guys, I want to start web development.But i have no idea from where should i start. I want to know from which websites or youtube channels should i learn this. I decided to take a course from Udemy but i read the reviews that the course is outdated. So please tell me from where i can get the resources, Any good websites or channels or anything else(up to date) so that i can start learning it.Please guide me, I’ll be thankful. Happy Coding 🙂

I tried to buy a course from Udemy but that courses are outdated, so i want to know from where can i start learning it.

Styling select field and options

I have a multi select field with a bunch of options that i want to display as small blocks rather than having a long list of items. I can do this by setting the “option” to “display: inline-block” however i get a problem where the options dont go into a second line when reaching the container border but get hidden behind the container.

enter image description here

As you can see here the last item us cut off and all following items are not visible.

.column-select {
    width: 100%;
}
.column-select option {
    display: inline-block;
    padding: 5px 10px;
    border-radius: 5px;
    background: #2b3035;
    color: #FFFFFF;
    margin: 5px;
    outline: none;
}

Is there any way to have the options pass into the second line instead of going behind the container?

How to get actual height of element?

There are elements with fixed height. I need to insert new element inside their and update fixed height to new value via browser extension. I can’t edit source of elements in order to set auto/% css. Because they rendering by react-virtualized out of my control in external site.

How to get actual height after insert child element? In order to update fixed height to actual.

let root = document.querySelector('#root')
let firstChild = root.children[0]
console.log('firstChild height =', firstChild.style.height)
console.log('===')

firstChild.innerHTML = '<img src="https://cdn.sstatic.net/Sites/stackoverflow/Img/favicon.ico?v=ec617d715196" />'

console.log('Must be 32px')
console.log('style =', firstChild.style.height)
console.log('getBoundingClientRect =', firstChild.getBoundingClientRect().height)
console.log('offsetHeight =', firstChild.offsetHeight)
console.log('clientHeight =', firstChild.clientHeight)
<div id="root">
  <span style="height: 20px; background-color: black;">Text</span>
  <span style="height: 20px; background-color: black;">Text</span>
<div>

How to format setInterval output in JS?

I’m creating a cubing timer using JS. The way my timer works looks like this:

javascript:

// Timer
let = [milliseconds, seconds, minutes, hours] = [0, 0, 0, 0]
let timeRef = document.querySelector("#timer");
let int = null;

function StartTimer() {
    if (int !== null) {
        clearInterval(int);
    }
    int = setInterval(displayTimer, 10);
}

function ResetTimer() {
    clearInterval(int);
    [milliseconds, seconds, minutes, hours] = [0, 0, 0, 0];
    timeRef.innerHTML = '0.00';
}

function StopTimer() {
    clearInterval(int);
}

function displayTimer() {
    milliseconds += 10;

    if (milliseconds == 1000) {
        milliseconds = 0;
        seconds++;
        if (seconds == 60) {
            seconds = 60;
            minutes++;
            if (minutes == 60) {
                minutes = 0;
                hours++;
            }
        }
    }
    let h = hours < 10 ? '0' + hours : hours;
    let m = minutes < 10 ? '0' + minutes : minutes;
    let s = seconds < 10 ? '0' + seconds : seconds;
    let ms = milliseconds < 10 ? '00' + milliseconds : milliseconds < 100 ? '0' + milliseconds : milliseconds;
    timeRef.innerHTML = `${s}.${ms}`
}

// Running Timer by pressing Space bar
let state = 'stopped';

const transitions = {
  waiting: state => ResetTimer(),
  started: state => StartTimer(),
  stopped: state => StopTimer(),
};

document.addEventListener('keydown', changeState);
document.addEventListener('keyup', changeState);

function changeState({code, repeat, type: action}){

  if(code !== 'Space' || repeat){
    return;
  }
  
  // this allows to have more event types and states in the future without cluttering
  const actions = {
    keydown: () => state === 'stopped' ? 'waiting' : 'stopped',
    keyup: () => state === 'stopped' ? state : 'started',
  };
   
  const next = actions[action]();
  next === state || transitions[state = next](state);
  
}

html:

<body>
    <div class="scramble-bar">{{scramble}}</div>
    <div id="time">
        <div id="timer">
            0.00
        </div>
    </div>
    <script src="js/main.js"></script>
</body>

It’s a solution from internet. Now I want to format output of setInterval from looking like this: 01.230 to this: 1.23. I want to remove zeros from both sides. Zero in the end doesn’t even change, it always stays zero. At the start it looks like in html 0.00. but when it starts, it becomes 00.000. I’ve already changed something in Timer, so don’t get confused if something looks illogical.

And one more problem is displaying minutes and hours. Actually, I would like to display them, but only if it gets to the point of displaying them. If seconds > 60, I want to add minutes to the timer. If minutes > 60, I want to add hours. Currently, when it comes to 60 seconds, it starts again from 00.000. (59.990 -> 00.000).

How can I do it?

How do i take user input from keyboard in my crossword game instead of the popup with the alphabets

function initvkeyboard(){
                var chars = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",]
                for(var i = 0; i < chars.length; i++){
                    $("#kbtnlist").append("<div class='kbtn' onclick=typechar('"+chars[i]+"')>"+chars[i]+"</div>")
                }
            }

I am making a crossword game this is a javascript function which accepts the input from the popup and displays it. Instead of it i want to give keyboard access to this game how do i make this function to get user input instead from my keyboard and not print the popup

function initvkeyboard(){
    Window.location = ""+ input.value;

    for(var i = 0; i<input; i++){
        $("#kbtnlist").append("<div class='kbtn' onclick=typechar('"+chars[i]+"')>"+chars[i]+"</div>")
    }
}

this is what i am trying to do i want to give keyboard access to my crossword game and not give popup

addEventListener in Javascript not working on first click [duplicate]

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Event Handler</title>
</head>

<style>
    P{
        opacity: 1;
        transition: all .5s;
    }
</style>

<body>
    <div class="container">
        <h1>Welcome</h1>
        <p id="para">Lorem ipsum dolor sit amet consectetur adipisicing elit.</p>
        <button id="button">Toggle Hide</button>
    </div>

    <script>
        let para = document.getElementById("para");
        let button = document.getElementById("button");

        button.addEventListener("click", function hide(){
            para.style.opacity == "0" ? para.style.opacity = "1" : para.style.opacity = "0";
        });
    </script>
</body>
</html>

The above code is a simple html code with a Heading, “Welcome”, a paragraph and a button.
Whenever I click the button I want to toggle the opacity of the paragraph.
Inside the “script” tag I am using this code to achieve this:

button.addEventListener("click", function hide(){
   para.style.opacity == "0" ? para.style.opacity = "1" : para.style.opacity = "0";
});

Now it works completely fine. However when I write it this way it doesn’t work on first click. I have to click twice to make this work.

button.addEventListener("click", function hide(){
    para.style.opacity == "1" ? para.style.opacity = "0" : para.style.opacity = "1";
});

Any idea why this happens?

How do I avoid repetition when concatenating to one of three strings?

I have the following ugly pattern:

// defined once
const articleComponents = {
    header: "",
    body: "",
    footer: ""
};

// ...

function appendSuffix(suffix)
{
    if (/* target header */) {
        if (!articleComponents.header.endsWith(" ")) {
            articleComponents.header += " ";
        }
        articleComponents.header += suffix;
    }
    else if (/* target body */) {
        if (!articleComponents.body.endsWith(" ")) {
            articleComponents.body += " ";
        }
        articleComponents.body += suffix;
    }
    else if (/* target footer */) {
        if (!articleComponents.footer.endsWith(" ")) {
            articleComponents.footer += " ";
        }
        articleComponents.footer += suffix;
    }
}

This is obviously redundant but due to the nature of the += operator for strings, and strings being immutable, it’s hard to simplify this.

Goals

  • Ideally, in each if-statement, the articleComponents.xyz expression should appear exactly once. In my actual code, these expression are even longer, and it’s even more painful to repeat them.
  • articleComponents should not be modified; I rely on its format
    • additional helper objects inside appendSuffix are okay

Javascript onclick only working before page fully loaded

So I have a function where if user click on checkbox, some input will be unhide, like below

function myFunc() {
        var datInput = document.getElementById("dat");
        var everydayCheckbox = document.getElementById("everyday");

        if (everydayCheckbox.checked) {
            datInput.style.display = "block";
        } else {
            datInput.style.display = "none";
        }
    }
<div class="col-md-6 col-sm-6 col-xs-12">
                                    <input class="form-control" type="text" name="dateranges" id="dat" style="display:none" value="$pre" />
                                    <input type="text" name="daterange" id="daterange" class="form-control date" placeholder="Choose multiple dates">
                                    <p style="color: white">
                                        <input type="checkbox" name="everyday" id="everyday" onclick="myFunc()" value="everyday" class="flat" /> Everyday
                                    </p>
                                </div>

The problem is, the above code only working if page not fully loaded, my first thought is that it is due to package conflict but i cant figure out which package that cause this is problem.

Here is the package i used which is located in same html with above function

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

<script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.10.0/js/bootstrap-datepicker.min.js" integrity="sha512-LsnSViqQyaXpD4mBBdRYeP6sRwJiJveh2ZIbW41EBrNmKxgr/LFZIiWT6yr+nycvhvauz8c2nYMhrP80YhG7Cw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
<script type="text/javascript">
    function myFunction() {
        document.getElementById("daterange").disabled = true;
    };
    function myFunc() {
        var datInput = document.getElementById("dat");
        var everydayCheckbox = document.getElementById("everyday");

        if (everydayCheckbox.checked) {
            datInput.style.display = "block";
        } else {
            datInput.style.display = "none";
        }
    }

    
</script>

and here is the package i used from html which above function extended from, which located at bottom of html

<!-- jQuery -->
<script src="{{asset('vendors/jquery/dist/jquery.min.js')}}"></script>
<!-- Bootstrap -->
<script src="{{asset('vendors/bootstrap/dist/js/bootstrap.min.js')}}"></script>
<!-- FastClick -->
<script src="{{asset('vendors/fastclick/lib/fastclick.js')}}"></script>
<!-- NProgress -->
<script src="{{asset('vendors/nprogress/nprogress.js')}}"></script>
<!-- iCheck -->
<script src="{{asset('vendors/iCheck/icheck.min.js')}}"></script>
<!-- Datatables -->
<script src="{{asset('vendors/datatables.net/js/jquery.dataTables.min.js')}}"></script>
<script src="{{asset('vendors/datatables.net-bs/js/dataTables.bootstrap.min.js')}}"></script>
<script src="{{asset('vendors/datatables.net-buttons/js/dataTables.buttons.min.js')}}"></script>
<script src="{{asset('vendors/datatables.net-buttons-bs/js/buttons.bootstrap.min.js')}}"></script>
<script src="{{asset('vendors/datatables.net-buttons/js/buttons.flash.min.js')}}"></script>
<script src="{{asset('vendors/datatables.net-buttons/js/buttons.html5.min.js')}}"></script>
<script src="{{asset('vendors/datatables.net-buttons/js/buttons.print.js')}}"></script>
<script src="{{asset('vendors/datatables.net-fixedheader/js/dataTables.fixedHeader.min.js')}}"></script>
<script src="{{asset('vendors/datatables.net-keytable/js/dataTables.keyTable.min.js')}}"></script>
<script src="{{asset('vendors/datatables.net-responsive/js/dataTables.responsive.min.js')}}"></script>
<script src="{{asset('vendors/datatables.net-responsive-bs/js/responsive.bootstrap.js')}}"></script>
<script src="{{asset('vendors/datatables.net-scroller/js/dataTables.scroller.min.js')}}"></script>
<script src="{{asset('vendors/jszip/dist/jszip.min.js')}}"></script>
<script src="{{asset('vendors/pdfmake/build/pdfmake.min.js')}}"></script>
<script src="{{asset('vendors/pdfmake/build/vfs_fonts.js')}}"></script>
<!-- jQuery custom content scroller -->
<script src="{{asset('vendors/malihu-custom-scrollbar-plugin/jquery.mCustomScrollbar.concat.min.js')}}"></script>
<!-- Switchery -->
<script src="{{asset('vendors/switchery/dist/switchery.min.js')}}"></script>

<!-- jQuery Smart Wizard -->
<script src="{{asset('vendors/jQuery-Smart-Wizard/js/jquery.smartWizard.js')}}"></script>

<!-- Custom Theme Scripts -->
<script src="{{asset('build/js/custom.js')}}"></script>

Why does the arrow not draw in my React code?

My code contains a toolbar, it’s about a dropdown. When pass is selected it should enable the ability to create an arrow by drag and dropping on the canvas. I use JS React with useState and useEffect. Here’s the important snippets:

    const handleFieldMouseDown = (event) => {
      const rect = canvasRef.current.getBoundingClientRect();
      const x = event.clientX - rect.left;
      const y = event.clientY - rect.top;
      if (addingArrow) {
        setArrowStartPoint({ x, y });
      } else if (addingArea) {
        setAreaStart({ x, y });
      // Handle other elements as usual
    };
  }
  
  const handleFieldMouseMove = useCallback((event) => {
    const rect = canvasRef.current.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;
    if (addingArrow && arrowStartPoint) {
     drawArrow(arrowStartPoint, { x, y });
    } else if (addingArea && areaStart) {
      setPreviewArea({
        x: Math.min(areaStart.x, x),
        y: Math.min(areaStart.y, y),
        width: Math.abs(x - areaStart.x),
        height: Math.abs(y - areaStart.y)
      });
    }
  
    // Call drawArrow to update the arrow drawing
    
  }, [arrowStartPoint, addingArrow, addingArea, areaStart]);

  const handleFieldMouseUp = (event) => {
    const rect = canvasRef.current.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;
    if (addingArrow) {
      
      setArrowEndPoint({ x, y });
      const newArrow = {
        start: arrowStartPoint,
        end: arrowEndPoint,
        type: arrowType,
      };
      drawArrow(arrowStartPoint, arrowEndPoint);
      setArrows((arrows) => [...arrows, newArrow]);
      setArrowStartPoint(null);
      setArrowEndPoint(null);
      setIsDrawingArrow(false);

    }else if (addingArea && areaStart) {
      const createdArea = {
        x: Math.min(areaStart.x, x),
        y: Math.min(areaStart.y, y),
        width: Math.abs(x - areaStart.x),
        height: Math.abs(y - areaStart.y),
      };
      setAreas((areas) => [...areas, createdArea]);
      setAreaStart(null);
      setPreviewArea(null);
      setAddingGoal(false);
      setAddingCone(false);
      setAddingNumber(false);
      setAddingBall(false);
      setAddingPlayer(false);
      setAddingArrow(false);
    }
  };


   const Arrow = ({ start, end }) => {
      const canvasRef = useRef(null);
    
      useEffect(() => {
        const canvas = canvasRef.current;
        const ctx = canvas.getContext('2d');
    
        const drawArrow = (start, end, ctx) => {
          // Check if arrowStartPoint is not null
          
           // decide which type of arrow to draw
            switch (arrowType) {
              case 'pass':
                ctx.beginPath();
                ctx.moveTo(start.x, start.y);
                ctx.lineTo(end.x, end.y);
                ctx.strokeStyle = 'black'; // Arrow color
                ctx.lineWidth = 2;
                ctx.stroke();
                break;
              case 'run':
                // draw a dashed arrow
                break;
              case 'dribbling':
                // draw a wavy arrow
                break;
              case 'highball':
                // draw a slightly curved arrow
                break;
              default:
                break;
            }
          
        };
    
        drawArrow();
    
      }, [start, end]);
    
      return <canvas ref={canvasRef} />;
    };
    useEffect(drawArrow, [arrowType]);
    useEffect(() => {
      if (goalImage === null) {
        // If goalImage is not yet loaded, don't attempt to draw it
        return;
      }

      const canvas = canvasRef.current;
      const ctx = canvas.getContext('2d');
    
      // Clear the field
      ctx.clearRect(0, 0, canvas.width, canvas.height);
    
      // Redraw the field
      drawField();
    
      // Draw each player
      for (const player of players) {
        ctx.beginPath();
        ctx.arc(player.x, player.y, 10 /* player size */, 0, Math.PI * 2);
        ctx.fillStyle = 'blue'; // player color
        ctx.fill();
    
        // Draw player number
        ctx.fillStyle = 'white'; // text color
        ctx.fillText(player.id, player.x-3, player.y+3); // adjust these values as needed
      }
    
  // Create a new image object and set its source
  const ballImg = new Image();
  ballImg.src = ballImage;

  // Draw each ball when the image has loaded
  ballImg.onload = () => {
    for (const ball of balls) {
      // Draw the image at the ball's position
      ctx.drawImage(ballImg, ball.x, ball.y, 16, 16); // Adjust the size (14, 14 here) as needed
    }
  };
    
// Draw arrows
for (const arrow of arrows) {
  Arrow(arrow.start, arrow.end, ctx);
}

      // Draw each area
      for (const area of areas) {
        ctx.beginPath();
        ctx.rect(area.x, area.y, area.width, area.height);
        ctx.fillStyle = 'rgba(0, 0, 255, 0.5)';
        ctx.fill();
      }

    }, [players, balls, mousePosition, areas, arrows]);

I want that the arrow appears when dragging and dropping. The Arrow shows on Mouse down but as soon as I lift my Mouse the arrow disappears.

how to add style class to notion edit page

I am trying to add some class style to notion edit page. But it seems that some kind of technologies(flutter-web?) notion used prevent that happens. the dom tree is rendered by a controlled mutation state.

Any ideas that we can inject class to notion element?

below is the console warning when add class to notion page element:

4536-03e8b1b293f00187a4d8.js:1   NOTION WARNING  Reverting mutation of attribute class from "notion-selectable notion-text-block" -> "notion-selectable notion-text-block" in component undefined MutationRecord

Is there a library or technique to support query parameters in getStaticProps in Next.js?

I’m using Next.js for my application and I have a page where I need to fetch data at build time using the getStaticProps function. I want to be able to handle query parameters in this function, but by default, it doesn’t provide direct support for query parameters.

Is there a recommended library or technique that I can use to handle query parameters within the getStaticProps function in Next.js?

I’ve come across the query-string library, but I’m not sure if it’s the best approach or if there are any other alternatives available. I would appreciate any suggestions or examples that can help me achieve this functionality.

Thank you in advance!

To specify font size in pixels (px) using the Quill library in a Vue 3 environment, for example, (2px, 4px, 8px)

I’m having difficulty customizing the font size in pixels (px) using the Quill library. Below is the HTML and JavaScript code

    <template>
    <QuillEditor
    ref="myQuillEditor"
    @blur="onEditorBlur"
    @focus="onEditorFocus"
    @ready="onEditorReady"
    @text-change="onEditorChange"
    class="form-control"
    style="height: 800px;"
    :toolbar="toolbar"
    required
    /></template>


    import { QuillEditor } from '@vueup/vue-quill'
    import '@vueup/vue-quill/dist/vue-quill.snow.css';
    import Quill from 'quill';
    let SizeStyle = Quill.import('attributors/style/size');
    SizeStyle.whitelist = ['10px', '12px', '14px', '16px', '18px', '20px', '24px', '30px',   '32px','36px','48px','60px','72px','96px'];
    Quill.register(SizeStyle, true);
    export default {
    components: {
    QuillEditor
    },
    data() {
    return {toolbar: [
        ['bold', 'italic', 'underline', 'strike'],
        [{ 'list': 'ordered' }, { 'list': 'bullet' }],
        [{ 'background': [] }, { 'color': [] }],
        [{ 'font': [] }],
        [{ 'script': 'sub' }, { 'script': 'super' }],
        [{ 'indent': '-1' }, { 'indent': '+1' }],
        [{ 'direction': 'rtl' }],
        [{ 'size': [false, '10px', '12px', '14px', '16px', '18px', '20px', '24px',       '30px','32px','36px','48px','60px','72px','96px'] }],
        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
        [{ 'align': [] }],
        ['clean'],
        ['link', 'image', 'video']    
    ]
    }
    },
    mounted() {
    this.$refs.myQuillEditor.quill.on('text-change', () => {
      let range = this.$refs.myQuillEditor.quill.getSelection();
      if (range) {
        let format = this.$refs.myQuillEditor.quill.getFormat(range);
        let sizeDropdown = document.querySelector('.ql-size .ql-picker-label');
        if (sizeDropdown) {
          sizeDropdown.textContent = format.size || 'Normal';
        }
      }
    });
    },
    };

enter image description here
I made an attempt, and the result is as follows. However, when selecting the font size, the text only appears as ‘Normal.