(Firebase Firestore)TypeError: n.indexOf is not a function

I’m trying to add another field value in a document but firebase returns TypeError: n.indexOf is not a function. Here’s the code:

async function linkLCSN(cor, sn) {
  try {
    await setDoc(doc(db, "cor", cor), {
      sn: sn,
    }, {merge: true});
  } catch(e) {
    console.error(e);
  }
} 

I’ve already succeeded in doing this way but I don’t know why this time it keeps giving me this error. This is the working code:

async function submitToDatabase(name, email, cor, cs, cn, concern) {
    try {
        //Set Datas 
        await setDoc(doc(db, "cor", cor), {
        name: name,
        email: email,
        cor: cor,
        courseSection: cs,
        contactNumber: cn,
        isViewed: false,
        timestamp: serverTimestamp(),
        }, {merge: true});
        const docRef = await addDoc(collection(db, "cor", cor, "concerns"), {
        concernData: concern,
        });
        console.log("Yung betlog nasa:" + docRef.id);
        //Do page changes
        let a = document.querySelector(".concern-main-container");
        let b = document.querySelector(".concern-preview-container");
        a.style.display = "none";
        b.style.display = "block";
    } catch(e) {
        console.error(e);
        //Custom Alert
    }
}

How to use timeline_item.add content field to use a repeating image Vis.js Timeline

I have been using the timeline_item add function with content field to represent the element with a image. It works fine.

timeline_items.add({
    id                        : entity_id,
    group                     : "timeline_group_id",
    start                     : start_date,
    end                       : end_date,
    content                   : "<img src='" + element_src_link + "'></img>",
    className                 : 'timeline-imagecontainer',
});

However, although I explicitly define a className, that does not help with the style properties of the image.

I want to have a repeating background with the img inside the timeline element.

How can I achieve this ?

How to move index 0 to index 1 array in the javascript [duplicate]

I have an array that I want to find an item with an ID of 1.
Then change the index of the found item from 0 to 1.
This is not working properly. Please guide me to get the answer.

My expected output:

[
{id:2,name:"sara"},
{id:1,name:"jhon"},
{id:3,name:"James"},
]

const arr=[
{id:1,name:"jhon"},
{id:2,name:"sara"},
{id:3,name:"James"},
]

function move(arry, from, to) {
  let numberOfDeletedElm = 1;

  const elm = input.splice(from, numberOfDeletedElm)[0];

  numberOfDeletedElm = 0;

  arry.splice(to, numberOfDeletedElm, elm);
}

const findIndex =arr.findIndex((element) => element.id === 1);
const result = move(arr, findIndex, findIndex++);

console.log(result);

JS output for the get ABC function [duplicate]

I looking for this issue where I have the functions
getA - > sync fn getB - > async fn getC - > promise fn
and another fn which is combining and returning the response of all the three functions, i.e getABC fn, which should give me a result in this form.

Result should be in:-

[ result A, result B, Result C]

    function A() {
        return 'A';
    }
    
    function B(callback) {
        setTimeout(() => {
            callback('B')
        }, 10);
    }
    
    function C() {
        return Promise.resolve('C');
    }
    
    function getABC() {
        const extractData = (data) => {
            return data;
        }
        return Promise.all([A(), B(extractData), C()]);
    }

