How to cap a value between 2 integers?

Let’s say I am trying to state a range between two integers, i.e. 0 and 3. Anything that is lower than this range will loop back from the upper end, and vice versa. It is kind of like how integers work in other languages.

For example (range 0 to 3):

cap(-4) // returns 0
cap(-3) // returns 1
cap(-2) // returns 2
cap(-1) // returns 3
cap(0)  // returns 0
cap(1)  // returns 1
cap(2)  // returns 2
cap(3)  // returns 3
cap(4)  // returns 0
cap(5)  // returns 1
cap(6)  // returns 2
cap(7)  // returns 3
cap(8)  // returns 0

The best working code that I could make is this:

const cap = (value, low, high) =>  value < low ? high - (high - value) % (high - low + 1) : (value - low) % (high - low + 1) + low

Is there a more elegant way to do this? I feel like there’s a way to do this without using conditional.

How to Filiter nestead array of objects. using multiselect

   jsonData = [
      {
        isMaster: false,
        selected: false,
        ID: 0,
        "Profile Type": "Line of Business",
        Risk: [
          {
            isMaster: false,
            selected: false,
            ID: 0.1,
            "Overall Control Effectiveness": "Not Assessed",
            "Rating": "0",
            Control: [
              {
                isMaster: false,
                selected: false,
                ID: 0.2,
                "Control Classification": "Key",
                "Control Effectiveness Rating": "Partially Effective"
              },
              {
                isMaster: false,
                selected: false,
                ID: 0.21,
                "Control Classification": "Compensating",
                "Control Effectiveness Rating": "Partially Effective"
              }
            ]
          },
          {
            isMaster: false,
            selected: false,
            ID: 0.11,
            "Overall Control Effectiveness":"Insignificant",
            "Rating": "0",
              Control: [
                {
                  isMaster: false,
                  selected: false,
                  ID: 0.12,
                  "Control Classification": "Arrangement",
                  "Control Effectiveness Rating": "Partially Effective"
                },
                {
                  isMaster: false,
                  selected: false,
                  ID: 0.13,
                  "Control Classification": "Compensating",
                  "Control Effectiveness Rating": "Effective"
                }
              ]
          }
        ]
      },
      {
        isMaster: false,
        selected: false,
        ID: 1,
        "Profile Type": "Business Unit (BU) / Support Unit (SU)",
        Risk: [
          {
            isMaster: false,
            selected: false,
            ID: 1.1,
            "Overall Control Effectiveness": "Low",
            "Rating": "2",
            Control: [
              {
                isMaster: false,
                selected: false,
                ID: 1.2,
                "Control Classification": "key",
                "Control Effectiveness Rating": "Partially Effective"
              },
              {
                isMaster: false,
                selected: false,
                ID: 1.21,
                "Control Classification": "Arrangement",
                "Control Effectiveness Rating": "Partially Effective"
              },
              {
                isMaster: false,
                selected: false,
                ID: 1.22,
                "Control Classification": "key",
                "Control Effectiveness Rating": "Effective"
              },
            ]
          },
          {
            isMaster: false,
            selected: false,
            ID: 1.11,
            "Overall Control Effectiveness": "Medium",
            "Rating": "5",
          }
        ]
      },
      {
        isMaster: false,
        selected: false,
        ID: 2,
        Name: "0940375C025200FAA38ED98A F9DE03D61ADAB727BA8C26D4",
        "Business Profile Owner": "Susheel",
        Folder: "CBA / Audit",
        "Profile Type": "Business Profile Instances",
        Risk: [
          {
            isMaster: false,
            selected: false,
            ID: 2.1,
            "Overall Control Effectiveness": "High",
            "Rating": "5",
            Control: [
              {
                isMaster: false,
                selected: false,
                ID: 2.2,
                "Control Classification": "Arrangement",
                "Control Effectiveness Rating": "Not Determined"
              },
              {
                isMaster: false,
                selected: false,
                ID: 2.21,
                "Control Classification": "Arrangement",
                "Control Effectiveness Rating": "Not Tested"
              }
            ]
          },
          {
            isMaster: false,
            selected: false,
            ID: 2.11,
            "Overall Control Effectiveness": "very High",
            "Rating": "0",
          }
        ]
      },
      {
        isMaster: false,
        selected: false,
        ID: 3,
        "Profile Type": "Supplier",
        Risk: [
          {
            isMaster: false,
            selected: false,
            ID: 3.1,
            "Overall Control Effectiveness":"Lindgren",
              "Rating": "0",
            Control: [
              {
                isMaster: false,
                selected: false,
                ID: 3.2,
                "Control Classification": "Arrangement",
                "Control Effectiveness Rating": "Not Tested"
              },
              {
                isMaster: false,
                selected: false,
                ID: 3.21,
                "Control Classification": "Arrangement",
                "Control Effectiveness Rating": "Not Tested"
              }
            ]
          },
          {
            isMaster: false,
            selected: false,
            ID: 3.11,
            "Overall Control Effectiveness": "Lindgren",
            "Rating": "3",
          }
        ]
      },
    ];

