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; */
`;

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.

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.

On click only works once

for my responsive (mobile) hamburger-menu, i wanted to show the menu, when a class is pressed.
But it only works once (‘click’ is only locked once in the console, so it doesn’t register the clicks after it was pressed one time).
My JS code:

var btn = document.querySelector(".toggle-btn");
var navbar = document.querySelector(".menue");



btn.addEventListener('click', () =>{
    console.log('click');
    navbar.classList.toggle("active");
})

My html code:

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

<div class="nav-bar">
    <nav>
        <div class="logo">
            <a href="../../index.php"><img src="../png/lg_nord_logo_navbar.png" alt=""></a>
        </div>
        <a href="#" class="toggle-btn">
            <span class="bar"></span>
            <span class="bar"></span>
            <span class="bar"></span>
        </a>
        <div class="menue">
            <ul>
                <li><a href="#">Disziplinen</a>
                    <ul>
                        <li><a href="../disziplinen/30_m_startblock.php">30 meter startblock</a></li>
                        <li><a href="../disziplinen/30_m_fliegend.php">30 meter fliegend</a></li>
                        <li><a href="../disziplinen/60m.php">60 meter</a></li>
                        <li><a href="../disziplinen/10er_hopserlauf.php">10er Hopserlauf</a></li>
                        <li><a href="../disziplinen/Klappmesser.php">Klappmesser</a></li>
                        <li><a href="../disziplinen/Klimmzuege.php">Klimmzüge</a></li>
                        <li><a href="../disziplinen/liegestuetze.php">Liegestütze</a></li>
                        <li><a href="../disziplinen/standweitsprung.php">Standweitsprung</a></li>
                    </ul>
                </li>
                <li><a href="#">Daten hinzufügen</a>
                    <ul>
                        <li><a href="../addData/30_m_startblock.php">30 meter startblock</a></li>
                        <li><a href="../addData/30_m_fliegend.php">30 meter fliegend</a></li>
                        <li><a href="../addData/60m.php">60 meter</a></li>
                        <li><a href="../addData/10er_hopserlauf.php">10er Hopserlauf</a></li>
                        <li><a href="../addData/Klappmesser.php">Klappmesser</a></li>
                        <li><a href="../addData/Klimmzuege.php">Klimmzüge</a></li>
                        <li><a href="../addData/liegestuetze.php">Liegestütze</a></li>
                        <li><a href="../addData/standweitsprung.php">Standweitsprung</a></li>
                    </ul>
                </li>
                <li><a href="#"><i class="material-icons">support_agent</i>Athleten (beta)</a>
                    <ul>
                        <li><a href="../athlet_search/index.php?name=tom">Tom-Luca</a></li>
                        <li><a href="../athlet_search/index.php?name=marc">Marc          </a></li>
                        <li><a href="../athlet_search/index.php?name=leo">Leo          </a></li>
                        <li><a href="../athlet_search/index.php?name=lukas">Lukas</a></li>
                        <li><a href="../athlet_search/index.php?name=vincent">Vincent</a></li>
                        <li><a href="../athlet_search/index.php?name=damien">Damien</a></li>
                        <li><a href="../athlet_search/index.php?name=karsten">Karsten</a></li>
                    </ul>
                </li>
                <li><a href="../../settings/"><i class="material-icons">admin_panel_settings</i> Einstellungen</a></li>
                <li><a class="state" href="login.php">Login</a></li>
                <li><a href="../logout.php"><i class="fas fa-sign-out-alt"></i>  Logout</a></li>
            </ul>
        </div>
    </nav>
</div>

What is my mistake? Thank you for your advice!

window.screen.width do not work on ios devices?

I have sphere animation on my site, for laptop, tablet and mobile I m using different sizes of sphere. Here you can see conditions of every type of device:

Laptop:
var screen_size = window.screen.width;
if(screen_size < 1025){
    false;
}else{
    sphere animation code;
}
Tablet:
var screen_size = window.screen.width;
if(screen_size >= 1025  || screen_size  < 668){
    false;
}else{
    sphere animation code;
}
Mobile:
var screen_size = window.screen.width;
if((screen_size > 667)){
    false;
}else{
    sphere animation code;
}

If I use one script separately its – works, other operation system – its works. I think suppose main problem in “window.screen.width”.

Here you an see my site with full code: thesevenwang

I need to get sequence of 20 records for Ag-Grid React Js from javaScript object, instead of fetching from json server (url) while i scroll down

I am Implementing Ag-grid for infinite scrolling, the problem I am facing is when we hit API for data it returns all data. what I want is that if we scroll down it then hit API to bring the next data. But in ag-grid, all data comes in sequence of 20 rows and saves in our browser memory.

i have json data as js objects, need to get sequences of 20 data from object in js, instead of fetching from url.

import React, { useState } from 'react'
import { AgGridReact } from 'ag-grid-react';
import 'ag-grid-enterprise';
import 'ag-grid-community/dist/styles/ag-grid.css';
import 'ag-grid-community/dist/styles/ag-theme-alpine.css';
import {data} from './data'

const App = () => {
  const [gridApi, setGridApi] = useState(null);

  const columns = [
    { headerName: "Athlete", field: "athlete", filter: "agTextColumnFilter", cellRenderer: 'Loading' },
    { headerName: "Age", field: "age", filter: "agTextColumnFilter" },
    { headerName: "Country", field: "country", filter: "agTextColumnFilter" },
    { headerName: "Year", field: "year", filter: "agTextColumnFilter" },
    { headerName: "Date", field: 'date', filter: "agTextColumnFilter" },
    { headerName: "Sport", field: 'sport', filter: "agTextColumnFilter" },
    { headerName: "Gold", field: 'gold', filter: "agTextColumnFilter" },
    { headerName: "Silver", field: 'silver', filter: "agTextColumnFilter" },
    { headerName: "Bronze", field: 'bronze', filter: "agTextColumnFilter" },
    { headerName: "Total", field: 'total', filter: "agTextColumnFilter" },
  ]
  const datasource = {
    getRows(params) {
      console.log(JSON.stringify(params, null, 1));
      const { startRow, endRow}= params
      // let url = `http://localhost:3001/olympic?`
     
      //Pagination 
      url += `_start=${startRow}&_end=${endRow}`
      fetch(data)
        .then(httpResponse => httpResponse.json())
        .then(response => {
          params.successCallback(response, 499);
        })
        .catch(error => {
          console.error(error);
          params.failCallback();
        })
    }
  };

  const onGridReady = (params) => {
    setGridApi(params);
    // register datasource with the grid 
    params.api.setDatasource(data);
  }


  const components = {
    Loading: (params) => {
      if (params.value !== undefined) {
        return params.value
      } else {
        return "Loading .. "
      }
    }
  }

  return (
    <div>
      <h1 align="center">Trial Scroll</h1>
      <div className="ag-theme-alpine" style={{ height: 800 }}>
        <AgGridReact
          columnDefs={columns}
          rowModelType="infinite"
          onGridReady={onGridReady}
          cacheBlockSize={20}
          rowData={data}
        />
      </div>
    </div>
  );
};
export default App 

here i tried to get data on url from json server, but i need to get data from javascript object.

How to add dynamic Where queries in objection.js?

I have a table which has a global search bar that needs to trigger search for all fields like firstName, lastName, email and role.

Also have a dynamic filter which can have single or multiple filter like “firstName” or/And “lastName”

Obviously they need to be paginated.

For pagination i can use Model.query().page(1, 10)

But how to supply search or filter. assuming only search or filter active at a given time.

Search and filter both using LIKE. How to dynamically do this.

Web3js smart contract interaction gas and signing

So I can interact with a function within a smart contract.
I also know that to actually do the transaction I need something like this:

const contractObj = new web3.eth.Contract(abi, contractAddress)

const transaction= await contractObj .methods.NameofTheMethod(x).send({from:myAddress,gasLimit:value})

My question is: what is the next step? Because I put myAddress but I should sign this before send the transaction right?

Otherwise how will it be able to take the fee from the gas?