I am writing a code to check if number is a palindrome or not. But when i check the output for 2 numbers, its coming different

V SIMPLE code: function allPalindromicPerms(num){
//find reverse of a number and then comapre the reversed number with the main number
var finalNum = 0;
var originalNum = num;
let remainder= 0;
while(num){
remainder = num % 10;
console.log(‘remainder’+remainder);
num = num – remainder;
num = num / 10;
finalNum = finalNum*10 + remainder;
console.log(finalNum);

  }
  if(finalNum == originalNum){
       console.log("is palindrome");
     
  }else{
       console.log("not a palindrome");
    
      
  }
    

}

allPalindromicPerms(23456788888765432) – with the the output is coming fine.

allPalindromicPerms(234567888888765432) – but this is not giving me right output.

could you help me what is wrong?

How do I enable a Gauge chart in Billboard.js to go past 100%, but still show the gauge filled?

I have a gauge chart that I need to go past 100% when it is filled to represent output time done by a machine. I need it to go past 100% simply to showcase efficiency. I have tried to enable a max value higher than 100%, but I need the gauge to be filled at 100%, but the label to show the value passed 100%. Is there a rule of thumb for this or would I need to remake the gauge chart entirely?

enter image description here

Might it be possible to do it in a sort of tiered fashion in the same way a multi gauge chart does it? I am thinking of dividing the performance into a sort of tiered structure to better show the data. The idea I have is that when the first tier is reached the next would start populating. IE when purple’s done red starts then green and so on.
enter image description here

A function in a nodejs module is defined, but shows undefined when acessed?

I am making a Discord bot in using NodeJS and TypeScript and am trying to import some custom modules in a loop using the following code:

const eventFiles = fs.readdirSync("./src/events/").filter((file: string) => file.endsWith('.ts'));

for(const file of eventFiles)
{
    const module: string = file.substring(0, file.length - 3);

    const event = require(`./events/${module}`);

    console.log(event);
    console.log(`Function: ` + event.exectue);

    if(event.once)
    {
        client.once(event.name, (...args) => event.exectue(client, ...args));
    }
    else
    {
        if(event.isasync) client.on(event.name, async (...args) => await event.exectue(client, ...args));
        else client.on(event.name, (...args) => event.exectue(client, ...args));
    }
}

From the debugging I have done so far, it appears that I am successfully loading the execute functions from my modules when I log the module to the console, however the execute function is undefined on every module except the last one?

Does anyone know what is happening? Thanks!

Algorithm Javascript

Question Description:

Permission to ask, regarding the questions below :

Trefor has 10, 5, 2, 3, 6, 7 coins and wants to buy goods for 23 coins with a transaction fee of 0.5 coins per coin, mention the coins needed based on the cheapest transaction fee, mention the remaining coins owned and the transaction fee.**

Example

Input: [10, 5, 2, 3, 6, 7]
Total Transactions**: 23**

Fee Per Coin: 0.5

Output:

Required Coins: [10,7,6, 5]
Cost: 2

Remaining coins: [3, 3, 2]

const input = document.getElementById("input");
      const btn = document.getElementById("btn");
      const output = document.getElementById("output");
      btn.addEventListener("click", function () {
        let arr = input.value.split(",");
        let total = 0;
        let fee = 0.5;
        let coin = [];
        let remnant = [];
        let cost = 0;
        for (let i = 0; i < arr.length; i++) {
          total += parseInt(arr[i]);
        }
        for (let i = 0; i < arr.length; i++) {
          if (total - parseInt(arr[i]) >= 0) {
            total -= parseInt(arr[i]);
            coin.push(arr[i]);
          } else {
            remnant.push(arr[i]);
          }
        }
        cost = coin.length * fee;
        output.innerHTML = `Required Coins: ${coin}<br>Cost: ${cost}<br>The rest of the coin: ${remnant}`;
      });
<input type="text" id="input" placeholder="coin" />
    <button id="btn">Submit</button>
    <div id="output"></div>
   

MUI – useGridRootProps should only be used inside the DataGrid/DataGridPro component

We’re getting this error when clicking “Filter” in the context menu of our DataGrid. We are attempting to implement this hierarchy of components for the DataGrid like so:

MigrationJobTable.tsx:

    return (
        <div data-testid='migrationJobTable' style={{ height: '100%', width: '100%' }}>
            <ClientSideDataGrid
                rows={rows}
                columns={MigrationJobColumns({ setIsPageLoading, caseId, userId })}
                setRows={setRows}
                GetRowsFromResponseObject={GetRowsFromResponseObject}
                apiString={apiString}
                initialSortModel={[{ field: 'JobId', sort: 'desc' }]}
                getRowId={(x: MigrationJob) => x.JobId}
                isPageLoading={isPageLoading}
                disableVirtualization={disableVirtualization}
                // Tests for this component do not pass without this
                columnBuffer={9}
            />
        </div>
    );

ClientSideDataGrid.tsx

interface Props extends DataGridProProps {
    initialSortModel: GridSortModel | undefined;
    disableVirtualization?: boolean | undefined;
    setRows?: Function | undefined;
    GetRowsFromResponseObject?: Function | undefined;
    apiString?: string | undefined;
    enablePagination?: boolean;
    CustomNoRowsOverlay?: React.JSXElementConstructor<any> | undefined;
    isPageLoading?: boolean | undefined;
    pageSize?: number | undefined;
}

    return (
        <div className="data-grid-pro-class" data-testid="clientSideDataGrid" style={{ height: '100%', width: '100%' }}>
            <BaseDataGrid
                {...props}
                rowCount={props.rows.length}
                page={page}
                componentsProps={{
                    pagination: {
                        dataLoadType: DataLoadType.CLIENT,
                        RefreshRows: LoadRows,
                        pageSize: props.pageSize ?? defaultPageSize,
                        page: page,
                        setPage: setPage
                    }
                }}
            />
        </div>
    );

BaseDataGrid.tsx:

interface Props extends DataGridProProps {
    initialSortModel: GridSortModel | undefined;
    disableVirtualization?: boolean | undefined;
    setRows?: Function | undefined;
    GetRowsFromResponseObject?: Function | undefined;
    apiString?: string | undefined;
    enablePagination?: boolean;
    CustomNoRowsOverlay?: React.JSXElementConstructor<any> | undefined;
    isPageLoading?: boolean | undefined;
    pageSize?: number | undefined;
}

    return (
        <div className="data-grid-pro-class" data-testid="serverSideDataGrid" style={{ height: '100%', width: '100%' }}>
            <DataGridPro
                {...props}
                localeText={determineLocaleFromBrowserSetting()}
                rowHeight={27}
                headerHeight={47}
                disableSelectionOnClick={true}
                disableVirtualization={props.disableVirtualization ?? false}
                pagination={props.enablePagination ?? true}
                pageSize={props.pageSize ?? defaultPageSize}
                rowsPerPageOptions={[props.pageSize ?? defaultPageSize]}
                components={{
                    Pagination: DiscoverPagination,
                    NoRowsOverlay: props.CustomNoRowsOverlay ?? GridNoRowsOverlay
                }}
                disableMultipleColumnsSorting
                initialState={{
                    sorting: {
                        sortModel: props.initialSortModel
                    }
                }}
            />
            <Backdrop sx={{ zIndex: (theme) => theme.zIndex.drawer + 1 }} open={props.isPageLoading ?? false}>
                <CircularProgress />
            </Backdrop>
        </div>
    );

We did not get this issue before trying to use this modularized component hierarchy. We wanted to switch to this format to reuse and force other devs to use a base set of props. Any ideas?

Dropzone Rails Gem How to Send with 0 Files

I want to know the right way on how I handle still sending even when I have 0 files uploaded. I have a form that has a lot of data to input and the images are optional.

I could probably send this with an entirely separate Ajax request that is a duplicate of ‘sendingmultiple’, otherwise I am unsure if this is possible within the confines of dropzones solutions in handling this case.

  Dropzone.options.dropzone =
    url: '/test/create'
    autoProcessQueue: false
    clickable: true
    uploadMultiple: true
    timeout: 180000
    parallelUploads: 8
    maxFiles: 8
    maxFilesize: 5
    acceptedFiles: 'image/*'
    addRemoveLinks: true
    headers: 'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
    init: ->
      dzClosure = this

      document.getElementById('submit-button').addEventListener 'click', (e) ->
        e.preventDefault()
        e.stopPropagation()
        dzClosure.processQueue()
        return

      @on 'sendingmultiple', (data, xhr, formData) ->
        formData.append 'item_number', jQuery('#item_number').val()
        ... more form data
        return
      @on 'success', (file, responseText) ->
        window.location.href = url
        return
      return

