Sending data to specific user in Socket IO

In my socket io server, currently whenever a user connects I add them to an array and join them to a room with the name being their unique user Id. The code for this is shown below:

Server.js:

var users  = []

io.on('connect', (socket) => {
    socket.on('join', (data) => {
       // Add user to array
       users.push({socketId: socket.id, username: data.username, userId: data.uid})
       // Join a user into their own room with the name being their unique user Id
       socket.join(data.uid)
    }) 
})

When sending to one specific user, currently I am doing the following:

// Find the user from the users array
const user = users.find(u => u.userId = userId)
// Emit to room that I joined them to after connecting
io.to(user.userId).emit("send message", messageData)

An alternative approach would be to not have users join rooms with their own user id’s after connecting, and instead directly send events to users socket Ids. This would look like the following:

io.to(user.socketId).emit("sendMessage", messageData)

Using this method, users would not need to join their own room as soon as they connect, unlike the first method.

Is there any benefit to using this second approach as opposed to the first? Is there any scenarios where one solution would fit better?

Also, instead of joining a user to their own room on connect, could I just use io.to(user.socketId).emit("send message", data) which uses the user’s socket id as the room name, as I believe socket IO always automatically connects a user to their own room using their socket Id. However, this feature is mentioned in v3 of socket io documentation and not v4, therefore is this still a built in feature? Thanks.

Open an email draft via Browser Add-On

I am trying to create a feedback button in my Add-On, which basically opens an email draft with a given subject and email alias.

This is my attempt right now, but clicking the button, does not do anything.
Does anyone spot the problem? :/
I am using Firefox 115.5.0esr (64-bit); and reduced the Add-on to a minimum for troubleshooting.

manifest.json

{
  "manifest_version": 2,
  "name": "My Email Extension",
  "version": "1.0",
  "description": "Generate email with a button click",
  "icons": {
    "48": "icon.png"
  },
  "permissions": [
    "tabs"
  ],
  "browser_action": {
    "default_icon": "icon.png",
    "default_title": "Generate Email",
    "default_popup": "popup.html"
  },
  "icons": {
    "48": "icon.png"
  }
}

popup.html

<!DOCTYPE html>
<html>
<head>
  <title>My Email Extension</title>
  <script src="popup.js"></script>
</head>
<body>
  <button id="generateEmail">Generate Email</button>
</body>
</html>

popup.js

document.getElementById('generateEmail').addEventListener('click', function() {
  var emailUrl = "mailto:[email protected]";

  chrome.tabs.create({ url: emailUrl });
});

How to add a class to the body that will change depending on the page in the remix?

The body is located in the root.jsx, where I want to give it a parameter as class that will change depending on the page. In the route on each of the pages I want to assign values, for example the class on _index is equal to “company homepage”, in restaurants route the class is equal to “venue company” and so on. Is it possible to transfer parameters from routes to root.jsx?

root.jsx


export default function App() {
  return (
    <html lang='en'>
      <head>
        <meta charSet='utf-8' />
        <meta name='viewport' content='width=device-width, initial-scale=1' />
        <link rel='preconnect' href='https://fonts.googleapis.com' />
        <link
          rel='preconnect'
          href='https://fonts.gstatic.com'
          crossOrigin='anonymous'
        />
        <link
          href='https://fonts.googleapis.com/css?family=Montserrat:wght@100,300,400,500,700&display=swap'
          rel='stylesheet'
        />
        <Meta />
        <Links />
      </head>
      <body>
        <Outlet />
        <ScrollRestoration />
        <Scripts />
        <LiveReload />
      </body>
    </html>
  );
}

_index.jsx


export default function Index() {
  const { startPage } = useLoaderData()
  const page = startPage.page.sections;
  return (
    <main id='main'>
      <PageComponents page={page} />
    </main>
  );
}

restaurants.jsx

export default function Restaurants() {
  const { restaurants } = useLoaderData();
  return (
    <>
      <PageComponents page={restaurants.sections} />
      <footer className='footer' />
    </>
  );
}

PageComponents.jsx

import loadable from "@loadable/component";

