How to check if swap operation can be performed on non negative integers in an array

I want a function that performs swap operations on the elements in an array in a fashion that the resulting array is strictly increasing. For example numbers = [13,31,30] will produce output false because by swapping 13 to 31, 31 to 13 and 30 to 03 the array is not strictly increasing. if the initial array is already strictly increasing. No actions needed. You are allowed to choose any number from the array and swap any two digits in it.

Angular a11y CDK – possible to not import the entire library?

We import Angular a11y CDK like so:

import { FocusableOption, FocusKeyManager } from '@angular/cdk/a11y';

It also imports all of the other a11y features, even those that we don’t need yet. Is there a way to import just what we need? Tried importing from @angular/cdk/a11y/key-manager/ or something equivalent. Are we going against the grain here by not importing from public-api?

enter image description here

how to export data to excel in reactjs

I have some data from a REST API server and I want to export them into an excel file. I saw in another question that it can be done using react-export-excel. but when I tried it like the example code, it gives this error even though I already included the jszip dependencies (3.10.0):

Could not find module in path: 'jszip/2.4.0' relative to '/node_modules/xlsx/xlsx.js'

if I changed the jszip into the 2.4.0 version, it gives this error instead:

Could not find module in path: 'jszip' relative to '/node_modules/xlsx/xlsx.js'

here’s my code (and here’s the codesandbox)

import "./styles.css";
import React from "react";
import ReactExport from "react-export-excel";

const ExcelFile = ReactExport.ExcelFile;
const ExcelSheet = ReactExport.ExcelFile.ExcelSheet;
const ExcelColumn = ReactExport.ExcelFile.ExcelColumn;

const dataSet1 = [
  {
    name: "Johson",
    amount: 30000,
    sex: "M",
    is_married: true
  },
  {
    name: "Monika",
    amount: 355000,
    sex: "F",
    is_married: false
  },
  {
    name: "John",
    amount: 250000,
    sex: "M",
    is_married: false
  },
  {
    name: "Josef",
    amount: 450500,
    sex: "M",
    is_married: true
  }
];

const dataSet2 = [
  {
    name: "Johnson",
    total: 25,
    remainig: 16
  },
  {
    name: "Josef",
    total: 25,
    remainig: 7
  }
];

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

How to reset dynamic object values to empty up on button click in react

In my react application I have a dynamic object called statusFilters which holds multiple variables. I wanted this object state value to be empty when I click a button. Here is my code.

ObjectList (minimal code)

function ObjectList({
  search,
  setSearch,
  trackingObjects,
  loading,
  error,
  selectedObj,
  setSelectedObj,
  statusFilters,
  setStatusCheckboxFilters,
  setStatusFilters,
}) {
  const handleClick = React.useCallback((obj) => {
    setSelectedObj(obj);
  }, []);
  console.log(statusFilters, "dynamic objects");

  const resultObjs = filterSearch(
    filterObjects(trackingObjects, statusFilters),
    search
  );

  const [res, setReset] = useState(false);
  const reset = () => setReset(!setStatusFilters);
  const objsWithLocations = resultObjs.filter(
    ({ location }) =>
      location?.[0] !== null &&
      location?.[0] !== undefined &&
      location?.[1] !== null &&
      location?.[1] !== undefined
  );

  const defaultFilterState = useMemo(
    () => makeDefaultFilterState(trackingObjects),
    [trackingObjects]
  );
  const filterOptionsObj = useMemo(
    () => makeFilterOptionsObj(trackingObjects),
    [trackingObjects]
  );
  const resetAllFilters = () => {
    setStatusFilters([]);
  };
  const filterHandler = (e) => {
    setStatusFilters({ ...statusFilters, [e.target.name]: e.target.checked });
  };

  const discardFilters = () => {
    setStatusFilters([]);
  };
}

Button to reset statusFilters object to null.

<Button
            variant="text"
            text="Reset"
            sx={{
              fontSize: "24px",
              p: 0,

              verticalAlign: "baseline",
              ml: "6px",
              textTransform: "none",
            }}
            onClick={() => resetAllFilters()}
          />

But when I click on Reset button I got TypeError: statusFilters is not a function at resetAllFilters error. How can I fix this issue?

Here is the console log output of statusFilters object

enter image description here

Hide text overflow

