How do I hide all objects in a “source” (geoJson) in MapBox GL JS based on whether their description matches my string?

I’ve long tried to implement this feature for my map system, because I have lots of markers loaded in and it’s very useful to be able to enter a string such as “abc” into an input field to “filter out” (visually hide) all the ones that don’t contain that string inside of their description/title.

A few weeks ago, I found this example: https://docs.mapbox.com/mapbox-gl-js/example/filter-markers/

Unfortunately, they do it in a completely silly manner which doesn’t apply to my situation, so I was only able to grab the basic input part from their example. Then I got stuck. I tried countless things and after many hours of work, I at least have finally managed to be able to loop through my loaded-in geoJson “sources” (containing all the markers). So, I have this:

filterInput.addEventListener('keyup', (e) =>
{
    const value = e.target.value.trim().toLowerCase();

    let sources = Object.entries(map.getStyle().sources);

    for (const source of sources)
    {
        if (source[1].type == 'geojson')
        {
            console.log(source[0]); // The name of the source, for example "my nostalgic visited places".
            
            // Here, I'm trying to loop through all the inidividual markers of this geoJson "source" and, based on "value" and its title/description, either visually hide or display it. This is the part I just cannot figure out.
        }
    }
});

I obviously need to loop through the markers inside each geoJson inside my sources for loop, but how? I don’t know:

  1. How to actually loop through those in the first place. I can’t find any in the source object.
  2. How to tell MapBox GL JS to hide/show them individually. The example that they have just bulk hide/show entire layers/sources, which is irrelevant.

If it helps, console.log(source[1]); causes this kind of output:

{type: 'geojson', data: 'http://127.0.0.1/mymap/geoJSON/my nostalgic visited places.geojson'}
data: "http://127.0.0.1/mymap/geoJSON/my nostalgic visited places.geojson"
type: "geojson"
[[Prototype]]: Object

Disappointingly, the [[Prototype]]: Object does not seem to contain any neat array of markers, as I first assumed would be the case. I don’t know what to make of it.

Blocking and non blocking code in parallel

I need to be able to run some code that is going to be blocking and some other code that will then, when blocked, start some other actions.

The usecase is the follows:

I have a file called index.ts running an express and socket server

I have a testfile called test.spec.ts that needs to be able to start the express server and then initiate some commands for running tests either via HTTP request or socket message(I would prefer HTTP)

The only way I found to keep the webserver alive is instanciating it with

import { spawnSync } from 'child_process';

