Combination Sum using recursion

I am new to data structure and I am trying this problem Combination Sum

I know this might be super basic stuff but I am learning recursion and not want to learn where I am doing wrong so that I can correct my thinking process.

Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.

The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the
frequency
of at least one of the chosen numbers is different.

The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.

var combinationSum = function(candidates, target) {
    if(candidates.length == 0) return [[]]
    if(target == 0) return [[]]
    if(target<0) return []
    result = []
    for(let i=0; i<candidates.length; i++){
        let arr = [...candidates]
        // take the element
        let result1 = combinationSum([...candidates], target-candidates[i])
        // ignore the element
        result1.forEach((e)=>{e.push(candidates[i])})
        let result2 = combinationSum(arr.slice(0, i).concat(arr.slice(i + 1)), target)
        result.push(...result1, ...result2)
    }
    return result
};

Right now, I am now working toward finding combination and not unique,
I am not able to comprehend why this is not working.

enter image description here

How to make images replace each other with a button?

So, I’m trying to develop a sort of visual novel, and I’m trying to make a code to replace other images when a specific image appears, (for example, if “happy” is onscreen i want “sad” to be hidden so the pictures don’t overlap eachother)
Here’s my code:

<style>
section {
  display: none;
}

.d-block {
  display: block;
}
</style>
<section class="d-block">Horace</section>
<section>Ursa</section>
<section><img id=sad src=https://png.pngtree.com/png-clipart/20220716/ourmid/pngtree-banana-yellow-fruit-banana-skewers-png-image_5944324.png></section>
<section><img id=neutral src=https://www.shutterstock.com/image-photo/banana-bunch-five-600nw-1057197824.jpg></section>
<section><img id=happy src=https://t4.ftcdn.net/jpg/05/65/93/25/360_F_565932566_6bll77MbikvLen4pPoLVvlrqmvKTZ7Nw.jpg></section>
<section>Thus</section>

<button>Next</button>
<script>
document.addEventListener("DOMContentLoaded", () => {
const TextShower = document.querySelector('button');
TextShower.addEventListener('click', function() {
  let hidden_section = document.querySelector('section:not(.d-block)');
  if (hidden_section != null) {
    hidden_section.classList.add('d-block');
  } else {
    TextShower.disabled = true;
    }
  });
  const Happy = document.getElementById("happy")
  if (happy.hasAttribute("d-block")) {
  document.getElementById("sad","neutral").removeAttribute("d-block")
        }
  });
    </script>
  const Happy = document.getElementById("happy")
  if (happy.hasAttribute("d-block")) {
  document.getElementById("sad","neutral").removeAttribute("d-block")
        }
  });

this is the if statement i tried to create to replace the portraits. did not work

Why i have to do “double submit” in my search form?

I’m currently working on a form that allows users to search for bills by their description, ID, or price. However, I’ve encountered an issue: after the initial search, I have to submit the form twice to get the desired results.

getBillsByIdDescriptionPrice(formState.search)
is a function that brings from de DB all the bills that match with the content from the input formState.search

The first search usually works fine. However, upon the second search, after submitting the query, it initially returns all the data instead of the specific result I’m looking for. Only after submitting the form again does it finally bring up the correct data.

Doing console logs, I noticed that during the second search, it briefly returns the correct result. However, shortly after, it reverts to displaying all the data, requiring an additional submission.

I hope someone can help me. Thanks a lot!

React with Typescript and Material UI

Link to the repo: https://github.com/guidomora/facturacion-front/blob/main/src/billing/components/BillingSearch.tsx

Here you can check the code:

 const { bills, getBillsByIdDescriptionPrice } = useContext(DataContext)
  const { formState, inputChange, search } = useFormSearch({ search: '' })

  const handleSubmit =  (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    if (formState.search === '') return
    getBillsByIdDescriptionPrice(formState.search)
    
  }

  const submitButton = () => {
    if (formState.search === '') return
    getBillsByIdDescriptionPrice(formState.search)
  }


{/* displayed data */}
      {(bills.length === 0) ? <Typography variant='h5' 
      sx={{ textAlign: 'center', color: 'black', fontWeight: 600, mt: 35 }}>
        No bills found...
      </Typography> :
        <BillingTable bills={bills} />
      }

selenium cannot execute webpack related code?

I want to use selenium to execute this code to get the token, but when I execute it like this

”driver.execute_script(‘(webpackChunkdiscord_app.push([[”],{},e=>{m=[];for(let c in e.c)m.push(e.c[c])}]),m).find(m=>m?.exports?.default?.getToken!==void 0).exports.default.getToken()’)”