Is there a way to make my CSS overlay take over the whole page? Stuck in an iframe

I’m attempting to create a decent button banner for my site because the text navigation makes the page look really wonky.

When clicking on any of the three buttons a curtain menu slides down into place. The problem is that I’m using Google Sites and the code has to be embedded within a frame.

I need the curtain menu to jump out of its frame and cover the entire page. I’ve tried changing the position and overflow elements to no avail.

I’m a complete noob. It’s taken me a week to get to this point and have been attempting to figure out this curtain menu for two days. I’m a little burned out on it – probably something simple that I’m missing.

<!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    body {
      font-family: 'Lato', sans-serif;
    }
    
    .container {
      display: flex;
      flex-flow: row nowrap;
      gap: 10px;
      justify-content: center;
      width: 100%;
      padding top: 30px
    }
    
    .overlay {
      height: 0%;
      width: 100%;
      position: fixed;
      z-index: 1;
      top: 0;
      left: 0;
      background-color: rgba(0, 0, 0, 0.9);
      overflow-x: auto;
      overflow: scroll;
      text-align: center;
      transition: .5s;
    }
    
    .overlay a {
      text-decoration: none;
      font-size: 24px;
      color: #818181;
      display: block;
      transition: 0.3s;
    }
    
    .overlay a:hover,
    .overlay a:focus {
      color: #f1f1f1;
    }
    
    .overlay-content {
      display: flex;
      flex-direction: column;
      position: relative;
      top: 25%;
      width: 100%;
      text-align: center;
    }
    
    .closebtnOverlay {
      position: absolute;
      top: 20px;
      right: 45px;
      font-size: 50px !important;
    }
    
    .button {
      background-color: #FF8C00;
      border: 2px solid #338C9A;
      border-radius: 12px;
      color: white;
      width: 120px;
      height: 40px;
      text-align: center;
      text-decoration: none;
      font-weight: bold;
      display: inline-block;
      font-size: 16px;
    }
    
    .button:hover {
      box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24), 0 17px 50px 0 rgba(0, 0, 0, 0.19);
    }
    
    @media screen and (max-height: 450px) {
      .overlay a {
        font-size: 20px
      }
      .closebtnOverlay {
        font-size: 40px !important;
        top: 15px;
        right: 35px;
      }
    }
  </style>
</head>
<div class="container">
  <div id="myNav" class="overlay">
    <a href="javascript:void(0)" class="closebtnOverlay" onclick="closeNav()">×</a>
    <div class="overlay-content">
      <a href="javascript:void(0)">Phoenix</a>
      <a href="javascript:void(0)">Prescott</a>
      <a href="javascript:void(0)">Scottsdale</a>
      <a href="javascript:void(0)">Tucson</a>
    </div>
  </div>
  <div id="myNav2" class="overlay">
    <a href="javascript:void(0)" class="closebtnOverlay" onclick="closeNav2()">×</a>
    <div class="overlay-content">
      <a href="javascript:void(0)">Cape Coral</a>
      <a href="javascript:void(0)">Jacksonville</a>
      <a href="javascript:void(0)">Lakeland</a>
      <a href="javascript:void(0)">Miami</a>
      <a href="javascript:void(0)">Ocala</a>
      <a href="javascript:void(0)">Orlando</a>
      <a href="javascript:void(0)">Palm Beach</a>
      <a href="javascript:void(0)">Pensacola</a>
      <a href="javascript:void(0)">Port Charlotte</a>
      <a href="javascript:void(0)">Sarasota</a>
      <a href="javascript:void(0)">St. Augustine</a>
      <a href="javascript:void(0)">St. Petersburg</a>
      <a href="javascript:void(0)">Tallahasse</a>
      <a href="javascript:void(0)">Tampa</a>
    </div>
  </div>
  <div id="myNav3" class="overlay">
    <a href="javascript:void(0)" class="closebtnOverlay" onclick="closeNav3()">×</a>
    <div class="overlay-content">
      <a href="javascript:void(0)">Austin</a>
      <a href="javascript:void(0)">Dallas</a>
      <a href="javascript:void(0)">Houston</a>
      <a href="javascript:void(0)">San Antonio</a>
    </div>
  </div>
  <button class="button" onclick="openNav()">Arizona</button>
  <button class="button" onclick="openNav2()">Florida</button>
  <button class="button" onclick="openNav3()">Texas</button>
  <script>
    function openNav() {
      document.getElementById("myNav").style.height = "100%";
    }

    function closeNav() {
      document.getElementById("myNav").style.height = "0%";
    }

    function openNav2() {
      document.getElementById("myNav2").style.height = "100%";
    }

    function closeNav2() {
      document.getElementById("myNav2").style.height = "0%";
    }

    function openNav3() {
      document.getElementById("myNav3").style.height = "100%";
    }

    function closeNav3() {
      document.getElementById("myNav3").style.height = "0%";
    }
  </script>
