Angular12 ReactiveFormsModule strange phenomenon

Partial code:

@Component({
  selector: "form-test",
  template: `
    <form [formGroup]="form">
      <input type="checkbox" formControlName="checkbox" />{{ item.name }}
      <p>form checkbox disabled: {{ form.get("checkbox").disabled }}</p>
    </form>
  `,
})
export class FormTestComponent implements OnChanges {
  @Input() item: any;

  form: FormGroup;

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({});
  }

  ngOnChanges(changes: SimpleChanges): void {
    this.form = this.fb.group({
      name: [""],
      checkbox: [false],
    });

    if (this.item.name === 111) {
      this.form.get("checkbox")?.disable();
    }
  }
}

I’ll assign a new group to this.form each time ngOnChanges is triggered, and I’ll make the disabled property of the checkbox true when this.item.name === 111, but when I click on the other list items, the disabled property of the checkbox will still look like it is true, it’s actually false, but the checkbox in the template renders out with disabled=true

enter image description here

enter to demo

An unhandled exception occurred: Class extends value undefined is not a constructor or null

I was migrating from Angular version 11 to 14 and In the end this error came when I was trying to run or build the application, after successfull migration.

ng serve

I wanted to serve the application, then I got this error

An unhandled exception occurred: Class extends value undefined is not a constructor or null See “C:UsersUserAppDataLocalTempng-ISIjXpangular-errors.log” for further details.

Property undefined error(reading ‘title’) [duplicate]

I am getting an error which says “cannot read properties of undefined(reading ‘title’)
Here is my code below I have declared the variable title, description and author all as a string. Please can someone help me out, I want to know what I am not doing right.

import React, { useState } from 'react'
import { Link } from 'react-router-dom'
import axios from 'axios'
import validation from './TodoValidation'

