input type=number does not change on scroll

I have a simple number input element:

<input type="number" id="test" min="0" max="100" value="50">

Earlier I could change the value of the element just by scrolling inside the input element. But I could not do that anymore with Chrome version 100. Is this some kind of bug in Chrome or has something changed in the recent version of Chrome?

Also, I noticed if I add a blank event listener to that element then it works properly in Chrome:

document.getElementById('test').addEventListener('wheel', () => { })
<input type="number" id="test" min="0" max="100" value="50">

How to a hide single line in ggplotly grouped time series graph by default? (plotly,R,Javascript)

Plotly has this nice function to hide a plot, if you click on its name in the legend. The legend items turns grey and the line only appears again, if we click on the legend item again.

Consider you want to deploy a shiny app, where the user can look at the time series and additionally he can look at the series trend seasonality etc. in the same plot.

I want initially only the series to be displayed in the rendered ggplotly object, when the user opens the app. All other diagnostic plots like Trend (in my reprex) and seasonality should be hidden by default. Only when I click on the legend item Trend (reprex), the trend line should additionally appear.

I know how to do this in shiny, with shiny functions, but I want to be able to solve it with plotly or javascript functionality in the way I mentioned above.

reprex code (try to hide the line “Trend” by default):

library(plotly)
library(lubridate)
library(ggplot2)
set.seed(42)
data <- tibble(id = c(rep("A",24)),
               value = c(cumsum(rnorm(12)), seq( 1, 7, length.out = 12)),
               date = rep(c(ymd("2013-01-01")+ months(0:11)),2),
               label = c(rep("Series",12),rep("Trend", 12))
)
p <- ggplot(data, mapping = aes(x= date, y= value, color = label)) +
            geom_line()  +
            xlab("")
ggplotly(p) %>% layout(legend=list(y = -0.2,
                                   xanchor = 'left',
                                   yanchor = 'bottom',
                                   orientation = 'h')) 

Updating & Patching game files

i have a problem, im making a game launcher and i want to add an update function. The idea is that this update function checks differences in files and download only the changed ones or new ones as the game weight is more than 1Gb and its not funny to redownload it all.

The thing is that i dont know how to make it. The Launcher was made with electron so i understand it should be ideal to done this in javascript.

Please any help would be great.

I saw a similar post that recommends using bsdiff & bspatch but that only works in .NET.

webpack-dev-server and WASM HMR

I’m trying to make a real time shooter game on the web using ThreeJS and Rapier. Rapier is a physics engine written in rust and can be used in JS using the WASM module. Now in development webpack-dev-server and HMR are really a god given tool, if it works. The RAPIER WASM module gets loaded but from the wrong port. My HTTP server runs on http://localhost:8080 but the devserver on -:9000. The fetch mechanism that webpack uses to get the WASM doesn’t configure the port for the fetch. Is this a bug or misconfiguration on my end?

My webpack.config.js:

const dotenv = require('dotenv');
dotenv.config();

const path = require('path');
const zlib = require('zlib');

