making axes in radar chart thicker

I have a radar Chart with chart.js in MVC Core.net 6. so this is my code:

var options = {
    scale: { 
       ticks: { 
       max: 100,
       beginAtZero: true,
       stepSize: 20,
       display: false
       } ,
   },                      
   tooltips: {                          
      callbacks: {
         label: function (tooltipItem, data,) {
             var questionNum =Math.ceil((tooltipItem.yLabel * gtotal[tooltipItem['index']]) / 100);                              
             return  data.datasets[tooltipItem.datasetIndex].label + ": " + questionNum +" From" + gtotal[tooltipItem['index']];                        
           }
     }
   },
    scaleSteps: 5,
    scaleStartValue: 1
  };

 var myRadar =new Chart(ctx, {
                   type: 'radar',
                   data: ChartData,
                   options: options
               });

enter image description here

how can I make the axes thicker?

Javascript Array solution

I have a multi dimensional dynamic JSON array : example –

{
    "TEST": [{
        "_DocumentType": "INVOICE",
        "_DocumentDate": "2022-12-31",
        "_AccountNumber": "910:11:77:44520",
        "_DocumentNumber": "BILL-3270",
        "Detail": [{
                "test": "INVOICE",
                "test2": "2022-10-21"
            },
            {
                "test": "INVOICE",
                "test2": "2022-10-21"
            }
        ]
    }, {
        "_DocumentType": "INVOICE",
        "_DocumentDate": "2022-12-31",
        "_AccountNumber": "910:11:77:44520",
        "_DocumentNumber": "BILL-2543",
        "Detail": [{
                "test": "INVOICE",
                "test2": "2022-12-31"
            },
            {
                "test": "INVOICE",
                "test2": "2022-12-31"
            }
        ]
    }, {
        "_DocumentType": "INVOICE",
        "_DocumentDate": "2022-12-31",
        "_AccountNumber": "910:11:77:44520",
        "_DocumentNumber": "BILL-3270",
        "Detail": [{
                "test": "INVOICE",
                "test2": "2022-12-31"
            },
            {
                "test": "INVOICE",
                "test2": "2022-12-31"
            }
        ]
    }]
}

if _DocumentNumber are same in any array them combined with that if different _DocumentNumber then other array

I have made an app in Tizen Studio its a hls stream player but keeps infinite loading

I have made an app in Tizen Studio its a hls stream player it uses hls.js to play a stream and has remote controls and a little more things when i test it in the tizen studio emulator everything works but after i package it and add it to samsung seller the qa testers keep saying it infinite loads. What could be the problem?
This is the main.js

  var videoPlayer = document.getElementById("videoPlayer");
  videoPlayer.tabIndex = 0; // add tabindex to focus the element
  videoPlayer.requestFullscreen();

  var player = new shaka.Player(videoPlayer);

  player.configure({
    abr: {
      enabled: true
    }
  });

  var manifestUri = 'https://janus.xpbroadcasting.com:8443/dash/xptv1.mpd';

  player.load(manifestUri).then(function() {
    console.log('The video has now been loaded!');
    videoPlayer.requestFullscreen();
  }).catch(function(error) {
    console.error('Error code', error.code, 'object', error);
  });

  player.addEventListener('error', function(event) {
    console.error('Error code', event.detail.code, 'object', event.detail);
    console.log('A video playback error occurred.');
    if (event.detail.code === 6003 || event.detail.code === 6004 || event.detail.code === 6005) {
      console.log('The video failed to load due to a network error. Retrying...');
      showOfflineNotification();
      setTimeout(function() {
        player.load(manifestUri);
      }, 5000);
    }
  });

  function showOfflineNotification() {
    var offlineNotification = document.getElementById("offline-popup");
    offlineNotification.style.display = "block";
    videoPlayer.style.display = "none";
  }

  function showOnlineNotification() {
    var offlineNotification = document.getElementById("offline-popup");
    offlineNotification.style.display = "none";
    videoPlayer.style.display = "block";
    player.load(manifestUri).then(function() {
      console.log('The video has now been loaded!');
      videoPlayer.requestFullscreen();
    }).catch(function(error) {
      console.error('Error code', error.code, 'object', error);
    });
  }

  window.addEventListener("online", showOnlineNotification);
  window.addEventListener("offline", showOfflineNotification);

  if (navigator.onLine) {
    showOnlineNotification();
  } else {
    showOfflineNotification();
  }

  // Add event listeners to the buttons
  var playButton = document.getElementById("playButton");
  var pauseButton = document.getElementById("pauseButton");
  var stopButton = document.getElementById("stopButton");
  var forwardButton = document.getElementById("forwardButton");
  var backwardButton = document.getElementById("backwardButton");

  playButton.addEventListener("click", function() {
    player.play();
  });

  pauseButton.addEventListener("click", function() {
    player.pause();
  });

  stopButton.addEventListener("click", function() {
    player.pause();
    player.seek(0);
  });

  forwardButton.addEventListener("click", function() {
    var currentTime = player.getPlaybackRate();
    player.seek(currentTime + 10);
  });

  backwardButton.addEventListener("click", function() {
    var currentTime = player.getPlaybackRate();
    player.seek(currentTime - 10);
  });
  