Multi-select values are of the following types.

selection = [
         {
            name: "High",
            type: "Risk",
            column: "Overall Control Effectiveness"
        },
        {
           name: "5",
           type: "Risk",
           column: "Rating"
      }
    ]

 selection1 = [
             {
                name: "key",
                type: "Control",
                column: "Control Classification"
            },
            {
               name: "Not Assessed",
               type: "Risk",
               column: "Overall Control Effectiveness"
          }
        ]

 selection2 = [
             {
                name: "key",
                type: "Control",
                column: "Control Classification"
            },
            {
               name: "Not Assessed",
               type: "Risk",
               column: "Overall Control Effectiveness"
          },{
               name: "0",
               type: "Risk",
               column: "Rating"
          }
        ]

these selections are of type Dynamic.

if the selections of having only the same types (eg: type=”Risk”) we need to print all matching values.
nothing but || (OR operation)

if the selections of having the different types (eg: type=”Risk” , type=”Control”) we need to print satisfying values as nothing but && (AND operation).

if selection2 is selected then the following will be the output.

 {
    isMaster: false,
    selected: false,
    ID: 0,
    "Profile Type": "Line of Business",
    Risk: [
      {
        isMaster: false,
        selected: false,
        ID: 0.1,
        "Overall Control Effectiveness": "Not Assessed",
        "Rating": "0",
        Control: [
          {
            isMaster: false,
            selected: false,
            ID: 0.2,
            "Control Classification": "Key",
            "Control Effectiveness Rating": "Partially Effective"
          }
        ]
       }
     ]
   }

       const jsonData = [
          {
            isMaster: false,
            selected: false,
            ID: 0,
            "Profile Type": "Line of Business",
            Risk: [
              {
                isMaster: false,
                selected: false,
                ID: 0.1,
                "Overall Control Effectiveness": "Not Assessed",
                "Rating": "0",
                Control: [
                  {
                    isMaster: false,
                    selected: false,
                    ID: 0.2,
                    "Control Classification": "Key",
                    "Control Effectiveness Rating": "Partially Effective"
                  },
                  {
                    isMaster: false,
                    selected: false,
                    ID: 0.21,
                    "Control Classification": "Compensating",
                    "Control Effectiveness Rating": "Partially Effective"
                  }
                ]
              },
              {
                isMaster: false,
                selected: false,
                ID: 0.11,
                "Overall Control Effectiveness":"Insignificant",
                "Rating": "0",
                  Control: [
                    {
                      isMaster: false,
                      selected: false,
                      ID: 0.12,
                      "Control Classification": "Arrangement",
                      "Control Effectiveness Rating": "Partially Effective"
                    },
                    {
                      isMaster: false,
                      selected: false,
                      ID: 0.13,
                      "Control Classification": "Compensating",
                      "Control Effectiveness Rating": "Effective"
                    }
                  ]
              }
            ]
          },
          {
            isMaster: false,
            selected: false,
            ID: 1,
            "Profile Type": "Business Unit (BU) / Support Unit (SU)",
            Risk: [
              {
                isMaster: false,
                selected: false,
                ID: 1.1,
                "Overall Control Effectiveness": "Low",
                "Rating": "2",
                Control: [
                  {
                    isMaster: false,
                    selected: false,
                    ID: 1.2,
                    "Control Classification": "key",
                    "Control Effectiveness Rating": "Partially Effective"
                  },
                  {
                    isMaster: false,
                    selected: false,
                    ID: 1.21,
                    "Control Classification": "Arrangement",
                    "Control Effectiveness Rating": "Partially Effective"
                  },
                  {
                    isMaster: false,
                    selected: false,
                    ID: 1.22,
                    "Control Classification": "key",
                    "Control Effectiveness Rating": "Effective"
                  },
                ]
              },
              {
                isMaster: false,
                selected: false,
                ID: 1.11,
                "Overall Control Effectiveness": "Medium",
                "Rating": "5",
              }
            ]
          },
          {
            isMaster: false,
            selected: false,
            ID: 2,
            Name: "0940375C025200FAA38ED98A F9DE03D61ADAB727BA8C26D4",
            "Business Profile Owner": "Susheel",
            Folder: "CBA / Audit",
            "Profile Type": "Business Profile Instances",
            Risk: [
              {
                isMaster: false,
                selected: false,
                ID: 2.1,
                "Overall Control Effectiveness": "High",
                "Rating": "5",
                Control: [
                  {
                    isMaster: false,
                    selected: false,
                    ID: 2.2,
                    "Control Classification": "Arrangement",
                    "Control Effectiveness Rating": "Not Determined"
                  },
                  {
                    isMaster: false,
                    selected: false,
                    ID: 2.21,
                    "Control Classification": "Arrangement",
                    "Control Effectiveness Rating": "Not Tested"
                  }
                ]
              },
              {
                isMaster: false,
                selected: false,
                ID: 2.11,
                "Overall Control Effectiveness": "very High",
                "Rating": "0",
              }
            ]
          },
          {
            isMaster: false,
            selected: false,
            ID: 3,
            "Profile Type": "Supplier",
            Risk: [
              {
                isMaster: false,
                selected: false,
                ID: 3.1,
                "Overall Control Effectiveness":"Lindgren",
                  "Rating": "0",
                Control: [
                  {
                    isMaster: false,
                    selected: false,
                    ID: 3.2,
                    "Control Classification": "Arrangement",
                    "Control Effectiveness Rating": "Not Tested"
                  },
                  {
                    isMaster: false,
                    selected: false,
                    ID: 3.21,
                    "Control Classification": "Arrangement",
                    "Control Effectiveness Rating": "Not Tested"
                  }
                ]
              },
              {
                isMaster: false,
                selected: false,
                ID: 3.11,
                "Overall Control Effectiveness": "Lindgren",
                "Rating": "3",
              }
            ]
          },
        ];


