How can I print the output inside the 3rd blank box in the given image

`
Question no 3

    <form>
        <input type="text" id="f_num" placeholder="Enter your first number"><br><br>
        <input type="text" id="s_num" placeholder="Enter your second number"><br><br>
        <input type="submit" value="Multiply" onclick="mul()">
        <input type="submit" value="Divide" onclick="div()"><br><br>
        <input type="text">
    </form>
</body>
<script>
    function mul(){
        var a=parseInt(document.getElementById("f_num").value);
        var b=parseInt(document.getElementById("s_num").value);
        var res= a*b;
        document.write(res);
    }
    function div(){
        var a=parseInt(document.getElementById("f_num").value);
        var b=parseInt(document.getElementById("s_num").value);
        var res= a/b;
        document.write();
    }
    
</script>

`

I am trying to show my output inside the third box but it shows the output in a separate page. How to solve that.

Created library have issues with @testing-library

I’m working on a private library of components published in Gitlab Package Registry.
The components works pretty well, but testing using @testing-library throw an error .

Here is the error:

Details:

    /Users/zlnk/Git/making/vts/payments/node_modules/@vts/kb/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import r from "react";
                                                                                      ^^^^^^
    SyntaxError: Cannot use import statement outside a module

       5 | import HelpOutlineIcon from '@mui/icons-material/HelpOutline'
       6 | import { Box, Grow, Typography } from '@mui/material'
    >  7 | import { Icon } from '@vts/kb'
         | ^

      at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
      at Object.<anonymous> (src/containers/nav-bar/nav-bar.tsx:7:1)

As far as I understand, the issue is because package is importing react

My vite.config.ts

import { resolve } from "path"
import { viteStaticCopy } from "vite-plugin-static-copy"
import { defineConfig } from "vite"
import dts from "vite-plugin-dts"

export default defineConfig({
  publicDir: false,
  build: {
    lib: {
      entry: resolve(__dirname, "src/index.ts"),
      name: "kb",
      fileName: "index",
      formats: ["es"],
    },
    rollupOptions: {
      external: ["react"],
      output: {
        globals: {
          react: "React",
        },
        assetFileNames: "static/styles/components.css",
      },
    },
  },
  plugins: [
    dts({
      insertTypesEntry: true,
    }),
    viteStaticCopy({
      targets: [
        {
          src: resolve(__dirname, "src/static"),
          dest: "./",
        },
        {
          src: resolve(__dirname, "./README.md"),
          dest: "./",
          rename: "README.md",
        },
        {
          src: resolve(__dirname, "./package.json"),
          dest: "./",
        },
      ],
    }),
  ],
})

I’m not sure why this happens, but here is my tsconfig.json

{
  "compilerOptions": {
    "jsx": "react",
    "target": "ESNext",
    "types": ["vite/client"],
    "useDefineForClassFields": true,
    "module": "ESNext",
    "lib": ["ESNext", "DOM"],
    "moduleResolution": "Node",
    "strict": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "esModuleInterop": true,
    "noEmit": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "skipLibCheck": true,
    "declaration": true,
    "declarationDir": "dist"
  },
  "include": ["src"],
  "exclude": ["src/**/*.stories.tsx", "vite-env.d.ts"]
}

I want a way to keep using ESM but preventing the issue.

SmartClient In angular

Im trying to implement SmartClient into my angular project while following the documentacion. But ive gotten stuck on a certain part:

import {drawCanvasOnElement} from '@app/_helpers/smartclient-framework';
This import should import this function:

export function drawCanvasOnElement (builder, element) {

     isc.FileLoader.load(() => {
         builder(element);
     }, {target: element});
 }

But the error i get is the following:
First error

I tried putting the function in the same class so that i can call the function myself but then i get the following error:
Second error
And this error is the one i cant get to work, and i dont understand why because isc.FileLoader works when its in the index.html, so FileLoader is definitly part of the isc namespace but wont let me use it in the component ts.

