Conditional parameter always resolves to undefined

I’m trying to make a value resolver like this:

type Method<TValue, TArgs extends [...any]> = (...args: [...TArgs]) => TValue;

function getValue<TValue, TArgs extends [...any]>(value: TValue | Method<TValue, TArgs>, args?: typeof value extends Method<TValue, TArgs> ? TArgs : never): TValue | undefined {
  if (typeof value === 'function') {
    return args ? (value as Method<TValue, TArgs>)(...args) : undefined;
  }
  return value;
}

But when I try to call it with a function, like so:

function test(num: number): number { return num };

const value1 = getValue(test, [23]);
                               ^^-ERROR

const value2 = getValue<number, [number]>(test, [23]);
                                                 ^^-ERROR

I get this error:

Argument of type ‘number[]’ is not assignable to parameter of type ‘undefined’

Does anyone know how I can get the args parameter to correctly resolve to the required array of parameters?

React js with Zod validation superRefine not updated realtime with values changes

React js with Zod validation superRefine not updated realtime with values changes

for this code every thing is fine but I want when the user start with the end date and then the error show “select start date first” after that return back to start date and select start date error of “select start date first” is still shown why is that and how to solve it

const formSchema = z
  .object({
    game: z.string().min(1, { message: "you must select at least one game" }),
    tournamentName: z
      .string()
      .min(2, "Tournament Name must be at least 2 characters."),

    platform: z.enum(["mobile", "pc", "xbox"]),
    description: z.string(),
    rules: z.string(),
    coverImage: z.any(),
    profileImage: z.any(),
    startDate: z
      .date()
      .refine(
        (date) => date instanceof Date && !isNaN(date) && date > new Date(),
        {
          message: "Start Date must be a valid date and in the future.",
        }
      ),
    endDate: z.date().refine((date) => date instanceof Date && !isNaN(date), {
      message: "End Date is required.",
    }),
  })
  .superRefine((data, ctx) => {
    const { startDate, endDate } = data;
    console.log(data);
    if (!startDate && endDate) {
      ctx.addIssue({
        path: ["endDate"],
        message: "select start date first",
      });
    }
    if (startDate > endDate) {
      ctx.addIssue({
        path: ["endDate"],
        message: "End Date must be after Start Date.",
      });
    }
  }); 

React js with Zod validation superRefine not updated realtime with values changes how can I get real time updating that when I update end date without start date set –> error “you must select start date” and if return to start date the error must not shown all things real time

upload picture in google form selenium

I’m reaching out for some help regarding uploading an image to Google Forms using Selenium. I’ve been working on this for days, and despite trying various approaches, I still can’t make it work. Here’s the situation:

I’ve managed to open the form and even triggered the file upload dialog box by clicking the “Add file” button. However, when it comes to interacting with the dialog, specifically clicking on the file input button (type=”file”), I keep hitting a wall. The button is present in the DOM and visible on the page, but Selenium doesn’t seem to be able to interact with it.

Here’s what I’ve tried so far:

Locating the button – I've located the correct XPath for the "Add file" and file input button.
Waits and delays – I’ve added explicit waits (WebDriverWait) to ensure the elements are loaded before interacting with them.
JavaScript execution – I even attempted executing JavaScript directly to trigger the click event, but that didn’t solve the issue.
Other actions – I've tried switching to the frame or the dialog using switch_to.frame() just in case it’s an iframe, but that approach hasn’t helped either.

So far, I’ve been able to:

Open the Google Form.
Click the "Add file" button successfully.
Wait for the popup to appear. But I’m stuck at trying to upload the image itself.

I’m working on a project where this functionality is critical, and I really need to finish this as soon as possible. If anyone has experience with uploading images in Google Forms using Selenium, or any ideas on how I can fix this issue, please share your insights!

I’m open to any suggestions, whether it’s about tweaking the current approach or trying something entirely different. Thank you so much in advance for your help!

import undetected_chromedriver as webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
import time

# Configuration des options de Chrome
options = webdriver.ChromeOptions()
profile = r"C:\Users\User\AppData\Local\Google\Chrome\User Data\Profile 1"
options.add_argument(f"user-data-dir={profile}")
options.add_argument("profile-directory=Profile 1")
driver = webdriver.Chrome(options=options, use_subprocess=True)