const selection2 = [
                 {
                    name: "key",
                    type: "Control",
                    column: "Control Classification"
                },
                {
                   name: "Not Assessed",
                   type: "Risk",
                   column: "Overall Control Effectiveness"
              },{
                   name: "0",
                   type: "Risk",
                   column: "Rating"
              }
            ];

function isArray(val) {
  return Array.isArray(val);
}


function isObject(val) {
  return val && typeof val === 'object' && val.constructor === Object;
}
 
 function onFilter(selection2) {
   let finalOutput = [];
   let selectionType = [];
   
   selection2.map(function items(i) {
       selectionType.push(i.type)
   })
      let templist = jsonData;


     templist = templist.filter((item) => {



      if (isObject(item)) {
        objectLoop(item);
        function objectLoop(item) {
          Object.keys(item).forEach((key) => {

            selection2.map(function items(i) {
               if(items[key] == i.column) {
               

                }
            })
              


            if (isObject(item[key])) {
              objectLoop(item[key]);
            }
            if (isArray(item[key])) {
              item[key].map((subItems) => {
                if (isObject(subItems)) {
                  objectLoop(subItems);
                }
              });
            }
          });
        }
      }
      return item;
    });
    
    console.log(templist)
  }
  
onFilter(selection2)

   
            
            
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Filtering table data using multiple columns in JavaScript