//Register listeners for remote control buttons
  tizen.tvinputdevice.registerKey("MediaPlay", function() {
    player.play();
  });

  tizen.tvinputdevice.registerKey("MediaPause", function() {
    player.pause();
  });

  tizen.tvinputdevice.registerKey("MediaStop", function() {
    player.pause();
    player.seek(0);
  });

  tizen.tvinputdevice.registerKey("MediaFastForward", function() {
    var currentTime = player.getPlaybackRate();
    player.seek(currentTime + 10);
  });

  tizen.tvinputdevice.registerKey("MediaRewind", function() {
    var currentTime = player.getPlaybackRate();
    player.seek(currentTime - 10);
  });


//Add event listener to handle keyboard controls
  document.addEventListener("keydown", function(event) {
    if (event.target !== videoPlayer) return; // check if videoPlayer has focus
    switch (event.keyCode) {
      case 10009: // Return key
        window.history.back();
        break;
      case 415: // Play key
        if (player.isPaused()) {
          player.play();
        } else {
          player.pause();
        }
        break;
      case 413: // Stop key
        player.pause();
        player.seek(0);
        break;
      case 417: // Forward key
        var currentTime = player.getPlaybackRate();
        player.seek(currentTime + 10);
        break;
      case 412: // Backward key
        var currentTime = player.getPlaybackRate();
        player.seek(currentTime - 10);
        break;
      default:
        console.log("Unsupported key: " + event.keyCode);
    }
  });
});````

Create a distinct array in javascript

I want to distinct my array called “myCar” and list down the name of the car depend on their color.

I have this array..

let myCar = [
    {Name : 'Saab', Color : 'Red'},
    {Name : 'Volvo', Color : 'Green'},
    {Name : 'BMW', Color : 'Black'},
    {Name : 'Toyota', Color : 'Black'},
    {Name : 'Audi', Color : 'Red'},
];

I create a simple function called “distinctArray()” and it look like this..

function distinctArray(array) {
    let distinct = [];
    array.forEach((element) => {
        if (!distinct.includes(element.Color)) {
            distinct.push(element.Color);
        }
        let newElemVal = []
        newElemVal.push(element.Name)
        distinct.push(newElemVal)
        }
    );
    return distinct;
    }
let distinct = distinctArray(myCar);
console.log(distinct);

But the output is look like This

I just want to get the color of each cars and list the car in an array. So, i want it like this way..

Expected Output:

[   
    "Red"
        [ "Saab", "Audi" ]

    "Green"
        [ "Volvo" ]
        
    "Black"
        [ "BMW", "Toyota" ]
]

I’m not sure what is lacking with my code but is there an easiest way to get the exact data?

Thanks for your help. 🙂

When I initialize/call a function to create a dynamic grid from inside on ready it is breaking global selectors for grid items. How can i fix?

I initially copied parts of this code to create a dynamic grid, I don’t really understand why it’s written as it is, I believe it’s called as a declaration. I was able to get it working as desired with a static array with dummy data. When it came time to connect it to live site and I rearranged the code to initialize the function to create grid in the onLoad. When I did that it broke all of the global selectors for grid items, meaning event listeners are no longer recognized and I can’t access them globally in the document.

const myData = [
  {
    "Name":"Cabin A",
    "Sep 01":"1",
    "Sep 02":"2",
    "Sep 03":"TName",
    "Sep 04":"TName",
    "Sep 05":"4",
    "Sep 06":"G2 Name",
    "Sep 07":"G2 Name"
  },
  {
    "Name":"Camp B",
    "Sep 01":"G3 ",
    "Sep 02":"G3 ",
    "Sep 03":"G3 ",
    "Sep 04":"5",
    "Sep 05":"6",
    "Sep 06":"G4 ",
    "Sep 07":"G4 "
  },
  {
    "Name":"RV Site",
    "Sep 01":"7",
    "Sep 02":"G5 ",
    "Sep 03":"8",
    "Sep 04":"9",
    "Sep 05":"10",
    "Sep 06":"G6 ",
    "Sep 07":"G6 "
  }
]