I am getting result something like this ['A', undefined, 'C]
expected => ['A', 'B', 'C']

Moving circles with pure javascript and html canvas

I am new to programming and am playing around with HTML canvas and JavaScript. I am only using vanilla JavaScript right now, and I am trying to get a circle to move and get bigger or smaller when I click some buttons.

Everything that I’ve tried to do has resulted in, for example, the more I press the move left button, the faster it goes left, and if I press the move right button while it is moving left, it just slows down until it stops. Then it goes right.

This happens with every direction and size. All of the attempts I’ve made are basically this same code in a different order, so if anyone knows how to do this, I’d appreciate it. Thx.

Ignore the file names… they are from an old project. The styling looks weird in here because I made it on a much larger screen. I’m not that good with CSS yet.

const canvas = document.getElementById("canvas1");
const ctx = canvas.getContext('2d',);
const posUp = document.getElementById("posUp");
const posDown = document.getElementById("posDown");
const posRight = document.getElementById("posRight");
const posLeft = document.getElementById("posLeft");
const radUp = document.getElementById("radUp");
const radDown = document.getElementById("radDown");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let size = 0;
let PI = Math.PI;
let posX = window.innerWidth/2;
let posY = window.innerHeight/2;
let angle = 0;
let radius = 50;



const rrgb = `rgb(${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)})`
const strokeRRGB = `rgb(${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)}, ${Math.floor(Math.random() * 255)})`


function posUpFunc() {    
    posY-= 2;
}
function posRightFunc() {
    posX+= 2;
}
function posDownFunc() {
    posY+= 2;
}
function posLeftFunc() {
    posX-= 2;
}
function radUpFunc() {
    radius++;
}
function radDownFunc() {
    radius--;
}

posUp.onclick = () => {
    console.log(posY)

    setInterval(posUpFunc, 10);
}

posRight.onclick = () => {
    console.log(posY)    
    setInterval(posRightFunc, 1);

}

posDown.onclick = () => {
    console.log(posY)
    setInterval(posDownFunc, 10);

}

posLeft.onclick = () => {
    console.log(posY)
    setInterval(posLeftFunc, 10);

}

radUp.onclick = () => {
    console.log(posY)
    setInterval(radUpFunc, 10);

}

radDown.onclick = () => {
    console.log(posY)
    setInterval(radDownFunc, 10);

}


function draw() {
    ctx.fillStyle = rrgb;
    ctx.strokeStyle = strokeRRGB;
    ctx.lineWidth = 3;
    ctx.clearRect(0,0,window.innerWidth,window.innerHeight)
    ctx.beginPath();
    ctx.arc(posX, posY, radius, 0, PI * 2);
    ctx.closePath();
    ctx.fill();
    ctx.stroke();
}    



setInterval(draw, 10)
body {
    overflow: hidden;
}


#canvas1 {
    position: absolute;
    border: 2px solid black;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;

}

button {
    height: 2.5%;
    width: 5%;
    position: absolute;
    cursor: pointer;
    z-index: 100;
}

button:hover {
    border: 1px solid black;
}

#posUp {
    left: 5%;
}

#posRight {
left: 10%;
top: 6.5%;
}

#posDown {
left: 5%;
top: 10%;
}

#posLeft {
left: 0%;
top: 6.5%;

}

#radUp {
left: 50.5%;
}

#radDown {
left: 50.5%;
top: 10%;
}

#circle-direction {
position: relative;
top: 5%;
left: 3%;
width: fit-content;
height: fit-content;
z-index: 100;

}

#circle-size {
    position: absolute;
    top: 0.9%;
    left: 50%;
    width: fit-content;
    height: fit-content;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <script src="aestheticPasswordStrengthMeter.js" defer></script>
<link rel="stylesheet" href="aestheticPasswordStrengthMeter.css">  
  <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>
<body>
    <div id="circle-direction">Change circle direction.</div>
    <div id="circle-size"> Change circle size.</div>
    <button id="posUp">⇑</button>
    <button id="posRight">⇒</button>
    <button id="posDown">⇓</button>
    <button id="posLeft">⇐</button>
    <button id="radUp">⇑</button>
    <button id="radDown">⇓</button>
    <canvas id="canvas1"></canvas>
</body>
</html>

Form-data Xmlhttprequest not submitting data

I am trying to submit a form using the post method and a FormData object. I annotated my servlet with @MultipartConfig but it doesnt work ( i run it in debug mode )

js

async function addAuthors() {
        let xhr = new XMLHttpRequest();
        const form = document.getElementById( "authorForm" );
        const FD = new FormData(form);
        xhr.open("POST", "http://localhost:8081/Task1_war/main?command=addAuthor");
        xhr.send(FD);
} 

