How do I implement generic / package-agnostic logging for a Node.JS Project?

I want to add logging to my Node.JS project, so that I can view debug logs while the application runs. There are a lot of different loggers out there for JavaScript apparently, and I’m not sure which one to use. Ideally, I would like to write my code so that the logger is not part of the codebase, but instead the logging is generic and I can switch between different generic logging libraries as I see fit. How can I do this?

Datatables Checkboxes extension combined with Sortable

For a project I’m working on, the admin of the system will be assigning questions to some quizes from a huge pool of questions. For better filtering of the questions upon their selection, I had to use Datatables. Then, I noticed that a simple checkbox for each table row wasn’t enough to select them when being paginated, so after some research I found the Checkboxes extension for Datatables that would solve $_POST of the selected rows and pagination problems.

Everything worked fine with the transition, but the latest requirement of my project is the ability to re-order questions, so I also utilized jQuery Sortable, to re-order the question rows. But then I noticed that re-ordering the rows, doesn’t actually re-order the selected rows returned by Datatables Checkboxes…

The minimal working code I used for a mockup of my project is below:

jQuery(function($) {
  $('#questions-pool tbody').sortable({
    connectWith: '#questions-pool tbody',
    handle: 'td.move-handle',
  });

  var questions = $('#questions-pool').DataTable({
    ordering: false,
    dom: '<"#upper-controls"lf>t<"#lower-controls"ip>',
    lengthMenu: [
      [10, 50, 100, -1],
      [10, 50, 100, 'All']
    ],
    initComplete: function(settings) {
      var api = this.api();
      var selected = [387, 386, 385, 384, 383, 382, 381, 380, 379, 378];

      api.cells(
        api.rows(function(idx, data, node) {
          return (selected.indexOf(Number(data[2])) >= 0) ? true : false;
        }).indexes(),
        3
      ).checkboxes.select();
    },
    columnDefs: [{
      targets: 3,
      checkboxes: {
        selectAllPages: false,
      }
    }],
  });

  $('#get-selected').click(function(event) {
    var form = $('#questions-form');

    $(form).find('.questions-postfields').remove();

    console.log('Deleted previous fields');

    $.each(questions.column(3).checkboxes.selected(), function(index, rowId) {
      $(form).append(
        $('<input>')
        //  .attr('type', 'hidden')
        .attr('name', 'questions[]')
        .attr('class', 'questions-postfields')
        .val(rowId)
      );
    });
  });
});

Also a working fiddle of the code above can be found here. So the fiddle starts with some rows already selected by their respective checkboxes. I also have a button that emulates form submission, where upon the submission I’ve coded the script to create on-the-fly hidden fields for each selected ID. So upon clicking the button, the previous fields are removed and appended to the form from scratch. However, no matter how you re-order the rows, the selected IDs always appear in the same order.

Do you have any idea why this is happening?

Access renderChart for vue-chartjs 4 using Vue Composition API

I would like to set some default Options on my Chart Component in order to avoid appending those in every class calling my component.

In vue-chartjs 3 it was possible calling the renderChart method and override the current options for the chart, but I am not able to replicate it using vue-chartjs 4 and vue 3 composition API

Ex. in vue-chartjs 3

import { Line, mixins } from 'vue-chartjs'

export default {
  extends: Line,
  mixins: [mixins.reactiveProp],
  props: ['chartData', 'options'],
  mounted () {
    this.renderChart(this.chartData, this.options)
  }
}

Mixins are not available on this version.

Do you have any idea how this could be accomplished?

This is my code using vue-chartjs 4

<template>
  <Doughnut :chartData="chartData" />
</template>

<script lang="ts">

import { ref } from 'vue'
import { Doughnut } from 'vue-chartjs'
import { Chart as ChartJS, registerables, ChartData } from 'chart.js'

ChartJS.register(...registerables);

export default {
  components: { Doughnut },
  setup() {
    const chartData = ref<ChartData>({ datasets: [] });
    const defaultOptions = {
      responsive: true
    }

   // Here I want to append my default options to current options
    
    return { graph, chartData, chartId }
  }
}
</script>

