How do I know if the user is a Discord Nitro subscriber or not?

How do I know if the user is a Discord Nitro subscriber or not? If subscriber convert to nitro emoji? I tried the code below but, even though the user is not a subscriber, it is showing the emoji.

    const isNitro = user.premiumSinceTimestamp !== null;
    let nitroEmoji = "";
    
    if (isNitro) {
      nitroEmoji = '<:nitro:1061528915610443847>';
    } else {
      return;
    }
    
    

const badges = user.client.users.cache

  .get(user.id)
  .flags.toArray()
  .map((flag) => {
    switch (flag) {
      case "PremiumEarlySupporter":
        return "<:rhx_earlysupporter:1061699404731523172>";
      case "ActiveDeveloper":
        return "<:rhx_activedeveloper:1061699496377073777>";
      case "HYPESQUADONLINEHOUSE1":
        return "<:HypeSquadBravery:1061533364693246003>";
      case "HYPESQUADONLINEHOUSE2":
        return "<:Badge_Brilliance:1061533563612307538>";
      case "HypeSquadOnlineHouse3":
        return "<:Badge_Balance:1061533833540927488>";
      case "VerifiedDeveloper":
        return "<:rhx_earlyverifieddeveloper:1061699872824230009>";
        


const badgesString = badges.join(" ");


const embed = new Discord.EmbedBuilder()
  .setTitle(nitroEmoji + badgesString + ` ${user.tag}`)
  .setColor("Black");


message.reply({ embeds:  });

   } 

}

Jest test that simulates throwing an Axios exception fails with empty error message

I am trying to write a Jest test to cover a scenario whereby an axios.post (in the code I am trying to test) throws and handles an exception. The test successfully throws an error for a mocked axios instance and the appropriate catch block in the code I am wishing to test is reached. However, the error/exception message is empty. This then causes some assertions that I am trying to do in the test to fail.

The relevant section of the code to test looks as follows:

try {
  // Call the token endpoint with the client/user credentials and check the response.
  const { status, data } = axios.post(authenticationConfig.tokenEndpoint, 
   'grant_type=client_credentials', { headers });

  if (status === StatusCodes.OK) {
    ...
  }
}
catch(err) {
  console.log(JSON.stringify(err));
  res.status(StatusCodes.UNAUTHORIZED);
  res.json(err.response.data.error);
}

The corresponding test looks like:

it('cannot get access token', async () => {
  const response = {
    response: {
      data: {
        error: 'My error'
      }
    }
  };

  const req = {
    headers: {
      'authorization': 'Basic client_id:client_secret'
    }
  };
  
  mockedAxios.mockImplementation(() => {
    throw new Error(response);
  });

  const provide = await authenticationMiddleware.provide(req, res, next);
  await provide(req, res, next);
  expect(mockedAxios).toBeCalledTimes(1);
  expect(res.status).toHaveBeenCalledTimes(1);
  expect(res.status).toHaveBeenCalledWith(StatusCodes.UNAUTHORIZED);
});

The err object in the catch block is logged out as an empty object even though from the test I’m throwing an error with a fully populated object. The test passes if I remove the ‘res.json’ statement from the catch block.

● authentication middleware › cannot get access token

    TypeError: Cannot read property 'data' of undefined

      89 |         console.log(JSON.stringify(err));
      90 |         res.status(StatusCodes.UNAUTHORIZED);
    > 91 |         res.json(err.response.data.error);

Any ideas most welcome please. No doubt the way that I’m mocking Axios and causing it to throw an exception is wrong. The code does enter the catch block but the ‘err’ object is empty for some reason.

Many thanks.

Customizing YAxis in Oracle Apex Chart

I have the following situation in Apex (v22.11): I have a chart with the type ‘Combination’; so the series are one line chart and 4 bar charts. The format of the y axis is ‘Percent’ (so the numbers are <= 1). The line chart has a fixed value (85% or .85) and the bar charts have variable (percent) numbers.
I have the following problem: I can’t customize the y axis of this chart and I can’t explain why.

The best solution for me in this case is, when the chart show the fixed value on this y axis on one side and on the other side the y axis customize the steps automatically. Because I am a beginner in JavaScript I could not make it happen.

Because I am a beginner, I tried the following under Attributes -> Advanced -> JavaScript Initialization Code:

function(options){
   options.yAxis.step = .05;
   return options;
}

Among other things, it should display the number 85%, but he only displays the numbers 0%, 10%, 20%, 30%, and so on. When I change the step to ‘= .5’ (for example) then it works and Apex customize it. And I don’t know why?? I searched on the attributes of oj-chart but I don’t find another possiblities to change the Y Axis.

This point is also important:
On this line chart (Series) I can not activate the label ‘Show’ because my SQL Query is something like this:

SELECT DISTINCT CLASSROOM,
--Calculation for Bar1
--Calculation for Bar2
--Calculation for Bar3
--Calculation for Bar4
.85 AS Target
FROM EMP_SAMPLE
GROUP BY (CLASSROOM)

And when I activate this, the percent number of this line will be shown three or four times on the chart depending on how much classroom (for the x axis) you have in the database. And I need the value only one time for this line.

Of course another solution could be the following: I write the percent number on or left-side or right-side or under this line with JavaScript (but of course only one time), but here I have the same problem as a beginner and I don’t know how. (Or is it possible to customize it with HTML and CSS?)

Can anyone help me? Thanks in advance.

How to populate collection in Strapi V3?

I’m trying to create custom controller for my Strapi (v3.6.10) model, but have a problem with populating one specific field. Here are my models:

  1. Parent model:
{
  "kind": "collectionType",
  "collectionName": "clinic_pages",
  "info": {
    "name": "clinic-page",
  },
  "attributes": {
    "clinic": {
      "model": "clinic"
    },
    ...otherParentModelFields,
  }
}
  1. Clinic:
{
  "kind": "collectionType",
  "collectionName": "clinics",
  "attributes": {
    ...otherFields,
    "schedule": {
      "type": "component",
      "repeatable": true,
      "component": "clinic.schedule"
    },
  }
}
  1. Schedule:
{
  "collectionName": "components_clinic_schedules",
  "info": {
    "name": "schedule",
  },
  "attributes": {
    "time": {...},
    "day": {...}
  }
}

I need to populate only few fields from parent model, including clinic. So I’m using this query:
await strapi.services[MODEL].findOne(ctx.query) and receiving full schedule data in response:

{
  ...otherFieldsOfModel,
  clinic: {
    id: 1,
    ...otherFields,
    schedule: [
      { id: 1, time: '9:00', day: 'monday' },
      { id: 2, time: '10:00', day: 'tuesday' }
    ]
  }
}

That’s fine, I see clinic and schedule, and all other fields in parent model. But then I wand to add populate to reduce size of those other fields and what I got?. Every time I’m getting anything instead of populated data for clinic.schedule even if I’m adding it to populate list. In all this cases:

await strapi.services[MODEL].findOne(ctx.query, {});
await strapi.services[MODEL].findOne(ctx.query, {clinic: true});
await strapi.services[MODEL].findOne(ctx.query, ['clinic']);
await strapi.services[MODEL].findOne(ctx.query, ['clinic', 'clinic.schedule', 'clinic.schedule.day', 'clinic.schedule.time']);

and so on… I mean I tried any possible syntax variant and don’t even got a schedule: null. This field not returning anymore in the response. How do I populate this collection?

P.S. Yes, I know that Strapi is v4 already, unfortunately I can’t update it for now.

How to share third party packages during runtime in Vue?

I have a container app with 4 different Vue apps. They all are using almost same third party packages. I want to share the packages in runtime (i.e., to cache them somewhere), so that any of my apps can use the packages without multiple time downloading and use them from that cache. Basically how can I share dependencies across multiple Vue apps in runtime?

I tried on it but I don’t want to use MonoRepo, as that is more to do with build time reduction. I want to share the dependencies in runtime, as whenever an app runs do not have to download them several times

NestJS: How to build and deploy the nestJS app only with javascript

I’ve implemented a NestJS app in Javascript without the TS support. And I would like to deploy it. I’m wondering how one can achieve that. All the documentation points to how to do that using typescript. Using a nest build command, mentioned here in this post. But there is no proper documentation for achieving this with Javascript. There is also an issue here without the proper answer.

Here are the current scripts in my project

"scripts": {
    "format": "prettier --write "**/*.js"",
    "start": "babel-node index.js",
    "start:dev": "nodemon",
    "test": "jest",
    "test:cov": "jest --coverage",
    "test:e2e": "jest --config ./test/jest-e2e.json"
  },

I believe I should not be using babel in production env. I should be building the app files and use node dist/main. But how can I build the app?

Creating a grid slider in javascript

I am trying to create a grid slider where there is one big image left and 4 smaller on the right. So 5 elements that are part of the same slider that change one by one. First the big image fades to a new one then the first smaller image and so on, at the end start again.

How can I do this? Is there a carousel that can do this? Or does this have to be custom made?

I’ve tried this:

function homeCarousel() {
    // Create an array of the current image sources
    var currentImageUrls = [];
    $('.img-container img').each(function() {
        currentImageUrls.push($(this).attr('src'));
    });

    $.ajax({
        url: '/get-image-urls',
        type: 'GET',
        success: function(data) {
            var newImageUrls = data;

            var previousIndex = 0;
            var usedIndices = [];

            // Create an array to store the preloaded images
            var preloadedImages = [];

            // Preload the images by creating new Image objects and setting
            // their src attributes to the image URLs
            for (var i = 0; i < newImageUrls.length; i++) {
                var img = new Image();
                img.src = newImageUrls[i];
                preloadedImages.push(img);
            }

            function changeImage(index) {
                setTimeout(function() {
                    var currentIndex = previousIndex;
                    while (usedIndices.includes(currentIndex) || currentImageUrls.includes(newImageUrls[currentIndex])) {
                        currentIndex = Math.floor(Math.random() * newImageUrls.length);
                    }
                    usedIndices.push(currentIndex);

                    // Use the preloaded image for the current index
                    var currentImage = preloadedImages[currentIndex];

                    // Check if the screen is small enough to only update the first image
                    if (window.matchMedia('only screen and (max-width: 600px)').matches) {
                        // The screen is small, so only update the first image
                        $('.img-container img').eq(0).attr('src', currentImage.src);
                        $('.img-container img').eq(0).fadeTo(1000, 0, function() {
                            // Fade the image out and then set the src attribute
                            // to the new image URL and fade it back in
                            $(this).attr('src', currentImage.src);
                            $(this).fadeTo(1000, 1);
                        });
                        changeImage(0);
                    } else {
                        // The screen is not small, so update all of the images
                        $('.img-container img').eq(index).fadeTo(1000, 0, function() {
                            // Fade the image out and then set the src attribute
                            // to the new image URL and fade it back in
                            $(this).attr('src', currentImage.src);
                            $(this).fadeTo(1000, 1);
                        });

                        if (index + 1 < $('.img-container img').length) {
                            changeImage(index + 1);
                        } else {
                            usedIndices = [];
                            changeImage(0);
                        }
                    }
                }, 3000);
            }

            changeImage(0);
        }
    });
}

But there are a lot of bugs. For example I load 5 images by default at the start, sometimes a new image is loaded which already is loaded at the beginning so double images are visible, I want all to be unique at any given time. Also sometimes an image gets replaced by an image that was already there so it fades into the same image.

Is there something like slick slider that can achieve this more easily?

How to add properties to an existing javascript object, js doc?

I have a JSDoc comment of a typedef like below,

/**
 * @typedef {Object} obj1
 * @property {boolean} a - Property 1
 * @property {boolean} b - Property 2
 */

I want to have a new typedef which includes the following properties as well:

* @property {boolean} c - Property 3
* @property {boolean} d - Property 4

How to add any additional properties to the object besides a and b?

In code, it’s like this:

const obj1 = {
  a: true,
  b: false
}

const obj2 = {
  a: true,
  b: false,
  c: true,
  d: false
}

As you can see a and b are shared, so I don’t want to repeat defining them, they’re exactly the same.

How to add properties to an existing definition?

in code, we can do something like:

const obj2 = {
  ...obj1,
  c: true,
  d: false
}

Can we do something like the following jsDoc?

/**
 * @typedef {Object} obj1
 * @property {boolean} a - Property 1
 * @property {boolean} b - Property 2
 */

/**
 * @typedef {Object} obj2
 * @property {...obj1}
 * @property {boolean} c - Property 3
 * @property {boolean} d - Property 4
 */

??

VisNetwork: nodesIdSelection argument in VisOptions does not behave similarly to selectNode argument in visEvents

I am having a hard time figuring out why in VisNetwork, the nodesIdSelection argument in VisOptions does not behave similarly to the selectNode argument in visEvents.

Basically, when I click on any node, the R console returns as expected “The selected node ID is: X” but when I select the node from the dropdown list (generated with visOptions) then the message is not issued in the console.

Here is a reproducible example:

library(shiny)
library(visNetwork)
ui <- fluidPage(
  visNetworkOutput('network')
)

server <- function(input, output, session) {
  getDiagramPlot <- function(nodes, edges){
    v <- visNetwork(
      nodes,
      edges
    ) %>%
      visPhysics(stabilization = TRUE, enabled = TRUE) %>%
      visOptions(highlightNearest = list(enabled = T, degree = 1, hover = F),
                 nodesIdSelection = list(enabled = TRUE, main = "Select ID"),
                 autoResize = TRUE, collapse = FALSE) %>%
      visEdges(color = list(highlight = "red")) %>% # The colour of the edge linking nodes
      visLayout(improvedLayout = TRUE) %>%
      visEdges(arrows = edges$arrows) %>%
      visInteraction(multiselect = F) %>%
      visEvents(selectNode = "function(nodes) {
            Shiny.onInputChange('current_node_id', nodes.nodes);
            ;}")
    return(v)
  }

  testFunction <- function(node_id){
    print(paste("The selected node ID is:", node_id))
  }

  nodes <- data.frame(id = 1:3, label = 1:3)
  edges <- data.frame(from = c(1,2), to = c(1,3))

  output$network <- renderVisNetwork(
    getDiagramPlot(nodes, edges)
  )

  observeEvent(input$current_node_id,{
    testFunction(input$current_node_id)
  })
}

shinyApp(ui, server)

Is there a way to pass the same javascript code in visEvents to nodesIdSelection?

Best,

C.

I tried to pass the javascript code from visEvents:

"function(nodes) {
            Shiny.onInputChange('current_node_id', nodes.nodes);
            ;}"

to the style HTML argument (in nodesIdSelection) but this had not effect.

Best way to find active JavaScript code in string of code with JavaScript?

I am working on project, where I am supposed to extract parameter of certain function for use in further logic. Due to limited access, I am only able to get stringified JavaScript script, that user is able to input into the website (yes, safety features are in place). I did not find better solution to this, than to scan that string either by regex, or character by character. But the issue I am facing is, that I need to find out which code is “active” (not commented, not in quotes etc.). I did not want to go down the route of something like (this is only mock):

/* 
for character in string
  if(character === "/")
      if(nextCharacter === *)
          ingore until === star/
      if(nextCharacter === /)
          ignore until rn
  else if(character === "`")
      ingore until === `
  else if(character === "'")
      ingore until === '
  else if(character === `"`)
      ingore until === "
*/

Because it could stop working/become incomplete with every new version of ES and the solution overall seems too brute forcy and like something that JavaScript might have built in solution for.

Is there a better solution to this?

Is there any improvment for below color code selector of its brightness>

**

you can move the cursor on the color scheme panel and select your
desired color code; Anyone can improve moving Brightness bar with a
better Javascript Code for below snippt? how the brightness moving
button can be improved, it has lagging sometimes , it’s been used a
lot of events but still it has some problems , if any othe problems or
improvments are there kindly suggest, thank you.

**

<!DOCTYPE html>
<html>

<head>
  <style>
    p {
      font-size: 20px;
      outline: 1px dashed black;
    }
  </style>
</head>

<body onmousemove="shc();mmove('movebar');" onload="colorbuilder(100);" onmouseup="mup();">
  <div style='border:1px solid black;width:fit-content;'>
    <label id="lablesize" for='size' style='font-size:20px;'></label><input oninput="scsizechange(this.value);" type='range' id='size' name='size' min='1' max='5'>
  </div>
  <div id="colormaker" onclick="clickoncolor();" onmouseover="oncolorover();" onmouseout="colormout();"
    onmouseleave="itsonclick=0;itsoncolor=0;"
    style='outline:1px dashed black;outline-offset:2px;width:fit-content;margin:2px;'></div>
  <div id="showcolor" style='font-size:20px;outline:1px solid black;outline-offset:2px;width:fit-content;margin:2px;'>
  </div>
  <br>
  <div id="clickshow"
    style="font-size:15px;font-weight:bold;font-style:italic;outline:1px solid black;width:fit-content;visibility:hidden;">
  </div>
  <script language="javascript">
    itsoncolor=0;
         brightnessvalue=100;
         itsonclick=0;
         var xm,testvalue=0,sto,leftv,sto1,opv=0,leftbrightnessv=370;
         function clickoncolor()
         {
         itsonclick=1;
         colorcodemaker();
         document.getElementById("clickshow").style.visibility="visible";
         document.getElementById("clickshow").innerHTML="Now you can copy your selected color code above<br>Note: Move out and return back your mouse cursor to the color scheme for continuous change";
         }
         
         function oncolorover()
         {
         itsoncolor=1;
         leftbrightnessv=parseInt(document.getElementById("movebar").style.left);
         brightnessvalue=100-parseInt((leftbrightnessv-370)/1.3);
         document.getElementById("brightshow").innerHTML=(brightnessvalue+"%");
         }
         
         function colormout()
         {
         if(itsonclick==0)
         {
         itsoncolor=0;
         colorout();
         }
         
         }
         
         
         function colorout()
         {
         
         csccv=document.getElementById("size").value;
         topstart=34;
         leftstart=9;
         tov=(topstart+csccv*100);
          coloroutst="<p><div style='text-align:center;margin-left:-200px;'>Brightness: </div></p><p id='cnote'>Move your mouse cursor on the color scheme to show its color code and Click to select your color</p>";
         coloroutst+="<div style='position:absolute;left:370px;top:"+(tov+28)+"px;border-radius:5px;z-index:0;width:150px;height:9px;background-image:linear-gradient(to right";
         
         hslbc=95;
         while (hslbc>=30)
         {
         coloroutst+=(","+h_s_lToHex(240, 100, hslbc));
         hslbc-=5;
         }
         leftbarsh=(-8*(parseInt(Math.log10(brightnessvalue))+1)-14);
         coloroutst+=");'></div>";
         coloroutst+=("<div id='movebar' style='position:absolute;left:"+leftbrightnessv+"px;top:"+(tov+23)+"px;z-index:1'><div style='padding:10px;border-radius:50%;border:1px solid black;background-image:radial-gradient(white , lightgrey , grey);z-index:1;'></div><div id='bluebutton' style='position:absolute;padding:6px;left:4px;top:4px;border-radius:50%;border:1px solid blue;background-image:radial-gradient(lightblue, blue);z-index:2;'></div> <div id='visiblebar' style='position:absolute;z-index:2;top:23px;left:6px;opacity:0;' ><div style='width:0;height:0;border-left:5px solid transparent;border-right:5px solid transparent;border-bottom:5px solid grey;'></div><div id='brightshow' style='position:absolute;padding:20px;border-radius:5px;background-color:grey;z-index:2;top:6px;left:"+leftbarsh+"px;width:fit-content;'>"+brightnessvalue+"%</div></div> </div>");
         document.getElementById("showcolor").innerHTML=coloroutst;
         
         document.getElementById("movebar").onmousedown= function() {mdown("movebar")};
         document.getElementById("movebar").onmouseup= function() {mup()};
         document.getElementById("movebar").onmouseover= function() {mmover()};
         document.getElementById("movebar").onmouseout= function() {mout()};
         }
         
         function hsl_to_r_g_b(h,s,l,rgbp)
         {
             s /= 100;
             l /= 100;
             C = (1 - Math.abs(2 * l - 1)) * s;
             var hue = h / 60;
             X = C * (1 - Math.abs(hue % 2 - 1));
             r = g = b = 0;
             if (hue >= 0 && hue < 1) {
                 r = C;
                 g = X;
             } else if (hue >= 1 && hue < 2) {
                 r = X;
                 g = C;
             } else if (hue >= 2 && hue < 3) {
                 g = C;
                 b = X;
             } else if(hue >= 3 && hue < 4) {
                 g = X;
                 b = C;
             } else if (hue >= 4 && hue < 5) {
                 r = X;
                 b = C;
             } else {
                 r = C;
                 b = X;
             }
             m = l - C / 2;
             r += m;
             g += m;
             b += m;
             r *= 255.0;
             g *= 255.0;
             b *= 255.0;
             if(rgbp=="r") return Math.round(r);
             if(rgbp=="g") return Math.round(g);
             if(rgbp=="b") return Math.round(b);
           
         }
         
         function h_s_lToHex(h, s, l) {
           h /= 360;
           s /= 100;
           l /= 100;
           var r, g, b;
           if (s === 0) {
             r = g = b = l;
           } else {
             const hue2rgb = function(p, q, t) {
               if (t < 0) t += 1;
               if (t > 1) t -= 1;
               if (t < 1 / 6) return p + (q - p) * 6 * t;
               if (t < 1 / 2) return q;
               if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
               return p;
             };
             const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
             const p = 2 * l - q;
             r = hue2rgb(p, q, h + 1 / 3);
             g = hue2rgb(p, q, h);
             b = hue2rgb(p, q, h - 1 / 3);
           }
           const toHex = function(x) {
             const hex = Math.round(x * 255).toString(16);
             return hex.length === 1 ? '0' + hex : hex;
           };
           return '#'+toHex(r)+toHex(g)+toHex(b);
         }
         
         function shc()
         {
         if(itsoncolor==1 && itsonclick==0)
         {
         document.getElementById("clickshow").style.visibility="hidden";
         document.getElementById("clickshow").innerHTML="";
         colorcodemaker();
         }
         }
         
         function colorcodemaker()
         {
         stringv="";
         csccv=document.getElementById("size").value;
         topstart=34;
         leftstart=9;
         ntopv=0;
         xmouse=event.clientX;
         ymouse=event.clientY;
         huev=parseInt((event.clientX-leftstart)/csccv);
         satv=(100-parseInt((event.clientY-topstart)/csccv));
         stringv+=("<p><b>rgb</b>("+hsl_to_r_g_b(huev,brightnessvalue,satv,"r")+","+hsl_to_r_g_b(huev,brightnessvalue,satv,"g")+","+hsl_to_r_g_b(huev,brightnessvalue,satv,"b")+")</p>");
         stringv+=("<p><b>hex :</b>"+h_s_lToHex(huev, brightnessvalue, satv)+"</p>");
         stringv+=("<p><b>hsl</b>("+huev+","+brightnessvalue+"%,"+satv+"%)</p>");
         ntopv=((100*csccv)+(topstart+15));
         stringv+=("<div style='outline:1px solid black;outline-offset:2px;margin:2px;position:absolute;padding:50px;left:300px;top:"+ntopv+"px;border:3px outset hsl("+huev+","+brightnessvalue+"%,"+Math.abs(100-satv)+"%);color:hsl("+huev+","+brightnessvalue+"%,"+Math.abs(100-satv)+"%);border-radius:5%;background-color:hsl("+huev+","+brightnessvalue+"%,"+satv+"%)'>Color Display</div>");
         
         document.getElementById("showcolor").innerHTML=stringv;
         }
         
         function scsizechange(ssize)
         {
         colorout();
         document.getElementById("lablesize").innerHTML=("Resolution of Color Scheme("+ssize+"):");
         for (i=0;i<100;i++)
         {
         divc=("cc"+(i+1));
         document.getElementById(divc).style.height=(ssize+"px");
         document.getElementById(divc).style.width=((ssize*360)+"px");
         }
         }
         
         function brightnesschange(svalue1)
         {
         
         hvalue1=100;
         
         for(i=0;i<100;i++)
         {
         
         st="linear-gradient(to right";
         
         huev=0;
         
         do {
         
         st+=(","+h_s_lToHex(huev, svalue1, hvalue1));
         
         huev++;
         
         } while (huev<=360);
         
         hvalue1--;
         
         st+=")";
         
         cid=("cc"+(i+1));
         
         document.getElementById(cid).style.backgroundImage=st;
         }
         
         }
         
         
         function colorbuilder(svalue)
         {
         
         st="";
         hvalue=0;
         lvalue=100;
         topvalue=10;
         csize=2;
         document.getElementById("size").value=csize;
         colorout();
         document.getElementById("lablesize").innerHTML=("Resolution of Color Scheme("+csize+"):");
         for(i=0;i<100;i++)
         {
         st+=("<div id='cc"+(i+1)+"' style='height:"+(csize*1)+"px;width:"+(csize*360)+"px;top:"+topvalue+"px;left:10px;background-image:linear-gradient(to right");
         do {
         st+=(","+h_s_lToHex(hvalue, svalue, lvalue));
         hvalue++;
         } while (hvalue<=360);
         st+=");'></div>";
         hvalue=0;
         lvalue--;
         topvalue+=csize;
         }
         
         document.getElementById("colormaker").innerHTML=st;
         
         return svalue;
         }
         
         function mdown(ss)
         {
         testvalue=1;
         
         xm=event.clientX;
         
         leftv=parseInt(document.getElementById(ss).style.left);
         
         }
         
         function mmove(ss1)
         {
         
         if (testvalue==1)
         {
         
         
         document.getElementById("cnote").style.visibility="hidden";
         
         brightvalue=0;
         
         xm=(event.clientX-xm);
         
         document.getElementById(ss1).style.left=((leftv+xm)+"px");
         
         xm=(event.clientX);
         
         leftv=parseInt(document.getElementById(ss1).style.left);
         
         if(leftv>500)
         document.getElementById(ss1).style.left=(500+"px");
         else if (leftv<370)
         document.getElementById(ss1).style.left=(370+"px");
         
         brightvalue=parseInt(document.getElementById(ss1).style.left);
         
         brightvalue=100-parseInt((brightvalue-370)/1.3);
         
         bslvalue=parseInt(Math.log10(brightvalue+1));
         
         document.getElementById("brightshow").innerHTML=(brightvalue+"%");
         
         document.getElementById("brightshow").style.left=((-8*(bslvalue+1)-14)+"px");
         
         brightnesschange(brightvalue);
         
         }
         sto=setTimeout(mmove);
         }
         
         function mup()
         {
         
         testvalue=0;
         clearTimeout(sto);
         }
         
         function mmover()
         {
         document.getElementById("cnote").style.visibility="hidden";
         
         document.getElementById("visiblebar").style.visibility="visible";
         if(opv<=0.5)
         {
         
         document.getElementById("visiblebar").style.opacity=opv;
         opv+=0.1;
         } else {
         
         clearTimeout(sto1);
         }
         sto1=setTimeout(mmover,150);
         }
         
         function mout()
         {
         document.getElementById("cnote").style.visibility="visible";
         
         if(testvalue==0)
         {
         opv=0;
         document.getElementById("visiblebar").style.opacity=0;
         document.getElementById("visiblebar").style.visibility="hidden";
         clearTimeout(sto1);
         }
         }
         
         
  </script>
</body>

</html>

Why is my code adding extra blank ?

`I’ve created a program that allows the user to enter some information to add their first and last names to a list.

When the list is blank – the “Delete” button is disabled. When all users have been manually deleted, the “Delete” button should be disabled.

That all works fine – however, every time my “Save” button is clicked to add a user to the list, it also generated a blank value to the list. Because of that, the “Delete” button doesn’t disable because it’s counting the blank value as a part of the list.

Added a screenshot of my browser inspection – Inspection_Image – (https://i.stack.imgur.com/ncZCt.png)

The value below “John Smith” Shouldn’t be there, but was added alongside John Smith and i cant figure out why!

MemberList

<h1>Member List</h1>

<form method="post" id="_frmFull">

    <label for="lstMembers">Member:</label>
    <select size="10"
            name="lstMembers"
            id="lstMembers">
    </select>


    <button type="button"
            id="addMember"
            name="Add Member">
            Add Member
    </button>
    <button type="button"
            name="Delete Member"
            id="delete">
            Delete Member</button>

        <div id="Modal" class="modal">

            <div class="modal-form">

                <label for="memTitle">Title:</label>
                <input list="memTitles" name="memTitles" id="memTitle">

                <datalist id="memTitles">
                    <option value="Dr">
                    <option value="Mr">
                    <option value="Mrs">
                    <option value="Ms">
                </datalist>

                <label for="firstName">First Name:</label>
                <input type="text" name="firstName" id="firstName" required="required">

                <label for="middleName">Middle Name (optional):</label>
                <input type="text" name="middleName" id="middleName">

                <label for="lastName">Last Name:</label>
                <input type="text" name="lastName" id="lastName" required="required">

                <br><br>

                <label for="Country">Country:</label>
                <input list="countries" name="Country" id="Country">
                <datalist id="countries">
                    <option value="Australia">
                    <option value="United Kingdom">
                    <option value="America">
                    <option value="New Zealand">
                </datalist>

                <label for="Gender">Gender:</label>
                <select name="Gender" id="Gender">
                    <option>Male</option>
                    <option>Female</option>
                    <option>Other</option>
                </select>

                <label for="birthDate">Birthdate:</label>
                <input type="date"
                       id="birthDate"
                       min="1900-01-01"
                       max="2022-12-31" required="required">

                <br><br>

                <div id="resiAddress">

                <p>Residential Address:</p>

                <br>

                <label for="txtResidentialAddress">Address:</label>
                <input type="text" required="required" id="txtResidentialAddress" oninput="copyAddressFields();">


                <br><br>

                <label for="txtResiPostCode">Postcode:</label>
                <input type="text" required="required" id="txtResiPostCode">

                <br><br>

                <label for="txtResiSuburb">Suburb:</label>
                <input type="text" required="required" id="txtResiSuburb">

                <br><br>

                <label for="txtResiCountry" class="country">Country</label>
                <input type="text" required="required" id="txtResiCountry">

                <br><br>

                <label for="txtResiState">State:</label>
                <input type="text" required="required" id="txtResiState">

            </div>

                <br><br>

                <label for="chkSynchronizeAddresses">Same as residential </label>
                <input type="checkbox" required="required" id="chkSynchronizeAddresses" >

                <div id="postAddress">

                    <p>Postal Address:</p>

                    <br>

                    <label for="txtPostalAddress">Address:</label>
                    <input type="text" id="txtPostalAddress">

                    <br><br>

                    <label for="txtPostCode">Postcode:</label>
                    <input type="text" id="txtPostCode">

                    <br><br>

                    <label for="txtPostalSuburb">Suburb:</label>
                    <input type="text" id="txtPostalSuburb">

                    <br><br>

                    <label for="txtPostalCountry">Country:</label>
                    <input type="text" id="txtPostalCountry">

                    <br><br>

                    <label for="txtPostalState">State:</label>
                    <input type="text" id="txtPostalState">

                </div>

                <br><br>

                <label for="txtPhone" class="phone">Phone: (optional)</label>
                <input id="txtPhone" type="text">


                <br><br>

                <label for="txtMobile" class="mobile">Mobile: (optional)</label>
                <input id="txtMobile" type="text">


                <br><br>

                <button type="button" name="save" id="save">Save</button>

                <br><br>

                <button type="button"
                        name="cancel"
                        id="closeModal">
                        Cancel</button>
            </div>

        </div>

    </form>

console.log(“Log test – please work!!”)

const addBtn = document.getElementById(“addMember”);
const modal = document.getElementById(“Modal”);
const cancelBtn = document.getElementById(“closeModal”);
let chkSynchronizeAddresses = document.getElementById(“chkSynchronizeAddresses”);
const _frmFull = document.getElementById(“_frmFull”);
let Member = document.getElementById(“lstMembers”);
let Delete = document.getElementById(“delete”);
let save = document.getElementById(“save”);
let fName = document.getElementById(“firstName”);
let lName = document.getElementById(“lastName”);
let birthDate = document.getElementById(“birthDate”);

Delete.disabled = Member.value === “”;

addBtn.onclick = function (){
openPopUp();
console.log(‘function – correct’);
}

cancelBtn.onclick = function (){
let closeTrue = confirm(“Close form? You’ve not saved anything.”)
if (closeTrue === true) {
closePopUp();
}
}

chkSynchronizeAddresses.onclick = function (){
console.log(“Is this working??”);

if (chkSynchronizeAddresses.checked){
document.getElementById(“txtPostalAddress”).setAttribute(“readonly”, “true”);
document.getElementById(“txtPostCode”).setAttribute(“readonly”, “true”);
document.getElementById(“txtPostalState”).setAttribute(“readonly”, “true”);
document.getElementById(“txtPostalSuburb”).setAttribute(“readonly”, “true”);
document.getElementById(“txtPostalCountry”).setAttribute(“readonly”, “true”);
copyAddressFields();
}
else {
document.getElementById(“txtPostalAddress”).removeAttribute(“readonly”);
document.getElementById(“txtPostCode”).removeAttribute(“readonly”)
document.getElementById(“txtPostalState”).removeAttribute(“readonly”);
document.getElementById(“txtPostalSuburb”).removeAttribute(“readonly”);
document.getElementById(“txtPostalCountry”).removeAttribute(“readonly”);
}

}

function copyAddressFields () {
if (chkSynchronizeAddresses.checked){
document.getElementById(“txtPostalAddress”).value = document.getElementById(“txtResidentialAddress”).value;
document.getElementById(“txtPostCode”).value = document.getElementById(“txtResiPostCode”).value;
document.getElementById(“txtPostalSuburb”).value = document.getElementById(“txtResiSuburb”).value;
document.getElementById(“txtPostalState”).value = document.getElementById(“txtResiState”).value;
document.getElementById(“txtPostalCountry”).value = document.getElementById(“txtResiCountry”).value;

}

}

let idCount = 0

save.onclick = function (){

let fNameValue = fName.value
let lNameValue = lName.value
let bDateValue = birthDate.value
let pCountryValue = document.getElementById(“txtPostalCountry”).value
let pSuburbValue = document.getElementById(“txtPostalSuburb”).value
let pStateValue = document.getElementById(“txtPostalState”).value
let pCodeValue = document.getElementById(“txtPostCode”).value
let pAddressValue = document.getElementById(“txtPostalAddress”).value

if (fNameValue === “”){
alert(“Please enter your first name to proceed”);
return false;
}

else if (titleValue === “”) {
alert(“Please enter your title to proceed”);
return false
}

else
if (lNameValue === “”) {
alert(“Please enter your last name to proceed”);
return false;
} else if (bDateValue === “”) {
alert(“Please select a DOB to proceed”);
return false;
} else if (pCountryValue === “”) {
alert(“Please enter your country to continue”);
return false;
} else if (pSuburbValue === “”) {
alert(“Please enter your suburb to continue”);
return false;
} else if (pCodeValue === “”) {
alert(“Please enter your postcode to continue”);
return false;
} else if (pAddressValue === “”) {
alert(“Please enter your Address to continue”);
return false;
} else if (pStateValue === “”) {
alert(“Please enter your state to continue”);
return false;
} else {

Member.innerHTML +=
`${idCount} ${_frmFull.firstName.value} ${_frmFull.lastName.value}`
idCount++
console.log(“check – is increase even working????”)
Delete.disabled = Member.options.length === 0;

}

closePopUp();
return true;

}
function closePopUp() {
modal.style.display=”none”;
}
function openPopUp() {
modal.style.display = “block”;
}

Delete.onclick = function removeOption () {
Member.remove(Member.options);
console.log(“is remove being triggered??”)
Delete.disabled = Member.options.length === 0;
}

if (Member.options.length == “”){
Delete.disabled = true
}
else {
Delete.disabled = false
}

data not getting displayed on the reusable component in the vuejs application

In my laravel vue application I'm trying to fetch total number of orders for the current day for a shopify store sing Shopify's admin REST API and display that on my vue component. 

Following is my controller

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use CarbonCarbon;

class ShopifyOrderController extends Controller
{
    public function fetchOrders()
    {
        // Set up cURL request
        $access_token = 'shpat_XXXXXXXXXXXXXXXXXXXXXXXX';
        $today = Carbon::today()->toIso8601String();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://API_KEY:ACCESS_TOKEN@STORE_NAME.myshopify.com/admin/orders/count.json?status=any&created_at_min={$today}");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "Content-Type: application/json",
            "X-Shopify-Access-Token: {$access_token}"
        ));

       // Make cURL request
        $response = curl_exec($ch);
        $response_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        //dd($response);die;

        // Check for empty or null response
        if (empty($response) || is_null($response)) {
            return 0;
        } else {
            // Return the response from the API
            return $response;
        }
    }

}

when I dd($response);die; it correctly gives me out put as count:1 for today.

And then I have a reusable vue comonent called, ShopifyOrdersScoreCard.vue and following is it’s code

<template>
    <div data-aos="fade-up" class="col-md-12 mx-1 border bg-white rounded rounded-lg w-100 h-100 py-2 px-3">
        <table class="w-100 h-100">
            <tr>
                <td class="align-top" style="height:10px">
                    <dashboard-widget-header 
                        image="https://cdn0.iconfinder.com/data/icons/social-media-2092/100/social-35-512.png" 
                        width="32" 
                        height="32" 
                        title="Shopify" 
                        imageAlt="Shopify">
                    </dashboard-widget-header>
                </td>
            </tr>
            <tr>
                <td class="align-middle text-center">
                    <div class="row">
                        <div class="col-12">
                            <div class="row">
                                <div class="col-12">
                                    <h6 class="m-b-5 custom-non-comparison-score-card-title">
                                        Orders
                                    </h6>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-12">
                                    <h5 class="mb-0 custom-non-comparison-score-card-value">
                                        <p 
                                            v-if="orders"
                                        >
                                            {{ orders }}
                                        </p>
                                        <p 
                                            v-else
                                        >
                                            Loading...
                                        </p>
                                    </h5>
                                </div>
                            </div>
                        </div>
                    </div>
                </td>
            </tr>
        </table>
    </div>
</template>

<script>
export default {
    props: ['orders'],

    created() {
        console.log('Shopify 343434 Orders:', this.orders);
    }
}
</script>

Here my console log giving me Undefined as the out put (that’s my problem, can’t figure out why it’s happening)

And I use this component on my index.vue. Following is my index.vue.

<template>
    <div>
        <draggable v-model="items" :options="{ group: 'shared' }" class="d-flex">
            <div v-for="item in items" :key="item.id" class="col-md-2 col-sm-2 col-lg-2" >
                <component :is="item.component" :item="item" />
            </div>
        </draggable>
    </div>
</template>

<script>
import ShopifyOrdersScoreCard from './ShopifyOrdersScoreCard.vue';

export default {
    data() {
        return {
            items: [
                { id: 1, component: ShopifyOrdersScoreCard, orders: null }
            ]
        }
    },
    methods: {
        fetchOrders() {
            // Make a request to the Laravel server to fetch the orders data
            axios.get('/orders').then(response => {
                console.log('Response:', response);
                console.log('Orders:', response.data);
                // Update the orders prop in the ShopifyOrdersScoreCard component
                this.items[0].orders = response.data;
                console.log('Items:', this.items);
            });
        }
    },
    created() {
        this.fetchOrders();
    }
}
</script>

These console logs giving me the correct out put. but

console.log('Shopify 343434 Orders:', this.orders); in my ShopifyOrdersScoreCard.vue giving me undefined….

because of that the order count is not getting displayed on my index.vue..

enable submit when date is selected from datepicker

submit button gets enabled when I type date manually but when I select it from datepicker it does not gets enabled

`<html>
<body>
    <input type="date" id="txt" onkeyup="manage(this)" class="form-control" name=<?php echo 'actual_date__' . $cur['id'] . '__' . $cur['master_id'] ?> value="<?php echo $filtered_row_result1["actual_date"] ?? ''; ?>" >
    <input type="submit" id="btSubmit" disabled />
</body>
<script>
    function manage(txt) {
        var bt = document.getElementById('btSubmit');
        if (txt.value != '') {
            bt.disabled = false;
        }
        else {
            bt.disabled = true;
        }
    }
<script>
</html>`