</div>
</body>

</html>

React: Expand/collapse material UI Data table

I am trying to show a component when a user clicks on a table row. when specific table row is clicked a DriverTripOverview component should expands right below it.

Current state of my implementation

When I click on a specific row, the DriverTripOverview component is shown below the whole table.

What I want
I want to show the component below clicked table row.

Here is my code
TripsTable.js (minimal code)

function TripsTable({ data, userSettings, refetchData, ...props }) {
  const classes = useStyles();
  const { t } = useTranslation();
  const isKm = userSettings.metrics === Metrics.KM;

  const columns = [
    {
      field: "collision",
      headerName: " ",
      flex: 0.7,
      disableColumnMenu: true,
      renderCell: (params) => (
        <span className={classes.iconsCell}>
          {params.row.events
            .map((e) => e.event_type_name)
            .includes("COLLISION") && (
            <img src={collision} alt="" title="Collision" />
          )}
          {params.row.isBeaconTagged && (
            <img src={BeaconsIcon} alt="" title="Beacon" />
          )}
          {params.row.isBluetoothTagged && (
            <img src={BluetoothIcon} alt="" title="Bluetooth" />
          )}
        </span>
      ),
    },
    {
      field: "tripStartTimeStr",
      headerName: t("date"),
      flex: 1.5,
      disableColumnMenu: true,
      sortComparator: (v1, v2, p1, p2) => new Date(v1) - new Date(v2),
      renderCell: (params) => (
        <pre>
          <span
            style={{
              marginLeft: 0,
              padding: "5px 7px",
              borderRadius: 7,
              color: params.row.score < 72 ? "#fff" : "",
              fontWeight: "normal",
              backgroundColor:
                params.row.score < 72 ? "#F44138" : "transparent",
            }}
          >
            {params.value}
          </span>
        </pre>
      ),
    },
    {
      field: "tripType",
      headerName: t("tripType"),
      flex: 1.4,
      disableColumnMenu: true,
      hide: isHiddenTripType,
      renderCell: (params) => (
        <TripTypeSelector
          type={params.value}
          tripId={params.row.tripId}
          refetchTrips={refetchData}
        />
      ),
    },
    {
      field: "drivingTimeSeconds",
      headerName: t("drivingTime"),
      flex: 1.1,
      disableColumnMenu: true,
      sortComparator: (v1, v2, p1, p2) =>
        p1.api.getRow(p1.id).drivingTimeSeconds -
        p2.api.getRow(p2.id).drivingTimeSeconds,
      renderCell: (params) => (
        <span>
          {Math.round(params.value / 60)} {t("minutes")}
        </span>
      ),
    },
    {
      field: "distanceDriven",
      headerName: t(isKm ? "kilometersDriven" : "milesDriven"),
      flex: 1.1,
      disableColumnMenu: true,
      sortComparator: (v1, v2, p1, p2) =>
        p1.api.getRow(p1.id).distanceDriven -
        p2.api.getRow(p2.id).distanceDriven,
      valueFormatter: (params) =>
        `${params.value.toFixed(2)} ${t(isKm ? "km" : "mi")}`,
    },
    ...DrivingBehaviourKeysArr.map((evnt) => ({
      field: evnt,
      headerName: t(evnt),
      flex: 0.9,
      disableColumnMenu: true,
      renderCell: eventScoreCell,
    })),
    {
      field: "fleetId",
      headerName: t("Fleet"),
      flex: 1.1,
      disableColumnMenu: true,
    },
    {
      field: "category",
      headerName: t("category"),
      flex: 1.1,
      disableColumnMenu: true,
      sortComparator: (v1, v2, param1, param2) =>
        param1.api.getCellValue(param1.id, "score") -
        param2.api.getCellValue(param2.id, "score"),
      renderCell: (params) => (
        <span style={{ color: getCategoryColor(params.row.score) }}>
          {params.value}
        </span>
      ),
    },
    {
      field: "score",
      headerName: t("score"),
      flex: 1,
      disableColumnMenu: true,
    },
  ];

  const [isVisible, setIsVisible] = useState(true);
  const { fleetId, driverId } = useParams();
  const { tripId } = useQuery();
  const history = useHistory();
  const ref = useRef();

  const filteredData = isOnlyBusinessTrips
    ? data.filter((row) => row.tripType == TripTypes.BUSINESS)
    : data;

  const trip = useMemo(
    () => filteredData.find((t) => t.tripId === tripId),
    [filteredData, tripId]
  );

  useEffect(() => {
    setTimeout(() => ref.current?.scrollIntoView({ behavior: "smooth" }), 100);
  }, [isVisible, trip]);

  const handleSelectTrip = useCallback(
    (row) => {
      if (row.id !== tripId) {
        history.push(FrontendRoutes.DRIVER_OVERVIEW(fleetId, driverId, row.id));
        setIsVisible(true);
      } else {
        setIsVisible(!isVisible);
      }
    },
    [isVisible, driverId, tripId]
  );

  const rows = useMemo(
    () => filteredData.map((d) => ({ ...d, id: d.tripId })),
    [filteredData]
  );
  // console.log("data", data);
  return (
    <ChartWrapper {...props}>
      <div className={classes.root}>
        <DataTable
          selectionModel={tripId ? [tripId] : undefined}
          rows={rows}
          columns={columns}
          onCellClick={handleSelectTrip}
        />
      </div>

      {trip && isVisible && (
        <DriverTripOverview trip={trip} userSettings={userSettings} />
      )}
      <span ref={ref} />
    </ChartWrapper>
  );
}

