Best way to show barcode included pdf in html

I am showing a pdf as image or directly image depending on situation which include bar barcodes and depending on situation i generate it. There is not any problem on print preview of browser but when they printed some of the barcodes are not readable for barcode reader. What is the best way to show and print them? This is my code:

<style>
    img {
        height: 6IN;
        width: 4IN;
    }

    .new-page {
        page-break-before: always;
    }

    p {
        font-size: 70%;
    }

    b {
        font-size: 70%;
    }
</style>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/barcodes/JsBarcode.code128.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.10.377/pdf.min.js"></script>



@{
    int i = 0;
    int j = 0;
    int page = 1;
    int cnt = 1;
}
@foreach (var item in Model)
{
    if (item.Platform == "Walmart")
    {
        <div class="row new-page">
            <div class="col-12">
                <canvas id="[email protected]" style="width:100%; height:auto;"></canvas>

                @*            <img src="@item.Image" onload="generateBarcodeAndPrint('@item.OrderId')"/>
        *@
            </div>
        </div>
        <script>
            // URL to your base64 encoded PDF
            var pdfData = '@Html.Raw(item.Image)';
            var orderId = '@item.OrderId';
            // Load the PDF data using pdf.js
            pdfjsLib.getDocument({ data: atob(pdfData) }).promise.then(function(pdf) {
                // Render the first page as an image
                pdf.getPage(1).then(function(page) {
                    var canvas = document.getElementById('[email protected]');
                    var context = canvas.getContext('2d');
                    var viewport = page.getViewport({ scale: 2 });

                    canvas.width = viewport.width;
                    canvas.height = viewport.height;

                    var renderContext = {
                        canvasContext: context,
                        viewport: viewport
                    };

                    page.render(renderContext).promise.then(function() {
            @*                    if (@((page+1) / 2 == Model.Count ? "true" : "false")) {
                    window.print();
                    }*@
                        });
                });
            });
        </script>
        @if (item.TotalCount > 1)
        {
            string s;
        }
        @while (cnt != item.TotalCount)
        {
            cnt++;
        }
        @if (cnt == item.TotalCount)
        {
            cnt = 1;
            var orders = Model.Where(w => w.OrderId == item.OrderId).ToList();

            <div class="row new-page">
                <br>
                <div class="col-12">
                    <p style="font-size:14px;text-align:center;vertical-align:bottom;">@(page)</p>
                    @if (item.OrderNavigation.ShipServiceLevel == null)
                    {
                        <p>@item.CreateDate</p>

                    }
                    else if (item.OrderNavigation.ShipServiceLevel == "Econ US Dom")
                    {
                        <p>@item.OrderNavigation.ShipServiceLevel | @item.CreateDate</p>
                    }
                    else
                    {
                        <b style="text-align:center;">@item.OrderNavigation.ShipServiceLevel | @item.CreateDate</b>
                    }
                </div>
                <hr>
                <div class="col-12">

                    @*            <b  class="text-center" style="text-align:center;font-size:80%;"> Quantity: @ViewBag.shippings[j].Items[0].Quantity</b>
        *@
                    <!-- Generate barcode for OrderId -->
                    <canvas id="[email protected]" style="width:90%;height:20%;"></canvas>
                    <script>
                        // Function to generate barcode for each OrderId
                        function generateBarcodeForOrderId(id, orderId) {
                            JsBarcode("#barcodeCanvas-" + id, orderId, { format: "CODE128" });
                            //setTimeout(function () {
                            //    window.print();
                            //}, 500);
                        }
                        generateBarcodeForOrderId("@item.Id", "@item.OrderId");
                        // Call the function with the current OrderId
                        //window.onload = function () {
                        //    // Call the function with the current OrderId
                        //    generateBarcodeForOrderId("@item.OrderId");
                        //};
                    </script>
                </div>
                <hr>
                <div class="col-12">
                    <p>@item.OrderNavigation.Address</p>
                </div>
                @foreach (var ittem in orders)
                {
                    <hr>
                    <p style="text-align:center;">Quantity</p>
                    <div style="border: 2px solid #000; width: fit-content; padding: 10px; text-align: center; margin: auto;">
                        <h3> @ittem.OrderNavigation.Quantity</h3>

                    </div>
                    <br />
                    <div class="col-12">
                        <b class="text-center" style="text-align:center;">@ittem.OrderNavigation.Title</b>
                    </div>
                    <hr>
                    <div class="col-12">
                        <b class="text-center" style="text-align:center;">SKU: @ittem.OrderNavigation.Sku</b>
                    </div>
                    <hr>
                    <div class="col-12">
                        <b class="text-center" style="text-align:center;">Label Count: @item.TotalCount</b>
                    </div>
                }


            </div>
            page++;
            j++;



        }
        else
        {
            @*            cnt++;
*@                      j++;
        }
    }

    else
    {
        <div class="row new-page">
            <div class="col-12">
                <img src="@item.Image" style="width:97%; height:auto;" onload="generateBarcodeAndPrint('@item.Id','@item.OrderId')" />
            </div>
        </div>
        @while (cnt != item.TotalCount)
        {
            cnt++;
        }
        @if (cnt == item.TotalCount)
        {
            cnt = 1;
            var orders = Model.Where(w => w.OrderId == item.OrderId).ToList();


            <div class="row new-page">
                <br>

                <div class="col-12">
                    <p style="font-size:14px;text-align:center;vertical-align:bottom;">@(page)</p>

                    @{
                        var v = item.OrderNavigation.ShipServiceLevel;
                        int g = 6;
                    }
                    @if (item.OrderNavigation.ShipServiceLevel == null)
                    {
                        <p>@item.CreateDate</p>

                    }
                    else if (item.OrderNavigation.ShipServiceLevel == "Econ US Dom")
                    {
                        <p>@item.OrderNavigation.ShipServiceLevel | @item.CreateDate</p>
                    }
                    else
                    {
                        <b style="text-align:center;">@item.OrderNavigation.ShipServiceLevel | @item.CreateDate</b>
                    }


                </div>

                @*            <b class="text-center" style="text-align:center;font-size:80%;"> Quantity: @ViewBag.itemdet[i].Payload.OrderItems[0].QuantityOrdered</b>
    *@
                <!-- Generate barcode for OrderId -->
                <canvas id="[email protected]" style="width:90%;"></canvas>

                <script>
                    // Function to generate barcode for each OrderId and trigger print
                    function generateBarcodeAndPrint(id, orderId) {
                        JsBarcode("#barcodeCanvas-" + id, orderId, { format: "CODE128" });

                        // Wait for the barcode to be fully generated
                        //setTimeout(function () {
                        //    window.print();
                        //}, 500); // Adjust the delay as needed
                    }
                </script>
            </div>
            <hr>
            <div class="col-12">
                <p>@item.OrderNavigation.Address</p>
            </div>
            @foreach (var ittem in orders)
            {
                <hr>
                <div class="col-12">
                    <p style="text-align:center;">Quantity</p>
                    <div style="border: 2px solid #000; width: fit-content; padding: 10px; text-align: center; margin: auto;">
                        <h3> @ittem.OrderNavigation.Quantity</h3>

                    </div>
                    <hr>
                    <div class="col-12">
                        <b class="text-center" style="text-align:center;">@ittem.OrderNavigation.Title</b>
                    </div>
                    <hr>
                    <div class="col-12">
                        <b class="text-center" style="text-align:center;">SKU: @ittem.OrderNavigation.Sku</b>
                    </div>
                    <hr>
                    <div class="col-12">
                        <b class="text-center" style="text-align:center;">Label Count: @item.TotalCount</b>
                    </div>
                </div>
            }

            page++;


            i++;
        }
        else
        {
            j++;
            @*            cnt++;
*@                  }
    }





}