He reported an error saying m is not defined.

But if you execute this directly in the browser’s developer console

‘(webpackChunkdiscord_app.push([[”],{},e=>{m=[];for(let c in e.c)m.push(e.c[ c])}]),m).find(m=>m?.exports?.default?.getToken!==void 0).exports.default.getToken()’

The code works fine

I want to execut this code use selenium ,please, who can help me!!

App restarts when I make an api call through firebase functions

I’m fairly new to google firebase functions.

For some reason when my frontend makes an api call to the backend, the app looks like it restarts everything. Im not sure why. The endpoints are correct. I get a console message from the backend. Here is my code for reference

const express = require("express");
const functions = require("firebase-functions");
require("dotenv").config();

const cors = require("cors");
const axios = require("axios");
const baseURL = "https://api.pledge.to/v1/organizations";
const myHeader = {
  "Authorization": `Bearer ${process.env.API_KEY}`,
};

// Instantiate the app here
const app = express();
app.use(cors());

app.get("/", (req, res) => {
  console.log("Hello World");
  res.status(200).send("baus");
});

app.get("/organizations", async (req, res) => {
  console.log("Making API call");
  console.log(req.query.cause_id);
  try {
    // eslint-disable-next-line max-len
    const response = await axios.get(baseURL+"?"+`cause_id=${req.query.cause_id}`, {
      headers: myHeader,
    });
    const data = await response.data;
    res.status(200).send(data);
    // res.json(data);
  } catch (error) {
    console.error(error);
    res.status(500).json({error: "Internal Server Error"});
  }
});

app.get("/searchOrg", async (req, res)=> {
  console.log("Search query >>>", req.query.q);
  try {
    const response = await axios.get(baseURL+"?"+`q=${req.query.q}`, {
      headers: myHeader,
    });
    const data = await response.data;
    res.status(200).send(data);
  } catch (error) {
    console.error(error);
    res.status(500).json({error: "Internal Server Error"});
  }
});

app.get("/next", async (req, res)=>{
  // console.log("Im in the next endpoint");
  // Using template literals
  let queryString = " ";
  // eslint-disable-next-line guard-for-in
  for (const key in req.query) {
    queryString += `${key}=${req.query[key]}&`;
  }
  // Remove the trailing '&' if necessary
  queryString = queryString.slice(0, -1);

  try {
    const response = await axios.get(baseURL+"?"+`${queryString}`, {
      headers: myHeader,
    });
    const data = await response.data;
    res.status(200).send(data);
    // res.json(data);
  } catch (error) {
    console.error(error);
    res.status(500).json({error: "Internal Server Error"});
  }
});

// Listen command
exports.api = functions.https.onRequest(app);

I tested it using firebase emulators:start. I made sure to update the endpoints on my frontend so that it sends the request to the right server.

I checked the network tab when I make the api call and it says I am getting a 101 status code and a type websocket Also for some reason the amount of time it is taking to process the request is pending

Any ideas why this could be happening? Could it be that I configured the hosting wrong for my frontend. Any help is appreciated. Thanks in advance. Happy coding!

ascii art using letter in javascript [duplicate]

Create a program that translates the input (any combination of X, Y, or Z) to their low-resolution
ascii art-like representation (use letter ‘O’ as the character to draw the letters).

Input Parameters:

  • letters – any combination of the letters X, Y, and Z (example: XYZ, ZXY, ZZXXXYYYYY)
  • size – block size of each letter; odd numbers, greater than or equal to 3 (example: 3, 5, 7, 9… etc)
  • direction – horizontal or vertical

more for a beginner coding and i could not find any refence other reference ive found is make image into ascii art and it would be helpful if it could be explained every part.thank you

Playwright headless tests are slower than headful tests

Playwright headless tests are supposed to be faster than the headful tests. My headful tests are taking ~17sec and headless ones are taking ~1min.

Looking into the problem, I saw that in headless mode, the chrome might be running without gpu acceleration and I should force enable gpu acceleration through flags like

--use-gl="swiftshader"
--enable-unsafe-webgpu
--ignore-gpu-blacklist

I tried all of them, none of them seems to work. Do someone know the solution? Am I on the right track?

Implementing JS code to change CSS elements

This is a code excerpt from my program, and I would like to know how o change this in order to adjust the top and left values by using JS variables in the tag which is above it in order to randomize its position in a 9×9 grid. I am making a game out of this.

<style>
            #backgroundColor {
                background-color: rgba(211, 233, 254, 0.779);
                margin-top: 5%;
            }

            #content {
                text-align: center;
                width: 100%;
            }
