How to save data on array in localStorage – TypeError: push is not a function

I am trying to push player data (object) in a array, then save into localStorage, but I can’t get it working even if I initialize the array. On the first run I got the data, but on the next runs the array is not recognized.

Does anyone know what is going on?

  function handleRanking() {
    console.log('run function');
    let prevRanking = localStorage.getItem('ranking');
    if (prevRanking === null) {
      console.log('null value');
      prevRanking = [];
    }
    const player = {
      name,
      score: total,
      picture: gravatarEmail,
    };
    if (Array.isArray(prevRanking)) {
      prevRanking.push(JSON.stringify(player));
      localStorage.setItem('ranking', prevRanking);
    } else {
      console.log('not an array');
    }
  }

“Objects are not valid as a React child”

    </div>
    {
    data.map(function(movie){
    const title = movie.title
    const id = movie.id
     
    return <Move key={id} title={title}  />
})}
    </div>
  );
the Object im trying to use {
    "adult": false,
    "backdrop_path": "/iQFcwSGbZXMkeyKrxbPnwnRo5fl.jpg",
    "genre_ids": [
        28,
        12,
        878
    ],
    "id": 634649,
    "original_language": "en",
    "original_title": "Spider-Man: No Way Home",
    "overview": "Peter Parker is unmasked and no longer able to separate his normal life from the high-stakes of being a super-hero. When he asks for help from Doctor Strange the stakes become even more dangerous, forcing him to discover what it truly means to be Spider-Man.",
    "popularity": 8450.164,
    "poster_path": "/1g0dhYtq4irTY1GPXvft6k4YLjm.jpg",
    "release_date": "2021-12-15",
    "title": "Spider-Man: No Way Home",
    "video": false,
    "vote_average": 8.4,
    "vote_count": 8021
}

im trying get access properties of the object for example title but im getting the error “Objects are not valid as a React child”

how to match one or more slashes

i’ve this regex expression

\(?!.*d|s|w|D|S|W|b|[|]|^|$|.|||?|*|+|{|}|(|))

i want that when doing this: \s,
it will not match anything.

but when doing this: \m
it will match every slash () separately.

i hope that you will understand, it was a bit hard to explain.
i’ve tried word boundaries and some examples here in stackoverflow but i found nothing…

TypeError: ko.applyBindings is not a function in OJET

Below is my HTML code to open oj-dialog

<div id="dialogWrapper">
    <div style="display:none" id="modalDialog1" title="Modal Dialog" data-bind="ojComponent:{component: 'ojDialog',
                                 initialVisibility: 'hide',
                                 open: dialogOpen,
                                 close: dialogClose,
                                 rootAttributes: {
                                   class: 'animate'
                                 }}">
      <div class="oj-dialog-body">
        The dialog window can be moved, resized and closed with the 'x' icon.
        Arbitrary content can be added to the the oj-dialog-body and oj-dialog-footer sections.
      </div>
      <div class="oj-dialog-footer">
        <button id="okButton" data-bind="click: closeDialog,
                                           ojComponent: {component: 'ojButton',
                                                         label: 'OK'}"> </button>
      </div>
    </div>
    <button id="buttonOpener" data-bind="click: openDialog,  
                                         ojComponent: {component: 'ojButton',
                                                       label: 'Open Modal Dialog'}"></button>

  </div>

Below is my corresponding js code :

define([‘require’, ‘exports’, ‘knockout’, ‘ojs/ojbootstrap’, ‘ojs/ojknockout’, ‘ojs/ojbutton’, ‘ojs/ojdialog’],
function(ko, oj, $) {
‘use strict’;

var ViewModel = function() {
var self = this;

self.openDialog = function() {
  $("#modalDialog1").ojDialog("open");
};

self.closeDialog = function(data, event) {

        // attempt fadeOut with jQuery
  $(event.target)
    .closest(".oj-dialog.animate")
    .fadeOut(function() {
      console.log("faded out", this);
      $("#modalDialog1").ojDialog("close");
    });
  };

self.dialogOpen = function(event, ui) {
  $(event.target)
    .closest(".oj-dialog.animate")
    .addClass("fully-opaque");
};

self.dialogClose = function(event, ui) {
  $(event.target)
    .closest(".oj-dialog.animate")
    .removeClass("fully-opaque");
};

};

ko.applyBindings(new ViewModel());
});


