Combining two arrays of objects to find uniques (not working – using filter, splice, Set, and concat) [duplicate]

Objective: Need to find a uniqueArray of objects from two arrays of objects. The uniqueArray needs to accomodate all {key:value} changes on the objects.

While attempting to test equality, keep getting false positives.

Starting Point: Two Arrays containing database objects:

const old_workflow = [{a:1, b:2},{a:3,b:4}]
const new_workflow = [{a:1, b:2},{a:3,b:5}]

Ideal Result:
The uniqueArray must result in 1 copy of each unique objects from both arrays

const uniqueArray = [{a:1, b:2},{a:3,b:4},{a:3,b:5}] 

Approaches Attempted: I tried many, but none worked, here are two examples

#1
    let concatArray = new_workflow.concat(old_workflow);
    let uniqueArray = [...new Set(concatArray)];

#1 Issue: I thought this was the purpose of Set(), however, the uniqueArray contains duplicates when reviewed visually

#2
     const arrayUnique = (array: any) => {
        let a = array.concat();
        for (var i = 0; i < a.length; ++i) {
          for (var j = i + 1; j < a.length; ++j) {
            if (a[i] === a[j]) a.splice(j--, 1);
          }
        }
    
        return a;
      };
    
    const uniqueArray = arrayUnique(new_workflow.concat(old_workflow));

#2 Issue: this uniqueArray also contains objects that have identical key:value pairs

I think the issue is that the objects are truly unique from each other, regardless of the properties… so…

How can I prove or disprove object equality? Must I go through each key?

How to prevent escaping in Flask

I have a Flask application and I have a script in the index.html template:

<script>
    // Handles displaying bay modals
    const bay_modal = document.getElementById("bay_modal");
    const modal_title = document.getElementById("bay_modal_title")
    const modal_buttons = document.getElementsByClassName("bay_modal_button");
    const bay_modal_quit = document.getElementById("bay_modal_quit")
    const bay_modal_from_selection = document.getElementById("from")
    const bay_modal_to_selection = document.getElementById("to")

    // Close the modal when the exit button is clicked
    bay_modal_quit.addEventListener('click', function() {
        bay_modal.style = "visibility: hidden;"
    })

    // Add event listeners to each bay button to open the modal
    for (let i = 0; i < modal_buttons.length; i++) {
        modal_buttons[i].addEventListener('click', async function() {
            // Get data about the bay
            bay_data = JSON.parse(
                fetch("{{ url_for('route_scheduler')}}", {body: JSON.stringify(
                    { request_type: "GET_HYDRATE_DATA", bay_identifier: modal_buttons[i].id }
            )}));
            
            const scheduleFrom = {};
            const scheduleTo = {};

            bay_data.schedule.forEach(sch => {
                scheduleFrom[sch[0]] = true;
                scheduleTo[sch[1]] = true;
            });

            for (let j = 0; j < 25; j++) {
                if (scheduleFromDict[j]) {
                    bay_modal_from_selection[j].style = "background: red;";
                };
                if (scheduleToDict[j]) {
                    bay_modal_to_selection[j].style = "background: red;";
                };
            };

            modal_title.innerText = modal_buttons[i].name;
            bay_modal.style = "visibility: visible;";
        });
    };
</script>

I am getting a TemplateSyntaxError from Jinja2:

bay_modal_quit.addEventListener('click', function() {
    ^^^^^^^^^^^^^^^^^^^^^^^^^
jinja2.exceptions.TemplateSyntaxError: expected token ',', got 'click'

I am assuming this has something to do with the curly brackets in the script and flask HTML escaping. Note that the script itself uses an escape. I need to conditionally disable the escaping but still have it work in some sections. Is there a way to do that?

Incisor Masking

I’m trying to understand masking in Incisor and have run into an issue with a simple proof of concept. I have two white box GraphicObjects and want one to mask the other.

Here’s what I’ve done:
Created two white box GraphicObjects.
Moved the top box (-40, -40) relative to the bottom box.
Applied the makeMasker() function to the top box to make it the masker.
However, when I run the code, I only see the top white box. I expected the bottom left corner of the bottom box to be masked by the top one, but that’s not happening.

Here’s the relevant code:

class ProjectMain {

    init() {
        this.whiteBox = new GraphicObject( nc.graphicAssets.WhiteBox, nc.mainScene, "WhiteBox" );

        this.masker = new GraphicObject( nc.graphicAssets.WhiteBox, nc.mainScene, "Masker" );
        this.masker.position.x = -40;
        this.masker.position.y = -40;
        this.masker.makeMasker( nc.masks.MainMask );
    }
}

Can anyone point out what I might be missing or doing wrong with the masking process?

Parsing data in nodejs post results in empty json

I try to get the data from a post in a nodejs app. Iam confused because the result is always {}
I use the curl:

curl -X POST "http://localhost:3001/ingo2" -H "Content-Type: application/json" -d "{'macros':[], 'signals':[], 'constants':[], 'math':'true'}"

and use in my nodejs

const express = require('express');
var bodyParser = require('body-parser');
const app = express();
const port = 3001;
app.use(bodyParser.json({ type: 'application/*+json' }));

app.post('/ingo2', async function(req, res) {
    console.log(req.body);
    res.json({
        success: 'ok',
        fails: 0
    });
});

As written the result is {}. What I do wrong?
Iam on Windows and nodejs 20.12.2

Why would javsascript think a global variable is undefined

I’m writing a function to check if a table on the page is empty and insert rows with or without header as appropriate.

The code on the page itself is:

  <div id='uncoveredServices' style='display: none;'>

    <h2>Uncovered services</h2>

    <table id='tblServices'></table>
    <button type='button' id='btnSave' name='btnSave'>Save</button>

  </div>

  <div id='testDiv'>Test Text</div>

  <script src='js/addshortage.js'></script>
  <script src='js/diagramfunctions.js'></script>

The javascript is:

// Get the main table we will use to store all these shortages
var lstServices = document.getElementById('tblServices');

function transferService(btnSelected) {

  // If the table is empty, show the schedules div and add some headers
  if (lstServices.rows.length == 0) {

    document.getElementById('testDiv').innerHTML = 'Success';

  } else {
    document.getElementById('testDiv').innerHTML = 'Failure';
  }

}

The function is called from a button elsewhere on the page:

<button type="button" data-uid="G30291" data-from="2024-06-03" data-stp="P" data-tomorrow="0" data-terminates="LEEDS" onclick="transferService(this)">Select</button>

There are several of these, created by a search function. This allows the user to search for services, then pick the matching one.

Screenshot showing sample error

When I run this, it tells me that ‘lstServices’ is undefined. I’ve tried referencing other elements on the page which are declared in the same way and they work fine. I’ve even tried getting rid of the ‘display: none’ (I was desperate) but I can’t work out what’s going on!

Any help greatly appreciated.

Safari iOS 17 on iPad mini: Web content shifts down after toggling fullscreen mode on iPad

I’m optimizing a web app for iPad, and I’ve encountered an issue with the layout shifting after toggling fullscreen mode. Here’s what happens:

  1. I enable fullscreen mode on the app (either through a user interaction or programmatically).
  2. When I exit fullscreen mode, all
    of the content is shifted slightly downward, leaving an unaccounted-for gap at the top of the page.
  3. This gap is not visible in the DOM or CSS, and the content at the bottom of the page is
    pushed slightly off-screen.

This issue only seems to happen on iPad, in Safari. I was not able to reproduce on an iPhone or in alternate browsers on iOS. I’ve tried inspecting the DOM and viewport properties, but I can’t identify what’s causing the shift.

I cannot share my project, but this api demo produces the same issue on my iPad mini 6th gen: https://davidwalsh.name/demo/fullscreen.php

Here is my fullscreen code:

  requestFullscreen: async function (el, retryCount, retryDelay) {
      for (let i = 0; i <= retryCount - 1; i++) {
          let app = document.getElementById(el);
          if (app !== null) {
              if (isMobile.any()) {
                  try {
                      if (app.requestFullscreen) {
                          app.requestFullscreen();
                      } else if (app.mozRequestFullScreen) {
                          app.mozRequestFullScreen();
                      } else if (app.webkitRequestFullscreen) {
                          app.webkitRequestFullscreen();
                      } else if (app.msRequestFullscreen) {
                          app.msRequestFullscreen();
                      }
                      break;
                  } catch (error) {
                      console.error('Fullscreen not allowed: ', error.message);
                  }
              }

          }
          await new Promise(r => setTimeout(r, retryDelay));
      }
  }

  exitFullscreen: function () {
      try {
          if (document.exitFullscreen) {
              document.exitFullscreen();
          } else if (document.mozCancelFullScreen) {
              document.mozCancelFullScreen();
          } else if (document.webkitExitFullscreen) {
              document.webkitExitFullscreen();
          } else if (document.msExitFullscreen) {
              document.msExitFullscreen();
          }
      } catch (error) {
          console.error('Fullscreen not allowed: ', error.message);
      }
  }

I tried setting the apple-mobile-web-app-status-bar-style meta tag to black-translucent but that changed nothing.

Any insights or workarounds would be greatly appreciated!

Apply CSS Styling to a shadow root child element

I am trying to edit the right click menu from VS Code. I have found out that it’s in a so called “shadowRoot DOM”.

<div class="shadow-root-host">
    #shadow-root (open)
        <div class="context-view monaco-component monaco-menu-container bottom left fixed">
            <div class="monaco-scrollable-element">
                <!-- Content -->
            </div>
        </div>
    </div>
</div>

enter image description here

The div with the class “monaco-scrollable-element” is the one I’m trying to style.
I’ve tried styling the div “shadow-root-host” to see if it would inherit the styles from there but with no success.

I have no knowledge of JS. Only HTML and CSS.

How to turn URL into its Title in Bulk using App Script?

I need to export bulk data for real estate. There is an option to replce url with its Title but you have to do it one by one in google sheets. I was hoping to see if there is a way I can do it faster using App Script. Please help 🙁

I tried IMPORTXML but it has its limits.

I had tried this below, but it only gets the host website’s name.

function TitleFromURL(input) {
  var regex = /^(?:https?://)?(?:w{3}.)?([^.]+)/;
  var match = input.match(regex);
  return match ? match[1] : '';
}

Sample Data:

Column A Column B
https://www.realtor.ca/real-estate/27633475/720b-waverley-road-dartmouth-dartmouth For sale: 720B Waverley Road, Dartmouth, Nova Scotia B2X2G4 – 202426370

VueJS/Vue Router/Firebase – router.push() loads new page temporarily, then immediatley goes back to the Register page

I have a page that allows a user to register an account. Upon clicking submit, the user should be redirected to a Library page. However, what is happening is the Library page will flash on the screen for a second, then the Register page shows up again.

This is the RegisterPage.vue

import { ref } from 'vue'
import { getAuth, createUserWithEmailAndPassword } from 'firebase/auth'
import { useRouter } from 'vue-router'
const email = ref('')
const password = ref('')
const router = useRouter()

const register = () => {
  createUserWithEmailAndPassword(getAuth(), email.value, password.value)
    .then((data) => {
      console.log('Succesfully Registgered')
      router.push('/library', { shallow: true })
    })
    .catch((error) => {
      console.log(error.code)
      alert(error.message)
    })
}
const signInWithGoogle = () => {}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.5.1/vue.global.min.js"></script>
<template>
  <div>
    <form>
      <h1>Create and Account</h1>
      <input type="email" placeholder="[email protected]" v-model="email" required />
      <input type="password" placeholder="password" v-model="password" required />
      <button @click="register">Register</button>
      <button @click="signInWithGoogle">Sign in with Google</button>
    </form>
  </div>
</template>

Looking at the register() method, he user is successfully registered in the Firebase console, and the console.log successfully posts the message, so i know the method works. I just cant figure out why the Library page only loads for a second, then reverts back to the Register page.
index.ts

import HomePage from '@/views/HomePage.vue'
import LibraryPage from '@/views/LibraryPage.vue'
import RegisterPage from '@/views/RegisterPage.vue'
import SignInPage from '@/views/SignInPage.vue'
import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomePage,
    },
    {
      path: '/register',
      name: 'register',
      component: RegisterPage,
    },
    {
      path: '/sign-in',
      name: 'sign-in',
      component: SignInPage,
    },
    {
      path: '/library',
      name: 'library',
      component: LibraryPage,
    },
  ],
})