/* I want to change the top and left values to correspond with JS variables. */
            h1 {
                position: absolute;
                top: 1.75%;
                /* Alter values in a grid by 10.75. Make a varible in <script>, go from 1.75-87.75 */
                left: 27.25%;
                /* Alter values in a grid by 5.5. Make a variable in <script>, go from 27.25-71.25 */
                color: rgb(47, 0, 0)
            }

            div {
                position: relative;
                text-align: center;
            }

            image {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
            
            .center {
                display: block;
                margin-left: auto;
                margin-right: auto;
                width: 50%;
            }

            .numbers {
                font-family: monospace;
                font-size: xx-large;
                font-weight: normal;
                font: Menlo;
            }

            .title {
                font-family: monospace;
                font-style: italic;
                font-weight: lighter;
                font-size: xx-large;
            }

            .subtitle {
                font-family: monospace;
                font: Courier;
                font-size: large;
                font-weight: lighter;
            }
        </style>

I tried using the following JS Code:

<script type="text/javascript">
    "use strict";
            function getNumCoords(ifX, ifY) {
                const numGridMax = 8;
                var yPos = Math.floor(Math.random()*numGridMax);
                var xPos = Math.floor(Math.random()*numGridMax);
                if (ifX === 1) {
                    return (xPos*5.5)+27.25;
                }
                if (ifX === 1) {
                    return (yPos*10.75)+1.75;
                }
            }
            var outputX = getNumCoords(1, 0) + "%";
            var outputY = getNumCoords(0, 1) + "%";
            var number = document.getElementById("random");
    </script>

In order to change the CSS Elements.

Three.js smooth rotation in character control

Code :

I’ve written a code that adds character movement to an Object3D in Three.js
WASD respectively sets the move forward , left , backward , right variables

  • constants :
walkinbgSpeed = 5;
rotationSpeed = Math.PI ;
  • updateRAF : passed deltatime in seconds , updates movement position then calls rotate
 updateRAF(dts) {
        if (this.moveForward) {
            this.model.position.z += this.walkinbgSpeed * dts;
            this.rotate(dts, 0)
        }
        if (this.moveBackward) {
            this.model.position.z -= this.walkinbgSpeed * dts;
            this.rotate(dts, Math.PI)
        }
        if (this.moveLeft) {
            this.model.position.x += this.walkinbgSpeed * dts;
            this.rotate(dts, Math.PI/2)
        }
        if (this.moveRight) {
            this.model.position.x -= this.walkinbgSpeed * dts;
            this.rotate(dts, -Math.PI/2)
        }

    }
  • rotate : smoothly rotates an Object3D by gradually increments the interpolation factor t + using the quaternion slep function directly on the model’s quaternion
 rotate(dts, angle) {
        let t = 0;

        const animateRotation = () => {
            t += this.rotationSpeed * dts;

            if (t >= 1) {
                t = 1; // Clamp t to ensure it doesn't exceed 1
            }

            const qb = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), angle);

            this.model.quaternion.slerp(qb, t);

            if (t < 1) {
                requestAnimationFrame(animateRotation); // Continue animation if not finished
            }
        };

        requestAnimationFrame(animateRotation);
    }

Problem :

  • Pressing one direction at a time rotates the model smoothly as intended

  • Combining two direction buttons starts with a smooth rotation , ends up insta-rotating the model in the last held button direction with no smoothness applied

Note :

  • If needed full code can be provided

  • Any help is greatly appreciated

Is it possible to use WFS.writeTransaction on the server side of a node application

I have a node application that traces a route on a road network and is returned in a JSON format.
I have created on OpenLayers feature from the JSON object and I want to save this feature into an OpenLayers v9 layer using WFS-T.
This processing is all occurring on the server side. There is no map interface.
When I call the WFS.writeTransaction() function I get TypeError: Cannot read properties of undefined (reading ‘createElementNS’)

I have done this successfully previously, but It has always been on the client side and with a map interface.

The code below is from the ol/xml.js file and seems to indicate there should be a document available

export function createElementNS(namespaceURI, qualifiedName) {
   return getDocument().createElementNS(namespaceURI, qualifiedName);
}

My question is is it possible to create a document on the server side so this writeTransaction method will succeed?

Getting dropped file path in Electron

In electron, there’s a feature where you can drag out an element and drop it on your desktop as seen in this example. I’ve searched all over the place for a possible example or GitHub issue I can refrence but the closest I got to a working solution was to simply drag out a filler file which then the system searches for and provides me with a valid path.

I’ve noticed this question which seems to have gone unanswered unfortunately (and the Electron team also seems unintrested in adding onto the startDrag function anytime soon)

