export more row in datatables footer

I check every discussion and many documentations but I didn’t find any help.

I would like to add more rows in footer when export in PDF the datatable table, I found here the code for excel export but for pdf there isn’t nothing.enter image description here

After footer row ‘Totale’ (#total_count tr) there are 8 rows not visible

This is my code:

    $('#cercaFoglioCassa').click(function() {
  $('#foglioCassa').DataTable().destroy();
  let dati = {};

  dati['min'] = $('#min').val();
  dati['max'] = $('#max').val();
  if ($('#checkSospeso').is(':checked')) {
    dati['checkSospeso'] = 'SI';
  } else {
    dati['checkSospeso'] = 'NO';
  }

  dati = JSON.stringify(dati);
  let now = new Date();
  let jsDate = now.getDate() + '-' + (now.getMonth() + 1) + '-' + now.getFullYear();

  let dataMin = $('#min').val();
  let dataMax = $('#max').val();

  // DataTables initialisation
  var table = $('#foglioCassa').DataTable({
    "language": {
      url: 'https://cdn.datatables.net/plug-ins/1.10.25/i18n/Italian.json'
    },
    "processing": true,
    "serverSide": true,
    "order": [],
    "searching": false,
    "autoWidth": false,
    "ajax": {
      url: "action.php",
      type: "POST",
      data: {
        action: 'getCassa',
        dati
      },

    },
    drawCallback: function(settings) {
      $('#total_order').html(settings.json.total);
      $('#total_bonifico').html(settings.json.bonifico);
      $('#total_contanti').html(settings.json.contanti);
      $('#total_bancomat').html(settings.json.bancomat);
      $('#total_cCredito').html(settings.json.cCredito);
      $('#total_finanziaria').html(settings.json.finanziaria);
      $('#total_assegno').html(settings.json.assegno);
      $('#total_rid').html(settings.json.rid);

    },
    "columnDefs": [{
        "targets": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
        "orderable": false,
      },
      {
        width: '10%',
        targets: 1
      }

    ],
    "dom": 'lBfrtip',
    "buttons": [{
      extend: 'collection',
      text: 'Esporta',
      buttons: [{
          extend: 'copy',
          footer: true
        },
        {
          extend: 'excelHtml5',
          footer: true,
          customize: (xlsx, config, dataTable) => {
            let sheet = xlsx.xl.worksheets['sheet1.xml'];
            let footerIndex = $('sheetData row', sheet).length;
            let $footerRows = $('tr', dataTable.footer());

            // If there are more than one footer rows
            if ($footerRows.length > 1) {
              // First header row is already present, so we start from the second row (i = 1)
              for (let i = 0; i < $footerRows.length; i++) {
                // Get the current footer row
                let $footerRow = $footerRows[i];

                // Get footer row columns
                let $footerRowCols = $('th', $footerRow);

                // Increment the last row index
                footerIndex++;

                // Create the new header row XML using footerIndex and append it at sheetData
                $('sheetData', sheet).append(`
            <row r="${footerIndex}">
              ${$footerRowCols.map((index, el) => `
                <c t="inlineStr" r="${String.fromCharCode(65 + index)}${footerIndex}" s="2">
                  <is>
                    <t xml:space="preserve">${$(el).text()}</t>
                  </is>
                </c>
              `).get().join('')}
            </row>
          `);
              }
            }
          }
        },
        {
          extend: 'csv',
          footer: true
        },
        {
          extend: 'pdfHtml5',
          orientation: 'landscape',
          footer: true,
          pageSize: 'A4',
          filename: 'fogliocassa' + jsDate,
          exportOptions: {
            columns: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
          },
          customize: function(doc) {
            //Remove the title created by dataTables
            doc.content.splice(0, 1);
            //Create a date string that we use in the footer. Format is dd-mm-yyyy
            var now = new Date();
            //var jsDate = now.getDate()+'-'+(now.getMonth()+1)+'-'+now.getFullYear();
            // Logo converted to base64
            // var logo = getBase64FromImageUrl('https://datatables.net/media/images/logo.png');
            // The above call should work, but not when called from codepen.io
            // So we use a online converter and paste the string in.
            // Done on http://codebeautify.org/image-to-base64-converter
            // It's a LONG string scroll down to see the rest of the code !!!
            var logo = '';




            // A documentation reference can be found at
            // https://github.com/bpampuch/pdfmake#getting-started
            // Set page margins [left,top,right,bottom] or [horizontal,vertical]
            // or one number for equal spread
            // It's important to create enough space at the top for a header !!!
            doc.pageMargins = [100, 80, 100, 30];
            // Set the font size fot the entire document
            doc.defaultStyle.fontSize = 11;
            // Set the fontsize for the table header
            doc.styles.tableHeader.fontSize = 7;
            // Create a header object with 3 columns
            // Left side: Logo
            // Middle: brandname
            // Right side: A document title
            if (dataMin == dataMax) {
              doc['header'] = (function() {
                return {
                  columns: [{
                      image: logo,
                      width: 64,
                    },
                    {
                      alignment: 'right',
                      fontSize: 14,
                      text: 'Foglio cassa del ' + dataMin
                    }
                  ],
                  margin: 20
                }
              });

            } else {
              doc['header'] = (function() {
                return {
                  columns: [{
                      image: logo,
                      width: 64,
                    },
                    {
                      alignment: 'right',
                      fontSize: 14,
                      text: 'Foglio cassa dal ' + dataMin + ' al ' + dataMax
                    }
                  ],
                  margin: 20
                }
              });
            }

            // Create a footer object with 2 columns
            // Left side: report creation date
            // Right side: current page and total pages
            doc['footer'] = (function(page, pages) {
              return {
                columns: [{
                    alignment: 'left',
                    text: ['Creato il: ', {
                      text: jsDate.toString()
                    }]
                  },
                  {
                    alignment: 'right',
                    text: ['Pag. ', {
                      text: page.toString()
                    }, ' di ', {
                      text: pages.toString()
                    }]
                  }
                ],
                margin: 20
              }
            });
            // Change dataTable layout (Table styling)
            // To use predefined layouts uncomment the line below and comment the custom lines below
            //doc.content[0].layout = 'lightHorizontalLines'; // noBorders , headerLineOnly
            var objLayout = {};
            objLayout['hLineWidth'] = function(i) {
              return .5;
            };
            objLayout['vLineWidth'] = function(i) {
              return .5;
            };
            objLayout['hLineColor'] = function(i) {
              return '#aaa';
            };
            objLayout['vLineColor'] = function(i) {
              return '#aaa';
            };
            objLayout['paddingLeft'] = function(i) {
              return 4;
            };
            objLayout['paddingRight'] = function(i) {
              return 4;
            };
            doc.content[0].layout = objLayout;
          }

        }
      ]
    }]
  });


  $('#risultatoFiltro').css('display', 'block'); // Mostro tabella

  //Carico incassi divisi per tipo di pagamento

  // $('#bonifico').html('Bonifico: €' + forziere['bonifico']);
  // $('#contanti').html('Contanti: €' + forziere['contanti']);
  //
  // $('#sommaIncassi').css('display','block');



});

how to use vue component as custom directive in vue

**0

I want to pass an instantiated Vue Component as a prop to another component and then render it, like so:**
**0

I want to pass an instantiated Vue Component as a prop to another component and then render it, like so:**
**0

I want to pass an instantiated Vue Component as a prop to another component and then render it, like so:**

Unable to render useState,useEffect hooks in custom component package using microbundle & React

Hi I am trying to create a sample library using react 18.2.0 & Microbundle and Although library built successfully but when it is consumed in the client app im getting the below error in console log
Error

below is my library code

App.js

import './App.css';
import Dropdown from "./components/Dropdown";

function App() {
   
  let dropdown_data = ['Item 1', 'Item 2', 'Item 3'];

    return (
      <div className="dropdown">
         <Dropdown jsonData={dropdown_data} />
      </div>
  )
}

export default App;

Created components folder under that created Dropdown.js

import React from "react";
import {useEffect, useState} from 'react';

export const Dropdown = (props) => {
    const [dropdown, setDropdown] = useState([]);
    useEffect(() => {
        loadData();
    }, []);
    const loadData = () => {
        setDropdown(props.jsonData);
    }
    return (
        <div className="dropdown">
            <select> {
                dropdown.map((item, index) => (
                    <option key={index}>
                        {item}</option>
                ))
            } </select>
        </div>
    )

}

in the src folder created the lib.package.js

export { Dropdown } from "./components/Dropdown.js";

below is my package.json

{
  "name": "libtestone",
  "version": "0.1.0",
  "private": true,
  "main": "./dist/lib.umd.js",
    "module": "./dist/lib.module.js",
    "source": "src/lib.package.js",
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.3.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "build:lib": "microbundle --jsx React.createElement --jsxFragment React.Fragment --jsxImportSource react"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "microbundle": "^0.15.0"
  }
}

