error when inserting into relational table many to many

I’m trying to persist relational data in myql database with typeORM and nestjs but it’s showing an error apparently in the database

the entity

  @ManyToMany(()=> Stock, stock => stock.seals)
  @JoinTable()
  stock: Stock[];

the service

var c = getConnection().getRepository(Seals).save(createSealDto)
     return c 

the error

 ERROR [ExceptionsHandler] Cannot add or update a child row: a foreign key constraint fails (`stocksystem`.`stock_seals_seals`, CONSTRAINT `FK_70140d58e95fbceed988b224e64` FOREIGN KEY (`stockId`) REFERENCES `stock` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)

my payload

{"client":{"id":1},"stock":[{"id":1},{"id":1}],"price":398}

Is there a way to set the serializableCheck to false for one reducer only in redux?

Currently I have disabled the serializableCheck in my store.js and it works, however I’d prefer if I could only set it to false for one reducer in particular, and keep it set to true for all the rest.

export const store = configureStore({
    reducer: {
        app: appReducer,
        settings: settingsReducer,
        admin: adminReducer,
        popout: popoutReducer,
    },
    middleware: getDefaultMiddleware({
        serializableCheck: false,
    }),
});

I’m aware disabling this check can cause issues in the future, I only have one reducer where I want this check to be disabled.

Thanks

Google graphs not following the sequence of points

I am creating an web app with a table of x,y & α,β for the user to input and graphing them on google line chart as 2 different series. However, the google chart does not follow the sequence of the co-ordinates and jumps to different sequence. The points are there the line follows an unusual probably the shortest distance between the coordinates as shown in the following picture instead of square is like N.
example graph of square
the code is the following:

google.charts.load('current', {packages: ['corechart']});
      google.charts.setOnLoadCallback(drawCurveTypes);
      const input = document.querySelector('table');
      input.addEventListener('input', updateValue);

      function updateValue(e)   {  drawCurveTypes()  }
      function drawCurveTypes() {
            var data  = new google.visualization.DataTable();
            var data2 = new google.visualization.DataTable();
            var x  = [];
            var y  = []; 
            var a  = [];
            var b  = [];
            var s  = [];
            var ss = [];
            for (var i = 0; i < 20; i++) {
                   var u = i+1
                   x[i] =    +document.getElementById("x"+u).value;
                   y[i] =    +document.getElementById("y"+u).value;
              if (x[i]!==0 || y[i]!==0) {
                var temp=[]
                temp.push( +document.getElementById("x"+u).value);
                temp.push( +document.getElementById("y"+u).value);
                  s.push(temp);
              }
            } 
             for (var i = 0; i < 20; i++) {
              var u = i+1
                a[i] =     +document.getElementById("a"+u).value;
                b[i] =     +document.getElementById("b"+u).value;
              if (a[i]!==0 || b[i]!==0) {
                 var temp=[]
                temp.push( +document.getElementById("a"+u).value);
                temp.push( +document.getElementById("b"+u).value);
                  ss.push(temp);
               }
               }

             data.addColumn('number', 'X');
             data.addColumn('number', 'Geometry');
             data.addRows(s);
            data2.addColumn('number', 'X');
            data2.addColumn('number', 'Columns');
            data2.addRows(ss);
            var joinedData = google.visualization.data.join(data, data2, 'full', [[0, 0]], [1], [1]);
            var options = {


              backgroundColor: '#35424a',
              legendTextColor:'#ffffff',
              chartArea:{left:60,width:'72%',height:'88%'},      
          };


            var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
            chart.draw(joinedData, options);
          }