I have been checking the documentation, but I was not able to make it work.
https://vue-chartjs.org/migration-guides/#new-reactivity-system

why is the cursor messed like this?

My terminal goes like this:

import { useEffect } from "react";
import { Terminal as TerminalType } from 'xterm';
import { FitAddon } from 'xterm-addon-fit';
//import { SearchAddon } from 'xterm-addon-search'
import 'xterm/css/xterm.css';

export const Terminal = ({
    initialValue
  } : {
    initialValue?: string
  }) => {

  const id = 'xterm-container';
  useEffect(() => {
    const terminal = new TerminalType({
      cursorBlink: true,
      cursorStyle: window.api.isWindows ? "bar" : "underline"
    });

    const fitAddon = new FitAddon();
    terminal.loadAddon(fitAddon);

    window.api.receive('terminal.incomingData', (data) => {
      terminal.write(data);
    });
    
    terminal.open(document.getElementById(id) as HTMLElement);
    terminal.onData(key => {
      window.api.send('terminal.keystroke', key);
    });
    
    terminal.focus();
    window.api.send('terminal.keystroke', "cd C:\rn");

  }, []);

  return (
    <div id={id}></div>
  )
}

where in the backend I connect xterm to real terminal like this:

ipcMain.on('terminal.keystroke', (_, key) => {
  ptyProcess.write(key);
});

  const shell = isWindows ? 'powershell.exe' : 'bash';
  ptyProcess = spawn(shell, [], {
    name: 'xterm-color',
    cols: 80,
    rows: 30,
    cwd: isWindows ? process.env.USERPROFILE : process.env.HOME,
    env: process.env as INonUndefinedEnv
  });
  ptyProcess.onData(data =>
    EnforceNonNull(win).webContents.send('terminal.incomingData', data)
  );

but when send the text, the cursor for some reason gets messed like in the below image. Sending a text like this reproduce the error:

window.api.send('terminal.keystroke', "cd C:\rn");

enter image description here

Mission with Javascript :)

Good afternoon everyone, I have a problem with javascript.

I was assigned as a task to make a box that changes color when clicking on the page, I was doing my code but I managed to make the box but not change color.

I use Eventlistener because i want to repeat the change color.

Idk what is bad in my code i see alot of forums but nothing help.

I hope you can help me, thanks

<!DOCTYPE html>
<meta charset="utf-8">

<html><head>
  <title> Cuadro cambia color // By Abraham Gonzalez </title>
</head>

<script>


  function myBody(){
      var myBody;
      myBody = document.getElementById("myBody");
      myBody.addEventListener("click", btnRojoClic)
      ctx.fillStyle = rgb[Math.floor(Math.random() * 255)];
      
  }

  function btnRojoClic(){
    var myBody;
    myBody = document.getElementById("myBody")
    myBody.style.color = "red"

  }
  
</script>

<body id="myBody"> 

 <canvas id="canvas" width="400" height="400"></canvas>
 <script>



 var canvas = document.getElementById("canvas");
 var ctx = canvas.getContext("2d");


  
 var posicion = 0;    
 var tamano = 0;
    
 setInterval(function () {
    ctx.clearRect(0, 0, 400, 400);
    ctx.fillRect(posicion,0 , tamano, tamano);
    
    posicion++;
    tamano++;
    
    if (posicion > 400){
        posicion = 0;
        tamano = 0;
    }
}, 30);



</script></body></html>

 


 

Format a string as if it were an XML file

I’m writing a method that is generating the body of an XML file. The method returns a string, which I then pass to
const file = new Blob([content], {type: "text/xml"});
as the content variable. How can I get this string to format itself as a more readable format? Specifically, I’m looking for a way to auto-indent and add newlines wherever necessary as opposed to adding them manually.

Process to create a page on my website for people to sign it (How people sign Steam Profiles)

I am a new developer, and I am creating a my first website to help learn HTML, CSS, and JS. What skills/tools would I need to accomplish this? I don’t need anything that holds people back from entering more than one name or an inappropriate name. I would just need to be able to delete whatever names from my end. I think it would just be a cool feature to implement.

react-dom.development.js:67 Warning: Encountered two children with the same key

I have this React code which I would like to use to select all rows:

export interface ILiquidationSpread {
  id?: number;
}

export const getEntitiesIds: ICrudGetAllLiquidationSpreadIdsParamsAction<[]> = (
  searchIdParam,
.....
) => {
  const requestUrl = `${apiUrl}/rows-id-list?`;
  return {
    type: ACTION_TYPES.FETCH_LIQUIDATIONSPREAD_IDS_LIST,
    payload: axios.get<[]>(`${requestUrl}......),
  };
};

from this call I get the following response:

[151, 4, 11, 28, 35, 1, 2, 29, 3, 7, 496, 19, 68, 9, 166, 12, 8, 167, 67, 6, 168, 30, 112, 10, 958,…]

Using this code I would like to select all rows into paginated table:

const selectAll = event => {
    const entitiesIds = props.getEntitiesIds(
      ........
    );

// how I can get the ids as a list and select all table rows?
let x = [];
const checked = event.target.checked;
const cbs: NodeListOf<HTMLInputElement> = document.querySelectorAll('.liquidationSpreadCb');
cbs.forEach((cb: HTMLInputElement, i) => {
  cb.click();
  const itemId = cb.className.replace(/D/g, '');
  const item: ILiquidationSpread = liquidationSpreadList.filter(val => val.id === Number(itemId))[0];
  x.push(item);
});
if (!checked) {
  x = [];
}
setSelectedItems(x);

};

How I can get a list of all Ids at the beginning of the rows and select all table rows?

Como llamar a una funcion alert desde php [closed]

Tengo la siguiente duda, estoy intentando llamar a una función que contiene un alert desde un echo de php:

if($fila["seccion"]=="Escultura"){
          echo '<section class="pic escultura1">';
          echo "<a href='exposiciones/expo1.php?variable1=$seccion&variable2=$nombre'>";
          echo "<img class='agrandar' id='foto' src='$imagen' alt='Logo centro exposición' onmouseover='return animacion($enunciado);'>";
          echo '<h3 id="textostitulos">';
          echo "$nombre";
          echo '</h3></a></section>';

    }

Quiero llamar en onmouseover a la función animación, pero no se como hacerlo desde php, ya que esa función se encuentra en otro fichero js.

Automatically download file after load page php

I’m trying to implement a script on an html template where after loading the template, the file download starts automatically.
My files in question are txt, csv and xlsx.

After 2 seconds, as per setTimeout, the script is activated but it does not download the file, but opens a new page as the content of it.

Another question I wanted to ask was whether it is possible to put the absolute path of the file as the folder containing them is nested at a higher level than $ _SERVER ["DOCUMENT_ROOT"].

$file = '/var/www/.........../file.txt';
    echo "<script>
                $(function() {
                    $('a[data-auto-download]').each(function(){
                    var $this = $(this);
                        setTimeout(function() {
                            window.location.href = $this.attr('href');
                        }, 2000);
                    });
                });
            </script>
            <a data-auto-download href="".$file."">here</a>";

Adding delay in observable returns partial data in Angular rxjs

In my code I need to add delay by using timer(500). But the issue is that it returns partial data. It is returning 2 fields while actual data has 17 fields. I have attached my code. please see it. Thank you

Returned value:

 ['booking_display_id', 'edit']

Expected value:

 ['booking_display_id', 'bookingstatus', 'b_contactname', 'member', 'b_emailaddress', 'b_mobilenumber', 'startdate', 'enddate', 'duration', 'bookingguest', 'guestnotes', 'vouchers', 'paypalpaymentpdt', 'totalCost', 'canPay', 'canCancel', 'edit']

 this.displayedColumns = combineLatest(this.table.columns.reduce((observables: Observable<boolean>[], col) => {
  // handle showIf property of column
  const show = col.showIf(this.injector, this.route.queryParamMap);
  observables.push(show instanceof Observable ? show : of(show));
  return observables;
}, []), timer(500)).pipe(
  map(showCols => {
    const cols = this.table.columns.filter((c, i) => showCols[i])
      .map(c => c.id);
    this.editEnabled && cols.push('edit');
    this.deleteEnabled && cols.push('delete');
    console.log('cols', cols)
    return cols;
  })
 );