How can I draw this chart with chart.js or google chart

How can I draw this chart with chart.js or google chart or any javascript framework.

I want to plot exactely like this :
enter image description here

I need to draw the line with the same X point,
But I can’t find any option can rotate the green line to vertical.

<!DOCTYPE html>
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<body>
<canvas id="myChart" style="width:100%;max-width:400px"></canvas>

<script>
var xValues = [0, 1, 2, 3, 4];

new Chart("myChart", {
  type: "line",
  data: {
    labels: xValues,
    datasets: [
    { 
      data: [0, 0.8, 3.2, 4.8, 5],
      borderColor: "red",
      fill: false,
      pointRadius: 1,
    }, { 
      data: [5, 4.8, 3.2, 0.8, 0],
      borderColor: "blue",
      fill: false,
      pointRadius: 1,
    },{
      data: [4,4],
      borderColor: "green",
      fill: false,
      pointRadius: 5,
    }]
  },
  options: {
    legend: {display: false},
    scales: {
      y: {
        beginAtZero: true
      },
      x: {
        beginAtZero: true
      },
      xAxes: [{
        ticks: {
          display: false
        }
      }],
      yAxes: [{
        ticks: {
          display: false
        }
      }]
    }
  }
});
</script>

How do I wrap EventTarget.addEventListener() so it can be used as an async iterator?

How does one use async iterators to consume events coming from a callback, like EventTarget.addEventListener and similar?

As an example, the following code does not exist but illustrates what I’d like to see:

for await (const event of onevent('scroll')) {
  console.log(event)
  break // cleanup
}

When attempting to create this onevent wrapper function, I run into basic issues – like yield not being available in the callback (makes sense) and no obvious way to remove listeners from when the listener breaks a loop.

async function *onevent(eventName) {
  const changeEvent = (event) => {
    yield event // yield cannot be used in this scope
  }

   window.addEventListener(eventName, changeEvent)

   // There doesn't seem to be a way to cleanup on loop "break"
   // window.removeEventListener(eventName, changeEvent)
}

for await (const event of onevent('scroll')) {
  console.log(event)
  break // cleanup?
}

Or am I misunderstanding the purpose of async iterators?

Run javascript on a specific execution context

enter image description hereI am trying to write a javascript that renames the text of a button on a website.

`setInterval(function() {

    let Bestellbutton2 = document.getElementsByClassName("_7tbHf _3LH_L");
   
    Bestellbutton2[0].innerHTML = "Anfrage absenden";}, 500);`

The problem I’m having seems to be the execution context. This code only works if I inspect the element first, or if I manually change the execution context from above to the selected one (checkout).

How can I solve this problem?

This code works only if i inspect element first, or if manually change execution context form top to the one selected (chekcout).

Is it correct to write a code to pass data to child component in vue.js?

I have a question.
I use vue.js with defineComponent.

I want to get data and pass the data to child components but the data is undefined.

parent

<template>
  <Child :data="user"/>
  <div>{{ user.name }}</div> <!-- It works here -->
</template>

export default defineComponent({
  setup() {
    const user = ref({});
    const getData = () => {
      // takes 3 seconds
      user.value = data;
    }
    return {user}
  }
})

child

<template>
  <div>{{ user.name }}</div> <!-- TypeError Cannot read properties of undefined -->
</template>

export default defineComponent({
  props: {
    data: { type: Object },
  },
  setup(props) {
    const user = ref(props.data);
    return {user}
  }
})

If I use watch in child component, It works.
Is it correct to write a code like this?

child

export default defineComponent({
  props: {
    data: { type: Object },
  },
  setup(props) {
    const user = ref({});
    watch(props, (n, o) => user.value = props.data)
  }
})

Adobe Dreamweaver Change Javascript Version

I’m working with the newest Version of Dreamweaver.
I created a html file with corresponding css file and a javascript file. That worked fine but in my javascript file some things like let aren’t recognized by dreamweaver and are shown as an error.

The following code for example:

var questions = [{ id: 0, text: "Question 1" }];
var answers = [{ id: 0, text: "Answer 1", question: 0 }, { id: 1, text: "Answer 2", question: 0 }];