I am trying to make a filter/search table and I am using the JavaScript from this site.

Here’s the script:

function myFunction() {
  // Declare variables
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");

  // Loop through all table rows, and hide those who don't match the search query
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}

You can change which column to be used as the filter by changing the index in “td = tr[i].getElementsByTagName(“td”)[0];”

0 means the first column will be used, 1 means the second column, etc.

Using the same script, how can I use multiple columns to be the filter?

Flask get checkbox value without submit button

I’m trying to get value of checkbox in flask without a submit.

here is my app.py

from flask import Flask, render_template, request

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.form.get('c_check')=="0":
        print('success: 0')
        checked=''
    elif request.form.get('c_check')=="1":
        print('success: 1')
        checked='checked'
    return render_template('index.html')

Here is my javascript that toggle the checkbox:

function hello(){
    if (document.querySelector('input').value=='0'){    
        document.querySelector('input').value='1'
        console.log('value 1');
    }
    else {
        document.querySelector('input').value='0'
        console.log('value 0');
}

}

And here is my index.html

<form method="post" action="">

    <div class="form-check form-switch">
        <input class="form-check-input btn-lg" 
        name="c_check" 
        value="0" 
        type="checkbox" 
        role="switch" 
        id="flexSwitchCheckChecked" 
        onclick="hello()"
        >
        
        <label class="form-check-label btn-lg" 
        for="flexSwitchCheckChecked"></label>
        <input type="submit">
    </div>
</form>

<script src="{{url_for('static', filename= 'js/hello.js')}}"></script>

I want to

  1. Remove the submit button
  2. When I click on the checkbox, python should receive the checkbox value, 0 or 1.

The present code only returns 1 when I click the submit button. The solution should be that I remove the submit button entirely and have python listen on the value change and print that in real time.

I’m open to socketio solution, but I don’t know how to do it.

Thank you for your help.

How to crop an image on canvas and resize at the same time

I would like to cut this Banana image with this Mask Image so that I get this Cropped Banana image as a result.

I tried using ctx.globalCompositeOperation = 'destination-out'; but I get Banana with black frame or white frame only. The mask image covers up the source image, but it does not actually cut and shows the cut out part only.

Is there a way to achieve this without having white/black background?

Thanks! Happy coding!

How to find quality parameter in compressjs dynamically

My file size is 500kb (It will come dynamically anysize). And my target is 150kb.

For some reasons i can choose only quality