Here is an exaple of that property being used:
Example of FileLoader being used.

Any tips would be most appreciated.

If there is any confusion or i havent explained myself enough ill try to change it.

-Many thanks.

How can I fill text area in Javascript or Sencha(ExtJs)?

I have a text area and a grid. I want the text area to fill when I click on the grid’s row. I tried something like below but I can’t run it.

try {
    var criteriaList=[];
    var XThis = this;
    var grid_2 =XThis.down("#grd_1");
    var params = grid_1.getSelectionModel().getSelection()[0].data;

    var textArea = this.down("#tb_3").down('#textarea_1');
    X.search.clearCriteriaList("grd_1");


   textFill = function(params){
        try {
            if(params){
                textArea_1.getStore().loadData(params);
              
            }
        } catch (e) {
          //throw exception
        }
    };


}catch(e){
    //throw exception
}

How can fix it or how can I write what I want ?

Is there an Algorithm for this recursive problem fetching data from an api?

I am working on fetching some data from a server, and there are 6 endpoints I need to hit and fetch data from. but the problem I can’t get my head around writing an efficient algorithm without tons of for loops and ifs. I tried t divide the problem into smaller chunks but I can’t come up with a solution.


async function fetch_children(endpoint, state) {
  const temp = await call_api(endpoint, state);
  state["children"] = await temp;
  state["endpoint"] = endpoint;
  return state;
}

async function loop_over(state) {
  const item = await fetch_children(endpoints[0], state);
  if (item["children"]) {
    for (const idx in item["children"]) {
      item["children"][idx] = await fetch_children(
        endpoints[1],
        item["children"][idx]
      );

      if (item["children"][idx]["children"]) {
        for (const idm in item["children"][idx]["children"]) {
          item["children"][idx]["children"][idm] = await fetch_children(
            endpoints[2],
            item["children"][idx]["children"][idm]
          );
          if (item["children"][idx]["children"][idm]["children"]) {
            for (const id in item["children"][idx]["children"][idm][
              "children"
            ]) {
              item["children"][idx]["children"][idm]["children"][id] =
                await fetch_children(
                  endpoints[3],
                  item["children"][idx]["children"][idm]["children"][id]
                );
              if (
                item["children"][idx]["children"][idm]["children"][id][
                  "children"
                ]
              ) {
                for (const idd in item["children"][idx]["children"][idm][
                  "children"
                ][id]["children"]) {
                  item["children"][idx]["children"][idm]["children"][id][
                    "children"
                  ][idd] = await fetch_children(
                    endpoints[5],
                    item["children"][idx]["children"][idm]["children"][id][
                      "children"
                    ][idd]
                  );
                }
              }
            }
          }
        }
      }
    }
  }
  return item;
}

one of my attempts:

async function fetch_children(endpoint, state) {
  const temp = await call_api(endpoint, state);
  state["children"] = await temp;
  state["endpoint"] = endpoint;
  return state;
}

async function loop_over(endpoint, place) {
  const item = await fetch_children(endpoint, place);
  return item;
}

async function test(endpoints, state) {
  state = await loop_over(endpoints.pop(), state);
  if (state["children"].length >= 1 || endpoints.length >= 1) {
    for (const idx in state["children"]) {
      state["children"][idx] = await test(endpoints, state["children"][idx]);
    }
  }
  return state;
} 

but it didn’t work because for some reason endpoints is out of element even though I am checking the length

any help is appreciated, what an algorithm or what am I missing here?

Thanks in advance!

for more context the response tree need to looks like the following:

/// response of loop and ifs aforementioned function
{
  "name": "",
  "id": "",
  "children": [
    {
      "name": "",
      "id": "",
      "children": [
        {
          "name": "",
          "id": "",
          "children": [
            {
              "name": "",
              "id": "",
              "children": [
                { "name": "", "id": "" },
                { "name": "", "id": "" },
                { "name": "", "id": "" },
                { "name": "", "id": "" },
                { "name": "", "id": "" },
                { "name": "", "id": "" },
              ],
              "endpoint": "endpoints[3]"
            }
          ],
          "endpoint": "endpoints[2]"
        }
      ],
      "endpoint": "endpoints[1]"
    },
    {
        ....
    },
     ...
]
async function fetch_children(endpoint, state) {
  const temp = await call_api(endpoint, state);
  state["children"] = await temp;
  state["endpoint"] = endpoint;
  return state;
}

async function loop_over(endpoint, place) {
  const item = await fetch_children(endpoint, place);
  return item;
}

async function test(endpoints, state) {
  state = await loop_over(endpoints.pop(), state);
  if (state["children"].length >= 1 || endpoints.length >= 1) {
    for (const idx in state["children"]) {
      state["children"][idx] = await test(endpoints, state["children"][idx]);
    }
  }
  return state;
} 

It seems you are interpolating a keyframe declaration into an untagged string

I want to inject keyframes and some other styles into the style prop of a div

import styled, {css, keyframes} from 'styled-components'

const width = _selectWidth()
const fill = keyframes `100% { background-position: 50%;}`;
const fillCss = css`${fill} 8s 1s forwards`
const styles = {
    animation: fillCss,
    backgroundImage: `linear-gradient(to right, ${color} 50%, transparent 0)`,
    width: `${width}%`
};

And then I use it like this

<div style={styles} />

However, this gives me

It seems you are interpolating a keyframe declaration (dskIpG) into an untagged string. This was supported in styled-components v3, but is not longer supported in v4 as keyframes are now injected on-demand. Please wrap your string in the css“ helper which ensures the styles are injected correctly. See https://www.styled-components.com/docs/api#css

How can I use keyframes?

How to pass value from vue.js file to another html file?

the value of the “symbol” attribute in the widget must be dynamic depending on the choice of the currency pair in the list, in the vue.js file the value of the currency pair from the list is written to the “symbol” variable and I need to transfer the value of this variable from the vue file to normal html in order to use it later this is the value in the html file script
Vue.js file:

    <select v-model="currSymbol" @change="event => socket.emit('symbol:change', {symbol: currSymbol, interval: currInterval})">
    <option v-for="pair in pairs">
      {{ pair.symbol }}
    </option>

HTML file:

 <div id="app">
    <div class="tradingview-widget-container">
      <div class="tradingview-widget-container__widget"></div>
    </div>
  </div>

  <script type="text/javascript" src="https://s3.tradingview.com/tv.js"></script>


  <script type="text/javascript">
    new TradingView.widget(
    {
      "width": 1000,
      "symbol": "{{ symbol }}",
      "interval": "D",
      "timezone": "Etc/UTC",
      "theme": "light",
      "style": "1",
      "locale": "en",
      "toolbar_bg": "#f1f3f6",
      "enable_publishing": false,
      "allow_symbol_change": true,
      "container_id": "tradingview_02e7f"
    }
    );
  </script>

I don’t know how to accomplish this task.

OpenSSL Signature vs WebCrypto signature

Let’s use a test key (don’t use it, it’s just a test, I don’t use it either):

-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgkeS6LTDov1L2oShp6PgM2STESyMD1YTQkxUtxSJc1PahRANCAAR+uKNDd0l2odP4excxvTBY5bQxQBufCYb2TkVgp1NBefyO603LHzOelGVnnIFfamtJvv55AwVxt0nUlS0z450U
-----END PRIVATE KEY-----

I want to sign in Javascript and verify in PHP but I don’t get the same result so I tried to get at first same result for signing. Here is my code:

PHP:

$challenge=file_get_contents("/tmp/challenge-XIABFf");
$key=openssl_pkey_get_private(file_get_contents("/tmp/private-key"));
$response="";
openssl_sign($challenge,$response, $key, OPENSSL_ALGO_SHA384);
var_dump(base64_encode($response));

I get : MEYCIQCQt9+reL0WRzi26ft8CEUMRDhnd4vh50F3sYL9BA2x0QIhAJCD7bakD6jXIfYTNpEoGPTR9guusC7CFxbbFcKPvroq which is 96 characters.

Now in JS :

function arrayBufferToBase64(buffer) {
        var binary = '';
        var bytes = new Uint8Array(buffer);
        for (var i = 0; i < bytes.byteLength; i++) {
            binary += String.fromCharCode(bytes[i]);
        }
        return btoa(binary);
    }
function base64ToArrayBuffer(base64) {
    var binary_string = atob(base64);
    var len = binary_string.length;
    var bytes = new Uint8Array(len);
    for (var i = 0; i < len; i++) {
        bytes[i] = binary_string.charCodeAt(i);
    }
    return bytes.buffer;
}

key=await window.crypto.subtle.importKey("pkcs8",base64ToArrayBuffer("MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgkeS6LTDov1L2oShp6PgM2STESyMD1YTQkxUtxSJc1PahRANCAAR+uKNDd0l2odP4excxvTBY5bQxQBufCYb2TkVgp1NBefyO603LHzOelGVnnIFfamtJvv55AwVxt0nUlS0z450U"), {name: "ECDSA", namedCurve: "P-256"},true,["sign"]);
message=await window.crypto.subtle.sign({"name": "ECDSA", "hash": "SHA-384"},key,base64ToArrayBuffer("4BRYPzkacla7x5uR0bXtkQXC18odd9yCfcefjIrh")); console.log(arrayBufferToBase64(message));

The 4BRY… is the base64 of the challenge. And the result is : ZDDWSkpkwS8N8LYhHib/Qeb+P8DMRtKIT925AhO8m6bD/K5wAYEYa3Fq89Ik8z6t62a0dtuN8kydxNWttgFcdA== (88 characters) which is not the same as PHP, why?

how can I move html carousel by scrolling in JavaScript

I wrote a js code to move carousel when I scroll, but its’s not working.
Where is the problem?(I’m not an expert in js my main language is c#)

<div class="wrapper mx-auto">
        <i class="fa-solid fa-angle-left"></i>
        <div class="slider">
            <img src="https://www.cnet.com/a/img/resize/3470424f360dd5f4c082bf7a5b7c3f5cd78e298b/hub/2022/10/11/3d748baf-46a0-499c-af4c-6e88a8dec985/pixel-7-pro-watch-lanxon-promo-53.jpg?auto=webp&width=1200" />
            <img src="~/images/note20.jpg" />
            <img src="~/images/s23.jpg" />
            <img src="~/images/google-pixel7.jpg"/>
            <img src="~/images/iphone-xsmax.jpg" />
            <img src="~/images/iphone13.jpg"  />
        </div>
        <i class="fa-solid fa-angle-right"></i>
    </div>
const carousel = document.querySelector(".slider");
const dragging = (e) => {
    if (!isDragStart) return;
    e.preventDefault();
    carousel.scrollLeft = e.pageX;
}
carousel.addEventListener("mousemove", dragging);

Node : Get all day in a week for the same month

Using NodeJS I currently struggle with a date issue.
I need to get the first and last day of a week only if they are in the same month.
And this for the on-going week.
For example, for this week, and want it to return 20 (Monday) and 24 (Friday) for my timezone.

The issue is when two months are on the same week.

Example : We had Mon 27 feb / Tue 28 Feb / Web 1 Mar

I need to get 27 / 28 when we are on monday and tuesday,
And 1 / 3 when we are on Wednesday Thursday and Friday
(According to the previous example)

Currently I have this :

  const date = new Date();

  const startOfWeek = new Date(date);
  startOfWeek.setDate(startOfWeek.getDate() - startOfWeek.getDay() + 1);
  const firstDay = startOfWeek.getDate();

  const endOfWeek = new Date(date);
  endOfWeek.setDate(endOfWeek.getDate() + (5 - endOfWeek.getDay()));
  const lastDay = endOfWeek.getDate();

It works to get all date for the current week but when there are two months, firstDay is in the previous month and lastDay in the next month.

I tried searching for answers but I couldn’t manage to get one for this case …

Thanks !

Angular – Dynamically inject package css files on runtime for theming

The npm package that I use have a few themes. Lets say its an table view package.

I want set this themes on admin panel. If the admin desire table to be displayed in dark mode. When its changed on settings page, I want that spesific .css file to be injected for the table component.
I found a solution that I injected in the table component by reading settings data via my api but it didnt feel good.

Is there any way to inject theme css files at /node-modules/theme/light.css and dark.css in runtime without injecting them into document head on init method. I couldn’t find any.

btw, I am using scss in the project.

Load css file dynamically for theming
I found a solution similar to the one here, but I want to assign a theme to a global variable and act accordingly. I want to render by getting setting vars before loading the page without using Document.

I can change themes as lazy loading onInit via SettingsService but I’m not sure it’s best practice

Can’t display database info for session user with nextjs and prisma after using nextauth login with github

I use nextauth to log in with github. This automatically populates the db with name, avatar and email . I want to get id and role, which is set in prisma to ‘APPLICANT’ by default. When I check my prisma table, I see my name, avatarlink, email and role set to ‘APPLICANT’ and id. What I want to do is change the role ‘APPPLICANT’ to ‘CONSULTANT’ everytime a user clicks a button and vice versa but I get a message that the role and id are undefined. I have console logged them and they are undefined

For the role button, I set it so , as it’s APPLICANT by default, if you click on it and it goes to the recruiter page but I can’t change the status of the role

import Link from 'next/link';
import React from 'react';
import { signIn, signOut, useSession } from 'next-auth/react';
import axios from 'axios';

function Navbar() {
  const { data: session, status } = useSession();
  console.log('session => ', session);
  console.log('status => ', status);
  const [userData, setUserData] = React.useState({});

  const handleSwitchToConsultant = () => {
    axios.get(`/api/user/${session.user.id}`).then((response) => {
      setUserData(response.data);
      console.log('response.data => ', userData.id);
    });
    axios
      .put(`/api/user/editUser/${session.user.id}`, { role: 'CONSULTANT' })
      .then((response) => {
        // Update the session with the new role
        const newSession = {
          ...session,
          user: { ...session.user, role: 'CONSULTANT' },
        };
        // Save the new session to the client
        sessionStorage.setItem(
          'next-auth.session-token',
          JSON.stringify(newSession)
        );
      })
      .catch((error) => {
        console.log(error);
      });
  };
  const handleSwitchToApplicant = () => {
    axios
      .put(`/api/user/editUser/${session.user.id}`, { role: 'APPLICANT' })
      .then((response) => {
        // Update the session with the new role
        const newSession = {
          ...session,
          user: { ...session.user, role: 'APPLICANT' },
        };
        // Save the new session to the client
        sessionStorage.setItem(
          'next-auth.session-token',
          JSON.stringify(newSession)
        );
      })
      .catch((error) => {
        console.log(error);
      });
  };

  return (
    <div className="w-full h-20 pl-[15px] bg-[#2D3E64] flex justify-between align-center items-center">
      <h1 className="text-white font-semibold text-2xl">HDM</h1>
      <div className="flex justify-end">
        {!session && status !== 'authenticated' && (
          <Link
            href="/api/auth/signin"
            onClick={(e) => {
              e.preventDefault();
              signIn();
            }}
          >
            <button className="bg-slate-300 p-3 mr-3 rounded-lg">
              Sign In
            </button>
          </Link>
        )}
        {session && (
          <Link
            href="/api/auth/signout"
            onClick={(e) => {
              e.preventDefault();
              signOut();
            }}
          >
            <button className="bg-slate-300 p-3 mr-3 rounded-lg">
              Sign Out
            </button>
          </Link>
        )}

        <button className="bg-slate-300 p-3 mr-3 rounded-lg">Register</button>
        {session && session.user.role !== 'CONSULTANT' ? (
          <Link href="/companydetails">
            <button
              className="bg-slate-300 p-3 mr-3 rounded-lg"
              onClick={() => {
                handleSwitchToConsultant;
              }}
            >
              Recruiter
            </button>
          </Link>
        ) : (
          <Link href="/offers">
            <button
              className="bg-slate-300 p-3 mr-3 rounded-lg"
              onClick={() => {
                handleSwitchToApplicant;
              }}
            >
              Jobseeker
            </button>
          </Link>
        )}
      </div>
    </div>
  );
}

export default Navbar;

Typescript Parameter utility function only extract the parameters of the last definition from an overloading function [duplicate]

I’m having a problem with the Parameter utility function, I’m trying to extract all the possible parameters types of a function that has overloading definitions, but the utility only extracts the last definition, example:

type MyFunction = {
  (a: string, b: string): string
  (a: number): number
}

type Params = Parameters<MyFunction>

Params in this case is only of type:

type Params = [a: number]

Instead of [a: number] | [a: string, b:string]

Google Sign in and AngularJS

Because of Google Sign in will be deprecated, i’m trying to substitute with new one of Google ( https://developers.google.com/identity/gsi/web/guides/overview?hl=en )

I’m trying but I have some problems..

I have added in my index.html:

<script src="https://accounts.google.com/gsi/client" async defer></script>
                <div id="g_id_onload" data-client_id="cliend_id" data-login_uri="login_uri" data-auto_prompt="false">
                </div>

In my module.js I defined the
$rootScope.cliend_id and

$rootScope.login_uri.

So:

var initClient = function () {
            window.onload = function () {
                google.accounts.id.initialize({
                    client_id: $rootScope.cliend_id,
                    callback: data => $rootScope.handleCredentialResponse(data)
                });
                google.accounts.id.prompt();
            }
        }

        $rootScope.handleCredentialResponse = function (data) {
            console.log("handle", data)

        }
        initClient();

Now I receive error:

TypeError: Cannot read properties of undefined (reading ‘accounts’)

In other project this was because I need to declare var google ( for example in Angualr declare const google ), I have also tried here to declare: var google but it doesn’t work.

How can I solve this problem with google sign-in in angularJs?

window.focus() or window.close() not working on windows opened with google domain url

I am trying to reuse opened windows and to do that i want to use the .focus() method (or .close() and reopen new). While working i noticed that when i use urls with google domain, the methods stop working on Firefox (109.0.1 (64-bit)) and Chrome (Version 111.0.5563.64 (Official Build) (x86_64)). I’m using MacOS BigSur 11.7.

However, on Safari (6.3 (16614.4.6.11.4, 16614)) it works.

ex urls that did not work: https://www.google.com/, https://translate.google.com/, https://maps.google.com/maps?q=&layer=c&cbll=44.6514203255951,-63.57586876433356

focus method answer – I used this example to create my own way to test the problem explained above:

<script>
    window.openOrFocus = function(url, name, style = "width=500,height=500") {
        if (!window.popups)
            window.popups = {};
        if (window.popups[name]){
            window.popups[name].focus();
        } else{
            window.popups[name] = window.open(url, name, style);
        }
    }
</script>
<a href="#" onclick='window.openOrFocus("https://www.google.com/","google","width=500,height=500");'>Open/focus GOOGLE window</a></br>
<a href="#" onclick='window.openOrFocus("https://www.youtube.com/","youtube","width=500,height=500");'>Open/focus YOUTUBE window</a>

I placed some console logs and on Firefox i get a ‘Restricted’ on window.popups and using chrome i noticed that the param closed is true on google window even if it is not closed yet.