Use Object.groupBy function to group by a variable [duplicate]

How can I use the Object.groupBy function with a variable?

For example:

const inventory = [ 
  { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },
  { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" },
  { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" },
  { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" },
  { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" },
  { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" },
  { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" },
  { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" }
]

I would like to display data grouped by a single key, based on the user’s selection.

let key = 'Phase';
const result = Object.groupBy(inventory, ({ key }) => key);
console.log(result);

Current output:

{
  undefined: [
    { Phase: 'Phase 1', Step: 'Step 1', Task: 'Task 1', Value: '5' },
    { Phase: 'Phase 1', Step: 'Step 1', Task: 'Task 2', Value: '10' },
    { Phase: 'Phase 1', Step: 'Step 2', Task: 'Task 1', Value: '15' },
    { Phase: 'Phase 1', Step: 'Step 2', Task: 'Task 2', Value: '20' },
    { Phase: 'Phase 2', Step: 'Step 1', Task: 'Task 1', Value: '25' },
    { Phase: 'Phase 2', Step: 'Step 1', Task: 'Task 2', Value: '30' },
    { Phase: 'Phase 2', Step: 'Step 2', Task: 'Task 1', Value: '35' },
    { Phase: 'Phase 2', Step: 'Step 2', Task: 'Task 2', Value: '40' }
  ]
}

Expected output:

{
  Phase 1: [
    { Phase: "Phase 1", Step: "Step 1", Task: "Task 1", Value: "5" },
    { Phase: "Phase 1", Step: "Step 1", Task: "Task 2", Value: "10" },
    { Phase: "Phase 1", Step: "Step 2", Task: "Task 1", Value: "15" },
    { Phase: "Phase 1", Step: "Step 2", Task: "Task 2", Value: "20" }
  ],
  Phase 2: [
    { Phase: "Phase 2", Step: "Step 1", Task: "Task 1", Value: "25" },
    { Phase: "Phase 2", Step: "Step 1", Task: "Task 2", Value: "30" },
    { Phase: "Phase 2", Step: "Step 2", Task: "Task 1", Value: "35" },
    { Phase: "Phase 2", Step: "Step 2", Task: "Task 2", Value: "40" }
  ]
}

javascript getUTCDay() don’t get the day [closed]

Does someone has or is having same issue? How can I fix it? I need to split the date and grab the day, the month and the year. I tried with getDay() and same did not work too.

function splitDate() {
  //test to get the year of today
  let today = new Date();

  Logger.log(`today: ${today}`);
  let year = today.getUTCFullYear();
  Logger.log(`year: ${year}`);
  let month = today.getUTCMonth();
  Logger.log(`month: ${month}`);  
  let day = today.getUTCDay();
  Logger.log(`day: ${day}`);

  Logger.log(`day: ${day} - month: ${month} - year: ${year}`);

}

code and result

Weird problem with forms / radio buttons and arrow navigation using Angular and Template Driven Forms

I have a weird problem with one of my forms. I am using Template Driven Forms in Angular, and as soon as I want bind the selected value of radio buttons in a form via ngModel the navigation between the radio buttons and radio button groups via arrow keys and tab key stop working.

Without the ngModel Attribute I can jump from one radio button group to another using Tab. And in one radio button group I can use the arrow keys to select a specific option. I also cannot leave a radio button group using arrow keys. That’s all the way as it’s supposed to be.

But when I add ngModel then suddenly I can’t use the tab key anymore to jump between radio button groups and the arrow up and down keys are no longer trapped in one specific radio button group (Using Chrome Browser. Firefox also changes behaviour but in a different and also wrong way).

You can check it for yourself using the follow StackBlitz projects:
Without ngModel:
https://stackblitz.com/edit/stackblitz-starters-bwkfamcz?file=src%2Fapp%2Fform%2Fform.html

With ngModel:
https://stackblitz.com/edit/stackblitz-starters-fnptjpbf?file=src%2Fapp%2Fform%2Fform.html

Has anyone of you any idea, what is going on here?

Thanks in advance.

Refactoring a quasi legacy JavaScript codebase in TypeScript and dealing with data types [closed]

The project I am working on is a patchwork of at least 3 different ECMA versions and I have a question about application types.

In a folder named types there are files that define data structures. One of them contains:

const MATERIAL_TYPES = {
    TOOL: 'TOOL',
    GLASS: 'GLASS',
    GEAR: 'GEAR',
    BRICK: 'BRICK',
    SLAB: 'SLAB',
    CEMENT: 'CEMENT',
};

This works. Whenever a material needs to be referenced, the code imports this object and uses MATERIAL_TYPES.GLASS.

What I have so far is a @types folder at the root of the project with a tree of folders that loosely resemble the application’s:

root
├─── @types
│    └─── player
│    └─── items
│    └─── services
└─── src

Each folder has an index.ts file that exports the folder’s content and @types has an index.ts file, so anywhere in the code I just import type { SomeType } from "../@types.

For the material type above, I removed the object and instead created a type:

type MaterialType = {
    | 'TOOL',
    | 'GLASS',
    | 'GEAR',
    | 'BRICK',
    | 'SLAB',
    | 'CEMENT',
};

This way I “hardcode” the value:

function dealWithMaterial(material: MaterialType): string {}

// using the function
const result = dealWithMaterial("GLASS");

My questions are:

  1. Is this the right way to do it?
  2. If you have done this before and encountered this scenario, what did you do?
  3. Would you do it differently now? If so, how?

I know it is open ended, but I would like some thoughts by people who brought back old JS code to life with TypeScript.

Will new object assignment to same GLOBAL variable cause memory leaks?

I’m trying to set GLOBAL variable available across all modules of Node.js app.

module.exports = app => {
  app.get('/config', async (req, res) => {
     .....
     const { data } = await axios.get('.....')
     app.locals.MY_CONFIG = data.config

Will this line cause memory leaks every time the route is called?

app.locals.MY_CONFIG = [data.config]

in other words will this cause an issue:

app.locals.MY_CONFIG = [data.config]
app.locals.MY_CONFIG = [data.config]
app.locals.MY_CONFIG = [data.config]
app.locals.MY_CONFIG = [data.config]
...

I cant use import in nwjs

I use nwjs to to develop desktop applications; but i cant use “import” .
For example:

import { parseMetar } from "metar-taf-parser";

const metar = parseMetar(rawMetarString);

// -or-

// Optionally pass the date issued to add it to the report
const datedMetar = parseMetar(rawMetarString, { issued });

This is metar-taf-parser : metar-taf-parser
And i get this error:

Cannot use import statement outside a module

Why is sap.m.DatePicker rendering the calendar incorrectly?

I’m using SAPUI5 version 1.120.15 on an S4 gateway system. I am using SAPWebIDE to run this locally and it does it there too.

The DatePicker control is acting very strangely in a handful of apps. I have no idea why it is acting this way, does anyone know?

It looks like the week number field on the left side is being used for the date instead, causing it to look like there are 8 days in a week.
I tried putting a blank control elsewhere in the view <DatePicker /> and it still does this. I tried in a separate test app and it worked correctly.

Is there something about the app configuration that would cause this weird bug?

Thanks very much

enter image description here

Calling a Javascript async function with async/await when streaming JSON and parsing (Node.js)

I am trying to parse an enormous JSON stream in Javascript using Node.js, which is then stored in mariadb. As part of that, I have a table that will have a small number of rows (~50), but each row has a unique value. That way if I run across the value while parsing, I don’t need to add it to the DB if it’s already there.

The problem is, those 50 values will be used literally millions of times, so I don’t really want to check the DB before I do an insert — if I can do this in one query I’d be happier.

In order to do this, and since we’re talking 50 values here, I use a set. When I come across a value, I first check to see if it’s in the set and if not, I add it to the DB, then the set.

The problem is that occasionally the function executes a second time with the same value before the set got its item added, so I end up with an attempt to add a duplicate row. I’ve tried async/await, but I suspect that the whole thing is wrapped up in an async method that’s being called from the top level of the file, so at some point the async/await chain breaks and what should run synchronously no longer does.

Here’s the code I use to insert (DB stuff done via the mariadb connector):

DB file helpers

export const pool = mariadb.createPool({
    host: 'localhost',
    port: '3306',
    user: '*********',
    password: '**********'
});

export async function getBodyType(body, conn, map) {
    let subType = body.subType || "Other";

    if (subType && !map.has(subType)) {
        // Insert into the DB as we go, adding it to a set to ensure we don't duplicate
        db.insertBodyType(subType, conn)
            .then(result => {
                map.add(subType);
            });
    }

    return subType;
}

export async function insertBodyType(bodyType, conn) {
    try {
        await conn.query(queries.bodyTypesInsert, bodyType);
    } catch (err) {
        console.log(err);
    }
}

Before continuing, I’ve also tried the insert/add block as follows, which didn’t work either:

await db.insertBodyType(subType, conn);
map.add(subType);

Now here’s the way I call the above function, which is not itself in a function (it’s just the main body of the script):

let types = new Set();
const stream = fs.createReadStream(inputFile, 'utf8');
const parser = JSONStream.parse('*');
stream.pipe(parser)
    // I'm wondering if this is the culprit -- I don't know how to make the call to 
    // stream.pipe async or even if I can, so I don't know if making its body async even 
    // matters.
     .on('data', async (system) => {

        // Array of values we need for the system insert
        let systemData = [
            system.name, 
            system.coords.x, 
            system.coords.y, 
            system.coords.z, 
            helpers.isColonizable(system), 
            helpers.isPopulated(system), 
            helpers.canColonizeFrom(system)
        ];

        let bodyMap = new Map();

        // Somehow this sometimes calls twice before the first one finishes, despite the
        // fact that the whole chain from getBodyType() on up should be async
        for (let body of system.bodies) {
            let bodyType = await helpers.getBodyType(body, conn, types);
            if (!bodyMap.has(bodyType)) {
                bodyMap.set(bodyType, 0);
            }

            bodyMap.set(bodyType, bodyMap.get(bodyType) + 1);
        }
    }
})
.on('end', () => {
    db.pool.end();
})
.on('error', (err) => {
    db.pool.end();
});

This whole thing is run in node:

$ node do_this.js

Honestly, from what I’m reading on async/await here, I’m wondering if I’m even using the right tool for the job. I might be better off using something like C# that can handle true synchronicity with async methods, assuming I read things right.

DateTimeImmutable yielding distinct timestamps in distinct PHP runtimes

Running the following script:

var_dump(
    (DateTimeImmutable::createFromFormat(
        format  : 'Y-m-d H:i:s',
        datetime: '2120-10-03 07:00:00',
        timezone: new DateTimeZone('Europe/Zurich')
    ))->getTimestamp()
);

In PHP 8.2 produces the unix epoch timestamp 4757374800, which is correct.

When this script is executed on a server whose PHP version is 5.6, the value we get is incorrect 4757378400 (one hour too late).

Why does this happen?

Same happens if we compute the unix epoch second via:

date_default_timezone_set('Europe/Zurich');
$timestamp = strtotime('2120-10-03 07:00:00 Europe/Zurich');
echo $timestamp;

Undefined method ‘getStream’ SFTP

There is a file I want to read from another server via SFTP and .pem key.
I made connection to server and it was successful now when reading the file from server using this line

// Connect to SFTP
$sftp = new SFTP($host, $port);
if (!$sftp->login($username, $key)) {
    exit('Login Failed');
}

// Read a remote file
$remoteFile = '/path/to/file.log';
$content = $sftp->get($remoteFile);

I am getting below error.

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 98566176 bytes) in /var/www/Utility/vendor/phpseclib/phpseclib/phpseclib/Net/SFTP.php on line 2461

I tried the following code

$stream = $sftp->getStream('largefile.dat');
if ($stream) {
    while (!feof($stream)) {
        $chunk = fread($stream, 8192);
        // Process $chunk
    }
    fclose($stream);
}

But it gives the error

Undefined method ‘getStream’.intelephense(P1013)

I tried checking everything php phpseclib installation is proper.

curl can connect to repo.packagist.org via HTTP but fails with HTTPS [duplicate]

When I use curl https://repo.packagist.org/packages.json,get this error:

curl: (28) Failed to connect to repo.packagist.org port 443 after 21050 ms: Could not connect to server

But when using curl http://repo.packagist.org/packages.json, it correctly worked!

> {"packages":[],"notify-batch":"https://packagist.org/downloads/","providers-url":"/p/%package%$%hash%.json","metadata-url":"/p2/%package%.json","metadata-changes-url":"https://packagist.org/metadata/changes.json","search":"https://packagist.org/search.json?q=%query%&type=%type%","list":"https://packagist.org/packages/list.json","security-advisories":{"metadata":true,"api-url":"https://packagist.org/api/security-advisories/"},"providers-api":"https://packagist.org/providers/%package%.json","warning":"Support
> for Composer 1 will be shutdown on August 1st 2025. You should upgrade
> to Composer 2. See
> https://blog.packagist.com/shutting-down-packagist-org-support-for-composer-1-x/","warning-versions":"<1.99","provider-includes":{"p/provider-2013$%hash%.json":{"sha256":"a2b47ec1a1bb999e53d88aff50728aebbd3d68225c74aab1ff5f071bac42f5b7"},"p/provider-2014$%hash%.json":{"sha256":"347426977f09ca7feb7306fd990c2db8bf28b3f3d57716f8b90a12f1c21f1065"},"p/provider-2015$%hash%.json":{"sha256":"d9fa6571b23af36e89a1f73eb3be340c81743ae5b71e523cf228552d8e02d029"},"p/provider-2016$%hash%.json":{"sha256":"27c3687c41821dca9f6d65a0ca636ae6675120d4f045d132a097d8c0311818d4"},"p/provider-2017$%hash%.json":{"sha256":"f82637fef38646359f09365a7aef1bcbdf7db5d63b0511b3a1f9f8f58a9c2854"},"p/provider-2018$%hash%.json":{"sha256":"f4870961f191584a8e58a5683ef5882459e5f66ea2d70881750a53400b401857"},"p/provider-2019$%hash%.json":{"sha256":"70145dae32ee55bd86351b2e7520fd573c642917b7787009bb5b13bfa7208517"},"p/provider-2020$%hash%.json":{"sha256":"261d9f1aaca76417647dad0922781fffeac007531dffd9d5ff8eea9b69826430"},"p/provider-2021$%hash%.json":{"sha256":"231acb00ca80397db2f2ed9cfdaa7045839584e9f39dd03b87b9cebbb9ccf5d7"},"p/provider-2022$%hash%.json":{"sha256":"fbd72f659dbd3b7f28c2f4a03bb903759e1d7641c300e1eaea0dec25bd05683e"},"p/provider-2023$%hash%.json":{"sha256":"0b8c3c321c716153c450fe69d8fd4d23279fdc451212e28ccccbb25db0aef094"},"p/provider-2024$%hash%.json":{"sha256":"745def0c1dd86019d31400fa0899b9293bc5c9bc5ab2c790866cb365dcbb16f8"},"p/provider-2024-04$%hash%.json":{"sha256":"1128944b800d6c07420ddbe33aa14667f2ef6ea0833cddf84b92ca96ac3078d8"},"p/provider-2024-07$%hash%.json":{"sha256":"3582960dd2ea8d007e7e1bfb07938b08ab5a4179332d0ec65424a506332b8197"},"p/provider-2024-10$%hash%.json":{"sha256":"82ea763e72f57755471cf9a4cb2f99f7ef7a15b9675146528fb041a4345d3df1"},"p/provider-2025-01$%hash%.json":{"sha256":"f11d8fd77adedb70d261f92a09242b68ab67019920f6ec4fb8868bca6ab098aa"},"p/provider-archived$%hash%.json":{"sha256":"8bb3f3566d1b440250f124cb7e56479912c1ebc3471ac2924bf94382101d06a4"},"p/provider-latest$%hash%.json":{"sha256":"d2d84dcbc41a33a96cc1a39c91a29861f33e93ec0c1086c04754663eaad831c5"}}}

How do I make curl understand that it should work with https?

OpenCart 4.x: AJAX request returns “Invalid token session” despite valid user_token

I’m developing a custom OpenCart 4.x module that adds a button to the order page to log order data via AJAX. The button makes a GET request to my custom controller, but I’m getting an “Invalid token session” error despite passing a valid user_token.

Button in order_info.twig:

$('#log-order-button').on('click', function() {
    const orderId = '{{ order_id }}';
    
    $.ajax({
        url: 'index.php?route=extension/module/log_order/log&user_token={{ user_token }}&order_id=' + orderId,
        type: 'GET',
        dataType: 'json',
        success: function(json) {
            // handle response
        },
        error: function(xhr, status, error) {
            // handle error
        }
    });
});

Controller

<?php
namespace OpencartAdminControllerExtensionModule;

class log_order extends OpencartSystemEngineController
{
    public function log(): void
    {
        $json = array();

        // Check if user is logged in and has permission
        if (!isset($this->request->get['user_token']) || !$this->user->isLogged()) {
            $json['error'] = 'Permission denied or not logged in.';
        } elseif (!$this->user->hasPermission('modify', 'sale/order')) {
            $json['error'] = 'You do not have permission to modify orders.';
        } else {
            // Process order logging
        }

        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }
}

When I click the button, the AJAX request goes to:
http://localhost/admin123/index.php?route=extension/module/log_order/log&user_token=bcaa4bb96fb680351565d57951b2ef79&order_id=2

But instead of reaching my controller, I get “401 Unauthorized”
What I’ve Tried:

  • Verified user_token: The token is being passed correctly from the template
  • Session check: The user is logged in and can access other admin pages
  • Permission check: The user has modify permissions for orders
  • Route verification: The controller file exists in the correct location

OpenCart 4.1.0.3

SAP Fiori UI5 / I want to attach a custom Filter to every batch request assigned to a List Report (Analytical Table)

I am currently working on a standard Fiori Elements App. I use a List Report with an Analytical Table. My requirement is quite straightforward. I use a custom Data Provider in the backend that works perfectly with oData v4 but is also able to handle some custom functions via a filter fields.

Since I don’t want the filter to be part of the FilterBar of the Page and basically not be visible to the user, I want to directly attach it to the data binding of the table. The goal is that every batch request related to the Table automatically contains that custom filter.

Many Thanks in Advance!

Handle “onclick” button event in Maui Webview with HybridWebView

Handle “onclick” button event in Maui Webview with HybridWebView

I am writing a mobile application that works with a specific website. There are many buttons on this website and I need to handle the “onclick” events of these buttons.
For this, I tried to injected an eventlistener into the html when the site was navigated. I want to send a message to my application with the “onclick” event:

await webView.EvaluateJavaScriptAsync("window.addEventListener("HybridWebViewMessageReceived", function(e) {});" +
"var btns=document.querySelectorAll('button,input[type=button],input[type=submit]');" +
"for(var i=0;i<btns.length;i++){btns[i].addEventListener('click',function(e){ window.HybridWebView.SendRawMessage('Hello from JS!!!');});}");

I added a HybridWebView to the xaml section

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="EczasistanMaui.Pages.MedulaPage">
    
    <HybridWebView
    x:Name="hwv"
    DefaultFile="{Binding DefaultUrl}"
    RawMessageReceived="OnRawMessageReceived" />

</ContentPage>

But I can’t get any alert from here.

 private async void OnRawMessageReceived(object sender, HybridWebViewRawMessageReceivedEventArgs e)
    {
        // Event argument holds the message
        await DisplayAlert("Raw Message Received", e.Message, "OK");
    }

Where am I doing wrong?

Why does parent folder disappear from Azure Blob Storage when all child blobs are deleted?

I’m using Azure Blob Storage, and I understand that folders are simulated using blob names with / delimiters — there’s no real folder hierarchy.

Scenario:
I have a virtual folder structure like:
aman/verma/file.txt

I also have an explicitly created blob:
aman/verma/ (zero-byte blob to simulate folder)

After deleting all blobs under the prefix aman/verma/ — including the zero-byte blob aman/verma/ and file.txt — I noticed:

✅ The virtual folder aman/verma/ disappears — expected.
❌ The parent folder aman/ also disappears from listings if it had no other content, even though I never explicitly deleted aman/.

My question:
Why does the aman/ (parent folder) disappear from listings after deleting all blobs under aman/verma/, even if I never deleted aman/?

Is Azure automatically excluding aman/ from listings if it’s empty?

Does Azure treat zero-byte blobs like aman/ as ignorable unless they prefix other blobs?

How can I retain visibility of parent folders like aman/ even if all their subfolders/files are deleted?