Why does function “checkpassword” makes nothing on click?

I have a problem guys. As a beginner, I am trying to check the length of password and return the result, but it doesn’t work. after clicking button, it does nothing. What am I doing wrong?

<!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">
    <title>Document</title>
</head>
<script>
function checkpassword(){
    var pas=document.getElementByName(passcode).value;
    var x=pas.length;
    if(x<8){
        document.getElementById(message).innerHTML="Error 404!";
   }
   else{
    document.getElementById(message).innerHTML="It's acceptable"
   }
}
</script>
<body>
   
    <input type="password" name="passcode" placeholder="Enter password to check">
    <input type="submit" value="submit" onclick="checkpassword()">

<p id="message"></p>
</body>
</html>

Firefox, double click on empty line, contenteditable div

I’m working on a html editor (contenteditable div) and came across this issue:
Double (or triple) clicking on empty lines like <div><span><br></span></div> behaves differently in safari/chrome and firefox. In safari and chrome the empty lines get highlighted and selected. this is what I expect. but in firefox the caret dissappears and range.startcontainer is the container div (the contenteditable) instead of the empty line. firefox doesn’t highlight the span/empty line, I’m OK with that, but I would like to change the behaviour to act like a single click (caret stays in place and range.startcontainer is <span>.

You may ask what I want to to with empty lines. There’s styling options (change to list/bullet points for example) that should be accessible even when double clicking on the empty line.

I’ve tried to solve this by saving the start node on the first click and then restore it when the users clicks 2 or more times and bring the caret back by collapsing the range. but I guess there’s a better/cleaner solution since it’s only needed for ff.

any ideas appreciated!

How to change 1 CSS line after a new page within my website opens after clicking a link?

I would like to change 1 CSS line when you click a link in the website and a new page opens. I want to create a ‘order form’ link on a page, which goes to another page and then the order form should open up by changing the display to block of the div that contains the order form.

Is this possible, perhaps with Javascript? I have too little knowledge of Javascript therefore I am asking it here.

Thank you.

Best,
Silvan

react component is not re-rendering after state is changed

export default function RenderPages({storage, setStorage, state, setState}){
  const [pageNum, setPageNum]= useState(0)

  const currentFileId=state.currentFileId
  const currentFolderId= state.currentFolderId

  return (
    <div className="writing">
      {storage[currentFolderId][currentFileId].content.map((page, index)=>
      <div className='textarea'>
        <textarea placeholder='write here' defaultValue={page} id={index} onChange={(e)=>onChange(e, index)} rows={rows} cols={cols}></textarea>
      </div>)}
    </div>
  )
}

I expected that jsx would return renewal result after the state is changed, but it didn’t. I checked that currentFileId and currentFolderId value were changed. why this happen?

Django React Integration Error manifest.json not found 404

I integrated my react project successfully with Django. But every time I run the Django server, I get a manifest.json not found error.

Also, when I ever I make any changes to the react app, it’s not live to update when I run the Django server. I have to call npm run build every time to update the Django website.

Is there a solution for this such that I do not get the manifest.json not found error and also the website server live updates as I update the front end react code.

index.html

<head>
    <meta charset="utf-8" />
    <link rel="icon" href="/favicon.ico" />
    <meta name="viewport" content="width=device-width,initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta name="description" content="Web site created using create-react-app" />
    <link rel="apple-touch-icon" href="/logo192.png" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
        integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <script src="https://unpkg.com/react/umd/react.production.min.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom/umd/react-dom.production.min.js" crossorigin></script>
    <script src="https://unpkg.com/react-bootstrap@next/dist/react-bootstrap.min.js" crossorigin></script>
    <script>var Alert = ReactBootstrap.Alert</script>
    <title>React App</title>
    <link href="/static/css/2.e58a5209.chunk.css" rel="stylesheet">
    <link href="/static/css/main.f38b3f41.chunk.css" rel="stylesheet">
</head>

urls.py
path('', TemplateView.as_view(template_name='index.html')),

Directory Structure:
enter image description here

How to get these input values in an HTML table using querySelector?

I’m trying to get the other input values, but they’re always blank. Here’s the code I got:

function savePo() {
  let table = document.getElementById("dtable");
  let [, ...tr] = table.querySelectorAll("tr");
  let tableData = [...tr].map(r => {
    let td = r.querySelectorAll("td");
    return [...td].map((c, j) => j == 9 ? c.querySelectorAll('input[type="checkbox"]')[0].checked : j === 8 ? c.innerText : c.querySelectorAll('input').value)
  });
  console.log('Table Data: ' + tableData);
}

This is the Fiddle in case you feel like putting a finger on the issue.

Huge thank you!

addwatermarkfromtext() inacrobat not looping

ok, so I took bits of codes from the internet and managed to get some stuff to work but it only works on the first page and I would like that to be done on every page. I’m sure it’s a noob mistake but just haven’t found the answer.

The idea is that it writes the filename with a barcode font and the line after the page number, I put it in two different loops to have two different fonts (hoping that it makes sense).

    for (var p = 0; p < this.pageNum; p++);
var cMyText = event.target.documentFileName.replace(/.pdf$/i,"");
event.target.addWatermarkFromText({
    cText: cMyText,
    nFontSize:10,
    aColor: color.black,
    cFont: "LibreBarcode39Text-Regular",
    nHorizAlign:app.constants.align.left,
    nHorizValue: 36,
    nVertAlign:app.constants.align.top,
    nVertValue: -3,
    nStart: p
})
for (var s=0; s<this.pageNum; s++);
var cMyText = "nPage " + (s+1) + " of " + numPages;
event.target.addWatermarkFromText({
    cText: cMyText,
    nFontSize:8,
    aColor: color.black,
    nHorizAlign:app.constants.align.left,
    nHorizValue: 36,
    nVertAlign:app.constants.align.top,
    nVertValue: -10,
    nStart: s

})

Edit the Promise API manually so that instead of throwing an error and terminating the program, it will just log it somewhere. Maybe Promise.prototype

I am using discord.js v14 and everything in their library is just an API call that returns a Promise. The issue is sometimes that promise is rejected which is fine but I don’t want to have to do .catch on EVERY single promise. Is there a better solution to the one I am proposing?

If this is possible I’m assuming it would have something to do with Promise.prototype or something like that.

Example:

user.roles.remove("role_id").catch(e => console.error("Unable to remove user role, most likely a permmissions issue")
channel.send("Removed <user_id>'s role").catch(e => console.error("Unable to send message most likely a permissions issue"))

I just want to be able to do this

user.roles.remove("role_id")
channel.send("Removed <user_id>'s role")

and have it not terminate my program.

Are there any major differences between webgl and webgl2 APIs?

I’m currently learning WebGL and I found out that there are actually 2 variants of this api -> webgl and webgl2. So I would say that webgl2 is a newer version of the api, therefore it would be better to start with it. But I’m a bit confused now since most of the tutorials and documentations I’ve seen still uses webgl.

According to what I found there is not so much difference between them and that webgl2 has less support among browsers.

So I would be glad if someone could briefly explain what the main difference between them is and if it would be a problem to switch from one to the other.

Thanks in advance.

textarea text erases when using innerHTML

I have this function which uses innerHTML to insert html into a div:

function displayInputIntro() {
                var submitbutton = document.getElementById('submitbutton')
                var intro = document.getElementById('Intro')
                var introNewSection = document.getElementById('intro-row')
                var uniqueID = ""
                var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                var length = 7
                for (var i = length; i > 0; --i) uniqueID += chars[Math.floor(Math.random() * chars.length)];
                uniqueID = uniqueID
                introNewSection.innerHTML += '<div class="col-lg-5 mb-lg-0 mb-4" id=' + uniqueID + '><div class="card z-index-2"> <div class="card-body p-3" style="margin-top: -20px;"> <h6 class="ms-2 mt-4 mb-0">Intro <a href="#" onclick="javascript:deleteInput(' + uniqueID + ')" style="text-align: right; float: right; margin-right: 12px;"><i class="fa fa-times" style="color: gray;"></i></a></h6> <p class="text-sm ms-2">Section 1</p> <div class="container border-radius-lg"> <div class="row"> <textarea type="text" class="form-control" name="intro" placeholder="Enter your current Intro" id="textvalue" style="height: 100px;" required></textarea> </div> </div> </div> </div></div>'
                submitbutton.style.display = ''
             }

and then my html:

<div class="row mt-4" id="intro-row"></div>

however, as you can see in the introNewSection.innerHTML, I have a <textarea type="text" class="form-control" name="intro" placeholder="Enter your current Intro" id="textvalue" style="height: 100px;" required></textarea>

the problem is, this function displayInputIntro() can be triggered multiple times. Every time its triggered, and there’s any text inside the textarea, it just clears it and I don’t know why. how can I fix this?

How to automatically scroll only inside tag in Vue.js

I am creating frontend using vue 2.

There I have a chat inside tag and have done auto-scroll to the end of chat on updated().

Unfortunately, it scrolls not only inside but also the whole page to this moment. How to override it? (show the whole code for you to recognise that it’s impossible to have a ref on last message but not div – loaded_messages is an array from API and dialogs – from WebSocket)

<template>
          <div class="box col-md-8" >
            <div id="chat-messages" class="chat__order" style=" 
                border: 1px solid grey; overflow-y: scroll;">

                    <ol class="chat">

                  <div v-for="m in loaded_messages[0]"
                        direction="column"
                        justify-content="start"
                        align-items="end"
                        margin-left=2px
                        :key="m.id">
                   <li class="self" v-if="m.username == user"> 
                    <b-avatar :src="m.get_message_info.get_thumbnail"></b-avatar>
                      <div class="msg">

                      <p>{{m.content}} </p>
                      <time>{{m.get_datetime}}</time>

                      </div>
                    </li>

                   <li class="other" v-else> 
                    <b-avatar :src="m.get_message_info.get_thumbnail"></b-avatar>
                        <div class="msg">
                        <p>{{m.content}}</p>
                        <time>{{m.get_datetime}}</time>
                        </div>
                  </li>

                  </div>

                <div  v-for="dialog in dialogs"
                        direction="column"
                        justify-content="start"
                        align-items="end"
                        :key="dialog.id">

                   <li class="self" v-if="dialog.username == user"> 
                    <b-avatar></b-avatar>
                      <div class="msg">
                              <p>{{dialog.message}} </p>
                              <time>{{dialog.datetime}}</time>
                      </div>
                    </li>

                   <li v-else> 
                    <b-avatar></b-avatar>
                    <div class="msg">
                            <p>  {{dialog.message}} </p>
                    </div>
                  </li>

                </div> 

                  <div ref="lastMessage"></div>
              </ol>
          </div>
        </div> 

</template>

<script>

        methods: { 

// scroll to the last message

      scrollToElement() {
      const [el] =  this.$refs.lastMessage;
      if (el) {
        el.scrollIntoView({ behavior: "smooth" });
      }
    },

   },

    updated() {
      this.scrollToElement();
    },

</script>

Time Complexity of permutation function Should be T((n!)^2)?

Problem : Given an array of nums of distinct integers, return all the possible permutations.

For example, [1,2,3] have the following permutations:
[ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ].

This is my javascript implementation, similar to the standard solution for this problem.
I found many places saying this time complexity is to be T(n*n!). But as I understand it should be T((n!)^2). Again I could be wrong !!.

JavaScript Solution

var permute = function(nums) {
    if(nums.length === 0) return [];
    if(nums.length ===1){
        return [[...nums]]; 
    }
    
    let results = [];
    const len = nums.length;
    for(let i=0; i<len; i++){
        // eg: [1,2,3,4]
        const temp = nums[i]; 
        nums[i] = nums[len-1]; 
        nums[len-1] = temp; // [4,2,3,1]
        const n = nums.pop(); // [4,2,3]
        const prems = permute(nums);
        prems.forEach(perm => perm.push(n));
        results = results.concat(prems); 
        nums.push(nums[i]) // [4,2,3,4]
        nums[i] = temp; // [1,2,3,4]
        
    }
    
    return results;
    
 
};

Here is How I got the answer as T((n!)^2)

so for the outer,

1st itteration
  • Each iteration will do a recursive call with n-1 items array
  • Then the results, which will be all permutations with n-1 items will be size (n-1)!
  • So we have to loop through (n-1)! items to append the popped element.
For n itterations

So for the first recursive call, this will happen n times (the outer loop is going from 0 to n)

So, for the first recursive call T-(n*(n-1)!)

Since the recursion tree size is n!
the final time complexity should be – T(n!n(n-1)!) = T((n!)^2).

Am I missing something here ??

Using hex string as Map key best performance way

I am getting MongoDB ObjectIds, which are 12 bytes and their hex string looks like this: 62d34be4f8cd489f6d5b8e0e.

I want to use the object id as a map key like this:

new Map().set(ObjectId('62d34be4f8cd489f6d5b8e0e'),"value")

That doesn’t really work because each ObjectId object is unique so two with the same id are not equal objects.

There are a few ways I can think of:

  • Use the hex string as map key:
new Map().set("62d34be4f8cd489f6d5b8e0e", "value")
  • Use a buffer / Uint8Array, and use some special Map which works with arrays as keys
new Map().set(Buffer.from("62d34be4f8cd489f6d5b8e0e", "hex"), "value")
  • Turn the buffer into a 12 byte string which looks like b�K���H�m[�x0E
new Map().set(Buffer.from("62d34be4f8cd489f6d5b8e0e", "hex").toString(), "value")
  • Turn the buffer into a number (this turns a 12 byte buffer into a 16 byte number so it seems a little wierd)
new Map().set(Buffer.from("62d34be4f8cd489f6d5b8e0e", 'hex').readInt16BE(), "value")

Which method has the best performance?

connect contact form to firebase-database using javascript i need someone to tell me exactly what to do step by step

I have this code below in javascript I want to make the contact form stored in firebase.

import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.9.0/firebase-app.js'

const firebaseConfig = {
  apiKey: '',

  authDomain: '',

  databaseURL: '',

  projectId: '',

  storageBucket: '',

  messagingSenderId: '',

  appId: '',
}

// Initialize Firebase

const app = initializeApp(firebaseConfig)

//reference messages collection
const messageRef = firebase.databaseURL().ref('messages')

//Listen for form submit
document.getElementById('contactForm').addEventListener('submit', submitForm)

function submitForm(e) {
  e.preventDefault()
  // Get Values
  const name = getInputVal('yourName')
  const gender = getInputVal('gender')
  const message = getInputVal('input-area2')

  saveMessage(name, gender, message)
}
// function to get form values
function getInputVal(id) {
  return document.getElementById(id).value
}

// save the message to firebase

function saveMessage(name, gender, message) {
  const newMessageRef = messageRef.push()
  newMessageRef.set({
    name: name,
    gender: gender,
    message: message,
  })
}

and here is the HTML.

<section class="row get-in-touch-row" id="contact">
      <div
        class="col-sm-12 col-md-12 col-lg-12 col-xl-12 col-xxl-12 text-center align-self-center get-in-touch-info"
      >
        <h2>get in touch</h2>
        <p>
          Lorem ipsum dolor sit amet consectetur adipisicing elit. Nesciunt
          quisquam, temporibus suscipit totam soluta tenetur beatae ea non eum!
          Quisquam!
        </p>
        <form action="" id="contactForm">
          <input
            class="input-area1"
            id="yourName"
            type="text"
            placeholder="Your Name"
            required
          />
          <input
            class="input-area1"
            id="gender"
            type="text"
            placeholder="Gender"
            required
          />
          <textarea
            name=""
            id="input-area2"
            cols="10"
            rows="10"
            placeholder="Message"
          ></textarea>
          <button type="submit">SEND MESSAGE</button>
        </form>
      </div>
    </section>

<script src="index-script.js"></script>
    <script src="index-script2.js" type="module"></script>
    <script
      src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
      crossorigin="anonymous"
    ></script>

as you can see the form is one section on my website the javascript code above goes under index-script2 the error given to me is that firebase is not defined. any help what can I do to fix it and make it work.i need someone to tell me exactly what to do.