display current user’s email in frontend supabase

im trying to display the current logged in user’s email in the dashboard. the user details are fetching in the console log.

const User = supabase.auth.getUser()
  console.log(User)

  const navigate = useNavigate();
  async function logout() {
    await supabase.auth.signOut();
    console.log("logged out")
    navigate('/')
  }
  
  return (
    <div>
      <h4>User Email: {User.email} </h4>
      {User?
      (<h4>WORKING....</h4>):(
        <h4>Not Working....</h4>
      )
      }
      <button onClick={logout}>Logout</button>
    </div>
  );
}

Use node module in django

I’m trying to use nodejs modules (lodash) inside of my Django app but nothing happen.

The architecture is as follow:

- myproject
    - dist
    - myapp
        - templates
            - index.html
        - apps.py
        - views.py
        - ...
    - myproject
        - settings.py
        - urls.py
        - ...
    - nodes_module
    - static
        - js
            - script.js
    - manage.py
    - package.json

I edited my settings.py so nodes_module/ is considered as static:

STATIC_URL = "/static/"
STATIC_ROOT = 'dist/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
    ('node_modules', os.path.join(BASE_DIR, 'node_modules/')),
)

And here is the content of my index.html:

hello
<div id="result"></div>

<script>console.log("yolo")</script>

<!-- This should write "2 4 6 8 10" on console and page but doesn't -->
{% load static %}
<script src="{% static 'node_modules/lodash/lodash.js' %}">
    import _ from 'lodash';

    console.log("yolo2")
    const array = [1, 2, 3, 4, 5];
    const doubled = _.map(array, function(n) {return n * 2;});
    const resultElement = document.getElementById('result');

    resultElement.innerHTML = doubled;
    console.log(doubled);
</script>

I got a lot of errors while trying but now, with this architecture and code, I don’t have errors anymore but nothing appear on my page except the “hello”. For some reasons, the first console.log("yolo") does appear on the console but not the second one console.log("yolo2"). It’s like it never went inside the second <script></script> tag.

I read a lot of stack overflow and other posts on web and tried a lot of things before posting here but couldn’t manage to find a working solution…

Auth0 Real-time Webtask Logs Extension not working and user not getting stored in database

I am using the Auth0 Real-time Webtask Logs Extension to debug the create action script of my custom database. I have placed a few console log statements in the script, but nothing is being outputted in the Real-time Webtask Logs. I have already installed and configured the extension in my Auth0 dashboard, and I have selected the correct tenant in the Real-time Webtask Logs Extension console. I have also checked the logs in the Auth0 dashboard to make sure that the script is being executed and that there are no errors. However, the output from the console log statements is still not being displayed in the Real-time Webtask Logs Extension console.

The other problem is that the user is not getting stored in the database after registration. The script seems to be executing correctly as I am able to receive the authResult that is returned by the callback of auth0.WebAuth.signup() method, but the user is not being added to the database. I am not sure if these two issues are related or if there is a separate issue with the database connection or the insert query.

Here’s what my signup code looks like:

const auth0 = new auth0.WebAuth({
  clientID: 'MY_CLIENT_ID',
  domain: 'MY_AUTH0_DOMAIN'
});

auth0.WebAuth.signup({
  connection: 'Username-Password-Authentication',
  email: '[email protected]',
  password: 'password',
  userMetadata: { // this will be stored in user_metadata
    firstName: 'John',
    lastName: 'Doe'
  }
}, function(err, result) {
  if (err) {
    console.error(err);
  } else {
    console.log(result);
  }
});

Here is what my create action script looks like:

function create(user, callback) {
  const mysql = require('mysql');
  const bcrypt = require('bcrypt');

  const connection = mysql.createConnection({
        host: 'host',
    user: 'user',
    password: 'pwd',
    database: 'database',
    port: 8000,
  });
  
  console.log("test");

  connection.connect();

  const query = 'INSERT INTO users SET ?';

  bcrypt.hash(user.password, 10, function(err, hash) {
    const insert = {
      fname: user.firstName,
      lname: user.lastName,
      email: user.email,
      password: hash,  
    };

    connection.query(query, insert, function (err, results) {
      console.log("saving");
      if (err) return callback(err);
      if (results.length === 0) return callback();
      console.log("success");
      callback(null);
    });
  });
}

FYI, when I test the script using Auth0’s Save and Try feature, the user gets stored in the database. Also, the login script works without any issues.

How can I fix these issues and ensure that the Real-time Webtask Logs Extension works and the user gets stored in the database after registration?