try:
    driver.get("https://forms.gle/HcKLXz9ErXkm63qK8")
    print("Formulaire ouvert avec succès.")

    # Cliquer sur le bouton 'Add file'
    add_file_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, '/html/body/div[1]/div[3]/form/div[2]/div/div[2]/div/div/div/div[2]/div/div[3]/span/span[2]'))
    )
    add_file_button.click()
    print("Bouton 'Add file' cliqué avec succès.")

    # Attendre que le popup apparaisse
    popup = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, '/html/body/div[1]/div[2]'))  # XPath du popup
    )
    print("Popup visible.")

    # Localiser le bouton 'Browser' à l'intérieur du popup
    browser_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, '/html/body/div[1]/div[2]//button[@aria-label="Browser"]'))  # XPath du bouton 'Browser'
    )

    # Utiliser ActionChains pour s'assurer que le bouton est interactif
    action = ActionChains(driver)
    action.move_to_element(browser_button).click().perform()
    print("Bouton 'Browser' cliqué avec succès.")

    # Attendre que la boîte de dialogue de téléchargement soit ouverte
    file_input = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.XPATH, '//*[@type="file"]'))  # XPath de l'élément de saisie de fichier
    )
    
    # Upload de l'image
    file_path = "./01.png"
    file_input.send_keys(file_path)
    print(f"Image téléchargée avec succès : {file_path}")

    # Soumettre le formulaire
    submit_button = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, '/html/body/div[1]/div[2]/div[3]/div[2]/div[2]/div/div/div/div[1]/div/div[2]/div/button'))
    )
    submit_button.click()
    print("Formulaire soumis avec succès.")

except Exception as e:
    print(f"Erreur: {e}")
finally:
    driver.quit()

thanks you for your help

Solid color background is applying with some transparency

i have a backgroundcolor set white in “#headerPop” but it is having some transparency even i change the color to black i still see elements beneath it

by the way this ui is made for mobiles so it will be goofy to see if it runs in desktop so i strongly suggest to view it phone mode in web developer tools

function getBID(elementName) {
  return document.getElementById(elementName);
}

const driverImg = getBID("driverImg");
const namee = getBID("name");
const logoBox = getBID("logoBox");
const namedisc = getBID("namedisc");
const start = getBID("start");
const display = getBID("display");
const headerHamburger = getBID("headerHamburger");
const headerLogo = getBID("headerLogo");
const header = getBID("header");
const headerPopLi = document.querySelectorAll("#headerPop ul li");
const headerPop = getBID("headerPop");

driverImg.onload = function () {
  namee.style.fontSize = logoBox.offsetHeight / 2 + "px";
  driverImg.style.left = namee.offsetWidth + "px";
  logoBox.style.width = namee.offsetWidth + driverImg.offsetWidth + "px";
  logoBox.style.left = (start.offsetWidth - logoBox.offsetWidth) / 2 + "px";
  namedisc.style.width = namee.offsetWidth + "px";
  namedisc.style.top = namee.offsetHeight + "px";
};
function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function run() {
  await wait(3000);
  start.style.visibility = "hidden";
  display.style.visibility = "visible";
  headerHamburger.style.height = headerLogo.offsetHeight + "px";
  headerHamburger.style.top =
    (header.offsetHeight - headerHamburger.offsetHeight) / 2 + "px";
  const liHeight = headerPop.offsetHeight / 5;
  headerHamburger.onclick = function () {
    const d1 = window.getComputedStyle(headerPop).visibility;
    if (d1 == "visible") {
      headerPop.style.visibility = "hidden";
    } else {
      headerPop.style.visibility = "visible";
    }
  };
  headerPopLi.forEach((li) => {
    li.addEventListener("click", () => {});
    li.style.height = liHeight + "px";
    li.style.fontSize = liHeight / 2 + "px";
    if (li.innerHTML == "Home") {
      li.style.borderTop = "1px solid black";
    }
  });
}

run();
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
#start {
  background-color: rgba(72, 188, 132, 0.425);
  height: 100%;
  width: 100%;
  overflow: hidden;
}
#logoBox {
  position: absolute;
  height: 10%;
  top: 30%;
}
#name {
  position: absolute;
  color: rgb(72, 188, 132);
  margin: 0;
  top: 10%;
}
#driverImg {
  position: absolute;
  height: 80%;
  top: 10%;
}
#namedisc {
  font-family: "Courier New", Courier, monospace;
  position: absolute;
  color: rgb(72, 188, 132);
  text-align: center;
}