<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>

@*<script>
$(document).ready(function() {
    alert('@ViewBag.count label will be printed.');
});

</script>*@

Module Parse Failed when using pdfjs-dist with Electron + Vue

When I import pdfjs-dist in my Electron Vue project, I get the following error:

error in ./node_modules/pdfjs-dist/build/pdf.js

Module parse failed: Unexpected character ‘#’ (1413:9) You may need an
appropriate loader to handle this file type, currently no loaders are
configured to process this file. See
https://webpack.js.org/concepts#loaders | | class
PDFDocumentLoadingTask {

static #docId = 0; | | constructor() {

Similar questions have suggested modifying webpack. I’m working off a clone of this project, which doesn’t have a webpack config, but does have a very simple babel.config.js.

The offending line is
import * as pdf from 'pdfjs-dist';

Node.js abort controller on pipeline behaves differently

These two code snippets work differently. I provided the signal of the abort controller to the pipeline and aborted the pipeline after 5 seconds the program starts.

First code snippet:

const { Readable } = require('stream');
const { pipeline } = require('stream/promises');

async function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function main() {
  console.log(`${process.version}`);

  const ac = new AbortController();

  setTimeout(() => {
    console.log("Abort!");

    ac.abort();
  }, 1000 * 5);

  try {
    await pipeline(
      Readable.from((async function* () {
        for (let i = 0; i < 10; i++) {
          console.log(`Emit ${i}`);
          yield `${i}`;
          await sleep(1000);
        }
      })()),
      async function* (iter) {
        for await (const value of iter) {
          console.log(`Transform ${value}`);
          yield `${value}${value}`;
        }
      },
      async function* (iter) {
        for await (const value of iter) {
          console.log(`Read ${value}`);
        }
      },
      {
        signal: ac.signal,
      }
    );
  } catch (err) {
    console.error("Aborted");
  }
}
main()
  .then(() => {
    console.log("Program ended");
    process.exit(0);
  })
  .catch((err) => {
    console.error(err);
    process.exit(1);
  });

Output:

v16.20.2
Emit 0
Transform 0
Read 00
Emit 1
Transform 1
Read 11
Emit 2
Transform 2
Read 22
Emit 3
Transform 3
Read 33
Emit 4
Transform 4
Read 44
Abort!
Emit 5
Aborted
Program ended

Second code snippet:

const { Readable, Transform } = require('stream');
const { pipeline } = require('stream/promises');

async function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function main() {
  console.log(`${process.version}`);

  const ac = new AbortController();

  setTimeout(() => {
    console.log("Abort!");

    ac.abort();
  }, 1000 * 5);

  try {
    await pipeline(
      Readable.from((async function* () {
        for (let i = 0; i < 10; i++) {
          console.log(`Emit ${i}`);
          yield `${i}`;
          await sleep(1000);
        }
      })()),
      Transform.from(
        async function* (iter) {
          for await (const value of iter) {
            console.log(`Transform ${value}`);
            yield `${value}${value}`;
          }
        },
      ),
      async function* (iter) {
        for await (const value of iter) {
          console.log(`Read ${value}`);
        }
      },
      {
        signal: ac.signal,
      }
    );
  } catch (err) {
    console.error("Aborted");
  }
}
main()
  .then(() => {
    console.log("Program ended");
    process.exit(0);
  })
  .catch((err) => {
    console.error(err);
    process.exit(1);
  });

Output:

v16.20.2
Emit 0
Transform 0
Read 00
Emit 1
Transform 1
Read 11
Emit 2
Transform 2
Read 22
Emit 3
Transform 3
Read 33
Emit 4
Transform 4
Read 44
Abort!
Emit 5

The only difference is how the transformation stream is made. First code snippet uses an async generator function and second code uses an async generator function wrapped using Transform.from utility function.

Second code snippet seems that the program exited abnormally because the try-catch block did not work.

Is it a bug or an expected behavior?

Beginner here. Doing an exercise on objects using javascript and I am stuck on this problem even though I feel like my code makes sense

enter image description hereThe exercise is basically asking me to build upon a function which sorts out items in any given ‘kitchen’ object, appropriately. If there are any string values with jumbled up letters, I should make them all lowercase. If there are any properties called shelvesInCupBoards or shelvesNotInCupboards, I should add a new property called ‘totalShelves’ and the value should be the sum of the previous two mentioned. And I should also delete shelvesInCupboards and shelvesNotinCupboards in this case. finally, if there is a ‘hoover’ property, that should be deleted as well.

enter image description hereMy code was a mixture of for loops and if and else statements. I feel like I’ve used the proper syntax throughout according to VS anyway but it still doesn’t work. I think the problem is tied to the ‘hoover’ section of my code and also the very last } bracket. without the hoover code, my bootcamp’s console says: ‘Illegal return statement’. With the hoover code it says: ‘SyntaxError: Delete of an unqualified identifier in strict mode’. Any help or explanations for what I’m doing wrong? and any more efficient ways to write out this code?