<script src="https://www.gstatic.com/charts/loader.js"></script>
<table class="table" style="background: #35424a; padding:10px; float:left;">
                <tr>
                  <th>x</th>
                  <th>y</th>
                  <th>α</th>
                  <th>β</th>
                  <th>B</th>
                  <th>H</th>
                </tr>
                <tr>
                    <th><input type="number" id="x1"   /></th>
                    <th><input type="number" id="y1"   /></th>
                    <th><input type="number" id="a1"   /></th>
                    <th><input type="number" id="b1"   /></th>
                    <th><input type="number" id="w1"   /></th>
                    <th><input type="number" id="h1"   /></th>
                </tr>
                <tr>
                    <th><input type="number" id="x2"   /></th>
                    <th><input type="number" id="y2"   /></th>
                    <th><input type="number" id="a2"   /></th>
                    <th><input type="number" id="b2"   /></th>
                    <th><input type="number" id="w2"   /></th>
                    <th><input type="number" id="h2"   /></th>
                </tr>
                <tr>
                    <th><input type="number" id="x3"   /></th>
                    <th><input type="number" id="y3"   /></th>
                    <th><input type="number" id="a3"   /></th>
                    <th><input type="number" id="b3"   /></th>
                    <th><input type="number" id="w3"   /></th>
                    <th><input type="number" id="h3"   /></th>
                </tr>
                <tr>
                    <th><input type="number" id="x4"   /></th>
                    <th><input type="number" id="y4"   /></th>
                    <th><input type="number" id="a4"   /></th>
                    <th><input type="number" id="b4"   /></th>
                    <th><input type="number" id="w4"   /></th>
                    <th><input type="number" id="h4"   /></th>
                </tr>
                <tr>
                    <th><input type="number" id="x5"   /></th>
                    <th><input type="number" id="y5"   /></th>
                    <th><input type="number" id="a5"   /></th>
                    <th><input type="number" id="b5"   /></th>
                    <th><input type="number" id="w5"   /></th>
                    <th><input type="number" id="h5"   /></th>
                </tr>
              </table>
              
              <div id="chart_div" style="float:right ; height:600px; width:50%; padding-right:20px ; ">
        </div>

nodejs tcp server write msg to specific connected client

How can I send a msg to a specific client that is connect to my nodejs tcp server? I was thinking to connect with anoher client that send’s the ip and port of the client that i want to recieve a msg and write to that client but when i do this i get ECONNRESET error.

here is my server:

const net = require('net');
const Parser = require('teltonika-parser-ex');
const binutils = require('binutils64');

let server = net.createServer((c) => {
    console.log("client connected");
    c.on('end', () => {
        console.log("client disconnected");
    });

    c.on('data', (data) => {

   
        let buffer = data;
        console.log(buffer);
      
        let parser = new Parser(buffer);     

        if (parser.isImei) {
            c.write(Buffer.alloc(1, 1)); // send ACK for IMEI
        } else {


            let avl = parser.getAvl();
          
             console.log("parseRec", avl?.records?.map(({ gps, timestamp }) => {
                  return { gps, timestamp }
              }
              )
              )

            let writer = new binutils.BinaryWriter();
            writer.WriteInt32(avl.number_of_data);


            let response = writer.ByteBuffer;

           c.write(response); // send ACK for AVL DATA
            // console.log(test);
            
        c.write(Buffer.from('000000000000000F0C010500000007676574696E666F0100004312', 'hex')); // SEND GETINFO 
        }
 
    });

});

server.listen(1574, '0.0.0.0', () => {
    console.log("Server started");
});

Convert a buffer to a Javascript object or JSON

I’m trying to convert a Buffer to JSON object. I’ve tried a lot of measures so far. but it doesn’t seem to work.

Here’s my buffer:

<Buffer 7b 22 6d 65 73 73 61 67 65 73 22 3a 5b 5d 2c 2.... 4972 more bytes>

Steps I’ve tried:

console.log('Object1', JSON.stringify(request.response.body));  

output: {“type”:”Buffer”,”data”:[]}

console.log('test2.....', JSON.parse(request.response.body));

JSON.parse() is not logging any output, even after waiting for long.

How do I convert this to a readable JS object?

What the purpose of using +new?

#Hello,#

I heard that +new object cast the object as an integer, can i have an exemple showing the difference between new and +new ?

Here’s the code i’m trying to understand.

function App() {

  const calculateTimeLeft = () => {
    let year = new Date().getFullYear();
    const difference = +new Date(`10/01/${year}`) - +new Date();
    return year
  };

  return (
    <div className="App">
      {console.log(calculateTimeLeft())}
    </div>
  );
}

thanks community !

In an Angular 8 SSR app, there is a memory leak

