Angular Reset Password User or Password Not Found

I have an issue when user chooses forgot password. The forgot password form appears user enters email, user get’s alert to check there email and user clicks link which take you to reset form. The user type in new password password. I get alert saying password reset successful. User gets routed to login page. When I type in new password and it says Password or User name is incorrect. So its not being updated. I’m thinking it has something to do with way I’m doing my update. It not being updated in database. My console.log and alerts confirm its reaching service and endpoints. If someone can please point me in the right direction I would be so grateful. . I have included only necessary code snippet:

Reset Password Component:

 let resetObj={
 token: this.token,
  Password: this.form.value.password
 }

 //This gets called on submit
  this.accountService.resetPassword(resetObj)

      .subscribe({
          next: () => {
              this.alertService.success('Password reset successful, you can now login', 
               { keepAfterRouteChange: true });
                this.form.reset();
                this.router.navigate(['../../login'], { relativeTo: this.route });
              },
          error: error => {
              this.alertService.error(error);
           
          }
      });

accountService:

  resetPassword(resetObj: any) {
    return this.http.post(`${this.apiUrl}/reset-password`,  resetObj);
  }

endpoint:
controller.js

  router.post('/reset-password', passwordReset)

 function passwordReset(req,res, next){
 console.log("Does it goet to password reset");

     const token = req.body.token;
     const newPassword = req.body.password; 
     
     console.log("What do  properties hold" + " " + " " + newPassword + " " + " " + 
      token)
       userService.resetPassword(token, newPassword)
       .then(() =>res.json({}))
        .catch(err => next(err));          

   }