const CompressionPlugin = require('compression-webpack-plugin');
const ThreadsPlugin = require('threads-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const WebpackBar = require('webpackbar');
const { WebpackManifestPlugin: ManifestPlugin } = require('webpack-manifest-plugin');
const TerserPlugin = require('terser-webpack-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');

const DEBUG = process.env.NODE_ENV !== 'production';
const FILENAME = DEBUG ? '[name]' : '[name].[contenthash]';
const CHUNK_FILENAME = DEBUG ? '[name]' : '[id].[contenthash]';

module.exports = {
    mode: DEBUG ? 'development' : 'production',

    entry: { bundle: path.join(__dirname, 'resources/js/bundle.js') },

    output: {
        path: path.join(__dirname, 'public'),
        filename: FILENAME + '.js',
        chunkFilename: CHUNK_FILENAME + '.js',
        publicPath: '',
        clean: true,
    },

    module: {
        rules: [
            {
                test: '/.m?js$/',
                exclude: /(node_modules|bower_components)/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env']
                    }
                }
            },
            { test: /.(frag|vert)$/, use: 'raw-loader' },
            {
                test: /.(sa|sc|c)ss$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    { loader: 'css-loader', options: { importLoaders: 2 } },
                    'postcss-loader',
                    'sass-loader',
                ]
            },
            { test: /.(png|svg|jpg|jpeg|webm|gif)$/i, type: 'asset/resource' },
            { test: /.(woff|woff2|eot|ttf|otf)$/i, type: 'asset/resource' },
            { test: /.svelte$/, use: { loader: 'svelte-loader', options: {
                emitCss: false,
                hotReload: DEBUG,
                compilerOptions: { dev: DEBUG },
                hotOptions: {
                    preserveLocalState: false,
                    noReload: false, // prevent reload after fatal error
                    acceptAccesssors: true,
                    acceptNamedExports: true
                }
            } } },
            { test: /node_modules/svelte/.*.mjs$/, resolve: { fullySpecified: false } }
        ]
    },

    plugins: [
        new CopyPlugin({ patterns: [
            // { from: './resources/images', to: 'images' },
            { from: './resources/textures', to: 'textures' },
            { from: './resources/scenes', to: 'scenes' },
        ] }),
        new ManifestPlugin(),
        new MiniCssExtractPlugin({
            filename: FILENAME + '.css',
            chunkFilename: CHUNK_FILENAME + '.css'
        }),
        // new ThreadsPlugin(),
        new WebpackBar(),
    ].concat(DEBUG ? [] : [
        new CompressionPlugin({
            filename: '[path][base].gz',
            algorithm: 'gzip',
            test: /.(js|css|html|svg)$/,
            threshold: 10240,
            minRatio: 0.8,
        }),
        new CompressionPlugin({
            filename: '[path][base].br',
            algorithm: 'brotliCompress',
            test: /.(js|css|html|svg)$/,
            compressionOptions: {
                params: {
                    [zlib.constants.BROTLI_PARAM_QUALITY]: 11,
                },
            },
            threshold: 10240,
            minRatio: 0.8,
        })
    ]),

    optimization: {
        minimize: true,
        minimizer: [ new TerserPlugin(), new CssMinimizerPlugin() ],

        splitChunks: {
            cacheGroups: {
                vendor: {
                    test: /[\/]node_modules[\/]/,
                    name: 'vendor',
                    chunks: 'all'
                }
            }
        }
    },

    devServer: {
        port: 9000,
        static: path.join(__dirname, 'public'),
        hot: true,
        client: {
            overlay: {
                errors: true,
                warnings: false,
            },
            progress: true,
            reconnect: 10,
            webSocketURL: {
                hostname: 'localhost',
                port: 9000,
            }
        },
        compress: true
    },
    
    devtool: DEBUG ? 'inline-source-map' : false,

    experiments: {
        asyncWebAssembly: true
    }
};

I’ve googled a fair bit for solutions but so far I haven’t found anything that looks like my particular issue.

Stubbing nested component with its own nested components in angular test

I have a component (Parent), which has a custom nested component (ChildOne) which has its own custom nested component (ChildTwo). I want to unit test Parent, so I have created stubs for the children. However, stubbing a component seems to cause it not to have any children, so ChildTwo is missing which is needed for my test. Is there a way I can stub a component, while keeping it’s children?

HTML:

<app-child-one>
  <p></p>
  <div>
    <app-child-two (click)="onClick($event)">
    </app-child-two>
  </div>
</app-child-one>

Typescript:

@Component({
    selector: 'app-parent',
    templateUrl: './parent.component.html',
    styleUrls: ['./parent.component.scss']
})
export class ParentComponent {

    onClick(event: Event) {
        console.log(event);
    }
}

Spec:

@Component({ selector: 'app-child-one', template: '' })
export class ChildOneStubComponent {

}

@Component({ selector: 'app-child-two', template: '' })
export class ChildTwoStubComponent {

}

