Object set getting sorted javascript

i have a object set like below.

"a":{
 "b2":{
 "head":"xyx"
},
"b1":{
  "head":"pqr",
  "body": "abc",
},
 "b3":{
 "head":"xyx"
},
}

I want to get object in same order as b2,b1,b3 but when I console object a the order changes to b1,b2,b3.
How I can get in the same order?

I want to change this javascript code to firestore

const Table = require(‘cli-table’)

const log = console.log

const mockdata = require(‘./mock.json’)
const mockdata2 = require(‘./mock2.json’)

// Make the data random by shuffling

function randomizeArr(arr) {

let cIndex = arr.length, tempValue, randomIndex

while (cIndex != 0) {

randomIndex = Math.floor(Math.random() * cIndex)

cIndex -= 1

tempValue = arr[cIndex]

arr[cIndex] = arr[randomIndex]

arr[randomIndex] = tempValue

}

return arr

}

const data = randomizeArr(mockdata)

const data2 = randomizeArr(mockdata2)

// Save the drawing data here

let drawingResult = []

// Loop over the data, I know it O(n^2) and you should avoid that

for (let i = 0;i < data.length;i++) {

for (let j = 0;j < data2.length;j++) {

const cIndex = data[i]

const againstIndex = data2[j]

// This is the match up logic, to follow the procedure (see README)

if (againstIndex.subcity == cIndex.subcity) {

  const drawOne = drawingResult.map(c => c.lane_id).indexOf(againstIndex.subcity)

  const drawTwo = drawingResult.map(c => c.subcity).indexOf(cIndex.lane_id)

  if (drawOne === -1 && drawTwo === -1) {

    cIndex.subcity = againstIndex.subcity ? drawingResult.push(cIndex, againstIndex) : 

drawingResult.push(cIndex,againstIndex)

  }

}

}

}

// Help me to create a beautiful table in terminal

