Construct a Gamepad in js

So I was trying to simulate a controller in JavaScript but couldn’t find a way to construct a new Gamepad() and could not figure out how to work this out from the docs could anybody help.

This is what my current code looks like:

function simulateControllerInput(key) {
    const mapping = keyMappings[key];
    if (mapping) {
        const simulatedGamepad = new Gamepad(); // <-- This is where I want to construct the Gamepad
        simulatedGamepad.axes = mapping.axes;
        const buttonEvent = new GamepadEvent("gamepadbuttondown", {
            bubbles: true,
            cancelable: true,
            gamepad: simulatedGamepad,
        });
        document.dispatchEvent(buttonEvent);
    }
}

Ajv nodejs schema validation: get value of custom field in case of error

I have following nodeJs code

const Ajv = require('ajv');
const addFormats = require('ajv-formats');
const ajv = new Ajv({allErrors: true, allowUnionTypes: true});
addFormats(ajv);

// addKeyword for severityType ??

const schema  = {
  $schema: 'http://json-schema.org/draft-07/schema#',
  type: 'object',
  properties: {
    slices: {
      type: 'array',
      items: {
        type: 'object',
        properties: {
          personId: { type: 'string', severityType: 'error' },
          position: { type: 'string', severityType: 'error' },
          networkId: { type: 'string', severityType: 'warning' },
        },
        required: ['personId', 'position', 'networkId'],
      },
    },
  },
  required: ['slices'],
}

const data = {
  slices: [
    {
      personId: 55, // This should trigger the severityType 'error'
      position: null, // This should trigger the severityType 'error'
      networkId: null, // This should trigger the severityType 'warning'
    },
  ],
};

const validateSchema = (data, schema) => {
  const validate = ajv.compile(schema);
  const isValid = validate(data);
  if (validate.errors) {
    logger.error(`Validation errors: ${JSON.stringify(validate.errors)}`);
    logger.error(`severityType : //print severityType `);
  }
  return {
    isValid,
    errors: validate.errors,
  };
};

I want to validate ‘data’ object and in case of validation error I want to print error + value of severityType (‘error’ or’warning’ or can be any value). I know it is not standard JSON validation schema, but I added it as custom filed to fetch its value to be able to act depend on severityType value in case of error of validation.
How to be able to get severityType value?

Arbitrary number of resizable panes ()

The task is to build an interface of several resizable panes separated by splitters:
enter image description here

Panes added in the loop (as far as its number could vary):

//Left pane is single
let newLeftDiv = document.createElement('div');
divContainer.appendChild(newLeftDiv);   
for (let i = 0; i < selectedFiles.length; i++) {
            
    //barPane pane is single
    const newBarPane = document.createElement('div');
    divContainer.appendChild(newBarPane);

    //rightPane
    const newRightPane = document.createElement('div');
    divContainer.appendChild(newRightPane);
        
    const vertSplit = new VerticalSplitter (divContainer,newLeftDiv,newBarPane,newRightPane);
    newLeftDiv = newRightPane;
            
}

Class VerticalSplitter assigns the listener to split bar and manages the height of panes:

startDrag(event) {
    this.startY = event.clientY;
    this.initialTopPaneHeight = this.topPane.offsetHeight;
    this.initialBottomPaneHeight = this.bottomPane.offsetHeight;
    document.addEventListener("mousemove", this.handleDrag.bind(this));
    document.addEventListener("mouseup", this.stopDrag.bind(this));

............

handleDrag(event) {
    if (this.isDragging) {
        const deltaY = event.clientY - this.startY;     
        const newTopPaneHeight = this.initialTopPaneHeight + deltaY;
        this.topPane.style.height = (this.initialTopPaneHeight + deltaY) +'px';
        this.bottomPane.style.height = (this.initialBottomPaneHeight  - deltaY) +'px';
            
    }

it works ok for first two panes (Most Top & pane0), but fails for all others.
e.g for pair pane 2 and 3 despite new height is assigning to the both panes, their values remains unchanged.

Checked that height values attempt to assign during the correct event (mouse move after the mouse down) and to the correct elements (id checked before height changing).

ExtJs expand and wait for child nodes to load

Im having an issue where the child nodes are not loaded even after expanding the node. I set the code to get the child nodes inside the expand callback and yet they aren’t available.

if (node.isExpandable()) {
  if (node.childNodes.length > 0) {
    template = node.childNodes;
    // someFunction(template)
  }
  else {
    node.expand(false, function () {
      template = node.childNodes;
      // someFunction(template);
      node.collapse();
    });
  }
}

I know that this way of expanding the node does get child nodes because i originally had an array of nodes and when performing the below, it was loaded successfully.

Ext.each(selectedNodes, function (node) {
  if (node.childNodes.length === 0) {
    node.expand(false, function () {
      node.collapse();
    });
  }
});

Ext.each(selectedNodes, function (node) {
  // node here has the children available.
});

Why only the first option of my if/else statements if printing? [closed]

I’m using a json file to take data from courses and put it in a select element. The javascript takes the json data and puts the correct information into the select element. I then want to select one of the options and it give the proper name, but it is only outputting the first option. I tried a switch statement and that didn’t work either, so I just want to know what I’m doing wrong.

// The html

    <select name="" id="CRN">
        <option value=""></option>
    </select>
    <input type="submit" value="Submit" id="btn"/>
    <h1 id="Course_Info"></h1>

//The js

for (let i = 0; i < data.courses.length; i++){
    var x = document.getElementById("CRN");
    var option = document.createElement("option");
    option.text = data.courses[i].CRN;
    x.add(option);
}

button.addEventListener("click", () => {
    if(selectCRN = data.courses[0].CRN){
        courseInfo.innerHTML = data.courses[0].Name;
    }else if(selectCRN = data.courses[1].CRN){
        courseInfo.innerHTML = data.courses[1].Name;
    }else if(selectCRN = 11011){
        courseInfo.innerHTML = data.courses[2].Name;
    }else if(selectCRN = 11338){
        courseInfo.innerHTML = data.courses[3].Name;
    }else if(selectCRN = 12005){
        courseInfo.innerHTML = data.courses[4].Name;
    }else if(selectCRN = 12017){
        courseInfo.innerHTML = data.courses[5].Name;
    }else if(selectCRN = 11452){
        courseInfo.innerHTML = data.courses[6].Name;
    }else if(selectCRN = 12904){
        courseInfo.innerHTML = data.courses[7].Name;
    }else{
        courseInfo.innerHTML = "";
    }
});

HTML- I am making a one page webpage and added bisels between sections top and bottom and the code doesn’t work anymore

I am studying HTML with VisualStudioCode for 2 months now and have been having trouble with creating this one page webpage, so I added bisels between the sections for a nice look using CSS and at first everything was OK. Today I opened VisualCode and noticed the bisel in the top became white with weird border (transparent) the rest of them were GONE, been trying to double check what could be the mistake in html.
Do you have any idea what might be wrong?

THANK YOU!!

Add bisels between the sections with images, they worked but now they don’t

Updating JavaScript class instance

When updating properties on a class instance, is this the best approach? I could use some clarification from a more experienced developer on this.

Here is my class:

class Cart {
  constructor(id) {
    this.id = id;
    this.cartItems = [];
    this.cartSubtotal = 0;
    this.cartQuantity = 0;
  }

  getCartQuantity() {
    const qty =
      this.cartItems.reduce((quantity, item) => item.quantity + quantity, 0) ||
      0;
    return qty;
  }

  getCartSubTotal() {
    let subTotal = 0;
    this.cartItems.forEach((cartItem) => {
      const product = products.find(
        (product) => product.id === cartItem.productId
      );
      subTotal += cartItem.quantity * (product.price || 0);
    });
    return subTotal;
  }

  addItem(cartItem) {
    this.cartItems.push(cartItem);
  }
}

Here is my add cart item end point:

app.post('/addToCart/:cartId', (req, res) => {
  const { cartId } = req.params;
  const { id, quantity, detail } = req.body;
  const cart = getUserCart(cartId);

  const item = new CartItem(uuidv4(), id, quantity, detail);
  cart.addItem(item);
  cart.cartSubtotal = cart.getCartSubTotal();
  cart.cartQuantity = cart.getCartQuantity();

  res.json(cart);
});

Setting the values on the post call makes sense and it works but I feel like there is a more elegant way to do this.

cart.cartSubtotal = cart.getCartSubTotal();
cart.cartQuantity = cart.getCartQuantity();

Any advice would be appreciated, thank you.

Not able to debug a Javascript challenge

I currently doing a challenge that requires me to debug a code snippet. The challenge states that there are bugs in the code that need to be changed to it can log true, true, true instead of true, false, false like it’s currently doing.

The code snippet is:

import BigNumber from 'bignumber.js';

const denominationsMultiplier = {
  WEI: new BigNumber(1, 10).times(10).exponentiatedBy(18),
  GWEI: new BigNumber(1, 10).times(10).exponentiatedBy(8),
  ETH: new BigNumber(1, 10).times(10).exponentiatedBy(1),
}

function getFiatValueToRender({
  value,
  conversionRate = 1,
  fromDenomination,
  fromCurrency,
}) {
  let number = new BigNumber(value, 16);
  if (fromCurrency !== 'ETH') {
    number = number.multipliedBy(conversionRate);
  }
  if (fromDenomination !== 'WEI') {
    number = number.multipliedBy(
      denominationsMultiplier.WEI
        .dividedBy(denominationsMultiplier[fromDenomination])
    )
  }
  return number.toString(32);
}

function getResult(value) {
  return getFiatValueToRender({
    value,
    conversionRate: 1,
    fromDenomination: 'GWEI',
    fromCurrency: 'ABC',
  })
}

let x = 0

console.log(getResult(0) === '0')
console.log(getResult(1) === '59682f00')
console.log(getResult(10600.47) === 'e762bdf8a40')

The challenge says the the bugs are specifically on lines 5, 15, 25, and 31 and by changing decimal numbers on those lines, the code can be fixed and make it log true, true, true. I’m really struggling on grasping what the issue is. I know that the function takes a value, its denomination, currency, and a conversion rate as input, performs calculations based on these parameters, and returns the value converted to a base-32 string. However, I’m not seeing how I can debug the console.log(getResult(1) === '59682f00') test to have it pass? Can someone illustrate how to debug the test to successfully figure out what changes are needed to fix the “bugs” in this challenge?

Importing a “raw” private key into the subtle crypto js library

I have a private key that is just a simple 32 byte private key that was generated somewhere else entirely outside of javascript. I want to import this private key into javascript using the subtle crypto library.

From my experimentation and research, it seems there is no way to import a raw private key. It has to be in either pkcs8 format, or in jwk format.

First, I tried to convert my 32 byte private key into jwk format. I ran into a dead end when I realized that jwk requires the “x” and “y” parameters, which are basically the public key. I don’t have the public key, all I have is the private key. I know you can generate the public key from the private key, but I assume that first requires you to import the private key first, which is what I’m trying to do.

Then I tried to convert it to pkcs8, but that also requires the x and y public points, which, again, I do not have.

Is this even possible? I know other crypto libraries let you import raw private keys, but for some reason subtle crypto doesn’t let you?

Pass a array or list as a parameter to procedure in Snowflake

I have built the following procedure in Snowflake. I would like to pass the CUSTOMER_FIRSTNAME as an array of strings so that the query is executed like this at the end: Customer_ID IN ('Tom','Marvin', 'Seb'),but that doesn’t work as it is right now. I also asked ChatGPT, but it didn’t really help me either.

CREATE OR REPLACE PROCEDURE DELETE_CUSTOMERS( "TABLENAME" VARCHAR(16777216), "CUSTOMER_LASTNAME" VARCHAR(16777216), "CUSTOMER_FIRSTNAME" ARRAY)
RETURNS VARCHAR(16777216)
LANGUAGE JAVASCRIPT
EXECUTE AS CALLER
AS '

var delete_from_table = `DELETE FROM CAMPAIGN.PUBLIC.` + TABLENAME + ` WHERE 
communication_lastname = ''${CUSTOMER_LASTNAME}''
AND customer_firstname IN (CUSTOMER_FIRSTNAME);`
  
try {
  snowflake.execute({sqlText: delete_from_table});
  return "Delete was successful.";
}
catch (err) {
  return "Failed: " + err;
}
';

CALL DELETE_CUSTOMERS('Customer_Table','Richard',ARRAY_CONSTRUCT('Tom','Marvin', 'Seb'));

How to get the height of a button component after card component render in jest?

I’m trying to write a test case where height of a Button from PopoverMenu doesn’t change regardless of how many headers are created. Before the fix, height of button would stretch out along with number of headers due to the increase in height. So I made a fix and tryin to add test case to prove it, but I’m always getting 0 for buttonHeightWithOneHeader. getButton() selects the button element and trying to get the height of that button by using getBoundingClientRect().height, but no luck. Doesn’t await waitFor give enough time for Card component to finish render? Not sure why I can’t get the height of Button element.

let buttonHeightWithOneHeader = 0;
let buttonHeightWithSixHeaders = 0;
  it('should have its button height remain unchanged regardless of the height of the header of the card', async () => {
    const { rerender } = render(
      <Card>
        <Card.Content>
          <Card.Header
            title="Overwatch"
            description="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed dos eiusmod tempor incididunt ut labore et dolore magna aliqua."
            action={
              <PopoverMenu
                buttonLabel="Menu"
                testId="button-menu"
              >
              </PopoverMenu>
            }
          />
        </Card.Content>
      </Card>
    );
    await waitFor(() => {
      buttonHeightWithOneHeader = getButton().getBoundingClientRect().height;
    });
  
    rerender(
      <Card>
        <Card.Content>
          <Card.Header
            title="Overwatch Overwatch Overwatch Overwatch Overwatch Overwatch"
            description="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed dos eiusmod tempor incididunt ut labore et dolore magna aliqua."
            action={
              <PopoverMenu
                buttonLabel="Menu"
                testId="button-menu"
              >
              </PopoverMenu>
            }
          />
        </Card.Content>
      </Card>
    );
    await waitFor(() => {
      buttonHeightWithSixHeaders = getButton().getBoundingClientRect().height;
    });

    expect(buttonHeightWithOneHeader).toEqual(buttonHeightWithSixHeaders );
  });

Trying to check if key present in array of objects inside of an array of objects

I need a way to return true or false if in changeFields array “printLogs” key is present or not. The object is shown below. I have tried looping but somehow cant get my head to wrap around it.

const printObj = [
  {
    _id: "656a69e14",
    document: { _id: "65b891" },
    user: "654cfbba3ea455b55b057195",
    changeFields: [
      {
        change: "update",
        quantity: [
          2,
          3,
          "2023 1 Oz Silver Maple Leaf Coin - Royal Canadian Mint",
        ],
      },
      { change: "update", subTotal: ["77.88", "116.82"] },
      { change: "update", totalAmount: ["107.88", "146.82"] },
    ],
    createdAt: "2023-12-01T19:10:54.575Z",
    updatedAt: "2023-12-01T19:10:54.575Z",
    __v: 0,
  },
  {
    _id: "65e0e",
    document: { _id: "651" },
    user: "",
    changeFields: [{ printLogs: "An order has been printed" }],
    createdAt: "",
    updatedAt: "",
    __v: 0,
  },
{},

]

I have tried javascript in built functions. The below worked to some degree but I need to return true or false if printLogs is present in changeFields.

const value = printObj.filter(function (x) {
  x.changeFields.filter(function (o) {
    console.log(o, o.hasOwnProperty("printLogs"));
  });
});

How to import/export functions between different NPM packages?

I’ve a React NPM package I’m developing as a framework for many of my other projects. Let’s call this package “framework”. Then I have a framework consumer.

So in the framework consumer project, I can run the following code:

and then I can use said framework like this, passing props to customize:

import Framework from 'framework'
export default function App() {
    return (
            <>
            <Framework
                appName="My App Name"
                logoImagePath={"/images/MyApp_logo.png"}
            />
            <OtherComponent />
            </>
    )
}

This works well.

However, I want to be able to call functions that the Framework can provide. For example, let’s say the Framework contains modals and has a setErrorMessage and I want to be able to have something in OtherComponent call a the setErrorMessage function.

How would I do this?

I’d like my OtherComponent to be able to do something like:

import {setErrorMessage} from 'framework'
export default function OtherComponent() {
    return <button onClick={()=>setErrorMessage("Stop, Error time!")}>Fire an error</button>
}

(of note, setErrorMessage is actually a setter function inside a context of Framework… but the idea is more conceptual. If I have a function in an npm package, how do I expose it to consumers?)

How can I see that FinalizationRegistry indeed invokes the given callback when an object gets consumed by the garbage collector?

In the latest Chrome browser 119.0.6045.159 (Official Build) (64-bit) in December, 2023, on Windows 10, I run the following snippet in the Chrome DEV console, and I expect to see the Garbage collected message in the output of the said console, but I don’t, what am I doing wrong?

const obj = {};
const registry = new FinalizationRegistry(note => {
  console.log(note);
});
registry.register(obj, 'Garbage collected');