How do I pass arguments to a globally registered plugin in ng2-charts (alternativelly, how do I register it locally)?

I have the following problem with ng2-charts (version 4.1.1, chart.js being version 4.4.0): I made a plugin to color different parts of a line chart according to some threshold values. I got help from this question for the plugin implementation. The thresholds are passed as input variables to the component which contains the chart. I need to instantiate multiple charts at the same time (imagine them on a dashboard, in a sort of grid layout), having different thresholds for each of them.

The problem is that, since the plugin I made is registered globally within Chart.js, it seems that the threshold values it gets are the ones passed first, for all the charts, even if I’m using this to refer to the instance variables of the class (and those do get updated). E.g., I have two charts, the first receives minThreshold: 10, maxThreshold: 20, the second minThreshold: 20, maxThreshold: 40, but the plugin considers 10 and 20 for both.

Just to explain a little bit the code, updateDataPointsColor is responsible of coloring the points laying on the linechart. I’m also using the annotation plugin to render a dashed horizontal line to represent the thresholds and, by the way, the interesting thing is that, though the latter plugin is registered globally, it is able to obtain dynamically the values of the thresholds as I update them in the options object. I’d like to do the same with my plugin or, alternatively (if it makes sense), register it locally (but I couldn’t seem to make it work).
Does anybody have any suggestions or idea about how to solve the issue?