As mentioned earlier, I’ve tried saving this temporary dummy file which then gets searched for and the respective path is given. Not very ideal for large systems just for a simple feature addition on the Electron teams end which is kind of disappointing. I’d also like to refrence this GitHub issue which I feel was closed down by the Electron team in an effort to effectively ditch their community.

Anyway, I apologize for the unesscary blabber and any efforts you will put into helping solve this issue would be highly appreciated.

Thanks.

Formulas not working until clicking “Enable Editing”

I’m using exceljs for my project to manipulate an excel file in my React app. It works as expected but when users download the file, the formulas in the file does not calculate until users click on “Enable Editing”. This is a problem because our users will mostly use ipad, and when they download from the ipad, it doesn’t even show the option to “Enable Editing”. Is there a way to recalculate the worksheet before downloading?
Here is the code:

const ExcelJS = require("exceljs");

const handlePrintExcel = async () => {
        try {
            const response = await fetch("/test.xlsx");
            if (!response.ok) {
                console.log("Network response error");
            }
            const blob = await response.blob();
            // Read the Blob using ExcelJS
            const workbook = new ExcelJS.Workbook();
            workbook.xlsx
                .load(blob)
                .then(async (wb) => {
                    const worksheet = workbook.getWorksheet("Sheet1");

                    const cell_f8 = worksheet.getCell("A1");
                    cell_f8.value = 123;
                    const cell_a2 = worksheet.getCell("A2");
                    cell_a2.value = 123;                    

                    workbook.properties.readOnlyRecommended = false;
                    workbook.properties.date1904 = false;

                    workbook.security = {
                        lockWindows: false,
                        lockStructure: false,
                        workbookPassword: null,
                        workbookAlgorithmName: null,
                        workbookHashValue: null,
                    };

                    workbook.calcProperties.fullCalcOnLoad = true;

                    // Write the changes to a buffer
                    const buffer = await workbook.xlsx.writeBuffer();
                    return buffer;
                })
                .then((data) => {
                    // Create a new Blob with the updated data
                    const updatedBlob = new Blob([data], {
                        type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                    });
                    // Create a URL for the Blob
                    const url = window.URL.createObjectURL(updatedBlob);
                    // Create an anchor element to trigger the download
                    const anchor = document.createElement("a");
                    anchor.href = url;
                    anchor.download = `Test.xlsx`;
                    // Trigger the download
                    anchor.click();
                    // Revoke the URL to release resources
                    window.URL.revokeObjectURL(url);
                })
                .catch((error) => {
                    console.error("Error processing Excel file: ", error);
                });
        } catch (error) {
            console.error("Error converting Excel file into Blob:", error);
        }
    };

Can’t execute ./gradlew clean

I’m currently working on my react native project and wanted to build apk to send my friend. I did everything according to this instruction https://reactnative.dev/docs/signed-apk-android and some video on youtube.

Everything worked fine till the moment when I tried to execute ./gradlew clean and then another command starting with ./gradlew. It just starts downloading it from https://services.gradle.org/distributions/gradle-8.3-all.zip and then fails.

I tried downloading it manually and everything seemed good, gradle -v command works fine from any console, but ./gradlew command still do the same.

I would be really grateful if someone could help me

chrome.downloads.download on MS Edge: windows update this week added a bug. Work-around?

I’m working on an extension for MS Edge (Version 122.0.2365.80) running on Win10 pro. The extension has been working properly, but not any more.
I’m using chrome.downloads.download in javascript and what it used to do is invoke the SaveAs dialog box pointing to the last saved-to folder. Now it points to the browser’s default directory.
Is anyone else seeing this?
Is there an option in chrome.downloads.download to point the SaveAs in the right direction?
Here’s the code for the background.js:

chrome.runtime.onInstalled.addListener(function() {
  console.log('Extension installed / updated');
});

chrome.runtime.onMessage.addListener(function (request, sender) {
  if (request.type === 'popupMessage') {
    // Access parameters from the content script
  var receivedParams = request.data;

  // Do something with the parameters
    console.log(receivedParams);
chrome.downloads.download({
       url: receivedParams,
       filename: 'desired_filename.ext',
       saveAs: true
    }, function(downloadId) {
       console.log('Download initiated with ID:', downloadId);
    });
   }
 });

Thanks in advance for any pointers you can provide.

When I call the background.js, I expect it to bring up the SaveAs dialog box pointing at the last-saved-to-directory.
Instead, the code (unchanged) now brings up the SaveAs dialog box pointing to the browser’s default directory.