userservice:

   async function resetPassword(token,  newPassword, result,res){

    console.log("InsideresetPassword Service")
    console.log("whats in token", token); 
    console.log("What is new password", newPassword);


     jwt.verify(token,process.env.JWT_Secret, async(err, data) =>{
    console.log("Does it get to this if")
      if(err){
        console.log("Reset Link is Expired");
      }else{ 
        console.log("Does it get to else in reset service")
        const response = data;
        const user = await User.findOne({email: {$regex: '^'+ response.email+"$", 
        $options: 'i'}});
        console.log("Whats email", user.email)
        const salt = await bcrypt.genSalt(10);
        const encryptedPassword = await bcrypt.hash(newPassword, salt);
        user.password = encryptedPassword;
       
        try{
            const updateUser = await User.findOneAndUpdate(
               {_id: user._id},
               {$set: user},
               {new: true}  //can show update
             
            )
           
              console.log( "Password Updated")
            

          }catch(error){
            console.log("Something went wrong while redirecting passwor


          }
        

        }


      
     })

 } 
  

DynamoDb Cannot read properties of undefined (reading ‘0’) when writing data

I am trying to write some data into DynamoDb. I’ve created the table with a partition key called s3jsonfile (String), and a sort key called messageId (String).

My main goal is to use this table to track the progress of my processing. Since my logic is based on receiving SQS messages, i’m gonna write there how many entries from the SQS message were processed, total number of entries, message number and the s3 key.

For writing, i’m passing to the function the s3jsonfile (partitionkey) and messageId(sort key).

I’ve verified the data i’m passing multiple times, its even included on my debugging. However, i’m always receiving this error:

Error initializing message processing: TypeError: Cannot read properties of undefined (reading '0')
    at Object.visit (/home/ec2-user/node-project/node_modules/@aws-sdk/client-dynamodb/dist-cjs/index.js:1003:36)
    at se_AttributeValue (/home/ec2-user/node-project/node_modules/@aws-sdk/client-dynamodb/dist-cjs/index.js:2544:25)
    at /home/ec2-user/node-project/node_modules/@aws-sdk/client-dynamodb/dist-cjs/index.js:2743:16
    at Array.reduce (<anonymous>)
    at se_ExpressionAttributeValueMap (/home/ec2-user/node-project/node_modules/@aws-sdk/client-dynamodb/dist-cjs/index.js:2739:32)
    at ExpressionAttributeValues (/home/ec2-user/node-project/node_modules/@aws-sdk/client-dynamodb/dist-cjs/index.js:3102:39)
    at applyInstruction (/home/ec2-user/node-project/node_modules/@smithy/smithy-client/dist-cjs/index.js:1092:27)
    at take (/home/ec2-user/node-project/node_modules/@smithy/smithy-client/dist-cjs/index.js:1060:5)
    at se_UpdateItemInput (/home/ec2-user/node-project/node_modules/@aws-sdk/client-dynamodb/dist-cjs/index.js:3096:40)
    at se_UpdateItemCommand (/home/ec2-user/node-project/node_modules/@aws-sdk/client-dynamodb/dist-cjs/index.js:1360:25)
Parameters used: {
  TableName: 'messageProcessingTable',
  Key: {
    s3jsonfile: 'converted_data_1726002816321.json',
    messageId: 'Message 1 of 1'
  },
  UpdateExpression: 'SET totalEntries = :totalEntries, entriesProcessed = :entriesProcessed, processingStatus =

:processingStatus, lastUpdated = :timestamp’,
ExpressionAttributeValues: {
‘:totalEntries’: ‘6’,
‘:entriesProcessed’: ‘0’,
‘:processingStatus’: ‘0’,
‘:timestamp’: ‘2024-09-10T21:13:45.990Z’
}
}

I’ve double checked my schema, my function to write the data, and i still can’t figure out the problem. Also, i’m using AWS SDK v3 so there is no need to pass S for string and N for number (thats why i’m passing to the update command the entire string).

The error is happening because i still have no data on this table?
The goal on this specific method is to initialize writing the data on this s3jsonfile (key) with the values i provided inside the method (sorting key).

I’m kinda new to DynamoDB. I don’t know if i should create my table in another way (without a sorting key maybe). Any input is highly appreciated, and sorry for the english.

Below is my code. Any additional information i’ll be glad to reply. If something on my post isn’t clear, please let me know. Thanks a lot.

// Initialize the message processing entry
const initializeProcessing = async (s3jsonfile, messageId, totalEntries, messageProcessingTableName) => {
    console.log('S3 Key:', s3jsonfile);
    console.log('Message Info:', messageId);
    console.log('Total Entries:', totalEntries);

    const params = {
        TableName: messageProcessingTableName,
        Key: {
            s3jsonfile,    // Partition key
            messageId      // Sort key
        },
        UpdateExpression: 'SET totalEntries = :totalEntries, entriesProcessed = :entriesProcessed, processingStatus = :processingStatus, lastUpdated = :timestamp',
        ExpressionAttributeValues: {
            ':totalEntries': totalEntries.toString(),  // Ensure this is a string
            ':entriesProcessed': '0',  // Plain string
            ':processingStatus': '0',  // Plain string
            ':timestamp': new Date().toISOString()  // ISO string for date
        }
    };

    console.log('Parameters for UpdateItemCommand:', JSON.stringify(params, null, 2)); // Detailed logging

    try {
        await dynamoDB.send(new UpdateItemCommand(params));
        console.log(`Message ${messageId} initialized for ${totalEntries} entries.`);
    } catch (error) {
        console.error('Error initializing message processing:', error);
        console.error('Parameters used:', params); // Log parameters for debugging
    }
};

EDIT: To clarify, on this method the entriesProcessed is static as 0 because it will be updated when the processing logic is done. Also, processing status will be updated only when all entries from the json are processed. Thats why their attributes are like static strings now.

how do i return the json object of my ajax GET request to an API in Asp.net MVC

Ok hi. Im having a lot of problems with a project im building. I want to use Ajax to make a request to the Google.Books api so i can make book searches from my website. Its a Asp.net MVC project. Im using Ajax on one of the pages. The documentation says just send a GET request to the url. I wrote the ajax request and I seem to get an 200 ok response but im not getting the json object. Also i want to put the info from the json response to show the title of the book and the author. Possibly a dropdown in html or a select div in html.

$(document).ready(function () {

$('getBookList').submit(function () {
    var key = "AIzaSyAAD3qgVCx8MeoD6aD-CzTasKijPE-Ny3Y";

    $.ajax({
        type: "GET",
        url: "https://www.googleapis.com/books/v1/volumes?q=search+terms&" + key,
        dataType: 'jsonp',
        data: { volumeInfo: title, volumeInfo: authors },
        success: function (data) {

            $('#volumeInfo:title').dropdown("show")(data)
            $('#volumeInfo:authors').dropdown("show")(data)
            $('#q').dropdown("show")(data)

                .fail(function (xhr, status, errorThrown) {
                    alert("Sorry, there was a problem!");
                    console.log("Error: " + errorThrown);
                    console.log("Status: " + status);
                    console.dir(xhr);

                });

        }
    });
});

});

Please help me with a JavaScript button chrome extension thing [closed]

I need help with a chrome extension that would add a button to the bottom of a specific website. The button should link to an edited version of the sites url.

For example, If the URL is https://www.example.com/part1/part2 the button would need to link to https://www.example.com/part3/part2 and I need it to be reusable so I can’t just put a URL there because the part2 will vary. Thanks

I’ve tried searching for solutions, but nothing worked.

“Declaration or statement expected” Error on else operator nested in if statement [closed]

Just starting to learn javascript and working through some practice exercises in an online course. The last exercise is setting up a simple login prompt using if statements and logical operators like OR. I receive an error when inputting the else statements.
Here is the code

I am really not sure why the else statements are giving this error. I believe I have nested everything properly and am using the right brackets after each operator.

create logarithmic color scale with specified steps

I need to do color scale that represents the same scale used in mapbox. The mapbox expression is this:

'fill-color': [
  'interpolate',
  ['linear'],
  ['log10', value],
  0, "white",
  Math.log10(1_000), "yellow",
  Math.log10(100_000), "orange",
  Math.log10(1_000_000), "red",
  Math.log10(60_000_000), "blue"
]

that means:

  • for very low value (log10(value) = 0), the color is white
  • at the first threshold (log10(1_000)), the color becomes yellow
  • at the mid threshold (log10(100_000)), the color transitions to orange
  • at the high threshold (log10(1_000_000)), the color changes to red
  • for the highest values (log10(60_000_000)), the color becomes blue.
    This creates a smooth transition between these colors based on values levels.

I would like to create a color scale in d3, so this is what I did:

  • I created the following scales to create the ticks:
const logScale = d3.scaleLog([1, 60_000_000], [0, 100]).base(10);
const logIncompleteTicks = logScale.ticks(TICKS_NUMBER);
const logTicks = _.uniq([0, ...logIncompleteTicks, 60_000_000]);
const logTickPositionScale = d3.scaleLinear([0, 60_000_000], [SCALE_HEIGHT, 0]);
  • now I need to create the background of the scale so the color scales. I created this:
const colorScale = d3.scaleLinear([0, 1_000, 100_000, 1_000_000, 60_000_000], ["white", "yellow", "orange", "red", "blue"]);

but I don’t know how to use it and I am also not sure that what I’ve done since now is correct, if it represents the same scale used in mapbox..

Here the full code:

import * as d3 from "d3";
import _ from "lodash-es";

const TICKS_NUMBER = 8;
const X = 0;
const Y = 0;
const SCALE_CONTAINER_WIDTH = 200;
const SCALE_CONTAINER_HEIGHT = 550;
const SCALE_WIDTH = 100;
const SCALE_HEIGHT = 530;

export default function App() {
  const logScale = d3.scaleLog([1, 60_000_000], [0, 100]).base(10);
  const logIncompleteTicks = logScale.ticks(TICKS_NUMBER);
  const logTicks = _.uniq([0, ...logIncompleteTicks, 60_000_000]);
  const logTickPositionScale = d3.scaleLinear(
    [0, 60_000_000],
    [SCALE_HEIGHT, 0]
  );
  const colorScale = d3.scaleLinear(
    [0, 1_000, 100_000, 1_000_000, 60_000_000],
    ["white", "yellow", "orange", "red", "blue"]
  );

  return (
    <div>
      <div
        style={{
          width: SCALE_CONTAINER_WIDTH,
          height: SCALE_CONTAINER_HEIGHT,
          display: "flex",
          justifyContent: "end",
          alignItems: "center",
          border: "2px solid red",
        }}
      >
        <svg
          x={X}
          y={Y}
          width={SCALE_WIDTH}
          height={SCALE_HEIGHT}
          overflow="visible"
        >
          <rect
            x={X}
            y={Y}
            width={SCALE_WIDTH}
            height={SCALE_HEIGHT}
            fill="white"
            stroke="black"
          />
          <g>
            {logTicks.map((logTick) => {
              const y = logTickPositionScale(logTick);

              return (
                <g key={logTick} transform={`translate(0, ${y})`}>
                  <line x1={0} y1={0} x2={SCALE_WIDTH} y2={0} stroke="black" />
                  <text
                    x={-5}
                    y={0}
                    textAnchor="end"
                    dominantBaseline="middle"
                    fontSize={12}
                  >
                    {logTick}
                  </text>
                </g>
              );
            })}
          </g>
        </svg>
      </div>
    </div>
  );
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.8.5/d3.min.js"></script>

the result is:
scale tmp

Why are there gaps in between functions in my chrome profiler snapshot?

I am profiling some code and i have a snapshot that looks like this:
enter image description here

The code is roughly this:

const createApply = (args)=>(element)=>{ 
  a()
  b()
}

Inside of _applyFilters

const apply = createApply(args)
elements.forEach(apply)

The anonymous function is the curried apply that is in the forEach(apply) loop. Sometimes i only see the apply function with no a() or b(). Sometimes i see just a() sometimes as you can see i see a bunch of a() b() a() b()....

There are no conditions or anything, both a() and b() are always called.

So, why do these (anonymous) functions in my image vary so wildly in their lenghts? Why do they have different amount of children (1,2,3 many…)? Why are there gaps?

Why isn’t it a dense table of anonymous->a(),b() of equal lenghts and no gaps? All these functions do is access some dictionaries and write the values to some sets.

Css. How to fit image into container

Would try to describe my problem clear:
I have a container with fixed width where on the left side should be the image and on the right side should be the text field. And when the typed text go to the next string the height of container should be increase. At the same time we should proportional with the increasing height of container increase height and width of image and decrease the width of text field. So the image should be fit in container and at the same time don’t affect container height
I have like this simple html:

Do anyone know how to do it? Is here anyone mark-up geek?)

I tried to do it via position: absolute for the image, then the container can depend only on the height of the text field, but it is not clear how much to increase the width of this image, and accordingly reduce the text field. I also tried to simply position both the image and the text field via display: flex, but in this case, since the text field’s height changes dynamically – height: auto then the image stretches the container’s height

Select2 Tooltip Not Appearing on Hover – Using jQuery and Event Delegation

I am using Select2 to enhance a element in my web application. I want to display tooltips when users hover over the options in the Select2 dropdown. However, the tooltips are not appearing as expected when hovering over the options. The tooltip container is created, but it doesn’t show up on hover.

Below is js file code

$(document).ready(function() {
function formatProjectOption(option) {
    if (!option.id) {
        return option.text;
    }
    return $('<span>' + option.text + '</span>');
}

$("#projectName").select2({
    placeholder: "Select Projects...",
    templateResult: formatProjectOption,
    templateSelection: formatProjectOption,
}).on('select2:open', function() {
    var $container = $('#projectName').next('.select2-container');
    var $tooltipContainer = $('<div class="select2-tooltip"></div>').appendTo($container);

    $('.select2-results__option').hover(
        function() {
            var tooltipText = $(this).data('tooltip');
            if (tooltipText) {
                $tooltipContainer.text(tooltipText).show();
            }
        },
        function() {
            $tooltipContainer.hide();
        }
    );

    // Adjust tooltip position on hover
    $('.select2-results__option').mousemove(function(e) {
        $('.select2-tooltip').css({
            top: e.pageY + 10,
            left: e.pageX + 10
        });
    });
});
const multiselect = $("select[multiple]");

multiselect.each(function() {
    const savedOptions = JSON.parse(localStorage.getItem(this.id));
    if (savedOptions) {
        const currentOptions = $(this).val() || [];
        const mergedOptions = [...currentOptions, ...savedOptions];
        $(this).val(mergedOptions).trigger("change");
    }
});
const savedStartDate = localStorage.getItem('startDate');
if (savedStartDate) {
    $('#startDate').val(savedStartDate);
}
const savedEndDate = localStorage.getItem('endDate');
if (savedEndDate) {
    $('#endDate').val(savedEndDate);
}
$("#label").select2();
$("#defect").select2();
$("#projectName").select2({
    placeholder: "Select Projects...",
});
$("#label").select2({
    placeholder: "Select Label...",
});
$("#defect").select2({
    placeholder: "Select Defect Type...",
});
// Show/hide form and chart sections based on user interaction
$("#form-section").show();
$("#nike-image").show();
$("#chart-section").hide();
$("#backToFormBtn").hide();

// Handle form submission
$("#metrics-form").submit(function(event) {
    event.preventDefault();
    multiselect.each(function() {
        const selectedOptions = $(this).val();
        localStorage.setItem(this.id, JSON.stringify(selectedOptions));
    });
    var projectName = $("#projectName").val();
    /*var squad = $("#squad").val();*/
    var label = $("#label").val();
    var startDate = $("#startDate").val();
    var defectType = $("#defect").val();
    var endDate = $("#endDate").val();
    if (projectName.length === 0 && label.length === 0) {
        $("#modal-body").html("Please Select Project Name Or Label.");
        $("#errorModal").modal("show");
    } else if (defectType.length == 0) {
        $("#modal-body").html("Please Select Defect Type.");
        $("#errorModal").modal("show");
    } else {
        localStorage.setItem('startDate', startDate);
        localStorage.setItem('endDate', endDate);
        $("#errorModal").modal("hide");
        $("#errorDateModal").modal("hide");
        $("#spinner").show();
        $.ajax({
            type: $(this).attr("method"),
            url: $(this).attr("action"),
            data: $(this).serialize(),
            success: function(response) {
                $("#spinner").hide();
                // Hide the form and show the chart section
                $("#form-section").hide();
                $("#chart-section").show();
                $("#backToFormBtn").show();
                var chartData = JSON.parse(response);

                google.charts.load("current", {
                    packages: ["corechart"],
                });
                google.charts.setOnLoadCallback(function() {
                    drawCharts(chartData);
                });
            },
        });
    }
});

$("#add-project-form").submit(function(event) {
    event.preventDefault();
    var form = $(this);
    var actionUrl = form.attr("action");
    var method = form.attr("method");

    // Show the spinner
    $("#spinner").show();

    $.ajax({
        type: method,
        url: actionUrl,
        data: form.serialize(),
        success: function(response) {
            $("#spinner").hide();

            // Assuming response contains the message and/or HTML snippet for displaying errors or success messages
            // Insert response into the designated element for messages

            $("#response-message")
                .removeClass("alert-danger")
                .addClass("alert-success")
                .find("#response-text")
                .text(response) // Set the response text
                .end()
                .fadeIn(500);

            // Optionally, you might want to update specific parts of the page
        },
        error: function(jqXHR, textStatus, errorThrown) {
            $("#spinner").hide();
            console.error("Error occurred:", textStatus, errorThrown);
            $("#response-container").html("<div class='alert alert-danger'>An error occurred while processing your request. Please try again.</div>");
        }
    });
});

// Handle the "OK" button click to hide the response message
$(document).on('click', '#response-ok', function() {
    $("#response-message").fadeOut(500);
});


$('#addProjectButton').click(function() {
    $("#add-project").show();
    $('#add-project').slideDown();
    $('html, body').animate({
        scrollTop: $('#add-project').offset().top
    }, 500);
});
// Handle "Back to Form" button click
$("#backToFormBtn").click(function() {
    $("#chart-section").hide();
});

function drawCharts(chartData) {
    drawBarChart("defectTotalCount", chartData.jiraStats, "Defect Type Count");
    drawBarGroupChart("defectGroupChart", chartData.numberOfDaysToResolveDefect, "Test", chartData.jiraStats);
    drawBarChartForPriorityCount("priorityCountChart", chartData.defectPriorityMatrices, "Priority Count");
    drawBarChartForOpenStatusDefect("openDefectCount", chartData.numberOfOpenDefectsByType, "Open Defect Count")
    populateTable(chartData);
}

function drawBarChart(containerId, chartData, title) {

    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Defect Type');
    data.addColumn('number', 'Defect(s) Count');
    data.addColumn({
        type: 'string',
        role: 'style'
    });
    data.addColumn({
        type: 'string',
        role: 'link'
    });

    chartData.forEach((element, index) => {
        var value = element.defectType;
        var count = element.count;
        var color = element.color;
        var link = element.jqlQuery;
        data.addRow([value, Number(count), 'color:' + color, link]);
    });


    var options = {
        title: title,
        vAxis: {
            title: 'Defect Count',
            format: '0',
            minValue: 0
        },
        hAxis: {
            title: 'Defect Type'
        },
        legend: {
            position: 'none'
        }
    };
    var chart = new google.visualization.ColumnChart(document.getElementById(containerId));
    chart.draw(data, options);
    google.visualization.events.addListener(chart, 'select', selectHandler);

    function selectHandler() {
        var selectedItem = chart.getSelection()[0];
        if (selectedItem) {
            var link = data.getValue(selectedItem.row, 3);
            if (link) {
                window.open(link, '_link');
            }
        }
    }
}

function drawBarGroupChart(containerId, chartData, title, colorData) {
    if (Object.keys(chartData).length === 0) {
        // Draw an empty chart
        drawEmptyChart(containerId, title);
        return;
    }
    // Convert javaData object into an array of arrays
    var data = [];
    var types = Object.keys(chartData);
    var defects = {};
    var jiraData = chartData;

    // Collect all unique defect keys
    types.forEach(function(type) {
        Object.assign(defects, chartData[type]);
    });

    // Create the header row
    var headerRow = ['Type'];
    Object.keys(defects).forEach(function(defect) {
        headerRow.push(defect);
    });
    data.push(headerRow);

    // Populate data rows
    types.forEach(function(type) {
        var row = [type];
        Object.keys(defects).forEach(function(defect) {
            row.push(chartData[type][defect] || 0);
        });
        data.push(row);
    });

    console.log(data);
    var chartData = google.visualization.arrayToDataTable(data);

    var options = {
        title: 'Total Days to resolve defect',
        vAxis: {
            title: 'Days'
        },
        hAxis: {
            title: 'Resolved Defect Type'
        },
        seriesType: 'bars',
        series: {} // You can adjust this to customize the chart
    };
    var index = 0;
    colorData.forEach(function(defect) {
        var groupSize = Object.keys(jiraData[defect.defectType]).length;
        for (var i = 0; i < groupSize; i++) {
            options.series[index++] = {
                color: defect.color
            };
        }
    });
    options.bar = {
        groupWidth: '200%'
    };
    var chart = new google.visualization.ComboChart(document.getElementById(containerId));
    chart.draw(chartData, options);
}

function drawEmptyChart(containerId, title) {
    var data = google.visualization.arrayToDataTable([
        ['Type', 'No Data'],
        ['No Data', 0]
    ]);

    var options = {
        title: title,
        vAxis: {
            title: 'Days'
        },
        hAxis: {
            title: 'Resolved Defect Type'
        },
        seriesType: 'bars',
        series: {} // You can adjust this to customize the chart
    };

    var chart = new google.visualization.ComboChart(document.getElementById(containerId));
    chart.draw(data, options);
}


function drawBarChartForPriorityCount(containerId, chartData, title) {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Type');
    data.addColumn('number', 'Count');
    data.addColumn({
        type: 'string',
        role: 'style'
    });

    chartData.forEach((element, index) => {
        var value = element.priorityName;
        var count = element.totalCount;
        var color = element.color;
        data.addRow([value, Number(count), 'color:' + color]);
    });


    var options = {
        title: title,
        vAxis: {
            title: 'Priority Total Count',
            format: '0',
            minValue: 0
        },
        hAxis: {
            title: 'Priority'
        },
        legend: {
            position: 'none'
        }
    };
    var chart = new google.visualization.ColumnChart(document.getElementById(containerId));
    chart.draw(data, options);
}


function drawBarChartForOpenStatusDefect(containerId, chartData, title) {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Defect Type');
    data.addColumn('number', 'Open Defect Count');
    data.addColumn({
        type: 'string',
        role: 'style'
    });

    chartData.forEach((element, index) => {
        var value = element.defectType;
        var count = element.count;
        var color = element.color;
        data.addRow([value, Number(count), 'color:' + color]);
    });


    var options = {
        title: title,
        vAxis: {
            title: 'Open Defect Count',
            format: '0',
            minValue: 0
        },
        hAxis: {
            title: 'Open Defect Type'
        },
        legend: {
            position: 'none'
        }
    };
    var chart = new google.visualization.ColumnChart(document.getElementById(containerId));
    chart.draw(data, options);
}

function populateTable(chartData) {
    const tableBody = document.getElementById("defectTable");
    // Clear existing table rows
    tableBody.innerHTML = '';

    // Populate table with single object data
    const row = `
         <tr>
             <td>${chartData.totalDefectCount}</td>
             <td>${chartData.totalResolvedCount}</td>
             <td>${chartData.totalOpenCount}</td>
         </tr>
     `;
    tableBody.insertAdjacentHTML('beforeend', row);
}
$("#clearSelection").click(function() {
    multiselect.val(null).trigger("change");
    multiselect.each(function() {
        localStorage.removeItem(this.id);
    });
    localStorage.removeItem('startDate');
    localStorage.removeItem('endDate');
    $('#startDate').val('');
    $('#endDate').val('');
});

$("#label").on("select2:select select2:unselect", function(e) {
    if (e.params.data.id === "ALL") {
        if (e.type === "select2:select") {
            // If "ALL" is selected, select all other options except "ALL"
            $(this).find('option[value!="ALL"]').prop("selected", true);
            $(this).trigger("change");
        } else if (e.type === "select2:unselect") {
            // If "ALL" is deselected, unselect all options
            $(this).val(null).trigger("change");
        }
    }
});

$("#defect").on("select2:select select2:unselect", function(e) {
    if (e.params.data.id === "ALL") {
        if (e.type === "select2:select") {
            // If "ALL" is selected, select all other options except "ALL"
            $(this).find('option[value!="ALL"]').prop("selected", true);
            $(this).trigger("change");
        } else if (e.type === "select2:unselect") {
            // If "ALL" is deselected, unselect all options
            $(this).val(null).trigger("change");
        }
    }
});
$('#startDate, #endDate').datepicker({
    container: 'body',
    format: 'yyyy-mm-dd',
    autoclose: true,
    orientation: 'bottom'
}).on('show', function() {
    $('html, body').animate({
        scrollTop: $('.form-group.text-center').offset().top
    }, 500);
    $('.form-group.text-center').css('margin-top', '19%');
}).on('hide', function() {
    $('.form-group.text-center').css('margin-top', '0');
});

});

Html code

   <!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Defect Dashboard</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet"/>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css">
    <link rel="stylesheet" href="defectdashboard.css">
    <link href="custom_styles.css" rel="stylesheet" />
</head>
<body>

<!-- Form Section -->
<section class="container mt-3" id="form-section">
    <div class="spinner" id="spinner" style="display: none;">
        <i class="fas fa-spinner fa-spin fa-3x"></i>
    </div>
    <form id="metrics-form" action="submit" method="POST" th:object="${defectModel}">
        <!-- Project Name Dropdown -->
        <div class="form-group">
            <label for="projectName">Project Name</label>
            <select id="projectName" name="projectName" class="form-control" th:field="*{projectName}" multiple>
                <option th:each="project : ${projectNames}" th:value="${project.name}" th:text="${project.name}"
                        th:data-tooltip="${project.labels}">
                ></option>
            </select>
        </div>
        <!-- Squad Dropdown -->
       <!-- <div class="form-group">
            <label for="squad">Squad Name</label>
            <select id="squad" name="squad" class="form-control" th:field="*{squad}" multiple>
                <option th:each="squad : ${squads}" th:value="${squad}" th:text="${squad}"></option>
            </select>
        </div>-->
        <div class="form-group">
            <label for="label">Domain/Platform/System</label>
            <select id="label" name="label" class="form-control" th:field="*{label}" multiple>
                <option value="ALL">ALL</option>
                <option th:each="label : ${labels}" th:value="${label}" th:text="${label}"></option>
            </select>
        </div>
        <div class="form-group">
            <label for="defect">Defect Type<span style="color:red">*</span></label>
            <select id="defect" name="defect" class="form-control" th:field="*{defect}" multiple>
                <option value="ALL">ALL</option>
                <option th:each="defect : ${defectTypes}" th:value="${defect}" th:text="${defect}"></option>
            </select>
        </div>
        <div class="form-row">
            <div class="form-group col-md-6">
                <label for="startDate">Start Date</label>
                <input type="text" id="startDate" name="startDate" class="form-control" th:field="*{startDate}" autocomplete="off" placeholder="Enter Start Date">
            </div>

            <div class="form-group col-md-6">
                <label for="endDate">End Date</label>
                <input type="text" id="endDate" name="endDate" class="form-control" th:field="*{endDate}" autocomplete="off" placeholder="Enter End Date">
            </div>
        </div>

        <!-- Multiselect Option -->
        <!-- Submit and Cancel Buttons -->
        <div class="form-group text-center">
            <button type="submit" class="btn btn-primary">Submit</button>
            <button type="button" id="clearSelection" class="btn btn-primary">Clear</button>
            <div class="tooltip-container">
            <button type="button" class="btn btn-secondary" id="addProjectButton" >Add New Project</button>
                <div class="tooltip-content">Only project co-ordinator can add a New Project</div>
            </div>
            </div>
    </form>
</section>

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>
<script src="dashboard.js"></script>
</body>
</html>

Css

    .header-bar {
     background-color: black;
     color: white;
     padding: 5px;
     display: flex;
     justify-content: space-between;
     align-items: center;
}
 .dashboard-defect{
     text-align: center;
     flex: 1;
}
/* Custom styles for bold labels */
 .form-group label {
     font-weight: bold;
}
 .chart-container {
     margin-bottom: 20px;
}
 .spinner {
     display: flex;
     justify-content: center;
     align-items: center;
     position: fixed;
     top: 0;
     left: 0;
     width: 100%;
     height: 100%;
     background-color: rgba(255, 255, 255, 0.8);
    /* Semi-transparent white background */
     z-index: 9999;
    /* Higher z-index to ensure it's displayed on top of other elements */
}
/* CSS for the spinner icon */
 .spinner i {
     font-size: 3em;
    /* Adjust the size of the spinner icon */
     color: #007bff;
    /* Spinner color, you can change this to match your design */
}
 .tooltip-container {
     position: relative;
    /* Ensure tooltip is positioned relative to this container */
     display: inline-block;
    /* Ensure it only takes up space for its content */
}
 .tooltip-content {
     display: none;
    /* Initially hidden */
     position: absolute;
    /* Positioning it relative to the container */
     background-color: #fff;
     color: #333;
     padding: 10px;
     border: 1px solid #ccc;
    /* Thin black border */
     border-radius: 4px;
     max-width: 300px;
    /* Adjust width as needed */
     white-space: nowrap;
    /* Keep text in a single line */
     overflow: hidden;
    /* Hide overflowed text */
     text-overflow: ellipsis;
    /* Add ellipsis for overflowed text */
     font-size: 12px;
     text-align: center;
     z-index: 1060;
    /* Ensure it is above other content */
     top: 100%;
    /* Position below the button */
     left: 50%;
    /* Center horizontally */
     transform: translateX(-50%);
    /* Adjust for centering */
     opacity: 0;
    /* Start as invisible */
     transition: opacity 0.3s, transform 0.3s;
    /* Fade in/out effect and slight move */
}
 .tooltip-container:hover .tooltip-content {
     display: block;
    /* Show tooltip on hover */
     opacity: 1;
    /* Make it visible */
     transform: translateX(-50%) translateY(5px);
    /* Slightly move it down */
}
 #response-message {
     display: none;
    /* Hide by default */
     max-width: 400px;
    /* Set a maximum width for the alert */
     width: 100%;
    /* Allow the width to adjust but not exceed max-width */
     margin: 20px auto;
    /* Center the alert horizontally with auto margins */
     padding: 10px;
    /* Padding inside the alert box */
     box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    /* Optional: Add shadow for better visibility */
     display: flex;
     align-items: center;
     justify-content: space-between;
     border-radius: 4px;
    /* Rounded corners */
}
 #response-text {
     flex: 1;
    /* Allow text to take up remaining space */
}
 #response-ok {
     margin-left: 10px;
    /* Space between the message and the button */
}
 .select2-tooltip {
     display: block;
     position: absolute;
     background-color: #333;
     color: #fff;
     padding: 5px;
     border-radius: 3px;
     font-size: 12px;
     z-index: 1000;
}
 .select2-container--open .select2-tooltip {
     display: block;
}