#display {
  position: absolute;
  top: 0;
  left: 0;
  margin: 0;
  height: 100%;
  width: 100%;
  visibility: hidden;
}

#header {
  position: fixed;
  left: 0;
  top: 0;
  height: 10vh;
  width: 100%;
  background-color: rgba(72, 188, 132, 0.425);
}

#headerLogo {
  position: absolute;
  height: 70%;
  top: 30%;
  left: 15%;
}

#headerHamburger {
  position: absolute;
  right: 15%;
  filter: invert(1);
}

#headerPop {
  position: fixed;
  top: 10%;
  left: 0;
  height: 27%;
  width: 100%;
  text-align: center;
  background-color: white;
  visibility: hidden;
}

#headerPop ul {
  margin: 0;
  padding: 0;
}

#headerPop ul li {
  font-family: "Courier New", Courier, monospace;
  font-weight: 800;
  color: black;
  align-content: center;
  border-bottom: 1px solid black;
}

#body {
  position: relative;
  top: 10vh;
  width: 100vw;
}

#home {
  position: relative;
  height: 80vh;
  width: 100vw;
}

#services {
  position: relative;
  height: 80vh;
  width: 100vw;
}

#caption {
  position: relative;
  margin: 3vh auto;
  width: 80vw;
  font-family: "Courier New", Courier, monospace;
  color: rgb(72, 188, 132);
  text-align: center;
  font-size: 2vh;
  font-weight: 800;
}

#home h1 {
  position: relative;
  margin: 3vh auto;
  width: 80vw;
  color: rgb(43, 43, 43);
  text-align: center;
  font-size: 3vh;
}
<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="./mobile.css" />
  </head>
  <body>
    <div id="start">
      <div id="logoBox">
        <h1 id="name">Carnex</h1>
        <img src="./resources/driver.png" alt="driver icon" id="driverImg" />
        <h1 id="namedisc">Book Drivers</h1>
      </div>
    </div>
    <div id="display">
      <div id="header">
        <h1 id="headerLogo">LOGO HERE</h1>
        <img src="./resources/hamburger.png" alt="hamburger icon" id="headerHamburger" />
      </div>
      <div id="headerPop">
        <ul>
          <li>Home</li>
          <li>Services</li>
          <li>become a driver</li>
          <li>About Us</li>
          <li>Contact US</li>
        </ul>
      </div>
      <div id="body">
        <section id="home">
          <div id="caption">Hire drivers with ease</div>
          <h1>Reliable Drivers for Your Car, Anytime, Anywhere.</h1>
        </section>
        <section id="services"></section>
        <section id="aboutUs"></section>
        <section id="contactUs"></section>
      </div>
    </div>
    <script src="./mobile.js"></script>
  </body>
</html>

Delayed function execution of setInterval

I’m trying to delay the execution of the setInterval function, which is set at 2000.
Ideally, I would like the function to be executed after 10000 at every refresh of the page + after each hide on click function (that makes all the created divs disappear by clicking anywhere on the page and makes the function starts all over again).

Here’s how it looks like without any delay:

var list = ["ar1",
            "ar2",
            "ar3",
            "ar4",
            "ar5",
            "ar6",
            "ar7"];

var t = setInterval(createCat, 2000);

function createCat() {
  var cat = $("<div>");
  cat.addClass("ar1");

  var index = Math.floor(Math.random() * list.length);
  var catClass = list[ index ];

  var cat = $("<div>");
  cat.addClass(catClass);

var x = Math.random() * $(window).width();
var y = Math.random() * $(window).height();

cat.css("left",x);
cat.css("top",y);

// by clicking anywhere on the page the function disappears and starts all over again

$("body").click(function() {
  cat.hide();
});

  $("body").append(cat);

}

I tried delaying setInterval with the setTimeout function then clearing it out to make way for the setInterval function but it was unsuccessful and I can’t figure out why:

var timeout = setTimeout(function createCat(){

    timeout = setTimeout(createCat, 10000);
}, 10000);

clearTimeout(timeout);

I have also tried the following but it did not work either:

let i = 1;
function createCat(value){
  setTimeout(function(){
    console.log("received value is : ",value)
  },8000);
}

how to detect if cursor text selection is visible on mobile browser?