new Compressor(selectedFile1, {
            quality: targetRatio,

i.e., If i pass targetRatio to 0.7, it will reduce image to 159kb~

To find the targetRatio dynamically what i did is

var targetRatio = fileSize / 150;

But, I cannot figure out how to do find the targetRatio to get exact value i.e., to reduce into 150kb

Here’s the place to test

This is a question about http request method

var http = require('http');
var fs = require('fs');
var querystring = require('querystring');
const port = 3000;
var server = http.createServer(function(req, res) {
    if(  ){
        fs.readFile('./index.html' ,'utf8' ,function(error, data) {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end()
           
        });
    }

    

}).listen(port, function() {
    console.log('Server is running...');
});

If the request method is get,
I am trying to execute a conditional statement.
I don’t know how to write the content in the conditional statement.

It’s a simple question, but I’d appreciate it if you could answer it.

React Material UI dropdown menu position changed during zoom out

In React Material UI v4 or v5, there is a common problem with zoom out, for example, if you put the following style to body or HTML tag:

    body {
    zoom: 80%; /* Zoom out */
    }

all the dropdowns in the Material UI position will be shifted from the correct place that must be on it.

1: This is the correct place without zoom:

enter image description here

2: This is the issue after adding zoom:

enter image description here

3: This is the video for the problem:

Dropdown menu video Mui v4

4: Some notes about this issue:

1- Actually, we can fix the problem using browser zoom out by pressing command and [ – ] key, but I’m looking for a code-based solution without telling the users to do something.

2- Select2 not facing the same issue, you can zoom out and keep the menu in the same place, maybe that because the way of implementing the dropdown is different.

Sandbox link for Select2

3- Angular Material not facing the same issue you can follow the link for the sandbox Angular to make sure there is no issue with zoom out.

5: The question is how to make Material UI behaves like Select2/ Angular Material or the normal dropdown
without telling users to do something, How does Material UI determine the dropdown menu position? how we can override this function?

Getting Leaflet markercluster text / properties for cluster popup tooltips?

Following this tutorial on how to get custom tooltips on Leaflet.markercluster popups and I don’t understand how the marker attributes are built with a.layer._markers[feat].feature.properties['name'], as I don’t know how to refer to the relevant text / property in my code. Their eg, simplified:

markers.on('clusterclick', function(a){
            popUpText = '<ul>';
            for (feat in a.layer._markers){
                popUpText+= '<li>' + a.layer._markers[feat].feature.properties['name'] + '</li>';
            }
            popUpText += '</ul>';
            var popup = L.popup().setLatLng([a.layer._cLatLng.lat, a.layer._cLatLng.lng]).setContent(popUpText).openOn(map); 
        })

The browser shows “Uncaught TypeError: a.layer._markers[feat].feature is undefined”, and this is the only time the tutorial refers to a.layer._markers[feat].feature.properties['name']. My code for non cluster popups:

var addressPoints = [
[36.942, 69.902, "a"],
[36.946, 69.911, "b"],
[36.943, 69.909, "c"],
]

for (var i = 0; i < addressPoints.length; i++) {
  var a = addressPoints[i];
  var title = a[2];
  var marker = L.marker(new L.LatLng(a[0], a[1]), {title: title});
  marker.bindPopup(a[2]);
  markers.addLayer(marker);
}

map.addLayer(markers);

I can’t find it through seemingly any variation of a.layer_markers[whatever]. How can I adjust their example to get the equivalent a.layer._markers[feat].feature.properties['name'] from my markers? Or how can I troubleshoot this by finding the properties of a.layer_markers[whatever] to make the tooltip display “a”, “b”, or other properties provided in addressPoints?

(‘navigation.navigate’) undefined is not an object

I’m working on the TouchaleOpacity with onPress to navigate to screen called ‘SignInScreen’, but isn’t work … (onPress={() => navigation.navigate(‘SignInScreen’)}) That error TypeError: undefined is not an object (evaluating ‘navigation.navigate’). Please help me fix this problem. I’ve done many stuff but still I can’t’ fix it.

IMPORTS

import React, { useState } from 'react';
import { LinearGradient } from 'expo-linear-gradient';
import { useTheme } from '@react-navigation/native';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import { ImageBackground, StyleSheet, View, Image, Text, TextInput, Button, TouchableOpacity, Dimensions, StatusBar, Animated } from 'react-native';
import * as Animatable from 'react-native-animatable';
const WelcomeScreen = ({navigation}) => {
    return (
        <View style={styles.container}>
            <View style={styles.header}>
                <Animatable.Image 
                animation="bounceIn" duration={1500} source={require('../assets/logo1.png')} style={styles.logo} resizeMode="stretch"/>
            </View>
            <Animatable.View style={styles.footer} animation="fadeInUpBig">
                <Text style={styles.title}>Stay connected with everyone!</Text>
                <Text style={styles.text}>Sign in with account</Text>
                <View style={styles.button}>
                <TouchableOpacity onPress={() => navigation.navigate('SignInScreen')}>
                    <LinearGradient colors={['#d60939', '#ad022a']} style={styles.signIn} title="Go to SignInScreen">
                        <Text style={styles.textSign}>Get Started</Text>
                        <MaterialIcons name="navigate-next" color="#fff" size={20}/>
                    </LinearGradient>
                </TouchableOpacity>
                </View>
            </Animatable.View>
        </View>
    );
}

const {height} = Dimensions.get("screen");
const height_logo = height * 0.28;

const styles = StyleSheet.create({
    background: {
        flex: 1,
        justifyContent: "flex-end",
        alignItems: 'center',
    },
    container: {
        flex: 1, 
        backgroundColor: '#cfcfcf'
    },
    loginButton: {
        width: '100%',
        height: 60,
        backgroundColor: '#242222',
    },
    registerButton: {
        width: '100%',
        height: 60,
        backgroundColor: '#0d0c0c',
    },
    logo: {
        width: height_logo,
        height: height_logo,
    },
    button: {
        alignItems: 'flex-end',
        marginTop: 30
    },
    header: {
        flex: 2,
        justifyContent: 'center',
        alignItems: 'center'
    },
    footer: {
        flex: 1,
        backgroundColor: '#fff',
        borderTopLeftRadius: 30,
        borderTopRightRadius: 30,
        paddingVertical: 50,
        paddingHorizontal: 30
    },
    logoContainer: {
        position: 'absolute',
        top: '20%',
        alignItems: 'center',
    },
    title: {
        color: '#05375a',
        fontSize: 30,
        fontWeight: 'bold'
    },
    text: {
        color: 'grey',
        marginTop:5
    },
    signIn: {
        width: 150,
        height: 40,
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 50,
        flexDirection: 'row'
    },
    textSign: {
        color: 'white',
        fontWeight: 'bold'
    },
    apptitle: {
        fontWeight: "bold",
        color: 'white',
        textShadowColor: 'rgba(0, 0, 0, 0.75)',
        textShadowOffset: {width: -1, height: 1},
        textShadowRadius: 10,
        padding: 5,
        borderRadius: 10,
        fontSize: 40,
        letterSpacing: 10,
    },
    info: {
        fontWeight: "bold",
        color: 'white',
        top: 20,
        borderRadius: 10,
        fontSize: 20,
        textAlign: 'center',
    },
    logindetails: {
        width: '70%', 
        height: 60, 
        backgroundColor: 'white', 
        textAlign: 'center',
        borderRadius: 50,
        margin: 5,
        color: 'black',
        bottom: '27%',
    },
})


export default WelcomeScreen;



OUTPUT

Uncaught Error: undefined is not an object (evaluating 'navigation.navigate')

SingInScreen what I want to navigate

import React from 'react'
import { View, Text, Button, StyleSheet } from 'react-native'

const SignInScreen = () => {
    return (
        <View>
            <Text>SignInSreen</Text>
            <Button title="Click Here" onPress={() => alert('Button Clicked!')}/>
        </View>
    )
}

export default SignInScreen;

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center'
    },
})