React state is not getting updated, component state data is not updating due to that [closed]

I am trying to receive the GET API result data to the component using redux-reducers and actions, component is not able to receive the data, it is showing below error in the component.
NOTE: I can able to see the result data in redux-actions file, but same data is not going to component

ERROR

HomeScreen.js:17 Uncaught TypeError: Cannot read properties of undefined (reading 'map')
    at HomeScreen (HomeScreen.js:17:1)

REDUCER FILE

import { PRODUCT_LIST_REQUEST,
        PRODUCT_LIST_SUCCESS,
        PRODUCT_LIST_FAIL
 } from '../constants/productConstants'

 export const productListReducer = (state = { products: [] }, action) => {
    switch (action.type) {
        case PRODUCT_LIST_REQUEST:
            return { loading: true, products: [] }

        case PRODUCT_LIST_SUCCESS:
            return {
                loading: false,
                products: action.payload.products,
            }

        case PRODUCT_LIST_FAIL:
            return { loading: false, error: action.payload }

        default:
            return state
    }
}

ACTION FILE

import axios from 'axios'
import { PRODUCT_LIST_REQUEST,
    PRODUCT_LIST_SUCCESS,
    PRODUCT_LIST_FAIL
} from '../constants/productConstants'

export const listProducts=()=> async(dispatch)=>{
    try{
        dispatch({type:PRODUCT_LIST_REQUEST})
        const {data}= await axios.get('/api/products/')
        console.log("data-------------")
        console.log({data})
        dispatch({
            type:PRODUCT_LIST_SUCCESS,
            payload:data
        })

    }catch(error){
        dispatch({
            type:PRODUCT_LIST_FAIL,
            payload:error.response && error.response.data.detail
            ? error.response.data.detail
            :error.message
        })

    }
}

