Is there a function for change y coordinates if position are equal?

Could you help me ?

I have array of objects:

[
  { 
    position: {x: 2, y: 3}
    ...
  },
  { 
    position: {x: 5, y: 5}
    ...
  },
  { 
    position: {x: 5, y: 5}
    ...
  }
]

I need a function that will change the coordinates so that elements with the same position move down the y-axis

For exampple

[
  { 
    position: {x: 2, y: 3}
    ...
  },
  { 
    position: {x: 5, y: 5}
    ...
  },
  { 
    position: {x: 5, y: 6} <= changed
    ...
  }
]

The main difficulty for me is that when the element is shifted down along the y-axis, the position may again coincide with some other element

[
  { 
    position: {x: 2, y: 3}
    ...
  },
  { 
    position: {x: 5, y: 5}
    ...
  },
  { 
    position: {x: 5, y: 6}
    ...
  }
  ...
  { 
    position: {x: 5, y: 6} <= not again !
    ...
  }
]

I need to get a list of com ports and then listen to each one

There is a code that should get a list of COM ports, and then go through each port and get the value returned by the device connected to the port

let portsPathes = [];

SerialPort.SerialPort.list().then((ports)=>{
    ports.forEach(port=>{
        portsPathes.push(port.path);
    });
    ports.close();
});
let datas = [];
portsPathes.forEach(portPath=>{
    let port = new SerialPort.SerialPort({
        path: portPath,
    baudRate: 9600,
    dataBits: 8,
    parity: 'none',
    stopBits: 1,
    flowControl: false
    });
    //port.close();
    //port.setMaxListeners(10000);
    //port.pipe(new ReadlineParser.ReadlineParser({delimiter: 'rn'}));
    //parser.once('data', data=>{console.log(data);});
});

When executing this code, I get an error

node:internal/process/promises:288
           triggerUncaughtException(err, true /* fromPromise */);
           ^

Error: Opening COM9: Access denied
Emitted 'error' event on SerialPort instance at:
    at SerialPort._error (C:Users1Desktopneftandurino-callbacknode_modules
@serialportstreamdistindex.js:78:18)
    at C:Users1Desktopneftandurino-callbacknode_modules@serialportstream
distindex.js:111:18

The same thing happens if you transfer the creation of SerialPort to forEach in the SerialPort.list()

Getting a Cors error when trying to upload larger files

I have an express nodejs endpoint where im able to upload a file.pdf,xls,txt.

Locally anything works fine but when I host it on my VPS which is running on a reverse proxy with a different origin, im getting a cors error

BUT only if file size is larger than ~15kb, when my file is smaller anything works fine.

I allowed any cors on my nginx

`

location / {

    add_header 'Access-Control-Allow-Origin' '*';

    return 301 https://$server_name$request_uri;

}`

And set my express server the same

Displaying the Resume for a candidate in a new tab ( A component) i need this solution in lwc in salesforce

As a recruiter , I should be able to see the resume in a separate tab in a candidate record without downloading the same from the Files related list.

As a recruiter , when I navigate to the candidate record page , I should be able to see a resume Tab , which should display the entire resume of the candidate , irrespective of the resume File format ( PDF or Word) attached under the related Files related list.

i created lightning web component i need html & js code

How can I determine if there is an event handler attached to a child node?

I have a simple react component defined as such:

export function ClickableContainer({onClick, children}) {
  return <div onClick={(event) => {
    onClick(event);
  }>{ children }</div>
}

Sometimes I might want to have clickable things inside this component:

export function Page() {
  return <ClickableContainer onClick={() => alert("stop poking me")}>
    <button onClick={() => alert("me like that")}>Please Click</button>
  </ClickableContainer>
}

I want to find a way to modify ClickableContainer such that clicks on its children don’t also register as clicks on the parent element.

Let me make it clear, I am aware I could do:

export function Page() {
  return <ClickableContainer onClick={() => alert("stop poking me")}>
    <button onClick={(event) => {
      event.stopPropagation();
      alert("me like that");
    }}>Please Click</button>
  </ClickableContainer>
}

But I DO NOT want to do this. I would rather save the users of my component the cognitive load and handle it inside the parent.

I have tried:

export function ClickableContainer({onClick, children}) {
  return <div onClick={(event) => {
    if (event.eventPhase !== 3) onClick(event);
  }>{ children }</div>
}

and

export function ClickableContainer({onClick, children}) {
  return <div onClick={(event) => {
    if (event.currentTarget == event.target) onClick(event);
  }>{ children }</div>
}

But these prevent clicks from registering altogteher.

It doesn’t have to be simple or pretty, is there any way to tell if an event has already been handled by a child component?

How can I have a resizing sticky div between a non-sticky header and footer?

I’m trying to write a page where there must be a header and a footer with a body, all with unknown heights.

There must be a full scroll bar, which should shrink between the header and the footer whenever they’re visible.

I’ve written a jsfiddle to demonstrate the issue.

https://jsfiddle.net/solidshook/xej43g0c/4/

I’ve made something close to what I need with a flexbox, which looks good but isn’t quite what I want:

<div class='header'>
  i am the header
</div>
<div class='body'>
  <div class='sidebar'>
    <div class='sidebar-top'>
     top of sidebar
    </div>
    <div class='sidebar-bottom'>
     bottom of sidebar
    </div>
  </div>
  <div class='content'>
    i am the content
  </div>
</div>
<div class="footer">
  i am the footer
</div>

 .body {
   display: flex;
 }

.content {
  width: 50%;
  height: 1000px;
  align-self: flex-start;
}

.sidebar {
  width: 20%;
  align-self: flex-start;
  position: sticky;
  top: 0;
  height: 100vh;
}

.sidebar-top {
   position:absolute;
   top: 0;
}

.sidebar-bottom {
  position: absolute;
  bottom: 0;
}

.header, .footer {
  width: 100%;
  background-color: pink;
 }
 
}

I would really prefer to do this entirely with CSS, but if there’s anything else to be done I’d be happy to see

Does anyone know how I could achieve this?

Thanks!

How do I include positive negative decimal numbers in this regular expression with max 2 digits before and after decimal?

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: '[twoDigitDecimaNumberDirective]'
})
export class TwoDigitDecimaNumberDirective {
  // Allow decimal numbers and negative values
  //private regex: RegExp = new RegExp(/^d*.?d{0,2}$/g);
  // Allow key codes for special events. Reflect :
  // Backspace, tab, end, home
  private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home', 'ArrowLeft', 'ArrowRight', 'Del', 'Delete'];
  constructor(private el: ElementRef) {
  }
  @HostListener('keydown', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    if (this.specialKeys.indexOf(event.key) !== -1) {
      return;
    }
    const current: string = this.el.nativeElement.value;
    const position = this.el.nativeElement.selectionStart;
    const next: string = [current.slice(0, position), event.key === 'Decimal' ? '.' : event.key, current.slice(position)].join('');
    if ((!(/^d{1,2}(.$|.d{1,2}$|$)/).test(next)) ) {
      event.preventDefault();
    }
  }
}

<input type="text" twoDigitDecimaNumberDirective>

Accepted Input
12,
12.23,
12.21,
01.12,
-12,
-12.23,
-12.21,
-01.12,

Not Accepted
123,
-123,
123.23,
12.234,
-123.23,
-12.234,

Help me out. thanks in advance

javascript event after event

After the mousedown event there is no onclick event
but if we don’t press the key and just click the event happens.

How can this be done?

example in which this is implemented https://showroom.littleworkshop.fr/

document.addEventListener('mousedown', function(event) {
  
 });

 document.addEventListener('mouseup', function(event) {
    
 });


 document.addEventListener('click', function(event) {

 

 });

Why is the popstate event handler not working?

I have registered the popstate event as a listener in JS, but only in Safari on My Mac it does not fire when the back button is pressed; in Chrome and Firefox it fires.

My Safari version is 16.3 (18614.4.6.1.5).

Here is the code


            window.history.pushState(null, null, null);

            window.addEventListener('popstate', (event) => {
                console.log('fire!')
            });

How can I get back button event detection in Safari?

Circular progress bar based on percentage

I’m working on a js code where circular progress bar shows based on ratings. But there’s an issue. Now total value is 10 set for progress bar. So I can enter max 10 in here. If I enter 9%, it not works as because max-value is 10. But I want something like that, if I enter any number with percent, like that 70% 85% 35%, the the value / max value will work as 100. How can I do it ?

Here’s my code:

    $(document).ready(function() {
      let val = $(".ratings").html();
      const progressBar = $('[role="progressbar"]');
      progressBar.attr('aria-valuenow', val); // Set the value to aria-valuenow attribute
      progressBar.css('--value', val); // Set the value to --value CSS custom property
      progressBar.text(val);
    });
