Burning subtitles into video using ffmpeg overlay on react native

I have managed to complete this task on node server but it’s too slow I don’t want to upgrade my instance so I decided to do the conversion on the front end, my app is on react native can please somebody help me convert the code and keep the same args and options

Server code

// Execute the ffmpeg command to burn the subtitles into the video
const ffmpeg = spawn("ffmpeg", [
  "-i",
  "pipe:0",
  "-vf",
  `subtitles=${subtitlePath}:force_style='Alignment=10,OutlineColour=&H100000000,BorderStyle=3,Outline=1,Shadow=0,Fontsize=10'`,
  "-c:a",
  "copy",
  "-progress", "pipe:1",
  outputPath,
]);

// Pipe the videoResponse array buffer to FFmpeg
ffmpeg.stdin.write(videoResponse.data);
ffmpeg.stdin.end();

// Send the output file as a response once the process is complete
ffmpeg.on("close", () => {
  fs.readFile(outputPath, (err, data) => {
    if (err) {
      console.error(err);
    } else {
      console.log(outputPath)
    }
  });
});

My try on react native but failed for several issues including, main ones are:

No such filter: ‘subtitles’ Failed to inject frame into filter

Invalid argument

Error initializing complex filters.

This is what I come up with so far

  componentDidMount() {
    FFmpegKit.executeAsync(`-i ${inputFilePath} -i ${subtitleFilePath} -filter_complex "[0:v][1:s]overlay=10:main_h-overlay_h-10" -c:a copy ${outputFilePath}`)
    .then((session) => {
      FFmpegKit.cancel();
  
      const returnCode = session.getReturnCode();
  
      if (ReturnCode.isSuccess(returnCode)) {
        console.log('Video with subtitles was created successfully!');
      } else {
        console.log('Error creating video with subtitles');
      }
    })
    .catch((error) => {
      console.log('Error creating video with subtitles', error);
    });
  }

