Active menu item NOT based on URL but based on a variable

I want to have a Menu with active items on my website. It should be added a class to activate the item. Since the project has cryptic URLs, URL-based solutions are not possible. The text of the respective menu item is shown in the respective page title.

My idea was to compare the pagetitle id="navtopheader" with the text in the menu item. If it is equal, add the menuactive class to the respective menu item.

My HTML looks basically like this:

<div id="navtopheader" class="navtopheader">menu item 1</div>
...
<div class="nav_ebene_2">
   <p>menu item 1</p>
</div>
<div class="nav_ebene_2">
   <p>menu item 2</p>
</div>
...

I can do it actually in an inefficient way:

var headertext = document.getElementById("navtopheader").innerText

var menutext0 = document.getElementsByClassName("nav_ebene_2")[0].innerText
var navlist = document.getElementsByClassName("nav_ebene_2");
if (headertext == menutext0) {
    navlist[0].classList.add("activemenu");
}

var menuitem1 = document.getElementsByClassName("nav_ebene_2")[1].innerText
if (headertext == menuitem1) {
    navlist[1].classList.add("activemenu");
}
...

But since the number of menu items varies across the website, i would get an error message if i include too much/too few menu items.

Is there an appropriate solution? I tried the whole day but didn’t solve the problem. Thank you!

Mocking Controller dependency in Nestjs

I am trying to mock my controller using nestjs createTestingModule and I have added overrider provider to mock the service but it still giving me this error(Screenshot attached screenshot). Kindly help.

I also tried added the other dependencies too but the error is same

Here is my controller.ts file

import {Body, NotFoundException, OnModuleInit, Param, Patch} from "@nestjs/common";
import {BitvavoService} from "./bitvavo.service";
import {DeleteMethod, GetMethod, PostMethod, PatchMethod} from "../../../../global/operations";
import {ApiController} from "../../../../utils/endpoints/api-controller.decorator";
import bitvavo, {BitvavoOrderResponse} from "bitvavo";
import {Repository} from "../../../repository/repository";
import {BitvavoTarget} from "./bitvavo-target";
import {RepositoryFactory} from "../../../repository/repository-factory.service";
import {CollectionNames} from "../../../repository/collection-names";
import {ProducerTargetBindingService} from "../../producer-target-binding/producer-target-binding.service";
import {User, UserClass} from "../../../../utils/endpoints/user.decorator";
import {Permissions} from "../../../../utils/endpoints/permissions.decorator";
import {Permission} from "../../../../utils/permission.enum";
import {EncryptionService} from "../../../encrypt/encrypt.service";
import {
  BitvavoBalanceDto,
  BitvavoPlaceOrderDto,
  BitvavoSingleTargetResponse,
  CreateBitvavoTargetDto,
  UpdateBitvavoTargetDto,
  ChangeBitvavoTargetMode,
  SellSingleBot
} from "./bitvavo-dtos";
import {toTargetDto} from "../target-dto";
import {ApiBotService} from "../../signal-producers/implementers/api-bot/api-bot.service";

const getBalances = async function (target: BitvavoTarget, decryptedKey: string, decryptedSecret: string) {
  try {
    const client = createBitvavoClient(decryptedKey, decryptedSecret);
    return (await client.balance({})).map(balanceToDto);
  } catch (e) {
    return null;
  }
};

@ApiController("signal-targets/bitvavo")
export class BitvavoController implements OnModuleInit {
  private repository: Repository<BitvavoTarget>;

  async onModuleInit() {
    this.repository = await this.repositoryFactory.create(BitvavoTarget);
  }

  constructor(
    private bitvavoService: BitvavoService,
    private repositoryFactory: RepositoryFactory,
    private producerTargetBindingService: ProducerTargetBindingService,
    private encryptionService: EncryptionService,
    private apiBotService: ApiBotService
  ) {}

  @PostMethod()
  @Permissions(Permission.CreateTargets)
  async create(@Body() targetDto: CreateBitvavoTargetDto, @User() user: UserClass) {
    const userTargets = await this.repository.getAll(user.sub);
    const safeModel = {
      ...targetDto,
      name: targetDto.name ? targetDto.name : `Bitvavo Wallet ${userTargets.length + 1}`,
      key: this.encryptionService.encrypt(targetDto.key),
      secret: this.encryptionService.encrypt(targetDto.secret)
    };
    await this.repository.create({...safeModel, userId: user.sub, positions: []}); // TODO some unique checking stuff
  }