enter image description here

Is there any way to use the values(Boolean) of two Callback functions in Node.js?

Here is my Problem:

I need to write a Test in Node.js for a function, which select the data from database. It returns the value by using a callback function.(Code is down below.)

getCompanyById(id, callback) {
        let company = null;
        this.db.query("SELECT * FROM Company where id=?", id)
            .on('result', function (data) {
                company = data;
            })
            .on('end', function () {
                callback(company);
            });
 }

What I want to do in the Test function is:

  1. Test this function with all id(here 1 and 2);
  2. If all the Tests passed, console.log(“Test for getCompanyById() passed”).

And here is the original version of my test Code.

function testGetSchoolAdministrationById() {
  var pass1,pass2;
  databaseConnection.getSchoolAdministrationById(1, function (schoolAdministration) {
      if(schoolAdministration.first_name == "Harald" &&
            schoolAdministration.last_name == "Schmidt" &&
            schoolAdministration.id_schoolAdmin == 1)
         pass1=true;
    }
  );
  databaseConnection.getSchoolAdministrationById(2, function (schoolAdministration) {
      if(schoolAdministration.first_name == "Madeline" &&
            schoolAdministration.last_name == "Müller" &&
            schoolAdministration.id_schoolAdmin == 2)
           pass2=true;
    }
  );
  console.log("Test for getCompanyById() passed: " + (pass1 && pass2));
}

