Can a badly configured nginx reverse proxy or cloudflare cdn causes my api to be called twice on one request

Problem:
I recently uploaded my website to my linode server to be able to use it with a domain and enable https. Everything looked liked it was working fine on my express.js api, but I recently checked my requests log and each time I made a request to domain.com/api/count it was printing two requests. The same goes for every other calls I made. Locally it works fine, but on my server it is not. So my questions is, is it possible that a misconfigured nginx reverse proxy or the cloudflare cdn causes that. I cannot find any other reason why it would since locally it works. Any help would be appreciated, thanks you!

If you need my nginx config or any other information, feel free to ask me.

Quick sort turns array into string [duplicate]

i have made an quick sort algorithm, but it returns a string instead of an wanted array.

const quickSort = (arr) =>  {
  if (arr.length < 2) {
    return arr;
  } else {
    let pivot = arr[0]

    let less = arr.slice(1).filter(i => i <= pivot)
    let grater = arr.slice(1).filter(i => i > pivot)

    return quickSort(less) + [pivot] + quickSort(grater);
  }
}

console.log(quickSort([1, 5, 93, 2]));

I can’t figure out why, my guess it that is has some thing to do with the line:

return quickSort(less) + [pivot] + quickSort(grater);

XHR Interceptor in Typescript

Why is the following monkey patch not allowed in Typescript?

const oldXHROpen = window.XMLHttpRequest.prototype.open

window.XMLHttpRequest.prototype.open = function (
    method: string,
    url: string,
    ...args: any[]
): void {
    return oldXHROpen.apply(this, [method, url, ...args])
}

It gives the following error:

Argument of type '[string, string, ...any[]]' is not assignable to parameter of type '[method: string, url: string | URL, async: boolean, username?: string | null | undefined, password?: string | null | undefined]'.
  Target requires 3 element(s) but source may have fewer.

However when looking at the definitions of open there is a method which only requires two arguments.

open(method: string, url: string | URL): void;

How can I make an SVG segment clickable in a webpage?

Below is a code snippet I am using to draw a simple square (though the shape will get much more complex further in the project as it is meant to visualize DWG files imported from a back-end).

I have however hit a wall in trying to get the SVG segment that is clicked.
What I am looking to do in the current setup is:

  1. User clicks on a segment of the SVG
  2. The segment closest to it (with some margin) is captured
  3. I can use that captured information in my code (preferably 4 number values, representing the x1, x2, y1 and y2)

The problem I am having is that I don’t know how to identify the segments, while I can see that they advance with an [x1, y1, x2, y2, x3, y3, x4, y4] pattern.

var draw = svg.SVG().addTo('body').size(300, 300);
var arr = new svg.Array([0, 0, 0, 100, 100, 100, 100, 0])
draw.polygon(arr).fill("0x000000");

An example of what I want to be able to do:

get the line along the point [50, 0] which should be in the first segment of the shape drawn in the snippet above. I need to correctly identify the segment the user has selected so I can work with that information. If I can somehow get the begin and end coordinate of the segment that was clicked that would probably lead me to a successful solution.

Acess violation for an East project

Ok, so I have a east project and you need to get past something were calling a “blue screen” and it says;

System error:access violation in 0x070cbf32 for provided URL

The access level for the URL is restricted pending usage of correct phrase key. Please use a different phrase key or see administrator for assistance. Provided phrase key should be in alphabetic characters only.

Error message 0x070cbf32; explicit violation found. There is a picture provided. https://i.stack.imgur.com/YvWhe.png

Getting URL encoded response.request.body in NodeJS?

I am using the request module in NodeJS to make an API call.

The request options are like this:

reqOpts: {
    form: {
        client_id: 'someID'
        client_secret: 'someValue'
        grant_type: 'someValue'
        refresh_token: 'dumm//yrefresh'
    },
    method: 'POST',
    url: 'someUri.com'
}

For the above request options, the response has a field, response.request.body which looks like this:

'refresh_token=dumm%2F%2Fyrefresh&grant_type=someValue&client_id=someID&client_secret=someValue'

Here you can see that refresh_token field was URL encoded in response i.e // got changes to %2F%2F. Is there a way to pass some parameters so that the response.request.body doesn’t encode the string and returns // intact as in the request?