Here’s my code:

import { ChangeDetectorRef, Component, Input, OnChanges, Output, SimpleChanges, ViewChild } from '@angular/core';
import { Chart, ChartDataset, ChartOptions, ChartType } from 'chart.js';
import { BaseChartDirective } from 'ng2-charts';
import { Subject } from 'rxjs';
import annotationPlugin from 'chartjs-plugin-annotation';


@Component({
  selector: 'chart',
  templateUrl: './chart.component.html',
  styleUrls: ['./chart.component.css']
})
export class ChartComponent implements OnChanges {

  @Input()
  get data(): any[] { return this._data; }
  set data(data: any[]) {
    this._data = data;
    this.updateDataPointsColor();
    this.updateChart();
  }
  private _data!: any[];

  @Input()
  get yAxes(): any { return this._yAxes; }
  set yAxes(yAxes: any) {
    this._yAxes = yAxes;
    this.lineChartOptions.scales['y'] = this._yAxes;
    this.updateDataPointsColor();
    this.updateChart();
  }
  private _yAxes: any;

  @Input()
  maxThreshold: number = undefined;

  @Input()
  minThreshold: number = undefined;

  @Output() onCloseChartsDashlet: Subject<void> = new Subject<void>();
  display: boolean = true;
  destroyed: Subject<boolean> = new Subject();

  @ViewChild(BaseChartDirective) chart!: BaseChartDirective;

  // contains _data array
  public lineChartData: ChartDataset[];

  public lineChartLabels: any[];