Below is my client app where i am consuming the package
App.js

import './App.css';
import {Dropdown} from "libtestone";

function App() {
  return (
    <div>
      <Dropdown />
    </div>
  );
}

export default App;

Prevent user from accessing a route depending on its type

I have an app running with React, Redux and Next.js. In my redux store I have a user which has, let’s say, an attribute “type”. Each type of users has its own array of “routes” it can access.

What is the best way to prevent the user from accessing certain routes ?
I am able to redirect with Next.js Middleware but I cannot manage to pass a variable to the request with the user’s type.

Sequelize 6.5 didn’t return complete child relationships & limit the key name

here’s my question.
I’m trying to get the nested relationships by Sequelize.

let results = await FarmVisitQuestionnaire.findOne({
        where: { Customer_ID, id:2 },
        include: [{
          model: FarmVisitSection,
          include: [{
            model: FarmVisitQuestion,
            include: [{
              model: FarmVisitQuestionOption,
            }]
          }]
        }],
      });

Everything works well excepts for the deepest relationship FarmVisitQuestionOption. It didn’t return the complete data in FarmVisitQuestionOption section, there’re two FarmVisitQuestionOption data but only one FarmVisitQuestionOption is returned (“i”:1). And the key names in FarmVisitQuestionOption are limited to only the first character as below:

"questionnaires": {
        "id": 2,
        "Customer_ID": "3380",
        "Title": "Form title",
        "createdAt": "2022-07-05T19:42:50.292Z",
        "updatedAt": "2022-07-05T19:42:50.292Z",
        "FarmVisitSections": [
            {
                "id": 2,
                "Title": "Section title",
                "Description": "Section description",
                "Order": 0,
                "createdAt": "2022-07-05T19:42:50.295Z",
                "updatedAt": "2022-07-05T19:42:50.295Z",
                "FarmVisitQuestionnaireId": 2,
                "FarmVisitQuestions": [
                    {
                        "id": 1,
                        "Title": "Question title?",
                        "Description": "Question description / extra info",
                        "Order": 0,
                        "Required": "true",
                        "Type": "checkbox1",
                        "createdAt": "2022-07-05T19:42:50.299Z",
                        "updatedAt": "2022-07-05T19:42:50.299Z",
                        "FarmVisitSectionId": 2,
                        "FarmVisitQuestionOptions": [
                            {
                                "i": 1,
                                "L": "First Option",
                                "V": "1",
                                "c": "2022-07-05T19:42:50.303Z",
                                "u": "2022-07-05T19:42:50.303Z",
                                "F": 1
                            }
                        ]
                    }
                ]
            }
        ]
    }

My DB was set up correctly:
FarmVisitQuestionOption table

However, the correct FarmVisitQuestionOption section should be:

"FarmVisitQuestionOptions": 
                      [
                            {
                                "id": 1,
                                "Label": "First Option",
                                "Value": "1",
                                "createdAt": "2022-07-05T19:42:50.303Z",
                                "updatedAt": "2022-07-05T19:42:50.303Z",
                                "FarmVisitQuestionId": 1
                            },
                            {
                                "id": 2,
                                "Label": "Second Option",
                                "Value": "2",
                                "createdAt": "2022-07-05T19:42:50.303Z",
                                "updatedAt": "2022-07-05T19:42:50.303Z",
                                "FarmVisitQuestionId": 1
                            }
                        ]

Can anyone help me with this issue? Any insights would be helpful. Thanks!

how to make the button work the next time the button is pressed

What I want to do is so that when I click the yes button, all the items are removed, and when I click the reset button, everything goes back, and so many times. What I get: I press the “yes” button, everything is deleted, then the “reset” button, everything goes back, I want to press the “yes” button again, but nothing else works

    const body = document.querySelector('.body');
const message = document.querySelector('.message');
const reset = document.querySelector('.panel__close')
const bodyMessage = document.querySelector('.body__message')

function removeChilds(childs) {
    for(const child of childs){
        child.parentNode.removeChild(child);
    }
}

let childs = [];

function create() {

    // here created elements for programm...

    childs.push(bodyError, bodyErrorImage, bodyText, bodyButtons, bodyButton1, bodyButton); // the created elements are pushing into the array
}
create();


