Why isn’t my calculator in JavaScript equating?

I’m making a calculator in JS, but it just keeps giving me NaN. I don’t understand why. Whenever I click equal, it gives me NaN. I can see that the numbers I clicked are in the log, however, when I equate them, it says NaN (op) Nan. Despite the previous acknowledgement of the numbers being clicked.

I have tried multiple things, including adding and removing console.log in different places, changing parseInt to parseFloat, then back to parseInt, and looking at other solutions, but none of them really worked for me.
Here’s my JS, and my HTML in case it matters.

var $screen = $("#screen");
var $number = $(".number");
var $clearnum = $(".clearnum");
var num1 = null;
var num2 = null;
var currentNumber = 1;
var op = $("#operator");
var answer = (num1, op, num2);
var click = 0;

function findAnswer() {
  num1 = parseInt(num1);
  num2 = parseInt(num2);
  console.log(num1, op, num2);
  if (op == "+") {
    answer = num1 + num2;
  }
  if (op == "-") {
    answer = num1 - num2;
  }
  if (op == "*") {
    answer = num1 * num2;
  }
  if (op == "/") {
    answer = num1 / num2;
  }
  num1 = answer;
  num2 = null;
  currentNumber = 1;
}

function more() {
  if (click > 8) {
    click = click - 5;
  }
  if (currentNumber == 2) {
    findAnswer();
    $screen.empty();
    $screen.append(num1);
  }
  currentNumber = 2;
}

function returnPractice() {
  if (click > 8) {
    return;
  }

  alert("This will never show if click is greater than 8.");
}

$number.on('click', function() {
  click++;
  returnPractice();
  var numberPressed = $(this).html();
  $screen.append(numberPressed);
  console.log(numberPressed);

  if (currentNumber == 1) {
    if (num1 = null) {
      num1 = numberPressed;
    } else {
      num1 = num1 + numberPressed;
    }
  }
  if (currentNumber == 2) {
    if (num2 == null) {
      num2 = numberPressed;
    } else {
      num2 = num2 + numberPressed;
    }
  }
});

$("#plus").on('click', function() {
  more();
  $screen.append("+");
  op = "+"
  currentNumber++;
});

$("#minus").on('click', function() {
  more();
  $screen.append("-");
  op = "-"
  currentNumber++;
});

$("#times").on('click', function() {
  more();
  $screen.append("*");
  op = "*"
  currentNumber++;
});

$("#divided").on('click', function() {
  more();
  $screen.append("/");
  op = "/"
  currentNumber++;
});

$clearnum.on('click', function() {
  $screen.empty();
  num1 = null;
  num2 = null;
  currentNumber = 1;
  click = 0;
});

$("#equal").on('click', function() {
  {
    $screen.append("=");
    findAnswer();
    a = answer;
    answer = a.toFixed(1);
    console.log(isNaN("answer"));
    if (click > 8) {
      $screen.empty();
      var answerLength = answer.toString;
      click = answerLength.length;
    }
    $screen.append(answer);
    console.log(answer);
  }
});
<html>

<head>
  <title>Calculator</title>
  <link href="resources/CSS/style.css" rel="stylesheet" type="text/css">
</head>

<body>
  <h1>Calculator</h1>
  <div id="calculator">
    <div id="screen"></div>
    <div id="buttons">
      <div id="numbers">
        <div class="number" id="num1">1</div>
        <div class="number" id="num2">2</div>
        <div class="number" id="num3">3</div>
        <div class="number" id="num4">4</div>
        <div class="number" id="num5">5</div>
        <div class="number" id="num6">6</div>
        <div class="number" id="num7">7</div>
        <div class="number" id="num8">8</div>
        <div class="number" id="num9">9</div>
        <div class="number" id="num0">0</div>
        <div class="equal" id="equal">=</div>
        <div class="clearnum" id="clear">C</div>
      </div>
      <div id="operators">
        <div class="operator" id="plus">+</div>
        <div class="operator" id="minus">-</div>
        <div class="operator" id="times">*</div>
        <div class="operator" id="divided">/</div>
      </div>
    </div>
  </div>
  <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
  <script type="text/javascript" src="resources/js/script.js"></script>
</body>

</html>

Here’s a screenshot of the issue too.

a screenshot of my project

Any help would be appreciated.

Trying to get javascript variables on one php page to show in another using WYSIWYG Web Builder 19

I have a javascript in the head of the index page and this function stores the variables from the functions in localstorage:

<script type="text/javascript">