  public lineChartOptions: ChartOptions = {
    animation: false,
    responsive: true,
    maintainAspectRatio: false,
    scales: {
      x: {
        display: false,
        title: {
          display: false,
          text: 'Time',
          font: {
            weight: 'bold',
            size: 14
          }
        },
        ticks: {
          display: true,
          padding: 10
        },
        grid: {
          color: "rgba(0, 0, 0, 0)"
        }
      }
    },
    datasets: {
      line: {
        backgroundColor: 'rgba(255, 0, 0, 0.3)',
        borderColor: 'rgba(31, 119, 180, 1)',
        pointBackgroundColor: 'rgba(31, 119, 180, 1)',
        pointBorderColor: '#fff',
        pointHoverBackgroundColor: '#fff',
        pointHoverBorderColor: 'rgba(31, 119, 180, 1)',
        tension: 0.1
      },
    },
    plugins: {
      annotation: {
        annotations: [
          {
            display: this.minThreshold ? true : false,
            type: 'line',
            id: 'minThreshold',
            scaleID: 'y',
            value: this.minThreshold,
            borderColor: 'red',
            borderDash: [5, 5],
            borderWidth: 0.5,
            drawTime: 'afterDatasetsDraw'
          },
          {
            display: this.maxThreshold ? true : false,
            type: 'line',
            id: 'maxThreshold',
            scaleID: 'y',
            value: this.maxThreshold,
            borderColor: 'red',
            borderDash: [5, 5],
            borderWidth: 0.5,
            drawTime: 'afterDatasetsDraw'
           },          
        ]
      }
    }
  };

  public lineChartLegend = false;
  public lineChartType: ChartType = 'line';

  public chartName = null;


  constructor(private cdRef: ChangeDetectorRef) {
    Chart.register(annotationPlugin);
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.minThreshold ||
        changes.maxThreshold) {

      if (changes.minThreshold) {
        this.lineChartOptions.plugins.annotation.annotations[0].value = this.minThreshold;
        this.lineChartOptions.plugins.annotation.annotations[0].display = this.minThreshold ? true : false;
      } else {
        this.lineChartOptions.plugins.annotation.annotations[1].value = this.maxThreshold;
        this.lineChartOptions.plugins.annotation.annotations[1].display = this.maxThreshold ? true : false;
      }

      if (this.minThreshold !== undefined ||
          this.maxThreshold !== undefined) {
        this.registerPlugins();
        this.updateDataPointsColor();
        this.updateChart();
      }
    }
  }

  ngOnDestroy(): void {
    //console.log("chart destroyed");
  }


  /**
   * Set data labels
   */
  private setLabels() {
    // do something
  }

  /**
   * Update chart with new data
   */
  updateChart() {

    this.lineChartData = [{
      data: this._data.map(el => {
        return {
          x: el.timestamp,
          y: el.value
        }
      }),
      fill: false
    }];
    this.setLabels();
    this.chart?.update();
  }

  /**
   * Change some data points color upon a condition
   */
  updateDataPointsColor() {

    let dataColors = this.lineChartOptions.datasets.line;
    let colorsArray: any = [];
    for (const dataPoint of this.data) {
      let color = 'rgba(31, 119, 180, 1)';
      if (dataPoint.value >= this.maxThreshold ||
          dataPoint.value <= this.minThreshold) {
        color = 'red';
      }
      colorsArray.push(color);
    }
    dataColors.pointBackgroundColor = colorsArray;
    dataColors.pointHoverBorderColor = colorsArray;
  }

  private registerPlugins() {
    Chart.register(
      {
        id: "color-by-min-max-thresholds",
        afterLayout: chart => {
          if (!this.maxThreshold || !this.minThreshold) {
            return;
          }
          let ctx = chart.ctx;
          ctx.save();
          let yAxis = chart.scales["y"];
          let yThresholdMax = this.maxThreshold ? yAxis.getPixelForValue(this.maxThreshold) : undefined;
          let yThresholdMin = this.minThreshold ? yAxis.getPixelForValue(this.minThreshold) : undefined;

          let offsetMax = yThresholdMax ? (yThresholdMax - yAxis.top) / (yAxis.bottom - yAxis.top) : 0;
          let offsetMin = yThresholdMin ? (yThresholdMin - yAxis.top) / (yAxis.bottom - yAxis.top) : 1;
      
          if (offsetMax < 0) {
            offsetMax = 0;
          } else if (offsetMax > 1) {
            offsetMax = 1;
          }

          if (offsetMin < 0) {
            offsetMin = 0;
          } else if (offsetMin > 1) {
            offsetMin = 1;
          }

          let gradient = ctx.createLinearGradient(0, yAxis.top, 0, yAxis.bottom);
          gradient.addColorStop(0, 'red');
          gradient.addColorStop(offsetMax, 'red');
          gradient.addColorStop(offsetMax, 'rgba(31, 119, 180, 1)');
          gradient.addColorStop(offsetMin, 'rgba(31, 119, 180, 1)');
          gradient.addColorStop(offsetMin, 'red');
          gradient.addColorStop(1, 'red');
          chart.data.datasets[0].borderColor = gradient;
          ctx.restore();
        }
      }
    );
  }

}