describe('ParentComponent', () => {
  let component: ParentComponent;
  let fixture: ComponentFixture<ParentComponent>;

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [
        ParentComponent, ChildOneStubComponent, ChildTwoStubComponent
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ParentComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeDefined();
  });

  it('calls onClick when child two is clicked', () => {
    const childTwo = fixture.debugElement.query(By.css('app-child-two'));
    childTwo.triggerEventHandler('click', null); // <-- this fails, child two is null

    expect(...);
  });

Creating a time slider with mapbox gl js

I want to filter the yield by time with the help of a slider in my application that I developed in Apache netbeans. When I run this html file with vs code, I can see the yield on the frontend, but when I run it with apache netbeans, I can’t get the yield. What could be the reason?………………………………………………………………………………………………………………………………………………………………….

<html>
<head>
    <meta charset='utf-8' />
    <title>Pride Parade Map</title>
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
    <link href="https://api.mapbox.com/mapbox-gl-js/v2.7.0/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v2.7.0/mapbox-gl.js"></script>
    <style>
        body { margin:0; padding:0; }
        #map { position:absolute; top:0; bottom:0; width:100%; }
    </style>
</head>
<body>
    <style>

.map-overlay {
    font: 12px/20px 'Helvetica Neue', Arial, Helvetica, sans-serif;
    position: absolute;
    width: 25%;
    top: 0;
    left: 0;
    padding: 10px;
}
.map-overlay .map-overlay-inner {
    background-color: #fff;
    box-shadow:0 1px 2px rgba(0, 0, 0, 0.20);
    border-radius: 3px;
    padding: 10px;
    margin-bottom: 10px;
}

        .map-overlay input {
            background-color: transparent;
            display: inline-block;
            width: 25%;
            position: absolute;
            margin: 0;
            cursor: ew-resize;
            bottom: 30px;
        }
        </style>


<div id='map'></div>

<div class='map-overlay top'>
    <div class='map-overlay-inner'>
       
        <label id='time'></label>
        <input id='slider' type='range' min='0' max='17' step='1' value='0' />
    </div>
    
</div>

<script src="https://d3js.org/d3.v4.min.js"></script>

<script>
mapboxgl.accessToken = 'pk.eyJ1IjoidHVnY2UtdGF5IiwiYSI6ImNrd3o3dTM1eTBmaWIycXB6bHlwb3djb2UifQ.GiUzrj8Wtb2JcDYcc3Xk6w';
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/light-v10',
    center: [35, 40],
    zoom: 5
});

var times = [
'1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    '10',
    '11',
    '12'
];

function filterBy(time) {
    var filters = ['==', 'time', parseInt(times[time])];
    // id of layer applied,, filters
    map.setFilter('time-circles', filters);
   

    // Set the label to the month
    document.getElementById('time').textContent = times[time]; 
}