  @GetMethod()
  @Permissions(Permission.ReadTargets)
  async get(@User() user: UserClass) {
    if (user.permissions.includes(Permission.AdminTargets)) {
      return await this.repository.getAllInternal();
    }
    return await this.repository.getAll(user.sub);
  }

  @GetMethod("/:id")
  @Permissions(Permission.ReadTargets)
  async getOne(@Param("id") targetId: string, @User() user: UserClass): Promise<BitvavoSingleTargetResponse> {
    let targetOpt;
    if (user.permissions.includes(Permission.AdminTargets)) {
      targetOpt = await this.bitvavoService.getOneInternal(targetId);
    } else {
      targetOpt = await this.bitvavoService.getOne(targetId, user.sub);
    }
    if (!targetOpt) {
      throw new NotFoundException();
    }
    const {bindings, target} = targetOpt;

    const decryptedKey = this.encryptionService.decrypt(target.key);
    const decryptedSecret = this.encryptionService.decrypt(target.secret);
    const balances = await getBalances(target, decryptedKey, decryptedSecret);

    return {
      target: toTargetDto({type: CollectionNames.Bitvavo, name: target.name, _id: target._id, targetMode: target.targetMode}),
      // producer: mapProducerToDto(producer),
      balances: balances,
      bindings: bindings
    };
  }

  @PostMethod("/:id/placeOrder")
  async placeOrder(@Param("id") id: string, @Body() body: BitvavoPlaceOrderDto, @User() user: UserClass): Promise<BitvavoOrderResponse> {
    let target;
    if (user.permissions.includes(Permission.AdminTargets)) {
      target = await this.repository.getOneByIdInternal(id);
    } else {
      target = await this.repository.getOneById(id, user.sub);
    }
    if (!target) {
      throw new NotFoundException();
    }
    return await this.bitvavoService.handleSignal(target, body);
  }

  @Patch("/:id")
  @Permissions(Permission.EditTargets)
  async update(@Param("id") id: string, @User() user: UserClass, @Body() targetDto: UpdateBitvavoTargetDto) {
    let target;
    let key;
    let secret;
    if (user.permissions.includes(Permission.AdminTargets)) {
      target = await this.repository.getOneModelByIdInternal(id);
    } else {
      target = await this.repository.getOneModelById(id, user.sub);
    }
    if (!target) {
      throw new NotFoundException();
    }
    if (targetDto.key) {
      key = this.encryptionService.encrypt(targetDto.key);
    } else {
      key = target.key;
    }
    if (targetDto.secret) {
      secret = this.encryptionService.encrypt(targetDto.secret);
    } else {
      secret = target.secret;
    }
    Object.assign(target, {...targetDto, key, secret});
    await target.save();
  }

  @DeleteMethod("/:id")
  @Permissions(Permission.DeleteTargets)
  async deleteTarget(@Param("id") id: string, @User() user: UserClass) {
    let target;
    if (user.permissions.includes(Permission.AdminTargets)) {
      target = await this.repository.getOneModelByIdInternal(id);
    } else {
      target = await this.repository.getOneModelById(id, user.sub);
    }
    if (!target) {
      throw new NotFoundException();
    }
    await this.repository.deleteById(id);
    await this.producerTargetBindingService.deleteAllForTarget({id: target.id, type: CollectionNames.Bitvavo});
  }

  @PostMethod("/:id/sellto/:base")
  @Permissions(Permission.EditTargets)
  async sellAllForTarget(@Param("id") id: string, @Param("base") base: string, @User() user: UserClass) {
    let target;
    if (user.permissions.includes(Permission.AdminTargets)) {
      target = await this.repository.getOneModelByIdInternal(id);
    } else {
      target = await this.repository.getOneModelById(id, user.sub);
    }
    if (!target) {
      throw new NotFoundException();
    }
    await this.producerTargetBindingService.deleteAllForTarget({id: target.id, type: CollectionNames.Bitvavo});
    await this.bitvavoService.sellAllToAsset(target, base);
  }

  @PatchMethod("/:id/changeTargetMode")
  @Permissions(Permission.EditTargets)
  async changeTargetMode(@Param("id") id: string, @Body() targetDto: ChangeBitvavoTargetMode, @User() user: UserClass) {
    let target;
    if (user.permissions.includes(Permission.AdminTargets)) {
      target = await this.repository.getOneModelByIdInternal(id);
    } else {
      target = await this.repository.getOneModelById(id, user.sub);
    }
    if (!target) {
      throw new NotFoundException();
    }

    Object.assign(target, {...target, targetMode: targetDto.targetMode});
    await target.save();
  }