var col = [];
for (var i = 0; i < myData.length; i++) {
  for (var key in myData[i]) {
    if (col.indexOf(key) === -1) {
      col.push(key);
    }
  }
}

const createGrid = () => {
  var c = 1;
  
  for(i=0;i<myData.length;i++){
  
    for(j=0;j<col.length;j++){
      let site = myData[i]

      var box = document.createElement('div')
      box.innerHTML += site[col[j]];
      box.className ="grid-item"
      var grid = document.getElementById('grid')
      grid.appendChild(box)

      box.id = c;
      box.draggable = true;

      box.style.gridColumn = ` ${j+1}/span 1`;
      c++;
    }
  
  }
}


createGrid(); // I need to call this from inside ready() 

function ready(){

    //createGrid();   
  
  /***  How can i call createGrid() from here and   */
  /*     access 'gridItems'  from other functions?    */
  

}

let gridItems = document.querySelectorAll(".grid-container .grid-item");

gridItems.forEach(function (item) {
  item.addEventListener("dblclick", handleit, false);
});

function handleit(){
  console.log('handled')
}
.grid-container {
  position: absolute;
  display: grid;
  grid-template-columns: repeat(auto, fit-content());
  grid-template-rows: repeat(auto, 20px);
}
.grid-item{
 cursor: move;
 align-items: center;
 border: 1px solid #000;
 padding: 2px;
}
        <body onload="ready();">
          <div class="grid-container" id="grid">
          </div>      
        </body>

Passport Nodejs – logout from previous sessions

sorry for silly question
I’m using passport for authentication purpose. I wanted to logout from previous sessions (be it on different browser or device) when user tries to login with new session.

I know I can user req.logout to log out but I’m not sure how to destroy all other sessions from db which my passport is creating while login.

Even if I manually delete them, I’m not auto logging out

The following is my passport config

const passport = require('passport'),
    LocalStrategy = require('passport-local').Strategy,
    User = require('../database/Schema').User,
    shortid = require('shortid');

passport.serializeUser( (user, cb) => {
    cb(null, user);
});

passport.deserializeUser( (obj, cb) => {
    cb(null, obj);
});

passport.use('localRegister', new LocalStrategy({
        usernameField: 'email',
        passwordField: 'password',
        passReqToCallback: true
    },
    (req, email, password, done) => {
        User.findOne({$or: [{email: email}, {username: req.body.username}]},  (err, user) => {
            if (err)
                return done(err);
            if (user) {
                if (user.email === email) {
                    req.flash('email', 'Email is already taken');
                }
                if (user.username === req.body.username) {
                    req.flash('username', 'Username is already taken');
                }

                return done(null, false);
            } else {
                let user = new User();
                user.email = email;
                user.password = user.generateHash(password);
                user.username = req.body.username;
                user.stream_key = shortid.generate();
                user.save( (err) => {
                    if (err)
                        throw err;
                    return done(null, user);
                });
            }
        });
    }));

