Why Javascript multiple async awaits behaves differently when it awaits promises vs when it awaits functions returning promises?

I have the below code with both the implementations.

const p1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('promise 1');
    }, 1000);
});

const p2 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('promise 2');
    }, 1000);
})

const p1func = () => new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('promise 1 func');
    }, 1000);
});

const p2func = () => new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve('promise 2 func');
    }, 1000);
})

async function TestPromise() {
    console.log("started");
    const val = await p1;
    console.log(val);

    const val2 = await p2;
    console.log(val2);
    //checkpoint 1: reaches this point in 1 second
    const val3 = await p1func();
    console.log(val3);

    const val4 = await p2func();
    console.log(val4);
    //from checkpoint 1, it takes 2 seconds to reach here
}

TestPromise();

When I ran the code I noticed that when js awaits 2 promises, it starts executing them parallelly & completes within 1 second(asynchronously). When the functions returning promises were run JS ran them one by one(synchronously).Is JS engine detecting 2 awaits on promises prior run inorder to be able to execute them parallelly? Why can’t it do the same with functions returning promises?

JavaScript Web Audio API – Sampling Problem and FFT

I am having a problem with the Web Audio API where the audio sampling rate is incorrect on an Android phone using Chrome, Opera and Edge browser, but it works fine using the Firefox browser.

I am recoding the microphone into an array using Web Audio API as follows, where just snippets of my code have been included, as I cannot paste all of it, but this is just to show which functions I am using.

let audioContext;
dataArrayFft = new Float32Array(bufferLength);
audioContext = new (window.AudioContext || window.webkitAudioContext)({ sampleRate:48000});
analyser = audioContext.createAnalyser();
const source = audioContext.createMediaStreamSource(stream);
source.connect(analyser);

I then call the following routine periodically (30Hz) to update my chart.js:

analyser.getFloatFrequencyData(dataArrayFft);

The code works fine on my PC using the Chrome browser and shows the full FFT spectrum up to 24kHz with a 48kHz sampling rate.

