How to set Authorization header in jest testing?

I have this testing code that it’s not returning what i want, and it’s sending me 401 Authorization error, am i doing something wrong? I’m new at testing. I already tried passing the raw authentication token, but still the same error.

This is the error:

GET /products › should return a list of products                                                  
                                                                                                  
expect(received).toBe(expected) // Object.is equality

Expected: 200
Received: 401

  22 |       .get("/product")
  23 |       .set("Authorization", `Bearer ${token}`);
> 24 |     expect(res.status).toBe(200);
     |                        ^
  25 |     expect(Array.isArray(res.body)).toBe(true);
  26 |   });
  27 | });

  at __tests__/controllers/product.test.ts:24:24
  at fulfilled (__tests__/controllers/product.test.ts:5:58)
import request from "supertest";
import { Request, Response } from "express";
import { app } from "../../src/app";
import { connect, disconnect } from "../../src/database/db";
import Product from "../../src/models/Product";
import Category from "../../src/models/Category";
import jwt from "jsonwebtoken";
import { login } from "../../src/controllers/auth"

beforeAll(async () => {
  await connect();
});

afterAll(async () => {
  await disconnect();
});

describe("GET /products", () => {
  it("should return a list of products", async () => {
    const token = jwt.sign({ role: "admin" }, "CARDAPIOJWTPASS");
    const res = await request(app)
      .get("/product")
      .set("Authorization", `Bearer ${token}`);
    expect(res.status).toBe(200);
    expect(Array.isArray(res.body)).toBe(true);
  });
});

Biggest value in bar chart does not appear

I have a bar chart that I have scripted and am loading values in through my json file. All values appear through labels except for my highest value (60). What can I do to get my 60 label to appear in my chart?

html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>CS50C Week11</title>
  </head>
  <body>
    <div style="margin-top: 50px; padding:auto">
        <canvas id="myCanvas" width="500" height="500" ></canvas>
      </div>
    <script src="script.js"></script>
  </body>
</html>

data.json

[25, 30, 40, 50, 35, 20, 45, 60, 55, 50]

script.js

try {
  // Load data from JSON file
  fetch('data.json')
    .then(response => response.json())
    .then(data => {
      // Initialize canvas element
      const canvas = document.getElementById('myCanvas');
      if (!canvas) {
        throw new Error('Canvas element not found');
      }
      const ctx = canvas.getContext('2d');

      // Set chart properties
      let chartWidth = 500;
      let chartHeight = 500;
      const barSpacing = 10;
      const barWidth = (chartWidth - (data.length - 1) * barSpacing) / data.length;
      const maxValue = Math.max(...data);
      const labelFont = '16px Arial';
      const valueFont = '12px Arial';
      const labelColor = '#333';
      const valueColor = '#999';

      // Draw bars and labels
        data.forEach((value, index) => {
        const x = index * (barWidth + barSpacing);
        const y = chartHeight - (value / maxValue) * chartHeight;
        const height = (value / maxValue) * chartHeight;

        // Draw bar
        ctx.fillStyle = '#66a';
        ctx.fillRect(x, y, barWidth, height);

        // Draw label
        ctx.font = labelFont;
        ctx.fillStyle = labelColor;
        ctx.textAlign = 'center';
        ctx.fillText(` ${index + 1}`, x + barWidth / 2, chartHeight + 20);

        // Draw value
        ctx.font = valueFont;
        ctx.fillStyle = valueColor;
        ctx.textAlign = 'center';
        ctx.fillText(value, x + barWidth / 2, y - 10);


      });
    })
    .catch(error => console.log(error.message));
} catch (error) {
  console.log(error.message);
}


I have tried adding this if condition in my Draw Label section of my JS

 ctx.textAlign = 'center';              
if (index === data.length - 1) {
        // Adjust x-coordinate for last bar label
        x += barWidth / 2;
      }

so that way it only manipulates x under that condition, but doing so makes my bar furthest to the right disappear (in addition to my 60 bar already being gone)

