I want to send values from JS to Rails when the page is loaded

Issue

When the page loaded, after adding the query parameter to the URL, I redirected to that URL.

However, an infinite loop occurs.

How can I implement this so that when the page is loaded, the value is sent from the JS to Rails and does not cause an infinite loop?

Code

window.onload = () => {
  function successGetPosition(position) {
    sessionStorage.setItem('latitude', position.coords.latitude);
    sessionStorage.setItem('longitude', position.coords.longitude);
    
    window.location.href = `/?latitude=${sessionStorage.getItem('latitude')}&longitude=${sessionStorage.getItem('longitude')}`;
  }

  function failGetPosition(error) {
        ...
  }

  options = {enableHighAccuracy: true};

  function getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(successGetPosition, failGetPosition, {enableHighAccuracy: true});
    } else { 
      alert("Geolocation is not supported by this browser.");
    }
  }
 
  getLocation();
};

jest testcase failing in react

Below code is working properly.

let token:any='';
   token = localStorage.getItem("okta-token-storage"); 
  const bearerToken= "Bearer "+JSON.stringify(token.accessToken.accessToken);
  const handleAction = async () => {
    if (link.current.href) { return }
    const result = await fetch(props.url, { 
      headers: {Authorization: bearerToken}
    })

but when I am testing it in jest it is failing.

below is the value of

okta-token-storage
{"accessToken":{"value":"eyJraWQiOiJFU1JPX21uMG00bEhmOHB2UVU2WUpOS2ZiWktPclp6VVlVZnhTUWRCdXh3IiwiYWxnIjoiUlMyNTYifQ.eyJ2ZXIiOjEsImp0aSI6IkFULkxnMHk5ajNRMWRHU0NlNDFWcHJYdHg4UnJTUWdqTHF0dWVOSWRNTHdBX0UiLCJpc3MiOiJodHRwczovL21hcnNoZGV2LW1tYy5va3RhcHJldmlldy5jb20vb2F1dGgyL2RlZmF1bHQiLCJhdWQiOiJhcGk6Ly9kZWZhdWx0IiwiaWF0IjoxNjUwNDU1NjQ1LCJleHAiOjE2NTA0NTkyNDUsImNpZCI6IjBvYTExYzFnM2cyZXl4dnJRMGg4IiwidWlkIjoiMDB1MTE0bTR1bDlEbW1nUnkwaDgiLCJzY3AiOlsiZW1haWwiLCJvcGVuaWQiLCJwcm9maWxlIl0s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M8LBARCydsLVNR8CeAiPdW4i2yy5G_ZE4wUGgE2MTq5GnRaHIxycIEoOe6dYMT0aBNivED3s7yEi0ORCZwWcpbXSzmQ__VTcFt8wCA9UDHKPV-LFcmWEuLcRu5IN2-Eoz0csX8R2gDz0vayK-EPnOOhcyNbaqzhy-kk1a3ELzzZUtgcHX_IBrGCPMg0U4lhpwHOahJK6BeuOPogonqMgNWX3cKhHt37QH-Qk-k7ZmGpt0cLAXjZ_iS2y0LfSNtMyByQHxxUNYHN1JHyL64-eIgBUr7h4cO6S4RIF9t_b7ctApWgddQmdaf_AkSeJcM_I7Cww","claims":{"ver":1,"jti":"AT.Lg0y9j3Q1dGSCe41VprXtx8RrSQgjLqtueNIdMLwA_E","iss":"https://infosysdev-infy.oktapreview.com/oauth2/default","aud":"api://default","iat":1650455645,"exp":1650459245,"cid":"0oa11c1g3g2eyxvrQ0h8","uid":"00u114m4ul9DmmgRy0h8","scp":["email","openid","profile"],"auth_time":1650432487,"sub":"[email protected]","Email":"[email protected]"},"expiresAt":1650459221,"tokenType":"Bearer","scopes":["email","openid","profile"],"authorizeUrl":"https://infosysdev-infy.oktapreview.com/oauth2/default/v1/authorize","userinfoUrl":"https://infosysdev-infy.oktapreview.com/oauth2/default/v1/userinfo"},"idToken":{"value":"eyJraWQiOiJFU1JPX21uMG00bEhmOHB2UVU2WUpOS2ZiWktPclp6VVlVZnhTUWRCdXh3IiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiIwMHUxMTRtNHVsOURtbWdSeTBoOCIsIm5hbWUiOiJPbmthciBUaXdhcmkiLCJlbWFpbCI6Ik9ua2FyLlRpd2FyaUBtYXJzaC5jb20iLCJ2ZXIiOjEsImlzcyI6Imh0dHBzOi8vbWFyc2hkZXYtbW1jLm9rdGFwcmV2aWV3LmNvbS9vYXV0aDIvZGVmYXVsdCIsImF1ZCI6IjBvYTExYzFnM2cyZXl4dnJRMGg4IiwiaWF0IjoxNjUwNDU1NjQ2LCJleHAiOjE2NTA0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ww-1ZM6Vho0jc99pRXmU8nfI84W2qYmX7iQOi-75f5rD2nFyFiTGuTKHAS_zKFxGFsbNhia7tEmS0xjHApbzHSK6EQd6GTXbIevoGaX7t-_UHSMoQ2sqtZESzMcUcfjLZV_0ATiQUc6TeEZ2HENQRZjbH2JET8AqTtRodzsfB2iDVGjR6BG4IeXSxACoy5Yp1yE_AAU5NPbD5118PC8IjIdiUELQMaWPAdFlbur0DuWSJk77zfPp2HRuCX4VYRcExAcksygtQnHLFbjfRM8JaMfLbw7L-5iiVf-AAWDXQ","claims":{"sub":"00u114m4ul9DmmgRy0h8","name":"test sharma","email":"[email protected]","ver":1,"iss":"https://infosysdev-infy.oktapreview.com/oauth2/default","aud":"0oa11c1g3g2eyxvrQ0h8","iat":1650455646,"exp":1650459246,"jti":"ID.LqrNy6IDojthuMTg94oSrc5cYK0aIp618ZANZqWqfMM","amr":["pwd"],"idp":"0oal0stulhljMSsEe0h7","nonce":"KNV60wLOkgtL8YwbnPUUv6MxW225t0gwfhf5tdrOfXAu2wWM6SYKpEfxte9pf8Ek","preferred_username":"[email protected]","auth_time":1650432487,"at_hash":"4qVToCgufKzAO1WPFIOXYg","lgn":"[email protected]","Groups":["infosys_Only_Group","Everyone","macti_ipsen_internal","macti_ipsen_admin","all_colleagues","infosys_Realestate_Internal"],"nid":"U1245868","typ":"Internal","employeeNumber":"1245868"},"expiresAt":1650459246,"scopes":["openid","profile","email"],"authorizeUrl":"https://infosysdev-infy.oktapreview.com/oauth2/default/v1/authorize","issuer":"https://infosysdev-infy.oktapreview.com/oauth2/default","clientId":"0oa11c1g3g2eyxvrQ0h8"}}

enter image description here

what mistake I am doing?

Request handler in Javascript

I am new to JS.
how can I handle fetch/XHR events in javascript? Basically I need to check if any fetch call has happened.
For example, in case of ajax call I could do this :

jQuery(document).ajaxSuccess(() => {
//some function
}

how to set a1,b1 field readonly in jquery table2excel plugin?

<script src="https://cdn.rawgit.com/rainabba/jquery-table2excel/1.1.0/dist/jquery.table2excel.min.js"></script>
<table id="table2" border="1">
    <thead>
        <th>Sr</th>
        <th>Name</th>
        <th>Location</th>
        <th>Job Profile</th>
    </thead>
    <tbody>
        <tr>
            <td>1</td>
            <td><p>Amit Sarna</p></td>
            <td>Florida</td>
            <td>Data Scientist</td>
        </tr>
</tbody>
</table>
<button onclick="ExportToExcel()">Export table to excel</button>
</html>
<script>
  function ExportToExcel() {
    $("#table2").table2excel({
      filename: "file.xls",
      exclude_inputs:true,
      ignoreColumn: ['A1']
    });
  }   
</script>

I want to set readonly column values in excel file.but i cannot set read only properties. please help me to solve this

What is the difference between “worker threads” and “clusters” in node.js and when to use which?

While reading the node.js docs I came across

Clusters of Node.js processes can be used to run multiple instances of Node.js that can distribute workloads among their application threads. When process isolation is not needed, use the worker_threads module instead, which allows running multiple application threads within a single Node.js instance.

I thought of worker threads being isolated, parallel processes already. What exactly is meant with “process isolation” here and how are clusters different from “Multiple threads within a single node.js instance”?

Recursively populate parent-child tree from MongoDB collection

I have a MongoDB database with a collection, using a mixture of Parent and Child References.

Each document in the collection includes two properties: parentId and childIds.

The parentId property is an (ObjectId) reference to the parent document.

The childIds property is an array of (ObjectId) references to child documents.

Given the collection:

[
  {
    "_id": {
      "$oid": "625fa5b1a8142aef1a1d034d"
    },
    "taskId": 1,
    "taskName": "New Task 1",
    "parentId": null,
    "childIds": [
      {
        "$oid": "625fa66a409d15316aada92e"
      }
    ],
    "subtasks": []
  },
  {
    "_id": {
      "$oid": "625fa66a409d15316aada92e"
    },
    "taskId": 2,
    "taskName": "New Task 2",
    "parentId": {
      "$oid": "625fa5b1a8142aef1a1d034d"
    },
    "childIds": [
      {
        "$oid": "625fc16c409d15316aada94c"
      }
    ],
    "subtasks": []
  },
  {
    "_id": {
      "$oid": "625fc16c409d15316aada94c"
    },
    "taskId": 3,
    "taskName": "New Task 3",
    "parentId": {
      "$oid": "625fa66a409d15316aada92e"
    },
    "childIds": [],
    "subtasks": []
  },
  {
    "_id": {
      "$oid": "625fc16f409d15316aada94f"
    },
    "taskId": 4,
    "taskName": "New Task 4",
    "parentId": null,
    "childIds": [
      {
        "$oid": "625fc173409d15316aada952"
      }
    ],
    "subtasks": []
  },
  {
    "_id": {
      "$oid": "625fc173409d15316aada952"
    },
    "taskId": 5,
    "taskName": "New Task 5",
    "parentId": {
      "$oid": "625fc16f409d15316aada94f"
    },
    "childIds": [],
    "subtasks": []
  }
]

My goal is to populate a recursive tree structure from that collection that can be sent to the client, so any child object will be in it’s respective parent subtasks array like:

[
  {
    "_id": "625fa5b1a8142aef1a1d034d",
    "taskId": 1,
    "taskName": "New Task 1",
    // This is a parent task so parentId is null
    "parentId": null,
    "childIds": ["625fa66a409d15316aada92e"],
    // subtasks will be the objects of the childIds,
    // just 625fa66a409d15316aada92e in this case
    "subtasks": [
      {
        "_id": "625fa66a409d15316aada92e",
        "taskId": 2,
        "taskName": "New Task 2",
        // This is a child, but also has children,
        // so both parentId and childIds are present
        "parentId": "625fa5b1a8142aef1a1d034d",
        "childIds": ["625fc16c409d15316aada94c"],
        "subtasks": [
          {
            "_id": "625fc16c409d15316aada94c",
            "taskId": 3,
            "taskName": "New Task 3",
            "parentId": "625fa66a409d15316aada92e",
            "childIds": [],
            "subtasks": []
          }
        ]
      }
      // ... More subtasks
    ]
  },
  {
    "_id": "625fc16f409d15316aada94f",
    "taskId": 4,
    "taskName": "New Task 4",
    "parentId": null,
    "childIds": ["625fc173409d15316aada952"],
    "subtasks": [
      {
        "_id": "625fc173409d15316aada952",
        "taskId": 5,
        "taskName": "New Task 5",
        "parentId": "625fc16f409d15316aada94f",
        "childIds": [],
        "subtasks": []
      }
    ]
  }
  // ... More tasks
]

I’m looking through similar issues that suggest using populate or aggregate but don’t have anything concrete to start with.

I currently just have this, where result is the array of documents from the collection as is:

export class Task extends Service {
  constructor(options: Partial<MongooseServiceOptions>, app: Application) {
    super(options);
  }

  find(params: Params): any {
    return super.find(params).then((result: any) => {
      // Todo: Populate parent-child tree structure to send to client

      return result;
    });
  }
}

Behaviour of :defined pseudo selector class

I had a script as follows

const custElem = document.createElement('my-elem')
let res = custElem.matches(':defined');
console.log(`custElem.matches(':defined'): ${res}`);

res = custElem.matches(':not(:defined)');
console.log(`custElem.matches(':not(:defined)'): ${res}`);

customElements.define('my-elem', class extends HTMLElement {
    constructor () { 
         super() 
    }
});

res = custElem.matches(':defined');
console.log(`After definition: custElem.matches(':defined'): ${res}`); // EXPECTED TRUE

I expected the last log to yield true. Why does custElem fail to match the :defined selector even after the definition of the custom element?

CSS invert popup position near boundary

I’m working on a popup box that shows some text some position away from an element when the cursor hovers over it. You can see a simplified demo here: https://jsfiddle.net/xsvm2Lur/61/

Right now the popup box will squash up when it is near the bounding box. I want the popup to appear to the bottom-left (if the popup will overflow to the right) or top-left (if the popup will overflow to the bottom and to the right) of the hovered element’s position if the popup will overflow.

The position and text that will be shown are dynamically generated (e.g. I don’t know before rendering).

Right now I have a working version using Javascript. The way I go about it is:

  • Get the text that will be displayed. Count the number of characters in the inputs x 0.25em for each character to get the width of the text
  • Calculate the width of the displayed string + padding (left and right). Let’s call it textLength. This will be set as the popup’s width so all the text goes into 1 line.
  • If textLength + x position of the cursor > box width, “invert” the popup box on the x-axis by deducting the popup’s “left” value by textLength and some distance away from the element.
  • Repeat the same check for the y position, i.e. if cursor position + line height (1em) + bottom padding > box height, invert y.

The solution works, but I’m wondering if there’s a better way to do this without character counting, or if there is another way to do it elegantly, maybe CSS only without Javascript?

Demo image

Mat angular table isn’t reacreated second time with the new values

When I’m opening a page, I’m creating a mat-angular table (the one from their documentation). The problem is that my page is composed from 3 components. I’m changing a value (a string) in a component and I’m sending this value to the component with the table. The table’s header should be updated with the new value. The problem is that even if I call the function which is generating my table (so I’m recreating the table again), the table is not updated with the new values. I looked in TS, the values are updated, but the template isn’t.
In my function which generates the table I have this:

this.dataSourceTable = new MatTableDataSource<myType>(
            this.createElements(),
        );

Can be that the somehow dataSourceTable is not updated?

Get coordinates of an image in pdf file

so I’m currently parsing a pdf in js and nodejs, and I got a response on my last question so thanks to that person 🙂

So, currently, my code looks like that : I get images, modify them, then replace them in my pdf on top of the previous image.

(async () => {
       const img = await Jimp.read(buffer).then(async function (image) {
          image.color([
            { apply: 'hue', params: [90] }]);
          let nameImage = `${objIdx.toString()}.jpg`;
          ++objIdx;
          image.writeAsync(nameImage, 'image/jpeg');
          let embeddedImage = await pdfDoc.embedJpg(fs.readFileSync(nameImage));

          pages[nbPage].drawImage(embeddedImage, {
            x: image.getWidth() / 2,
            y: image.getHeight() / 2,
            width: image.getWidth(),
            height: image.getHeight(),
          });

          fs.writeFileSync('client/public/sample_modified.pdf', await pdfDoc.save());
   })

and my problem is that I don’t know how to get the original coordinates of my image and the page it is from, so I can replace it correctly on the pdf. I would like to have access to the actual size too, because it is modified when it is on the file. I dont know if it is clear enough ? I dont know if it is achievable by having the ref of the object, because if so, I have access to that information too.

Thanks in advance !