const components = {
  logo: loadable(() => import("./Logo")),
  intro: loadable(() => import("./Intro")),
  languageSwitch: loadable(() => import("./LanguageSwitch")),
  venueGroup: loadable(() => import("./VenueGroup")),
};

export default function PageComponents({ page }) {
  return (
    <main>
      {page
        .filter(({ type }) => !!components[type])
        .map(({ data, type }) => {
          const Component = components[type];

          return (
            <div key={type}>
              <Component data={data} />
            </div>
          );
        })}
    </main>
  );
}

Tried function loader in root.jsx to get the API for each page and added a variable to body className, but sometimes there are going to be no data about pageClassName, so I need to pass parameter about className manually to each page from the routes and transfer this parameter to root.jsx

Page like crash after I saved a change in React.js

This problem finally annoys me.
I forgot when, I don’t know how, but if I remembered correctly, this problem happens after I update a plugin then undo it because it causes an error then delete node_modules and reinstall npm.
After I saved some changes in my code the page load and show the changes, but the page somehow crash.
I cannot push a button, cannot highlight a text, cursor always default, literally nothing I can do in that page. I just can scroll it. To kinda fix that, I always CTRL + Shift + R the page then it back to normal.
If I check the console on the browser, it returns an error like this

Uncaught ReferenceError: process is not defined
    4043 blank line 207766 > injectedScript:2
    r blank line 207766 > injectedScript:2
    8048 blank line 207766 > injectedScript:2
    r blank line 207766 > injectedScript:2
    8641 blank line 207766 > injectedScript:2
    r blank line 207766 > injectedScript:2
    <anonymous> blank line 207766 > injectedScript:2
    <anonymous> blank line 207766 > injectedScript:2
    <anonymous> blank line 207766 > injectedScript:2
    onload index.js:1
    be index.js:1
    he index.js:1
    tryDismissErrorOverlay webpackHotDevClient.js:184
    onSuccessfulHotUpdate webpackHotDevClient.js:150
    handleApplyUpdates webpackHotDevClient.js:257
    tryApplyUpdates webpackHotDevClient.js:273
    promise callback*tryApplyUpdates webpackHotDevClient.js:271
    handleWarnings webpackHotDevClient.js:147
    onmessage webpackHotDevClient.js:210
    js webpackHotDevClient.js:195
    Webpack 7
        __webpack_require__
        fn
        1
        __webpack_require__
        checkDeferredModules
        webpackJsonpCallback
        <anonymous>
blank line 207766 > injectedScript:2:13168
    4043 blank line 207766 > injectedScript:2
    r blank line 207766 > injectedScript:2
    8048 blank line 207766 > injectedScript:2
    r blank line 207766 > injectedScript:2
    8641 blank line 207766 > injectedScript:2
    r blank line 207766 > injectedScript:2
    <anonymous> blank line 207766 > injectedScript:2
    <anonymous> blank line 207766 > injectedScript:2
    <anonymous> blank line 207766 > injectedScript:2
    onload index.js:1
    (Async: EventHandlerNonNull)
    be index.js:1
    he index.js:1
    tryDismissErrorOverlay webpackHotDevClient.js:184
    onSuccessfulHotUpdate webpackHotDevClient.js:150
    handleApplyUpdates webpackHotDevClient.js:257
    tryApplyUpdates webpackHotDevClient.js:273
    (Async: promise callback)
    tryApplyUpdates webpackHotDevClient.js:271
    handleWarnings webpackHotDevClient.js:147
    onmessage webpackHotDevClient.js:210
    (Async: EventHandlerNonNull)
    js webpackHotDevClient.js:195
    Webpack 7
        __webpack_require__
        fn
        1
        __webpack_require__
        checkDeferredModules
        webpackJsonpCallback
        <anonymous>

I’ve been asking my friend about how to fix this but comes to no end.
How should I fix this?

suspence in vue 3 removes some buttons

I’m usually not a vue developer (or frontend) but everyone else is in their well deserved holidays and I want to finish this last ticket before I leave myself…