function Todo() {
 const [values, setValues]= useState({
  title: "",
  description: "",
  author: "",
 })
 const [error, setError]= useState({})
 const handleChange = (event)=> {
    setValues ({...values, [event.target.name]:event.target.value})
  }
const handleSubmit = (event)=> {
  event.preventDefault();
  setError(validation(values));
  if( error.title=== "" && error.description=== "" && error.author=== ""){
    axios.post('http://localhost:8081/Todo', values)
    .then(res => 
      {if (res.values==="")
      res.json("Todo item created successfully")})
    .catch(err => console.log(err))
  }}

Sending developer token to backend, how can I hide sensitive data?

I’m working with Apple Music MusicKit js API.

MusicKit is a front end js library that requires using the developer token in the front end to configure the MusicKit instance and get a user token.

I am attempting to create a web app utilizing MusicKit and I want to hide the developer token from users as it is sensitive data. I’ve noticed sending the token to the backend or bringing it into the front end from the backend causes it to show up in the network tab.

How can I set up my app in a way that I can utilize the developer token to get a user token but keep it hidden from users?

How to call multiple statements when setting a value for an object property in an object initializer in JavaScript?

If the property to be calculated only requires one statement, it is pretty simple

let object = {
    array: new Array(10)
};

Alternatively I can also do the following (though I don’t like it as much)

let object = {};
object.array = new Array(10);

But what if I want to (e.g.) initialize the array with values of 0 (by deafult the values are “undefined”)? I can only do it the second way

let object = {};
object.array = new Array(10);
for(let element of array){
    element = 0;
}

The closest thing to the first method that comes to mind might be doing something like this

let object = {
    array: (function(){
        let array = new Array(10);
        for(let element of array){
            element = 0;
        }
        return array;
    })()
}

Maybe there is a simpler way to do this that I do not know of?

Unit Test Case ARC-GIS Javascript

To do the unit test case I used the platform, jasmine for ARC-GIS Javascript.

npm install jasmine --save-dev

jasmine configuration files are installed and listed development dependency in your package.json file

npx jasmine init

This command creates a spec directory and a jasmine.json configuration file in the project

Then By adding the simple addition function in utility.js file

export function add(a, b) {
    return a + b;
  }

Unit test case function:

import { add } from '../libs/utility.js'; 

describe('Math Utility', () => {
  it('should add two numbers', () => {
    
    const num1 = 5;
    const num2 = 10;

    const result = add(num1, num2);

    expect(result).toEqual(15);
  });
}); 

Package.json:

{
  "name": "...",
  "private": ...,
  "version": "...",
  "type": "module",
  "scripts": {
    "dev": "...",
    "build": "...",
    "preview": "...",
    "cleancp": "...",
    "test": "jasmine"

  },
  "devDependencies": {
    "jasmine": "^5.1.0",
    "...": "..."
  },

To run the test case : npx jasmine

I got the error:

Error [ERR_MODULE_NOT_FOUND]: Cannot find module
‘E:pathtolibsmaplayers’ imported from E:pathtolibsutility.js
at new NodeError (internal/errors.js:322:7)
at finalizeResolution (internal/modules/esm/resolve.js:318:11)
at moduleResolve (internal/modules/esm/resolve.js:776:10)
at Loader.defaultResolve [as _resolve] (internal/modules/esm/resolve.js:887:11)
at Loader.resolve (internal/modules/esm/loader.js:89:40)
at Loader.getModuleJob (internal/modules/esm/loader.js:242:28)
at ModuleWrap. (internal/modules/esm/module_job.js:76:40)
at link (internal/modules/esm/module_job.js:75:36) { code: ‘ERR_MODULE_NOT_FOUND’ }

Please suggest the solution how to solve the issue.

Svelte: Is it possible to have two writable stores in svelte subscribe to each other?

There’s an object where its data matches with another object, yet they have different structures.

For example, consider this scenario:

The ‘Team’ object holds the team ID as its key.
The ‘Team’ object contains ‘name’ and ‘users’ objects as its values.
The ‘users’ object has the user ID as its key, which doesn’t overlap with user IDs from other teams.

So, I want to create a new object that has all users.

The ‘users’ object can be subscribed to by users, and modifying this should reflect changes in the ‘Team’ object.
Conversely, the ‘Team’ object can be subscribed to by users, and modifying it should reflect changes in the ‘users’ object.

How can I achieve this?

I attempted to update each object using a ‘subscribe’ function in JavaScript files, but I ended up stuck in an infinite loop and failed.

Here’s an example code and a REPL.”

<script>
    import {writable} from "svelte/store";
    
    const teamDict = writable({})
    const userDict = writable({})

    function initTeamDict() {
        teamDict.set({
            1: {
                name: "good team",
                users: {
                    1: "James",
                    2: "Poppy",
                    48: "Hway"
                }
            },
            2: {
                name: "bad team",
                users: {
                    47: "Kelin",
                    35: "Teo",
                    24: "Ferma"
                }
            }
        })
    }

    function initUserDict() {        
        userDict.set(Object.values($teamDict).reduce((acc, team) => ({...acc, ...team[`users`]}), {}))
    }


</script>

<button on:click={initTeamDict}>init team dict</button>
<button on:click={initUserDict}>init user dict</button>

<div> {JSON.stringify($teamDict)}</div>
<div> {JSON.stringify($userDict)}</div>

<button on:click={() => $teamDict[`1`][`users`][`1`] = "top"}>this button should change userDict also </button>
<button on:click={() => $userDict[`1`] = "bottom"}>this button should change teamDict also </button>

REPL

https://svelte.dev/repl/e6570ac9ca464c15967a43c8311dcd4d?version=4.2.8

Is the API being called before I call it? [duplicate]

I am trying to create a UI for an email validator. I am using an API that I can only make one call to per second. Below is my code so far – VERY BASIC. I barely got started. But when I try running it, it throws multiple errors with the same error message saying there are “Too many requests” and that I “have exceeded the requests per second allowed”. Is there a reason why it is telling me that I am exceeding my call limit? I am definitely not calling it more than once per second.

function App() {

  const [result, setResult] = useState('');

  useEffect(() => {
    validateEmail('')
  }, [])
  
  async function validateEmail(email){
    const response = await fetch(`https://emailvalidation.abstractapi.com/v1/?api_key=${API_KEY}&email=${email}`);
    const data = await response.json();
    console.log(data);
    setResult(data);
  }

  validateEmail('POOKIEWOOKIE.com')

  return (
    <div className="App">
      <h1>{result}</h1>
    </div>
  );
}

tooltip popup is not showing in nz-tabs

I have two tabs where I want to add an info icon before the tab text. Hovering over the icon should display a tooltip popup.

For the first tab, I added the tooltip to the anchor tag. As a result, the tooltip popup appears when hovering over both the tab text and the icon. However, the requirement is for the tooltip to only appear when hovering over the icon.

In the second tab, the icon is added correctly, but the tooltip popup is not appearing.

     <nz-tabset [nzLinkRouter]="true">
              <nz-tab >
                <a [nzTooltipOverlayClassName]="'tooltip-md'" *nzTabLink nz-tab-link nz-tooltip [nzTooltipTitle]="'This list represents your focus group of recruits, you can add an agent to your recruiting targets list from a list or detailed view. you can remove them by selecting the checkbox and clicking the Remove Target(s) button below'"  [routerLink]="['.']">
                <span nz-icon nzType="info-circle" nzTheme="fill" style="font-size: 19px;"></span>
                 My Recruiting Targets
                </a>
                <recruiting-targets></recruiting-targets>
              </nz-tab> 

              <nz-tab > 
                <a  *nzTabLink nz-tab-link nz-tooltip [routerLink]="['.']" [queryParams]="{ type: 'retention' }"
                  queryParamsHandling="merge"> 
                  <span nz-tooltip  [nzTooltipOverlayClassName]="'tooltip-md'" [nzTooltipTitle]="'This list represents your focus group of your agents for retention, you can add an agent to your retention targets list from a list or detailed view, the Portal knows when it’s one of your agents and will automatically add them to your Retention Targets. You can remove them by selecting the checkbox and clicking the Remove Target(s) button below'"  >
                  <span nz-icon nzType="info-circle" nzTheme="fill" style="font-size: 19px;"></span>
                </span>
                  My Retention Targets
                </a>
              <retention-targets></retention-targets>
            </nz-tab>
</nz-tabset>

suggest me some way that tooltip popup will come only on hovering over tool icon.

How do I make HTML light boxes on my merchandise page that show details specific to each product?

I am coding a website for a school project and decided to add a merchandise page. I wanted to include a product view so that people can see more details (like a description) when they click on a product.

I initially used this idea from a CodePen I found and it works really well but the only problem is it brings up the same lightbox no matter what product you click on. I want a design that is product specific. I tried simply adding more light boxes but it didn’t change anything. I think this has something to do with the Javascript but I am not sure as I have not learned the basics of that language yet.

Here is the HTML:

<body>
  <div class="lightbox-blanket">
    <div class="pop-up-container">
      <div class="pop-up-container-vertical">
        <div class="pop-up-wrapper">
          <div class="go-back" onclick="GoBack();"><i class="fa fa-arrow-left"></i>
          </div>
          <div class="product-details">
            <div class="product-left">
              <div class="product-info">
                <div class="product-manufacturer">NOOK
                </div>
                <div class="product-title">
                  LOUNGE CHAIR
                </div>
                <div class="product-price" price-data="320.03">
                  $320<span class="product-price-cents">03</span>
                </div>
              </div>
              <div class="product-image">
                <img src="https://via.placeholder.com/300" />
              </div>
            </div>
            <div class="product-right">
              <div class="product-description">
                Designer Karim Rashid continues to put his signature spin on all genres of design through various collaborations with top-notch companies. Another one to add to the win column is his work with Italian manufacturer Chateau d’Ax.
              </div>
              <div class="product-available">
                In stock. <span class="product-extended"><a href="#">Buy Extended Warranty</a></span>
              </div>
              <div class="product-rating">
                <i class="fa fa-star rating" star-data="1"></i>
                <i class="fa fa-star rating" star-data="2"></i>
                <i class="fa fa-star rating" star-data="3"></i>
                <i class="fa fa-star" star-data="4"></i>
                <i class="fa fa-star" star-data="5"></i>
                <div class="product-rating-details">(3.1 - <span class="rating-count">1203</span> reviews)
                </div>

              </div>
              <div class="product-quantity">
                <label for="product-quantity-input" class="product-quantity-label">Quantity</label>
                <div class="product-quantity-subtract">
                  <i class="fa fa-chevron-left"></i>
                </div>
                <div>
                  <input type="text" id="product-quantity-input" placeholder="0" value="0" />
                </div>
                <div class="product-quantity-add">
                  <i class="fa fa-chevron-right"></i>
                </div>
              </div>
            </div>
            <div class="product-bottom">
              <div class="product-checkout">
                Total Price
                <div class="product-checkout-total">
                  <i class="fa fa-usd"></i>
                  <div class="product-checkout-total-amount">
                    0.00
                  </div>
                </div>
              </div>
              <div class="product-checkout-actions">
                <a class="add-to-cart" href="#" onclick="AddToCart(event);">Add to Cart</a>
                
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="random-background">
    <div class="itemlist">
      <div class="itemlist-item-wrapper" onclick="OpenProduct(1);">
        <div class="product-details">
          <div class="">
            <div class="product-info">

              <div class="product-title" item-data="1">
                LOUNGE CHAIR
              </div>
              <div class="product-price" price-data="320.03" item-data="1">
                $320<span class="product-price-cents">03</span>
              </div>
            </div>
            <div class="product-image" item-data="1">
              <img src="https://via.placeholder.com/300" />
            </div>
          </div>
        </div>
      </div>
      <div class="itemlist-item-wrapper" onclick="OpenProduct(2);">
        <div class="product-details">
          <div class="">
            <div class="product-info">

              <div class="product-title" item-data="2">
                LOUNGE CHAIR
              </div>
              <div class="product-price" price-data="320.03" item-data="2">
                $320<span class="product-price-cents">03</span>
              </div>
            </div>
            <div class="product-image" item-data="2">
              <img src="https://via.placeholder.com/300" />
            </div>
          </div>
        </div>
      </div>
      <div class="itemlist-item-wrapper" onclick="OpenProduct(3);">
        <div class="product-details">
          <div class="">
            <div class="product-info">

              <div class="product-title" item-data="3">
                LOUNGE CHAIR
              </div>
              <div class="product-price" price-data="320.03" item-data="3">
                $320<span class="product-price-cents">03</span>
              </div>
            </div>
            <div class="product-image" item-data="3">
              <img src="https://via.placeholder.com/300" />
            </div>
          </div>
        </div>
      </div>
      <div class="itemlist-item-wrapper" onclick="OpenProduct(4);">
        <div class="product-details">
          <div class="">
            <div class="product-info">
              <div class="product-title" item-data="4">
                LOUNGE CHAIR
              </div>
              <div class="product-price" price-data="320.03" item-data="4">
                $320<span class="product-price-cents">03</span>
              </div>
            </div>
            <div class="product-image" item-data="4">
              <img src="https://via.placeholder.com/300" />
            </div>
          </div>
        </div>
      </div>
      <div class="itemlist-item-wrapper" onclick="OpenProduct(5);">
        <div class="product-details">
          <div class="">
            <div class="product-info">
              <div class="product-title" item-data="5">
                LOUNGE CHAIR
              </div>
              <div class="product-price" price-data="169.49" item-data="5">
                $<span class="product-price-dollar">169</span><span class="product-price-cents">49</span>
              </div>
            </div>
            <div class="product-image" item-data="5">
              <img src="https://via.placeholder.com/300" />
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</body>

And Javascript:

//Go Back
function OpenProduct(i){
  var i = $('.product-image[item-data="'+i+'"] img');
  var lbi = $('.lightbox-blanket .product-image img');
  console.log($(i).attr("src"));
  $(lbi).attr("src", $(i).attr("src"));  
  $(".lightbox-blanket").toggle();
    
  $("#product-quantity-input").val("0");
  CalcPrice (0);
  
}
function GoBack(){
  $(".lightbox-blanket").toggle();
}

//Calculate new total when the quantity changes.
function CalcPrice (qty){
  var price = $(".product-price").attr("price-data");
  var total = parseFloat((price * qty)).toFixed(2);
  $(".product-checkout-total-amount").text(total);
}

//Reduce quantity by 1 if clicked
$(document).on("click", ".product-quantity-subtract", function(e){
  var value = $("#product-quantity-input").val();
  //console.log(value);
  var newValue = parseInt(value) - 1;
  if(newValue < 0) newValue=0;
  $("#product-quantity-input").val(newValue);
  CalcPrice(newValue);
});

//Increase quantity by 1 if clicked
$(document).on("click", ".product-quantity-add", function(e){
  var value = $("#product-quantity-input").val();
  //console.log(value);
  var newValue = parseInt(value) + 1;
  $("#product-quantity-input").val(newValue);
  CalcPrice(newValue);
});

$(document).on("blur", "#product-quantity-input", function(e){
  var value = $("#product-quantity-input").val();
  //console.log(value);
  CalcPrice(value);
});


function AddToCart(e){
  e.preventDefault();
  var qty = $("#product-quantity-input").val();
  if(qty === '0'){return;}
  var toast = '<div class="toast toast-success">Added '+ qty +' to cart.</div>';  
  $("body").append(toast);
  setTimeout(function(){ 
  $(".toast").addClass("toast-transition");
    }, 100);
  setTimeout(function(){      
    $(".toast").remove();
  }, 3500);
}

Return a typescript interface that changes based on function inputs

I have a typescript interface:

interface MyInterface {
    property1?: string;
    property2?: string;
};
type InterfaceKey = keyof MyInterface;

The code below creates an object based on MyInterface. The verifyObjectProperty function allows the user to pass in an InterfaceKey (‘property1’ or ‘property2’) as a second parameter.

The function validates that the object has a string value for the given key, so it can no longer be undefined.

// - Create an object based on the interface
const myObject: MyInterface = {
    property1: 'a string',
}

const verifyObjectProperty = (
    objectToVerify: MyInterface,
    properyToVerify: InterfaceKey
): MyInterface => {
    // - Make sure object has the desired property
    if (objectToVerify[properyToVerify] === undefined) {
        objectToVerify[properyToVerify] = 'a new string';
    }

    // - Return the object
    return myObject;
};

I want to make it so the verifyObjectProperty function returns a typescript interface that shows which string is guaranteed to be there.

const verifiedObject = verifyObjectProperty(myObject, 'property1');
type property1 = typeof verifiedObject['property1']; // string
type property2 = typeof verifiedObject['property2']; // string | undefined

How to draw circles in a pyramid shape using p5js and matterjs

I am trying to draw multiple circles in pyramid shape like this: balls in pyramid shape

I have made this ‘Balls’ class:

class Balls {
  constructor(x, y, radius, color, ballCount) {
    this.x = x;
    this.y = y;
    this.radius = radius;
    this.color = color;

    this.balls = [];

    this.ballCount = ballCount;

    this.option = { restitution: 1, friction: 0.01, label: "ball" };
  }

  setupBalls() {
    for (var i = 0; i < this.ballCount; i++) {
      var ball = Bodies.circle(this.x, this.y , this.radius, this.option);
      this.balls.push(ball);
      World.add(engine.world, [this.balls[i]]);
    }
  }

  
  drawBalls() {
    fill(this.color);
    noStroke();
    for(var i = 0; i<this.balls.length; i++){
        drawVertices(this.balls[i].vertices);
    }
  }
}

‘setupBalls()’ method is called in ‘function setup()’ and ‘drawBalls()’ is called in ‘function draw()’ of p5.js like this:

function setup() {
    createCanvas(1200, 600);

    //create engine
    engine = Engine.create();
    //set world gravity to 0
    engine.world.gravity.y = 0;


    //balls
    balls = new Balls(width / 2 + 100, 250, 8, color(200, 0, 0), 15);
    balls.setupBalls();

}

 function draw() {

    background(125);
    Engine.update(engine);

    //balls
    balls.drawBalls();

}

I tried playing around with the x and y position using nested for loops but i just cant get the pyramid shape that i wanted.

Adobe’s Comb of property is not functioning when Javascript added PDF is integrated in the code

enter image description here

I have eight boxes in a field similar to the one above. Each digit should go in its own box if my input value is less than or equal to 8. I am using a comb of property to accomplish that.

Say If my input value is greater than 8 then entire value should be adjusted in the given 8 boxes. But when I use comb of then value greater than 8 is getting trimmed off from the field.

Therefore, I utilized a Java script to accomplish the above scenario. Using a Java script, I was able to find the solution. It functions flawlessly in Adobe Reader. However, my code did not function when I uploaded the identical PDF in it.

I am using aspose library for filling out the fields. Could you please help me with the above scenario?

Javascript: automatically stops all “threads” created by an async function when another function starts

I have multiple async functions that the user can call at any time, but I want to make sure that all previously run functions (and the “threads” they might have spawned) are stopped when a new function is called as they would otherwise try to use the same resource (webcodec decoder) which is not supported.

How could I do that?

My attempts: For now, I use a global counter accessible to all functions that I increase and copy at the beginning of all functions, and everytime an async function is called, I send to it the copy of the counter, and I check at the beginning of the subroutine and right after it returned if the global counter has been changed, but it is really heavy to maintain when you have many nested calls to async functions (as you need to repeat and pass the value of the copied variable to all calls). Moreover, this will not work if we call inside async functions are not coded by myself. So I would prefer to have something like:

functionCurrentlyRun = null


async runFunction(f, args) {
  if (functionCurrentlyRun) {
    stopFunctionAndAllSubthreads(functionCurrentlyRun);
  }
  return await runAndSaveIn(f, args, functionCurrentlyRun) 
}

async f1(args) {
  return await someAsyncCalls();
}


f2(args) {
  return await someAsyncCalls();
}

runFunction(f1, 42);
runFunction(f2, 43);

a bit like what is done with cancelAnimationFrame but for arbitrary functions.