With my Android phone I point each of the browsers (Chromer, Opera, Firefox, Edge) to my laptop IP address (https://192.168.1.149:3000) to view the web page on my phone to test my app.

The following IMAGE 1 shows the app running in the Chrome browser on my Windows 10 laptop and it is working as expected.

PC Chrome Browser running as expected

The following images 2,3,4 show my Android phone viewing the web page on my laptop and as you can see for Chrome, Opera and Edge (IMAGES 2,3,5) the FFT spectrum rolls off at 8kHz but for Firefox (IMAGE 4) it shows the full spectrum as expected and I have confirmed it works by using a signal generator.

Android Chrome, Opera, Firefox, Edge Browsers showing the problem

I do not understand why it works as expected on Firefox but there is this 8kHz limit on the other browsers indicating the sampling rate is being limited to 16kHz? Any thoughts on what this problem could be caused by?

How do i make a vertical bar to reveal the image underneath? [closed]

I have a little bit of a problem and i don t know how to approach it. So basically I have to pictures of a car, identical, one is scratched and one is not. The two images are overlaped and have a vertical bar in the middle. To the left of the bar only the scratched image is visible to the right only the normal one. As i drag the bar to the left, what is to the right of the car turns into the normal image. Vice versa if i move the bar to the right, whatever is to the left of the bar turns into the scratched car.

I have tried a lot of things but nothing seemed to work.

Typescript: matches 2 arrays [duplicate]

I need to find out if 2 arrays match (have common elements) in one or more elements.

Is there a more elegant way than the 2 loops?

In Java I would use a stream with lambda.

lst1.stream ().anyMatch (c -> lst2.contains (c))

But I am not sure hot to do that in Typescript/Javascript.

let lst1 : string [] = ["aaa", "bbb", "ccc"];
let lst2 : string [] = ["ddd", "eee", "bbb"];    // 1 match at "bbb"

let matches : boolean = false;
for (let a of this.lst1)
{
    for (let b of this.lst2)
    {
        if (a == b)
        {
            matches = true;
        }
    }
}

I have the next error Reverse for ‘solicitud_detail’ with keyword arguments

I am trying to see the details of my created requests but the url to enter the details is not recognized. I don’t know what it could be. I will attach the views of my code. If you can help me, please.

html

{% extends 'base.html' %}
{% load static %}
{% block content %}
{% include 'nav.html' with active='new1' %}

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous" />
<!-- DataTable.js -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.1/css/dataTables.bootstrap5.min.css" />
<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" />
<!-- Custom CSS -->
<link rel="stylesheet" href="{% static 'css/index.css' %}" />
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css">



<br>
<br>
<div class="hstack gap-3">
  <div class="p-2"><h3>Solicitudes </h3></div>
  <div class="p-2 ms-auto"></div>
  <div class="p-2"><a class="btn btn-primary btn-md" href="{% url 'crear_solicitud' %}">Crear OC</a> </div>
</div>
<br>
<div class="container">
  <table id="datatable-programmers" class="table table-hover">
    <thead class="table table-primary">

      <tr>
        <th>#</th>
        <th>Código</th>
        <th>Asunto</th>
        <th>Descripción</th>
        <th>Estado</th>
        <th>Plazo de Pago</th>
        <th></th>
      </tr>

    </thead>
  <tbody id="tableBody_programmers">
    <!-- Los resultados se mostrarán aquí -->
    
  </tbody>
  <br>
  <br>



</div>
        <!-- Bootstrap -->
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
        <!-- jQuery -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <!-- DataTable.js -->
        <script src="https://cdn.datatables.net/1.13.1/js/jquery.dataTables.min.js"></script>
        <script src="https://cdn.datatables.net/1.13.1/js/dataTables.bootstrap5.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

<script >
let dataTable;
let dataTableIsInitialized = false;

const dataTableOptions = {
    columnDefs: [
        { className: "centered", targets: [0, 1, 2, 3, 4, 5, 6] },
        { orderable: false, targets: [5, 6] },

    ],
    pageLength: 10,
    destroy: true,    
    language: {
        lengthMenu: "Mostrar _MENU_ registros por página",
        zeroRecords: "Ningún usuario encontrado",
        info: "Mostrando de _START_ a _END_ de un total de _TOTAL_ registros",
        infoEmpty: "Ningún usuario encontrado",
        infoFiltered: "(filtrados desde _MAX_ registros totales)",
        search: "Buscar:",
        loadingRecords: "Cargando...",
        paginate: {
            first: "Primero",
            last: "Último",
            next: "Siguiente",
            previous: "Anterior"
        }
    }

};

const initDataTable = async () => {
    if (dataTableIsInitialized) {
        dataTable.destroy();
    }

    await listProgrammers();

    dataTable = $("#datatable-programmers").DataTable(dataTableOptions);

    dataTableIsInitialized = true;
};

const listProgrammers = async () => {
    try {
        const response = await fetch("http://localhost:8000/listar_solicitudes/rector");
        const data = await response.json();

        let content = ``;
        data.programmers.forEach((programmer, index) => {
          
            content += `
                <tr>
                    <td>${programmer.pk}</td>
                    <td >${programmer.codigo}</td>
                    <td>${programmer.asunto}</td>
                    <td class="col-2">${programmer.descripcion}</td>
                    <td>${programmer.plazo_pago}</td>
                    <td>${programmer.sede  }</td>
                    <td>
    
                      <a class='btn btn-sm btn-success' href="{% url 'solicitud_detail' programmer_id=programmer.pk %}" title="Detalles"><i class="fa-solid fa-eye"></i></a>

                      <a class='btn btn-sm btn-primary'  title="Editar" href="{% url 'crear_solicitud' %}"> <i class='fa-solid fa-pencil'></i></a>
                      <button class='btn btn-sm btn-danger'  title="Eliminar" ><i class='fa-solid fa-trash-can'></i></button>
                    </td>
                </tr>`;
        });
        tableBody_programmers.innerHTML = content;
    } catch (ex) {
        alert(ex);
    }
};

window.addEventListener("load", async () => {
    await initDataTable();
});
</script>


{% endblock %}

views.py

def listar_solicitudes_rector(request):
    solicitudes = Solicitud.objects.all()

    programmers = []
    for solicitud in solicitudes:
            programmers.append({
                'pk':solicitud.pk,
                'codigo': solicitud.codigo,
                'asunto': solicitud.asunto,
                'descripcion': solicitud.descripcion,
                'estado': solicitud.Estado.name if solicitud.Estado else '',
                'plazo_pago': solicitud.plazo_pago.name,
                'sede': solicitud.sede.name if solicitud.sede else '',
                'presupuesto': solicitud.presupuesto.ID_Presupuesto if solicitud.presupuesto else '',
                'creado': solicitud.creado.strftime('%d-%m-%Y'),
                'creada_por': solicitud.creada_por.username if solicitud.creada_por else '',
            })
    data = ({'programmers': programmers})
    return JsonResponse(data)


def Details_solicitudes(request, programmer_id):
    solicitud = get_object_or_404(Solicitud, pk=programmer_id)

def Solicitudes_List_Rector(request):
    return render(request, 'rector/solicitudes_list.html')

urls.py

   path('solicitud_detail/<int:programmer_id>/', views.Details_solicitudes, name='solicitud_detail'),

    path ('Solicitudes_list/rector', views.Solicitudes_List_Rector, name='solicitudes_list_rector'),

    path('listar_solicitudes/rector', views.listar_solicitudes_rector, name='listar_solicitudes_rector'),

I have tried everything to change variables, leaving it as a static loop but I need it to be done through javascripts, I would like to know what I am doing wrong and how I can solve it with your help and it is possible.

cant seem to access a particular page in my nextjs project; routing issue

TeamsMain.jsx file:

import React from "react";
import styles from './page.module.scss';
import Image, { StaticImageData } from "next/image";
import { useRouter } from "next/navigation";
import { teamList } from "@/app/assets/constants/data";

export interface Team {
    image: StaticImageData;
    name: string;
}

const TeamsMain = () => {

    const router = useRouter();

    const handleClick = (team: Team) => {
        router.push(`/teams/${team.name}`);
    }

    return (
        <div className={styles.teamMain__container}>
            {teamList.map((team: Team) => (
                <div 
                    key={team.name} 
                    className={styles.team__container}
                    onClick={() => handleClick(team)}
                >
                    <Image src={team.image} alt={team.name}/>
                    <div className={styles.blue__overlay}>{team.name}</div>
                    <span>{team.name}</span>
                </div>
            ))}
        </div>
    )
}

export default TeamsMain;

teamProfile page.tsx:

import React from "react";
import styles from './page.module.scss';
import Image, { StaticImageData } from "next/image";
import { teamList } from "../assets/constants/data";
import { Team } from '@/app/components/TeamsMain';
import { useRouter } from "next/router";

interface TeamProfileProps {
    team: {
      image: StaticImageData;
      description: string;
    }
  }
  
  const TeamProfilePage = () => {

    const router = useRouter();
    const { teamId } = router.query;

    const selectedTeam = teamList.find((team: Team) => team.name === teamId);
  
    return (
      <div>
        {selectedTeam ? (
          <TeamProfile team={selectedTeam} />
        ) : (
          <p>Team not found</p>
        )}
      </div>
    );
  };
  
  const TeamProfile = ({ team }: TeamProfileProps) => {
    return (
      <div>
        <Image src={team.image} alt="teamLogo" width={100} height={100} />
        <p>{team.description}</p>
      </div>
    );
  };
  
  export default TeamProfilePage;

TeamId.tsx page:

import React from "react";
import TeamProfilePage from "../teamProfile/page";

const TeamIdPage = () => {
    return <TeamProfilePage/>;
};

export default TeamIdPage;

When I try to click on an individual team from my array in the TeamsMain, it directs me to a 404 error page. The data is in another file and everything seems fine with code there.

Tried a bunch of methods, tried changing file structure as well to no avail.

div not showing react-router-dom

I’m new to JS and react, and I’m currently programming a Firebase project by watching a tutorial on youtube

I have a problem with the display of this div :

export const Main = () => {
  return <div> Home page </div>;
};

Here is the App.tsx

import React from 'react';
import {BrowserRouter as Router, Route, Routes} from 'react-router-dom';
import "./App.css";
import { Main } from "./pages/main";

function App() {
  return (
    <div className="App">
      <Router>

        <Routes>
          <Route path="/" element={<Main />}/>
        </Routes>

      </Router>
    </div>
  );
}

export default App;

There is no error, just a blank page.

Thank you for your help !

It should display a div Home page at the main page

jSpreadsheet CE custom tooltip on hover

I am trying to set up custom tooltips for column headers. While the pro vers. site describes how to do this, I could not find the information on the CE site. I tried the following, but the column title appears in the tooltip.

jspreadsheet(document.getElementById('spreadsheet'), {
    workshets: [{
        columns: [
            {
                type: 'text',
                title: 'MyTitle',
                tooltip: 'This is a custom tooltip',
                width: 160
            }
        ]
    }]
});

Getting ‘Array’ as decoded json response from a post api call PHP

I’m trying to send a post request to my php endpoint from vue.js. This is the code :

$router->post('/add', function () {
    $json = file_get_contents('php://input');
    echo $json;
});

If I echo the json , I get an object as a response :

{
    "method": "POST",
    "headers": {
        "Content-Type": "application/json"
    },
    "body": "{"SKU":"ABC123","name":"Product Name","price":19.99,"type":1,"size":2,"weight":1.5,"height":10,"width":5,"length":15}"
}

However, when I try to decode it like this :

$router->post('/add', function () {
    $json = file_get_contents('php://input');
    $data = json_decode($json,true);
    echo $data;
});

I get this response : Array.
I can’t figure out why I’m not getting a decoded jsos, I’d appreciate any help, this is the post request from vue :

axios.post('http://127.0.0.1:8000/add', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      SKU: 'ABC123',
      name: 'Product Name',
      price: 19.99,
      type: 1,
      size: 2,
      weight: 1.5,
      height: 10,
      width: 5,
      length: 15
    })
  })
    .then(res => console.log(res))

    .catch(error => {
      console.error('Error:', error);
    });