The following code blog displays A Table with data and two Buttons on each row when everything is sycnron

      <NTable
        :fields="fields"
        :items="lkwQuellen"
        :filters="filters"
        :busy="isLoading"
        defaultSortKey="defaultSort"
        defaultSort="desc"
      >
        <template #cell-actions="{ item }">
          <div v-if="!isLoading" class="is-flex">
            <NButton
              size="small"
              variant="secondary"
              icon="far fa-address-book"
              class="mr-2"
              @click="showKontakte(item as ILkwQuelle)"
            >
            </NButton>
            <router-link :to="ROUTES.getLkwParkplatzEditorRoute(item.id)">
              <NButton size="small" icon="fa-edit"></NButton>
            </router-link>
          </div>
        </template>
      </NTable>

Now I need to change it so that NTable loads in some user Preferences with a backend-call. In Order to make the table wait for this data, I changed it to:

  <Suspense>
    <template #default>
      <NTable
        :fields="fields"
        :items="lkwQuellen"
        :filters="filters"
        :busy="isLoading"
        defaultSortKey="defaultSort"
        defaultSort="desc"
      >
        <template #cell-actions="{ item }">
          <div class="is-flex">
            <NButton
              size="small"
              variant="secondary"
              icon="far fa-address-book"
              class="mr-2"
              @click="showKontakte(item as ILkwQuelle)"
            >
            </NButton>
            <router-link :to="ROUTES.getLkwParkplatzEditorRoute(item.id)">
              <NButton size="small" icon="fa-edit"></NButton>
            </router-link>
          </div>
        </template>
      </NTable>
    </template>
    <template #fallback> Loading </template>
  </Suspense>

Now the table only loads in after the user-Preferences are retrived and applied (manly which coloums should be displayed).
However, for some reason, the two Buttons aren’t shown anymore. I have to guesses as to why:

  1. The two functions they relay on are also async, but only after clicking on the button. Supsense doesn’t recognises that and waits for the action to finish?
  2. The NButton are loaded in but suspense is still waiting for NTable, so the buttons aren’t addet to the NTable after it’s loaded in.
    Either way, I’m stumped about how to change it.

I did try to add a v-if=”!isLoading” to the div and added a @resolve to the supsense that changed the isLoading state but that changed nothing.

Map display not centered and showing zoomed out

My team tried to integrate the maps and everything looked good but the location of the pointer always comes either on top right/top left, i.e. it is not showing in the center. Also, the map results based on searched locations are very zoomed out. The videos I saw on leaflet tutorials showed coding to reflect map pointers on the center and relatively zoomed in. Attaching an image to understand my issue clearly and also an image to show what exactly I am looking for from this question and how exactly I want the map should look like from the search
enter image description here
enter image description here

I would really appreciate the help and guidance on this one.

Tried what was mentioned in the tutorial videos and was expecting a result similar to this.
enter image description here

ApexCharts – Updating One Series at a Time

I am trying to find a way to append data to the second of 2 series in an ApexChart object via exec(). This is in an application which is asking for live data based on a recursive JS timeout and Promise-ified AJAX calls; when data is found it is appended to the chart with the code below The only practical solution I can think of (based on the docs) is by appending blank data to the first series and real data to the second, but this seems to not work to append to either series. I seem to understand that it could be exec() which is causing the functionality to change.

