How to iterate thoug a Parameters tuples in TypeScript

How do you iterate though the TestParams tuple? I know that you can access it by index. But I want to go through each parameter type using iteration. Like a for

function auxFunction(arg1: number, arg2: string, arg3: boolean): string {
       return arg1 + arg2;
}

type TestParams = Parameters<typeof auxFunction>;

Notice that if i use the following line it shows an error: ‘i’ refers to a value, but is being used as a type here. Did you mean ‘typeof i’?

let i = 0;
type ParamType = TestParams[i];

Can’t take screenshot of hovered element in Cypress

I’m trying to take a screenshot of an element in with the hover effect, but the screenshots always come out without the hover effect.

    tableListMaps.lineWithText('Hello world', 'myLine');
    cy.get('@myLine').realHover().within(() => {
      highlightElement(commonMaps.BUTTON_DOWNLOAD_INLINE);
    });
    cy.screenshot('downloadScreenshot');

If I later on come back and hover over this element, I can see what I was trying to highlight was highlighted successfully, but it wasn’t captured by the screenshot.

Is there a way I could “fixate” the hover effect?

Context with spotify API

I’m trying to make a spotify stats app and I’m trying to make a context to save the token that the app gives you in the url when the user logs in.

TokenContext.js:

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

// query is the state
// SearchHandler is a function for changing the state.
export const TokenContext = React.createContext({
    token: "",
    logOut: () => { },
    logIn: () => { }
});

function getInitialState() {
    const token = localStorage.getItem('token')
    return token ? token : ""
}

// Defining a simple HOC component
const TokenContextProvider = (props) => {

    const [token, setToken] = useState(getInitialState);

    // Use Effect for getting the token form the url and saving it in the local storage
    useEffect(() => {
        const hash = window.location.hash
        let _token = window.localStorage.getItem("token")

        if (!_token && hash) {
            _token = hash.substring(1).split("&").find(elem => elem.startsWith("access_token")).split("=")[1]

            window.location.hash = ""
            window.localStorage.setItem("token", _token)
        }
        setToken(_token)


    }, [])

    const logIn = (token) => {
        setToken(token);
    };

    const logOut = () => {
        setToken("")
        window.localStorage.removeItem("token")
    }

    return (
        <TokenContext.Provider
            value={{ token: token, logOut: logOut, logIn: logIn }}
        >
            {props.children}
        </TokenContext.Provider>
    );
};

export default TokenContextProvider;

The problem is that the useEffect hook isn’t working because it is not saving the token in the local storage and the url keeps the same when the user already logged in.

Example of how the url stays:
http://localhost:3000/#access_token=BQA4OEmPw6VRknPFNW9Z2dS-uGZHbEJ3WbAWJy-jmsLFEy_PWMgMMfMYKqAQKdNgd6j1FDPIKYTNlztx2L1IgwC_gLvee-xx0hj8rKOVgDVtN1NktbhV4sHRtuzK_1EaRNGjrzxvkvXqdQ3jd0NiD4mHzd1uWC2udWTXejHDXHf9x8K3MxZGIQ&token_type=Bearer&expires_in=3600

React navigator not moving between screens

My app closes when I press the switch screen button. I don’t see any error output.
I did a version check and there was no problem.

The function I wrote for the button works

Router.js

import React from "react";
import { NavigationContainer } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import First from "./First";
import Second from "./Second";
const Stack = createNativeStackNavigator();

const Router = () =>{
    return(
        <NavigationContainer>
            <Stack.Navigator initialRouteName="First">
                <Stack.Screen name="First" component={ First }/>
                <Stack.Screen name="Second" component={ Second }/>
            </Stack.Navigator>
        </NavigationContainer>
    );
}

export default Router;

First.js

import React from 'react';
import {View,Text,Button} from 'react-native';


const First = ( props ) =>{
    const gotoSecond = () => {
        console.log("First");
        props.navigation.navigate("Second");
        console.log("second")
    }
    return (
        <View>
            <Text>Hello First Page!</Text>
            <Button title="Go SecondPage!" onPress={gotoSecond}/>
        </View>
    );

};

export default First;

Second.js

import React from 'react';
import {View,Text} from 'react-native';