COMPONENT FILE

import React ,{useState, useEffect} from 'react'
import {Row,Col} from 'react-bootstrap'
import ProductList from '../components/ProductList'
import {useDispatch, useSelector  } from 'react-redux'
import { listProducts } from '../actions/productActions'

export default function HomeScreen() {
  const dispatch = useDispatch()
    const productList = useSelector(state => state.productList)
    const { error, loading, products, page, pages } = productList
    useEffect(() => {
      dispatch(listProducts())

  }, [])
  return (
    <div>
      <Row>
        {products.map(product => (
           <Col key={product._id} sm={12} md={6} lg={4} xl={3}>
                <ProductList product_details={product}></ProductList>
           </Col>

        ))}
      </Row>
    </div>
  )
}

How can I use two different data sources for the main chart and dataZoom in Apache ECharts?

I’m working with Apache ECharts and trying to use two different data sources: one for the main chart and another for the dataZoom preview.

Due to the large amount of data, I’ve reduced the resolution over longer time periods to minimize the data sent to the client. However, I want the main chart to display a much higher resolution when the user zooms in on a smaller time range.

This screenshot shows my issue

Unfortunately, I can’t figure out how to use two different data sources for the main chart and the dataZoom overview. Does anyone have any suggestions on how to achieve this?

Basically the dataZoom chart should always show the complete chart, and the main plot should load and display the selected area.