export default memo(TripsTable);

How can show DriverTripOverview component below every clicked table row?

Use jest.spyOn with mockImplementation to throw an Error

I have a function called read within index.ts that uses Node.js promisify from the util module. The read function is surrounded by a try/catch and I would like to test, using jest, that when code fails console.error is called.

index.ts/read

export async function read(): Promise<string> {
    try {
        const readFileProm = promisify(readFile);
        const content = await readFileProm(__filename);
        console.log(content.toString());
        return content.toString();
    } catch (error) {
        console.error(error);
    }
}

testcase (jest)

    describe(`Read Function`, () => {
        it(`should call 'console.error' with error message 'An error has occurred'`, async () => {
            const consoleSpy = jest.spyOn(console, 'error');
            jest.spyOn(util, 'promisify')
                .mockImplementation(() => { throw new Error('An error has occurred')});
            await read();
            expect(consoleSpy).toHaveBeenCalledWith('An error has occurred');
        });
    });

According to the jest docs, I can spyOn and mock the implementation of the promisify function and what I’m expecting to happen is it throw an error, but no error is thrown causing the test case to fail. When I debug it goes the promisify function goes right to the next line. How can I mock the promisify with jest so that it causes throws the error causing the catch block to run the console.error to run?

How to wait FileReader.onload loads file successfully?

what I want to do is just simply read multiple file information through for loop. However, Javascript does not wait for the FileReader.onload even if I used Promise.

How can we wait for the FileReader.onload ? Here is the code example.

    const promises = [];
    for (let i = 0; i < files.length; i++) {
      promises.push(
        new Promise((resolve, reject) => {
          const fileReader = new FileReader();
          const filename = files[i].object.name;

          audioDict.filename[i] = filename;
          fileReader.readAsArrayBuffer(files[i].object);
          fileReader.onload = function (e: any) {
            audioCtx
              .decodeAudioData(e.target.result)
              .then(function (decodedData: AudioBuffer) {
                // source.buffer = decodedData;

                audioDict.audio[i] = {};
                for (let c = 0; c < decodedData.numberOfChannels; c++) {
                  audioDict.audio[i][c] = decodedData.getChannelData(c);
                }
                audioDict.sr[i] = decodedData.sampleRate;
              });
          };
          resolve(audioDict);
        })
      );
    }

    Promise.all(promises).then(() => {
      // Do something using audioDict here.
      console.log("done!");
    });

FATAL ERROR: Reached heap limit Allocation failed – JavaScript heap out of memory node, error persiting after change the max-old-space-size

I am building a scraper with nodejs cheerio, puppeteer and building a frontend with create-react-app.