what OR operator in JavaScript returns

I was expectng output to be "" (empty string) but it's display nothing

enter image description here

If I do this without a variable then it displays me ‘ ‘ (empty string)
enter image description here

I am using the Chrome console.

I tried with help of a debugger, in global memory random3 is having ” “

Just started learning javascript and pretty confused, how can i clean my code?

I’ve just started learning JavaScript, and i’m finding it very confusing so far. If anyone could help with any advice, many thanks in advance!


function Shoes (shoeName, productCode, quantity, itemValue) {
   this.shoeName = shoeName; 
   this.productCode = productCode; 
   this.quantity = quantity; 
   this.itemValue = itemValue; 
  

should ‘change’ and ‘shoeDescription’ be within the Shoe class, or separate functions? (as they are coming up in console.table)


     this.change = function (name, code, qty, value) {
      this.shoeName = name;
      this.productCode = code;
      this.quantity = qty;
      this.itemValue = value;
    
      console.log(`
      Item:
      ${shoeName} ${productCode} ${quantity} ${itemValue}

      has been edited to:
      ${name} ${code} ${qty} ${value}
      `)
   }
      

   
   this.shoeDescription = function () {
     
    return `
      Shoe: ${this.shoeName} 
      Product Code: ${this.productCode} 
      Qty: ${this.quantity}
      Value: ${this.itemValue}`
   }


}




function shoeSearch(shoes01, shoes02){
    let found = false;
    shoes01.forEach(x => {
        if(x.shoeName == shoes02){
            console.log(`${shoes02} found.`);
            found = true;
        }
    });
 
    if(!found){
        console.log(`${shoes02} not found.`)
    }
 }



function lowestItem(shoes01){
   let low = shoes01[0].itemValue;
   let shoeName = "";
   shoes01.forEach(shoes02 => {
       if (shoes02.itemValue < low){
           low = shoes02.itemValue;
           shoeName = shoes02.shoeName;
       }
   })

   console.log(`${shoeName} is our cheapest item, with value of £${low}`)
}




function highestItem(shoes01){
   let high = shoes01[0].itemValue;
   let shoeName = "";
   shoes01.forEach(shoes02 => {
       if (shoes02.itemValue > high){
           high = shoes02.itemValue;
           shoeName = shoes02.shoeName;
       }
   })

   console.log(`${shoeName} is our most expensive item has the value of £${high} `)
}



let sabat01 = new Shoes("nike", "nk0119", 2, 150);
let sabat02 = new Shoes("adidas", "ad5169", 43, 170);
let sabat03 = new Shoes("sketchers", "sk624", 10, 67);
let sabat04 = new Shoes("puma", "pu738", 20, 93);
let sabat05 = new Shoes("asics", "as823", 13, 50);

let shoeStock = [sabat01, sabat02, sabat03, sabat04, sabat05];



shoeStock.sort(
    (p1, p2) => 
    (p1.shoeName > p2.shoeName) ? 1 : (p1.shoeName < p2.shoeName) ? -1 : 0);


When i run these console.log, i don’t get why highest item doesn’t show
Also, how do i remove the ‘change’ and ‘shoe description’ from console.table

// find "adidas"
console.log(shoeSearch(shoeStock, "adidas"));
// try and find an item that doesnt exist
console.log(shoeSearch(shoeStock, "kicks"));
// find lowest item
console.log(lowestItem(shoeStock));
// find highest item
console.log(highestItem(shoeStock));
// get any item description
console.log(sabat03.shoeDescription());
// edit an item
console.log(sabat01.change("nike", "nk020", 88, 175));
// display product name in in ascending order
console.table (shoeStock)

Missing ordered list and unodered list points when converting html to pdf using jsPDF

I try to convert from html to pdf using jsPDF.

I could not get the pdf as the original html.
ordered list and unordered list bullet points are missing in the pdf file.

ordered-list-in-html

ordered-list-in-html

ordered-list-in-pdf

ordered-list-in-pdf

unordered-list-in-html

unordered-list-in-html

unordered-list-in-pdf
unordered-list-in-pdf

function BlazorDownloadFile(filename, text) {
  let parser = new DOMParser();
  let doc = parser.parseFromString(text, "text/html");

  console.log(doc.body);
  const element = doc.body;

  var opt = {
    margin: 1,
    filename: filename,
    html2canvas: { scale: 2 },
    jsPDF: { unit: "cm", format: "a4", orientation: "portrait" },
  };
  // Choose the element that our invoice is rendered in.
  html2pdf().set(opt).from(element).save();
}