const Second = () =>{
    return (
        <View>
            <Text>Hello Second Page!</Text>
        </View>
    );

};

export default Second;

OS:Android,
Emulator:Genymotion.

Array.prototype.map() expects a return value from arrow function – Apollo client -Reactjs

I am building a project management application using reactjs and graphql.

When I send out query from reactjs it gets a response with the data below

{
   "data":{
    "clients":[
       {
         "name":"Okoye Ifeoma",
         "email":"[email protected]",
         "phone":"0805-854-754-580"
       }
    ]
  }
}

But it does not show the data on the browser instead it display the following error on the console

Error: Array.prototype.map() expects a return value from arrow function

Clients

import { gql, useQuery } from "@apollo/client";
import ClientRow from "./ClientRow";
const GET_CLIENTS = gql`
  query getClients {
    clients {
      id
      name
      email
      phone
    }
  }
`;

export const Clients = () => {
  const { loading, error, data } = useQuery(GET_CLIENTS);

  if (loading) return <p>loading...</p>;
  console.log(data.clients);
  if (error) return <p>Something went wrong</p>;
  return (
    <>
      {!loading && !error && (
        <table className="table table-hover mt-3">
          <thead>
            <tr>
              <th>Name</th>
              <th>Email</th>
              <th>Phone</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {data.clients.map(client => {
              <ClientRow key={client.id} client={client} />;
            })}
          </tbody>
        </table>
      )}
    </>
  );
};

ClientRow

import { FaTrash } from "react-icons/fa";
export default function ClientRow({ client }) {
  return (
    <tr>
      <td>{client.name}</td>
      <td>{client.email}</td>
      <td>{client.phone}</td>
      <td>
        <button className="btn btn-danger">{FaTrash}</button>
      </td>
    </tr>
  );
}

Showing only a specific amount of Elements on a document

I am creating a search input which displays a list of results as the user inputs text. The results are called from a JSON database, which then takes certain info and places it as text within an anchor element. I am trying to display only six of these results at a time, and was wondering if there was a way to put a cap on the amount of a certain element which can be displayed and doesn’t over-rule the i variable I already have set? Thank you

My Code:

    for (let i=0; i < results.length; i++) {
  var div = document.getElementById('dropdown');
  var link = document.createElement('a');
  var locDot = document.createElement('img');
  var linkT = document.createElement('h1');
  var linkV = document.createElement('p');
  link.setAttribute('href', 'NTS_TAXI_PLACEMENT.html');
  link.setAttribute('class', 'link');
  link.setAttribute('id', `link${i}`);
  locDot.setAttribute('src', 'locationDot.png');
  locDot.setAttribute('class', 'locationDot');
  linkT.setAttribute('class', 'address');
  linkV.setAttribute('class', 'city');
  linkT.textContent = (`${results[i].title}`);
  linkV.textContent = (`${results[i].vicinity}`);
  div.appendChild(link);
  link.appendChild(locDot);
  link.appendChild(linkT);
  link.appendChild(linkV);
    var linkAmount = div.getElementsByTagName('a');
    var linkDisplay = linkAmount[i].style.display;
    document.getElementById('test').innerHTML = linkDisplay;
    
    function filterFunction() {
      var i, input, inputStr, div, a;
      input =  document.getElementById('searchInput');
      inputStr = input.value.toUpperCase();
      div = document.getElementById('dropdown');
      a = document.getElementsByTagName('a');
      for (i=0; i < results.length; i++) {
          txtValue = a[i].textContent;
          if (txtValue.toUpperCase().indexOf(inputStr) > -1) {
              a[i].style.display = "";
          } else {
              a[i].style.display = "none"; 
          }
      }
    }
}

Appending multiple templates to a DOM

Java Script
const cardDropdownTemplate = document.querySelector('[Card-Dropdown-Template]');
const cardDropdownContainer = document.querySelector('[card-dropdown-container]');

SearchBoxMainNav.addEventListener('input', async(event) =>{
  var input = document.getElementById('SearchTerm').value;
  const card = cardDropdownTemplate.content.cloneNode(true).children[0];
  cardDropdownContainer.innerHTML = "";
  if (input != "") {
    var result = cardSearch(input);
    console.log(result);
    for (var i = 3; i > -1; i--) {
      const name = card.querySelector("[Ygo-Card-Name]");
      const desc =  card.querySelector("[Ygo-Card-Desc]");
      name.textContent = result[i].name;
      desc.textContent = result[i].desc;
      cardDropdownContainer.append(card);
    }
  console.log(card);
  console.log(result);
  }
})