function getAnswers(question) {
    return answers.filter(x => x.question == question.id);
}

Shows following error for the x => x: ERROR: Parsing error: Unexpected token >.
I guess it has something to do with the javascript version dreamweaver is using.

How do I change that so that my code shows no error?

How handle error 404: Not Found from within a helper function in Node js express and go to 404 page

I have two Javascript helper function to fetch some data from a GraphQL endpoint and creates a url. This all works fine:

const getData = async (targetUrl: string) => {
  const options = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      query: GET_DATA,
      variables: {
        targetUrl,
      },
    }),
  };

  const response = await fetch(process.env.ENDPOINT, options);

  if (!response.ok) {
    throw new Error('Unable to parse json response');
  }

  const result = await response.json();

  if (result.errors?.length) {
    console.log('foo', result.errors);
    throw new Error('Something went wrong');
  }
  return result.data.page;
};

export default getData;

The small helper function which creates the url:

const getRedirectUrl = async (requestUrl: string) => {
  if (requestUrl.includes('/foo')) {
    const { content } = await getData(requestUrl);
    if (content.type === 'MyPage') {
      return `/my-page/?id=${content.id}`;
    }
  }
  return null;
};

export default getRedirectUrl;

Then in my server side route handler I use it like:

  if (redirectUrl) {
    res.redirect(redirectUrl);
    return;
  }

But when I request a non existing url (which contains /foo, I get a blank screen and it doesn’t go to 404 page. In terminal I get an error from getData() function:

Error: Something went wrong

When I inspect result.errors it gives:

[
  {
    message: '404: Not Found',
    extensions: {
      code: 'INTERNAL_SERVER_ERROR',
      serviceName: 'node',
      response: [Object],
      exception: [Object]
    }
  }
]

The same I see in GraphQL playground. The problem is that below query isn’t working because the targetUrl is not found.

query GetData($targetUrl: String!) {
    page (targetUrl: $targetUrl){
      content {
        ...on MyPage {
          id
          type
        }
      }
    }
  }

How to fix this? And how to somehow get out of the getData() function or go to 404 page?

OnMouse event happens only once

I insert selected text dynamically from a pdf to a textbox. I also create dynamic textboxes, in which 1st selected text is added to the 1st textbox with the page number of the pdf, for the next selection the mouse-up event is not fired.
I need to add the 2nd selected text to the newly added dynamic textbox and 3rd selected text to the 3rd textbox and so on.

I tried the below code, The pdf will be uploaded and viewed on the page on the left side(code not included).

var pageNumber = null;
const text       = '';
const selection  = '';
var highlightBtn = document.getElementById('highlight-btn1');

const myTextarea    = document.getElementById('copyText');
const myDynTextarea = document.getElementById('DTextBox');
const pageNo        = document.getElementById('pageNo');

document.addEventListener('mouseup', () => {
  document.getElementById('copyText').value = '';
  const selectedText = window.getSelection().toString();

  if ((selectedText !== '') && (myTextarea.value == '') && (pageNo.value == '')) {

    myTextarea.value += selectedText;
    pageNumber = PDFViewerApplication.pdfViewer.currentPageNumber;
    document.getElementById('pageNo').value = pageNumber;
    $('copyText').attr('disabled', true);
  } else {

    myDynTextarea.value += selectedText;
    pageNumber = PDFViewerApplication.pdfViewer.currentPageNumber;
    document.getElementById('pageNo').value = pageNumber;
  }
});


highlightBtn.addEventListener('click', () => {
  window.getSelection().getRangeAt(0).surroundContents(myTextarea);
  myTextarea.classList.add("highlightss");

});


//add button
$(function() {
  $("#btnAdd").bind("click", function() {
    var div = $("<tr />");
    div.html(GetDynamicTextBox(""));
    $("#TextBoxContainer").append(div);
  });
  $("body").on("click", ".remove", function() {
    $(this).closest("tr").remove();
  });
});

function GetDynamicTextBox(value) {
  return '<td><input  id="DTextBox" name = "DynamicTextBox"  type="text" style="width:100px;height:42px;" /></td>' + '<td><input type="text"  id="pageNo" size="10" /></td>' + '<td><input type="button" id="highlight-btn" size="10" value = "' + 'Highlight' + '" /></td>' + '<td><input type="button" id="highlight-btn1" size="10" value = "' + 'Highlight' + '" /></td>' + '<td><button type="button" class="btn btn-danger remove"><i class="glyphicon glyphicon-remove-sign"></i></button></td>'
}
#copyText,
#copyText1 {
  font-size : 18pt;
  height    : 42px;
  width     : 150px;
  }