When I run this code I am getting "ko.applybindings is not a function" error. Can Anyone see where its going wrong.

JavaScript: how to limit the number of time a button is clicked in django and JavaScript

i want to implement how to limit the number of time a button is clicked in django then send the user to the login page. To be more clear with my question, there is a download button and users can download pdfs when they are not logged in, now i want the max download to be 5 before a user is then redirect to the login or maybe register page so they can continue downloading.
I tried this simple javascript code to do it but what is does it just increment the number when a button is clicked i do not really know how check if it’s upto five click and then redirect.

<script type="text/javascript">
        var count = 0;
        var btn = document.getElementById("btn");
        var disp = document.getElementById("display");
  
        btn.onclick = function () {
            count++;
            disp.innerHTML = count;
            disp.save;
        }
    </script>
<button id="btn">Click here to download </button>
<span id="display">0</span>Clicked

any more information needed? i available to provide it

Fill out an autotable with a limited number of rows and additional columns

I am trying to create a table with autotable so I can explain the meaning of some abbreviations I have used before. The data comes from a database but let’s say that it is like this once it’s fetched:

const subjectMap = {ENG:'english', SPA:'Spanish', HIS:'History', SCI:'Science', ...}

As I need to get the key in a column and the value in the following column I did the following:

var tempRows = []
for (const [key, value] of Object.entries(subjectMap)) {
   var temp = [key, value];
   tempRows.push(temp)
   }
    
   doc.autoTable({
     body: 
     tempRows
   });

That gives me a table with two columns and as many rows as subjects I have in the map, however I would like to have just two rows and position the following subjects in additional columns. The result should be something like this:

           COLUMN1         COLUMN2         COLUMN3        COLUMN4
ROW1        ENG             English         HIS            History
ROW2        SPA             Spanish         SCI            Science

Maybe I could get to do it not using autotable and just using the doc.addtext in jspdf. I don’t need any formatting or lines, just the explication for each abbreviation and in order to save space I want them filling out the horizontal page like that.

Thank you.

Testing axios.create() instance with jest

I tried many solution from this task. I want testing axios instance api call without any libralies (jest-axios-mock, moaxios, msw, etc). I hope it’s possible, because i succeeded testing simple axios call ( axios.get / axios.post without .create )
The main problem comes i tried testing axios instance call, i collides with three main errors on different attempts.

1 axios_instance_1.axiosInstance is not a function

2 Cannot read property ‘then’ of undefined

3 Cannot read property ‘post’ of undefined

I get this when i try bypassing module mock ( jestjs.io/docs/bypassing-module-mocks )

My last attempt looked like this

axios-instance.ts

import axios from "axios";
export const axiosInstance = axios.create({
    headers: {'X-Custom-Header': 'foobar'}
})

api.ts

import { axiosInstance } from "../instancec/axios-instance";
export const axiosInstanceCounter = () => {
  return axiosInstance({
    method: 'post'
  }).then((data) => {
    console.log(data)
  })
}

axios.test.ts

import { axiosInstanceCounter } from '../features/api/axiosTest';
import { axiosInstance } from '../features/instancec/axios-instance';
import axios, { AxiosResponse } from 'axios';

jest.mock('../features/instancec/axios-instance', () => ({
   const instance = {
     create: jest.fn(),
   };
   return jest.fn(() => instance);
}));