  @PostMethod("/:id/stopBot/:base")
  @Permissions(Permission.EditTargets)
  async sellSingleTarget(@Param("id") id: string, @Param("base") base: string, @Body() body: SellSingleBot, @User() user: UserClass) {
    let target;
    let producer;

    if (user.permissions.includes(Permission.AdminTargets)) {
      target = await this.repository.getOneModelByIdInternal(id);
    } else {
      target = await this.repository.getOneModelById(id, user.sub);
    }

    producer = await this.apiBotService.getOneModelInternal(body.botName);

    if (!target || !producer) {
      throw new NotFoundException();
    }

    await this.producerTargetBindingService.deleteSingleForTarget(
      {id: target.id, type: CollectionNames.Bitvavo},
      {id: producer._id, type: CollectionNames.ApiBot}
    );
    await this.bitvavoService.sellAllToAsset(target, base);
  }
}

export const createBitvavoClient = (key: string, secret: string) => {
  return bitvavo().options({
    APIKEY: key,
    APISECRET: secret,
    ACCESSWINDOW: 10000,
    RESTURL: "https://api.bitvavo.com/v2",
    WSURL: "wss://ws.bitvavo.com/v2/",
    DEBUGGING: false
  });
};

const balanceToDto = (balance: {symbol: string; available: string; inOrder: string}): BitvavoBalanceDto => {
  return balance as BitvavoBalanceDto;
};

Here is my controller.spec.ts

import {BitvavoService} from "./bitvavo.service";
import {Test} from "@nestjs/testing";
import {BitvavoController} from "./bitvavo.controller";

describe("Bitvavo Controller", () => {
  let controller: BitvavoController;

  const mockValue = {};

  beforeEach(async () => {
    const moduleRef = await Test.createTestingModule({
      controllers: [BitvavoController],
      providers: [BitvavoService]
    })
      .overrideProvider(BitvavoService)
      .useValue({onModuleInit: jest.fn(), handleSignal: jest.fn(), sellAllToAsset: jest.fn(), getOne: jest.fn(), getOneInternal: jest.fn()})
      .compile();
  });

  it("test", () => {});
});

Get current user level without using while loops?

In my messaging app, I have a level system that track’s a user’s activeness with XP. It doesn’t store the actual level, only the amount of XP they have. Here’s the function for calculating the level:

function calculateLevel(num) {
  var lv = 0;
  do {
    lv++;
  } while (num >= Math.floor(Math.pow(30, Math.sqrt(Math.sqrt(lv)))));
  var x = num-Math.floor(Math.pow(30, Math.sqrt(Math.sqrt(lv-1))));
  var left = Math.floor(Math.pow(30, Math.sqrt(Math.sqrt(lv))))-num;
  var thislv = x + left;
  return {
    level: lv,
    xp: x,
    left: left,
    next: Math.floor(Math.pow(30, Math.sqrt(Math.sqrt(lv)))),
    prev: Math.floor(Math.pow(30, Math.sqrt(Math.sqrt(lv-1)))),
    thislv: thislv+1
  };
}

The formula for calculating how much XP each level requires is 30√(√(level)). However, I don’t want to use a while loop, because the app starts to slow down a bit after level 60. Is there a way to get the current level without having to use loops?

get value in input field from virtual keyboard in react

I am working on a countdown watch which have a virtual numpad (given in code as button) and three input (hour,minute and second). now i want that whenever i click input box and type in virtual numpad ,it print the value in that box only.

  1. there i used three ref to getElement of input and change set their value but dont know how to set for specific box
const inputOne = useRef(null);
const inputTwo = useRef(null);
const inputThree = useRef(null);

  const changeValue = (val) => {
    inputOne.current.value  = setTime({hour: updatedHour + val, minute: updatedMinute, second: updatedSecond}); 
    inputTwo.current.value = setTime({hour: updatedHour, minute: updatedMinute + val, second: updatedSecond});
    inputThree.current.value = setTime({hour: updatedHour, minute: updatedMinute, second: updatedSecond + val}); 
    }