yes.addEventListener('click', () => { // here deleting all elements and creating congratulation
    removeElements(childs);
    childs = [];


    // created congratulation

    const paraLox = document.createElement('p');
    paraLox.textContent = 'Congratulation, Jaba is work!';
    paraLox.style.fontSize = '3rem';
    paraLox.style.textAlign = 'center';
    paraLox.style.fontWeight = '1000';
    paraLox.style.color = 'red';
    body.appendChild(paraLox);

    //


    reset.addEventListener('click', () => {          // reset button
        paraLox.parentNode.removeChild(paraLox);
        create();
    
    
    });


});

Cannot read properties of null (reading ‘addEventListener’) in javascript chrome extensions

I am building chrome extensions using javascript. I have some struggles on addEventListeners. Kindly check the below code

var SpellCheck = document.getElementById('spellCheck')

SpellCheck.addEventListener('click', async () => {
  let [tab] = await chrome.tabs.query({
    active: true,
    currentWindow: true
  });

  var w = 600;
  var h = 550;
  var left = (screen.width / 2) - (w / 2);
  var top = (screen.height / 2) - (h / 2);

  chrome.windows.create({ 'url': 'onboarding.html', 'type': 'popup', 'width': w, 'height': h, 'left': left, 'top': top }, function (window) { });
});

but I got the below error please help me to reach out this issue.
enter image description here

javascript this in react function component event handler

const TimerView = observer(() => {
  const [timer] = useState(() =>
    observable({
      secondsPassed: 1,
      increaseTimer() {
        console.log(this, 888);
        this.secondsPassed++;
      },
    })
  );

  return (
  //   when click the span, error: this is undefined
  //   <span onClick={timer.increaseTimer}>
  //   Seconds: {timer.secondsPassed}
  //   </span>
  //  

    <span onClick={() => timer.increaseTimer()}>
      Seconds: {timer.secondsPassed}
    </span>

  //  this one works fine
  );
});

observer and observable are in mobx and mobx-react-lite.
What’s the difference between these two situation.It’s so confused.

Highlight the whole sentence

How Can I highlight the whole sentence just by click at only one word withen that sentence.