If you want to see the logs you can find them below

 LOG  init firebase : videocap-71b4a
 LOG  Running "videocap" with {"rootTag":11,"initialProps":{}}
 LOG  Loading ffmpeg-kit-react-native.
 LOG  Loaded ffmpeg-kit-react-native-ios-https-x86_64-5.1.0.
 LOG  Error creating video with subtitles [TypeError: undefined is not a function]
 LOG  ffmpeg version n5.1.2
 LOG   Copyright (c) 2000-2022 the FFmpeg developers
 LOG  
 LOG    built with Apple clang version 14.0.0 (clang-1400.0.29.102)
 LOG    configuration: --cross-prefix=x86_64-ios-darwin- --sysroot=/Applications/Xcode-v13.4.1.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator16.0.sdk --prefix=/Users/taner/Projects/ffmpeg-kit/prebuilt/apple-ios-x86_64/ffmpeg --pkg-config=/opt/homebrew/bin/pkg-config --enable-version3 --arch=x86_64 --cpu=x86_64 --target-os=darwin --disable-neon --disable-asm --ar=/Applications/Xcode-v13.4.1.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ar --cc=clang --cxx=clang++ --as='clang -arch x86_64 -target x86_64-apple-ios12.1-simulator -march=x86-64 -msse4.2 -mpopcnt -m64 -DFFMPEG_KIT_X86_64 -Wno-unused-function -Wno-deprecated-declarations -fstrict-aliasing -DIOS -DFFMPEG_KIT_BUILD_DATE=20220929 -isysroot /Applications/Xcode-v13.4.1.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator16.0.sdk -O2 -mios-simulator-version-min=12.1 -I/Applications/Xcode-v13.4.1.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator16.0.sdk/usr/include' --ranlib=/Applications/Xcode-v13.4.1.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ranlib --strip=/Applications/Xcode-v13.4.1.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/strip --nm=/Applications/Xcode-v13.4.1.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/nm --extra-ldflags='-mios-simulator-version-min=12.1' --disable-autodetect --enable-cross-compile --enable-pic --enable-inline-asm --enable-optimizations --enable-swscale --enable-shared --disable-static --install-name-dir='@rpath' --enable-pthreads --disable-v4l2-m2m --disable-outdev=v4l2 --disable-outdev=fbdev --disable-indev=v4l2 --disable-indev=fbdev --enable-small --disable-xmm-clobber-test --disable-debug --disable-neon-clobber-test --disable-programs --disable-postproc --disable-doc --disable-htmlpages --disable-manpages --disable-podpages --disable-txtpages --disable-sndio --disable-schannel --disable-securetransport --disable-xlib --disable-cuda --disable-cuvid --disable-nvenc --disable-vaapi --disable-vdpau --disable-alsa --disable-cuda --disable-cuvid --disable-nvenc --disable-vaapi --disable-vdpau --enable-gmp --enable-gnutls --disable-sdl2 --disable-openssl --enable-zlib --enable-audiotoolbox --disable-outdev=audiotoolbox --enable-bzlib --enable-videotoolbox --enable-avfoundation --enable-iconv --disable-coreimage --disable-appkit --disable-opencl --disable-opengl
 LOG    libavutil      57. 28.100 / 57. 28.100
 LOG    libavcodec     59. 37.100 / 59. 37.100
 LOG    libavformat    59. 27.100 / 59. 27.100
 LOG    libavdevice    59.  7.100 / 59.  7.100
 LOG    libavfilter     8. 44.100 /  8. 44.100
 LOG    libswscale      6.  7.100 /  6.  7.100
 LOG    libswresample   4.  7.100 /  4.  7.100
 LOG  Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '/Users/master/Documents/Code/videocap-mobile/media.mp4':
 LOG    Metadata:
 LOG      major_brand     :
 LOG  isom
 LOG  
 LOG      minor_version   :
 LOG  512
 LOG  
 LOG      compatible_brands:
 LOG  isomiso2avc1mp41
 LOG  
 LOG      encoder         :
 LOG  Lavf58.76.100
 LOG  
 LOG    Duration:
 LOG  00:00:11.82
 LOG  , start:
 LOG  0.000000
 LOG  , bitrate:
 LOG  813 kb/s
 LOG  
 LOG    Stream #0:0
 LOG  [0x1]
 LOG  (und)
 LOG  : Video: h264 (avc1 / 0x31637661), yuv420p(tv, bt470bg/bt470bg/smpte170m, progressive), 480x608, 682 kb/s
 LOG  , SAR 32757:32326 DAR 491355:614194
 LOG  ,
 LOG  24.15 fps,
 LOG  24 tbr,
 LOG  1000k tbn
 LOG   (default)
 LOG  
 LOG      Metadata:
 LOG        handler_name    :
 LOG  VideoHandler
 LOG  
 LOG        vendor_id       :
 LOG  [0][0][0][0]
 LOG  
 LOG    Stream #0:1
 LOG  [0x2]
 LOG  (und)
 LOG  : Audio: aac (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 126 kb/s
 LOG   (default)
 LOG  
 LOG      Metadata:
 LOG        handler_name    :
 LOG  SoundHandler
 LOG  
 LOG        vendor_id       :
 LOG  [0][0][0][0]
 LOG  
 LOG  /Users/master/Documents/Code/videocap-mobile/transcription.srt: Immediate exit requested
 LOG  Exiting normally, received signal 2.

Please help

Apexcharts Bar chart axis scale/range

I need to create tornado chart, I found an example in docs, but the problem is – chart looks like this:
bar chart

Because the difference between the values is small – 73758373, 71663063, 71006420. They look similar and chart makes no sense.

Is there any way to make it look better? At least see the difference between values, like in excel

Live Example - https://codepen.io/Vhrst/pen/zYmZMLP?editors=0011

I have tried all xaxis and yaxis properties, like: logarithmic, forceNiceScale, logBase, tickAmount, range

Double Quotes for encodeURI()

I’m trying to encode a string that uses double quotation marks using encodeURI(). However, quotation marks do not work and it seems like whenever I use them, it expects a variable.

The conversion for ASCII hex for quotation marks is 22, so I was expecting it to return 22. However, nothing is returned and does not work at all.

Spring Boot Allow CORS for 400 BAD REQUEST responses

This issue is bugging me from entire day today. I am not being able to read response body when server (Spring Boot) is sending a 400 BAD REQUEST response.

From the best of my knowledge, the access control headers in the response looks good and client should be allowed to read the body.

Technical details now.

My ReactJs application endpoint is http://localhost:3000/ which I use in browser to access the web app.

Client (ReactJs) application is sending an OPTIONS request (Preflight) first and server is returning 200 OK response with below headers.

Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: authorization, content-type
access-control-allow-methods: PUT, GET, HEAD, POST, DELETE, OPTIONS
access-control-allow-origin: http://localhost:3000
Access-Control-Max-Age: 1800
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Connection: keep-alive
Content-Length: 0
Date: Tue, 25 Apr 2023 10:24:39 GMT
Expires: 0
Keep-Alive: timeout=60
Pragma: no-cache
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block

Now the headers from the main POST request:

Access-Control-Allow-Credentials: true
access-control-allow-methods: PUT, GET, HEAD, POST, DELETE, OPTIONS
access-control-allow-origin: http://localhost:3000
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Connection: close
Content-Length: 101
Content-Type: application/json
Date: Tue, 25 Apr 2023 10:24:39 GMT
Expires: 0
Pragma: no-cache
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block

If I print the response using JSON.stringigy(...) then I get an empty object as {}.

If I print the response object directly. I see it like.
enter image description here

Response tab also appears as blank in Chrome Developer Tools (Network tab)
enter image description here

What I have tried:

  1. In postman, response body is returned properly as expected.
  2. Added a filter to log response from server side just to verify if it is server is actually sending the response. I can see the expected response printed.
  3. Tried Edge. Same issue.
  4. Response Body is properly readable for GET requests as well POST requests as long as response status is 200 OK. I can see the issue is only appearing when server is sending 400 BAD REQUEST response.

Below is my client-side source code. I do not have anything related to cors in my request.

fetch(`${API_ROOT}/xxx/schedule`, {
  method: "POST",
  body: postData,
  headers: {
    Authorization: `Bearer ${context.user.token}`,
    "Content-Type": "application/json",
  },
})
  .then(function (response) {
    console.log(JSON.stringify(response));
    console.log(response);
    if (!response.ok) {
      throw response;
    }
    return response.json();
  })
  .then(function (text) {
    toast.success("New record is added successfully.");
  })
  .catch(function (error: ErrorResponse) {        
    toast.error(
      <div>
        Error adding Schedule. <br />
        {error.message}
      </div>
    );
    console.log(["Error adding Schedule.", error]);
  });

Please let me know if more information is required.

Using thymeleafs field.errors in script tags javascript

I currently have a function that sets h6 to a success message when the form is submitted. However, the form field (name) can have errors, as shown by the div with fields.errors. Currently the message will show whenever the form is submitted regardless if there are errors

I want to make it so the function first checks if there are errors, then if there’s none it sets the success message. But to do this, I need access to the ${#fields.errors('name')} in the script tag, and I’m not sure how to do this

 <form id="forgot-password-form" th:action="@{forgot-password}" method="post" th:object="${forgotPasswordForm}" onsubmit="return myFunction()">

        <script>

            function myFunction() {
                document.getElementById("reset-info").innerHTML = "Success";
                return false;
            }
        </script>

        <h6 id="reset-info"></h6>

        <div class="input-box">
            <input type="name" class="form-control" id="name" placeholder="" th:field="*{name}"
                   data-cy="name" autofocus>
            <label for="name"> name<span class="required">*</span></label>
        </div>
        <div th:each="err : ${#fields.errors('name')}" th:text="${err}" class="error-message"></div>

        <div class="submit-button">
            <button type="submit" formnovalidate>Submit</button>

       

    </form>

How can I implement the search function?

I would like to add a search function “filterPokemon();” to my Pokedex. My attempts have all failed so far, as soon as you enter a name in the search, all Pokemon are hidden. In addition, you should be able to delete the search with an “x” and all Pokemons should be displayed.

Can anyone help?

Thanks.

Here is my code:

<!DOCTYPE html>
<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">
  <link rel="icon" href="img/web.ico">
  <link rel="stylesheet" href="style.css">
  <!--<link rel="shortcut icon" href="#">-->
  <title>Pokedex</title>
</head>
<body>
  <header>
    <div class="menuBar">
      <div class="headerLeft">
        <img src="img/International_Pokemon_logo.png">
      </div>
      <div class="headerRight">
        <input type="text" id="search" placeholder="Search Pokemon" onkeydown="filterPokemon()">
      </div>
    </div>
  </header>

  <div id="pokeContainer" class="pokeContainer"></div>

  <script src="script.js"></script>

  <footer>
    <div>
      <a href="sources.html">Quellen</a>
    </div>
  </footer>
  <button onclick="topFunction()" id="top" title="Go to top"><img src="img/chevron-up-solid.svg" alt=""></button>
  <script src="button.js"></script>
</body>
</html>
html {
    scroll-behavior: smooth;
}

body {
    margin: 0;
    font-family: 'Helvetica';
    background-color: rgb(244 244 244 / 36%);
}

/*++++++++++++++++++ HEADER ++++++++++++++++++*/

.menuBar {
    height: 120px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: white;
}

.headerLeft img {
    object-fit: contain;
    margin-left: 20px;
    height: 80px;  
}

.headerRight {
    display: flex;
    flex: 0.3;
    align-items: center;
    margin-right: 20px;
    margin-top: 16px;
    margin-left: 50px;
    justify-content: flex-end;
} 

.headerRight input {
    border: none;
    width: 70%;
    font-size: medium;
    background-color: rgb(244 244 244 / 80%);
    padding: 10px;
    border-radius: 10px;
    outline-color: rgb(244 244 244);
}

#searchBall {
    width: 35px;
    padding-bottom: 5px;
}

header {
    margin-bottom: 20px;
    position: fixed;
    width: 100%;
    z-index: 1;
}

/*++++++++++++++++ TOP BUTTON ++++++++++++++++*/

#top {
    position: fixed;
    width: 50px;
    height: 50px;
    bottom: 70px;
    right: 30px;
    z-index: 99;
    outline: none;
    border: none;
    cursor: pointer;
    padding: 9px;
    border-radius: 4px;
    background-color: #375daa;
    border-radius: 50px;
}
  