Another thing I didn’t understand is that I was “forced” to use the OnChanges hook to call registerPlugins because, otherwise, the values of the thresholds would be undefined (I tried registering the plugin both in ngOnInit and ngAfterViewInit, but with no success; in the hooks the values were set, but in the plugin function they were undefined).

Refused to connect to ‘http://localhost:3001/user/signup’ because it violates the document’s Content Security Policy using React and Node Js

I am creating a signup page using React and for my Backend I am using Node JS. When I am trying to call my signup api of Backend I am getting the following error
api.js:31 Refused to connect to ‘http://localhost:3001/user/signup’ because it violates the document’s Content Security Policy.
I am using the following sample function just to firstly connect to the backend api and then I will integrate the real form data.

export const postAPIWithoutHeader = async () => {
    console.log("postAPIWithoutHeader")
    console.log(body)
  try {
    var myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/json");

     var raw = JSON.stringify({
    "name": "some",
    "email": "[email protected]",
    "password": "Password234@",
    "role": "1",
    "require_servie": true
    });

    var requestOptions = {
    method: 'POST',
    headers: myHeaders,
    body: raw,
    redirect: 'follow'
    };

    let res = fetch("http://localhost:3001/user/signup", requestOptions)
      .then(response => response.text())
      .then(result => console.log(result))
      .catch(error => console.log('error', error));
    
    // console.log(reqBod)
    console.log("res",res)
    return res.data
  } catch (err) {

    console.log("the error we get is ",err);
    return err
  }
}

on my node backend I have allowed the cors using the following code in my app.js of backend

const corsOptions ={
    origin:['http://localhost:3000','http://localhost:3003'], 
    credentials:true,
    methods:"POST, GET, OPTIONS",
    optionSuccessStatus:200
};


app.use(cors(corsOptions))
app.options('*', cors(corsOptions));

I have tested the ap using postman and it works ok with the same URL.
Any help would be really appreciated

I was expecting to get the response from backend api.

How to create code block for a text editor

I’m trying to add a new feature to my note app witch is to add a code block.

This code block is actually a div tag with a classname that I will use, to style it and it will have the contenteditable="true".

There are two problems

First : when I press Enter, because of the contenteditable thing it creates a new div tag for me instead of moving to next line.

Second : I do not have a proper way of finding the position of i-coursor, my text is inside a p tag, not an input or textarea ( because I want to have HTML elements in my note ) so selectionStart and selectionEnd are not an option.

Please offer me a solution for finding i-coursor position as well as preventing default behavior of pressing Enter.

Look at this image to understand what I want better

Copy hyperlinks from one column to another in google sheets