html

   <form id="authorForm">
        <h1>Author (required)</h1>
        <input type="text"  name="authorName" class="req"/>
        <h1>Author image></h1>
        <input type="file" id="authorImage" name="path" accept=".jpg,.png,.jpeg ">

    </form>
    <div class="add" onclick="addAuthors()">Send</div>

web.xml

    <servlet>
        <servlet-name>MainServlet</servlet-name>
        <servlet-class>com.example.Task1.controller.MainController</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>MainServlet</servlet-name>
        <url-pattern>/main</url-pattern>
    </servlet-mapping>

How to have editable text box with dynamic value component

I am new to react and was in a problem. I am trying to have an editable textbox whose value gets rendered on click of a button in react. As value is non changable without adding an on change function I added an onchange function however it has a problem when dealing with an array?

I am getting HR details from a table and setting them in a variable array like so:

const getHRDtls = async (newToken = true) => {
    if (newToken) {
      const rsp = await getAuthorization();
    }

    setLoading(true);

    var coil = document.getElementById("hrcoilid").value;
    var url = "api/purchase-coil-handling/getHRDtls?" + "&coil=" + coil;
    axiosAPI
      .get(url, defaultOptions)
      .then((response) => {
        if (response.statusText != "" && response.statusText != "OK") {
          //reject(response.statusText);
        } else {
          var rows = [];
          console.log(response.data);
          //console.log(response.data[0].CD_DESC);

          rows[0] = response.data[0].CD_DESC;
          rows[1] = response.data[0].HRC_CAST_NO;
          rows[2] = response.data[0].HRC_CD_FPC_YARD;
          rows[3] = response.data[0].HRC_CD_PRODUCT;
          rows[4] = response.data[0].HRC_CD_PROD_GRP;
          rows[5] = response.data[0].HRC_CD_PS_IN_STCK;
          

          setHRDtlsData(rows);
        }
      })
      .finally((f) => {
        setLoading(false);
      });
  };

I have initialised the set function like so:

const [hrDtlsData, setHRDtlsData] = React.useState([]);

I am trying to set the values in my textbox like this:

<CustomOutlineInput
                              id="status"
                              label="Status"
                              variant="outlined"
                              size="small"
                              value={hrDtlsData[0]}
                              onChange={(e) => setHRDtlsData(e.target.value)}
                              InputLabelProps={{
                                shrink: shrink ? true : false,
                              }}
                              style={{
                                marginTop: "6px",
                                marginLeft: "0px",
                                marginRight: "0px",
                                padding: "0px",
                              }}
                              fullWidth
                            />

where I am doing this:

                               value={hrDtlsData[0]}
                              onChange={(e) => setHRDtlsData(e.target.value)}

However on trying to change the value in the textbox all values in other textboxes with similar code gets affected as on onChange I am setting the entire setHRDtlsData(e.target.value)} to target value . Is there a way to just set HR details for one element of the array without affecting the others without me needing to set individual elements of the row above into a seperate set variable. Please help

discord.js DM command on roles not working

the event handling command is not properly reading, I suppose
the code goes like this

const {client, Message} = require('discord.js')

module.exports = {
    name :"hint",
    /**
     * @param {Client} client
     * @param {Message} message
     */

    

    client.on("messageCreate" , message => {
        if (message.content == (`${config.prefix}ph`)) {
            if (message.member.roles.cache.some(role => role.name === 'Puzzle 1')) {
                message.author.send("hint first puzzle")
            } else if (message.member.roles.cache.some(role => role.name === 'Puzzle 2')) {
                message.author.send("hint second puzzle")
                .catch(console.error);
            }}
     
    })
}

not sure where I went wrong.

Can someone explain me the meaning of this symbol ( “ ) in React [duplicate]