But it returns “undefined”. After I searched on Internet, I realized that Node.js is Asynchrony and it won’t work this way. console.log("..") have already finished, while the callback have not yet. Also I have seen Answers, like use another Callback function to deal with the value. But in my case I have 2 Callbacks and no idea how to do it.

So here is my question:

  1. Is there any ways to achieve the goal of the function testGetSchoolAdministrationById() without changing the function getCompanyById(id, callback)?(Cause this has a quite big influence to other Codes.)

  2. If the 1. question is not possible, is there any ways to achieve the goal, while the function getCompanyById(id, callback) can be changed? In other word, is there any better ways to achieve the same goal of getCompanyById(id, callback) without using callbacks?

  3. Or maybe a Test Framework will help this? I’m not using any Test Framework, cause I haven’t tried and I’ not really familiar to those.

This is my first Project about Node.js, so I am not very confident about any concept I mentioned above. So any suggestions and answers are welcomed. And since this is also my first question on Stack overflow, any suggestions about the questions/title/structure are also welcomed. Hope that, I described this clearly. I really want to figure this out.

How to render new password with button in input field? PHP

I got problem,where after I hit Heslo(password) button it did what it should, but everytime resets whole page. How should I make it, that after hitting button it renders new password just in input field without reseting whole page?

this is part, where password is generated

<?php

if(!isset($_POST['generate'])){
  $password = "heslo pre edit/delete";
}else{
  $password = substr(md5(rand()), 0, 5);
}

?>

and html part for button and input

 <div class="input-group mb-3">
     <div class="input-group-prepend">
     <button class="btn btn-dark" type="submit" id="generate" name="generate">Heslo</button>
 </div>
     <input readonly="readonly" type="text" class="form-control"  name="editPassword" 
      id="editPassword" value="<?php echo $password ?>">
 </div>

enter image description here

Applying Specific Data Formatting from a Returned Data Object in JavaScript

I have a list of project data as below, the data in the object is based on the projectId. I am now trying to make a new data object that will be formatted based on userId to see which user has which projectId.

const projects = [
  {
    projectId: "abc123",
    name: "Project 1",
    userProjects: [
      {
        userId: "xyz789",
        projectId: "abc123",
        user: {
          userId: "xyz789",
          email: "[email protected]"
        },
      },
      {
        userId: "sdf012",
        projectId: "abc123",
        user: {
          userId: "sdf012",
          email: "[email protected]"
        },
      },
    ],
  },
  {
    projectId: "def456",
    name: "Project 2",
    userProjects: [
      {
        userId: "xyz789",
        projectId: "def456",
        user: {
          userId: "xyz789",
          email: "[email protected]"
        },
      },
    ],
  },
]

Below is my code that I am able to get all the existing users and all the existing projects.

const userInfo = [];
const projectInfo = [];

for (let i = 0; i < projects.length; i++) {
  const userProject = projects[i].userProjects;

  for (let j = 0; j < userProject.length; j++) {
    const projectExist = projectInfo.some((project) =>
      project.projectId.includes(userProject[j].projectId)
    );
    if (!projectExist)
      projectInfo.push({
        projectId: projects[i].projectId,
        name: projects[i].name,
      });

    const userExist = userInfo.some((item) =>
      item.userId.includes(userProject[j].user.userId)
    );
    if (!userExist)
      userInfo.push({
        userId: userProject[j].user.userId,
        email: userProject[j].user.email,
        project: projectInfo,
      });
  }
}

However, I am having to implement that which user owns which project. If now I print out the userInfo, it will show up both users has both projects in the array, which is not correct (user sdf012 only has the abc123).

Also, I am bad at data formatting like this task. Are there any resources you would recommend to learn? It is so important as I work with MongoDB and sometimes need to retrieve data and modify data to different specific formatting.

Thank you for the help!!!

Iterate nested object with for loop

how can I get the values of a nested object in a loop? I need to iterate through both levels:

for (let unit in ds1.units) {      
    for (let ports in ds1.units[unit].switchPorts) {
        console.log(ports)
    }
}

}

Object looks like this:
Screen
There is no output. When I access the value with ds1.units[unit].switchPorts I get it. Also I get the unit after the first for loop.