export default router
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.5.1/vue.global.min.js"></script>

Any help would be greatly appreciated.

leetcode give’s me the error Time limit exceeded

the problem

2070. Most Beautiful Item for Each Query

You are given a 2D integer array items where items[i] = [price i, beauty i] denotes the price and beauty of an item respectively.

You are also given a 0-indexed integer array queries. For each queries[j], you want to determine the maximum beauty of an item whose price is less than or equal to queries[j]. If no such item exists, then the answer to this query is 0.

Return an array answer of the same length as queries where answer[j] is the answer to the j.th query.

Example 1:

Input: items = [[1,2],[3,2],[2,4],[5,6],[3,5]], queries = [1,2,3,4,5,6]
Output: [2,4,5,5,6,6]
Explanation:

  • For queries[0]=1, [1,2] is the only item which has price <= 1. Hence, the answer for this query is 2.
  • For queries[1]=2, the items which can be considered are [1,2] and [2,4].
    The maximum beauty among them is 4.
  • For queries[2]=3 and queries[3]=4, the items which can be considered are [1,2], [3,2], [2,4], and [3,5].
    The maximum beauty among them is 5.
  • For queries[4]=5 and queries[5]=6, all items can be considered.
    Hence, the answer for them is the maximum beauty of all items, i.e., 6.
    Example 2:

Input: items = [[1,2],[1,2],[1,3],[1,4]], queries = [1]
Output: [4]
Explanation:
The price of every item is equal to 1, so we choose the item with the maximum beauty 4.

Note that multiple items can have the same price and/or beauty.

/*
 * @param {number[][]} items
 * @param {number[]} queries
 * @return {number[]}
 */
var maximumBeauty = function (items, queries) {

    const result = [];

    // Loop over each query
    for (let q = 0; q < queries.length; q++) {
        const queryPrice = queries[q];
        let maxBeauty = 0; // Initialize maxBeauty to 0 for each query

        // Loop over each item to find items with price <= queryPrice
        for (let i = 0; i < items.length; i++) {
            const price = items[i][0];
            const beauty = items[i][1];
            
            // Check if item's price is within the query's limit
            if (price <= queryPrice) {
                // Update maxBeauty if this item's beauty is greater
                maxBeauty = Math.max(maxBeauty, beauty);
            }
        }
        
        // After looping through all items, store the maxBeauty for this query
        result.push(maxBeauty);

    }

    return  result  // Should output: [2, 4, 5, 5, 6, 6]
};

script for checking a tick box and set value [closed]

I have a tick box in cell A7. I write this script but I think it is working correctly. The script should check the tick box if it is ticked then the scriot set the valllue (P) in the range A8:A15). If it is unticked then nothing happens in range (A8:A15). could you please help me to correct this script because I am beginner in google Apps script?

link to spreadsheet

function checkandsetvalue() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('EXAMPLE1');
  var valueA1 = sheet.getRange('A7').getValue();
  if (valueA1 = true) {
    sheet.getRange('C7').setValue(valueA1);
  }
}

Javascript not making cookie

I am working on Salesforce marketing cloud.

I have created a chrome extension using JavaScript. What it has to do is , when user enters username and hits “Next” button , it has to copy the value of Username and create a cookie

The url is https://mc.exacttarget.com/cloud . when you enter it , it navigates to “https://mc.login.exacttarget.com/hub-cas/login%5C*

I have 2 files

Manifest.json :