Html
        <div class="dropdown-Content" card-dropdown-container ></div>
        <template Card-Dropdown-Template>
            <div class="card-dropdown">
                <div class="card-name" Ygo-Card-Name></div>
                <div class="card-description" Ygo-Card-Desc></div> 
            </div>
        </template>

So I have this code, when it executes it listens for an input then sends that input into my api searcher, it searches the api for the 4 most simmilar listings in name then Uses a dom template to create a box and puts all the information in it so i can make a Dropdown.

My problem is currently it is only creating one Box and is just overwriting the information in that one box instead of making multiple boxes. Am I just using append wrong or what? When i watch it in slow mo The data gets overwriitten even before the append is reached in the code, so maybe its just drawing the template in real time after the append and the append only makes a new box that first time then does nothing the rest of the times?

Scrapy: Converting Javascript array to Json on Python

I have been struggling with a site I am scrapping using scrappy.
This site, returns a series of Javascript variables (array) with the products data.
Example:

datos[0] = ["12345","3M YELLOW CAT5E CABLE","6.81","1","A","N","N","N","N","N",0,0,0,0,0,"0","0","0","0","0","P","001-0030","12","40K8957","28396","250","Due: 30-12-1899",0.0000,1,"",''];
datos[1] = ["12346","3M GREEN CAT5E CABLE","7.81","1","A","N","N","N","N","N",0,0,0,0,0,"0","0","0","0","0","P","001-0030","12","40K8957","28396","250","Due: 30-12-1899",0.0000,1,"",''];
...

So on…

Fetching the array into a string with scrapy was easy, since the site response prints the variables.
The problem is I want to transform it into Json so I can process it and store it in a database table.

Normally I would use Javascript’s function Json.stringify to convert it to Json and post it in PHP.

However when using Python’s json.loads and even StringIO I am unable to load the array into json.

Probably is a format error, but I am unable to identify it, since I am not expert in Json nor Python.

EDIT:
I just realize since scrapy is unable to execute Javascript probably the main issue is that the data is just a string. I should format it into a Json format.

Any help is more than welcome.

Thank you.

Changing img title in an array with JS [duplicate]

I’ve just started learning HTML, CSS and JavaScript.
I have an image gallery and titles of those images in an array. Now when I click on picture in gallery it shows the title of said image in a text input field. I want to type in a new title in same field and after clicking on submit button for title to change and be adjusted in the array so if I hover over the image again it shows the changed title. All written in JS.

Been trying and refining this for hours and got the console to show no errors but code isn’t doing anything, maybe someone could take a look and see what I am missing.

        var image=document.querySelectorAll(".galery img");
        var new=document.querySelector(".edit input[type=text]");
        image.title=new;
        }

Your help and guidance would be much appreciated.

Different behaviours when using var vs {var} in chrome.storage.sync.get [duplicate]

I am not able to understand how exactly the chrome.storage.sync.get function works.

Usual Scenario:

chrome.storage.sync.get(["color", "colortwo"], function(colors) {
    changeColor.style.backgroundColor = colors.colortwo
});

Special Scenario:

chrome.storage.sync.get(["color", "colortwo"], function({colortwo}) {
    changeColor.style.backgroundColor = colortwo;
});

I am not able to understand how specifying function({colortwo}) is able to let us access the colortwo variable directly since chrome.storage.sync.get is supposed to return an object containing all of our data

Would love some insights as to how exactly Javascript handles this special case so that I can gain a deeper understanding. Thanks!

Javascript function await is only valid in async functions

 have this app that uses OCR to read image text and convert it to JSON array then write it to an HTML table and export it as an Excel Worksheet by using phpspreedsheet the app was working so far so good until I played around it and missed up something after that Javascript function is not working anymore so it should work to write the table content to an Excel file by [Change.php]

prepare.js