.sentence span:hover,
.highlight {
  background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class="sentence">(1)Lorem ipsum dolor sit amet. (2) consectetur adipisicing elit. (3)Similique aliquam totam odit excepturi. (4) reiciendis quam doloremque ab eius quos.</p>



Selected words:
<p id="selectedWords"></p>

<button>Show in alert</button>

How to place cursor at end of text in input field after form submission using html and javascript?

I’ve created a text input form in html that sends user input words via POST method to Django views.py file. Here is the code for this form:

<form method="POST" action="search">
                        {% csrf_token %}
                        <input  type="search" name="search" value="{{form.search.value}}" placeholder="Search here..."  autofocus x-webkit-speech/>
                </form>  

The value attribute takes the value returned by Django after a submit. Here is the code of my Django views.py file:

from django.shortcuts import render 
import requests 
from bs4 import BeautifulSoup as bs


from search.models import MyForm



def index(request):
    return render(request, 'index.html')

def search(request):
    if request.method == 'POST':
        search = request.POST['search']
        form = MyForm(request.POST)
        
        max_pages_to_scrap = 15
        final_result = []
        for page_num in range(1, max_pages_to_scrap+1):
            url = "https://www.ask.com/web?q=" + search + "&qo=pagination&page=" + str(page_num)
            res = requests.get(url)
            soup = bs(res.text, 'lxml')
            result_listings = soup.find_all('div', {'class': 'PartialSearchResults-item'})

            for result in result_listings:
                result_title = result.find(class_='PartialSearchResults-item-title').text
                result_url = result.find('a').get('href')
                result_desc = result.find(class_='PartialSearchResults-item-abstract').text
           
                final_result.append((result_title, result_url, result_desc))

        context = {'final_result': final_result, 'form':form}
        

        return render(request, 'index.html', context)

    else:
        return render(request, 'index.html')


When I submit the form, the value of the input field is well preserved but the cursor goes from the final position to the initial position. To solve this problem, I inserted a javascript script created in this article, in my index.html file which contains my form:

 
    <script>
  
        /* Creating a function called PosEnd
         in JavaScript to place the cursor 
         at the end */
        function PosEnd(end) {
            var len = end.value.length;
              
            // Mostly for Web Browsers
            if (end.setSelectionRange) {
                end.focus();
                end.setSelectionRange(len, len);
            } else if (end.createTextRange) {
                var t = end.createTextRange();
                t.collapse(true);
                t.moveEnd('character', len);
                t.moveStart('character', len);
                t.select();
            }
        }
    </script>

and I modified the form like this:

<input  type="search" name="search" value="{{form.search.value}}" placeholder="Search here..."  autofocus x-webkit-speech/>

became:

<input  type="search" name="search" PosEnd(value="{{form.search.value}}") placeholder="Search here..."  autofocus x-webkit-speech/>

but now when i submit the form the input values ​​are lost.

Discord.js – TypeError: message.delete is not a function (while deleting a reply to a command in DM)

await interaction.editReply(`Done! I counted to ${number}`)
                .then(message => setTimeout(() => message.delete(), 3000))

This gives an error while trying to delete a reply message in DM on Discord:

TypeError: message.delete is not a function

However it perfectly works in server channel. I would use deleteReply() but this does not work when you have edited the reply with editReply(). I should note though that deleteReply() for deleting a message that has not being edited works on DM and servers.

REGEX works when testing in regex101 but doesnt always work when executing script

So im working on a script and im trying to match certain patterns in some documents, thing is, while it works 9/10 times, SOMETIMES, it just refuses to work, ive tried checking in Regex101 and RegExr and it should work. But it doesnt.

  const ENDTIMEREGEX = /(Hora|Horario) de (cierre|finalización): (dd(:|.)dd)/ ;

Example of the text im having an issue with:

  1. NOTIFICAR a las partes en este acto, a las víctimas por intermedio de la Fiscalía, a la OCSPP una vez que venza el plazo para recurrir y,
    oportunamente, COMUNICAR.

Hora de cierre: 11:57 horas

PALABRAS CLAVE: resolucion_interlocutoria
suspension_del_proceso_a_prueba_reanuda_plazos

While other times im trying to match something thats like almost the exact same and it just works:

Hora de cierre: 13:13 horas.

That case works, but i dont see any difference or reason why this one would and the other wont.

Like, it should work! I’ve even tried just matching the exact text and it still wont work for some reason (also yes, ive tried looking for similar questions, but i havent found any with my particular problem)

Heroku worker crashing instantly when starting discordjs bot

I have been working on a discord bot that is working fine when run locally, but it is crashing when hosted on heroku.

  • I tried to create a Procfile with the following line: worker : node bot.js
  • I also checked in heroku resources, disabled web and enabled the worker dyno.
  • I have not exceeded the 550 hour monthly limit.

This is the package.json:

{
  "name": "randomizerbot",
  "version": "1.0.0",
  "description": "",
  "main": "bot.js",
  "scripts": {
    "start": "node bot.js"
  },
  "engines": {
    "node": ">=16.6.0"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "discord.js": "^13.6.0",
    "dotenv": "^16.0.0",
    "nodemon": "^2.0.15"
  }
}

This is my file structure:

file structure

This is the error log:

2022-07-11T14:48:48.995714+00:00 heroku[worker.1]: State changed from crashed to starting

2022-07-11T14:48:51.478349+00:00 heroku[worker.1]: Starting process with command `: node bot.js`

2022-07-11T14:48:52.092041+00:00 heroku[worker.1]: State changed from starting to up

2022-07-11T14:48:52.341005+00:00 heroku[worker.1]: Process exited with status 0

2022-07-11T14:48:52.809725+00:00 heroku[worker.1]: State changed from up to crashed

Is there something that I am missing?
Thanks in advance.

React setState not updating state inside stomp.js callback function

I have a page that connects to a SockJS socket over stomp. But when pass a function that is supposed to change the state to the .subscribe callback it doesn’t change the page’s state (the rest of the function completes normally)
Here is the code:

function initSocket() {
    const socket = new SockJS(`${process.env.API_URL}/ws`);
    const stompClient = over(socket);
    stompClient.connect(
        {},
        () => onSocketConnected(stompClient),
        onSocketError
    )
    appContext.setSocket(stompClient)
}

function handleIncomingCall(data) {
    const state = JSON.parse(data.body.toLowerCase());
    setIsIncomingCall(state)
}

function onSocketConnected(stompClient) {
    const options = {
        accessToken: cookies['logged-in'],
    };

    stompClient.send("/app/connect", {}, JSON.stringify(options));
    stompClient.subscribe(`/user/search/complete`, handleSearchComplete)
    stompClient.subscribe(`/user/search/failed`, handleSearchError)
    stompClient.subscribe(`/user/call/incoming`, handleIncomingCall)
}

The initSocket function is called on page render inside the useEffect.
I have tried wrapping the callback with a useCallback and binding it to the page, but it didn’t seem to help.