Please help me with the script I want to run automated to copy hyperlinks from one column to other except from first row in google sheets.

function copyHyperlinks() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('1 απαντήσεις φόρμας');
  const sourceRange = sheet.getRange('U:U'); // Replace 'A:A' with your source column
  const targetRange = sheet.getRange('T:T'); // Replace 'B:B' with your target column
  const values = sourceRange.getValues();

  for (let i = 1; i < values.length; i++) { // Start loop from row 2 (index 1)
    const link = values[i][0].getLinkUrl();
    if (link) {
      targetRange.getCell(i + 1, 1).setHyperlink(link, values[i][0]);
    }
  }
}

Thank you very much.

AWS S3 upload file as guest using cognito and aws sdk in js gets CORS issue

enter image description hereI am trying to use the steps mentioned in the website to upload an image to AWS s3 using amazon js sdk and cognito identity pool.

https://accreditly.io/articles/uploading-files-directly-to-aws-s3-from-an-html-form-securely

I am facing CORS issue while hitting file upload button from my browser.

Access to XMLHttpRequest at 'https://web-customize-v1.s3.ap-south-1.amazonaws.com/web-customize-v1/sofiaimg-png.png' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

PUT https://web-customize-v1.s3.ap-south-1.amazonaws.com/web-customize-v1/sofiaimg-png.png net::ERR_FAILED  aws-sdk-2.813.0.min.js:79

I am not sure how to add Access-Control-Allow-Origin: *
in my AWS server as using only S3 and congito identity pool.

Running of Microsoft edge browser

Can any one help?

Run a script that checks for SQL Server changes that returns a boolean value

I already plan on doing this differently with webhooks, but for now I just need to show a PoC for this where the browser client will check on intervals if there’s any changes to an SQL Server database and return a boolean value if it detects a change, where then my client side script will refresh the page if the bool value is true.

<script>
$(document).ready(function () {
        function refreshPage() {
            window.location.href = data.rtnurl;
        }
        setInterval(function () {
            $.ajax({
                url: 'testscript', //script to check data base update
                type: 'GET',
                success: function (data) {
                    if (data === 'true') {
                        refreshPage();
                        alert("New data was added.");
                    }
                }
            });
        }, 30000);
});
</script>

Here’s what I have right now, and was wondering how I would be able to use the URL to run a script to check for SQL Server updates.

Matching different objects with id field in different array map

I want to map X array and return a component. The component has a string prop but not in the same array. I want to find every object Y array who match with X.id

const X = [
{
id: 1,
symbolId: 2,
},
{
id: 2,
symbolId: 3,
},
{
id: 3,
symbolId: 3,
},
{
id: 3,
symbolId: 2,
},
]
const Y = [
{
id: 1,
symbol: "USD",
name: "Dollar",
},
{
id: 2,
symbol: "EUR",
name: "Euro"
},
{
id: 3,
symbol: "GLD",
name: "Gold"
}
]

I have this 2 array. I want to map X and find Y object with symbolID.

X.map((a)=> {
return (
<Text>{Y.find((b) => b.id === a.symbolId).name}</Text>
)
})

What I Expected is ;

<Text>Dollar</Text>
<Text>Gold</Text>
<Text>Gold</Text>
<Text>Dollar</Text>

But find method just control first object and return undefined for others. Is there any different method for this?

How can I dynamically change the items in my map without creating a new key?

I have the following sandbox

import "./styles.css";
import { useEffect, useState } from "react";

export default function App() {
  interface filter {
    company: boolean;
    gender: boolean;
  }
  const [people, setPeople] = useState<filter>({
    company: false,
    gender: false,
  });

    useEffect(() => {
    console.log(people);
  }, [people]);


  const toggleMenu = (menuItem: keyof typeof people) => {
    setPeople({ ...people, menuItem: !people[menuItem] });
  };


  return (
    <div className="App">
                    <button
                className="flex flex-row justify-center w-full"
                onClick={() => toggleMenu("company")}
              >
Click me 
</button>
    </div>
  );
}