map.on('load', function() {
    d3.json('time.geojson', function(data) {

        map.addSource('time-parades', {
            'type': 'geojson',
            'data': data
        });

        // is it possible to use < or > in expressions?
        map.addLayer({
            'id': 'time-circles',
            'type': 'circle',
            'source': 'time-parades',
            'paint': {
                'circle-color': [
                    'interpolate',
                    ['linear'],
                    ['get', 'time'],
                    5, '#9400D3',
                    10, '#0000FF',
                    15, '#00FF00'
                    
                ],
                'circle-opacity': 0.75,
                'circle-radius': [
                    'interpolate',
                    ['linear'],
                    ['get', 'time'],
                    5, 5,
                    15, 5
                ]
            }
        });

       

        filterBy(0);

        document.getElementById('slider').addEventListener('input', function(e) {
            var time = parseInt(e.target.value, 10); // need to change the 10
            filterBy(time);
        });
    });
});
</script>```

Defining a generic Typescript function that will take unknown parameters

I have a custom input component that has an onChange method.

type CustomInput = {
  dataType: string;
  onChange: (data: Record<string, unknown) => unknown; // this is causing issues, might need generic type
}

Usage:

type MyProp = {
  name: string;
  date: Date;
}

<CustomInput dataType="myPropData" onChange={(prop: MyProp) => { /* do stuff with prop */ }} />

Inside of the component, we perform some logic then call onChange(data). data will be different based on what dataType is passed.

Another usage may be

type MyOtherProp = {
  name: string;
  title: string;
  count: number;
}

<CustomInput dataType="myOtherPropData" onChange={(prop: MyOtherProp) => { /* do stuff with other prop */ }} />

Issue:

Because MyProp and MyOtherProp are not really Record<string, unknown>, I’m getting errors.

It’s clear why there are errors and I’m sure the answer is “use generics”, but it’s unclear to me how I can set the proper type on the onChange method. Using unknown params also throws errors and I’d like to avoid using any.

Remove multiple elements from array by id in vue

I have an array of devices. i want to remove all elements whose tagid is (4e1d8667-fc7e-f882-7951-6b4324c2b354)

Devices:[
{
    "id": "eaff0fce-d372-1321-724f-c32708b41fc3",
    "tagid": "4e1d8667-fc7e-f882-7951-6b4324c2b354",
    "IMSI": "3453453453",
    "IMEI": "",
    "Alias": "",
    "MNO": "",
    "Device": ""
},
{
    "id": "2f141436-0d96-d3de-fad4-be595df28143",
    "tagid": "3729c031-084c-d72f-0271-e54cd1e141a6",
    "IMSI": "345345345345345",
    "IMEI": "",
    "Alias": "",
    "MNO": "",
    "Device": ""
},
{
    "id": "54792e43-f284-e004-9892-7582c32afeeb",
    "tagid": "4e1d8667-fc7e-f882-7951-6b4324c2b354",
    "IMSI": "34534534534534534545345345",
    "IMEI": "",
    "Alias": "",
    "MNO": "",
    "Device": ""
},
{
    "id": "d9145780-d26f-f8d1-914e-d5106ebaab94",
    "tagid": "3729c031-084c-d72f-0271-e54cd1e141a6",
    "IMSI": "34534534534534534534",
    "IMEI": "",
    "Alias": "",
    "MNO": "",
    "Device": ""
}

]

Having an error in running a prisma command

I’m new to Prisma and Ts.ED framework, I’m trying to build a simple crud operation using them to understand the flow. I have Prisma installed globally(although, not recommended) and also invoked it globally using this command “prisma”. but, when I ran this command

"prisma generate" 

I have this error:

Error: Generator at tsed-prisma could not start:
/bin/sh: tsed-prisma: command not found. 

The error wasn’t there initially but started when I shut down my system. I have deleted the node modules and installed Prisma again, and still, the error persists. Please, I need help to resolve this error. Thank you

UseRef to trigger a styled tag

Does it make sense to useRef to trigger a styled tag which is loaded
in application via a custom librabry?

Would be a good practice to use querySelector instead of useRef? [Trying to overwrite the styling which comes from a custom library something similar to Material UI]

document.querySelector(StyleTagToChange).appendChild(document.createTextNode(newCSSRule)

TypeError: target.roles.map is not a function

I am trying to make a userinfo command, however, under the Roles bit, it errors saying:
TypeError: target.roles.map is not a function

Expected result:

console.log(target.roles.map(r => `${r}`).join(" ,"))

It will log out the roles that they have in the specific server.

Actual result:

console.log(target.roles.map(r => `${r}`).join(" ,")

It will log: TypeError: target.roles.map is not a function

What have I tried?

I tried doing:

console.log(target.roles.cache.map(r => `${r}`).join(" ,"))

Still logged the same thing but it has cache before the .map.

Code:

const {Client, CommandInteraction, MessageEmbed} = require('discord.js')
const moment = require('moment')

module.exports = {
    name: 'userinfo',
    description: "show the info type",
    type: 'CHAT_INPUT',
    options: [
        {
            name: 'target',
            description: 'target to get info on',
            type: 'USER',
            required: false
        }
    ],
    default_permission: true,
/**
 * 
 * @param {Client} client 
 * @param {CommandInteraction} int 
 * @param {String[]} args 
 */
    run: async(client, int, args) => {
        const target = int.options.getMember('target') || int.member

        let status;
        let statusEmoji
        switch (target.presence.status) {
            case "online":
                status = 'Online'
                statusEmoji = client.emojis.cache.get(`960628219608985650`)
                break;
            case "idle":
                status = 'Idle'
                statusEmoji = client.emojis.cache.get(`960628219621572638`)
                break;
            case "dnd":
                status = 'Do not Disturb'
                statusEmoji = client.emojis.cache.get(`960628123806879744`)
                break;
            case "offline":
                status = 'Offline'
                statusEmoji = client.emojis.cache.get(`960628219550249071`)
                break;
        }     

        const embed = new MessageEmbed()
        .setColor('YELLOW')
        .setTitle(`${target.user.tag}'s Info`)
        .setThumbnail(target.user.displayAvatarURL({ dynamic: true }))
        .addFields(
            {
                name: ':bust_in_silhouette: | Username:',
                value: `${target.user.username}`,
                inline: false
            },
            {
                name: ':busts_in_silhouette: | Nickname (Guild Username):',
                value: target.nickname ? `${target.nickname}` : `Same as discord username!`,
                inline: false
            },
            {
                name: ':hash: | Discriminator:',
                value: `${target.user.discriminator}`,
                inline: false
            },

            {
                name: ':id: | User ID:',
                value: `${target.user.id}`,
                inline: false
            },

            {
                name: `${client.emojis.cache.get('960628123806879744')} | Current Status:`,
                value: `${statusEmoji} | ${status}`,
                inline: false
            },

            {
                name: `:video_game: | Activity:`,
                value: target.presence.activities ? target.presence.activities[1].name : "This user isn't on activity!",
                inline: false
            },
            {
                name: `:new: | Registered at:`,
                value: moment.utc(target.user.createdAt).format('dddd, MMMM Do YYYY, HH:mm:ss'),
                inline: false
            },
            {
                name: `:speech_balloon: | Joined at:`,
                value: moment.utc(target.joinedAt).format('dddd, MMMM Do YYYY, HH:mm:ss'),
                inline: false
            },
            {
                name: `Roles:`,
                value: target.roles.map(r => `${r}`).join(" ,"),
                inline: false
            }
        )
        .setTimestamp()

        int.followUp({ embeds: [ embed ] })
    }
}