I’m trying to add update the jQuery Terminal cursor position when text selection cursor is visible. This is my code:

function update_mobile_cursor() {
    if (is_mobile) {
        var selection = document.getSelection();
        console.log(selection);
        if (selection.anchorNode === selection.focusNode) {
            var range = selection.getRangeAt(0);
            console.log(range);
            self.position(range.endOffset);
        }
    }
}

But both selection and range exists even when the selection cursor is not visible. When I type something, the endOffset points into the last typed character.

Is there a way to detect the visibility of the selection cursor on a mobile Browser?

I have a testing webpage: https://terminal.jcubic.pl/android.php when You press backspace it jumps to the beginning.

NOTE: that the function don’t trigger when text selection is changed, I’ve asked about it here: Listen to cursor change on mobile browser

I test this with Chromium based Brave.

Create top-level domain cookie inside subdomain not working (Express behind IIS rewrite)

I want to set a top-level domain cookie (i.e. domain:”.example.com”) from sub.example.com.

I know I have to set the “domain” attribute like so:

const app = express();
app.get("/set", (req, res) => {
  res.cookie("name", "express", { domain: '.example.com', path:'/', httpOnly:true, secure:true, sameSite:'lax' }).send("cookie sety");
});

But when I access the page from sub.example.com (Browser, Postman, …) it always says “domain: .sub.example.com”.

The website is running on Windows-Server, IIS 10, Node 20.

IIS is configured for bindings: sub.example.com, example.com (both 80 and 443).

Rewrite-Configuration:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>                                       
                <rule name="ReverseProxyInboundRule1" patternSyntax="ECMAScript" stopProcessing="true">
                    <match url="(.*)" />
                    <action type="Rewrite" url="http://localhost:3528/{R:1}" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer> 
</configuration>

I have no idea, at what point the domain get’s “rewritten”. I checked the web, stack-exchange and copilot. Couldn’t find any clue.

Insane amount of RAM usage with BullMQ + fetch

I have a small app that runs several requests(node-fetch) with in a queue with bullMQ.

And i have 3 worker threads (if i dont use this main event loop gets blocked and my whole app freezes.) (This is an another issue why main loop gets blocked with a few fetch requests ?)

queue A , queue B and queue C

all queues have same configuration