const changeTime = (e) => {
    setTime({ ...time, [e.target.name]: e.target.value });
  };
  1. this is input fields i use , updatedHour,updatedMinute and updatedSecond is part of setTime state.
  <input ref={props.inputOne} onChange={props.changeTime} name="hour"  placeholder="Hour"  value={props.updatedHour} />
          <input ref={props.inputTwo} onChange={props.changeTime} name="minute"  placeholder="Minute" value={props.updatedMinute} />
          <input ref={props.inputThree} onChange={props.changeTime} name="second"  placeholder="Second" value={props.updatedSecond} />
  1. this is buttons which create virtual keyboard
 <button className="grid-item" tpye='button' onClick={()=> props.changeValue('1')}>1</button>
  <button className="grid-item" tpye='button' onClick={()=> props.changeValue('2')}>2</button>
  <button className="grid-item" tpye='button' onClick={()=> props.changeValue('3')}>3</button>  
  <button className="grid-item" tpye='button' onClick={()=> props.changeValue('4')}>4</button>
  <button className="grid-item" tpye='button' onClick={()=> props.changeValue('5')}>5</button>
  <button className="grid-item" tpye='button' onClick={()=> props.changeValue('6')}>6</button>  
  <button className="grid-item" tpye='button' onClick={()=> props.changeValue('7')}>7</button>
  <button className="grid-item" tpye='button' onClick={()=> props.changeValue('8')}>8</button>
  <button className="grid-item" tpye='button' onClick={()=> props.changeValue('9')}>9</button>  
  <button className="grid-item" tpye='button' >Prev</button>  
  <button className="grid-item" tpye='button' onClick={()=> props.changeValue('0')}>0</button>  
  <button className="grid-item" tpye='button' >Next</button>  

Highlight an individual character of text block containing links and heading on mouse hover

I am trying to achieve that when hover over a character, the character should change its color. It should work on individual character , links, heading etc.

My following code gives me result that i want but it removes the links and headings.

JS Fiddle: http://jsfiddle.net/bvpodc6z/1/

HTML CODE

<div class="words">
        Lorem ipsum dolor sit amet, consetetur sadipscing elitr,
        sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat,
        sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum.
        <a href="#link">LINK</a>
        <h1>
        Heading
        </h1>
        Stet clita kasd gubergren, no sea takimata sanctus e Lorem ipsum dolor sit amet.
    </div>

JS Code

$cont = $('.words');
parts = $.map($cont.text().split(''), function(v){
    return $('<span />', {text:v});
});
$cont.empty().append(parts);

CSS Code