The toggleMenu function doesn’t seem to work correctly. The idea is to pass an arbitrary key (e.g. “company”) and have it toggle the value. Instead, I get the following output:

{company: false, gender: false, menuItem: true}

WHereas I want:

{company: true, gender: false}

I tried the code above but didn’t expect to see a new key created in my map…just need to update the existing key.

Why is Chrome iOS sending prompt when geolocation is granted

I want to allow geolocation in some sections of my website, to do so I prefer to ask for permission on the client page before prompting them with the browser geolocation permission request.

So I gather the response.state with something like the following…

navigator.permissions.query({ name: "geolocation" }).then((response) => {
  // do stuff with response.state
});

And then if the state is prompt I’ll just render another page asking them nicely to allow geolocation by clicking on a button. This button triggers this code

navigator.geolocation.getCurrentPosition(
  (position) => {
    if (position) {
      // location was granted for sure, we do stuff
    }
  },
  () => {
    // this means the client didn't accept geolocation
  }
);

It works perfectly on my computer, in all browsers. However, when refreshing the page on Chrome iOS after allowing geolocation, it’s still on prompt when the state should be granted; I can actually get the exact position despite the state being prompt which makes very little sense to me.

What’s going here with Chrome iOS? Is there a workaround? The behavior is different but I can’t pinpoint why, and can’t find documentation about it. This improved UX is essential. I could just prompt it and ask for the best but I want the client to approve first.

How to pass and display image data when navigating between pages in a React application?

I’m currently working on a React application where I have a profile page displaying posts, each containing an image. I want to implement functionality where clicking on a post navigates the user to a separate page displaying the full post details, including the image.

I’ve set up routing using React Router, and I’m able to navigate between pages successfully. However, I’m struggling to pass the image data from the profile page to the post page so that the same image is displayed.

Here’s what I’ve tried:

Created a ProfilePost component to display each post on the profile page.
Used the Link component from React Router to navigate to the post page when a post is clicked.
Passed the image data as a prop to the post page component (PostPageImg).
However, on the post page, the image data is not being displayed correctly.
Here’s a simplified v“ersion of my components:
//ProfilePost component from ProfilePage

   <Link to="/postpage">
      <GridItem
        cursor={"pointer"}
        borderRadius={4}
        overflow={"hidden"}
        border={"1px solid #dbdbdb"}
        borderColor={"whiteAlpha.300"}
        position={"relative"}
        aspectRatio={1 / 1}
      >
        <Flex
          opacity={0}
          _hover={{ opacity: 1 }}
          position={"absolute"}
          top={0}
          left={0}
          right={0}
          bottom={0}
          bg={"blackAlpha.400"}
          transition={"all 0.3s ease"}
          zIndex={1}
          justifyContent={"center"}
        ></Flex>
        <Image src={img} alt="profile post" w={"100%"} h={"100%"} objectFit={"cover"} />
        {/*<PostPageImg img={img} />*/}
      </GridItem>
    </Link>

//PostPageImg component from PostPage

import { Box, Image } from '@chakra-ui/react';
import React from 'react';

const PostPageImg = ({ img }) => {
  return (
    <Box>
      <Image src={img} alt="profile post" w="100%" h="100%" objectFit="cover" />
    </Box>
  );
};

export default PostPageImg;

and my images are coming from here:

<>
          <ProfilePost img="/img1.jpeg" />
          <ProfilePost img="/img2.jpeg" />
          <ProfilePost img="/img3.jpeg" />
          <ProfilePost img="/img1.jpeg" />
          <ProfilePost img="/img5.jpeg" />
          <ProfilePost img="/img5.jpeg" />
        </>```


I'm unsure why the image data isn't being passed correctly to the post page component. How can I ensure that the same image is displayed on the post page as the one clicked on the profile page?  

Any help or insights would be greatly appreciated. Thank you!