Please help me to fix this issue.

JavaScript: Interrupt a setTimeout() inside a promise, upon a click event

Here is a very simplified reproduction of the issue I am facing:

window.onload=function(){
    touchme = document.getElementById('click');
    function mains(){
        touchme.innerHTML = "clicked " + Math.random().toString();
    }
    function process() {
        touchme.dataset.clicked = "false";
        mains();
        touchme.addEventListener("click", () => {
            touchme.dataset.clicked = "true";
        }, {once : true});

        let clickPromise = new Promise((resolve, reject) => {
            var timer = setTimeout(() => {
                if(touchme.dataset.clicked == "true"){
                    resolve();
                }
                else{
                    reject();
                }
            }, 1500);
        });
        
        clickPromise.then(() => { 
            process();
        });

        clickPromise.catch(() => {
            alert("game over");
        });
    }

    process();
}

This bit of HTML has been used <body><button id="click">Click</button></body>

What I basically want is:

  • if I click the button, mains() will run immediately
  • if I don’t, setTimeout() will wait 1.5secs for me. Within this time if I click, setTimeout() resets and mains() gets executed
  • if I still don’t click, alert("game over") is executed. The “self callback loop” breaks

However, the mains() function isn’t being run immediately whenever I am clicking, instead it is waiting for the timeout, causing a delay of 1.5s after every click.

Naturally, the solution is to use clearTimeout(), however, I can’t seem to wrap my head around where to use it. Adding it inside the function argument of event listener causes the timeout to run independently of the click event and just makes it reject the promise 1.5s later, notwithstanding my button clicks. I also tried calling the function itself inside the event listener function, which doesn’t work. Adding it inside an if(touchme.dataset.clicked == "true") outside the setTimeout() and inside the promise wouldn’t work, as my initial value is false, so it just checks the initial state.

How to check image height and width before upload in Reactjs

I am working on reactjs and right now i am trying to validate image height and width before upload,how can i do this ? i want user cant upload more than 200*200 (pixel)/dynamic,How can i do this ? Here is my current code

const createOfficer = async () => {
   setShowSpinner(true)
    const formData = createFormDataObject(newOfficerData)
    const res = await putAPIFormDataWrapper(editDepartmentUrl, formData)
    if (!res.isError) {
      setShowSpinner(false)
      props.notify(res.data.data.message, 'success')
    } else {
      setShowSpinner(false)
      props.notify(res.error.message, 'error')
    }
  }

How do I skip weekends on the X-axis?

Actual behaviour
Now a series of all days of the week is being built on the X-axis.
like now:
2022-5-30
2022-5-31
2022-6-1
2022-6-2
2022-6-3
2022-6-4
2022-6-5
2022-6-6

Live demo with steps to reproduce

https://jsfiddle.net/5z1b9xnp/

let globalData = []; let finRez = [];
let chart;

let duration = 500; // Determines how long the animation between new points should be take
let startIterator = 1; // Determines how many points will be rendered on chart's init
let currentIterator = startIterator;
let maxIterator = 1;

let guiButton = document.getElementById('start');
let guiButtonState = 'Start';
let intervalId;

// Fetch data:
fetch('https://raw.githubusercontent.com/veleg/trade/main/trade.json')
  .then(response => response.json())
  .then(data => {
    parseData(data);
    createChart();
    initEvents();
  });

function initEvents() {
  guiButton.addEventListener('click', function() {
    if (guiButtonState === 'Stop') {
      // User clicked "Stop" -> stop animation and allow to resume
      intervalId = clearInterval(intervalId);
      guiButton.innerText = guiButtonState = 'Resume';
    } else {
      // If animation has finished, recreate chart
      if (guiButtonState === 'Restart') {
        createChart();
      }
      guiButton.innerText = guiButtonState = 'Stop';
      // Start animation:
      redrawChart(currentIterator += 1);
      intervalId = setInterval(function() {
        // If we reached last available point, stop animation:
        if (currentIterator === maxIterator) {
          intervalId = clearInterval(intervalId);
          currentIterator = startIterator;
          guiButton.innerText = guiButtonState = 'Restart';
        } else {
          redrawChart(currentIterator += 1);
        }
      }, duration);
    }
  });
}