My scraper take div, p h1,h2… element of a page and for each div it try to find work with regex.

The goal is to find address on the website but there is no id no class that allow to identify the address so I have to scrape the text content and math with regex. I think maybe those operations are quiet loud but everything was fine since I change some state on my frontend react app and I run again the full app and got the heap out of memory error in my backend terminal.

I try everything they say on google from people that get the same error. I change the –max-old-space-size to 8092 when runnin my app and in the package.json also in the start script I change the node env variable NODE_OPTIONS=–max-old-space-size=8192 in my bash file on my computer but nothing work…

It really slow now when I run my node app and seem to get stuck in the getScreenshot function.

I tried to run a small part of my code but it seem a memory is satured and need to clear because seem that I can’t run any script with node now!

I update my node version to 18 but nothing change also

The problem is that this project is for a client and I should send it in few days!!
Please can anyone can help me I totally stuck, thank you so much for any answer …!!!
this is my app code :

// ** app.js **

const path = require('path')
const fs = require('fs');


const Excel = require("xlsx");
const puppeteer = require('puppeteer');
const cheerio = require('cheerio');
const axios = require('axios')
const express = require('express')
const { Cluster } = require("puppeteer-cluster");
const app = express();
const PORT = 8000;
 

app.use(express.json())
app.use(express.urlencoded({ extended: true}))
app.use('/images', express.static(path.join(__dirname, 'images')))
 
 
app.use( (req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT, PATCH, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  next();
})
 
 
// functions
const getLinks = require('./functions/getLinks')
const getScreenShot = require('./functions/getScreenShot')
const getPaths = require('./functions/getPaths')
 
/// Excel file 
 
const file = Excel.readFile('./file/occitanie.xlsx');
const sheetName = file.SheetNames;
const data = Excel.utils.sheet_to_json(file.Sheets[sheetName[0]], {defval: ""});
 
let festivals = [];
 
data.forEach( festival => {
 
  const isDataMissing = !festival.num_voie && !festival.type_voie && !festival.nom_voie && !festival.complement_adresse;
  ;
 
  if(isDataMissing){
       return festivals.push({ id: festival.identifiant, name: festival.Nom, url: festival.site_internet})  ;
  } else {
       return;
  }
})
 
console.log(festivals.length)
// data.forEach( festival => {
//      return festivals.push({id: festival.identifiant, name: festival.Nom, url: festival.site_internet}) ;
// })
 
 
const scraper = async (festival) => {
    try {
      
          // puppeteer
          const browser = await puppeteer.launch();;
          const page = (await browser.pages())[0];
          // await page.setDefaultNavigationTimeout(0);
          // await page.setViewport({ width: 1280, height: 1024 });
          await page.goto(festival.url) 
          
  
          // cheerio
          const response  = await axios.get(festival.url);
          const isDownloadable = await response.headers['content-disposition'] === undefined? false : true ;
 
          if(!isDownloadable){
 
            const $ = await cheerio.load(response.data);
            let resultsLinks = await getLinks($, festival)
            console.log('RESULTS LINKS',resultsLinks)
  
            const image =  await getScreenShot(festival,$,page,browser, 1000);
            festival.image = image;
 
  
            // get screenshot from interesting page on website
  
            if(resultsLinks.length > 0){
  
                  const imageUrls = await getPaths(resultsLinks,festival,browser)
                  festival.images = imageUrls
                  return festival
 
            } else {
              return festival;
            }
 
          } else {
            return festival.message = "Le contenu est téléchargeable, il ne peut pas être lu. "
          }
         
  
    } catch (err) {
      console.log(err, "Erreur au cours de la collecte de l'url du festival", festival.url, festival.name)
      return festival = {id: festival.id, name: festival.name, url: festival.url, image: [],images: [], message: `Erreur: ${err.message} : ${festival.url}`};
  }
}
 
 

 
 
// //   // routes
 