I have a table that lists various records. However, these entries can be very long and I would like to limit their display. The figure below is an example of what I have at the moment. But I would like that if the entry reaches the maximum width (maxWidth: ’90px’), then the rest of the entry is not displayed.
I tried to do it with

overFlow: 'hidden', 
textOverflow: 'ellipsis',

But for some reason this doesn’t work. Please tell me how to achieve the desired result

const TableDataCellStyle = {
    color: '#111115',
    fontWeight: 400,
    fontSize: '12px',
    padding: 0,
    border: 0,
    maxWidth: '90px',
    whiteSpace: 'nowrap'

}

Formatting json with Objet.entries with REACT

is there a way to get the Objective for each participant "Mona", "Paul","Bastian" using Object.entries? Because the format from my api is not what I want and I have to modify it before using it.

Do you see what’s wrong in my code pelase ?

I mean having this format :

 {
        "names": [
            {
                "name": Mona,
                "age" :63,
                "Average":75,
             },
             {
                "name": Paul,
                "age" :29,
                "Average":75,
             },
           ...             
        ],
    
    ...
    }

Instead of this format from mi api:

 {
        "names": [
            {
                "Mona": 63,
                "Paul": 29,
                "Bastian": 31,
                "Average": 75
              }
          
        ],
    ...
    }

Here my function:

const { names, locations } = graphs ?? {}
function RadarNames() {
    const data = Object.entries(graphs.names[0]).map(([key, value]) => ({
        "name": key,
        "age": value,
    }))
    return creacteChart({
        data: data,
        polarAngleAxisOptions: { dataKey: 'name' },
        radars: [
            {
                name: 'name',
                dataKey: 'age',
            
            },
            {
                name: 'Average',
                dataKey: 'Average',
             
            },

        ],
    })
}

Recursively loop through object to display key/value pairs

I am facing a difficulty to loop through an object (the object also contains array in different layers) with at least 6 layers and show key/value pairs. , I tried to use For…In statement or recursion to loop through it. Sadly, it was not successful. Could anyone kindly provide the solution for me please, thank you very much.

  1. Recursive Function
function keyValuePairFunc(obj) {
    for (const [key, value] of Object.entries(obj)) {
      console.log(`${key}: ${value}`)
      if (typeof value === "object") {
        for (const [key, val] of Object.entries(value)) {
          console.log(`${key}: ${val}`)
        }
      }
            
    }
  }

keyValuePairFunc(loadedData);
  1. Object needed to be loop through
    enter image description here

Getting stack overflow to color my code CORRECTLY [migrated]

I have been making various stackoverflow questions and answers that of course have code in them, like this.

app.get('/error', (req, res) => {
   res.render('signup', { error: 'enter a username'});
   // Could also be "enter your name", or "enter your password".
});

Many of my questions have both the tags “javascript”, and “html” into my post, to describe what my post is about. But as you can see, the javascript code above is not colored correcty, because I put both “html”, and “javascript” as my tags. But if I put just the “javascript” tag into my post the code colors correctly.
code with just javascript tag in the stackoverflow post (code colored correctly)

So is there a work-around to specify the language for a specific code block, regardless of the tags on the post, or do I just have to go with the bad coloring?

jquery button click works for only the first data in laravel foreach loop

Please i have a data i loop through from db to laravel view which return as a input field. i am trying to get individual inputs from the foreach when a button is clicked, but the button returns on the first loop data

My code :

$('.btn-invest').click(function() {
            var invest_id = $('.btn-invest').attr('data-invest-id');
    var btcaddress = '{{ $info->btc_address }}'
    // alert(invest_id);
            var amount = $('#amount').val();
            var min = $('#min').val();
            // int parse min
            min = parseInt(min);
            // int parse amount
            // amount = parseInt(amount);
            if(amount === ''){
               Swal.fire({
                  icon: 'error',
                  title: 'Oops...',
                  text: 'Please enter amount!',
                })
            }else if(parseInt(amount) < min){
                Swal.fire({
                  icon: 'error',
                  title: 'Oops...',
                  text: 'Please enter amount greater than minimum amount',
                })
                // alert();
            }
            else{
                // alert(`Request made, kindly send your payment of ${amount} to:`)
                Swal.fire({
                    title: `Request made, kindly send your payment of ${amount} to: ${btcaddress}`,
                    text: "",
                    icon: "success",
                })
            }
        });

Load a new glb model in three js

I have a function which loads a glb file into my THREE scene.
Then I have a guibutton that calls another function which in theory should load another model
into the scene.