div[role="progressbar"] {
      --size: 3rem;
      --fg: #369;
      --bg: #def;
      --pgValue: var(--value);
      --pgPercentage: calc(var(--pgValue) * 10);
      width: var(--size);
      height: var(--size);
      border-radius: 50%;
      display: grid;
      place-items: center;
      background: 
        radial-gradient(closest-side, white 80%, transparent 0 99.9%, white 0),
        conic-gradient(var(--fg) calc(var(--pgPercentage) * 1%), var(--bg) 0);
      font-size: calc(var(--size) / 3.5);
      color: var(--fg);
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ratings" style="display: none;">9.5</div>
    <div role="progressbar" aria-valuenow="" aria-valuemin="0" aria-valuemax="10" style="--value:"></div>

Acrobat dropdown form to show hide layers with Javascript

Good morning!

Show hide layers from a dropdown in Adobe Acrobat!

I have implemented the script below that may have some errors but I have limited knowledge of JavaScript. I have adapted this script and seems to work locally however when I send it to the client it fails! is there any obvious errors in the following!

Any help much appreciated!!!


var layers = this.getOCGs();
var v = event.value; 
for (var i = 0; i < this.layers.length; i++) {
    if (layers[i].name == "Blank" && v == "BlankOption") {
        layers[i].state = true;
    }
    else if (layers[i].name == "Form1" && v == "Option1") {
        layers[i].state = true;
    }
    else if (layers[i].name == "Form2" && v == "Option2") {
        layers[i].state = true;
    }
        else if (layers[i].name == "Form3" && v == "Option3") {
        layers[i].state = true;
    }
        else if (layers[i].name == "Form4" && v == "Option4") {
        layers[i].state = true;
    }
        else if (layers[i].name == "Form5" && v == "Option5") {
        layers[i].state = true;
    }
        else if (layers[i].name == "Form6" && v == "Option6") {
        layers[i].state = true;
    }
        else if (layers[i].name == "Form7" && v == "Option7") {
        layers[i].state = true;
    }
        else if (layers[i].name == "Form8" && v == "Option8") {
        layers[i].state = true;
    }
        else if (layers[i].name == "Form9" && v == "Option9") {
        layers[i].state = true;
    }
    else if (layers[i].name != "BG-IMAGE"){
        layers[i].state = false;
    }
}

Jest is covering empty lines, comment lines and spaces in Source code

I’m using

"jest": "^29.5.0",
"jest-fetch-mock": "^3.0.3",
"jest-sonar-reporter": "^2.0.0",

Following is my jest.config.js:

module.exports = {
  automock: false,
  clearMocks: true,
  collectCoverage: true,
  coverageDirectory: "<rootDir>/Test/Reports",
  coveragePathIgnorePatterns: ["/node_modules/", "/Test/Unit/"],
  coverageReporters: ["text", ["lcovonly", { projectRoot: "." }]],
  testEnvironment: "node",
  testResultsProcessor: "<rootDir>/Test/node_modules/jest-sonar-reporter",
  testEnvironmentOptions: {
    browsers: ["chrome", "firefox", "safari"],
    url: "http://localhost",
  },
  moduleNameMapper: {
    "\.(css|less|sass|scss)$": "<rootDir>/Test/__mocks__/styleMock.js",
    "\.(gif|ttf|eot|png|svg)$": "<rootDir>/Test/__mocks__/fileMock.js",
    "^react$": "<rootDir>/Test/node_modules/react",
    "^react-dom$": "<rootDir>/Test/node_modules/react-dom",
  },
  rootDir: "../",
  roots: ["<rootDir>"],
  setupFiles: ["<rootDir>/Test/node_modules/mock-local-storage"],
  setupFilesAfterEnv: [
    "<rootDir>/Test/Unit/setupJest.js",
    "<rootDir>/Test/node_modules/mock-local-storage",
  ],
  transform: {
    "^.+\.(js|jsx|mjs)$": "<rootDir>/Test/jest-transformer.js",
  },
  verbose: true,
  watchman: true,
};

The coverage summary table and lcov.info file generated shows that new lines, comment lines, initialized variables, destructured props and non-existing lines are uncovered (example: file with 500 total lines, report says line 700-800 is uncovered).

useSWR fail to receive return response from Nextjs API route

I am using useSWR to call the internal Nextjs API route to query the database.

const fetcher = (url: string) => axios.get(url).then((r) => console.log(r.data))

export default function Model(){
    const searchParams = useSearchParams();
    const selectedMatch= searchParams.get("data"); 
    const { data } = useSWR("/api/model?data=" + selectedMatch, fetcher, {refreshInterval: 100});
    return (<p>{data}</p>)}

My /api/model:

import { connectToDB } from "@/app/utils/database";
import Events from "@/models/events";

export const GET = async (req: Object) => {
  await connectToDB();
  const matchString: String = req.nextUrl.searchParams.get("data")
  var events: any = {};

  try {
    matchString.split(",").map(async (match: string) => {
      events[match] = await Events.find({ name: match }).then((res) => res[0]);
    });
    return new Response(JSON.stringify(events), { status: 200 });
  } catch (error) {
    return new Response("Failed to fetch all events", { status: 500 });
  }
};

However, when I do the axios.get(url).then((r) => console.log(r.data)), it logs the empty object {}, if I console.log the JSON.stringify(events) in /api/model before the return, it does give me the correct data from the database, may I ask why?