function readFile(fileName) {
  console.log({ fileName });

  return await Tesseract.recognize(fileName, 'ara', {
  
    logger: m => console.log(m)
  });

}
function parseDataFromTextAndPropertyNames(text, propertyNames) {
  console.log({ text, propertyNames });

  return propertyNames
    .reduce((table, key) =>
      Object.assign(table, {

        [ key ]: RegExp(`${ key }\W+(\w+)`)
          .exec(text)?.[1] ?? ''

      }), {});
}
function writeParsedTextDataAsJSON(fileName, table) {
  console.log({ table });
   JSON.stringify({ table });

  // fake it ...
  return (await new Promise(resolve =>
    setTimeout(() => {

      console.log({ fileName, json: JSON.stringify({ table }) });
      resolve({ success: true });

    }, 1500)
  ));
}

console.log('... running ...');

function start(filenames) {
  const { data: { text } } = await readFile(filenames);

  const data = await
    parseDataFromTextAndPropertyNames(text, ['نقطة الخدمة', 'رقم العداد']);
 document.getElementById("dvjson").innerHTML = JSON.stringify(data, undefined, 4);
 const final = [JSON.stringify(data)];
 const ff = [JSON.parse(final)];
 constructTable('#table',ff);
 htmlstring = getElementById('table').innerHTML();
$.post('change.php', {string:htmlstring}).done(function(response){
      alert("done");
});
  console.log({ result });
}


// construct JSON array to HTML Table

 function constructTable(selector,data) {
             
            // Getting the all column names
            var cols = Headers(data, selector); 
  
            // Traversing the JSON data
            for (var i = 0; i < data.length; i++) {
                var row = $('<tr/>');  
                for (var colIndex = 0; colIndex < cols.length; colIndex++)
                {
                    var val = data[i][cols[colIndex]];
                     
                    // If there is any key, which is matching
                    // with the column name
                    if (val == null) val = ""; 
                        row.append($('<td/>').html(val));
                }
                 
                // Adding each row to the table
                $(selector).append(row);
            }
        }
         
        function Headers(data, selector) {
            var columns = [];
            var header = $('<tr/>');
             
            for (var i = 0; i < data.length; i++) {
                var row = data[i];
                 
                for (var k in row) {
                    if ($.inArray(k, columns) == -1) {
                        columns.push(k);
                         
                        // Creating the header
                        header.append($('<th/>').html(k));
                    }
                }
            }
             
            // Appending the header to the table
            $(selector).append(header);
                return columns;
        }

setTimeout(function() { 
      
        document.getElementById("loadspinne").style.display ="none";

        document.getElementById("message").style.display = "block";
      
    }, 8000);

prepare.php

<script src='scriptsprepare.js'></script>
<?php
if (!empty($target_file)){
    echo '<script>start("'.$target_file.'")</script>';
}
?>

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.2/xlsx.full.min.js"></script>
    <script src='https://unpkg.com/[email protected]/dist/tesseract.min.js'></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-0evHe/X+R7YkIZDRvuzKMRqM+OrBnVFBL6DOitfPri4tjfHxaWutUpFmBp4vmVor" crossorigin="anonymous">
    <link rel="stylesheet" href="stylemain.css">
    <script src="https://kit.fontawesome.com/bd514e8cb4.js" crossorigin="anonymous"></script>
    <script src='excelexportjs.js'></script>
</head>

<body>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2" crossorigin="anonymous"></script>
    <center>
        <div id="loadspinne" style="width: 12rem; height: 12rem; color:#0A9ACD;" class="spinner-border" role="status"></div>
        </div>
        <div class="animate__animated animate__backInDown mx-auto d-block" style="display:none !important;" id="message">
        <h4 style="font-family:Hana; font-size:32px; font-weight:bold;">تم تكوين كشف بنجاح</h4>
        </div>
    </center>
    <div class="container mt-5 ">
    <div style="display:none;" id="dvjson"></div>
    <table align="center" id="table"  border="1" style="display:none;"></table>
    </div>
</body>
</html>

Change.php

<?php
require 'vendor/autoload.php';

use PhpOfficePhpSpreadsheetSpreadsheet;
use PhpOfficePhpSpreadsheetWriterXlsx;
use PhpOfficePhpSpreadsheetReaderIReader;
$htmlString = $_GET['htmlstring'];