app.get('/', (req,res,next) => {
 
  const scrapers = festivals.slice(0,3).map(scraper);
  Promise.all(scrapers)
  .then( festivals => {
 
    // let data = {page: 1, data: festivals}
    // console.log(data)
    // fs.writeFileSync('result.json', JSON.stringify(data))
    console.log(festivals)
 
    res.status(200).json([{totalPage: festivals.length, data : festivals}])
  })
 
})
 
 
app.get('/results/', (req,res,next) => {
  const currentPage = Number(req.query.page) || 1;
  const lastPage = currentPage - 1;
  const perPage = 3;
  const totalFestival = Number(festivals.length);
  const totalPage = Math.ceil(totalFestival / perPage)
  const isLastPage  = currentPage === totalPage? true : false;
  let start = lastPage * perPage;
  let end = currentPage * perPage;
 
  const scrapers = festivals.slice(start,end).map(scraper);
 
  Promise.all(scrapers)
    .then( festivals => {
      console.log(festivals)
      res.status(200).json(festivals)
  })
 
})
 
 
 app.listen(PORT, () => console.log('server is running'))

**// then the getSnapshot function **

const getMatch = require('./getMatch')
const process = require('process')


const getScreenShot = async (festival,$,page,timeout) => {
  
  $('section,select,div,img,span,a,i,b,li,p,h1,h2,h3,h4').each( function () {
    let html = $.html($(this).clone().children().remove().end()); // html parent without children
    let text = $(this).clone().children().remove().end().text();
    const used = process.memoryUsage().heapUsed / 1024 / 1024;
    console.log(process.memoryUsage())
    let match = getMatch(text);
    let textReplace = text;
    if(match.length > 0){

       for(let i = 0; i < match.length; i++){
             const regexMatch = new RegExp(match[i],'g');
             textReplace = textReplace.replace(regexMatch,`<mark>${match[i]}</mark>`);
       }

       const replaceParent = $.html($(this).children().remove().end().html(textReplace))
    
    }
 
})
const idImage = festival.id + festival.name.normalize("NFD").replace(/[u0300-u036f]/g, "").replace("'", '').split(' ').join('') + Math.round(Math.random()*10000) + '.jpg';
const path = './images/'+ idImage;

await page.setContent($.html())
await page.waitForTimeout(timeout)
const image = await page.screenshot({path: path, fullPage: true})
// const b64string = await page.screenshot({ encoding: "base64", fullPage: true })
// const buffer = Buffer.from(b64string, "base64");
await browser.close()

return image;
}

module.exports = getScreenShot
```

Express request.cookies is seting the cookies with %

I’m trying to set this dictionary:
dados: { email: '[email protected]', iduser: 3, nome: 'Daniel David', nomecategoria: 'Protetor' } in a cookie using request.session.

My code that is trying set is as it:

response.cookie('lgadasdadfdvqwdsfgweklfcwevw_wdwcbwecwv_Wdwd', JSON.stringify(dados).replace(":", "=").replace(/{|}|"/g, "").replace(",", ";"), { maxAge: 900000, httpOnly: false }); 

But when I will see the cookie, it is as it:

email%3Ddanielfernandolucianodavid48%40gmail.com%3Biduser%3A3%2Cnome%3ADaniel%20David%2Cnomecategoria%3AProtetor

Print of the cookie seted in Chrome browser

How do i make these widgets responsive?

I am very new to GIS development. I was given the task to solve a few issues pertaining to some widgets that are present in a web app. The main objective is to render all widgets responsive regardless of the screen size of the device (laptop, desktop computer, phone, tablet, etc).

In attempting to understand the first step to follow, i decided to visit this site:

https://developers.arcgis.com/web-appbuilder/guide/make-widget-responsive.htm

which suggests there are two ways to solve the problem:

1.- modify the css layout – jimu.js/css/jimu.css

2.- modify the dijit layout – jimu.js/dijit/TileLayoutContainer.js

I opted to go for the jimu.css file, but the problem is I don’t know what code to add or modify. Here i have attached a screenshot of the webapp viewed from a mobile device.

enter image description here

As you can see from the picture, the widgets on the screen are misplaced. I would like to take full control of them and make them responsive for mobile devices.

I have also attached the css file. I will be very thankful if you could give me a few suggestions.

https://drive.google.com/file/d/1Y3liOWzS7CasOUEGykagSYC_oYKhUIXa/view?usp=sharing

Best Regards

Function not returning correct output from array input

Here is my code:

function filterOddLengthWords(words) {

  for (let i = 0; i < words.length; i++) {

    if (words[i].length % 2 === 1) {
      
    }
    return words[i];
  }
}

If I run array ['there', 'it', 'is', 'now'] as an argument, I am only getting ‘there’ back (output should be both there and now. I wrote the return outside of the conditional so it iterates through the entire array AND within the conditional but output is still just ‘there’. What am I missing here?