I have an angular SSR app that causes memory leaks on the server

it keeps on increasing memory on the server when the application is used and opened by many users.Unsubscribing subscriptions on ngOnDestory doesn’t work, still memory leaks persist

Not able to find whats the issue and whats the correct way to solve the problem

I am attaching the server.ts code

import "zone.js/dist/zone-node";

import * as express from "express";

import { join } from "path";

const domino = require("domino");
const fs = require("fs");
const path = require("path");

const app = express();

const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(process.cwd(), "dist/browser");

const template = fs
  .readFileSync(path.join(DIST_FOLDER, "index.html"))
  .toString();
const win = domino.createWindow(template);

(global as any)["window"] = win;
(global as any)["KeyboardEvent"] = win.KeyboardEvent;
(global as any)["HTMLInputElement"] = win.HTMLInputElement;
(global as any)["MouseEvent"] = win.MouseEvent;
(global as any)["Event"] = win.Event;
(global as any)["document"] = win.document;
(global as any)["navigator"] = win.navigator;
(global as any)["FormData"] = win.FormData;
// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const {
  AppServerModuleNgFactory,
  LAZY_MODULE_MAP,
  ngExpressEngine,
  provideModuleMap,
} = require("./dist/server/main");

app.engine(
  "html",
  ngExpressEngine({
    bootstrap: AppServerModuleNgFactory,
    providers: [provideModuleMap(LAZY_MODULE_MAP)],
  })
);

app.set("view engine", "html");
app.set("views", DIST_FOLDER);

app.get(
  "*.*",
  express.static(DIST_FOLDER, {
    maxAge: "1y",
  })
);

app.get(/.*aspx$/, function (req, res) {
  res.redirect(301, "WEBSITE URL");
});

// All regular routes use the Universal engine
app.get("*", (req, res, next) => {
  // special for robots.txt
  if (req.url === "/robots.txt") {
    next();
    return;
  }

  res.render("index", { req });
});

app.listen(PORT, () => {
  console.log(`Node Express server listening on http://localhost:${PORT}`);
});

Which JSON layout provides better performance to fetch data?

I realized that using two different ways to organize JSON data may affect my code performance especially if I need to filter() or map(). The two cases are shown below, both cases will include thousands of lines of data:

[
   //....
   {
     "url": "www.example2400.com"
   }
   {
     "url": "www.example2401.com"
   }
   //...
]

Or:

{
   "url": [
    //...
    "www.example2400.com",
    "www.example2401.com",
    //...
    ]
}

Which layout would provide better performance in terms of fetch(), filter() or map() the data to render it on the page? Or is there a better layout?

Unable to convert an array back to string by using join(” “)

I initially have a string whose words first letter I want to capitalize. After capitalization, I’m unable to convert the array back to string.
What’s wrong here?

const name = 'This is a beautiful day';
console.log(name)
const capitalizedName = name.split(' ');
for (let i = 0; i < capitalizedName.length; i++) {
capitalizedName[i] =
  capitalizedName[i][0].toUpperCase() + capitalizedName[i].substr(1);
}
capitalizedName.join(' ');
console.log(capitalizedName);

The output:-

This is a beautiful day
[ 'This', 'Is', 'A', 'Beautiful', 'Day' ]

Output that I was expecting:-

This is a beautiful day
This Is A Beautiful Day

handler.apply RangeError: Maximum call stack size exceeded

I’m trying to understand why there’s “RangeError: Maximum call stack size exceeded” error. We have a logger that we need to use. What I want to do, anytime you call the logger f.e logger.debug(‘My message’) I want to inject additional fields, in my case it’s thread id, correlation id etc. What I did is

// Main logger
const Log = require('ethos-js-logger');

const logLevels = ['fatal', 'error', 'warn', 'info', 'debug', 'trace'];
const ethosLogger = Log.createLogger();