Below is my snippet:

    sensorDataQuery(chartID, sensorDetails, rangeData).then((data) => {
        let dataToAppend = [];
        if (data.results.results !== undefined && data.results.results.length > 0) {
            dataToAppend.push({data: data.results.results});
        } else { // allow for the chart to update just the additional sensor
            dataToAppend.push({data: []});
        }
        if (getChartData(chartID)('extra_sensor_id') != undefined) {
            sensorDataQuery(getChartData(chartID)('extra_sensor_id'), sensorDetails, rangeData).then((extraData) => {
                if (extraData.results.results !== undefined && extraData.results.results.length > 0) {
                    dataToAppend.push({data: extraData.results.results});
                }
            });
        }
        if (dataToAppend.length == 0) {
            setChartDataAndContinue(chartID, currTime + 1);
            return;
        }
        ApexCharts.exec(chartID, 'appendData', dataToAppend).then(() => {
            setChartDataAndContinue(chartID, currTime + 1);
        });

With this code, I expected that data would be added to the main series or the secondary series by building an array with empty data if nothing was pulled from the server, or with new data from the data.results.results object.

Thanks for reading, anything helps!

React Chart.js providing equal gap for xAxes showing formatted dates

After adding displayFormats in scales.x, now my xAxes labels are having different gaps according to the data object it contains. How do I make my xAxes labels to be shown with equal gaps?
The follow code is shown as follow image.
Please remember that I still need to use displayFormats to format my data.

enter image description here

  const levelHistoryOptions = {
    responsive: true,
    maintainAspectRatio: false,
    layout: {
      padding: {
        top: 20,
        bottom: 20,
      },
    },
    plugins: {
      legend: {
        display: false,
      },
      datalabels: {
        color: theme.palette.primary.main,
        anchor: "end",
        align: "top",
        font: {
          size: 16, // Adjust the font size as needed
        },
        formatter: (value, context) => {
          return context.chart.data.datasets[context.datasetIndex].data[
            context.dataIndex
          ];
        },
      },
    },
    scales: {
      x: {
        type: "time",
        time: {
          unit: "day",
          displayFormats: {
            day: "MM월 dd일",
          },
        },

        offset: true,
        ticks: {
          source: "data",
          font: {
            size: 16,
          },
          color: theme.palette.primary.main,
        },
        grid: {
          color: theme.palette.mode === "dark" ? "#555" : "#ccc",
        },
        border: { color: theme.palette.mode === "dark" ? "#555" : "#ccc" },
      },
      y: {
        offset: true,
        display: false,
        beginAtZero: false,
      },
    },
  };

Where do GM.setValue()s database entries get stored in Firefox/MacOS?

GreaseMonkey, Firefox, Mac OSX.
I know you can see the keys with GM.listValues() but I cannot find a straightforward answer on Google where the sqlite/file is so that you can read the data somewhere else. I’d like to ideally open the sqlite folder so I can cleanly see the database entries without having to run the GM.listValues() command. I’ve tried looking in my Application Support Folder, about:debugging, about:config… None of the info I’ve seen online is making sense to me.

How to deep find an array for a children property match in JS

Let’s assume I have a similar object (a possible object for a website sidebar)

const sidebar = {
    label: "group 1-1",
    children: [
        {
            label: "group 1-2",
            children: [
                {
                    label: 'sub1-2-1',
                    slug: 'sub1-2-1'
                }, {
                    label: 'sub1-2-2',
                    slug: 'sub1-2-2'
                }
            ]
        },
        {
            label: 'sub1-2',
            slug: 'sub1-2'
        }
    ]
}

Now I need to identify if any of the slug in the array include sub1-2-2.
I know I could make a recursion, but my test fails and keep falsify. Here’s the code I’ve written so far:

const sidebar = {
    label: "group 1-1",
    children: [
        {
            label: "group 1-2",
            children: [
                {
                    label: 'sub1-2-1',
                    slug: 'sub1-2-1'
                }, {
                    label: 'sub1-2-2',
                    slug: 'sub1-2-2'
                }
            ]
        },
        {
            label: 'sub1-2',
            slug: 'sub1-2'
        }
    ]
}

function deepFind(group, location) {
    const parseSlug = (o) => o.slug === location
    return group.children ? deepFind(group.children, location) : group.some(parseSlug)
}


console.log(deepFind(sidebar,'sub-1-2-2'))

At first run, the children is a property, but the it becomes an array, so I am getting confused with the best way to make the recursion.

React Routing – how to use a different Layout for Marketing vs Product content?

I have a repo that has product and marketing in one. I want to use a separate Layout for each. I have it generally established structurally, but I don’t understand what to use for a logical check to assign a specific Layout that is isolated from the other.

This is my App.tsx:

import React from "react";
import { createBrowserRouter, RouterProvider, } from "react-router-dom"
import ProductLayout from "./components/Product/Layout/Layout"
import productRoutes from "./routes/productRoutes"
import MarketingLayout from "./components/Marketing/Layout/Layout"
import marketingRoutes from "./routes/marketingRoutes"
import ErrorPage from './components/Product/Error/NotFound';

function App() {
  const router = createBrowserRouter([
    {
      element: <ProductLayout />,
      errorElement: <ErrorPage />,
      children: productRoutes
    },
    {
      element: <MarketingLayout />,
      errorElement: <ErrorPage />,
      children: marketingRoutes
    },
  ])

/// What do I put here to indicate branching??

  return (
    <RouterProvider router={router} />
  );
}

export default App;

This is components/Product/Layout/Layout:

// Layout.js
import React from "react";
import { Outlet } from "react-router-dom";
import { Suspense } from "react";
import DelayedFallback from './DelayedFallback'; // import the component
import routes from 'src/routes/productRoutes.js'; // Import your routes file

export default function ProductLayout() {
  const location = useLocation();

  return (
    <>
      <main>
        <Suspense fallback={<DelayedFallback delay={500}><div>Loading...</div></DelayedFallback>}>
          <Outlet />
        </Suspense>
      </main>
    </>
  );
}

This is components/Marketing/Layout/Layout:

import React from "react";
import { Outlet } from "react-router-dom";

export default function MarketingLayout() {
  
  return (
    <>
      <main>
        <Outlet />
      </main>
    </>
  );
}

I have routes set up like this;
pathConstants.js

const PathConstants = {

    Home: "/",  
    Page1: "/page1", 
    Page2: "/page2", 
    Page3: "/page3", 
    Page4: "/page4", 
    NotFound: '*'
}

export default PathConstants

productRoutes.js

import React from "react"
import PathConstants from "./pathConstants"
import ErrorPage from "src/components/Product/Error/NotFound";


const Page1 = React.lazy(() => import("src/pages/Product/Page1"))
const Page2 = React.lazy(() => import("src/pages/Product/Page2"))


const routes = [    

    { path: PathConstants.Page1, element: <Page1 /> },
    { path: PathConstants.Page2, element: <Page2 /> },
]

export default routes

And marketingroutes.js

import React from "react"
import PathConstants from "./pathConstants"
import ErrorPage from "src/components/Marketing/Error/NotFound";

const Home = React.lazy(() => import("src/pages/Marketing/Home"))
const Page3 = React.lazy(() => import("src/pages/Marketing/Page3"))
const Page4 = React.lazy(() => import("src/pages/Marketing/Page4"))


const routes = [    

    { path: PathConstants.Home, element: <Home /> },
    { path: PathConstants.Page3, element: <Page3 /> },
    { path: PathConstants.Page4, element: <Page4 /> },
]

export default routes

Any help is appreciated.

Sign and Encryption to XML for SOAP services in JavaScript

I need create a logic in JavaScript that allow sign and encrypt XML for comunications SOAP.

In the tag header what values would go in its content

<soap:Header>
<wsse:Security>
<ds:DigestValue>
<ds:Signature>
<ds:SignedInfo>
   <ds:Reference>
     <ds:DigestValue>...</ds:DigestValue>
   </ds:Reference>
</ds:SignedInfo>
 <ds:KeyInfo>
   <wsse:SecurityTokenReference>
      <wsse:KeyIdentifier>...</wsse:KeyIdentifier>
   </wsse:SecurityTokenReference>
 </ds:KeyInfo>
<ds:SignatureValue>...</ds:SignatureValue>
</ds:Signature>
</wsse:Security>
</soap:Header>

How can I learn what each label means or how can I generate the respective content for those labels in javascript?

I tried this

for DigestValue

function calculateDigest(xmlContent) {
    const hash = crypto.createHash('sha256');
    hash.update(xmlContent);
    return hash.digest('base64');
}

for SignatureValue


function signDigest(digest, privateKey) {
  const signer = crypto.createSign('RSA-SHA256');
  signer.update(digest);
  return signer.sign(privateKey, 'base64');
}

for KeyIdentifier

function generateKeyIdentifier(certPem) {
  const certDer = Buffer.from(certPem.replace(/(-----(BEGIN|END) CERTIFICATE-----|n)/g, ''), 'base64');
  return crypto.createHash('sha256').update(certDer).digest('base64');
}

It works but I’m not sure since the external server gives me a 500 error

how to append css file to a child window in reactjs

I created a child window such that when a user click on a button it will open up the child window.

I am thinking of how to style the child window page with css

I attached my css file to the child window but it shows that home.css is not found.

the 2 files are in the same folder.

const playRaffle = async (values) => {

const data = {
    ...values,
    raffleId,
    "user_id": 19
}


const raffles = await StakeServices.playRaffle(data);
const res = raffles.data.data;
if (res) {

    const windowFeatures = "scrollbars=no,resizable=no,status=no,location=no,toolbar=no,menubar=no,width=600,height=400,left=400,top=250";
    const childWindow = window.open(`http://localhost:3000/agent/print-raffle?playDate=${res.created_at}&name=${res.winningTag}&price=${res.stake_price}&ticketid=${res.ticket_id}`, "_blank", windowFeatures);

    //  childWindow if the child window is successfully opened
    if (childWindow) {
        childWindow.opener = null;

        childWindow.onload = function (res) {
            var childDocument = childWindow.document;
            const queryParams = new URLSearchParams(childWindow.location.search);

            // Access individual parameters
            const item = queryParams.get('name');
            const price = queryParams.get('price');
            const ticketid = queryParams.get('ticketid');
            const playDate = queryParams.get('playDate');


            const styleLink = childWindow.document.createElement('link');
            styleLink.rel = 'stylesheet';
            styleLink.href = 'Home.scss'; // Adjust the path accordingly
            childWindow.document.head.appendChild(styleLink)

            var newDiv = childDocument.createElement('div');
            newDiv.id = 'myDiv';
            newDiv.class = 'myDiv';
            newDiv.classList.add("myDiv");
            newDiv.innerHTML = `
            <div class"inner-window font-sm">
                <table class="table">
                    <thead>
                        <th>Item</th>
                        <th>Price</th>
                        <th>Ticket ID</th>
                        <th>Date</th>
                    </thead>
                    <tbody>
                        <td>${item}</td>
                        <td>${price}</td>
                        <td>${ticketid}</td>
                        <td>${playDate}</td>
                    </tbody>
                </table>
            </div>`;
            childDocument.body.classList.add("child-body");
            childDocument.body.appendChild(newDiv);
        };
    } else {
        alert('Popup blocked. Please allow popups for this site.');
    }
}

}

Maui.net ExecuteScriptAsync(): Failed because a valid CoreWebView2 is not present

If I want to execute this method:

    private async void GetSessionIdFromWebView()
    {
        sessionId = await webViewer.EvaluateJavaScriptAsync("MauiAppInterface.GetSessionId();");
    }

I got this Exception:

System.InvalidOperationException: “A method was called at an unexpected time.

ExecuteScriptAsync(): Failed because a valid CoreWebView2 is not present. Make sure one was created, for example by calling EnsureCoreWebView2Async() API.”

I use the normal WebView and not the Webview2.

        <WebView x:Name="webViewer" />

In addition, the webview is not null when the above method is executed.

At androit and ios it works without problems only in windows i got this Exception.

Does anyone have any idea what the issue is?

Autodesk Viewer, Programmatic Camera Y-Axis Inversion

I have been using the markups core extension to get the viewer state and then restore it, which has been working, except I am running into an inversion problem (only in 3d). When a client interacts with specifically the y axis, and essentially flips the model to see underneath, or above, the viewer inverts itself, it seems during or after the restoreState() function. The values are identical, just inverted, for example a client’s getState() values of {x: 1, y: -1, z:-2} is restored and then inverted to {x: -1, y: 1, z: 2}.

To test this further, I used the getCamera(), took the position, the target, and the up value, and used setView() to programmatically set the camera position. What I found was without using the up, the optional value in the setView() function, the inversion repeated itself, the same effect, received the correct values, set them, then inverted. However this all fixed itself as soon as I used the up value. A new issue now is that the setView() function seems to lose the smooth transitioning of the camera that comes with getState() restoreState(), resulting in a very choppy and snappy UX. Knowing now that the issue lies somewhere in the up value I tried to go back to setState() restoreState() and try setting the up directly, this unfortunately did not work. I tried using orientCameraUp(true), setCameraUpVector() with both the getState().viewport.up and getState().viewport.worldUpVector.

  1. Is it possible to fix this inversion with the getState(), restoreState() so we can keep the smoothness of the transition?
  2. Is it possible to replicate the smooth transition of the restoreState() to use the method that had worked, setView().