function redrawChart(index) {
  // Set new subtitle on every redraw
  chart.setTitle(null, {
    text:  ' Заработано: ' + globalData[0].data[index][1]
  }, false);
    
    
    const newValues = globalData.map(series => series.data[index][1]);
    const maxIndex = newValues.indexOf(Math.max.apply(null, newValues));

  // To each series, add a point:
  chart.series.forEach(
    (series, seriesIndex) => {
            const enabled = maxIndex === seriesIndex && ((index < 5) || (index % 5 === 0));
      series.addPoint(
                {
          x: globalData[seriesIndex].data[index][0],
          y: globalData[seriesIndex].data[index][1]
                    <!-- dataLabels: { -->
                        <!-- enabled -->
                    <!-- }, -->
                    <!-- marker: { -->
                        <!-- enabled -->
                    <!-- } -->
        },
        false,
        false,
        false
      );
    }
  );

  // Now, once everything is updated, redraw chart:
  chart.redraw({
    duration
  });
}

function parseData(data) {
  Highcharts.objectEach(
    data,
    // Prepare Highcharts data-format:
    // series: [{
    //   data: [ [x, y], [x, y], ..., [x, y]]
    // }]
    (countryData, country) => {
            if (country !== 'Diamond Princess' && country !== 'Holy See') {
                globalData.push({
                    name: country,
                    data: countryData.map(p => [Date.parse(p.date), p.recovered / getCountryPopulation(country)])
                    <!-- data: countryData.map(p => [p.date, p.recovered / getCountryPopulation(country)]), -->
                    <!-- datas: countryData.date, -->
                    <!-- datass: countryData.map(p => [p.date, p.date]) -->
                });
            }       
            
        }
  );


  // Sort and limit dataset:
  globalData = globalData
    .sort((countryA, countryB) => {
      let countryALen,
        countryBLen;

      if (!countryA || !countryA.data || countryA.data.length === 0) {
        return 1;
      }

      if (!countryB || !countryB.data || countryB.data.length === 0) {
        return -1;
      }

      return countryB.data[countryB.data.length - 1][1] - countryA.data[countryA.data.length - 1][1];
    })
    .splice(0, 8);
        

  maxIterator = Math.max.apply(null, globalData.map(series => series.data.length - 1));
}


function createChart() {
    function format(y) {
    return y.toFixed(2);
  }

  chart = Highcharts.chart('container', {
    chart: {
      type: 'spline',
      marginLeft: 100
    },

    legend: {
      layout: 'proximate',
      align: 'right'
    },


    title: {
      floating: true,
      align: 'left',
      x: 93,
      y: 20,
      text: 'Confirmed cases per country per 1000 inhabitants'
    },
    subtitle: {
      floating: true,
      align: 'left',
      y: 60,
      x: 90,
      text:  ' Заработано: ' + globalData[0].data[0][1],
      style: {
        fontSize: '20px'
      }
    },
    tooltip: {
      split: true,
      pointFormatter: function() {
        <!-- var value = format(this.y); -->
        <!-- return `<span style="color:${this.color}">●</span> ${this.series.name}: <b>${value}</b><br/>`; -->
            }
    },

    yAxis: {
      title: {
        text: ''
      },
      maxPadding: 0.2,
      softMax: 1
    },

    xAxis: {

      gridLineWidth: 2,
      min: globalData[0].data[0][0],
      minRange: 7 * 24 * 3600 * 1000,
      type: 'datetime'
      <!-- categories: [1] -->
    },


    plotOptions: {
      series: {
        animation: {
          duration
        },
        <!-- marker: { -->
          <!-- symbol: 'circle' -->
        <!-- }, -->
        dataLabels: {
          formatter: function() {
            return format(this.y);
          }
        }
      }
    },
    series: globalData.map(series => {
      return {
        name: series.name,
        data: series.data.slice(0, startIterator).map(point => {
                    return { x: point[0], y: point[1] }
                })
      }
    })
  });
}


function getCountryPopulation(country) {
  return {
    "Заработано": 1,
    "Финансовый результат": 1
  }[country];
}

Product version
Highcharts JS v10.3.2 (2022-11-28)

It is necessary to skip days on the X axis that are not in the JSON file.
need:
2022-5-30
2022-5-31
2022-6-1
2022-6-2
2022-6-3
2022-6-6

Vuex cant read localstorage on page refresh

I store a user token in a vuex state.
When the page of my nuxt app is refreshed, i want this token to persist, to check for eligibility to visit user-related routes.

From a global middleware, i just dispatch an action like so

 context.store.dispatch('authModule/resetToken')

triggering the vuex action

resetToken(context) {
    context.commit('RE_AUTH')
  },

which triggers the following mutation

