loading an svg externally in canvas in fabric js

I want to upload individually all the elements in my svg into to my canvas.

you can see in the console [screenshot of the console(https://i.sstatic.net/Yj3SGXEx.png) that the svg file path is right and the console logs the content properly.

this is my code to upload the svg to my canvas

// URL of the external SVG file
const svgUrl = '../111.svg'; // Replace with your SVG URL

// Load the SVG file
fabric.loadSVGFromURL(svgUrl, (objects, options) => {
    console.log('SVG loaded:', objects);

    // Add objects to the canvas
    if (Array.isArray(objects)) {
        objects.forEach(obj => {
            canvas.add(obj);
        });
    } else {
        canvas.add(objects);
    }

    // Render the canvas
    canvas.renderAll();
}, (error) => {
    console.error('Error loading SVG:', error);
});

algorithmic task Space travel [closed]

I want found solution O (n) algorithm for this problem but unable to do.

After the cataclysm, there are only two ways to travel around the world:

  1. magic ferries that move between neighboring islands (naturally, the ferry can move in both directions), so from the island that is in the i-th place in the cosmic row, you can get to the i-1 and i+1 islands;

  2. portals through which you can teleport between islands regardless of the distance, but only if before the cataclysm these islands formed one continent (interestingly, the continents in this world had numbers, not names).
    It is necessary to find the minimum number of movements from the first island to the last.

    example 1

    11 -86 50 986 7 23 24 25 1846 201 9 19 11 86 2000 201 11 2010 234 156 11 456 488 478 985 6564 45341 3 201 8

answer 4

example 2

1 3 4 5 4 3

answer 2

The solution to the problem using a graph will be rejected because storing the list of nodes and the queue requires a lot of memory.Memory limit in this task 64 mb. Simply put, the solution using a graph is not optimal in terms of memory usage.
My question is there another algorithm to solve this problem. We know that the longest path is equal to the number of elements (islands) in the array.

const readline = require("readline").createInterface(process.stdin, process.stdout)

readline.on("line", line => {
  let arr = line.split(" ").map(Number)
  // console.time()
  const graph = createGraph(arr)
  const last = arr.length - 1
  arr = null
  const nodeState = new Map()
  const startNode = { id: 0, distanceToSource: Number.POSITIVE_INFINITY, visited: false, open: false, heapId: -1 };
  startNode.distanceToSource = 0
  nodeState.set(0, startNode)
  startNode.open = true
  const queue = Queue()
  queue.push(startNode);
  while (queue.length) {
    const parent = queue.pop()
    parent.visited = true
    if (parent.id === last) break
    graph.get(parent.id).forEach(curr => {
      let currNode = nodeState.get(curr);
      if (!currNode) {
        currNode = { id: curr, distanceToSource: Number.POSITIVE_INFINITY, visited: false, open: false, heapId: -1 };
        nodeState.set(curr, currNode);
      }

      if (currNode.visited) return

      if (currNode.open === false) {
        queue.push(currNode);
        currNode.open = true;
      }

      const distance = parent.distanceToSource + 1;
      if (distance >= currNode.distanceToSource) return;

      //currNode.parent = parent.id;
      currNode.distanceToSource = distance;
      // currNode.fScore = distance //+ heuristic(curr, arr.length - 1);
      queue.updateItem(currNode.heapId)
    });
    graph.delete(parent.id)
  }
  // console.timeEnd()
  console.log(nodeState.get(last).distanceToSource)
  readline.close()
}).on("close", () => process.exit(0))

function createGraph(arr) {
  const mapArr = new Map()
  for (let i = 0; i < arr.length; i++) {
    if (!mapArr.has(arr[i])) mapArr.set(arr[i], [i])
    else mapArr.get(arr[i]).push(i)
  }
  const graph = new Map()
  for (let i = 0; i < arr.length; i++) {
    const node = []
    if (i + 1 < arr.length)
      node.push(i + 1)
    if (i - 1 >= 0)
      node.push(i - 1)
    const findKey = mapArr.get(arr[i])
    node.push(...findKey.filter(x => x != i - 1 || x != i + 1))
    graph.set(i, node.filter(x => x != i).sort((a, b) => b - a))
  }
  return graph
}

const heuristic = (from, to) => to - from

function Queue() {
  class PriorityQueue {
    constructor() {
      this.data = []
      this.length = this.data.length;
    }

    compare = (a, b) => { return a.distanceToSource - b.distanceToSource }

    notEmpty() {
      return this.length > 0
    }

    pop() {
      if (this.length === 0) return undefined;

      const top = this.data[0];
      this.length--;

      if (this.length > 0) {
        this.data[0] = this.data[this.length];
        this.data[0].heapId = 0
        this.down(0);
      }
      this.data.pop();

      return top;
    }

    push(item) {
      this.data.push(item);
      item.heapId = this.length
      this.length++;
      this.up(this.length - 1);
    }

    up(pos) {
      const item = this.data[pos];

      while (pos > 0) {
        const parent = (pos - 1) >> 1;
        const current = this.data[parent];
        if (this.compare(item, current) >= 0) break;
        this.data[pos] = current;
        current.heapId = pos
        pos = parent;
      }

      item.heapId = pos
      this.data[pos] = item;
    }

    down(pos) {
      const halfLength = this.length >> 1;
      const item = this.data[pos];

      while (pos < halfLength) {
        let left = (pos << 1) + 1;
        const right = left + 1;
        let best = this.data[left];

        if (right < this.length && this.compare(this.data[right], best) < 0) {
          left = right;
          best = this.data[right];
        }
        if (this.compare(best, item) >= 0) break;

        this.data[pos] = best;
        best.heapId = pos
        pos = left;
      }

      item.heapId = pos
      this.data[pos] = item;
    }
    updateItem(pos) {
      this.down(pos);
      this.up(pos);
    }
  }

  return new PriorityQueue();
}

Unable to nest basic vanilla web component

I have a set of basic web components made out of plain JS. Example:

Account.ts

class Account extends HTMLElement{
   constructor(){
      super();
      this.innerHTML = '<p>My account</p>';
   }
}

customElements.define('account', Account);

Basket.ts

class Basket extends HTMLElement{
   constructor(){
      super();
      this.innerHTML = '<p>My Basket</p>';
   }
}

customElements.define('basket', Basket);

I am trying to create another web component (common) that can be nested in each of the above. For now, lets assume a basic <button> with a click event. I have tried:

CommonButton.ts

class CommonButton extends HTMLElement{
   constructor(){
      super();
      this.innerHTML = '<button onclick="console.log('clicked')">Click Me</button>';
   }
}

customElements.define('common-button', CommonButton);

Account.ts

class Account extends HTMLElement{
   constructor(){
      super();
      this.innerHTML = `
          <p>My Account</p>
          <common-button></common-button>
      `;
   }
}

customElements.define('account', Account);

There are no errors in the browser. I can see in the generated HTML:

<account>
     <p>My Account</p>
     <common-button></common-button>
</account>

However no <button> inside of <common-button>

why browser allow strange javascript: combination

Reading the XSS Filter Evasion Cheat Sheet I have realized as many of the XSS filter evasions are due to particular and strange behaviors that are hidden to common developers.

In particular the following XSS filter evasion techniques have struck me:

  • <SCRIPT/XSS SRC="http://xss.rocks/xss.js"></SCRIPT>
  • <BODY onload!#$%&()*~+-_.,:;?@[/|]^=alert("XSS")>
  • <a href="jav&#x09;ascript:alert('XSS');">Click Me</a>

The point is: why do modern web browsers allow such things? For example, why allowing to have strange characters in the middle on the javascript: directive and not just sticking to it? I’ve never seen a developer writing jav&#x09;ascript: instead of javascript:.

Sap Business Apllication Studio : layout editor error in XML views

I have a Fiori project in Sap BAS. It contains 2 view.

Project1
 -> webapp
   -> view
      -> View1.view.xml
      -> View2.view.xml

Index.html contains:

data-sap-ui-resourceroots='{ "project1": "./" }'

View1 contains an xml view for View2:

<mvc:XMLView viewName="project1.view.View2/>

When I run the app, it displays correctly the view2 in the view1.
But when I starts the Layout editor for View1, it drops the following error:

For scenarios involving fragments and nested views, your project must contain an index.html like or a localIndex.html file containing the data-sap-resourceroots attribute. Currently, your project does not contain such files.

resource project1/view/View2.view.xml could not be loaded from /di/home/user/projects/project1/webapp/./view/View2.view.xml. Check for ‘file not found’ or parse errors. Reason:

Anybody has a clue what did I wrong?
Thanks for the help

I tried to modify the link to view2 several mode, but always error comes.

Two or more time slots in flatpickr

There’s a way to make two or more separate slots in a time picker. Something like:

flatpickr(bookingHour, {
  enableTime: true,
  noCalendar: true,
  dateFormat: "H:i",
  enable: [
    {
      from: "11:30",
      to: "15:30",
    },
    {
      from: "19:30",
      to: "23:45",
    },
  ],
});

Something like enabling range(s) of dates but with time.

TypeError: is not a constructor when importing from my own package

I can’t seem to figure out what’s wrong with the package that I created which I’m now trying to import to my other project.

The main file of the package contains these exports (names changed):

export { Class1 } from './util/translations/class1';
export { Class2 } from './util/translations/class2';

Each file exports a class such as:

export class Class1 {
  private client: Client;

  constructor(config: Config) {
    this.client = new Client(Config);
  }

  async translateText(text: string, targetLanguage: Language): Promise<string> {
    return client.translate(text, targetLanguage)
  }
}

My package.json has these settings:

  "main": "dist/Localisation.js",
  "types": "dist/Localisation.d.ts",
  "files": [
    "dist/**/*"
  ],

My tsconfig.json:

"compilerOptions": {
    "outDir": "./dist",
    "rootDir": "./src",
    "target": "es2017",
    "module": "commonjs",
    "moduleResolution": "node",
    "declaration": true,
    "types": ["node", "jest"],
    "typeRoots": ["./node_modules/@types", "./types"],
    "baseUrl": "."
},
  "include": ["src/**/*.ts"],
  "exclude": [
    "node_modules",
  ]

I run tsc to compile the project and get the dist folder. The main file in dist looks like this:

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Language = exports.Class1 = exports.Class2 = void 0;
var class1_1 = require("./util/translations/class1");
Object.defineProperty(exports, "Class1", { enumerable: true, get: function () { return class1_1.Class1; } });
var class2_1 = require("./util/translations/class2");
Object.defineProperty(exports, "Class2", { enumerable: true, get: function () { return class2_1.Class2; } });
var languages_1 = require("./util/languages");
Object.defineProperty(exports, "Language", { enumerable: true, get: function () { return languages_1.Language; } });
//# sourceMappingURL=Localisation.js.map

I then run npm publish to publish my package with a bumped version. I pull that version in my other project and try to import Class1 and Class2.

import { Class1, Class2 } from "my-package";

But when I try to construct an instance of Class1, I’m getting Class1 is not a constructor. When I console log the imported Class1, I’m getting undefined as if it doesn’t exist at all on the package or as if the export didn’t work.

I’ve tried so many things, including:

  • changing exports in the package to export default
  • moving all my classes to the main file of the project instead of exporting them in the main file
  • using tsup instead of tsc

A very strange thing about is that I’m also exporting an enum in the same way in that same main file (from another folder within the package) and that enum is actually available and not null, the only thing that gets exported correctly.

I’m honestly not sure what I can do or try in this case.

niReact Code working fine in PC browser but not on mobile browser

My code is working fine on my laptop browser but not submitting the form on mobile browser.

import { useEffect, useState } from "react";
import axios from "axios";
import "bootstrap/dist/css/bootstrap.min.css";
import { uri } from "../constants/url";
import { ImageCard } from "./UI";

const Home = () => {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [wapp, setWapp] = useState("");
  const [dob, setDob] = useState("");
  const [successAlert, setSuccessAlert] = useState(false);
  const [warningAlert, setWarningAlert] = useState(false);
  const [alertMsg, setAlertMsg] = useState("");
  const [dim, setDim] = useState(false);
  const [showCard, setShowCard] = useState(false);
  const [qr, setQr] = useState("");

  useEffect(() => {
    let timer;
    if (successAlert || warningAlert) {
      timer = setTimeout(() => {
        setDim(true);
        setTimeout(() => {
          setSuccessAlert(false);
          setWarningAlert(false);
          setAlertMsg("");
          setDim(false);
        }, 2000);
      }, 4000);
    }
    return () => clearTimeout(timer);
  }, [successAlert, warningAlert]);

  useEffect(() => {
    if (qr !== "") {
      setShowCard(true);
    }
  }, [qr]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (validateForm()) {
      const data = {
        name,
        email,
        wapp,
        dob,
      };
      try {
        let response = await axios.post(uri + "sendWifiPassword", data);
        const qrCode = response.data;

        if (qrCode) {
          setQr(qrCode);
          setShowCard(true);
        }
      } catch (error) {
        console.error("Error:", error);
      }
    }
  };

  const validateForm = () => {
    if (name === "") {
      setAlertMsg("Please provide you Full Name");
      setWarningAlert(true);
      return false;
    }
    if (email === "" && wapp === "") {
      setAlertMsg("Please fill out either Email address or WhatsApp number");
      setWarningAlert(true);
      return false;
    }
    if (wapp !== "" && !/03d{9}/.test(wapp)) {
      setAlertMsg("Please provide valid Number. Eg: 03125671234");
      setWarningAlert(true);
      return false;
    }
    return true;
  };

  console.log(showCard, qr);

  return (
    <div>
      <nav className="navbar bg-body-tertiary">
        <div className="container-fluid">
          <a className="navbar-brand">Wifi Demo</a>
          <a href="/admin" className="btn btn-warning">
            Admin
          </a>
        </div>
      </nav>

      <div className="d-flex justify-content-center">
        <div className="col-md-6 col-lg-2">
          {successAlert && (
            <div
              id="successAlert"
              className="alert alert-success"
              style={{ opacity: dim ? 0.5 : 1 }}
            >
              {alertMsg}
            </div>
          )}
          {warningAlert && (
            <div
              id="warningAlert"
              className="alert alert-warning"
              style={{ opacity: dim ? 0.5 : 1 }}
            >
              {alertMsg}
            </div>
          )}
        </div>
      </div>
      {showCard ? (
        <ImageCard imgSrc={qr} setQr={setQr} showCard={showCard} setShowCard={setShowCard} />
      ) : (
        <div id="formContainer">
          <div className="d-flex justify-content-center">
            <a>Please fill the form below to get Wifi Password</a>
          </div>
          <div className="d-flex justify-content-center">
            <div className="col-md-6 col-lg-2">
              <form id="userForm" onSubmit={handleSubmit}>
                <div className="mb-3">
                  <label htmlFor="name" className="form-label">
                    Full Name
                  </label>
                  <input
                    type="text"
                    className="form-control"
                    id="name"
                    value={name}
                    onChange={(e) => setName(e.target.value)}
                  />
                </div>
                <div className="mb-3">
                  <label htmlFor="email" className="form-label">
                    Email address
                  </label>
                  <input
                    type="email"
                    className="form-control"
                    id="email"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                  />
                </div>
                <div className="mb-3">
                  <label htmlFor="wapp" className="form-label">
                    Whats App #
                  </label>
                  <input
                    type="text"
                    className="form-control"
                    id="wapp"
                    value={wapp}
                    onChange={(e) => setWapp(e.target.value)}
                  />
                </div>
                <div className="mb-3">
                  <label htmlFor="dob" className="form-label">
                    Date of Birth
                  </label>
                  <input
                    type="date"
                    className="form-control"
                    id="dob"
                    value={dob}
                    onChange={(e) => setDob(e.target.value)}
                  />
                </div>
                <button type="submit" className="btn btn-warning">
                  Submit
                </button>
              </form>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

export default Home;

I’ve tried changing background color to check where the problem. I’ve condition in handleSubmit() to check if (qr) exists then proceed, if I set background color to red here, it will change on web browser but not on mobile browser,

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (validateForm()) {
      const data = {
        name,
        email,
        wapp,
        dob,
      };
      try {
        let response = await axios.post(uri + "sendWifiPassword", data);
        const qrCode = response.data;

        if (qrCode) {
          setQr(qrCode);
          setShowCard(true);
        }
      } catch (error) {
        console.error("Error:", error);
      }
    }
  };

NOTE: I’ve manually copied the image data from log and provided it in the following component and it works fine on both laptop and mobile browser:

  <ImageCard imgSrc={qr} setQr={setQr} showCard={showCard} setShowCard={setShowCard} />

I’ve setup CORS in Back End and I’m sending req on my local network not local host (i.e, http://{my_ip_address}:5000) and its working on both browsers:

app.use(cors({
  origin: '*',
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  headers: ['Content-Type', 'Authorization']
}));

How to bind this using fomatter from the controller?

I am trying to re-use the formatter methods used in the xml view but from the controller. This is because I need to export to excel a ui.table and the class sap.ui.export.Spreadsheet get data is it is in the JSON Model and not as it looks like after the applying the formatter in the xml View.

sap.ui.define([
    "../controller/BaseController",
    "../model/models",
    "../model/formatter"
],
    function (BaseController, models, formatter) {
        "use strict";

        return BaseController.extend("ns.controller.Main", {
            formatter: formatter,
            _formattedUiTableData: function (sCode){
                return formatter.getStatusText(sCode);

            }
        });
});

/////////////////at formatter.js /////////////////////////////////////////////
sap.ui.define(["../controller/BaseController"

], function () {
    "use strict";

    return {
        serviceCoderDescription(sCode) {
            const oResourceBundle = this.getOwnerComponent().getModel("i18n").getResourceBundle();
            switch (sCode) {
                case "A":
                    return oResourceBundle.getText("CodeA");
                case "B":
                    return oResourceBundle.getText("CodeB");
                default:
                    return sCode;
            }
        }
    
    };
});

enter image description here

enter image description here

How do I keep scripts between renderings in Blazor .Net8?

I’m using blazor .net 8 with global interactive auto and I’ve put my scripts in App.razor, but they only load in prerender, when the application render interactive mode the scripts stop working and do the “flick” because the page is render for the second time.
How do I persist the Javascripts between renders (prerender to Interactive Auto for example)?

I’ve read a few things and discover the “data-permanent”

<div data-permanent> 

but doesn’t work.

Is there any way to persist Javascripts scripts between renders?

Stop clustering of stars in browser canvas for Galaga clone

I’m building a Midway Galaga clone in Javascript and the browser Canvas API, based on the video here: https://www.youtube.com/watch?v=P9h9RkHC-Iw. Currently I’m implementing the scrolling starfield, and have this code for placing the stars:

for(let index = 0; index < this.count; index += 1) {
  const x = (Math.random() * width) | 0;
  const y = (Math.random() * height) | 0;
  this.stars.push(new Star(x, y));
}

Due to the simple nature of the coordinate generation, stars have a habit of clustering too much and even overlapping. Is there a better coordinate generation method? My full current progress can be found here: https://codepen.io/ntchambers/pen/wvLdOer/5dc2ccba73fa9aaf98023c5b8179b516 (ignore the fact that it doesn’t scroll. I have thoughts on that but will be implementing it last).

While making an API call gives ‘options.uri is a required argument’

I am using node 12 and npm request module version 2.88.0. While making a request to an API call , it is giving me error as options.uri is a required parameter. Also i had tried to change the url to uri but still getting same.
apiURL is defined as in

{
  "Config": {
    "dev": {
      "apiURL": "https://apiURL.com"
      
  }
}
}

and config where its fetched on the basis of what enviornment is it running

const config = require('./default');

var dev = config.Config.dev;
var prod = config.Config.prod;

module.exports.configure = function () {
    var environment = 'dev'; //process.env.NODE_ENV;
    var config = {};
    switch (environment) {
        case 'prod':
                config = {
                    apiURL: prod.apiURL,
                   //etc
                }
                return config;
                
            case 'dev':
                config = {
                    
                    apiURL: dev.apiURL,
                    //etc
                }
                return config;
            
        default:
            var error =
                'No Environment Configured.';
            throw error;
    }
};

Here is the actual code part while making the api call

async function callAPI(id, pass) {
  request(
    {
      url: apiURL,
      method: 'POST',
      body: {
        id,
        pass,
      },
      json: true,
    },
    async function (error, response, body) {
      if (response && response.statusCode == 200) {
        logger.log(
          INFO,
          JSON.stringify({
            Module: 'API ',
            Response: `${JSON.stringify(body)}`,
          }),
        );
        return Promise.resolve(response);
      } else {
        return Promise.reject(response);
      }
    },
  );
}

Is it possible to store Google Maps object as an attribute in a Vue component?

My google maps is being initialized in mounted() and stored in map attribute:

mounted() {
  this.initMap();
},
methods: {
  async initMap() {
    const loader = new Loader({
      apiKey: settings.googlemaps,
      version: 'weekly',
    });

    try {
      await loader.load();
      const {Map} = await google.maps.importLibrary('maps');

      this.map = new Map(this.$refs.map, {
        center: {lat: 37.75768866503074, lng: -96.54510528125},
        zoom: 4,
        minZoom: 3,
        streetViewControl: false,
        mapTypeControl: false,
        mapId: settings.mapid,
      });
    } catch (error) {
      console.error('Error loading Google Maps API', error);
    }
  },
}

The markers content comes from an external API and is passed from the parent component:

watch: {
  places: {
    deep: true,
    handler() {
      this.initMarkers();
    },
  },
},

The problem is the markers is not being added to the map (I’m not applying the places loop yet):

async initMarkers() {
  try {
    const {AdvancedMarkerElement} =
      await google.maps.importLibrary('marker');

    new AdvancedMarkerElement({
      map: this.map,
      title: 'Marker title',
      position: {
        lat: 38.992534,
        lng: -122.745783,
      },
    });
  } catch (error) {
    console.error('Error loading marker library', error);
  }
},

Looks like AdvancedMarkerElement cannot read/access this.map correctly.

How to grab all checkboxes in GMail?

I am trying to just report back all checkboxes in Gmail for a small background script. Eventually i want to return only those that are checked. The checkboxes that are beside each email, used to select them and operate them, are indicated by role=”checkbox”.

With current code, i only get an empty list, and i can’t figure out why. Here is my code:

background.js

console.log("Start");
browser.contextMenus.create(
    {
        id: "AlertTest",
        title: "Test2",
        contexts: ["all"],
    },
    () => void browser.runtime.lastError,
);

browser.contextMenus.onClicked.addListener((info, tab) => {
    switch (info.menuItemId) {
    case "AlertTest":
        //console.log(info.selectionText);
        var ele = document.querySelectorAll("[role=checkbox]");
        console.log(ele);
        break;
    }
});

function onError(error) {
    console.log(error);
}

ref.current is null inside useEffect

I have a list of refs that is being forwarded to the child components. They seem to work fine as I can do operations with them as feedback to the user actions (in this case, it is scrolling into view). However, I want to scroll to them when component is rendered/mounted, which sounds like a classic ref usage: add ref dependencies to a useEffect and scroll when they are ready. But it basically does not work. When I console.log out the refs, I see the ref.current is assigned. However when I console.log refs[scrollTo], it is undefined. This might be related to how chrome browser consoles work though.

So here is my example code:

const MyComponent = (props) => {
  const refs = {
    a: useRef<HTMLDivElement>(null),
    b: useRef<HTMLDivElement>(null),
    c: useRef<HTMLDivElement>(null),
  }
  
  useEffect(() => {
    if (props.scrollTo && refs[props.scrollTo].current) {
      refs[props.scrollTo].current.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  }, [refs.a.current, refs.b.current, refs.c.current]);

  return <>
    <ChildComponent key='a' ref={refs.a} onClick={
      refs.a.current?.scrollIntoView({ behavior: 'smooth', block: 'start' })
    } />
    <ChildComponent key='b' ref={refs.b} onClick={
      refs.b.current?.scrollIntoView({ behavior: 'smooth', block: 'start' })
    } />
    <ChildComponent key='c' ref={refs.c} onClick={
      refs.c.current?.scrollIntoView({ behavior: 'smooth', block: 'start' })
    } />
  </>
};

refs[props.scrollTo].current always returns null here in the use effect, preventing me to scroll there on load. useCallback solution also does not apply here for me as well, since I need those DOM refs for scrollintoview behaviour on onclicks. What am I missing here?