new Queue('a-queue', {
connection: {
    url: process.env.REDIS_URL,
    enableReadyCheck: true,
},
defaultJobOptions: {
    attempts: 5,
    removeOnComplete: true,
    removeOnFail: false,
},

worker for the queue (a,b,c all same):

const processor = pathToFileURL(__dirname + '/a_processor.js')
new Worker('a-queue', processor, {
    connection: {
        url: process.env.REDIS_URL,
        enableReadyCheck: true,
    },
    concurrency: 1,
    useWorkerThreads: true,
})

And a_processor.js is sending some requests with fetch and returns the values.

Also i have a setting for the global concurrency limit in index.js (start of the express app):

await queue.setGlobalConcurrency(5)

Upto this points it seems like it works as i expected (bullmq dashboard blue ones are active yellow ones are waiting):
enter image description here

But after like a minute redis instance is crashing due high memory consumption:

enter image description here

Memory usage is like skyrocket when i run this app.And what is doing is just sending fetch requests (10-15 in paralel) and these requests are not like responsing mbs of data its only few kb of json each time.

Here’s the request method:

const headerGenerator = new HeaderGenerator()
const headers = headerGenerator.getHeaders()

const response = await fetch(`${domain}`, {
    headers: headers,
    agent: agentDcIp,
    signal: AbortSignal.timeout(15000) as any,
})

const body = await response.text()

return {
    body: body,
    ok: response.ok,
    status: response.status,
}

Any idea why this is happening and how to prevent it.

Set attribute in vue to html content without it being unescaped

I am using vue3, and would like to be able to render html in (bootstrap 5.3) tooltips.

However, vue3 escapes all html in v-bind attributes. Is it possible to disable this?

in template:

<td :title="mkTooltip(row, key)">some data</td>

if mkTooltip returns some <b>html</b>, this gets escaped. Is there any way to disable this behavior? I would really like to call a function to generate tooltips for table cells.

Alternative for navigator.getBattery() of battery api?

What should I use instead of navigator.getBattery(), as it is not working?

I am working on a chrome extension and with this what I want to do is –

function toggleBatterySaver(enable) {
  if (enable) {
      navigator.getBattery().then(battery => {
          if (battery.level < 0.2) {
              chrome.power.requestKeepAwake("system");
          }
      });
  } else {
      chrome.power.releaseKeepAwake();
  }
}

It is throwing an error:
navigator.getBattery() is not a function.

How to add dev-only dependencies in Deno?

In Node.js, we can use npm install -D to install a dev-only dependency, adding into package.json > devDependencies. When my package is published and used as a dependency, dev-only dependencies won’t be installed.

But in deno.json, there is only imports, no devImports. According to Deno v2 RC announcement, we can use deno add --dev. But this only add contents to deno.lock, not adding anything to deno.json. I tried deno add --dev eslint (not migrating Deno Lint yet), but it complained eslint: command not found.

I found denoland/deno#26865, but no answers are there.

Bootstrap v3.4.1 popover positioning fails

Im just using bootstrap v3.4.1 because of the popover and tooltip i’m not using anything else.

    <a href="#" class="edit"
                                        data-toggle="popover"
                                        data-icon="{{ category.icon }}"
                                        data-placement="top"
                                        data-content='
                                        <input type="text" name="hej" value="{{ category.title }}">
 
        <div class="SelectContainer"></div><input type="submit" name="EditCat" value="Redigera Kategori">
                                        '><i class="fa-regular fa-pen-to-square"></i></a>

This one works perfectly fine. It opens my popover and show the html everything works this far.

enter image description here

This is the three rows i have to work with right now.

Lets open the first one [Test]: enter image description here

Like you see the popover, goes to god knows where.

But if i open the last one and then the first and then the first one more time, this happens:

enter image description here

Its not right, but its better then the first try.

Anyone got any tips and ideas how i can solve this problem?

The only javascript i have right now is this:

$("[data-toggle=popover]").popover({html: "true", sanitize: false});

React Higher-Order Components, dose not pass props to Wrapped component when Higher-Order Components state changed

console inside MyComponent print value for the first time but value dose not show on view.

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

const withLoading = (WrappedComponent) => {

    class WithLoading extends React.Component {
        constructor(props) {
            super(props)
            this.state = { loading: true };
        }

        componentDidMount() {
            setTimeout(() => {
                console.log("setTimeout")
                this.state = { loading: false };
            }, 5000)
        }

        render() {
            console.log("render", this.state.loading)
            return <WrappedComponent {...this.props} loading={this.state.loading} />;
        }

    }

    WithLoading.displayName = `withLoading(${WrappedComponent.displayName || WrappedComponent.name})`;

    return WithLoading;

}


function MyComponent({ loading }) {
    console.log("MyComponent loading", loading)
    return (<p>is loading:{loading}</p>)
}


const hoc = withLoading(MyComponent);

export default hoc

How to refer to a dictionary item of data property from el-table data in Vue

I’m using el-table in Vue3 project. I have 3 questions about the code below. The first is :data=”MyDatalist[row.id]” didn’t take effect. row.id do exist in somelist_1. I don’t know how to write this binding correctly. The expand el-table-column can’t work.

<el-table :data="somelist_1" :row-class-name="tableRowClassName">
      <el-table-column type="expand" @row-click="refresh(row)">
            <template #default="props">
              <div>
                <el-table :data="MyDatalist[row.id]" :row-class-name="tableRowClassName">
                  <el-table-column label="ele1" prop="id1_ele1" />
                  <el-table-column label="ele2" prop="id1_ele2" />                                  
                </el-table>
              </div>
            </template>
      </el-table-column>
      ..............other el-table-column
</el-table>

Data property MyDatalist like below. It’s a dictionary of list.

export default {         
    data() {
        return {
              MyDatalist:{
               "id1":[id1_ele1, id1_ele2], 
               "id2":[id2_ele1, id2_ele2]}
            }
          },  
        .....
        }

When I tried a simple form of MyDatalist like:

 MyDatalist:[id1_ele1, id1_ele2]

and

:data="MyDatalist"

respectively, it displayed well. So I think :data=”MyDatalist[row.id]” is not correct.

The second question is I want to use row-class-name=”tableRowClassName” to set different color in diferent row. It’s exactly copied from this.

The third question is @row-click=”refresh(row)” can’t trigger. I tried other event like @cell-mouse-enter seem didn’t trigger either.

For the 2nd and 3rd question, is there any way for me to root cause?