it('Axios instance standart test', async () => {
    (axiosInstance.post as jest.Mock).mockResolvedValueOnce(() =>
      Promise.resolve(),
    );
    await axiosInstanceCounter();
    expect(axiosInstance).toBeCalledTimes(1);
});

And last error i receive it is Cannot read ‘post’ of undefined. Create mocks file in folder mocks and export from there also doesn’t help.
I don’t quite understand why it happens and I’ll be very thankful any hint, i also tried option with jest.spyOn but this failed.

How to use same funtion for 2 different variable

Have to use same function with two different variable with querySelector attached to the variable. Following is the javascript.

var productLink = document.querySelector('.products-link');
var productOffcanvas = document.getElementById('offcanvasProducts')

productOffcanvas.addEventListener('show.bs.offcanvas', function () {
    element.classList.toggle('active');
})
productOffcanvas.addEventListener('hide.bs.offcanvas', function () {
    productLink.classList.toggle('active');
})


var solutionsLink = document.querySelector('.solutions-link');
var solutionsOffcanvas = document.getElementById('offcanvasSolutions')

solutionsOffcanvas.addEventListener('show.bs.offcanvas', function () {
    solutionsLink.classList.toggle('active');
})
solutionsOffcanvas.addEventListener('hide.bs.offcanvas', function () {
    solutionsLink.classList.toggle('active');
})

How to console log in terminal and write in file at the same time with Pino and Express.js

I have this simple function that I created to log whatever happens in my code:

const pino = require('pino')

module.exports = pino({
  transport: {
    target: "pino-pretty",
    options: {
      translateTime: "SYS:dd-mm-yyyy HH:MM:ss",
      ignore: "pid,hostname",
      destination: './logs/logs.txt'
    }
  }
})

The problem with destination. If this option is, pino will write everything in file, not in console, if there is not, will print in console, but not in file. I want to print in console and write logs at the same time.

Is this possible?

Getting “Can’t find variable: Highcharts” error when injecting highchart html & JS inside iframe using javascript

Getting Can’t find variable: Highcharts” when I am injecting highchart js in iframe.

Requirement –
I need to create dynamic highchart boxes where we I can copy html/js/css content from high chart fiddle (as given in the highchart reference below) and can paste it in our application textareas (input for html/css/js).

Expected behavior – highchart should be visible in the iframe.

Test where I am getting error
“https://jsfiddle.net/6hwmx2ej/19/”

highchart reference
“https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/line-basic”

Clear the history of Magnific popup and show the first image I opened

I’m looking for a way to change the type of Magnific Popup and then change it back.
In the html below, when I open Magnific poppup, I can see the first.svg.
When I click on the a in the .each-link to show the image or youtube video, when I close and re-open the popup, I do not see the first.svg, I see the image or youtube video.
Is there a solution?

<div id="modal" class="modal-content mfp-hide">
  <a href="#!" class="overlay"></a>
  <div class="modal-wrapper">
    <div class="modal-contents">
      <div class="modal-content">
      <button class="modal-close">✖︎</button>
        <div class="each-link">
           <a class="link image" href="/test/" data-src="test.jpg"><img src="image.svg"></a>
          <a class="link video" data-type="video" data-src="https://www.youtube.com/watch?v=mCaIkrE861A"><img src="youtube.svg"></a>
        </div>
        <div class="content-image"><img src="first.svg"></div>
        <!-- data-src are retrieved from the custom fields-->
      </div>
    </div><!-- .modal-contents -->
  </div><!-- .modal-wrapper -->
</div>
//popup
jQuery(function ($){
    $('.popup-modal').magnificPopup({
        type: 'inline',
        preloader: false,
        modal: true,
        callbacks: {
            open: function () {
                $.magnificPopup.history.pushState(null,null,location.href);
            },
            close: function() {
                $.magnificPopup.instance.popupsCache = {}; // delete all templates
            },
            afterClose: function(){
                $.magnificPopup.instance.popupsCache = {}; // delete all templates
        }
        }
    });
    $(document).on('click', '.modal-close', function (e) {
        e.preventDefault(); 
        $.magnificPopup.close();
        location.reload();
    });
});