Ccapture.js and poor webm video quality

I created a simple script to test Ccapture.
It works well but the webm export is of a very poor quality (the edge of the shapes are very pixellated), even though the options are set to “quality: 100”.

I exaggerated the contrast (green background and red shapes) so that the quality shows.

Can someone tell me how I can improve the result?

Thanks.

<!DOCTYPE html>
<html>
<head>
</head>

<body>
    <canvas id="myCanvas" width="960" height="540" style="border:1px solid black"></canvas>
    <button onclick="startRecording()">Start</button>
    <button onclick="stopRecording()">Stop</button>

    <script>
        function startRecording() {
            t = 0;
            capturer.start();
            animation();
        }
    
        function stopRecording() {
            capturer.stop();
            capturer.save();
        }
    
        const canvas = document.getElementById("myCanvas");
        const ctx = canvas.getContext("2d");
        let t = 0;
        let  duration = 120;
        let  startSize = 100; 
        let  startX = (canvas.width - startSize) / 2;
        let  startY = (canvas.height - startSize) / 2;
        let  endSize = startSize * Math.sqrt(2);
        let  endX = (canvas.width - endSize) / 2;
        let  endY = (canvas.height - endSize) / 2;
        
        function animation(){
            const size = startSize + (endSize - startSize) * t / duration;
            const x = startX + (endX - startX) * t / duration;
            const y = startY + (endY - startY) * t / duration;
        
            ctx.fillStyle = "green";
        
            ctx.fillRect(0, 0, canvas.width, canvas.height);
        
            ctx.beginPath();
        
            if (t < duration / 2) { 
                ctx.fillStyle = "red";
                ctx.rect(x, y, size, size);
            } else { 
                ctx.fillStyle = "red";
                ctx.arc(x + size / 2, y + size / 2, size / 2, 0, Math.PI * 2);
            }
            ctx.fill();
        
            if (capturer && capturer.capture) {
                capturer.capture(canvas);
            }
        
            if (t < duration) {
                requestAnimationFrame(animation);
                t++;
            } else if (capturer && capturer.save) {
                capturer.stop();
                capturer.save();
            }
        }
    </script>

    <script src="https://www.clicktorelease.com/code/conway3d_ccapture/js/CCapture.all.min.js"></script>

    <script>
        var capturer = new CCapture( { 
            format: 'webm',
            framerate: 60,
            name: 'visualization',  
            quality: 100,
            verbose: true
        } );
    </script>

</body>

</html>

PS: I kept it all in one file so people can easily copy paste and test this.
If you want me to separate the html from the js, just ask.

Thank you.

I developed a webview application with Flutter and I’m having a cache problem

I am developing an application with flutter, I used flutter_webview in the application, there is no problem, but after a little navigation between large pages, I noticed that some pages are not loading, I think the cache memory is filling up. When I refresh, I can only access the page (reload), so is there a method for this, this way the application becomes unusable, how can I solve this problem thanks

Problems with classes in Tailwind when mapping

I have an API that pulls all data from a table into one. The issue is that I have a Header Component with links, and to make it more flexible and dynamic, I want to separate the pages that have the same category as the link and map them into objects, filtering them. All the mapping goes very smoothly, however when I try to apply the Tailwind classes to them, in case the link they redirect to is the current one, for some reason it adds several commas at the end of the classes “,,,,”.

I’m using NextJS App Directory and Tailwind. Here is the code I used in the Header:

<li
          className={`h-full flex flex-col justify-center group items-center cursor-pointer text-[17px] text-[gray] hover:text-[hsl(var(--theme-color-light))] px-2 border-4 border-transparent ${pages
            .filter((p) => p.category === "8")
            .map((p) =>
              pathname === "/paginas/" + p.url
                ? "font-bold text-[hsl(var(--theme-color))] border-t-[hsl(var(--theme-color))]"
                : ""
            )}`}
        >
          HABBLETXD
          <ul className="absolute rounded-[0.3rem] shadow-[0px_0px_20px_hsla(0,0%,0%,0.25)] top-[65px] opacity-0 pointer-events-none group-hover:opacity-100 group-hover:pointer-events-auto transition-all before:content-[''] before:w-0 before:h-0 before:absolute before:border-[7.5px] before:border-transparent before:border-b-[hsl(var(--theme-color))] before:top-[-15px] before:left-[calc(50%-10px)]">
            <div className="h-full w-full flex flex-col rounded-[0.3rem] overflow-hidden">
              {pages
                .filter((p) => p.category === "8")
                .map((item) => (
                  <a
                    className="px-4 py-[0.9rem] h-full w-full bg-white flex justify-center items-center text-base font-bold text-[hsl(var(--theme-color))] transition-all hover:bg-[hsl(var(--theme-color))] hover:text-white"
                    style={{ textShadow: "0px 0px 5px hsla(0, 0%, 0%, 0.25)" }}
                    key={item.name}
                    href={`/paginas/${item.url}`}
                  >
                    {item.name}
                  </a>
                ))}
            </div>
          </ul>
        </li>

The data I used in this code I set in states. In addition, I used hooks from NextJS itself, such as usePathname (pathname).

Here’s the print of how the code results:

How to reset `top`, `left`, `transition` attributes using a css class?

The below is meant for simulating a drag and drop effect. I’m manually changing the styles both on mousedown and mouseup events using Object.assign(target.style, ...). If I replace the assigment statements with .dragging class that contains the mousedown styles, followed by removing that class on mouseup, the associated left and top attributes set in mouseup stay after removing the .dragging class.

Here’s the working version:

(function() {
    let targets = document.querySelectorAll('.draggable');
    let offsetX;
    let offsetY;
    targets.forEach((target) => {
        target.isMouseDown = false;
        target.initialOffsetLeft = target.offsetLeft;
        target.initialOffsetTop = target.offsetTop;
        target.addEventListener('mousedown', (e) => {
            if (e.buttons === 1) {
                Object.assign(target.style, {
                    transition: null,
                    zIndex: 10000,
                    position: 'relative'
                });
                target.isMouseDown = true;
                offsetX = target.initialOffsetLeft + e.offsetX;
                offsetY = target.initialOffsetTop + e.offsetY;
            }
        });
        document.addEventListener('mouseup', (e) => {
            e.preventDefault();
            target.isMouseDown = false;
            Object.assign(target.style, {
                transition: 'all 0.5s ease',
                zIndex: null,
                left:  '0',
                top: '0'
            });
        });
        document.addEventListener('mousemove', (e) => {
            e.preventDefault();
            if (target.isMouseDown) {
                target.style.left = e.pageX - offsetX + 'px';
                target.style.top = e.pageY - offsetY + 'px';
            }
        });
    });
})();
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Roboto', sans-serif
}

.draggable {
  display: flex;
  padding: 10px 12px;
  margin-top: 0px;
  margin-left: 0px;
  margin-bottom: 11px;
  border-radius: 5px;
  margin-right: 5px;
  background-color: #000000;
  cursor: grab;
  flex-grow: 1;
  color: #ffffff;
  border: 1px solid #6c757d;
}

.my-card-group {
  margin-top: 30px;
  background-color: #000000;
  margin-right: 2%;
  margin-left: 2%;
  border: 1px solid #6c757d;
}
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<div class="card group">
  <div class="my-card-group">
    <div class="card-body">
      <div class="draggable">
        Lorem ipsum dolor sit amet 1
      </div>
      <div class="draggable">
        Lorem ipsum dolor sit amet 2
      </div>
      <div class="draggable">
        Lorem ipsum dolor sit amet 3
      </div>
    </div>
  </div>
</div>

Here’s what I do to replace the Object.assign(...) statements with .dragging class:

(function() {
    let targets = document.querySelectorAll('.draggable');
    let offsetX;
    let offsetY;
    targets.forEach((target) => {
        target.isMouseDown = false;
        target.initialOffsetLeft = target.offsetLeft;
        target.initialOffsetTop = target.offsetTop;
        target.addEventListener('mousedown', (e) => {
            if (e.buttons === 1) {
                target.classList.add('dragging')  // replaced with this
                target.isMouseDown = true;
                offsetX = target.initialOffsetLeft + e.offsetX;
                offsetY = target.initialOffsetTop + e.offsetY;
            }
        });
        document.addEventListener('mouseup', (e) => {
            e.preventDefault();
            target.isMouseDown = false;
            target.classList.remove('dragging') // replaced with this
        });
        document.addEventListener('mousemove', (e) => {
            e.preventDefault();
            if (target.isMouseDown) {
                target.style.left = e.pageX - offsetX + 'px';
                target.style.top = e.pageY - offsetY + 'px';
            }
        });
    });
})();
 

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Roboto', sans-serif
}

.draggable {
    display: flex;
    padding: 10px 12px;
    border-radius: 5px;
    margin: 0 5px 11px 0;
    background-color: #000000;
    cursor: grab;
    flex-grow: 1;
    color: #ffffff;
    border: 1px solid #6c757d;
    transition: all 0.5s ease; /*added this*/
    z-index: unset; /*added this*/
    left: 0; /*added this*/
    top: 0 /*added this*/
}

.dragging { /*added this*/
    z-index: 10000;
    position: relative;
    transition: all 0s;
}

.my-card-group {
    margin-top: 30px;
    background-color: #000000;
    margin-right: 2%;
    margin-left: 2%;
    border: 1px solid #6c757d;
}
 
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" />
<div class="card group">
  <div class="my-card-group">
    <div class="card-body">
      <div class="draggable">
        Lorem ipsum dolor sit amet 1
      </div>
      <div class="draggable">
        Lorem ipsum dolor sit amet 2
      </div>
      <div class="draggable">
        Lorem ipsum dolor sit amet 3
      </div>
    </div>
  </div>
</div>

This breaks how the dragging works because left and top as well as transition attributes persist after .dragging is removed, and the next time any of the .draggable is dragged, it starts where its previous drag ended and with a transition delay set by .dragging. Is there a way to achieve the initial behavior using a similar approach?

How to show a message if the search doesn’t match the result?

I am using node js and templates of ejs in my application, and I am trying to show a message in case the search field doesn’t match any result, I expected it will show me “Line does not exist.”, but it shows the search results instead as shown in the screenshot below:

enter image description here