const table = new Table({

head: [‘#’, ‘Home (first leg)’, ‘Away (first leg)’],

colWidths: [10, 50, 50]

})

let counter = 1

for (let i = 0;i < drawingResult.length;i += 2) {

table.push([counter, drawingResult[i].plate, drawingResult[i + 1].lane_id])

counter++

}

log(table.toString())

creating a dynamic value from only one variable that increases on each render?

I have the following logic that is scalable to only a certain degree in other words I have to write the logic manually for each case when a certain threshold has been reached current and biggest issue is I have a reference to only one item (thisCase) that gets increased each render.

any idea how to be able to se certain dynamic increment without having to write it manually for each case , this function is a utility function btw.

// let thisCase : number = 0  

// this case increase after each render and it has the maximum range of 8 

let increment = () => {
  if (thisCase > 8 && thisCase < 16) {
    alert('a');
  }
  if (thisCase > 16 && thisCase < 24) {
    alert('b');
  }
  if (thisCase > 24 && thisCase < 32) {
    alert('c');
  }
};

How to cancel pending promise calls inside callback function?

fetch(
                "https://rqyhfmwv4b.execute-api.us-east-1.amazonaws.com/production/join-meeting",
                requestOptions
            ).then((response) => response.json())
                .then(async (data) => {
                    // You need responses from server-side Chime API. See below for details.
                    const meetingResponse =
                        data.result
                            .meetingResponsee; /* The response from the CreateMeeting API action */
                    const attendeeResponse =
                        data.result
                            .attendeeResponsee; /* The response from the CreateAttendee or BatchCreateAttendee API action */
                    const configuration = new MeetingSessionConfiguration(
                        meetingResponse,
                        attendeeResponse
                    );

                    // In the usage examples below, you will use this meetingSession object.
                    const meetingSession = new DefaultMeetingSession(
                        configuration,
                        logger,
                        deviceController
                    );

                    const meetingReadinessChecker = new DefaultMeetingReadinessChecker(
                        logger,
                        meetingSession
                    );

                    // testing

                    if (pauseReadinessTest) {
                        setPauseReadinessTest(false);
                        return;
                    }

                    if (testParam == "All" && disableStartRedinessTest !== true) {
                        await audioTest(deviceController);
                        setMeetingTestProgress(15);
                        await micTest(meetingSession, meetingReadinessChecker, CheckAudioInputFeedback);
                        setMeetingTestProgress(25);
                        await videoTest(meetingSession, meetingReadinessChecker, CheckVideoInputFeedback);
                        await cameraTest(meetingSession, meetingReadinessChecker, CheckCameraResolutionFeedback);
                        setMeetingTestProgress(50);
                        await networkTest(meetingReadinessChecker, CheckNetworkTCPConnectivityFeedback, CheckNetworkUDPConnectivityFeedback);
                        setMeetingTestProgress(75);
                        await streamTest(meetingSession, meetingReadinessChecker, CheckAudioConnectivityFeedback, CheckVideoConnectivityFeedback);
                        setMeetingTestProgress(85);
                        await screenShareTest(meetingSession, meetingReadinessChecker, CheckContentShareConnectivityFeedback);
                        setMeetingTestProgress(100);
                        setRefreshIconClass(" ");
                        SetDisableStartRedinessTest(false);
                        setIsResult("result");
                    }

I have this block of code and I want to cancel the pending await function calls if at any point in time the user wants to exit from the test. But the issue is whenever the value of a variable gets updated it doesn’t reflect inside the block which is causing the main issue over here.

How to prevent a function from running multiple times using async, await? [duplicate]

I created an async function and I would like to call await only after some seconds so that I will not make request multiple times.
For that I created setTimeout function and make that async so that I can await my function inside it but still If I check network tab, I can see that request has been sent multiple times.
enter image description here
enter image description here

required a group of checkbox

i am making a form where i need to make gender field by using checkbox and make it required

$(document).ready(function() {
  $('.check3').click(function() {
    $('.check3').not(this).prop('checked', false);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row mx-auto">
  <div class="border border-dark col-sm-3">
    <h4 class="d-inline">Gender</h4>
    <p class="d-inline">*</p>
  </div>
  <div class="border border-dark col-sm-2"><input type="checkbox" class="check3">Male</div>
  <div class="border border-dark col-sm-2"><input type="checkbox" class="check3">Female</div>
  <div class="border border-dark col-sm-5"><input type="checkbox" class="check3">Transgender</div>
</div>

here i am able select any one field out of 3 but cannot make it required

Cannot read properties of undefined (reading ‘equal’)

TypeError: Cannot read properties of undefined (reading ‘equal’) and also in truffle console when i try to see the number of candidates it is also undefined. is there any problme with the command (.candidatesCount().toNumber)?

const { assert } = require("assert");


var Election = artifacts.require("./Election.sol");

contract("Election", function (acc) {
  it("initializes with two candidates", function () {
    return Election.deployed()
      .then(function (ins) {
        return ins.candidatesCount();
      })
      .then(function (count) {
        assert.equal(count, 2);
      });
  });
});

How to POST redirect to a new URL from Ajax on Success?

I have this code:

$.ajax({
    type: "POST",
    url: "/pro_signup",
    data: { data: data, key: key },
    dataType: "json",
    success: function (response) {
      document.getElementById("purchase").innerHTML =
        '<button class="btn btn-primary button-connected">Verifying...</button><p class="grey-text">Waiting for verification...</p>';
      window.location.href = "/pro_account";
    },
    error: function (exception) {
      document.getElementById("purchase").innerHTML =
        '<button class="btn btn-primary button-error">Failed</button><p class="grey-text">Verification has failed.</p>';
    },
  });

I have a route in my flask backend /pro_account that must only accept POST requests, so in success in the code above I cannot use window.location.href = "/pro_account";

How do I change this part (or the entire code) to make a post request on success to redirect to the /pro_account URL?

How to write pretty URL based from data?

How to write pretty url from these data?
I need something like this https://mywebsite.com/admin/leads/count/data1/data2/data3

Thanks in advance. 🙂

var x = {data1, data2, data3};

$.ajax({
url: ‘https://mywebsite.com/admin/leads/count/’,
data: x,
type: ‘GET’,
contentType: “application/x-www-form-urlencoded”,
datatype: “json”,
async: false,
success: function(data){
$(“#leads_count”).val(data);
leadsCtr = data;
}
});

how to display scroll to top/bottom in vertical page bar only?

I want my scroll to top/button to appear in pages that have vertical scrollbar only. It is working as intended. However, whenever i clicked scroll back to top button , the button will become scroll back to bottom button. The scroll back to bottom button will always appear in every page including pages that do not have vertical scrollbar. Is there any way to solve this problem ?

ScrollToTop.vue

<template>

      <div v-scroll="onScroll" >
        <v-btn v-if = "!isVisible"
            fab fixed bottom right color="primary" @click="toBottom">
            <v-icon>mdi-arrow-down-bold-box-outline</v-icon>
        </v-btn>

        <v-btn v-else
            fab fixed bottom right color="primary" @click="toTop">
            <v-icon>mdi-arrow-up-bold-box-outline</v-icon>
        </v-btn>
      </div>
</template>

<script>

export default{

    data () {
        return {
        isVisible: false,
        position: 0,


    }
  },
   methods: {
    onScroll () {
      this.isVisible = window.scrollY > 100
    },
    toTop () {
      this.position = window.scrollY
      window.scrollTo({
        top: 0,
        left: 0,
        behavior: 'smooth'
      })
    },
    toBottom(){
      let pos = this.position > 0 ? this.position : document.body.scrollHeight
      window.scrollTo({
        top: pos,
        behavior: 'smooth'
      })
    },

  }
}

</script>

Default.vue

<script>

export default {
    name: "DefaultLayout",
    data() {
        return {

            hasScroll: false
        };
    },
    methods: {

        hasVerticalScroll() {
        this.hasScroll = document.body.offsetHeight > window.innerHeight;

    }
    },

}
</script>

<template>
  <v-app dark v-scroll="hasVerticalScroll">

     <ScrollToTop v-if="hasScroll"/>

  </v-app>
</template>



Changes made on my local server does not reflect in production

When I apply this regular expression, it works in my local server but not prod

function businessSize(a, b) {
return a.replace(/^d+/g, "") - b.replace(/^d+/g, "");
}
sizes.sort(businessSize);
sizes.reverse();

This is how it looks on my local server. and that is how I want it to look on prod also.

Local server

This is how it comes to shows in production. the 1-19 goes to the bottom. How can I make sure it stays on top

Production Server

Get Deeply Nested Documents in Mongoose

I am building a side project that uses a mongodb database. I am using the MERN stack to build out a web application with my data. I am using Mongoose to get data from my database on a NodeJS/Express server to build my REST API. Here is an example of the data I have. I have deeply nested subdocuments that I need to retrieve. Each user has an array of ‘contacts’. Each ‘contact’ has an array of ‘tasks’. I would like to get an array of all tasks that are nested in each user. For example, if a user has 2 contacts, and each contact has 3 tasks, I would like an array with 6 tasks.

{
   userName: 'jdoe',
   uid: 12343,
   contacts: [
      {
          name: 'Jane Doe',
          tasks:[
             {
                taskName: 'Task1'
             },
             {
                taskName: 'Task2'
             },
             {
                taskName: 'Task3'
             },
          
          ]
      },
      {
          name: 'Bob Smith',
          tasks:[
             {
                taskName: 'TaskA'
             },
             {
                taskName: 'TaskB'
             },
             {
                taskName: 'TaskC'
             },
          
          ]
      }
   ]
}

To query my data with Mongoose, I tried something like this

User.findOne({uid: req.params.uid}, 'contacts.tasks', (yasks,err)=>{
  if(err){
    res.send(err)
  }else{
      res.send(tasks)
    }
})

However, this query returns something like this

{
"_id": "353453",
"contacts": [
    {
        "tasks": [
            {
                 taskName: 'Task1'
            }
        ]
    },
    {
        "tasks": [
            {
                 taskName: 'Task1'
            },
            {
                 taskName: 'Task1'
            }
        ]
    },
    {
        "tasks": []
    },
    {
        "tasks": []
    }
   ]
}

I am looking for a response such as this

       [
            {
                 taskName: 'Task1'
            },
            {
                 taskName: 'Task1'
            },
                            {
                 taskName: 'Task1'
            },
            {
                 taskName: 'Task1'
            }
        ]  

I am wondering if there i any way I can do this with Mongoose. If not, what kind of javascript can I run to transform my data to be structured like this? Any help is greatly appreciated!

Webpack Won’t Load PNG Despite Require, Config and Modules Reinstall

There are several threads about this one issue, but none of them have yielded any results to me so far. As the title suggests, my React project contains an img tag, where a png is provided as it’s source.

So far, I have tried using requiring the path AND importing it as a variable. I have also added the loaders in my webpack config as you can see below.

Also of note is that the dimensions are actually loaded, and when right clicking to check the image source, the website returns a Cannot GET /[object%20Object]

Any insight is greatly greatly appreciated!

Thank you in advance!

Image Tag

 <img src={require('./mug1.png').default} className="mugImage" />

CSS

.mugImage {
  object-fit: cover;
  width: 100%;
  height: 100%;
  z-index: 10;
}

Webpack

const HtmlWebPackPlugin = require("html-webpack-plugin");
const htmlPlugin = new HtmlWebPackPlugin({
  template: "./src/index.html",
  filename: "./index.html"
});
module.exports = {
  mode: "development",
  resolve: {
    fallback: {
      assert: require.resolve('assert'),
      crypto: require.resolve('crypto-browserify'),
      http: require.resolve('stream-http'),
      https: require.resolve('https-browserify'),
      os: require.resolve('os-browserify/browser'),
      stream: require.resolve('stream-browserify'),
    },
  },
  module: {
    rules: [{
      test: /.js$/,
      exclude: /node_modules/,
      use: {
        loader: "babel-loader"
      }
    },
    {
      test: /.css$/,
      use: ["style-loader", "css-loader"]
    }, {
      test: /.(jpg|png|svg)$/,
      use: {
        loader: 'url-loader',
        options: {
          limit: 25000
        }
      }
    },
    {
      test: /.(png|jpe?g|gif)$/i,
      use: [
        {
          loader: 'file-loader',
          options: {
            esModule: false,
          },
        },
      ],
    },



    ]
  },
  plugins: [htmlPlugin]
};

Stop body from scrolling on safari iOS 15

I have a scrollable page and a drawer. When the drawer is open (which is not scrollable) I noticed that when I do a scroll touch – from bottom to top or top to bottom, the safari url/search bar appears/disappears and this breaks my layout. I tried having overflow:hidden and touch-action:none on body when the drawer is open, but this doesn’t work on Safari. The only solution I found is setting the html overflow to hidden, but this makes the page behind the drawer to reset the scrolling position (0,0).
Is there any solution to keep the current scroll position while disabling this annoying effect?