#top:hover {
    background-color: #555;
}

#top span {
    color: white;
}

/*++++++++++++++++++ FOOTER ++++++++++++++++++*/

footer {
    background-color: white;
    height: 50px;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 30px;
    margin-bottom: 15px;
}

footer div a {
    text-decoration: none;
    color: black;
}

/*++++++++++++++++ POKE CONTAINER ++++++++++++++++*/

.pokeContainer {
    display: flex;
    flex-wrap: wrap;
    align-items: space-between;
    justify-content: center;
    margin: 0 auto;
    max-width: 1200px;
    padding-top: 150px;
}

.pokemon {
    background-color: #eee;
    border-radius: 20px;
    box-shadow: 0 3px 15px rgba(100, 100, 100, 0.5);
    margin: 10px;
    padding: 20px;
    text-align: center;
    display: flex;
    width: 250px;
    height: 250px;
    flex-direction: column;
    justify-content: space-evenly;
    align-items: center;
}

.pokemon .imgContainer {
    border-radius: 50%;
    width: 150px;
    height: 150px;
    text-align: center;
    margin-bottom: 10px;
    position: relative;
    right: 20px;
}

.pokemon .imgContainer img {
    padding-top: 10px;
    max-width: 100%;
}

.pokemon .pokemonInfo {
    margin-top: 5px;
    padding-bottom: 15px;
}