.words span:hover{color:#F00}

How to read an array inside another array in an ” Json object” -> Jade/PUG.js

I’m trying to “create” a template using “Json” in Pug, but there is a point where I need to put much Information. But the problem for me becomes where I need to read an element deeply inside.

-
  var SuperSlidersInfo = {
      'numero': '4',
      'sectionName': 'Dignidad',
      'video': true,
      'youtube': [
        'idVideo',
        'idVideo2',
        ],
      'notes':[
        ['prueba1', 'prueba2'],
        ['segundo1', 'segundo2', 'segundo3'],
      ],
      'img': [
        'NombreImagen',
        'NombreImagen2',
        ],
      'extension': 'jpg',
      'titulo': [
        'Titulo',
        ],
      'parrafo': [
        'Texto',
      ]}
+SuperSlidersPug(SuperSlidersInfo)

mixin SuperSlidersPug(SuperSlidersInfo)
 .container-pc
    .container-sliderAutomatico.no-phone
      div(id=`sliderAutomatico${SuperSlidersInfo.numero}` class= SuperSlidersInfo.video ? "dosVideos-container" : "otraCosa").sliderAutomatico
        each imgName, index in SuperSlidersInfo.img
          //- div(class= SuperSlidersInfo.video ? "dosVideos").sliderAutomatico__section
          div(class= SuperSlidersInfo.video ? "dosVideos" : "otraCosa").sliderAutomatico__section
            .swiper-content
              if SuperSlidersInfo.video
                .section_videoContainer
                  a(href=`#video${SuperSlidersInfo.sectionName}${index}`).section_videoThumbnail--Container
                    img(src=`${imgURL}${SuperSlidersInfo.sectionName}${index + 1}.${SuperSlidersInfo.extension}`, alt="")
                  h3.swiper-content_titulo= `${SuperSlidersInfo.titulo[index]}`
                  .section_video--notes
                    //- -----------------
                    //- Problem
                    //- -----------------
                    //- the "a" below works, but I need to "create" and each, or for, or any loop for to put all the elements in that especific array. 
                    //- a(href=`${SuperSlidersInfo.notes[index]}`).section_video--note
                    
                    //- The "each" below it suppose to works. But when I put the "[index]" it brokes..
                    each note, noteIndex in SuperSlidersInfo.notes[index]
                      a(href=`${note}`).section_video--note

For general elements it works well. But when I need to read the “notes”. It’s impossible por me.

But when I put each note, noteIndex in SuperSlidersInfo.notes[index] everything is broken…

So I need to read the “elements” that “note” has in its array…

//- Works well
each note, noteIndex in SuperSlidersInfo.notes
//- It's Broke
each note, noteIndex in SuperSlidersInfo.notes[index]

the index is from the each that exist almost at top of the code

For loops and if statements

I have a character on screen that I’m trying to make it collect collectable items, however, with the if statement in the for loop present, it makes all the collectables disappear from screen; and without it, the collectables are drawn, but I’m only able to collect 1 and the other 2 disappear. The objective is the get the array to loop over and draw the collectables and have the collectables disappear as the game character walks over them.

var collectable

function setup(){
collectable = false
  collectable = [
    { collectable_x_pos: 1220, collectable_y_pos: 100, isFound: false },
    { collectable_x_pos: 220, collectable_y_pos: 100, isFound: false },
    { collectable_x_pos: 1820, collectable_y_pos: 100, isFound: false },
  ];
}
function draw(){

if (collectable.isFound == false) {
   for (var i = 0; i < collectable.length; i++) {
     drawCollectable(collectable[i]);
     checkCollectable(collectable[i]);
   }
 }
function drawCollectable(t_collectable) {
  fill(0, 255, 255);
  quad(
    t_collectable.collectable_x_pos - 70,
    t_collectable.collectable_y_pos + 277,
    t_collectable.collectable_x_pos - 54,
    t_collectable.collectable_y_pos + 331,
    t_collectable.collectable_x_pos - 36,
    t_collectable.collectable_y_pos + 277,
    t_collectable.collectable_x_pos - 54,
    t_collectable.collectable_y_pos + 222
  );
}
function checkCollectable(t_collectable) {
  if (
    dist(gameChar_x, gameChar_y, t_collectable.x_pos, t_collectable.y_pos) < 20
  ) {
    console.log("Collected");
    collectable.isFound = true;
  }
}

JavaScript conditional font color change of part of text

I tried to change the font color of my String in my vue application based on a condition. However, the solutions I found so far changed the color for the whole text. I only want specific parts to be changed. For example:

const exampleString= 'Yesterday I was ACTIVITY with FRIEND who I first met in PLACE'

The words in capital letters should be in color red but the rest in black. So a condition like “if three subsequent chars are capital letters than color red until empty space”. Is there a way to implement this ?

Submitting form with js while ? is missing in the return result

I write a form submit thread with the attr method:

var href = a.attr('href');
      if(href =='') return;
      if(href.startsWith('http') || href.startsWith('//:')){
        a.attr('href',href.trim());
        if(href.indexOf(location.hostname) > -1){
          return;
        }
        if(href.indexOf('<?php echo $_SERVER['SERVER_NAME']; ?>') > -1){
          return;
        }

        a.attr('href','go.htm?uri='+href);
        a.attr('rel','nofollow');
      }

However, it returns the URL without ?, for example, I want to return https://example.abc.com/?ref=abc, the return result will be https://example.abc.com/ref=abc without “?” the question mark.

I’m struggling with solving this and I appreciate any helpful tips.

Making a React component more general to handle realtime database collections

I am working on some javascrit code, handling a firebase realtime database and using React to manage the user interface. I want to have a generic class where I can provide the name of a collection to use, as a prop.

For example, this:

<MediaInput type='movies'/>

would make a component to use the movies collection.

This:

<MediaInput type='books'/>

would make a component to use the books collection.

And so on with:

<MediaInput type='tapes'/>

or

<MediaInput type='films'/>

…etc…

Below is my current code, the problem is that it only works with the books collection.

I have tried replacing ‘books’ by ‘dbCln’ in a few ways but it did not work. Does anyone know how I need to modify the code (I assume changing the lines containing ‘books’ by lines containing ‘dbCln’ in some way) to get the result I want.

import React from 'react';
import firebase from './initFirebase';
import './MediaInput.css';
import AppDB from './AppDB.js';

class MediaInput extends React.Component {
  constructor(props) {
    super(props);
    this.appDatabase = new AppDB();

    this.state = {
      books: [],
      dbCln: {
        [props.type]: []
      }
    };
  }


  componentDidMount() {
    this.getUserData();
  }


  componentDidUpdate(prevProps, prevState) {
    if (prevState !== this.state) {
      this.writeUserData();
    }
  }


  writeUserData = () => {
    this.appDatabase.addCollection(this.state);
  };


  getUserData = () => {
    let ref = firebase.database().ref("/");
    ref.on("value", snapshot => {
      const state = snapshot.val();
      this.setState(state);
    });
  };


  handleSubmit = event => {
    event.preventDefault();
    let name = this.refs.name.value;
    let price = this.refs.price.value;
    let uid = this.refs.uid.value;

    if (uid && name && price) {
      const { books } = this.state;
      const devIndex = books.findIndex(data => {
        return data.uid === uid;
      });
      books[devIndex].name = name;
      books[devIndex].price = price;
      this.setState({ books });
    } else if (name && price) {
      //const uid = new Date().getTime().toString();
      let uid = new Date().getTime().toString();
      const { books } = this.state;
      books.push({ uid, name, price });
      this.setState({ books });
    }

    this.refs.name.value = "";
    this.refs.price.value = "";
    this.refs.uid.value = "";
  };


  render() {
    return (
        <React.Fragment>
            <div className="inp-block">
            <form onSubmit={this.handleSubmit}>
              <div className="form-row">
                <input type="hidden" ref="uid" />
                <div className="form-group col-md-6">
                  <label className='inp-lbl'>Name</label>
                  <div className='inp-name'>
                    <input
                      type="text"
                      ref="name"
                      placeholder=""
                    />
                  </div>
                </div>
                <div className="form-group col-md-6">
                  <label className='inp-lbl'>Price</label>
                  <div className='inp-price'>
                    <input
                      type="text"
                      ref="price"
                      placeholder=""
                    />
                  </div>
                </div>
              </div>
              <div className="btn">
                <button type="submit" className="btn-primary">
                  Save
                </button>
              </div>
            </form>
            </div>
        </React.Fragment>
    )
  }
}

export default MediaInput;

react-router-sitemap giving ERROR Failed at the [email protected] sitemap script

I have a React router-based Single-Page-App and I’m trying to generate the sitemap links using react-router-sitemap version:^1.2.0 but I’m getting the same error again. And giving me Errors in the CSS files. I’m trying different techniques for 6 hours. Please suggest some solution.

Routes.js

import React from 'react';
import { Route, Routes } from "react-router-dom"

import GameComponent from './GameComponent';
import PlayGame from './PlayGame';
import PrivacyPolicy from './PrivacyPolicy';
import TermsConditions from './TermsConditions';

function Routesdef(props) {
    return (

        <Routes>
            <Route exact path="/" element={<GameComponent suggested__Games={props.suggested__Games} games={props.ALL__GAMES} key="all" />} />
            <Route exact path="/gamecomponent/:category" element={<GameComponent suggested__Games={props.suggested__Games} games={props.ALL__GAMES} key="categoryWise" />} />
            <Route path="/playgame/:gamename/:title/:gameSource/:category/:index" element={<PlayGame games={props.ALL__GAMES} suggested__Games={props.suggested__Games} key="playing" />} />
            <Route exact path="/privacypolicy" element={<PrivacyPolicy />} />
            <Route exact path="/termsconditions" element={<TermsConditions />} />
        </Routes>

    )
}
export default Routesdef

sitemap-generator.js

require("babel-register")({
  presets: ["es2015", "react"]
});

const router = require('./Routes.js').default;
const Sitemap = require('react-router-sitemap').default;

(
  new Sitemap(router)
    .build('https://www.onlineplaygames.online')
    .save('./public/sitemap.xml')
);

Scripts in Package.json

  "scripts": {
    "build:staging": "env-cmd -f .env.staging npm run build",
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "sitemap": "babel-node src/sitemap-generator.js"
  },

Please Suggest some solution…????

Cors error while rendering FB Chat plugin for whitelisted domains

I am trying to add the Messenger Live Customer Chat Plugin dynamically to a site by first whitelisting the domain via the API and then injecting the script tag to the whitelisted domain site.

Now, after injecting the script to the whitelisted site it fails with CORS error. But, if I manually whitelist the URL via the Facebook app using the UI it works fine. I dont understand why does whitelisting via API does not work when the docs clearly say it should work.

  1. Successfully whitelisting a domain for a FB page via the API
curl 'https://graph.facebook.com/v12.0/me/messenger_profile?access_token=EAxxxxxxxPr' 
  -H 'authority: graph.facebook.com' 
  -H 'sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="96", "Google Chrome";v="96"' 
  -H 'accept: application/json, text/plain, */*' 
  -H 'content-type: application/json' 
  -H 'sec-ch-ua-mobile: ?0' 
  -H 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36' 
  -H 'sec-ch-ua-platform: "macOS"' 
  -H 'origin: https://livechat.frangout.com' 
  -H 'sec-fetch-site: cross-site' 
  -H 'sec-fetch-mode: cors' 
  -H 'sec-fetch-dest: empty' 
  -H 'referer: https://livechat.frangout.com/' 
  -H 'accept-language: en-GB,en-US;q=0.9,en;q=0.8' 
  --data-raw '{"whitelisted_domains":["https://my-domain.com"]}' 
  --compressed

Result: {success: true } and I can also GET the whitelisted_domains and see it is already whitelisted

  1. Injecting script dynamically to the whitelisted site so that it loads the Messenger Live Chat Plugin
        var fbCustomerChat = document.createElement('div');
        fbCustomerChat.id = "fb-customerchat";
        fbCustomerChat.classList.add("fb-customerchat");
        fbCustomerChat.setAttribute('page_id', 'xxx')
        document.body.appendChild(fbCustomerChat);

        window.fbAsyncInit = function() {
            FB.init({
              appId            : 'xxx',
              autoLogAppEvents : true,
              xfbml            : true,
              version          : 'v12.0'
            });
        };

        (function(d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) return;
            js = d.createElement(s); js.id = id;
            js.src = "https://connect.facebook.net/en_US/sdk/xfbml.customerchat.js";
            fjs.parentNode.insertBefore(js, fjs);
        }(document, 'script', 'facebook-jssdk'));
  1. Browser Logs

Access to XMLHttpRequest at 'https://www.facebook.com/plugins/customer_chat/facade_gating/?page_id=106040728582517&suppress_http_code=1' from origin 'https://sid-s-school-12f2.thinkific.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
xhr-patch.js:87 GET https://www.facebook.com/plugins/customer_chat/facade_gating/?page_id=106040728582517&suppress_http_code=1 net::ERR_FAILED 200

Access to XMLHttpRequest at 'https://www.facebook.com/plugins/customer_chat/SDK/trucnated co

Refused to frame 'https://www.facebook.com/' because an ancestor violates the following Content Security Policy directive: "frame-ancestors https://www.facebook.com".

Create a node.js cpu process list

Node.js tried to make json a process that uses cpu a lot and distribute it. But I don’t know how to get cpu’s information. What should I do?

Currently, cpu information is agreed to be brought only from No. 1 to No. 5 in the process that is used a lot.

How to get state of children from parent in class component

I’m trying to display the state of child component in parent component, but somehow the text “abcde” still not show, here is the sample code

import React from 'react';
import {SafeAreaView, StyleSheet, Text} from 'react-native';
import {TouchableOpacity} from 'react-native-ui-lib';

class ChidComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: '',
    };
  }
  render() {
    return (
      <SafeAreaView>
        <TouchableOpacity
          onPress={() => {
            this.props.getText(this.state.text);
          }}>
          <Text>Get Text</Text>
        </TouchableOpacity>
        <TouchableOpacity
          onPress={() => {
            this.setState({text: 'abcde'});
          }}>
          <Text>set ramdom text</Text>
        </TouchableOpacity>
      </SafeAreaView>
    );
  }
}

const style = StyleSheet.create({
  text: {
    fontWeight: 'bold',
    fontSize: 40,
  },
});
class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      show: false,
      text: '',
    };
  }
  getTextFromChild(value) {
    this.setState({text: value});
  }
  render() {
    return (
      <SafeAreaView>
        <Text>{this.state.text}</Text>
        <ChidComponent
          getText={this.getTextFromChild.bind(this)}
          show={this.state.show}
          press={() => this.setState({show: !this.state.show})}
          textStyle={style.text}
        />
      </SafeAreaView>
    );
  }
}
export default ParentComponent;

But somehow the screen still empty, the ‘abcde’ still not show, come from functional component so i don’t know what going on, please help, thank you a lots