I tried to modify the condition in the if statement <% } else if(oneresult != ''){ %> in different ways but it doesn’t work. Below is the code:

<%- include('partials/header') -%>

<div class="container mt-5 w-50">
  <h2 class="mb-4">Search a Line</h2>

  <form action="/line" method="GET">
    <input
      type="text"
      name="line"
      class="form-control"
      placeholder="Enter a Line"
    />

    <button type="submit" class="btn btn-danger btn-block mt-3">
      Search in Database
    </button>
  </form>

  <% if(oneresult) { %>
  <h4 class="text-danger my-4">Search Results:</h4>
  <table class="table table-bordered" width="100%" cellspacing="0">
    <thead>
      <tr>
        <th>ID</th>
        <th>Line</th>
        <th>Date</th>
      </tr>
    </thead>

    <tbody>
      <% oneresult.forEach( oneresult=>{ %>
      <tr>
        <td><%= oneresult.id %></td>
        <td><%= oneresult.result %></td>
        <td><%= oneresult.date %></td>
      </tr>
      <% }) %>
    </tbody>
  </table>
  <% } else if(oneresult != ''){ %>

  <div class="alert alert-danger mt-4">Line does not exist.</div>

  <% } %>
</div>

<%- include('partials/footer') -%>

Any suggestions, please?

Adding the onclick event to a field of each row in the Ajax datatables in HTML

I have a datatables table that uses JSON data to display information in the table.
I put the desired link along with its ID on one of the fields of each row so that the user can enter the page specific to the details of each field .
But now, instead of using the a tag, I want to create an onclick event that will open a web page for me by calling window.open(‘https://somewhere’).
I want to set an event on the data that comes from the title
I did a short search on the internet but did not find any results
Thank you for your help

The general form of codes related to the table and table script

table structure :

<table class="datatables-basic table table-bordered">
            <thead>
                <tr>
                    <th></th>
                    <th></th>
                    <th></th>
                    <th>schoolName</th>
                    <th>HeadName</th>
                    <th>PhoneNumber</th>
                    <th>HeadPhoneNumber</th>
                    <th>Address</th>
                    <th>IsActive</th>
                    <th>DO</th>

                </tr>
            </thead>
 </table>

table script (DataTable):

 $(function () {

            var dt_basic_table = $('.datatables-basic'),
                dt_basic;

            // DataTable with buttons
            // --------------------------------------------------------------------

            if (dt_basic_table.length) {
                var listFilesUrl = "https://localhost:44309/AllSchools";
                dt_basic = dt_basic_table.DataTable({
                    ajax: listFilesUrl,
                    columns: [
                        { data: '' },
                        { data: 'schoolId' },
                        { data: 'schoolId' },

                        //I want to set an event on the data that comes from the title
                        { data: 'title',
                            render: function (data, type, row) {
                                return $('<a>')
                                    .attr({ target: "_blank", href:"https://localhost:44309/RenderSchool?schoolId=" + row.schoolId })
                                    .text(data)
                                    .wrap('<div></div>')
                                    .parent()
                                    .html();
                            }
                        },

                        { data: null,
                            render: function (data, type, row){
                                var details = row.headFirstName + " " + row.headLastName;
                                return details;
                            }
                        },
                        { data: 'phoneNumber' },
                        { data: 'headPhoneNumber' },
                        { data: 'address' },
                        { data: 'isActive' },
                        { data: '' }
                    ],

Passing variables from view to Javascript code in Django

I have a template like the below in Django

{% extends 'reports/base.html' %}

{% block title %} Report Name {% endblock %}

{% block content %}
<!--
<div class="container-fluid">
  <div class="row"><div class="col">
    <ul class="list-group">
      {% for r in report_list %}
      <li class="list-group-item"><a class="link-offset-2 link-underline link-underline-opacity-0" href={% url 'reports' report_id=r.id %}>{{ r.report_name }}</a></a></li>
      {% endfor %}
    </ul>

  </div><div class="col"></div><div class="col"></div></div>
</div>-->
<div class="demo-container">
  <div id="sales"></div>
  <div id="sales-popup"></div>
</div>

<script>
  $(() => {
    let drillDownDataSource = {};
  
    $('#sales').dxPivotGrid({
      allowSortingBySummary: true,
      allowSorting: true,
      allowFiltering: true,
      allowExpandAll: true,
      showBorders: true,
      showRowGrandTotals: false,
      showColumnGrandTotals: false,
      fieldChooser: {
        enabled: true,
      },
      export: {
        enabled:true
        },
      onCellClick(e) {
        if (e.area === 'data') {
          const pivotGridDataSource = e.component.getDataSource();
          const rowPathLength = e.cell.rowPath.length;
          const rowPathName = e.cell.rowPath[rowPathLength - 1];
          const popupTitle = `${rowPathName || 'Total'} Drill Down Data`;
  
          drillDownDataSource = pivotGridDataSource.createDrillDownDataSource(e.cell);
          salesPopup.option('title', popupTitle);
          salesPopup.show();
        }
      },
      onExporting: function(e) { 
        var workbook = new ExcelJS.Workbook(); 
        var worksheet = workbook.addWorksheet('Main sheet'); 
        DevExpress.excelExporter.exportPivotGrid({ 
            worksheet: worksheet, 
            component: e.component,
            customizeCell: function(options) {
                var excelCell = options;
                excelCell.font = { name: 'Arial', size: 12 };
                excelCell.alignment = { horizontal: 'left' };
            } 
        }).then(function() {
            workbook.xlsx.writeBuffer().then(function(buffer) { 
                saveAs(new Blob([buffer], { type: 'application/octet-stream' }), 'PivotGrid.xlsx'); 
            }); 
        }); 
        e.cancel = true; 
    },
      dataSource: {
        fields: [
          /*{
          caption: 'primary_label',
          width: 120,
          dataField: 'primary_label',
          area: 'row',
        }, */{
          'caption': 'secondary_label',
          'dataField': 'secondary_label',
          'width': 150,
          'area': 'row',
          'expanded': true
        },
        {
          caption: 'account',
          dataField: 'account',
          width: 150,
          area: 'row',
          expanded: true
        },
        {
          caption: 'category',
          dataField: 'category',
          width: 150,
          area: 'row',
          expanded: true
        },
        {
          caption: 'subcategory',
          dataField: 'subcategory',
          width: 150,
          area: 'row',
          expanded: true
        }, {
          dataField: 'period',
          dataType: 'date',
          area: 'column',
        }, {
          caption: 'value_eth',
          dataField: 'value_eth',
          dataType: 'number',
          summaryType: 'sum',
          //format: 'Number',
          format: {
                type: "fixedPoint",
                precision: 0
            },
          area: 'data',
        },
      // Filters
        {
          area: 'filter', 
          dataField: 'secondary_label',
          filterType: 'include',
          filterValues: ['1.1. Staked Assets', '3.2. Operating Performance']
      },
      {
        area: 'filter', 
        dataField: 'account',
        filterType: 'include',
        filterValues: ['3.2.1. Net Revenue', '3.2.2. Cost of Revenue','1.1.1. Staked ETH']
    }],
        store: sales,
      },
    });
  
    const salesPopup = $('#sales-popup').dxPopup({
      width: 1360,
      height: 600,
      //resizeEnabled:true,
      contentTemplate(contentElement) {
        $('<div />')
          .addClass('drill-down')
          .dxDataGrid({
            width: 1260,
            height: 500,
            scrolling: {
              mode: 'virtual',
            },
            export: {
              enabled:true,
              allowExportSelectedData: true
              },
              onExporting(e) {
                const workbook = new ExcelJS.Workbook();
                const worksheet = workbook.addWorksheet('LIDO');
          
                DevExpress.excelExporter.exportDataGrid({
                  component: e.component,
                  worksheet,
                  autoFilterEnabled: true,
                }).then(() => {
                  workbook.xlsx.writeBuffer().then((buffer) => {
                    saveAs(new Blob([buffer], { type: 'application/octet-stream' }), 'LIDO.xlsx');
                  });
                });
                e.cancel = true;
              },
            columns: ['period', 'primary_label', 'secondary_label', 'account','base_token_address','value_eth'],
          })
          .appendTo(contentElement);
      },
      onShowing() {
        $('.drill-down')
          .dxDataGrid('instance')
          .option('dataSource', drillDownDataSource);
      },
      onShown() {
        $('.drill-down')
          .dxDataGrid('instance')
          .updateDimensions();
      },
          
    }).dxPopup('instance');
  });
  
</script>
{% endblock %}

The portion where the field list definition starts, I wanted to make this dynamic and get the values from a view which has logic to determine the field list.

dataSource: {
        fields: [

Have the following on the view logic

    field_list = ['col1','col2']
    return render(request, 'reports/report.html', context={'field_list': field_list})

I tried using the Jinja expression within the javascript and it throws syntax error, how can I fix this.

      dataSource: {
        fields: [
        {% for f in field_list %}  
        {
          'caption': f,
          'dataField': f,
          'width': 150,
          'area': 'row',
          'expanded': true
        },
        {% endfor %}

Loading image from a website and displaying it onto a canvas

I am trying to build a frontend with SvelteKit which queries a webserver using an HTTP get request for a file. I receive the file (which is ZIP format), unzip it, and extract an image from it. I am trying to then display the image on the frontend, but am struggling to get the displaying part part working. I am new to Svelte, JS and frontend development (coming from a scientific programming/Python background) so I am trying to hack my way through this. This is what I’ve tried so far:

<script>
...
async function download() {
    ...
    // get image portion of the data
    const image_data = await zip_data.file('view_img.jpg').async('blob');

    image_url = URL.createObjectURL(image_data);
    console.log('image url', image_url);
    console.log(image_data)

    const ctx = canvas.getContext('2d');

    var img = new Image();
    img.onload = function() {
        ctx.drawImage(img, 0, 0);
    };
    img.src = image_url
}
</script>
...
<canvas bind:this={canvas} width=600 height=400></canvas>

VSCode is complaining that I cannot create the image object without any arguments (The error is showing up as: Expected 1 arguments, but got 0.js(2554)) but all of the code samples that I see online show Image being created with no arguments. The only difference I notice is that most of the code samples create images in the onMount() function, but in my specific case, I am trying to load an image after processing some user input and running my HTTP GET query.

I would appreciate someone’s help in figuring out how to do this seemingly simple task of downloading an image and showing it on the frontend that I’m building.

TYVM!

How can I treat special characters as part of a whole word in a regex search?

If I want to do a “whole word” search for a string with special characters, like say “A+”, how can I write a Javascript regex that will match the whole word for cases like the following:

  1. Is the only text in the string: “A+”
  1. Is at the end of the string: “You got an A+.”

  2. Is at the beginning of the string: “A+ good job!”

  3. Is in the middle: “You did A+ work here.”

It should return false for:

  1. Not whole word: “A++”

  2. Not whole word”: “You got an A++!”

… and many other cases

I’d love to just use b:

 /b(A+)b/g 

…but that seems to interact poorly with special characters (in fact I’m not sure that regex can even match anything…).

How can I determine if there is a duplicate dictionary in an array of dictionaries in JavaScript?

I have an array of dictionaries and I want to determine if there are any duplicate dictionaries. I tried using the _uniq method from Lodash.js and it looks like it’s finding unique dictionary objects but not determining if they’re equal. I also tried using the Set method which lets me store unique values of any type, whether primitive values or object references.

I know Lodash.js also has a method _.isEqual that determines equality between two unique dictionary objecs so it may be useful.

How can I determine if there is a duplicate dictionary in an array of dictionaries in JavaScript?

// The function should return True because there are two equal dictionaries
arr = [
    {
      "a": 1,
      "b": 2,
    },
    {
      "a": 1,
      "b": 2,
    }
];

// Lodash.js attempt
function hasDuplicate(arr) {
    return _uniq.(arr).length !== arr.length;
}

// Set attempt
function hasDuplicate(arr) {
    const noDuplicates = new Set(arr);
    return arr.length !== noDuplicates.size;
}

Unable to fetch data from database using Nodejs

I am working with Nodejs and using expressjs for API’S,Right now i am getting “undefined” in console.log (coming from model), How can i fetch data using express js ?

const sendotps = async (req, res) => {
    var phone_number=req.body.phone_number;
    if (!phone_number || !phone_number.trim() || phone_number == null || phone_number < 10)
        return res.status(400).send({ statusCode: 400, statusMessage: 'Bad Request', message: 'Enter valid mobile number', data: null });
    try {
        const result= await User.sendOtp(phone_number);
        console.log('result is '+ result);
        if(result!"notexist")
            {
                    // further code
            }
        else
            {
                    // further code
            }   
    } catch (err) {
        res.status(500).send({
            statusCode: 500,
            statusMessage: 'Internal Server Error',
            message: null,
            data: null,
        });
    }

Here is my “model file”(user.model)

static sendOtp(phone_number) {
        const sql2 = "SELECT * FROM users WHERE phone_number = '${phone_number}' AND is_registered='1'";
                const [rows2, fields2] = await pool.execute(sql2);
               if(rows2>0)
                {
                        return rows2;
                }
                else
                {
                        return "notexist";
                }
    }