spawnSync('ts-node', ['path/to/index.ts"], { cwd: "path/to/workdir"});

which will block until the child process is killed( could be up to 30min later).

Is there a way to split into two processes, one that gets blocked when starting it and one continuing to work that exposes some functions for interactions with the test file?

My target would look like this:

// index.ts

import * as express from "express";
const app = express();

const port = 3000;

app.get('/', (req, res) => {
    res.send('Hello World!');
});

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`);
});
// test.spec.ts

import { spawnSync } from 'child_process';

describe("Test",()=>{

  it("Test", async ()=>{

    // create somehow a child process that should block
    const childProcess = ...
    childProcess.do(spawnSync('ts-node', ['path/to/index.ts'], {cwd: 'path/to/workdir'}) //should block now

    // the following code should run in parallel
    await new Promise(r => setTimeout(r, 5000)); //wait some time until the webserver is ready

    fetch('http://localhost:3000').then((ret)=>{
      expect(ret,'to be Hello World').to.contain('Hello World!");
    })
    ... // more tests
  });
});

How to replace a substring between two indexes ignoring HTML tag in JavaScript

I want to replace a substring in a text between two indexes. But I want to ignore any HTML tag when counting the index.

For example

If the text is the best kitchen knife I want to replace the substring from index 4 to 8 with ‘nice’ so the output should be the nice kitchen knife

But if the text is in HTML tag like
<li>the best kitchen knife</li>
or
<li>the <span>best</span> kitchen knife</li> and given indexes are 4 and 8, it should count from ‘the’ not from <li>. So the expected output should be <li>the <span>nice</span> kitchen knife</li>

I used the following code but it doesn’t work as I’m expecting.

function replaceBetween(origin, startIndex, endIndex, insertion) {
    return (
        origin.substring(0, startIndex) + insertion + origin.substring(endIndex)
    );
}

Usage:

replaceBetween("<li>the <span>best</span> kitchen knife</li>", 4, 8, "nice");

Output:

<li>nice<span>best</span> kitchen knife</li>

Expected Output:

<li>The <span>nice</span> kitchen knife</li>

How to solve Master Mind using Genetic Algorithm

Welcome,
I had to make a bot for the mastermind game to solve it using AI,
well Donald Knuth’s algorithm is simple, but It takes more moves and is not efficient up to me.
So, after researching I found a paper and its code on solving mastermind with genetic algorithm.
But that paper is like a benchmark and doesn’t explain, as well as I don’t understand python!
Hence looking for a code on other languages (my preferred language is pure js),I found:

Link Language Disadvantage
LINK1 Javascript with Jquery Jquery is a problem more than that the three modes are confusing (I want only Human vs AI)
LINK2 React js React js is a problem more than that see the [My problem] below
LINK3 Java Again, see the [My problem] below

[My problem]=The way it calculates the output (black and white coins) is different
That is as you can see in the LINK1,

Output for
Guess:[2, 2, 5, 2]
Answer:[4, 5, 3, 5]

Output:-
Correct coin in, Correct position: 0
Correct coin in, Wrong position: 1
The above output is correct,


But the below output which is got for LINK2 & LINK3 code is wrong
Output for
Guess=[2, 2, 5, 2]
Answer=[4, 5, 3, 5]

Output:-
Correct coin in, Correct position: 0
Correct coin in, Wrong position: 2



I got these outputs by extracting the code part that the algorithm uses to check

Correct code, extracted from link1

prediction = [2, 2, 5, 2];
answer = [4, 5, 3, 5];
function testCode (combination, solution) {
    NUM_FIELDS = solution.length;
    var a = 0;
    var b = 0;
    var marked = [0, 0, 0, 0];
    for(var i = 0; i<NUM_FIELDS; i++) {
        if(combination[i] == solution[i]) {
            a++;
            marked[i] = 1;
        }
    }
    for(var i = 0; i<NUM_FIELDS; i++) {
        if(combination[i] != solution[i]) {
            for(var j = 0; j<NUM_FIELDS; j++) {
                if(i != j && 0 == marked[j] && combination[i] == solution[j]) {
                    b++;
                    marked[j] = 1;
                    break;
                }
            }
        }
    }   
    return [a, b];
}
console.log(testCode(prediction,answer));

Wrong code, extracted from link2 & link3

prediction = [2, 2, 5, 2];
answer = [4, 5, 3, 5];
function getMoveScore(input, answer) {
  let correctColorLocation = 0;
  let correctColorWrongLocation = 0;
  // correct color correct location
  for (let i = 0; i < input.length; i++) {
    if (input[i] === answer[i]) {
      correctColorLocation += 1;
    }
  }
  // correct color
  for (let i = 0; i < answer.length; i++) {
    var inputSet = new Set(input);
    if (inputSet.has(answer[i])) {
      correctColorWrongLocation += 1;
    }
  }
  correctColorWrongLocation -= correctColorLocation;
  const incorrect = 4 - correctColorWrongLocation - correctColorLocation;
  return [correctColorLocation,correctColorWrongLocation];
}
console.log(getMoveScore(prediction, answer));


Anyway this is not the problem, Main problem is

  • Everything is ok in LINK1 but the 3 modes are confusing
  • I am looking for a simple code that is console-based(not graphical),explanation&commented code is appreciated but not needed

Calculating HTML input using JavaScript

Hi I am trying to calculate the percentage using the input from the HTML input

let timeSpend = document.querySelector(".time_spend")

var fSubject = (50/timeSpend)*100;
var sSubject = (25/timeSpend)*100;
var tSubject = (25/timeSpend)*100;
window.alert(fSubject);

This is my HTML input that I have the type of number but I don’t know why it still not working

<input
          type="number"
          id="text-box"
          class="time_spend"
          placeholder="How much time do you have?"
        />

ReactJS vs Flutter

Which is better and which will be the best one in the future?Some said ‘Flutter already overtaked the whole reactJS’ and others said ‘It is only a matter of time that reactJS will overtake flutter again.’. It’s best to learn flutter or reactJS or both?

How does an array of numbers and its sorted version strictly equal to each other? [duplicate]

Let’s say we have an array of numbers in Javascript:

const arr = [1,3,2,6,5,3];

We sort it using the native sort method:

arr.sort(); // OR arr.sort((a, b) => a - b)

Now how do the unsorted and sorted array equal to one another?

console.log(arr === arr.sort()) // logs true 

I am aware the sort method does not create a new array, so they would both point to the same address on the memory.

However, their element order is different, and since arrays are list-like objects, with enumerable indices, the order of elements do matter unlike objects.

So, if all above is true, how are they strictly equal?

const arr = [1, 3, 2, 6, 5, 3];
arr.sort(); // OR arr.sort((a, b) => a - b)
console.log(arr === arr.sort()) // logs true

Exclude directory from webpack copy in vue CLI

I have a Vue3 project made with Vue CLI 5.0.1

My setup has a public folder where I have static assets that I need to serve, but it is very heavy (1GB of assets) so when I launch the npm run serve command I get the build stuck on [92%] sealing (asset processing copy-webpack-plugin).

I need so to exclude the public/resources directory from the copy-webpack-plugin.

I tried with the following config added in my vue.config.js:

    chainWebpack: (config) => {
    config.plugin("copy").tap(([options]) => {
      options[0].ignore.push("resources/**");
      return [options];
    });
 }

But I get this error:

ERROR TypeError: Cannot read property 'ignore' of undefined

Hide/show Children on checkbox backend admin

I am trying to Hide/show large Children based on checkbox option backend admin through css.I tried following

ul.categorychecklist input[type=”checkbox”]:checked +label + .selectit {
    display: block!important;
}

ul.categorychecklist ul {
    margin-top: 15px;
    display: none;
}
<label class="selectit"><input value="464" type="checkbox" name="tax_input[brand_year_model][]" id="in-brand_year_model-464"> AUDI</label>
<ul class="children">

<li id="brand_year_model-500" class="popular-category"><label class="selectit"><input value="500" type="checkbox" name="tax_input[brand_year_model][]" id="in-brand_year_model-500"> A3</label> <ul class="children">

<li id="brand_year_model-1909"><label class="selectit"><input value="1909" type="checkbox" name="tax_input[brand_year_model][]" id="in-brand_year_model-1909"> 2019</label></li>

<li id="brand_year_model-1075" class="popular-category"><label class="selectit"><input value="1075" type="checkbox" name="tax_input[brand_year_model][]" id="in-brand_year_model-1075"> 2020</label></li>

<li id="brand_year_model-1352" class="popular-category"><label class="selectit"><input value="1352" type="checkbox" name="tax_input[brand_year_model][]" id="in-brand_year_model-1352"> 2021</label></li>

<li id="brand_year_model-1629"><label class="selectit"><input value="1629" type="checkbox" name="tax_input[brand_year_model][]" id="in-brand_year_model-1629"> 2022</label></li>
    </ul>
</li>



    </ul>
</li>
</ul>

But i am unable to do so in backend.With a long list it looks untidy.Kindly see.Looking for show category children s only when checked

typescript inheritance human data

Create class “Human” which has two protected members:
 name
 constructor() : this initialises name Create another class “Employee” which extends “Human”
and have three members:
 department
 constructor() : this initialises both name and department
 getInfo() : this dispalys name and department of the employee

Discord JS: Shutdown bot via slash command

I have the following command.

const { SlashCommandBuilder } = require("@discordjs/builders")

module.exports ={
    data: new SlashCommandBuilder()
    .setName("shutdown")
    .setDescription("Shutdown the bot"),
    async execute(interaction) {
        interaction.reply("Shutting down").then(() => {
            client.destroy();
        })
    }
}

The command should shutdown the bot. The only thing it is doing at the moment is crashing the bot because ReferenceError: client is not defined.
I appreciate any help

How to call exact same function on two different html classes?

All am trying to do is, just incorporate a function which shorts the paragraphs and add “Show more” and “Show less” when show more is already opened. Its working on single html element but when i use it on another one, it just uses the two ones option to the first one.

Here is my function:

! function(e) {
    "object" == typeof module && "object" == typeof module.exports ? e(require("jquery"), window, document) : e(jQuery, window, document)
}(function(e, s, t, n) {
    e.fn.shorten = function(s) {
        "use strict";
        var n = {
            mode: 1,
            showChars: 100,
            minHideChars: 10,
            ellipsesText: "...",
            moreText: 'Show more',
            lessText: 'Show less',
            onLess: function() {},
            onMore: function() {},
            errMsg: null,
            force: !1
        };
        var more_button = '<button type="button" style="width: 100%;background-color: white;height: 30px;border-color: black;margin-top: 20px;margin-bottom: 20px;color: black;" class="btn btn-lg btn-primary"><span><span>Show more</span></span></button>';
        var less_button = '<button type="button" style="width: 100%;background-color: white;height: 30px;border-color: black;margin-top: 20px;margin-bottom: 20px;color: black;" class="btn btn-lg btn-primary"><span><span>Show less</span></span></button>'
        return s && e.extend(n, s), e(this).data("jquery.shorten") && !n.force ? !1 : (e(this).data("jquery.shorten", !0), e(t).off("click", ".morelink"), e(t).on({
            click: function() {
                var s = e(this);
                var zz = n.mode === 2 ? more_button : n.moreText;
                var zx = n.mode === 2 ? less_button : n.lessText;
                return s.hasClass("less") ? (s.removeClass("less"), s.html(zz), s.parent().prev().prev().show(), s.parent().prev().hide(0, function() {
                    n.onLess()
                })) : (s.addClass("less"), s.html(zx), s.parent().prev().prev().hide(), s.parent().prev().show(0, function() {
                    n.onMore()
                })), !1
            }
        }, ".morelink"), this.each(function() {
            var s = e(this),
                t = s.html().trim(),
                r = t.length,
                o = t.substr(n.showChars, r - n.showChars).indexOf(" "),
                i = n.showChars + o;
            if (r > i + n.minHideChars) {
                var l = t.substr(0, i);
                if (l.indexOf("<") >= 0) {
                    for (var a = !1, h = "", c = 0, f = [], u = null, d = 0, p = 0; i >= p; d++) {
                        if ("<" != t[d] || a || (a = !0, u = t.substring(d + 1, t.indexOf(">", d)), "/" == u[0] ? u != "/" + f[0] ? n.errMsg = "ERROR en HTML: the top of the stack should be the tag that closes" : f.shift() : "br" != u.toLowerCase() && f.unshift(u)), a && ">" == t[d] && (a = !1), a) h += t.charAt(d);
                        else if (i >= c) h += t.charAt(d), c++;
                        else if (f.length > 0) {
                            for (j = 0; j < f.length; j++) h += "</" + f[j] + ">";
                            break
                        }
                        p++
                    }
                    l = e("<div/>").html(h + '<span class="ellip">' + n.ellipsesText + "</span>").html()
                } else l += n.ellipsesText;
                var blur_style = (n.mode === 2) ? "-webkit-mask-image: linear-gradient(#fff,#fff,rgba(255,255,255,0));" : "";
                var _temp_button = n.mode === 2 ? more_button : n.moreText;
                var m = '<div class="shortcontent" style="'+ blur_style +'">' + l + '</div><div class="allcontent">' + t + '</div><span><a href="javascript://nop/" class="morelink" style="text-decoration: underline;color:black;">' + _temp_button + "</a></span>";
                s.html(m), s.find(".allcontent").hide(), e(".shortcontent > *:last", s).css("margin-bottom", 0)
            }
        }))
    }
});

And here is how i apply on html :

$('.overview-1477').shorten({
    showChars: 250,
    mode: 1,
    moreText: 'Show more',
    lessText: 'read less'
});
$('.course_content_2544').shorten({
    showChars: 600,
    mode: 2,
}); 

So when mode === 1 then it should show moreText and lessText but when mode === 2 then another design elements are added.

But when i use this on to call for two elements, both the elements work based on last configs.

So i need to tweak the code, to work on different elements but no idea where i have missed. Please help

How can I catch CORS request did not succeed and display it to the user on my frontend?

I’m creating a front-end to a back-end I’ve created. I’ve got my system working where if the back end is online, the front-end displays the requested data from my back-end API. I currently do this using the JavaScript fetch function like this:

fetch("http://localhost:3001/public-key")
.then((response) => response.json())
.then(returnedKey => {
    this.setState({ publicKey: returnedKey })
})
.catch(err => {
    console.log("error")
    this.setState({ publicKey: "Error" })
});

What I want to do is catch the CORS request did not succeed message when my back-end is down and set the state of publicKey to an error so it displays “error” to the user, however the way I’m trying to do it with catch doesn’t seem to be working.

Any insight would be greatly appreciated.

How to change a Javascript object with a dynamic path?

Im trying to change a variable list with newList. The problem is that i dont know how to change the list when it got path added with a function.

Add string to object

Object.byString = function(o, s) {
    s = s.replace(/[(w+)]/g, '.$1'); // convert indexes to properties
    s = s.replace(/^./, '');           // strip a leading dot
    var a = s.split('.');
    for (var i = 0, n = a.length; i < n; ++i) {
        var k = a[i];
        if (k in o) {
            o = o[k];
        } else {
            return;
        }
    }
    return o;
}

Return path

function getPath2(){
   const split = get("path").split('~');
   var newSplit = "";
   for (key in split){
      if(!split[key] == ""){  
        newSplit = newSplit + "."+split[key]+"";
      }
   }
   return newSplit;
   }
//  this works
//  {afas: {…}, fa: {…}, fas: {…}, af: {…}}
console.log(Object.byString(list, getPath2()));

//  this works
// {afas: {…}, fa: {…}, af: {…}, fas: {…}}
console.log(newList);

// This is not working
Object.byString(list, newPath) = newList;

Error I get back:
script.js:420 Uncaught ReferenceError: Invalid left-hand side in assignment
at HTMLLIElement. (script.js:420:32)

Angular: canactivate auth gaurd issue

I am learning angular 13 & i am stuck at point, below is the code

this is my authservice file

export class AuthService {
  loggedIn = false;

  isAuthenticated() {
    const promise = new Promise(
      (resolve, reject) => {
        setTimeout(() => {
          resolve(this.loggedIn);
        }, 800);
      }
    );
    return promise;
  }
}

i am getting this error

this is my auth guard service file

import { Injectable } from '@angular/core';
import {
  ActivatedRouteSnapshot,
  CanActivate,
  Router,
  RouterStateSnapshot,
} from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';

@Injectable()
export class AuthGuardService implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return this.authService.isAuthenticated()
      .then(
        (authenticated: boolean) => {
          if (authenticated) {
            return true;
          } else {
            this.router.navigate(['/']);
          }
        }
      );
    }
}

screenshot of error
enter image description here

Can anybody help me??