Keycloak-js: How to include custom rediect_uri and login_hint

I built a web application using Keycloak-js

Currently, keycloak.init(options) takes me to the login form, but this doesn’t have the options to include redirectUri and loginHint

According to the documentation, the ones where we can include these options, are login(options) and createLoginUrl, but not sure how to use them and in what order?

Can anyone please help?

How to merge 2 button in HTML/Javascript?

Hi all I have a simple example in which I have two separated button, as I am showing in the code. I would like to create 1 single Button. Initially is the “Multiply Button” and after having clicked on it, it becomes the “Refresh page button” and once I clicked it go back to “multiply” and so on in a loop. Someone has an idea of How I put together the two button? (each button activate a function which correspond to the name of the button.

<!DOCTYPE html>
<html>
<body>
<form>
<input type="button" onClick="multiplyBy()" Value="Multiply" />
</form>

    <foreignObject id="specificityObject" x="6" y="7" width="80" height="80">
        <div xmlns="http://www.w3.org/1999/xhtml">
            <p>
                <span style="font-size:27px" id = "result"  ></span>
            </p>
        </div>
    </foreignObject>

    <foreignObject id="specificityObject" x="780" y="830" width="100" height="100">
            <div xmlns="http://www.w3.org/1999/xhtml">
                    <button onClick="window.location.reload();">Refresh Page</button>
            </div>
    </foreignObject>

</body>

<script>
    function multiplyBy()
{
        var num1 = document.getElementById("firstNumber").value;
        var num2 = document.getElementById("secondNumber").value;
        num3 = var num1 * var num2;
        document.getElementById("result").innerHTML = num3;
}

function reload() {
    reload = location.reload();
}
// Event listeners for reload
reloadButton.addEventListener("click", reload, false);

</script>

</html>

mat-checkbox select multiple value and on focus submit array

how to submit checked options on mat-checkbox on focusot()

I try to solve this with @HostListener and focusout() but this is working wrong.
Anytime I check or uncheck the checkbox option focusout is triggered.

I need to trigger focusout only when I click anywhere outside (need to trigger this even if I click on a menu item or any other button), but if I click inside the checkboxes, needs to only push or remove from checkboxes array without trigger focusout. Here is also stackblitz

export class CheckboxOverviewExample implements OnInit {
  checkedOptions = [
    { title: 'aa', value: 1, checked: true },
    { title: 'bb', value: 2, checked: false },
    { title: 'cc', value: 3, checked: true },
    { title: 'dd', value: 4, checked: false },
  ];
  selectedVal: any[] = [];
  @HostBinding('attr.tabindex') tabIndex = '-1';
  submitedVal: any[];

  ngOnInit() {
    const data = this.checkedOptions.filter((x) => x.checked);
    this.selectedVal = data.map((x) => x.value);
  }

  @HostListener('focusout', ['$event'])
  focusout(event) {
    this.submit('this.selectedVal')
  }

  updateCheckboxArray(option, isChecked) {
    if (isChecked) {
      if (this.selectedVal.findIndex((x) => x === option.value) === -1) {
        this.selectedVal.push(option.value);
      } else {
        const idx = this.selectedVal.findIndex((x) => x === option.value);
        this.selectedVal.splice(idx, 1);
      }
    } else {
      const idx = this.selectedVal.findIndex((x) => x === option.value);
      this.selectedVal.splice(idx, 1);
    }
  }
}

I also try document:click

@HostListener('document:click', ['$event'])
    clickOut(event) {
        if (this.checkboxBox.nativeElement.contains(event.target)) {
            this.submit('this.selectedVal')
        }
     }

but with this, if I click on any other button or menu item, this.submit() is not triggered correctly

Cannot destructure property ‘data’ of ‘(intermediate value)’ as it is undefined error in Next JS & Graph QL

I’m trying to achieve a Apollo request to SpaceX api. But getting a ​500 (Internal Server Error) and also at getStaticProps. I don’t know if it’s a syntax issue or some error in my method of usage.

Note: API is used in postman and it works fine there.

Please help me. Thank you !

  import { ApolloClient, InMemoryCache, gql, ApolloError } from "@apollo/client";
  import Head from "next/head";
   import Image from "next/image";
  import styles from "../styles/Home.module.css";

   export default function Home({ launches }) {
  console.log(launches, "data");

UI layer as usual from Next JS

  return (
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className={styles.main}>
        <h1 className={styles.title}>
          Welcome to <a href="https://nextjs.org">Next.js!</a>
        </h1>

        <p className={styles.description}>
          Get started by editing{" "}
          <code className={styles.code}>pages/index.js</code>
        </p>

        <div className={styles.grid}>
          <a href="https://nextjs.org/docs" className={styles.card}>
            <h2>Documentation &rarr;</h2>
            <p>Find in-depth information about Next.js features and API.</p>
          </a>

          <a href="https://nextjs.org/learn" className={styles.card}>
            <h2>Learn &rarr;</h2>
            <p>Learn about Next.js in an interactive course with quizzes!</p>
          </a>

          <a
            href="https://github.com/vercel/next.js/tree/canary/examples"
            className={styles.card}
          >
            <h2>Examples &rarr;</h2>
            <p>Discover and deploy boilerplate example Next.js projects.</p>
          </a>

          <a
            href="https://vercel.com/new?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
            className={styles.card}
          >
            <h2>Deploy &rarr;</h2>
            <p>
              Instantly deploy your Next.js site to a public URL with Vercel.
            </p>
          </a>
        </div>
      </main>

      <footer className={styles.footer}>
        <a
          href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
          target="_blank"
          rel="noopener noreferrer"
        >
          Powered by{" "}
          <span className={styles.logo}>
            <Image src="/vercel.svg" alt="Vercel Logo" width={72} height={16} />
          </span>
        </a>
      </footer>
    </div>
  );
}

export async function getStaticProps() {
  console.log("ran func data from spacex");

  const client = new ApolloClient({
    uri: "https://api.spacex.land/graphql/",
    cache: new InMemoryCache(),
  });

  const { data } = await client
    .query({
      query: gql`{
          launchesPast(limit: 1) {
            mission_name
            launch_date_local
            launch_site {
              site_name_long
            }
            links {
              article_link
              video_link
            }
            rocket {
              rocket_name
              first_stage {
                cores {
                  flight
                  core {
                    reuse_count
                    status
                  }
                }
              }
              second_stage {
                payloads {
                  payload_type
                  payload_mass_kg
                  payload_mass_lbs
                }
              }
            }
            ships {
              name
              home_port
              image
            }
          }
        }
      `,
    })
    .then((res) => console.log(res))
    .catch((err) => console.log(err, "error on your side"));

  console.log("ran func data from spacex");

  return {
    props: {
      launches: data
    },
  };
}

Trying to use useRef to run a function on a generated item in React/Remix/Prisma

I’ve gone through multiple useRef/useEffect instructions but I just can’t seem to make it work here.

The code workflow here is: Remix/React, get data from database, display data, turn data into a ticker that can be updated

If anyone could point out any glaring errors they see in this code as to why the useEffect hook isn’t firing, or why the useRef hook can never find the {listRef} within the , I would love to know.

import { Links, redirect, useLoaderData, Outlet } from 'remix'
import { db } from '~/utils/db.server'
import { getUser } from '~/utils/session.server'
import { ReactSortable } from "react-sortablejs"
import { useState, useRef, useEffect } from 'react'
import tickerStylesUrl from '~/styles/tickerDisplay.css'

export const links = () => [{ rel: 'stylesheet', href: tickerStylesUrl }]

export const loader = async ({ request, params }) => {
  
  const user = await getUser(request)
  const ticker = await db.ticker.findUnique({
    where: { id: params.tickerId },
    include: {
      headlines: true,
    },
  })
  if (!ticker) throw new Error('Ticker not found')

  const data = { ticker, user }
  return data
}

export const action = async ({ request, params }) => {

}
// The ticker function displays the items without styling, so it finds the database perfectly and can get the data
function displayTicker() {
  const { ticker, user } = useLoaderData()

  const headlines = ticker.headlines
  const tickerParentStyle = {
    width: "1920px",
    height: "1080px",
    position: "relative",
    backgroundColor: "black"
  }
  const tickerStyle = {
    position: "absolute",
    padding: "0",
    bottom: "0",
    color: `${ticker.fontColor}`,
    backgroundColor: `${ticker.backgroundColor}`,
    fontFamily: `${ticker.font}`,
    fontSize: "2em",
  }
  const tickerHeadlineStyle = {
    margin: "auto",
    height: "50%",
  }

  // So begins the found ticker code I had hoped to integrate
  // Source: https://www.w3docs.com/tools/code-editor/2123
  function scrollTicker() {

    const marquee = listRef.current.querySelectorAll('.tickerHeadlines');
    let speed = 4;
    let lastScrollPos = 0;
    let timer;
    marquee.forEach(function (el) {
      const container = el.querySelector('.headlineItem');
      const content = el.querySelector('.headlineItem > *');
      //Get total width
      const elWidth = content.offsetWidth;
      //Duplicate content
      let clone = content.cloneNode(true);
      container.appendChild(clone);
      let progress = 1;
      function loop() {
        progress = progress - speed;
        if (progress <= elWidth * -1) {
          progress = 0;
        }
        container.style.transform = 'translateX(' + progress + 'px)';
        container.style.transform += 'skewX(' + speed * 0.4 + 'deg)';
        window.requestAnimationFrame(loop);
      }
      loop();
    });
    window.addEventListener('scroll', function () {
      const maxScrollValue = 12;
      const newScrollPos = window.scrollY;
      let scrollValue = newScrollPos - lastScrollPos;
      if (scrollValue > maxScrollValue) scrollValue = maxScrollValue;
      else if (scrollValue < -maxScrollValue) scrollValue = -maxScrollValue;
      speed = scrollValue;
      clearTimeout(timer);
      timer = setTimeout(handleSpeedClear, 10);
    });
    function handleSpeedClear() {
      speed = 4;
    }
  }

  const listRef = useRef()
  console.log("listRef: " + JSON.stringify(listRef))
  // This console appears everytime, but is always empty, presumably because DOM has just rendered

  useEffect(() => {
    console.log("useEffect fired")
    // This console NEVER fires, sadly. I thought this would happen ONCE rendered
  }, [listRef]);

  return (
    <>
      <Links />
      <div style={tickerParentStyle}>
        <div style={tickerStyle}>
          <div key={ticker.id} style={tickerHeadlineStyle} class="tickerWrapper">
            <ul className="tickerHeadlines" ref={listRef} style={{ margin: "10px 0 10px 0" }} >
              {/* Hoping to map through the ticker items here, and have them displayed in a list, which would then be manipulated by the useRef/useEffect hook */}
              {headlines.map((headline) => (
                <>
                  <li class="headlineItem" key={headline.id}>
                    <span>
                      {headline.content} {ticker.seperator}
                    </span>
                  </li>
                </>
              ))}
              {scrollTicker()}
            </ul>
          </div>
        </div>
      </div>
    </>
  )
}

export default displayTicker

As always, any help is appreciated.

Programatically redirect user to another page ReactJS

I want to programatically redirect the user to a loading page while I await for a response from the server api. I’m trying to do this inside a class component

The code I’ve got looks more or less like this:

class App extends Component { 
    constructor(props){
        super(props);
    }

    handleSubmit = () => {
      useNavigate("/loading")
      }
    }
    render() { 
      return ( 
        <div>
          <button onClick={this.handleSubmit}>
            Upload! 
          </button>
        </div>
      ); 
    } 
  }

export default App;

The thing is that nothing happens when i click the “Upload!” button. I’ve read that useNavigate cannot be used inside a class component but I’m not sure how I could implement this differently.

I guess my question is, how can I use useNavigate inside a class component?

Minus-sign in regular expression in js is not allowed, though regular expression is fine

I want to allow user to input decimal value with maximim 9 integer digits, and maximum 2 decimals after dot. But also this value can be negative, with “-” sign. Evereything is ok, except this minus sign. Though sites like “regexp.online” show that my regular expression is fine, it does no work in js+jquery. Minus sign fails the checking. See:

<input name="price" style="height:20px;">

$('[name="price"]').bind("change keyup input", function() {
  pricecheck = '^(\-)?\d{1,9}(\.\d{0,2})?$';
  var regex = new RegExp(pricecheck, 'g');
  if (!regex.test(this.value)) {
    console.log('not in regex');
    this.value = this.value.slice(0, -1);
  }
});

And fiddle – https://jsfiddle.net/obc6qptf/

I tried this “minus” without backslashes – the same result. What is wrong?