#pageNo,
#pageNo1 {
  font-size : 18pt;
  height    : 42px;
  width     : 40px;
  }
#table {
  height : 100%;
  width  : 80%;
  }
#highlight-btn,
#highlight-btn1 {
  padding          : 15px 25px;
  font-size        : 12px;
  text-align       : center;
  cursor           : pointer;
  outline          : none;
  color            : #fff;
  background-color : #04AA6D;
  border           : none;
  border-radius    : 15px;
  box-shadow       : 0 5px #999;
  }
.highlightss {
  background-color : yellow;
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table">
  @*
  <tbody id="TextBoxContainer"></tbody>*@
  <tr>
    <td>
      <label for="pageNo">PageNo:</label>
      <input type="text" id="pageNo" size="10" />
    </td>
    <td>
      <button type="button" id="highlight-btn" size="10">Highlight</button>
    </td>
    <td>

      <button type="button" id="highlight-btn1" size="10">Highlight</button>
    </td>
    <td>
      <button id="btnAdd" type="button" class="btn btn-primary" data-toggle="tooltip" data-original-title="Add more controls"><i class="glyphicon glyphicon-plus-sign"></i>&nbsp; Add&nbsp;</button>

    </td>
    <td id="TextBoxContainer"></td>
  </tr>
</table>

JS regex to find the first number at the beginning of a string

I need to perform a very simple task in JS, but coming from PHP, it’s unknown territory for me…

So I need to extract the first number from a string. The string can be one of these:

180gr.
140gr. - 200gr.
unlimited food

So, in the above cases I want to extract 180 for the first string, 140 for the second, and an empty string for the third one.

In PHP, the command to do that would be preg_match( '/^d*/', $string, $matches );.

Can someone help me figure out how to write this in JS?

Open AI on Node – Configuration is not a constructor

I have nearly copy-pasted the example from open ai’s node documentation. I am putting this in my Next.js project. I get the following error: TypeError: openai__WEBPACK_IMPORTED_MODULE_1__.Configuration is not a constructor

import { Configuration, OpenAIApi } from "openai";

const configuration = new Configuration({
organization: process.env.OPEN_ORG_ID,
apiKey: process.env.OPENAI_API_KEY,
});

const openai = new OpenAIApi(configuration);

export async function testOpenAi() {
openai
    .createCompletion({
    model: "text-davinci-003",
    prompt: "Say this is a test",
    max_tokens: 7,
    temperature: 0,
    })
    .then((response) => {
    // console.log(response);
    })
    .catch((err) => {
    console.error(err);
    });
}

After doing npm install openai I still get this error. What am I missing?

How is this 30 and not 40 [closed]

function meal(animal) {
  animal.food = animal.food + 10;
}

var dog = {
  food: 10
};

meal(dog);
meal(dog);

console.log(dog.food);

my question is when you first run the Code
the first function runs first which is
meal(dog);
0=10+10
which would be
20=10+10

when the second function is called it should be

20=10+10
which should be
40=10+10

yet answer is 30

I was expecting 40 not 30
if i can see step by step on whats going on

Next.js sever not starting correctly

When I run yarn dev in my nextjs project, the server does not start. I don’t know why is it happening. I am attaching the screenshot of the terminal below.

enter image description here

I was adding a package through yarn add and I terminated the process when it was linking dependencies. After that, when I am trying to run my development server, I get the same thing all the time.

Please help me fix this problem.

PS: I have deleted the yarn.lock file and node_modules and reinstalled the packages but getting the same thing as shown in the above screenshot. I have also cleared the cache but nothing works.

I tried to start the server on another system and the server successfully started on that system but it is not starting on my system.

Thanks in advance for your help.

I tried to start the development server but it doesn’t seem to start correctly.