.pokemon .pokemonId {
    background-color: rgba(0, 0, 0, 0.09);
    border-radius: 10px;
    font-size: 0.8em;
    padding: 7px 12px;
    position: relative;
    right: 107px;
    top: 5px;
    color: white;
    font-weight: bold;
}

.pokemon .pokemonName {
    margin: 15px 7px 12px 7px;
    letter-spacing: 1px;
    color: white;
}

.pokeball {
    position: absolute;
    padding-left: 80px;
    padding-bottom: 80px;
    transform: rotate(5deg);
    opacity: 0.5;
}

.pokemonType {
    background-color: rgba(0, 0, 0, 0.09);
    border-radius: 10px;
    font-size: 0.8em;
    padding: 7px 12px;
    color: rgb(255, 255, 255);
    font-weight: 500;
}
const pokeContainer = document.getElementById('pokeContainer');
const pokemonNumber = 150;
const colors = {
    fire: '#F75131',
    grass: '#7BCE52',
    electric: '#FFC532',
    water: '#58ABF6',
    ground: '#D6B55A',
    rock: '#BCA55A',
    fairy: '#E4A5E5',
    poison: '#B45AA4',
    bug: '#ADBD20',
    dragon: '#7B62E7',
    psychic: '#FF72A5',
    flying: '#9CACF5',
    fighting: '#A35139',
    normal: '#ADA594'
};