function storeGlobals() {

localstorage.setItem("name", name.value)
localstorage.setItem("current_age", current_age.value)
localstorage.setItem("retirement_age", retirement_age.value)
localstorage.setItem("base_salary", base_salary.value)
localstorage.setItem("emailid", emailid.value)

localstorage.setItem("FEGLI_BASIC_LIFETIME_COST", "$"+total_FEGLI_BASIC_LIFETIME_COST)
localstorage.setItem("fegli_opa_cost", "$"+total_fegli_opa_cost)
localstorage.setItem("UB_PERMANENT_LIFETIME_COST", "$"+total_UB_PERMANENT_LIFETIME_COST)
localstorage.setItem("fegli_opb_cost", "$"+total_fegli_opb_cost)
localstorage.setItem("UB_TERM_COST", "$"+total_UB_TERM_COST)
localstorage.setItem("Estimated_Total_FEGLI_Lifetime_Cost", "$"+total_Estimated_Total_FEGLI_Lifetime_Cost)

localstorage.setItem("total_savings", "$"+total_savings_final)
localstorage.setItem("regular_finalresult", "$"+regular_total_savings_final)
localstorage.setItem("regular_fegli_basic_coverage", "$"+FEGLI_BASIC_COVERAGE_AMT_report_final)
localstorage.setItem("regular_fegli_opa", "$"+FEGLI_OPA_AMT_report_final)
localstorage.setItem("regular_fegli_opb", "$"+"$"+FEGLI_OPB_AMT_report_final)

}
</script>

Then, in another page (results.php) I have the following in the head tags:

<script type="text/javascript">

function readGlobals() {

localstorage.getItem("name")
localstorage.getItem("current_age")
localstorage.getItem("retirement_age")
localstorage.getItem("base_salary")
localstorage.getItem("emailid")

localstorage.getItem("FEGLI_BASIC_LIFETIME_COST")
localstorage.getItem("fegli_opa_cost")
localstorage.getItem("UB_PERMANENT_LIFETIME_COST")
localstorage.getItem("fegli_opb_cost")
localstorage.getItem("UB_TERM_COST")
localstorage.getItem("Estimated_Total_FEGLI_Lifetime_Cost")

localstorage.getItem("total_savings")
localstorage.getItem("regular_finalresult")
localstorage.getItem("regular_fegli_basic_coverage")
localstorage.getItem("regular_fegli_opa")
localstorage.getItem("regular_fegli_opb")

}
</script>

I am calling this function as a onload event.

Does this look correct? So far, it’s not working. If you are familiar with WYSIWYG Web Builder, what would be the correct way to do this. Any help is appreciated.

Mike

Compare 2 large tables of objects by string similarity of one of their property in Javascript

I would like to compare 2 large tables of objects from two different databases:

  • an array of 2700 objects
  • an array of 1800 objects

Each object is a scientific publication with 30 properties. The aim is to identify duplicate titles. But as the titles have not been entered in exactly the same way in the two databases, I want to make my comparison on the publication title using the Levenshtein distance implemented in this answer: Compare Strings Javascript Return %of Likely

I’ve tested two ways of doing this:

  • using Map: I store each array in 2 different maps, using the publication title as the key. Then I loop through first map, then I loop through second map, and execute a Levenshtein test on the 2 keys.
  • using only titles: I create 2 arrays of publication titles. Then I loop through first array, then I loop through second array, and execute a Levenshtein test on the 2 elements.

Both processes are extremely time-consuming. Do you think there’s a more efficient way of doing this?

Thank you very much for your answers.

500 | Internal Server Error after deploying Next.js app and seeing browsecSiteContentScript: data is not for auth in the console

I deployed my Next.js (14) application successfully, but when I navigate to the website from another site, I encounter a 500 | Internal Server Error.
enter image description here
Additionally, in the browser console, I see the following message:enter image description here

I’ve checked the server logs, and there’s no specific error related to the deployment process. The application works fine when accessing it directly (e.g., typing the URL), but when coming from other websites, the error occurs. And If I reload the page then it work fine.

File Structure:

enter image description here

Questions:

  1. What could be causing this 500 | Internal Server Error when
    navigating from another website?
  2. Could the browsecSiteContentScript: data is not for auth message be related to
    a browser extension, or is it something in my Next.js configuration?

Any help would be appreciated. Thanks!

How to activate a nested, named router outlet

Starting on a fresh Angular 17 project (+SSR/SCSS but shouldn’t have any impact on the issue), this is my bootstrapped app.component.html with the default outlet:

<h1>App Component</h1>
<router-outlet />

And this is the child.component.html with the nested, named outlet:

<p>childcomponent works!</p>
<router-outlet name="userProfile"></router-outlet>

A third “demo” component should be rendered in this named outlet. This is my router setup:

export const routes: Routes = [{
  path: "demo",
  component: DemoComponent,
  outlet: "userProfile"
}, {
  path: "global/en",
  component: ChildComponent,
}];

I can call localhost:4200/global/en(userProfile:demo) without any error message but the DemoComponent is never rendered inside the named outlet. Putting the demo route in the “children” array of the main route doesn’t work either. When accessing the nested outlet from the angular dev tools, it throws an “Outlet not activated” error. What am I missing here ?

Have I learned the right skills to become a Fullstack web dev? [closed]

I am a beginner programmer who is studying to become a Fullstack web developer.

And I want to ask whether some of the skills I have learned are right to make me a beginner Fullstack web developer.

I made the website into several sections for study,
with the first part, namely FE, I studied reactJS and nextJS as the framework that I will use to create FE websites, and the second is the connector between FE and BE, I studied socket.io, because I was curious about realtime systems, and the third is BE, I studied nodeJS and expressJS as the framework that I will use to create BE, and the fourth is the connector between BE and DB, I use the module provided by the DB provider, and the fifth is DB, I use postgresql as the DB that I will use.

Is all that enough for me to become a beginner Fullstack web developer?

I am studying web development self-taught and I really need advice to develop my skills.

Issue: Missing Styles and Improper Font Loading with html2canvas

I am encountering an issue while using html2canvas in my React project. When I try to capture screenshots of a specific page, some styles are missing, and fonts are not rendering properly in the generated image. The output screenshot doesn’t match the original page design. For example, in the generated image, I noticed:

Font styles are incorrect compared to the original page (fonts are not properly loaded).
Certain styles, such as specific colors and visual elements, are either missing or improperly rendered.
I have attached a comparison of the original design and the output generated by html2canvas for reference.

[Original Design:]

enter image description here

[html2canvas Result:]

enter image description here

Expected Behavior: The generated image should match the original design with all styles and fonts correctly applied.

Actual Behavior: The image produced by html2canvas lacks certain styles, and fonts are replaced by default ones, not reflecting the actual fonts used in the project.

How Fix JavaScript Limitations on WebBrowser? [closed]

I developed a web application, but it’s not working well on Samsung TVs, specifically in their WebBrowser, which has limited JavaScript support. I need to find a way to simulate this browser on my computer to identify its limitations or explore alternative solutions to fix the issue.

Browser:

enter image description here

How to do a replace using regex of a sentence with variable content in the middle and the end containing “/” [duplicate]

I’m having difficulty replacing content where I only know the beginning and end, where it’s also a problem to replace due to (“/”). This is the line of code I need to remove.

<div class="inputIcon -lft"><svg><use href="**variable content**"></use></svg></div>

.replaceAll(/<div class="inputIcon -lft">(.*)div>/g,'')

Custom Layers disappears after showing up briefly

I am working on a project where I need to display some dynamic content on a leaflet map basically a infotainment website. A simple version of the thing I am trying to do is display a custom layer where each tile has a different color. The code attached below shows the custom tiles but then it disappears I am not sure what might be the issue for this behaviour

EDIT As suggested by @mplungjan changing order seemed to solve the issue I am able to attain my expected result of only select tiles being shown over base OSM layer

function getRandomBoolean() {
    return Math.random() < 0.5;
}
var CustomGridLayer = L.GridLayer.extend({
  createTile: function(coords) {
    var size = this.getTileSize();
    console.log('--size--', size)

    var tile = L.DomUtil.create('canvas', 'leaflet-tile');

    tile.width = size.x;
    tile.height = size.y;
    var ctx = tile.getContext('2d');

    ctx.fillStyle = getRandomColor();
    ctx.fillRect(0, 0, size.x, size.y);

    // Add text to the tile
    ctx.fillStyle = 'white';
    ctx.font = 'bold 16px Arial';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    ctx.fillText('Tile', size.x / 2, size.y / 2);

    if(!getRandomBoolean()) {
        tile.style.display = 'none';
    } 
    return tile;
  }
});

function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

var customLayer = new CustomGridLayer({
  maxZoom: 18,
  tileSize: 256
});

var map = L.map('map', {
  center: [51.505, -0.09],
  zoom: 13
});



