Pass Local Files or Remote Video Files with React js through API response

Here is my response i got from database

enter image description here

from above shown images i assigned video path to Video_Name. is that correct way to pass local video files ???

if answer is no then how to pass local video file path to database after that how i access local file system in react js through api response

import FormDialog from "./dialog";
const initialValue = { Name: "", Floor: "", Group: "", Camera: "", Videos: "" };

function App() {
  const actionButton = (params) => {
    setOpen(true);
  };

  const [open, setOpen] = React.useState(false);
  const [formData, setFormData] = useState(initialValue);
  const handleClose = () => {
    setOpen(false);
    setFormData(initialValue);
  };

  const onChange = (e) => {
    const { value, id } = e.target;
    // console.log(value,id)
    setFormData({ ...formData, [id]: value });
  };

  const columnDefs = [
    { headerName: "Name", field: "Company_Name", filter: "agSetColumnFilter" },
    { headerName: "Floor", field: "Floor Number" },
    { headerName: "Group", field: "Group_Name" },
    { headerName: "Camera", field: "Camera_Number" },
    { headerName: "Videos", field: "Video_Name" },
    {
      headerName: "Actions",
      field: "dob",
      cellRendererFramework: (params) => (
        <div>
          <Button
            variant="contained"
            size="medium"
            color="primary"
            onClick={() => actionButton(params)}
          >
            Play
          </Button>
        </div>
      ),
    },
  ];

  const onGridReady = (params) => {
    console.log("grid is ready");
    fetch("http://localhost:8000/get_all")
      .then((resp) => resp.json())
      .then((resp) => {
        localStorage.setItem("apidata", JSON.stringify(resp.results));
        console.log(resp.results);
        params.api.applyTransaction({ add: resp.results });
      });
  };

i used this code to pass local video file directly like import video from "./video1.mp4" like How to pass local video file through api response instead of this

enter image description here

How pass local video files to react ag-grid. pass video to play button

for more code detail Click here

If statement to make a button appear/disappear based on the results of game

I have 1v1 browser games on my website & I’m trying to make a button show up for the winner & not show up for the loser on a pop-up modal in the post-game. I’m specifically targeting the “Claim Prize” button on the pop-up” Pop-up Modal “Claim Prize”

HTML for the Button:

  <button class="button button--secondary button--small modal__button"
  data-button="claim">
  Claim Prize
</button>

Js used to define the winner.

function endGame() {
  if(!isGameOver) return;
  let text;
  if(scores.player > scores.opponent) 
    text = TEXTS.win;
  else if(scores.player < scores.opponent)
    text = TEXTS.lose;
  else
    text = TEXTS.draw;
  
  text += `<br> Scores: ${scores.player} - ${scores.opponent}`;

  showEndScreen(text);

Current if statement to attempt to make it show only for the winner:

<script>
  var theyLost = (TEXTS.Win)
  if (theyLost) true;
  document.getElementById("claim").style.display="none";
</script>

supercluster: get all markers in a cluster

I’m using superclsuter for clustering markers in react native map, what I want is to get all children from a cluster no matter what level of nesting a cluster may have.

to explain the situation a little better, a cluster can have markers and other clusters as children, I need to flatten the child clusters to get markers inside them.

cluster
  marker
  cluster(3 markers)

// this should return the 4 markers, the top-level marker, and markers within the child cluster

Calling an event from socket.io

I’m trying to call an event, but an error occurs: UnhandledPromiseRejectionWar
ning: TypeError: Cannot read property ’emit’ of undefined
How it is possible to bypass it? nodejs

import { io } from 'socket.io-client';
import { EventEmitter2, OnEvent } from '@nestjs/event-emitter';

import { SynchronizeService } from './synchronize.service';
import { UserService } from '../user/user.service';

const serverAddress = 'http://localhost:3050'
const socket = io(serverAddress, { reconnection: true })

export class SocketClient {
constructor(
private readonly synchronizeService: SynchronizeService,
private eventEmitter: EventEmitter2,
private readonly userService: UserService
) {}

@OnEvent('order.created')
async handler(req):Promise<void> {
 try{
   socket.on('synchronize', () => {
   });
   socket.on('send_from_server', async ({ msg }) => {
     await this.eventEmitter.emitAsync('order.came')
   });
  socket.emit('synchronize', req);
} catch (e) {
  console.log(e);
}
}

}

How to add custom colors to the line chart created using Angular

I have created line chart using Fushionchart in Angular with API data. I have method to add custom color to the chart but it doesn’t work. Here I have provide full code to figure the flow. Function pass two parameters and need to set to the label of chart.FYI: *getColorCode() is located in dashboard.service.ts(in below). Here’s the full code.

/* dashboard.component.html */

  <div *ngIf="multipleConsump" class="chart-card-body p-3">
       <app-consumption-summery-chart></app-consumption-summery-chart>
     </div>

/* dashboard.component.ts */

 getConsumptionData(): void {
    this.typeChart.reset();

    if (this.trendLogTabIndex == 0 || this.trendLogTabIndex == 1) {
      this.tempIntervalid = 2;
    } else if (this.trendLogTabIndex == 2) {
      this.tempIntervalid = 3;
    } else if (this.trendLogTabIndex == 3) {
      this.tempIntervalid = 4;
    }

    this.ltDashboardService
      .getCategoryTrends(
        this.buildingId,
        this.tempIntervalid,
        this.intervalTime.from,
        this.intervalTime.to,
      )
      .subscribe(
        (res: Object[]) => {
          if (res.length) {
            const labels = res[0]["data"].map((x) => x.label);
           
            const values = res
              .filter((x: any) => this.selectedTypes.indexOf(x.itemId) > -1)
              .map((x: any) => {
                return {
                  seriesname: x.name,
                  data: x.data.map((d) => {
                    return {
                      value: d.value,
                    };
                  }),
                };
              });

            this.typeChart.setData(labels, values);
          }
        },
        (err) => console.log("Err")
      );
  }

/* dashboard.service.ts */

    getCategoryTrends(building: number, interval: intervalGroup, from:Date, to:Date): Observable<any> {
  
  return this.dataService.get(this.config.endPoints['building-type-consumption-group'], {
    startDate: from,
    endDate: to,
    groupId: GroupBy.MeterType,
    serviceTypeId: ServiceType.ELECTRICAL,
    buildingId: building,
    interval: interval,
    siteId: this.config.siteConfigurations.siteId,
    dataMode: DataMode.CategorySum,    
  })

}

/* Get color code function (meter type is ChartGroupType.METER_TYPES for above function ) */

/*

Get color code
*/

private getColorCode(chartGroupType: ChartGroupType, itemId: number) {
  let item;
  let color;
  switch(chartGroupType) {
    case ChartGroupType.METER:
      return '';
    case ChartGroupType.BUILDING_CATEGORY:
      item = find(this.initialService.navigationStore.buildingCategories, {buildingCategoryID: itemId});
      return this.getDefaultColorCode(item);
    case ChartGroupType.METER_TYPES:
      item = find(this.initialService.navigationStore.meterTypes, {meterTypeID: itemId});
      return this.getDefaultColorCode(item);
    case ChartGroupType.HT_LOOPS:
      return '';
  }
}

private getDefaultColorCode(item) {
  let color;
  if(item === undefined || item.attributes.length === 0) {
    return this.config.config.defaultColorCode;
  } else {
    color = find(
      item.attributes, 
      {
        textId: this.config.config.attributes.COLOR_CODE
      });
      console.log(item + 'chart colors are: ')
    return color===null || color === undefined?this.config.config.defaultColorCode:color.value;
  }
}

How to convert JavaScript function into React Typescript function? [closed]

So, im working on Google Maps API and I first created it using Javascript function, but now i wanted to convert it into React.

Here is my Javascript code:

function addPlaces(places, map) {
  const placesList = document.getElementById("places");

  for (const place of places) {
    if (place.geometry && place.geometry.location) {
      const image = {
        url: place.icon,
        size: new google.maps.Size(71, 71),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(17, 34),
        scaledSize: new google.maps.Size(25, 25),
      };

      const m = new google.maps.Marker({
        map,
        draggable: false,
        icon: image,
        // animation: google.maps.Animation.BOUNCE,
        title: place.name,
        position: place.geometry.location,
        opacity: 0.5,
      });
      markerPool[place.name] = m;

      const li = document.createElement("li");

      li.textContent = place.name;
      placesList.appendChild(li);
      li.addEventListener("click", () => {
        const m = markerPool[li.textContent];
        m.setOpacity(1);
        map.setCenter(place.geometry.location);
      });
    }
  }
}

So how can i convert all these function into React typescript?

AJAX fails to get data from input

I am trying to create/insert data into the database, but I am still getting an error for getting the data I’ve input. I tried using the dump and die method, and I encountered that no data is being gotten from the data that has been input. What could be wrong with my codes?

Here is the result of the inspected element

Click to see image

My Modal

<div id="modalAddChild" class="modal fade" tabindex="-1" aria-labelledby="modalAddChild">
    @csrf_field
    {{ method_field('PUT') }}
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title"><b>Add Child</b></h4>
                <button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">X</button>
            </div>
            <div class="modal-body">
                <p><i>Note: In Weight, it is required to put (.) regardless if it is (.0).</i></p>
                <p><i>Note: In Height, do not add (.) if it is (.0) but it is allowed to put (.) if it's any number.</i>
                </p>
                <form id="saveChild" method="post">
                    <div class="form-group row">
                        <div class="col-sm-6">
                            <label for="mothersname">Mother's Name:</label>
                            <input type="text" class="form-control" id="mothersname" name="mothersname" required>
                        </div>
                        <div class="col-sm-6">
                            <label for="childsname">Child's Name:</label>
                            <input type="text" class="form-control" id="childsname" name="childsname" required>
                        </div>
                    </div>

                    <div class="form-group row">
                        <div class="col-sm-6">
                            <label>Indigenous:</label>
                            <select class="form-control" id="ind_id" name="ind_id" required>
                                <option value="">YES or NO</option>
                                @foreach ($indigenous as $key => $value)
                                <option id="{{ $key }}" value="{{ $key }}">{{ $value }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-sm-6">
                            <label>Sex:</label>
                            <select class="form-control" id="sex_id" name="sex_id" required>
                                <option value="">M or F</option>
                                @foreach ($sex as $key => $value)
                                <option id="{{ $key }}" value="{{ $key }}">{{ $value }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>

                    <div class="form-group row">
                        <div class="col-sm-6">
                            <label>Date of Birth:</label>
                            <input type="text" class="form-control" id="birthdate" name="birthdate"
                                placeholder="YYYY-MM-DD" required>
                        </div>
                        <div class="col-sm-6">
                            <label>Actual Date of Weighing:</label>
                            <input type="text" class="form-control" id="actualdate" name="actualdate"
                                placeholder="YYYY-MM-DD" required>
                        </div>
                    </div>

                    <div class="form-group row">
                        <div class="col-sm-6">
                            <label>Weight(kg):</label>
                            <input type="text" class="form-control" id="weight" name="weight" required>
                        </div>
                        <div class="col-sm-6">
                            <label>Height(cm):</label>
                            <input type="text" class="form-control" id="height" name="height" required>
                        </div>
                    </div>

                    <div class="form-group row">
                        <div class="col-sm-6">
                            <label for="zone">Zone:</label>
                            <input type="text" class="form-control" id="zone" name="zone" required>
                        </div>
                        <div class="col-sm-6">
                            <label>Age in Months:</label>
                            <input type="text" class="form-control" id="ageinmonths" name="ageinmonths" required>
                        </div>
                    </div>

                    <div class="form-group">
                        <button type="submit" value="Submit" class="btn btn-flat btn-primary" id="saveBtn">Submit</button>
                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

My AJAX

<script type="text/javascript">
    $('#saveChild').submit('click', function() {

        var zone = $('#zone').val();
        var mothersname = $('#mothersname').val();
        var childsname = $('#childsname').val();
        var ind_id = $('#ind_id').val();
        var sex_id = $('#sex_id').val();
        var birthdate = $('#birthdate').val();
        var actualdate = $('#actualdate').val();
        var weight = $('#weight').val();
        var height = $('#height').val();    
        var ageinmonths = $('#ageinmonths').val();
        var dataString="zone="+zone+"&mothersname="+mothersname+"&childsname="+childsname+"&ind_id="+ind_id+"&sex_id="+sex_id
        +"&birthdate="+birthdate+"&actualdate="+actualdate+"&weight="+weight+"&height="+height+"&ageinmonths="+ageinmonths;    

        $.ajax({
            type: "POST",
            dataType: "JSON",
            data: dataString,
            url: "insert_child",
            success: function(data) {
                console.log(data);
                if (data == "success"){
                    alert("Data successfully added!");
                } else if (data = "failed") {
                    alert("ERROR IN FETCHING DATA!");
                }
                displayData();
            }
        });
        return false;
    });

    $('#saveBtn').click(function() {
        $('#modalAddChild').modal('hide');
    });

    $('#modalAddChild').on('hidden.bs.modal', function(e) {
        $(this)
            .find("input,textarea,select")
            .val('')
            .end()
            .find("input[type=checkbox], input[type=radio]")
            .prop("checked", "")
            .end();
    })
</script>

JavaScript Class : Return a new instance of child class from base class (Kind of Mutual or Circular Relation)

Hello StackOverFlow, this is my first question.
Sorry if title is bad.

I wanted help related to Classes in JavaScript, I am pretty good at JavaScript but never encountered this kind of situation.

I have two files, in the first file :



/**
 *
 *    ParentClass
 *
 */
class  ParentClass  {

        constructor()  {

                let Second  =  new ChildClass();

        }

}


And in the second file :



/**
 *
 *
 *    ChildClass
 *
 *
 */
class  ChildClass  extends  ParentClass  {}


You can clearly see that I will get Error if I use that code. It was confusing for me because I never wrote this kind of code, it was some legacy code I picked up form Github.

I wrote a solution, it’s working but I don’t know if it’s a bad practice.

The solution :



/**
 *
 *    ParentClass
 *
 */
class  ParentClass  {

        constructor()  {

                const  ChildClass  =  import('~/class-child.ts');
                const  CurrentChildClass  =  new  ChildClass();

        }

}


I am trying to insert a div element into my page, but it does not appear. Any idea on how this can be fixed?

I am trying to implement this timeline that I have created on CodePen.io into my web page, but above all the other div elements. However, when I try to input the div above, all I get is a blank rectangle exactly where I would want the timeline to be. Is there a reason why it is coming back as blank and not with the javascript timeline that was made?

https://codepen.io/redking613/pen/QWQMOPZ

Picture of what website looks now & where I want the timeline to be

Picture of what my timeline looks like via CodePen.io

I appreciate any help that I can get! Thank you.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Milestone 3</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="w3.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>

  <img src="SANDYMC.png" alt="Sandy Shores MC" style="width: 450px;">

  <style>
    .column-left {
      float: left;
      width: 20%;
      height: 800px;
      text-align: center;
    }

    .column-right {
      float: right;
      width: 20%;
      height: 800px;
      text-align: center;
    }

    .column-center {
      display: inline-block;
      width: 60%;
      height: 800px;
      text-align: center;
    }

    table,
    th,
    td {
      border: 1px solid;
      margin-left: 100px;
    }

    body,
    html {
      font-family: arial, sans-serif;
      font-size: 11pt;
    }

    #visualization {
      box-sizing: border-box;
      width: 100%;
      height: 300px;
    }

    .vis-item.medications {
      background-color: #b0e2ff;
    }

    .vis-item.appointments {
      background-color: #eaeaea;
    }

    .vis-item.messages {
      background-color: #fa8072;
    }

    .vis-item.procedures {
      background-color: #b4eeb4;
    }

    .vis-item.testResults {
      background-color: #ffffcc;
    }

    .vis-item.hospitalAdmissions {
      background-color: #ffffcc;
    }
  </style>
</head>

<body>

  <h2>Patient Portal</h2>
  <div id="visualization"></div>

  <script>
    var groups = new vis.DataSet([
      { content: "Medications", id: "Medications", value: 1, className: "medicationClass" },
      { content: "Allergies", id: "Allergies", value: 2, classname: "allergiesClass" },
      { content: "Messages", id: "Messages", value: 3, className: "messagesClass" },
      { content: "Procedures", id: "Procedures", value: 4, classname: "proceduresClass" },
      { content: "Test Results", id: "testResults", value: 5, className: "testresultsClass" },
      { content: "Hospital Admissions", id: "hospitalAdmissions", value: 6, className: "hospitalClass" },
    ]);

    function showAllGroups() {
      groups.forEach(function (group) {
        groups.update({ id: group.id, visible: true });
      });
    }

    var items = new vis.DataSet([
      {
        start: new Date(2020, 05),
        group: "Medications",
        className: "medicationClass",
        content: "<h4 class='eventtitle'>Tylenol</h4>",
      },
      {
        start: new Date(2020, 05),
        group: "Allergies",
        classname: "allergiesClass",
        content: "<h4 class='eventtitle'>Allergy</h4>Type: Peanuts",
      },
      {
        start: new Date(2021, 01),
        group: "Messages",
        classname: "messagesClass",
        content: "<h4 class='eventtitle'>Message</h4>(1) Unread Message",
      },
      {
        start: new Date(2019, 09),
        group: "Allergies",
        classname: "allergiesClass",
        content: "<h4 class='eventtitle'>Allergy</h4>Type: Latex",
      },
      {
        start: new Date(2018, 07),
        group: "Procedures",
        className: "proceduresClass",
        content: "<h4 class='eventtitle'>Procedures</h4>Type: Knee Replacement",
      },
      {
        start: new Date(2015, 02),
        group: "testResults",
        className: "testresultsClass",
        content: "<h4 class='eventtitle'>Test Result</h4>Type: Lab Test",
      },
      {
        start: new Date(2016, 09),
        group: "hospitalAdmissions",
        className: "hospitalClass",
        content: "<h4 class='eventtitle'>Hospital Admission</h4>Patient scheduled for surgery",
      },

    ]);

    // create visualization
    var container = document.getElementById("visualization");
    var options = {
      groupOrder: function (a, b) {
        return a.value - b.value;
      },
      groupOrderSwap: function (a, b, groups) {
        var v = a.value;
        a.value = b.value;
        b.value = v;
      },
      groupTemplate: function (group) {
        var container = document.createElement("div");
        var label = document.createElement("span");
        label.innerHTML = group.content + " ";
        container.insertAdjacentElement("afterBegin", label);
        var hide = document.createElement("button");
        hide.innerHTML = "hide";
        hide.style.fontSize = "small";
        hide.addEventListener("click", function () {
          groups.update({ id: group.id, visible: false });
        });
        container.insertAdjacentElement("beforeEnd", hide);
        return container;
      },
      orientation: "both",
      editable: true,
      groupEditable: true,
      start: new Date(2012, 6),
      end: new Date(2022, 10),
    };

    var timeline = new vis.Timeline(container);
    timeline.setOptions(options);
    timeline.setGroups(groups);
    timeline.setItems(items);

  </script>

  <div class="container">

    <div class="column-left" style="background-color:#aaa;" height: 100%>
      <h2>Health Record</h2>
      <button class="w3-button w3-hover-black">Medications</button>
      <br>
      <br>
      <br>
      <br>
      <button class="w3-button w3-hover-black">Appointments</button>
      <br>
      <br>
      <br>
      <br>
      <button class="w3-button w3-hover-black">Messages</button>
      <br>
      <br>
      <br>
      <br>
      <button class="w3-button w3-hover-black">Procedures</button>
      <br>
      <br>
      <br>
      <br>
      <button class="w3-button w3-hover-black">Test Results</button>
      <br>
      <br>
      <br>
      <br>
      <button class="w3-button w3-hover-black">Hospital Admissions</button>
    </div>

    <div class="column-center w3-border" style="background-color:rgb(117, 114, 114)
            ;">
      <h2>Patient History</h2>
      <div class="w3-panel w3-border w3-border-black">
        <h3>Advil - Medications</h3>
        <strong>01/28/2022</strong>
        <p>Patient was prescribed advil to reduce migraines and reduce fever.</p>
      </div>

      <div class="w3-panel w3-border w3-border-black">
        <h3>Lastest Visit Summary - Appointments</h3>
        <strong>01/27/2022</strong>
        <p>Patient described issues consisting of migraines, high fevers, etc.
          <br>
          Prescription for advil was given to the patient.
          <br>
          Sore throat, runny nose symptoms
        </p>
      </div>

      <div class="w3-panel w3-border w3-border-black">
        <h3>Metal Knee Replacement - Procedures</h3>
        <strong>12/26/2021</strong>
        <p>Patient got a new Metal Knee.
        </p>
      </div>

      <div class="w3-panel w3-border w3-border-black">
        <h3>Adderall - Medications</h3>
        <strong>08/17/2021</strong>
        <p>Patient prescribed for adderall medication due to ADHD diagnosis.
        </p>
      </div>

    </div>
    <div class="column-right" style="background-color:#aaa;">

      <h2>Key Metrics</h2>
      <p>Height</p>
      <canvas id="linear" style="width:100%;max-width:600px"></canvas>

      <script>
        var xValues = [];
        var yValues = [];
        generateData("x * 2 + 7", 0, 10, 0.5);

        new Chart("linear", {
          type: "line",
          data: {
            labels: xValues,
            datasets: [{
              fill: false,
              pointRadius: 1,
              borderColor: "rgba(255,0,0,0.5)",
              data: yValues
            }]
          },
          options: {
            legend: { display: false },
            title: {
              display: true,
              text: "Patient Height Chart - (Lifespan)",
              fontSize: 16
            }
          }
        });
        function generateData(value, i1, i2, step = 1) {
          for (let x = i1; x <= i2; x += step) {
            yValues.push(eval(value));
            xValues.push(x);
          }
        }
      </script>

      <p>Weight Chart</p>
      <canvas id="myChart" style="width:100%;max-width:600px"></canvas>

      <script>
        var xValues = [50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150];
        var yValues = [7, 8, 8, 9, 9, 9, 10, 11, 14, 14, 15];


        new Chart("myChart", {
          type: "line",
          data: {
            labels: xValues,
            datasets: [{
              fill: false,
              lineTension: 0,
              backgroundColor: "rgba(0,0,255,1.0)",
              borderColor: "rgba(0,0,255,0.1)",
              data: yValues
            }]
          },
          options: {
            legend: { display: false },
            scales: {
              yAxes: [{ ticks: { min: 6, max: 16 } }],
            }
          }
        });
      </script>


      <h3>Allergies</h3>
      <p>Peanuts, Apple, Milk</p>

</html>

How to get user info from Google OAuth2

Google is mandating an upgrade to their authentication/authorization mechanism, deprecating their existing mechanism.

The entire “GoogleAuth” object and all methods is deprecated.

The migration guidelines provide old->new guidance and examples (many of which don’t work as described, but that’s another story).

The old GoogleAuth object had one particularly necessary method .getUserInfo().

The docs do not provide a migration path for most methods on this object, and not for this one. (The migration doc merely says “remove” with regard to this method.) None of the sample code in migration offer guidance for this.

There is a companion set of docs that describe a different code path, that seems not-entirely-compatible with the new Google Identity Service, and which suggests the user data is embedded in a JWT, but offers no guidance on how to decrypt that JWT.

My code for authenticating, authorizing, and accessing google’s api’s is more or less functional (still pops a dialog on every new page load, still working on that), but getting the user info has defeated me after scrutinizing every migration doc, code sample, and considerable searching.

Has anyone cracked this nut?

I am terribly afraid that the answer is so simple that I have spent a full day banging my head on my own stupidity.

I’m even more afraid it’s not possible!

React Router not showing in Chrome extension

In my React Chrome extension app, when using nested routes, routing is not working. I have the following code:

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Router } from 'react-router-dom';
import { createMemoryHistory } from 'history';
import 'bootstrap/dist/css/bootstrap.min.css';
import { AuthProvider } from './context/AuthProvider'
import App from './App';

const history = createMemoryHistory();

ReactDOM.render(
  <React.StrictMode>
    <AuthProvider>
      <Router history={history}>
        <App />
      </Router>
    </AuthProvider>
  </React.StrictMode>,
  document.getElementById('root')
);

In App.js, only <AppbarGuest /> is displaying in the Chrome extension. anything beyond that is not rendering.

App.js

import * as React from 'react';
import "@fontsource/roboto";
import "./App.css";
import { BrowserRouter, Router, Routes, Route } from "react-router-dom";

import Box from '@mui/material/Box';
import Vault from "./pages/vault";
import AddItem from "./pages/additem";
import Generator from "./pages/generator";
import Settings from "./pages/settings";
import EmptyVault from "./pages/emptyvault";
import TermsAndConditions from "./pages/terms";
import PrivacyPolicy from "./pages/privacy";
import VerifiedEmail from "./pages/verifiedemail";

import BottomNav from "./components/bottomnav";
import Appbar from "./components/appbar";
import AppbarGuest from './components/appbarguest';
import Sidebar from "./components/sidebar";
import Toolbar from '@mui/material/Toolbar';

import Login from "./components/forms/auth/login";
import Register from "./components/forms/auth/register";
import ForgotPassword from "./components/forms/auth/forgotpassword";
import ResetPassword from './components/forms/auth/resetpassword';

import RequireAuth from './components/requireauth';
import PersistLogin from './components/persistlogin';

import useAuth from './hooks/useAuth';

function App() {

  const { auth } = useAuth();

  return (
    <BrowserRouter>
      <div className="App">
        <Box sx={{ display: 'flex' }}>
            {auth?.accessToken ? <Appbar /> : <AppbarGuest />}
            {auth?.accessToken ? <Sidebar width={200} /> : <></>}
            <Box component="main" sx={{ flexGrow: 1, p: 4, mb: 7 }}>
            <Toolbar />
            <Routes>
                <Route path="/login" element={<Login />} />
                <Route path="/register" element={<Register />} />
                <Route path="/forgotpassword" element={<ForgotPassword />} />
                <Route path="/terms" element={<TermsAndConditions />} />
                <Route path="/privacy" element={<PrivacyPolicy />} />
                <Route path="/verifiedemail" element={<VerifiedEmail />} />
                <Route element={<PersistLogin />}>
                <Route element={<RequireAuth />}>
                    <Route path="/" element={<Vault />} />
                    <Route path="/additem" element={<AddItem />} />
                    <Route path="/generator" element={<Generator />} />
                    <Route path="/settings" element={<Settings />} />
                    <Route path="/reset" element={<ResetPassword />} />
                    <Route path="/emptyvault" element={<EmptyVault />} />
                </Route>
                </Route>
            </Routes>
            </Box>
        </Box>
        {auth?.accessToken ? <BottomNav /> : <></>}
      </div>
    </BrowserRouter>
  );
}

export default App;

Select closest focus targets on Browser or Windows

First time posting here. I’m working on a mouse-and-keyboard disability device for a course bioengineering course and I’ve got a feature that I’ve got no clue how to begin implementing. Basically, I want to be able to “select” which are the K “focus targets” nearest to the cursor, draw boxes around them/highlight them (much like Chrome or Windows does) and, after deciding which “target” I want to select, focus/click that one. The goal is to use eye-tracking software to move a cursor and then blink/contract a muscle to see which are the closest targets (that way you can click on really tiny stuff which would be hard to select otherwise).

Not sure if “focus target” is the right word, I mean “what gets selected next” after you press Tab. If there’s some “universal” way of doing this across apps that’d be great, but either a browser-only or Windows-only way would be great. The only workaround idea I’ve had so far is to press Tab a bunch of times, see what changes appear on screen, use OpenCV to detect on-screen changes and then see which are closest to the cursor, but that means the screen would spaz out and also wouldn’t work if there’s any sort of animation on the screen.

Thanks in advance!

Running php files from javascript on linux

Running php files from javascript on linux

I am running fetch as a way to run php files from javascript.
Specifically, the following code is executed

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>test</title>
  </head>
  <body>
    <form name="form" id="form">
      <input type="text" id="text">
      <button type="button" onclick="push()">push</button>
    </form>

    <script>
        async function push(){
          var form = document.form;
          console.log(form.text.value);
          await fetch('test.php?text='+ form.text.value)
          .then(res=> {return res.text();})
          .then(res => {
            console.log(res);
            var result = JSON.parse(res);
            console.log(result.result);
            console.log(result.msg);
          });
        }
    </script>
  </body>
</html>

<?php
    if(isset($_GET['text']) && $_GET['text']!=""){
        $token = $_GET['text'];
        $result = "OK";
        $msg = $_GET['text'];
    }else{
        $result = "NG";
        $msg = "message";
    }

    $result = json_encode(
        array(
            "result" => $result,
            "msg" => $msg,
        )
    );

    echo $result;
    return $result;
?>

This works fine on windows, but does not work on linux.
The entire php script is returned in console.log(res).
Do you know why?

The linux environment uses the following

OS:
Debian GNU/Linux 10 n l

PHP:
PHP 7.3.31-1~deb10u1 (cli) (built: Oct 24 2021 15:18:08) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.31, Copyright (c) 1998-2018 Zend Technologies
with Zend OPcache v7.3.31-1~deb10u1, Copyright (c) 1999-2018, by Zend Technologies

Do I need some kind of spell to make it recognize the php file?

Javascript replace unicode char with global flag

I want to remove Zero Width Space character from string and want to preserve rest of text.

I am usually replacing string with str.replace('/red/g', 'blue') usage.

This time I want to replace u200B unicode character.

Using str.replace('u200B', '@') works but when I add global flag str.replace('/u200B/g', '@') it doesn’t work.

It works with replaceAll but I want to make with replace method.