{
    "manifest_version": 3,
    "name": "SFMC Login Tracker",
    "version": "1.0",
    "description": "Stores the username in a cookie when a user logs into SFMC.",
    "permissions": ["cookies", "scripting", "activeTab"],
    "host_permissions": ["https://mc.login.exacttarget.com/hub-cas/login*"], 
    "content_scripts": [
      {
        "matches": ["https://mc.login.exacttarget.com/hub-cas/login*"], 
        "js": ["content.js"]
      }
    ]
  }
  

Second is the JavaScript:

// Function to set a cookie with a specified name, value, and expiration in days
function setCookie(name, value, days) {
  const date = new Date();
  date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
  const expires = "expires=" + date.toUTCString();
  document.cookie = name + "=" + value + ";" + expires + ";path=/";
}

// Function to extract the username when the form is submitted
function handleLogin() {
  // Select the username input field; adjust the selector to match the SFMC login page
  const usernameField = document.querySelector("input[name='username']");
  console.log("The username is :"+usernameField);
  if (usernameField) {
    const username = usernameField.value;

    // Set a cookie with the username, valid for 7 days
    setCookie("ActiveUser", username, 7);
    console.log(`Cookie set: ActiveUser=${username}`);
  }
}

// Attach the handler to the login form submit event
document.addEventListener("DOMContentLoaded", () => {
  const loginForm = document.querySelector("LoginForm"); // Adjust if needed
  if (loginForm) {
    loginForm.addEventListener("submit-btn", handleLogin);
  }
});

Somehow its not creating cookie as expected. i am not sure what i am doing wrong

When i go to inspect in chrome , i was expecting a cookie with name as ActiveUser be there

NextJS API route is not able to access search params

I have a simple NextJS app where I have a client component that calls an API route.

I am trying to access some search params in a route that I created but it is always returning null.

My client component is like so which calls my API on click of a button

export default function ClientComponent() {

  const getData = async ({
    secretId
  }) => {
    const url = new URL('/api/mydata', window.location.href)
    url.searchParams.set('secretId', secretId) // attaches the query param and this value is definitely there
    
    const response = await fetch(url)

    const data = await response.json()

    console.log("data:", data)
  }
  
  return (
    <button onClick={handleGetSecret}>
      Reveal secret
    </button>
  )
}

I then have a route app/api/mydata/route.tsx which handles the request

import { NextRequest } from "next/server"

export async function GET(request: NextRequest) {

  const secretId = request.nextUrl.searchParams.get('secretId')

  console.log("secretId:", secretId)
  
  return Response.json({ message: 'hello', secretId })
}

but somehow secretId which I try get from the search params is always null.

I have tried converting this to a post endpoint to use the request body too but same thing happens. The value is always null

I have also tried calling this endpoint from Postman and the same thing happens. It seems NextJS isn’t able to access search params in route files even though I tried to follow this here

Any idea what might be causing the value to be returning null even when I can see the search param in my URL when I print the object?

NextURL {
  [Symbol(NextURLInternal)]: {
    url: URL {
      href: 'http://localhost:3000/api/mydata?secretId=abc123',
      origin: 'http://localhost:3000',
      protocol: 'http:',
      username: '',
      password: '',
      host: 'localhost:3000',
      hostname: 'localhost',
      port: '3000',
      pathname: '/api/secrets',
      search: '?secretId=abc123',
      searchParams: URLSearchParams { 'secretId' => 'abc123' },
      hash: ''
    },
    options: { headers: [Object], nextConfig: undefined },
    basePath: '',
    domainLocale: undefined,
    defaultLocale: undefined,
    buildId: undefined,
    locale: undefined,
    trailingSlash: false
  }
}

React Component – Calling a function when a touch occurs but ignoring swipes

I’ve written a react component that is supposed to distinguish between touches and swipes. The idea is:

  1. If the user swipes on the component, its image changes. This is working fine.
  2. If the user touches the component, it shrinks whilst being touched and expands when released. This is also working fine.
  3. It must only call “onTouch” at the end of a touch gesture, but NEVER when a swipe takes place. This is because I only want the user go the new page when they have pressed the element, not swiped across it. Think of Airbnb and when the user is swiping along an Explore card vs selecting it. This is the behaviour I want.