Do we use weglot in react native? [closed]

https://www.weglot.com/

Form the above link i can’t find any steps orinstruction to achive that.. so anyone know means please share

Weglot is a platform that offers website translation services. It allows website owners to easily translate their websites into multiple languages without having to manually translate each page. With Weglot, you can integrate translation seamlessly into your website and manage all your translations from one dashboard.

Integrating Weglot for Multi-Language Support in React Native

I have find some steps in gemini but its not working

While Weglot doesn’t have a dedicated React Native integration, you can achieve multi-language functionality using their JavaScript integration for Single Page Applications (SPAs). Here’s a detailed step-by-step guide:

  1. Weglot Setup:

a. Account and Project:

  • Head to Weglot: weglot.com and create an account.
  • Once logged in, create a new project and define the languages you want to support (e.g., English, French, Spanish).

b. Weglot JavaScript Integration:

  • In your Weglot project dashboard, navigate to the “Installation” section.
  • Choose the “JavaScript” integration option. Weglot will provide a code snippet that needs to be integrated into your React Native app.
  1. React Native App Integration:

a. Installation (Optional):

  • Consider using a library like react-native-async-storage to store the user’s preferred language locally. This can improve the user experience by remembering the chosen language across app launches.

b. Weglot Script Integration:

  • Open your app’s main entry point (usually App.js or index.js).
  • Paste the Weglot JavaScript code snippet you obtained in step 1.b within the componentDidMount lifecycle method of your main component. This ensures the script runs after the app loads.