$reader = new PhpOfficePhpSpreadsheetReaderHtml();
$spreadsheet = $reader->loadFromString($htmlString);

$writer = PhpOfficePhpSpreadsheetIOFactory::createWriter($spreadsheet, 'Xls');
$writer->save('ddd.xls'); 

$spreadsheet = PhpOfficePhpSpreadsheetIOFactory::load("ddd.xls");

$sheet = $spreadsheet->getActiveSheet();
$sheet->getColumnDimension('A')->setAutoSize(false);
$sheet->getColumnDimension('B')->setAutoSize(false);
$sheet->getColumnDimension('A')->setWidth(16);
$sheet->getColumnDimension('B')->setWidth(13);

$sheet->getStyle('A1:B1')->getFont()
    ->setName('Arial')
    ->setSize(14)
    ->setBold(true);
$writer = new Xlsx($spreadsheet);
$writer->save('ddd.xlsx');
// header('Location: ddd.xlsx');
?>

Cosnole Log [Errors]:-

Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules (at prepare.js:4:10)
upload.php:4 Uncaught ReferenceError: start is not defined
    at upload.php:4:9
(anonymous) @ upload.php:4

breaking out from a for loop statement

I have a small issue as I’m not that good with coding, I have a code that it’s working for me good but I want to improve it. i want that my code when it will not find any data to just get out of the loop for and show this message “AUCUNE DEMANDE A VALIDER”.
thanks in advance

for (i = 1; i < dataValues.length; i++) {
    if (dataValues[i][11] === 'COMMANDE CONFIRMER' && dataValues[i][12] != '' && dataValues[i][13] === '') {
        pasteSheet.appendRow([dataValues[i][0],
            dataValues[i][1],
            dataValues[i][2],
            dataValues[i][3],
            dataValues[i][4],
            dataValues[i][5],
            dataValues[i][6],
            dataValues[i][7],
            dataValues[i][8],
            dataValues[i][9],
            dataValues[i][10],
            dataValues[i][11]]);
      
        var clearRow = i + 2;
        copySheet.getRange('A' + clearRow + ':M' + clearRow).clear();
    }
}

// get destination range
var destination = pasteSheet.getRange(pasteSheet.getLastRow() + 1, 1, max, 1);

// clear source values
Browser.msgBox('Commande Confirmer');
}

returning first value [object Promise] [duplicate]

const wordEl = document.getElementById('word');    
let selectedWord = [];
let correctLetters = [];

let apiUrl = 'https://random-word-api.herokuapp.com/word';

async function getData(url) {
  let response = await fetch(url);
  let data = await response.json();
  selectedWord = await data;
}
selectedWord = getData(apiUrl);

async function displayWord() {
  wordEl.innerHTML = `
    ${selectedWord
      .toString()
      .split('')
      .map(
        (letter) =>
          `
          <span class="letter">
            ${correctLetters.includes(letter) ? letter : ''}
          </span>
        `
      )
      .join('')}
  `;
}

window.addEventListener('keydown', (e) => {
  if (selectedWord.toString().includes(e.key)) {
    if (!correctLetters.includes(e.key)) {
      correctLetters.push(e.key);
      displayWord();
    }
  }
});

displayWord();

Hello my first value returning [object promise]. After pressing any key value returning what I want.

How can i get normal value before clicking any key? Thank you!

Fetching data inside of mapped components

Not sure how best to phrase this question, other than asking for a clean way to do it.

I have an array of objects each containing a name and a URL, i’m mapping over each item so i can fetch data from the URL and display it, however there are hundreds of items, meaning hundreds of fetch requests.

This is what i have:

Index.js:

const fruits = [
  { name: "apple", url: "http://foo" },
  { name: "banana", url: "http://bar" },
];

const App = () => {
  return fruits.map((fruit) => {
    <FruitContainer fruit={fruit} />;
  });
};

FruitContainer.js

const FruitContainer = (fruit) => {
  const [fruitData, setFruitData] = useState({});

  const getFruitData = async () => {
    const data = await fetch(fruit.url);
    let json = await data.json();
    setFruitData(json);
  };

  useEffect(() => {
    getFruitData();
  }, []);

  return (
    <>
      <Text>{fruitData.name}</Text>
      <Text>{fruitData.color}</Text>
    </>
  );
};