Iterating a JSON string with maps in JS

I have been trying to iterate in a JSON that contains a map within a map for hours with no luck…

This is the JSON string:

{“P31”:{“wikibase-entityid”:”Q16603799″},”P227″:{“string”:”1084653095″},”P1001″:{“wikibase-entityid”:”Q183″},”P1448″:{“monolingualtext”:”Verordnung über Sicherheit und Gesundheitsschutz bei der Verwendung von Arbeitsmitteln”},”P1813″:{“monolingualtext”:”Betriebssicherheitsverordnung”},”P7677″:{“string”:”betrsichv_2015″},”P580″:{“time”:”+2002-10-03T00:00:00Z”},”P2671″:{“string”:”/g/1224z0c0″},”P9696″:{“string”:”11477″}}

Image for an easy visual reference:
enter image description here

I basically want to create a loop inside which I’ve got access to the property (PXXX, first thing), the type of the property (key in the inner map) and the value of the property (value in the inner map).

I have tried to convert the string to a Map using “new Map(JSON.parse(jsonStr))”, “new Map(Object.entries(jsonStr))” and other with no luck.

Additionally, I tried to iterate inside it with a “for (var key in obj)” and with a “myMap.forEach((value_propertyInfo, key_propertyName) => {…}” without luck either.

Some times it looks like I am iterating char by char, while others simply throw an error saying that the map is not iterable.

Does anybody know what I should use instead?

Thanks!

Mouse event for download functionality not working in IE

I am trying to implement a functionality to download a pdf file using javascript. My code is not working in IE 11. Any leads are much appreciated. Below is the code I am using.

saveByteArray: function(reportName, byte) {
     
var bytes = new Uint8Array(byte);
var blob = new Blob([bytes], {type: "application/pdf"});
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
var fileName = reportName;
link.download = fileName;
link.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));

}