Example Code (Replace YOUR_API_KEY with your actual key

import React, { useEffect } from 'react';
const App = () => {
  useEffect(() => {
    window.Weglot = {
      key: YOUR_API_KEY, // Replace with your Weglot API key
    };
    const script = document.createElement("script");
    script.setAttribute("src", 'https://cdn.weglot.com/weglot.min.js');
    document.body.appendChild(script);
     return () => {
      // Cleanup function (optional)
    };
  }, []);

  // ... rest of your app code
};
export default App;
  1. Handling Dynamic Content:

    Weglot might not automatically detect all translatable content in React Native apps due to their dynamic nature.
    To ensure proper translation, you need to mark dynamic content using the data-wg-id attribute.

Example:
<Text data-wg-id="welcome_message">Welcome to our app!</Text>

I need to achieve the weglot in react native

How to fade between a series of sticky divs with scroll? [closed]

I have a series of full screen divs (for example 5) stacked on top of each other in a grid. I want to be able fade them in and out in sequence as I scroll up and down on the page. I want to make it with vanilla js, no jquery and the like.

I have the five divs stacked inside a grid but I cant figure out how to make them fade in and out based on scroll. Is intersection observer the way to go?

I figured I could put my five divs inside a container that is 500vh high and calculate the opacity for each div based on some scroll position inside that, but how to code that calculation escapes me?

Extension to create a hyperlink after select a text in web page and open new browser tab

I am lookin for a solution to create a Chrome extension or if somebody know ready solution for the following.

After select a text in web page and right click to have the option to open new tab with the following logic.

I select text “Gradina” and right click to open click and open the following link in new tab

https://praktiker.bg/en/**Gradina**/c/P1305

Some example of similar extension

enter image description here

I tried similar extension but dont fit to my issue.

Json.stringify() is ignoring a object property after xlsx.sheet_to_json

so im using the SheetJs Library to read an excel file.

 const data = XLSX.utils.sheet_to_json(workbook.Sheets[sheet])

Wich returns Objects like this.

enter image description here

Ignoring the other properties.

The property rowNum is created by the sheet_to_json function and returns the Excel row Number of the Object.

I then use JSON.stringifyto create the JSON string of a single excel sheet. Wich i string concetate to a previous sheet.

this.convertedJson= this.convertedJson +JSON.stringify(data,undefined, 4);

Now the problem im encountering. After using .stringify() i get returned every single property the different rows have, except rowNum.

This is the part of the output String for the Object above.

{
        "WebShop": "AR_APPD-72642_RDS_RetailerUI_User",
        "__EMPTY": "",
        "__EMPTY_2": "AR RDS Retailer UI User (Prod)",
        "__EMPTY_3": "AR RDS Retailer UI User (Prod) ",
        "__EMPTY_4": "RtailerUI",
        "__EMPTY_5": "RtailerAI"
    }

I’ve found an older changelog of SheetJs, where ive noticed that the rowNum property was changed from enumerable to non-enumerable. Following up on that lead, apparently you cant serialize non-enumerable properties with .stringify(). Does anyone know a simple solution how i can still use .stringify() with non-enumerable properties. Or how i can change all rowNum properties of every object to enumerable?

How does the JIT compiler Maglev in chrome v8 perform?

I write some js codes in a function named f , and call the f 4 times. That’s all I did, quite simple.

After I run it with ./d8 –trace-opt, I find the f is compiled 4 times by Maglev, 2 times by Turbofan, and then 2 times by Maglev.

In the turbofan period, it shows that “Found optimize code for f….”, which means that when it try to compile f with Turbofan again, it will directly return the code compiled at the first time, just as many blogs say.

But what about the Maglev? It compiles everytime and many times, and when I try to look at the result of it with option ‘–print-maglev-code’, it prints codes which are different with each other. Some are long, some are short.

Dose it have something to do with deoptmization becasue I see 6 times deopt from Maglev code and 3 times deopt from Turbofan code with option –trace-deopt? I am quite confused, and need some help.

What I need for help:

I’d like to know, in the source code files or any blog link, where is the reason for a function to get Magleved?

Will the deoptimization from maglev code influence the later call of f , which makes it compile again and render the different compiled codes?

Why maglev doesn’t get the code it compiled before just like Turbofan? Does it have something to do with FeedbackVector?

I am a beginner in v8 and I am very willing to refer to the source code. But I can’t find the exact code and don’t know if the code I find is the right place. Thanks.