RE_AUTH: (state, token) => {

    if (!state.token && process.client && localStorage.getItem('auth-token')) {
      token = localStorage.getItem('auth-token')
      state.token = token
    }
  },

When i reload the page, the mutation is triggered, but the if condition does not resolve true and execute the code to reappend the token, even though there is the correct named token in localhost.

When i however then navigate to another page, the code does execute and reappends the token. I dont understand why, because global middleware should be executed first in lifecycle and vuex should have access to localstorage

document.querySelector().innerHTML not working properly

i’m trying to make a website and i’m trying to use a js function to write the header. Here is the js code(writeStuff.js):

document.querySelector(".WriteHeader").innerHTML = `
    <div>
        <img src="images/logo.png" alt="Wizards and Potters Logo">
        <title>Wizards & Potters, a Harry Potter/DnD webcomic</title>
        <div class="header">
            <h3 id="nav"><a id="headernav" href="0005.html">READ</a> ¦ ¦ ¦ ¦ <a id="headernav" href="archive.html">ARCHIVE</a> ¦ ¦ ¦ ¦ <a id="headernav" href="about.html">ABOUT</a></h3>
        </div>
    </div>
`;

And I call it in my page here:

    <body>
        <div class-'WriteHeader'></div>
        <h2 id="title"> 1. NPC Monologues <a href="0002.html">></a></h2>

And reference the script at the bottom:

        <p id="footer">ⒸAHumanIBelieve, 2023</p>
        <script src="writeStuff.js"></script>
    </body>
</html>```

I've tried changing the name of the js thing, the name of the js file, removing and replacing the dor.

Is there a way to hook into Next.js build-time execution?

I know that Next.js does some build-time execution for SSG. Is there a way to hook into this build-time execution to run some basic code?

Let’s say that these special functions are delimited with $, so:

// build-time only function
const $concat = (...args: string[]) => args.join(" ")

const x = $concat(
    "this",
    "that",
    "and the other"
)

would build to the following JS:

const x = "this that and the other"

This would be super useful for tailwind class name manipulations.

Java spring boot web socket not working with javascript WebSocket object

I created a web socket with spring boot’s TextWebSocket handler and it works perfectly fine with postman but it doesn’t work with the javascript Socket object.


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(locationHandler(), "/users/location")
                .addInterceptors(new HttpSessionHandshakeInterceptor())
                .setAllowedOrigins("*");
    }

    @Bean
    public LocationHandler locationHandler() {
        return new LocationHandler();
    }

}

Above is my configuration code.
This is my handler code:

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;

public class LocationHandler extends TextWebSocketHandler {

        @Override
        public void handleTextMessage(WebSocketSession session, TextMessage msg) {
            System.out.println(msg.getPayload());
            try {
                session.sendMessage(new TextMessage("test"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
}

This is the error I get on the javascript side:

Event {
  "isTrusted": false,
  "message": "The operation couldn’t be completed. Connection refused",
}

This is my javascript code:

  let test = new WebSocket("ws://192.168.1.80:8080/");
  test.onerror = function(err) {
    console.log(err);
  }
  
  test.onopen = function() {
    console.log("opened");
    test.send('test work please');
  }

Nothing is received in the backend side.

I tried allowing cors but I’m not sure if I did it properly. I couldn’t find much online on the TextWebSocketHandler as most web sockets in spring are implemented with STOMP.

Blank Page is loading in github Pages

I have deployed my react app made using create-react-app by using the gh-pages npm package to github pages.

The steps I have performed are :

Step 1: Install gh-pages via the terminal
$ npm install gh-pages –save -dev

Step 2: Modified the package.json and added

“homepage”: “https://nemb0t.github.io/todo_typescript/”

Step 3: In the “scripts” section of package.json, added

“predeploy”: “npm run build”,
deploy”: “gh-pages -d build”,

Step 4: Ran the command ‘npm run deploy’.

I am not using react router or any other routers since mine is a simple todo list application.

This is what my github pages looks like:
Github pages preview

Please note I the app is working as expected in the development server (npm start) and the app also works as expected when ran after its build (“npm run build” and then “serve -s build”).
Note: when running build I replaced the homepage (“homepage”: “.”).

Github: https://github.com/NemB0t/todo_typescript

Site URL: https://nemb0t.github.io/todo_typescript/

I have tried tweeking the URL in the homepage of the package.json, tried many tweeks to the different tags but nothing seems to help.

The app is expected to look like this:
Expect Todo App

Kindly help in resolving the issue. I have been struggling with the problem the entire week and have tried out many solutions from stackover flow and other forums.