L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);

map.addLayer(customLayer);
#map {
  height: 100vh;
}
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>Leaflet Example</title>
  <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
</head>

<body>
  <div id="map"></div>
</body>

</html>

Refactor AWS cdk stack into multiple smaller stacks

I am running up against the resource limit in my current cdk stack and need to refactor into a smaller stack. I want to do so without decoupling existing resources. This is especially true of my databases.

My current stack deploys one vpc containing a bastion host, an api gateway and corresponding lambda, a few dynamodb tables, and a neptune database, and configures all the necessary permissions. The api gateway in particular is eating up my entire resource limit.

To solve this issue, I want to refactor out pieces of my stack into a smaller stack. The resources declared in the refactored stacks (currently LambdaStack and ApiGatewayStack) are declared identically to the resources in the existing mono-stack. The refactored top level stack is shown below:

export class MyStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: MyStackProps | any) {
    super(scope, id, props);

    dotenv.config();

    const { deploymentEnvironment } = props || { deploymentEnvironment: 'dev' };
    const isDev = deploymentEnvironment === 'dev';

    const vpcId = `NeptuneVPC${isDev ? 'Dev' : 'Prod'}`;
    const vpc = new ec2.Vpc(this, vpcId, {
      maxAzs: 2,
      // subnetConfiguration: [
      //   {
      //     cidrMask: 24,
      //     name: 'public',
      //     subnetType: ec2.SubnetType.PUBLIC,
      //   },
      //   {
      //     name: 'private',
      //     subnetType: ec2.SubnetType.PRIVATE_WITH_EGRESS,
      //   },
      // ],
    });

    const bastionName = `NeptuneBastionHost${isDev ? 'Dev' : 'Prod'}`;
    const bastionHost = this.createBastionHost(
      vpc,
      bastionName,
      `key-pair-neptune-bastion-${isDev ? 'dev' : 'prod'}`,
    );

    const lambdaStack = new LambdaStack(this, 'LambdaStack', {
      deploymentEnvironment,
      vpc,
    });

    const apiGatewayStack = new ApiGatewayStack(this, 'ApiGatewayStack', {
      deploymentEnvironment,
      vpc,
      lambdaStack,
    });

    const s3PublicBucket = new s3.Bucket(this, `my-${isDev ? 'dev' : 'prod'}-images`, {
      blockPublicAccess: new s3.BlockPublicAccess({
        blockPublicAcls: false,
        blockPublicPolicy: false,
        ignorePublicAcls: false,
        restrictPublicBuckets: false,
      }),
      objectOwnership: s3.ObjectOwnership.OBJECT_WRITER,
    });

    // S3
    s3PublicBucket.grantPublicAccess();
    s3PublicBucket.grantWrite(lambdaStack.mainLambda);
    s3PublicBucket.grantPutAcl(lambdaStack.mainLambda);

    // Dynamo, Neptune, etc...

I’m particularly worried about orphaning or deleting existing resources, so I was wondering:

  1. Will the resources I’ve refactored to their own stack be deleted and redeployed? My instinct is yes.
  2. Will the resources that I’d left in the top level stack be left alone? This piece is especially important because they represent all my core databases.
  3. If I wanted to move the stateful resources (databases and buckets) to their own stacks without deletion and recreation, how could I do so?

At the root of this is the question: how does cdk decide whether a resource refers to an existing resource or a new resource?

ACS Video Call Recording servercallId API Error

I developed a project that can make video calls with the “QuickStart: Add 1:1 video calling” and “Rooms Call”. When I access the Call Id value from this project and use it in the API, I get this error; Invalid join identity, cannot join call. Status: 400 (Bad Request) ErrorCode: 8527

Content: {“error”:{“code”:“8527”,“message”:“Invalid join identity, cannot join call.”}}

enter image description here
enter image description here

Example call id: 34117f27-6459-4826-9v44-756rdde1c313

CallRecording API
QuickStart: Add 1:1 video calling to your app

What could I be doing wrong? I applied all the articles and solution suggestions but I couldn’t get a result.Despite having an active video call, I keep encountering the error ‘Invalid join identity, cannot join call.

Equation is moved to the extreme right after upgrading to MathJax v3

I’ve a personal blog built on minimal-mistakes Jekyll theme. Some of the posts use LaTex parsed by MathJax. I’ve been using MathJax v2 with the following configuration:

MathJax.Hub.Config({

  showProcessingMessages: false,
     messageStyle: "none",
     tex2jax: {
       inlineMath: [ ['$','$'], ["\(","\)"] ],
       displayMath: [ ['$$','$$'], ["\[","\]"] ],
       processEscapes: true
     },
     TeX: {
       MultLineWidth: "100%",
       equationNumbers: { autoNumber: "AMS" }
     },
     "HTML-CSS": { fonts: ["Latin-Modern"] }

});

MathJax.js?config=TeX-AMS-MML_HTMLorMML

Here’s an equation and its output.

$$
E[X] = sum_{i=1}^{k-1}sum_{j=i+1}^{k} X_{ij}Pr[text{i and j have the same birthday}]
$$
$$ Pr[text{i and j have unique birthdays}] = 365/365 * 364/365 $$ ($$ i $$ may have been born on any of the $$ 365 $$ days, and $$ j $$ on any of the remaining $$ 364 $$ days).
$$
therefore Pr[text{i and j have the same birthday}] = 1 - frac{364}{365} = frac{1}{365} \
begin{equation*}
begin{aligned}
  E[X] & = frac{1}{365} * sum_{i=1}^{k-1}sum_{j=i+1}^{k} X_{ij} \
   & = frac{1}{365} * sum_{i=1}^{k-1} (k - i - 1 + 1) \
   & = frac{1}{365} * sum_{i=1}^{k-1} (k - i) \
   & = frac{1}{365} * (sum_{i=1}^{k-1} k - mathop{sum_{i=1}^{k-1}} i) \
   & = frac{1}{365} * (k(k - 1) - (1 + 2 +...+ k - 1)) \
   & = frac{1}{365} * (k(k - 1) - frac{k(k - 1)}{2}) \
   & = frac{k(k - 1)}{(365 * 2)}
end{aligned}
end{equation*}
$$

v2

I upgraded MaxJax to v3, and obtained the v3 configuration using the conversion tool provided by MathJax.

v3 configuration:

window.MathJax = {
  tex: {
    inlineMath: [ ['$','$'], ["\(","\)"] ],
    displayMath: [ ['$$','$$'], ["\[","\]"] ],
    processEscapes: true,
    multlineWidth: "100%",
    tags: "ams"
  },
  options: {
    ignoreHtmlClass: 'tex2jax_ignore',
    processHtmlClass: 'tex2jax_process'
  }
};

v3

As you can see, the equation is moved to the extreme right, and overlaid on top of the text above it. How do I fix this?

move sub array to main array with only one value [closed]

I am strugging to format the below array.

const arr = [
    {
    "id": 96,
    "body": "Post on FB",
    "smAccounts": [
      {
        "id": 1,
        "name": "Test 1"
      },
      {
        "id": 3,
        "name": "Glem vital"
      },
      {
        "id": 2,
        "name": "Shiv"
      }
    ]    
  },
  {
    "id": 96,
    "body": "Post on FB",
    "smAccounts": [
      {
        "id": 1,
        "name": "Test 1"
      },
      {
        "id": 3,
        "name": "Glem vital"
      },
      {
        "id": 2,
        "name": "Shiv"
      }
    ]    
  },
  {
    "id": 96,
    "body": "Post on FB",
    "smAccounts": [
      {
        "id": 1,
        "name": "Test 1"
      },
      {
        "id": 3,
        "name": "Glem vital"
      },
      {
        "id": 2,
        "name": "Shiv"
      }
    ],
  }
];

I want OutPut in below format:

arr = [
    {
    "id": 96,
    "body": "Post on FB",
    "smAccounts": 
      {
        "id": 1,
        "name": "Test 1"
      }  
  },
  {
    "id": 96,
    "body": "Post on FB",
    "smAccounts": 
      {
        "id": 2,
        "name": "Glem vital"
      }   
  },
  {
    "id": 96,
    "body": "Post on FB",
    "smAccounts":
      {
        "id": 3,
        "name": "Shiv"
      }
  }
];

Can’t find a solution to login to external webapp through auth0 [closed]

I’m using a web application (this is not mine app, just external), which implements an auth0.
My aim is to login to my account via JS-code. Like, I want to make http calls not through UI, but from my code. As far as I understand, I need to provide my credentials to auth0, they would return me JWT, and I would provide it to webapp. Can you please help me?

I’ve found this example, but how can I know details like “scope”?

auth0.authorize({
  audience: 'https://mystore.com/api/v2',
  scope: 'read:order write:order',
  responseType: 'token',
  redirectUri: 'https://example.com/auth/callback'
});