This another function loads the model only sometimes, some others the console says that the model cannot be found(error 404).
It’s weird because changing the name of the loaded asset(say ‘test’ instead of ‘mytest’) makes the loader work(I don’t know why but occasionally it loads correctly).

Here’s the another function which supposedly has to load a new scene with a new model

   function loadAnother(){
        scene2 = new THREE.Scene()
        const loader2 = new THREE.GLTFLoader()
        loader2.load('assets/test.glb', function(glb){
        const root2 = glb.scene;
        root2.scale.set(1,1,1)
        scene2.add(root2);
        })

loadAnother()

This function produces a 404 error, but the test.glb I’m loading is spelled correctly

In Typescript, upon passing a declared class as an argument to Object.getPrototypeOf, the result refers to the parent class. Why is that?

For instance :

class Parent {

  foo() {
    console.log("foo");
  }
}

class Child extends Parent {

  bar() {
    console.log("bar");
  }
}

Here, the expression

Object.getPrototypeOf(Child) === Parent

would evaluate to true.

Now I understand the basics of prototypical inheritance and how classes work in Javascript that is, every function has a prototype property, which is copied on to the newly created class instance’s __proto__ property upon calling the function with the new operator

I also understand that Object.getPrototypeOf essentially returns the __proto__ property of any given object and generally we simulate inheritance in pure javascript by the means of setting the prototype property of the child class to an instance of the parent class, like this :

function Parent(){}
 
Parent.prototype.foo = function(){
  console.log("foo");
}
 
function Child(){}
 
// Inherit properties from Parent
Child.prototype = new Parent();

My questions are :

  • what does the result of Object.getPrototypeOf when called with a class as an argument represent ? How is it linked to class inheritance in TS/JS ?

  • Is it safe to use Object.getPrototypeOf to check if whether a particular class extends another class at runtime ?

Updating Json Value with that of another Json

I want to update automatically the value of comments_list with the values in the comments JSON object

const tweet = JSON.stringify({"tweet_id":1,"created_at":"2022-06-28","comments_list":[]})
const comments = JSON.stringify({"tweet_id":1,"commenter_id": 2"commenter_first_name":"tito","commenter_username":"tito_lulu"})

The final output should look like this

{"tweet_id":1,"created_at":"2022-06-28","comments_list":[{"commenter_id": 2"commenter_first_name":"tito","commenter_username":"tito_lulu"}]}

JSON not parsing correctly using JSON.parse but $.parseJSON works

In JS I have a string variable as follows:
Text JSON Data:

[{ "id" : "3", "parent" : "2", "text" : "Lack of Survey Information" },{ "id" : "4", "parent" : "3", "text" : "Lack of Surveyor Resource" },{ "id" : "5", "parent" : "3", "text" : "Land access unavailable" },{ "id" : "2", "parent" : "1", "text" : "Design Incorrect" },{ "id" : "1", "parent" : "16", "text" : "Abortive Work" },{ "id" : "6", "parent" : "1", "text" : "Wrong design info used in construction" },{ "id" : "16", "parent" : "#", "text" : "a" }]

This is output from the following code:

            console.log("Text JSON Data:"+strJSON)
        var objJSON=$.parseJSON(strJSON)
        var objJSON=JSON.parse(strJSON)

It parses using $.parseJSON but does not parse using JSON.parse (I get a bizarre “JSON.parse is not a valid function” error though it clearly is). I am using Chrome. It gets weirder, when I just use $.parseJSON successfully and then use JSON.stringify on the returned JSON object it crashes and throws up an error (“JSON.stringify is not a valid function”).

What is weird is that I pass several other JSON strings to this function and they are parsed fine. I thought it might be something to do with the ‘#’ symbol but it seems to parse OK in JSFiddle. I know when using VBA that sometimes an error code is triggered for a line of code when in fact the error is caused by something else. I am wondering if that is what is going on here.

What I need to understand is why this particular string is triggering the bizarre errors.

How to change no file chosen to a filename in Bootstrap using jQuery.?

I am trying to set no file chosen in upload file to a filename . How to set no file chosen to a file name.
What I have tried is:

<input class="form-control" id="imgInp" type="file" accept=".png,.jpg,.jpeg" name="img" required> 

On load of a form , I am trying to set value of no file chosen to a filename

$('#imgInp').val('abcd.jpg');

Output

How to change no file chosen in file input?