const mainTypes = Object.keys(colors);

const fetchPokemons = async () => {
    for (let i = 1; i <= pokemonNumber; i++) {
        await getPokemon(i);
    }
}

const getPokemon = async id => {
    const url = `https://pokeapi.co/api/v2/pokemon/${id}`
    const res = await fetch(url);
    const pokemon = await res.json();
    createPokemonCard(pokemon);
}

fetchPokemons();

function createPokemonCard(pokemon) {
    const pokemonElement = document.createElement('div');
    pokemonElement.classList.add('pokemon');
    
    const pokemonTypes = pokemon.types.map(element => element.type.name);
    const type = mainTypes.find(type => pokemonTypes.indexOf(type) > -1);
    const name = pokemon.name[0].toUpperCase() + pokemon.name.slice(1);
    const color = colors[type];

    pokemonElement.style.backgroundColor = color;

    const pokemonInnerHTML = `
        <span class="pokemonId"># ${pokemon.id.toString()
            .padStart(3, '0')}</span>
            <img class="pokeball" src="img/ball_transparent.png">
        <div class="imgContainer">
            <img src="https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/${pokemon.id}.png">
        </div>
        <div class="pokemonInfo">
            <h3 class="pokemonName">${name}</h3>
            <small class="pokemonType">${pokemonTypes.join(', ')}</small>
        </div>
        
    `;

    pokemonElement.innerHTML = pokemonInnerHTML;

    pokeContainer.appendChild(pokemonElement);
}
  
  function filterPokemon() {
    let search = document.getElementById('search').value;
    search = search.toLowerCase();
    let content = document.getElementById('pokeContainer');
    content.innerHTML = '';
    for (let i = 0; i < pokemon.name.length; i++) {
        const name = pokemon.name[i]['name'];
        if (name.toLowerCase().includes(search)) {
            createPokemonCard(i);
        }
    }
}

React download button

I have an API that returns a pdf. I need that when I click a button downloads that pdf. I tried it on Postman and it returned the pdf correctly. My current code:

const [document, setDocument] = useState();
const downloadFile = async () => {
    const source = axios.CancelToken.source();
    setLoading(true);
    await getDocument(source); //getDocument saves document on 
    setLoading(false);
};
const getDocument = useCallback (async (source) => {
    await DocumentCalls.getDocument(setDocument, source)
}, []);

And my button:

<Button
     onClick={downloadFile}
>
   Download File
</Button>

Why is my openai api chrome extension not working

I am trying to create a google extension with openai api. After researching around for a while I made this code. However, when I type in the question and click “Ask”, these 2 errors appeared on console:
-Error handling response: TypeError: Cannot read properties of undefined (reading ‘answer’) at chrome-extension://enfpcdboapcobchgbmiiklnljabckpof/popup/popup.js:9:32
-Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.
I don’t know what is the problem. I am new to javascript so sorry if I made any dump mistake. Here is the code:

manifest.json

{
    "manifest_version": 3,
    "name": "GPT",
    "version": "1.0.0",
    "description": "OpenAI",
    "background": [{
        "matches": ["https://www.google.com/*"],
        "service_worker": ["background.js"],
        "persistent": true
    }],
    "action": {
        "default_popup": "popup/popup.html"
    },
    "icons": {
        "16": "images/icon-16.png",
        "32": "images/icon-32.png",
        "128": "images/icon-128.png"
    }
}

popup.html

<!DOCTYPE html>
<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>TrainerAI</title>
    <link rel="stylesheet" href="bulma.min.css">