I have created this example in the online editor of ECharts, to demonstrate my issue

How can I have a webpage access a text file, edit it and autosave? [closed]

What I would ultimately like to achieve is for the webpage to load the text file “list1.txt”, display the text, and make the text editable through the browser on the webpage, then whenever the text is edited I want it to autosave to the text file so next time someone loads the webpage it will continue where it left off.

        <div style="text-align:center">
        <iframe id="myFrame" src='list1.txt' scrolling='yes' height="800" width="400" frameborder="0"></iframe>

        <script>
        var frame = document.getElementById('myFrame');
            frame.onload = function () {
                var body = frame.contentWindow.document.querySelector('body');
                body.style.color = 'red';
                body.style.fontSize = '20px';
                body.style.lineHeight = '20px';
            };
        iframe.contentDocument.designMode = 'on';   
        </script>
        </div>

This is the code I have created so far. Simultaneously, my editing of the iframes property such as font colour are not changing.

Regular expression in monaco editor integration with angular14

I have integrated monaco editor in angular14 and have created a custom highlighter, I want to highlight only standalone keywords as per the list I have created, but it is highlighting the keywords from my list when they have alphanumeric characters or _ as prefix. Please modify the regular expression below.

[/b(external|in_map|internal|out_map|encoder|decoder|xml_schema|asn_block|external_only|session)b/, ‘keyword’],enter image description here

Highlight only the standalone word from the keyword list