const handler = {
  get(target: any, prop: string) {
    // Adding additional information into logger
    if (logLevels.includes(prop)) {
      const correlationId = httpContext.get('correlationId');
      const endpoint = httpContext.get('endpoint');
      const apiKey = httpContext.get('apiKey');

      const message = {
        correlationId,
        endpoint,
        apiKey,
        isMainThread,
        ...(!isMainThread && { WorkerThreadId: threadId }),
      };
      return (args: any) => {
        target[prop].apply(target, [args, message]);
      };
    }

    // When create a new instance of logger return Proxy
    if (prop === 'createLogger') {
      return (args: any) => {
        return new Proxy(Log.createLogger(args), handler);
      };
    }

    // Return default logger implementation
    return target[prop];
  },
};

const logger = new Proxy(ethosLogger, handler);

export { logger };

It perfectly works. But when I run tests, even one file, I’m getting this error

    RangeError: Maximum call stack size exceeded

      24 |       };
      25 |       return (args: any) => {
    > 26 |         target[prop].apply(target, [args, message]);
         |                            ^
      27 |       };
      28 |     }

P.S. I thought I could be due to if (prop === 'createLogger') line, but in that test I don’t create a new logger, just import it from this file and use.

Storybook javascript GET 404 (Not Found) error about components

I need to fix a Storybook with stories, it’s broken (it’s unclear when it was broken, probably after some angular upgrades a while ago), it didn’t work for some time.
Currently, some of stories are displayed properly, however for most of stories there are similar javascript errors. The stories with that js errors are not displayed at all.

It’s a huge Angular project.
For many stories the js errors are (or similar for another story, with another components):

enter image description here

Is it related to the angular code itself, or it’s all about .storybookmain.js ?

If this is helpful, then:

start-storybook -V
6.0.28

node -v
v14.18.1

ng --version    
@angular-devkit/architect          0.901.15
@angular-devkit/build-angular      0.901.15
@angular-devkit/build-ng-packagr   0.901.15
@angular-devkit/build-optimizer    0.901.15
@angular-devkit/build-webpack      0.901.15
@angular-devkit/core               9.1.15
@angular-devkit/schematics         9.1.15
@angular/cdk                       9.2.4
@angular/cli                       9.1.15
@angular/material                  9.2.4
@ngtools/webpack                   9.1.15
@nguniversal/common                9.1.1
@nguniversal/express-engine        9.1.1
@schematics/angular                9.1.15
@schematics/update                 0.901.15
ng-packagr                         9.1.5
rxjs                               6.6.7
typescript                         3.7.7
webpack                            4.42.0

Any ideas how to fix it? Thank you.

P.S. Upgrading/downgrading storybook didn’t help that much, so it was decided to stick with a current one Storybook of 6.0.28 (at least some of many stories are displayed).

How do I use filter inside filter in react

I have an array getting from an API data, I would like to filter categories if it’s in category. I was trying like :

data.filter((post) => post.categories.filter((category) => if(category._id === category) return category

It didn’t work for me

Here is my array data :

export interface Post {
  categories: Category[]
  publishedAt: string
  _id: string
  _createdAt: string
  title: string
  author: {
    name: string
    image: string
  }
  comments: Comment[]
  description: string
  mainImage: {
    asset: {
      url: string
    }
  }
  slug: {
    current: string
  }
  body: [object]
}

export interface Category {
  _id: string
  _ref?: string
  title: string
}

and I tried this too

posts.map((post) => {
                  post.categories.filter((category) => {
                    if (category._ref === isCategory) return category
                  })
                  {
                    return <Posts post={post} />
                  }
                })

How can I do it ?

Group array data with lodash

I have an array of objects and I want to group them as an array of arrays with 10 objects each.

input: data = [{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},....{100}]

output: groupedData = [ [{1},..{10}], [{11},...{20}], ... [{91}, ..{100}] ]

I have tried with lodash _groupBy like this
groupedData = _groupBy(data, 10)
but the output is
undefined: [{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},....{100}]

Only let users with a specific permission use kick slash command

I know how to make it so that only ME can use a slash command, that way if someone isn’t me and tries to use my slash command it will be gray like :

grey slash command

client.application.commands.permissions.set([
  {
    id : cmd.id,
    permissions : [
      {
        type : 'USER',
        id : 'My id',
        permission : true
      }
    ]
  }
])

How to do the same thing for permissions ? How to do it so that only members with a specific role can use the command ?