passport.use('localLogin', new LocalStrategy({
        usernameField: 'email',
        passwordField: 'password',
        passReqToCallback: true
    },
    (req, email, password, done) => {

        User.findOne({'email': email}, (err, user) => {
            if (err)
                return done(err);

            if (!user)
                return done(null, false, req.flash('email', 'Email doesn't exist.'));

            if (!user.validPassword(password))
                return done(null, false, req.flash('password', 'Oops! Wrong password.'));

            return done(null, user);
        });
    }));


module.exports = passport;

The following is my user schema (I’m using mongodb)

let mongoose = require('mongoose'),
    bcrypt   = require('bcryptjs'),
    shortid = require('shortid'),
    Schema = mongoose.Schema;

let UserSchema = new Schema({
    username: String,
    email : String,
    password: String,
    stream_key : String,
});

UserSchema.methods.generateHash = (password) => {
    return bcrypt.hashSync(password, bcrypt.genSaltSync(8));
};

UserSchema.methods.validPassword = function(password){
    return bcrypt.compareSync(password, this.password);
};

UserSchema.methods.generateStreamKey = () => {
    return shortid.generate();
};

module.exports = UserSchema;

The following is my login route

const express = require('express'),
    router = express.Router(),
    passport = require('passport');

router.get('/',
    require('connect-ensure-login').ensureLoggedOut(),
    (req, res) => {
        req.logOut();
        res.render('login', {
            user : null,
            errors : {
                email : req.flash('email'),
                password : req.flash('password')
            }
        });
    });

router.post('/', passport.authenticate('localLogin', {
    successRedirect : '/',
    failureRedirect : '/login',
    failureFlash : true
}));

module.exports = router;

filter out a string number out of an array in typescript js

Trying to filter out a string number from and array in typescript.
Result should be [“apple”]

const arr =  ['1', '2', 'apple'];

const result = arr.filter((k) => parseInt(k) == k)
console.log('result = ', result)

https://www.typescriptlang.org/play?#code/MYewdgzgLgBAhgJwTAvDGBtA5ARiwGhiwCYCiA1AQQBkBVAUSwF0BuAWAChPRJYEBTCAFcANrDSIEAOgBmASzH8EACmUBrAJSoAfDAAOiCPwCSYKOq0o0m7uAggR-KSJABzZVgHCxqIoS+iUBpAA

How to parse a very deeply nested JSON file for saving into MongoDB

I am trying to save data from an old SOAP API from Escapia Property Manager using Node.js. I have managed to connect to the API and get the info sent back in XML format. I have no real experience with XML so I have converted it to JSON in node. Now here’s the really difficult part. The JSON data is highly nested. I’m talking to an absurd amount. I cannot for the life of me get this data to parse correctly to load it into MongoDB using Mongoose. I honestly do not know if I’m even heading down the right path with this and could really use some help in understanding the best way to handle this data.

Here’s the JSON file Unit-Response.json

When I run a parse on this file I get the following:

node app.js
{
  's:Envelope': {
    'xmlns:s': 'http://schemas.xmlsoap.org/soap/envelope/',
    's:Body': {
      'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
      'xmlns:xsd': 'http://www.w3.org/2001/XMLSchema',
      UnitDescriptiveInfoStream: [Object]
    }
  }
}

Any ideas of how to get all of this out of the file and into MongoDB?

nextJS: 403 error when fetch an api in getserversideProps

When fetch in getServerSideProps, it’s always return error 403(Forbidden)

Code

export const getServerSideProps : GetServerSideProps = async (ctx) => {
     const {uuid} = ctx.params;

     const res = await axios.get(
          `https://backend.gobot.id/api/v1/auth/forgot-password/${uuid}`
        );  
     console.log(res.status)
     return {
        props:{uuid}
      }

}

Return
AxiosError: Request failed with status code 403

But when i’am fetch it not inside getServerSideProps, and it’s not returning the error

I ask it to my backend, and he tells me that him friend need to configure a something whitelist in next config.

Any1 can help me to solve it? How can i fetch to an api in getServerSideProps()?

How to fetch an api in getServerSideProps that returning 403 error while when fetch it not at inside getServerSideProps.. Its Succesfull

getting `ClientConfigurationError: empty_url_error: URL was empty or null` when trying to pass headers via axiosinstance

Iam using a react appliation. I need to pass Bearer key in headers for axios call.

Iam using @azure-msal for authentication.

When trying to call the created axiosInstance., getting ClientConfigurationError: empty_url_error: URL was empty or null. at ClientConfigurationError.AuthError [as constructor] error.

Not sure what iam missing. Can you help me.. Below is the code Iam using

import axios from 'axios';
import { PublicClientApplication } from '@azure/msal-browser';
const getAxiosInstance = () => {
  const msalConfig = {
    auth: {
      clientId: process.env.REACT_APP_CLIENT_ID,
      authority: process.env.REACT_APP_AUTHORITY,
      redirectUri: window.location.origin,
    },
  };
  const msalInstance = new PublicClientApplication(msalConfig);
  const account = msalInstance.getAllAccounts()[0];
  console.log("Msal account new",account);
  const scopes = ["openid", "profile", process.env.REACT_APP_OAUTH_SCOPE_URL];
  const getAccessToken = async () => {
    const response = await msalInstance.acquireTokenSilent({
      scopes,
      account,
    });
    return response.accessToken;
  };
  const axiosInstance = axios.create({
    baseURL: process.env.REACT_APP_BASEURL_PROJECT,
  });
  axiosInstance.interceptors.request.use(async (config) => {
    const token = await getAccessToken();
    config.headers.Authorization = `Bearer ${token}`;
    return config;
  });
  return axiosInstance;
};
export default getAxiosInstance();

WordPress: Using JavaScript to insert onclick function and img src set to change image by ID?

In WordPress and Woocommerce, I am attempting to apply javascript within the child theme functions.php, so if a user clicks a specific product attribute color swatch, it will change a preview image (shown below the swatch selectors) with a specific ID to a new image source URL. I have very limited javascript knowledge and am fumbling my way through this.

I was able to get one single swatch (Black) to change the target image, but I cannot figure out how to repeat the command for the other swatches. Here is what I have so far:

add_action( 'woocommerce_before_single_product', 'bluetera_swatch_onclick' );


function bluetera_swatch_onclick() { ?>


    <script type='text/javascript'>
        var input = document.getElementById("ecorigidswatches_Black");
        input.onclick = function swapproductimg() {
        document.getElementById('selected-swatch').src="https://www.laserfelt.com/wp-content/uploads/2021/06/BlackHexagon.jpg";

}

    </script>
    <?php
}

Here is a link to the product page in question:

https://www.laserfelt.com/product/hexagon-acoustic-wall-tiles/

I was also trying to create a conditional statement that would only execute this function if the user was viewing a product in a specific category. But I would not figure out how to do that either. All of my attempts failed. We have different sets of color swatches and I am trying to figure out a way to have the script load only when it is needed.

I am also wondering if this would be the most efficient way to achieve the desired result, or if there is a better way that would improve page load speeds? I am limited to working with the existing plugin that creates these product swatch options. That is why I am having to insert the onclick function in a roundabout way.

We do not want to use any of the pre-existing swatch plugins that only changed the main product image.

I would really appreciate some pointers, tips and direction. Thanks!

when i run my React Native app it shows me this message

info Starting JS server…
info Installing the app…

FAILURE: Build failed with an exception.

  • What went wrong:
    A problem occurred configuring project ‘:react-native-gradle-plugin’.

java.util.concurrent.ExecutionException: org.gradle.api.GradleException: Failed to create Jar file C:Usersswabi.gradlecachesjars-9196b729407d7fbb2907378f4b4c34b5akotlin-gradle-plugin-1.6.10.jar.

  • Try:

Run with –stacktrace option to get the stack trace.
Run with –info or –debug option to get more log output.
Run with –scan to get full insights.

BUILD FAILED in 3m 43s

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

  • What went wrong:
    A problem occurred configuring project ‘:react-native-gradle-plugin’.

java.util.concurrent.ExecutionException: org.gradle.api.GradleException: Failed to create Jar file C:Usersswabi.gradlecachesjars-9196b729407d7fbb2907378f4b4c34b5akotlin-gradle-plugin-1.6.10.jar.

  • Try:

Run with –stacktrace option to get the stack trace.
Run with –info or –debug option to get more log output.
Run with –scan to get full insights.

BUILD FAILED in 3m 43s

at makeError (C:UsersswabiAwesomeProjectnode_modules@react-native-communitycli-platform-androidnode_modulesexecaindex.js:174:9)
at C:UsersswabiAwesomeProjectnode_modules@react-native-communitycli-platform-androidnode_modulesexecaindex.js:278:16
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async runOnAllDevices (C:UsersswabiAwesomeProjectnode_modules@react-native-communitycli-platform-androidbuildcommandsrunAndroidrunOnAllDevices.js:82:7)
at async Command.handleAction (C:UsersswabiAwesomeProjectnode_modules@react-native-communityclibuildindex.js:108:9)

info Run CLI with –verbose flag for more details.

(jsPsych) How can I get access to the user response before the trial finishes?

I have a html-button-response trial that shows images and takes user input from clicking the button. I want to know what response the user gave BEFORE the trial ends. I can’t find this anywhere in the docs or issues. I know there is a way to get it from the data object passed to certain callbacks but on_load does not have that. I need the response so that I can play audio feedback after click. The way I am handling this is using the on_load trial callback and adding a click event to the buttons as soon as the trial loads. The callback for the click event is where I need access to the response.

Here is my code to give an idea of what I am trying to do:

on_load: () => {
      const buttonsGroupElement = document.getElementById("jspsych-html-button-response-btngroup")
      const buttonsContainerList = buttonsGroupElement.children
      const containerListArray = Array.from(buttonsContainerList)


      containerListArray.forEach((container) => {
        const button = container.children.item(0)

        button.addEventListener("click", () => {

          const lastTrialIdx = jsPsych.data.getLastTrialData().trials[0].trial_index + 1

          const prevResponse = jsPsych.data.allData.trials[lastTrialIdx]

          
         if (prevResponse) {
           // play correct audio
         } else {
           // play incorrect audio
         }

          // buffer to give enough time for the audio to play
          setTimeout(() => jsPsych.finishTrial(), 390)
        })
      })

I have tried different ways of getting the trial data but can’t seem to find a way to get it. I thought the approach above would work but although jsPsych.data.allData.trials is all the current trials, when I try accessing the current one it says it is undefined.

How can I get the user response after click?