</head>
<body>
    <div class="container m-3">
        <h1 class="title">TrainerAI</h1>
    </div>
    
    <div class="container m-3">
        <div class="field">
            <label class="label">Ask Anything</label>
            <div class="control">
                <input type="text" class="input" id="questionBox">
            </div>
        </div>
    </div>

    <div class="container m-3">
        <button class="button is-success is-fullwidth" id="askButton"> Ask </button>
    </div>

    <div class="container m-3">
        <div class="field">
          <label class="label">Result</label>
          <div class="control">
            <textarea class="textarea" id="resultBox" rows="10" readonly></textarea>
          </div>
        </div>
    </div>
</body>
<script src="popup.js"></script>
</html>

popup.js

const questionBox = document.getElementById("questionBox");
const askButton = document.getElementById("askButton");
const resultBox = document.getElementById("resultBox");

// Send message to background.js on button click
askButton.addEventListener("click", () => {
  chrome.runtime.sendMessage({ question: questionBox.value }, (response) => {
    // Display response from background.js in resultBox
    resultBox.value = response.answer;
  });
});

background.js

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    // Check if the message is a question
    if (request.question) {
      const apiUrl = "https://api.openai.com/v1/completions";
      const apiKey = "";
      const model = "text-davinci-003";
      const prompt = `${request.question}
  
      fetch(apiUrl, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": `Bearer ${apiKey}`,
        },
        body: JSON.stringify({
          "model": model,
          "prompt": prompt,
          "max_tokens": 300, 
          "temperature": 0,
        }), 
      })
      .then(response => response.json())
      .then(data => {
        const answer = data.choices[0].text;
        console.log(answer)
        sendResponse({ answer: answer });
      })
      .catch(error => console.log(error));  
      return true;
    }
  });

How can I spy on a function that is returned by a other function with Jest spyOn

I wonder why the last assert (expect(msgSpy).toBeCalled()) in this example fails. What do I need to change to make it pass?

  it('spyOn test', () => {
    const newClient = () => {
      const getMsg = () => {
        return 'dear spyOn';
      };
      const getHello = () => {
        return `Hello, ${getMsg()}`;
      };
      return {
        getMsg,
        getHello,
      };
    };

    const c = newClient();
    const helloSpy = jest.spyOn(c, 'getHello');
    const msgSpy = jest.spyOn(c, 'getMsg');

    expect(c.getHello()).toEqual('Hello, dear spyOn');

    expect(helloSpy).toBeCalled(); // asserts to true
    expect(msgSpy).toBeCalled();   // <-- asserts to false!
  });

While automating the Oracle forms, script is getting passed even if it is not executed properly (using selenium with robot js and nut js)

[Here the Another.png not present in that particular form still it is not coming to the catch block .
And even if it doesn’t find the correct Capture.png it is clicking somewhere in the form and script is getting passed.

  1. post click step 65, getting one popup because of that it is not executing rest of the step still that method getting passed
    Can anyone help me in this for proper validation – it should fail if the step doesn’t execute properly] (https://i.stack.imgur.com/mK0zQ.png)

Can anyone help me in this for proper validation – it should fail if the step doesn’t execute properly

Typescript errors while destructuring foreach from object.entries output

I am having certain types that are categorized based on mimetypes

export type MimeType = 'image' | 'application' | 'text';

export type ApplicationMimeType = '.pdf' | '.zip';

export type ImageMimeType = '.gif' | '.png' | '.jpeg' | '.jpg' | '.svg' ;

export type TextType = '.csv' | '.txt';

export type ExtensionTypes = ImageMimeType[] | ApplicationMimeType[] | TextType[];

export type FileType = {
  image?: ImageMimeType[];
  application? : ApplicationMimeType[];
  text? : TextType[]
};

Now when I use it in a function, then use Object.entries when a certain object is passed, the key type is set to string. Is there a way for this key to be set to the type of MimeType?

I tried the solution that is given in this link: Typescript Key-Value relation preserving Object.entries type

Code I tried that is giving me error Type 'undefined' is not assignable to type 'string[]'.

How can I restrict key to be MimeType and extensions to be ExtensionTypes


export type Entries<T> = {
  [K in keyof T]: [extensions: T[K]][];
}[keyof T][];

export const getAcceptedFileTypes = (mimeTypes: FileType) => {
  const acceptedTypes = {};
  Object.entries(mimeTypes as Entries<mimeTypes>).forEach(([key, extensions]) => {
    if (key === 'text') {
      acceptedTypes['text/*'] = extensions;
    } else if (key === 'image') {
      extensions.forEach(
        (image) => (acceptedTypes[`image/${image.substring(1)}`] = [image])
      );
    } else {
      extensions.forEach(
        (application) =>
          (acceptedTypes[`application/${application.substring(1)}`] = [
            application,
          ])
      );
    }
  });
  return acceptedTypes;
};

getAcceptedFileTypes({ image: ['.png'], application: [] })

How can we add custom property in array prototype in javascript just like length to receive last item of that array? [duplicate]

I am looking for a way to create a new variable in Array prototype in javascript similar to Array.length property. So that I can get the last element just by calling that array property. Something like mentioned below

Example:

const arr = ['a','b','c'];

// Current working property: length
console.log(arr.length) // It will give me 3 and I didn't need to call any function.

// What I want to achieve: lastItem
console.log(arr.lastItem) // It should give me 'c' without calling as a function.

I have a way to get last item by creating a prototype method but I don’t want to call any method to get last value. I want it to be set as property only.

Cannot update a component (`AuthProvider`) while rendering a different component (`RequireAuth`)

I’m working with react-auth-kit

I have this button, when we click on it the function Auth is launched

SignIn file

const navigate = useNavigate();

<button className="signin__enter_enterbutton" onClick={auth}>
       Увійти
       <svg className="signin__enterbutton-arrow" width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M1.29231 12L10.1538 3.13846V11.0769H12V0H0.923077V1.84615H8.86154L0 10.7077L1.29231 12Z" fill="black" />
       </svg>
</button>

const auth = async () => {
        const response = await authUser(body);
        const token = await response.text();

        if (token === 'User not Found') {
            setError(true);
        } else if(response.status === 200){
            signIn({
                token: token,
                tokenType: 'Bearer',
                expiresIn: 140,
                authState: {
                    user: phoneNumber,
                }
            });

            navigate('/account');
        }
    }

App file

const routes = [
  {
    element: <OutletPage />,
    children: [
      {
        path: 'account',
        element: <RequireAuth loginPath="/sign-in"><Account /></RequireAuth>
        // element: <Account />
      }
    ]
  }
];

<div className="app">
      <CartContext.Provider value={{ numberCart, setNumberCart }} >
        <RouterProvider router={router} />
      </CartContext.Provider>
</div>

Oh and if i delete element: <RequireAuth> <Account /> </RequireAuth> in App.js file and I’ll just leave <Account /> everything is gonna work either

OutLet file

  const [isFilter, setIsFilter] = useState(false);
  let location = useLocation();

  useEffect(() => {
    if (location.pathname.includes('catalog')) {
      setIsFilter(true);
    } else if (!location.pathname.includes('catalog')) {
      setIsFilter(false);
    }
  })

  return (
    <>
      <ScrollToTop />
      <NavBar />
      <div className='app__navCatalogPlusPage'>
        {(!isFilter && location.pathname !== '/hookah-catering') &&
          <div className='app__WithoutFooter_navCatalog'>
            <Navigation />
            <Catalog />
          </div>
        }
        <Outlet />
      </div>
      <Footer />
    </>
  )

In SignIn response receives a response from authUser() that function takes body it is just password and login and will return Bearer Token if everything is okay. Then i convert response into a text and check that we have not received 'User not Found' if not received, write down paramethers in react-auth-kit function signIn() and then call react-router-dom function useNavigate() and there is main problem i will get this type of error errorerror

in the second image we can see some error called auth in SignIn file of the fifty-seventh line on this line i have a navigate('/account'); code, and if i delete it error will gone BUT useNavgate() is imoportant bacause only it can work with React Routes in correct way and i have no idea why react-auth-kit cannot work with react-router-dom and how to fix it

Why is the login path loaded twice in my code below?

Below are codes of my app.component.ts and another module called login. I have setup router for navigation to login component. I will first put down my code and then state my problem after that.

app.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
    constructor(private router: Router) { }

    ngOnInit() {
        const accessToken = localStorage.getItem('access_token');
        // if(accessToken) {
        //  this.router.navigateByUrl('/posts');
        // } else {
        //  this.router.navigateByUrl('/login');
        // }
    }
}

login.component.ts

import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Subscription } from 'rxjs';

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit, OnDestroy {

    paramsSubscription: Subscription | undefined;

    constructor(private route: ActivatedRoute, private router: Router) { }

    ngOnInit() {
        this.paramsSubscription = this.route.queryParams.subscribe(params => {
            const accessToken = params['access_token'] || localStorage.getItem('access_token');
            console.log('ACCESS TOKEN: ', accessToken);
            if(accessToken) {
                localStorage.setItem('access_token', accessToken);
            }
        });
    }

    ngOnDestroy() {
        this.paramsSubscription?.unsubscribe();
    }

    loginViaFacebook() {
        window.location.href = 'http://localhost:3000/auth/facebook';
    }

    loginViaGoogle() {
        window.location.href = 'http://localhost:3000/auth/google';
    }
}

I am trying to pass a query parameter to the /login path and if the same is found I want to redirect the user to /posts.
The path I am trying to access is http://localhost:4200/login?access_token=abcdef.
There is an unexpected behaviour that I am observing. When I comment the navigation code in ngOnInit() of app.component.ts I am able to capture the queryParam in my login.component.ts. However if I keep it uncommented, I can see the queryParam getting logged once and the login path is again called and this time there is no query param(It is empty).

I am new to angular. Is there something related to routers that I am missing?

Prerendering error when deploying next js, sanity project?

I have the following error usin Sanity cms with Next.js 13

Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error
TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:14062:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async fetchPrices (/vercel/path0/.next/server/pages/index.js:581:17)
    at async getStaticProps (/vercel/path0/.next/server/pages/index.js:558:24)
info  - Generating static pages (3/3)

Export encountered errors on following paths:
    /
Error: Command "npm run build" exited with 1
Deployment completed
BUILD_UTILS_SPAWN_1: Command "npm run build" exited with 1

Context:
I have “next”: “13.3.0”, “next-sanity”: “^4.1.7”, installed

.env.local:

  • NEXT_PUBLIC_SANITY_DATASET=production
  • NEXT_PUBLIC_SANITY_PROJECT_ID={projectID}
  • NEXT_PUBLIC_BASE_URL=http://localhost:3000/

build script package.json:
“build”: “next build && next export”,

I use pages folder structure not appDir

in pages:

  • api(folder)
  • _app.tsx
  • _document.tsx
  • index.tsx

next.config.js:

const nextConfig = {
  pageExtensions: ["mdx", "md", "jsx", "js", "tsx", "ts"],
  reactStrictMode: true,
};

module.exports = nextConfig;

If I do

npm run build

It build out fine, but when I do a commit neither netlify or vercel can’t deploy, I get the above error.
I also receive error if in env.local I use the prod url…

This is my local build:

Route (pages)                              Size     First Load JS
┌ ● / (390 ms)                             40.9 kB         114 kB
├   └ css/41abe3765720b937.css             851 B
├   /_app                                  0 B            73.6 kB
├ ○ /404                                   182 B          73.8 kB
├ λ /api/getPrices                         0 B            73.6 kB
└ λ /api/getQuote                          0 B            73.6 kB

Looks weird that both api endpoint is 0 B, but I have no clue at this point what is the issue.. Before I added Sanity cms to the project everything was fine, but now I can’t merge the cms implementation to master as the deployment fails…

deployment error:

Error occurred prerendering page "/". Read more: https://nextjs.org/docs/messages/prerender-error
SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at packageData (node:internal/deps/undici/undici:6370:23)
    at specConsumeBody (node:internal/deps/undici/undici:6348:14)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async fetchPrices (/vercel/path0/.next/server/pages/index.js:582:18)
    at async getStaticProps (/vercel/path0/.next/server/pages/index.js:558:24)
info  - Generating static pages (3/3)
> Export encountered errors on following paths:
    /
Error: Command "npm run build" exited with 1
Deployment completed
BUILD_UTILS_SPAWN_1: Command "npm run build" exited with 1

If any more context needed regarding my implementation let me know.