Recently sarted learning react and i do not understand the use of this symbol ( “ )
I have shared the code below as it is used after styled.nav`

import { NavLink as Link } from 'react-router-dom';
import styled from 'styled-components';
  
export const Nav = styled.nav`
  background: #63D471;
  height: 85px;
  display: flex;
  justify-content: space-between;
  padding: 0.2rem calc((100vw - 1000px) / 2);
  z-index: 12;
  /* Third Nav */
  /* justify-content: flex-start; */
`;

How can I send localstorage data from JavaScript ajax call and print return data from views in Django template

I have stored some data on localStorage( Itemnames and ItemIds), now I want to send itemid’s to django views from ajax. I have basics knowledge of django and learning Javascript. I tried to figureit out by myself but its been more than 4 days I could not succeed, any help will be highly appreciated.

My Javascript:

$(document).ready(function() {
    var compare = localStorage.getItem("comparisionItems");
    var compareObj = JSON.parse(compare);
    
    var data_url = window.location.href;
    console.log(compare)
    console.log(compareObj)
    
   
      
      $.ajax({
        url: './compare',
        type: "POST",
        data: {'compare_id': compareObj },
        headers: { "X-CSRFToken": $.cookie("csrftoken") },
        dataType: "json",
        success: function (data) {
            console.log(data)
            
        },
        error: function () {
            alert("Some problem on passing data");
        }
        
    });
});

After getting the localstorageitmes, the console return looks like this:

My views:

def compare(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
    compare_id= request.POST.getlist('compare_id[itemIds]')
    """compare_id=request.POST.getlist('itemIds[]')  """
   
    """compare_id = request.POST.get('compare_id')"""
    product = get_object_or_404(Products, id=compare_id)
    context={ 'product':product}
   
    """ return render (request, './ecommerce/compare.html', context)"""
    return render (request, './compare.html', context)
else:
    context = None
    return render(request,'./compare.html', context)

How can I get the products which have id’s pass by ajax? And is there any different ways to pass those products to the template or I can do it just like the regular Django context process?

Email verification theory – Looking for general guides

This is just a general question on how Email verification can commonly be carried out in a secure way in web apps (I am targeting nodejs based frameworks, but I don’t want any framework specific code, just the steps). I can’t seem to find any general guides on the best practices for email verification, so asking here 🙂

What I have in mind is the following

  1. When a user signs up, create a random token and store it in a DB table along with a field token_created_at that tells when the token is created. Then send a verification mail with that token and the user id.

  2. When the user clicks on the link, the route get’s the token and the id. We can then lookup the table to verify the token for that id. If when the route is clicked is already past the token_created_at field, we simply say they need to generate a new verification URL. If it matches, the account is verified.

This is what I have in mind ? Is this a right approach for email verification ?

Thanks in advance ! 🙂

Flood fill using color picker in javaScript

I’m working on a paint app that has multiple tools (pen, eraser…etc.) and I created a flood fill tool. The code below fills according to colourPalette inputs. I’m trying to use a color picker to pick the color of the fill. How can I adapt the following code to do so?

there’s the colourPalette function that has r,g,b,a as arguments and I think that’s the problem
I created a color picker but the problem is linking it to the tool

var d;
    function FillBucketTool()
    {
        let self = this;
        d = pixelDensity();
      //set an icon and a name for the object
      self.icon = 'assets/fillBucket.png';
      self.name = 'fillBucketTool';
      self.colour = ColourPalette(0,0,100,100);
    
    //create div and picker for tool
//    self.colorPara = createDiv('Fill Color').position(985,943).class('box options').style('font-size', '30px');
//    self.fillColorPicker = createColorPicker().parent(self.colorPara).style('margin: 10px; width: 70px');
//    self.colour = ColourPalette(self.fillColorPicker.value(),255);
    
  self.draw = function () {
    if (mouseIsPressed) {
      floodFill(mouseX, mouseY);
    }
  };

  self.setColour = function (col) {
    self.colour = col;
  };

  function matchColour (pos, oldColour) {
    var current = getPixelData(pos.x, pos.y);
    return (   current[0] === oldColour[0] && current[1] === oldColour[1] 
            && current[2] === oldColour[2] && current[3] === oldColour[3] );
  }

  function getKey (pos) {
    return ""+pos.x+"_"+pos.y;
  }

  function checkPixel(pos, positionSet) { 
    return ! positionSet.hasOwnProperty( getKey(pos) );
  }

  function floodFill (xPos, yPos) {

    var stack = [];
    var pixelList = {};

    var first = {'x':xPos,'y':yPos};
    stack.push( first );
    pixelList[ getKey(first) ] = 1;

    loadPixels();
    var firstColour = getPixelData(xPos, yPos);

    while (stack.length > 0) {

      var pos1 = stack.pop();

      setPixelData(pos1.x, pos1.y, self.colour);

      var up = {'x':pos1.x,  'y':pos1.y-1};
      var dn = {'x':pos1.x,  'y':pos1.y+1};
      var le = {'x':pos1.x-1,'y':pos1.y};
      var ri = {'x':pos1.x+1,'y':pos1.y};

      if (0 <= up.y && up.y < height && matchColour(up, firstColour)) addPixelToDraw(up);
      if (0 <= dn.y && dn.y < height && matchColour(dn, firstColour)) addPixelToDraw(dn);
      if (0 <= le.x && le.x < width  && matchColour(le, firstColour)) addPixelToDraw(le);
      if (0 <= ri.x && ri.x < width  && matchColour(ri, firstColour)) addPixelToDraw(ri);
    }

    updatePixels();
      
    function addPixelToDraw (pos) {

      if (checkPixel(pos, pixelList)  ) {
        stack.push( pos );
        pixelList[ getKey(pos) ] = 1;
      }
    }
  }  

}


function ColourPalette (r,g,b,a) { 
  var self = (this !== window ? this : {});
  if (arguments.length === 0) {
    self['0'] = 0; self['1'] = 0; self['2'] = 0; self['3'] = 0;
  } else if (arguments.length === 1) {
    self['0'] = r[0]; self['1'] = r[1]; self['2'] = r[2];  self['3'] = r[3]; 
  } else if (arguments.length === 4) {
    self['0'] = r; self['1'] = g; self['2'] = b; self['3'] = a;
  } else {
    return null;
  }
  return self;
}

function getPixelData (x, y) {
  var colour = [];
  for (var i = 0; i < d; ++i) {
    for (var j = 0; j < d; ++j) {
      let idx = 4 * ((y * d + j) * width * d + (x * d + i));
      colour[0] = pixels[idx];
      colour[1] = pixels[idx+1];
      colour[2] = pixels[idx+2];
      colour[3] = pixels[idx+3];
    }
  }
  return colour;
}

function setPixelData (x, y, colour) {
  for (var i = 0; i < d; ++i) {
    for (var j = 0; j < d; ++j) {
      let idx = 4 * ((y * d + j) * width * d + (x * d + i));
      pixels[idx]   = colour[0];
      pixels[idx+1] = colour[1];
      pixels[idx+2] = colour[2];
      pixels[idx+3] = colour[3];
    }
  }
}

XMLHttpRequest FormData not submitting data

I am trying to submit a form using the post method and a FormData object. I annotated my servlet with @MultipartConfig but it doesnt work

js

async function addAuthors() {
        let xhr = new XMLHttpRequest();
        const form = document.getElementById( "authorForm" );
        const FD = new FormData(form);
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.open("POST", "http://localhost:8081/Task1_war/main?command=addAuthor");
        xhr.send(FD);
} 

html

   <form id="authorForm">
        <Label>Author (required)</Label>
        <input type="text"  name="authorName" class="req"/>
        <label class="errorInput"  ></label>
        <Label>Author image></Label>
        <input type="file" id="authorImage" name="path" accept=".jpg,.png,.jpeg ">

    </form>
    <div class="add" onclick="addAuthors()">Send</div>

API host’s rate-limit header not read properly

Here is my code:

const timer = ms => new Promise(resolve => setTimeout(resolve, ms));

const createThrottler = (limitHeader) => {
  let requestTimestamp = 0;
  let rateLimit = 0;
  return (requestHandler) => {
    return async (...params) => {
      const currentTimestamp = Number(Date.now());
      if (currentTimestamp < requestTimestamp + rateLimit) {
        const timeOut = rateLimit - (currentTimestamp - requestTimestamp);
        requestTimestamp = Number(Date.now()) + timeOut;
        await timer(timeOut)
      }
      requestTimestamp = Number(Date.now());
      const response = await requestHandler(...params);
      if (!rateLimit > 0) {
        rateLimit = Math.floor((60 / response.headers.get(limitHeader)) * 1000);
      }
      console.log(limitHeader);
      console.log(rateLimit);
      return response;
    }
  }
}

const throttle = createThrottler("X-***-Ratelimit");
const throttleFetch = throttle(fetch);

function getRelease(idFiltered) {
  return throttleFetch(`https://api.***.com/releases/${idFiltered}`, {
    headers: {
      'User-Agent': '***/0.1',
    },
  }).then(response => response.json())
    .then(data => {
      if (data.message === 'Release not found.') {
        return { error: `Release with ID ${idFiltered} does not exist` };
      } else {
        const id = data.id;
        const delimiter = document.getElementById("delimiter").value || "|";
        const artists = data.artists ? data.artists.map(artist => artist.name) : [];
        const barcode = data.identifiers.filter(id => id.type === 'Barcode')
          .map(barcode => barcode.value);
        var formattedBarcode = barcode.join(delimiter);
        const country = data.country || 'Unknown';
        const genres = data.genres || [];
        const formattedGenres = genres.join(delimiter);
        const labels = data.labels ? data.labels.map(label => label.name) : [];
        const formattedLabels = labels.join(delimiter);
        const catno = data.labels ? data.labels.map(catno => catno.catno) : [];
        const formattedCatNo = catno.join(delimiter);
        const styles = data.styles || [];
        const formattedStyles = styles.join(delimiter);
        const tracklist = data.tracklist ? data.tracklist
          .map(track => track.title) : [];
        const formattedTracklist = tracklist.join(delimiter);
        const year = data.year || 'Unknown';
        const format = data.formats ? data.formats.map(format => format.name) : [];
        const qty = data.formats ? data.formats.map(format => format.qty) : [];
        const descriptions = data.formats ? data.formats
          .map(descriptions => descriptions.descriptions) : [];
        const preformattedDescriptions = descriptions.toString()
          .replace('"', '""').replace(/,/g, ', ');
        const formattedDescriptions = '"' + preformattedDescriptions + '"';
        console.log(idFiltered,
          artists,
          format,
          qty,
          formattedDescriptions,
          formattedLabels,
          formattedCatNo,
          country,
          year,
          formattedGenres,
          formattedStyles,
          formattedBarcode,
          formattedTracklist
        )

        return [idFiltered,
          artists,
          format,
          qty,
          formattedDescriptions,
          formattedLabels,
          formattedCatNo,
          country,
          year,
          formattedGenres,
          formattedStyles,
          formattedBarcode,
          formattedTracklist
        ];
      }
    });
}

But the “X-***-Ratelimit” header is clearly not being read correctly, as when I do

      console.log(limitHeader);
      console.log(rateLimit);

I initially get back

object

and thereafter

X-***-Ratelimit
Infinity

From the host’s documentation:

We attach the following headers to responses to help you track your rate limit use:

X-***-Ratelimit: The total number of requests you can make in a one minute window.

X-***-Ratelimit-Used : The number of requests you’ve made in your existing rate limit window.

X-***-Ratelimit-Remaining: The number of remaining requests you are able to make in the existing rate limit window.

Any help please? TIA.