(function($){$( document ).on( 'click', '.each-link a', function( e ){
  e.preventDefault();
  var src = $(this).data('src'),
      type = $(this).data('type'),
      target = $(this).parent().parent().children('.content-image');

  if( type === 'video' ){
    const regex = /^((?:https?:)?//)?((?:www|m).)?((?:youtube.com|youtu.be))(/(?:[w-]+?v=|embed/|v/)?)([w-]+)(S+)?$/gm;
    src = src.replace(regex, `$5`);
    target.html( '<iframe src="https://www.youtube.com/embed/' + src + '">');
    target.addClass( 'embed-video' );
    target.removeClass( 'embed-comic' );
  } else {
    target.html( '<img src="' + src + '">' );
    target.removeClass( 'embed-video' );
    target.addClass( 'embed-comic' );
  }
  
});})(jQuery);

There’s something wrong with my shunting yards algorithms

I got some problem on working with shunting yards algorithm : I use it to parse an equation then use that equation to draw an graph, but somehow it’s parsing x^2-0.5x+1 to -0.5x+1, is there anyways to fix that
Here the link to the test code : https://codepen.io/Inasaya-Flanderin/pen/ExbbgQm
This is the code part:

function parse(rpn) {
    let stack = [];

    Array.from(rpn).forEach((t) => {
        let tr = null;
        if (isNumber(t) || isVariable(t)) {
            tr = genNode(t, false);
        } else {
            if (Object.keys(binary_functions).includes(t)) {
                tr = genNode(binary_functions[t], true, false);

                let a = stack.pop();
                let b = stack.pop();

                if (typeof a === 'number') {
                    tr.right = genNode(a, false);
                } else {
                    tr.right = a;
                }

                if (typeof b === 'number') {
                    tr.left = genNode(b, false);
                } else {
                    tr.left = b;
                }
            } else if (Object.keys(unary_functions).includes(t)) {
                tr = genNode(unary_functions[t]);

                a = stack.pop();

                if (typeof a === 'number') {
                    tr.left = genNode(a, false);
                } else {
                    tr.left = a;
                }
            }
        }
        tr.name = t;
        stack.push(tr);
    });

    return stack.pop();
}

function eval(tree) {
    if (tree.func) {
        if (tree.unary) {
            return tree.val.eval(eval(tree.left));
        } else {
            return tree.val.eval(eval(tree.left), eval(tree.right));
        }
    } else {
        if (constant_names.includes(tree.val)) {
            return constants[tree.val];
        } else if (varnames.includes(tree.val)) {
            return variables[tree.val];
        } else {
            return tree.val;
        }
    }
}

How can I transfer data sent from frontend to backend to another frontend? – NODE.JS [closed]

I transferred the data of an object from frontend to backend using WS, which I want to display on another frontend page.
Can I create another WS connection on the same port?

I used this WS:

const  app  =  expressz ( ) ;
const  szerver  =  igényel ( "http" ) . CreateServer ( alkalmazás )
const  WebSocket  =  megköveteli ( "ws" )

const  wss  =  új  WebSocket . Szerver ( { szerver : szerver } ) ;

Esetleg ha egy másik változóval hozom létre?
Köszönöm a segítséget!

How to decrypt text in js?

Encrypted text:
“daa82089dea872c56ae29cc7fae7a113f73d1f693d392462a77059a25b622266505bc2487575524b1c7fc1a953b3e66da4b56b3e1c88c8350b8ca94805603e47d04c8836b3a187a8cb3270635c1397984c7e49195efc99889072be7cf2230b835cef55f2032510319804874757b1d5aa”

Decrypt key: “e9644439636b8e794ff8c82293bf182c”