I can’t get Requirement 3 to work, because it is always calling onTouch when a swipe occurs. This occurs when holding, and then swiping whilst being held, or if a quick swipe takes place. But neither of these should trigger onTouch. Please advise how I can fix this? I’ve tried asking ChatGPT but it fails every time!

import React, { useRef, useState } from "react";
import {
  Animated,
  View,
  TouchableWithoutFeedback,
  StyleSheet,
} from "react-native";

interface Props {
  children: React.ReactNode;
  duration?: number; // Optional prop to control the duration of the animation
  onTouch: () => void;
}

function ShrinkOnTouch({ children, duration, onTouch }: Props) {
  if (duration === undefined) duration = 125;

  const scale = useRef(new Animated.Value(1)).current; // Initial scale value (1)
  const [isTouched, setIsTouched] = useState(false);

  // Function to handle the shrink action
  const handleTouchStart = () => {
    setIsTouched(true);
    Animated.timing(scale, {
      toValue: 0.95, // Shrink to 90% of the original size
      duration: duration, // Set the duration of the shrinking animation
      useNativeDriver: true,
    }).start();
  };

  // Function to handle the release action (expand back to original size)
  const handleTouchEnd = () => {
    if (isTouched) {
      setIsTouched(false);
      Animated.timing(scale, {
        toValue: 1, // Expand back to original size
        duration: duration, // Set the duration of the expanding animation
        useNativeDriver: true,
      }).start();
      onTouch();
    }
  };

  // Function to handle swipe detection (expand back to original size if swipe detected)
  const handleTouchMove = (e: any) => {
    if (
      isTouched &&
      (Math.abs(e.nativeEvent.pageX) > 5 || Math.abs(e.nativeEvent.pageY) > 5)
    ) {
      // If swipe detected, expand the component back to original size
      setIsTouched(false);
      Animated.timing(scale, {
        toValue: 1,
        duration: duration, // Same duration for the swipe expansion
        useNativeDriver: true,
      }).start();
    }
  };

  return (
    <View style={styles.container}>
      <TouchableWithoutFeedback
        onPressIn={handleTouchStart}
        onPressOut={handleTouchEnd}
        onPress={handleTouchEnd}
      >
        <Animated.View
          style={[styles.animatedChild, { transform: [{ scale }] }]}
          onStartShouldSetResponder={() => true}
          onResponderMove={handleTouchMove}
        >
          {children}
        </Animated.View>
      </TouchableWithoutFeedback>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  animatedChild: {
    justifyContent: "center",
    alignItems: "center",
  },
});

export default ShrinkOnTouch;

The script does not run when the page changes with Astrojs ViewTranstation

I am using Astrojs ViewTranstation. The scripts do not work and are not reloaded when the page is changed. I am having this problem with Google Tag. Does anyone have a solution?

<div id="disqus_thread" class="py-12"></div>
<script  defer>
    function loadDisqus() {
        if (window.DISQUS) {
            window.DISQUS.reset({
                reload: true,
                config: function () {
                    this.page.url = window.location.href;
                    this.page.identifier = window.location.pathname;
                }
            });
        } else {
            var d = document,
                s = d.createElement("script");
            s.src = "https://###/embed.js";
            s.setAttribute("data-timestamp", +new Date());
            (d.head || d.body).appendChild(s);
        }
    }

    document.addEventListener("astro:page-load", loadDisqus);

    document.addEventListener("DOMContentLoaded", loadDisqus);
</script>



<noscript>
    Please enable JavaScript to view the <a href="https://disqus.com/?ref_noscript">comments powered by Disqus.</a>
</noscript>

I tried the following for Google Tag and it still doesn’t work when the page is changed.

<script 
  async 
  src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"
></script>
<script is:inline>
  window.dataLayer = window.dataLayer || [];
  function gtag() {
    dataLayer.push(arguments);
  }
</script>
<script is:inline>
  document.addEventListener(
    "astro:page-load",
    () => {
      gtag("js", new Date());
      gtag("config", "G-XXXXXXXXXX");
    },
    { once: false }
  );
</script>