Issue with user input

I am currently creating a simple calculator program and have run across an issue with this line of code:

    var n1 = readInt("Enter the First Number in Equation ");
    var op1 = readLine("Enter the first operator ]");
    var n2 = readInt("Enter the Second Number in the Equation ");
    var op2 = readLine("Enter the Second Operator ");
    var n3 = readInt("Enter the Third Number in the Equation ");

The application gives me a “SyntaxError: Unexpected end of input” and cites the line right after the previously shown code. Is there any issues with the given code? Or am I missing something else?

javascript date change yyyymmdd

    var d = new Date();
    var year = d.getFullYear();
    var month = d.getMonth() + 1;
    var date = d.getDate();

    today = new Date(year,month-1,date).toLocaleDateString();
    threeD = new Date(year,month-1,date-3).toLocaleDateString();
    sixD = new Date(year,month-1,date-6).toLocaleDateString();


    document.write('today '+today+" <br/>"); // today 2022. 5. 3.


    document.write('before 3day : ' +threeD+" <br/>"); // before 3day : 2022. 4. 30.


    document.write('before 3day : ' +sixD+" <br/>"); // before 3day : 2022. 4. 27.

I want to change from 2022. 5. 3. to 202220503 and threeD,sixD yyyymmdd like this.

How can I make a jQuery selector ignore sections of text it’s already modified?

I’m working on a website with a built-in wiki of sorts — on page load, all the paragraphs on a page are parsed using a jQuery selector, and any occurrence of a wiki entry in the text is converted to a link. For example…

<p>Blah blah blah lung blah blah blah.

…would become…

<p>Blah blah blah <a data-reference="lung" onclick="getModalContent(this)">lung</a> blah blah blah.

So far, this has worked pretty well, but I’ve recently run into an issue: some of the terms being parsed for now contain shorter terms. To continue with the lung example, imagine the list of terms to make links for contained both “lung” and “lung cancer,” and I needed any occurrence of the full phrase “lung cancer” to direct users to the “lung cancer” modal.

Unfortunately, I can’t figure out how to make that work. This is the code I’m currently using to parse the paragraphs and generate links:

function populateModalLinks() {
    const unsortedReferenceItems = localStorage.getItem("referenceTerms").split(",");
    const referenceItems = unsortedReferenceItems.sort((a,b) => b.length - a.length);
    console.log(referenceItems);

    // Here's an idea to ensure there's never a mixup:
    // 1. Sort all reference terms by length, longer to shorter (done).
    // 2. On page load, iterate over the list, only turning the *first* occurrence into a link.
    
    barriers = [".", ",", "!", "?", "…", " "];
    for (i = 0; i < barriers.length; i++) {
        for (j = 0; j < referenceItems.length; j++) {
            $("p:contains('" + referenceItems[j] + barriers[i] + "')").html(function(_, html) {
                combo = referenceItems[j] + barriers[i];
                return html.replace(combo, '<a data-reference="' + referenceItems[j] + '" onclick="getModalContent(this)">' + referenceItems[j] + '</a>' + barriers[i]);
            });

            $(".contentsText p").find("a").contents().unwrap();
        }
    }
}

populateModalLinks();

Crude, I’ll admit, but it’s mostly gotten the job done until now. As you might be able to tell from that comment towards the beginning, I initially thought that sorting the reference terms from longest to shortest would prevent this from being an issue — if the parser got to “lung cancer” first, it would make any occurrences of that phrase into links before the loop for “lung” ever got the chance.

As it stands, however, the parser doesn’t recognize when there’s already a link somewhere, so it just tears its way through the existing “lung cancer” link and tries to shove a “lung” link in there. In addition to not being the intended functionality, this also screws up the HTML so bad that the incomplete tags spill over into the rendered text (see screenshot below).

broken HTML generated by parser

I’ve tried several extensions of the selector in the code above, such as this fairly complicated one…

$("p:contains('" + referenceItems[j] + barriers[i] + "')").not($("p a:contains('" + referenceItems[j] + barriers[i] + "')")).html(function (_, html) {

…but none of them have gotten the job done either. I thought I had a pretty decent understanding of how jQuery selectors worked, but can’t seem to figure this out, and no other Stack Overflow questions seem to cover this exact problem. Any help would be greatly appreciated.

How to pass variables from Azure Pipeline to JavaScript?

I’m attempting to run an Azure Pipeline, with some environment variables defined in the pipeline itself, and I am using the Maven Build task to build my project with Maven to launch various tests. A JS file automatically runs before each test, and I’m supposed to configure these variables in this file, which would make them available to use in the tests themselves. Currently, I have something like this:

# azure-pipelines.yml

trigger:
- none

pool:
  vmImage: ubuntu-latest

variables:
- name: user_secret
  value: "foo"

steps:

 - task: Maven@3
   inputs:
     mavenPomFile: 'pom.xml'
     goals: test
     publishJUnitResults: true
     testResultsFiles: '**/surefire-reports/TEST-*.xml'
     javaHomeOption: 'JDKVersion'
     mavenVersionOption: 'Default'
     mavenAuthenticateFeed: false
     effectivePomSkip: false
     sonarQubeRunAnalysis: false
// config.js

function fn(){
    return  {
        secret: user_secret
    };
}

The error I get is "user_secret" is not defined

I am being told I can debug it locally because the pipeline is providing the values as environment variables, and that I should be able to validate that locally by setting the variables when I run my code. Unfortunately, I can’t figure out how to do it.

Similar to the above example, I also tried to get the variable process.env.user_secret, but this didn’t work for me either.

How can I access Azure variables in my code?

Arc.js not drawing line in OpenLayers 6

my code is

    const testSource = new VectorSource({
      loader: () => {
        const start2 = { x: 43.449928, y: 39.956589 };
        const end2 = { x: 55.606186, y: 49.278728 };

        const generator = new arc.GreatCircle(start2, end2);


        const line = generator.Arc(100, { offset: 10 });
        const features = [];
        line.geometries.forEach((geometry) => {
          const line = new LineString(geometry.coords);
          line.transform('EPSG:4326', 'EPSG:3857');
          const style = new Style({
            stroke: new Stroke({
              color: '#EAE911',
              width: 2,
            }),
          });

          features.push(new Feature({ geometry: line }));

          features.forEach((feature) => {
            feature.setStyle(style);
            testSource.addFeature(feature);
          });
        });
      },
    });

    const vectorLineLayer = new VectorLayer({
      className: 'drawing-layer',
      source: testSource,
    });
    mapReference.addLayer(vectorLineLayer);

I can see that the source exists inside my layer but it will not draw no matter what I do, any ideas? It’s not a zIndex issue because I have my vectorLayer CSS set zIndex.

Discord.js command timeout

I have a command where it asks a question and gives different responses based on the answer, and that part works, but the command doest end, meaning that if you reply to a new instance of the command, the first instance and the new instance will reply. I tried different timeout functions but nothing worked.
here’s the code:

module.exports = {
name: 'test',
description: "test comand",
execute(message, args, Discord) {
    message.channel.send("Do you want to test this command?n `Yes`, `No` or `Mayhaps`")
    console.log(message.author.id)
    const collector = new Discord.MessageCollector(message.channel, m => m.author.id === member, { time: 10000 });
    collector.on('collect', message => {
        if (message.content.toUpperCase() == "YES") {
            message.channel.send("Let's Go! It worked!");
    } else if (message.content.toUpperCase() == "NO") {
            message.channel.send( "Task failed successfully.");
     } else if (message.content.toUpperCase() == "MAYHAPS") {
            message.channel.send("ERROR: IT WORKED ANYWAY");
        }
})
}

}

Some Prisma Model @@map not generating

I have a few models in my schema.prisma file that are not generating with their @@map for use in the client.

model ContentFilter {
  id                Int           @id @default(autoincrement())
  blurriness        Float?        @default(0.3)
  adult             Float?        @default(0.5)
  medical           Float?        @default(0.8)
  violence          Float?        @default(0.5)
  racy              Float?        @default(0.5)
  party_settings_id Int           @unique
  party_settings    PartySettings @relation(fields: [party_settings_id], references: [id])

  @@map("contentfilter")
}

model PartySettings {
  id                 Int            @id @default(autoincrement())
  start              DateTime?      @default(now())
  end                DateTime?      @default(now())
  require_location   Boolean?       @default(false)
  require_name       Boolean?       @default(true)
  allow_comments     Boolean?       @default(true)
  allow_likes        Boolean?       @default(true)
  allow_before_party Boolean?       @default(false)
  party_id           Int            @unique
  party              Party          @relation(fields: [party_id], references: [id])
  content_filter     ContentFilter?

  @@map("partysettings")
}

model Party {
  id          Int            @id @default(autoincrement())
  name        String
  hash        String         @unique
  description String
  user_id     Int
  user        User           @relation(fields: [user_id], references: [id])
  images      Image[]
  order       Order?
  settings    PartySettings?

  @@map("party")
}

the rest of my models are available in the client by referencing them with prisma.mappedname
such as prisma.party (from the example above) that table is exposed and available within the client. But both the partysettings and contentfilter is not avialable. I’ve ran the migrate and generate commands many times as well as deleted my database and reran migrate and generate.
Could anyone help me understand what i’m doing so different in these two tables?

Bypass a JavaScript timer

I’m trying to bypass a timer on a website that makes me wait 20 seconds until I can skip to the next page and it is a total pain, so I’m wondering if there is a way to do that. I have little to no coding knowledge so it would be great if anyone could help me out. Let me know if I’m not providing enough code.

this is what the inspect element says when ever I can skip to the next page

this is what it says when the timer is counting down

displaying data on heatmap

Currently I am trying to find a way to display timeseries data through a heatmap via highcharts, and I was wondering if there is a way to plot the data on this manner without resorting to using CSVs. The link below is the kind of chart I would like to reproduce:

https://www.highcharts.com/demo/heatmap-canvas

Currently this is my attempt at this, but for some reason the data is not plotting at all…

Highcharts.chart('container', {

    data: {
        //csv: document.getElementById('csv').innerHTML
    },

    chart: {
        type: 'heatmap'
    },

    boost: {
        useGPUTranslations: true
    },

    title: {
        text: 'Highcharts heat map',
        align: 'left',
        x: 40
    },

    subtitle: {
        text: 'Temperature variation by day and hour through 2017',
        align: 'left',
        x: 40
    },

    xAxis: {
        type: 'datetime',
        min: Date.UTC(2017, 0, 1),
        max: Date.UTC(2017, 0, 8, 23, 59, 59),
        labels: {
            align: 'left',
            x: 5,
            y: 14,
            format: '{value:%B}' // long month
        },
        showLastLabel: false,
        tickLength: 16
    },

    yAxis: {
        title: {
            text: null
        },
        labels: {
            format: '{value}:00'
        },
        minPadding: 0,
        maxPadding: 0,
        startOnTick: false,
        endOnTick: false,
        tickPositions: [0, 6, 12, 18, 24],
        tickWidth: 1,
        min: 0,
        max: 23,
        reversed: true
    },

    colorAxis: {
        stops: [
            [0, '#3060cf'],
            [0.5, '#fffbbc'],
            [0.9, '#c4463a'],
            [1, '#c4463a']
        ],
        min: -15,
        max: 25,
        startOnTick: false,
        endOnTick: false,
        labels: {
            format: '{value}℃'
        }
    },

    series: [{
          data: [[2017-01-01,0,2.7],[2017-01-02,0,1.7],[2017-01-03,0,-0.7],[2017-01-04,0,2.5],[2017-01-05,0,-6.6],[2017-01-06,0,-9.2],[2017-01-07,0,1.7],[2017-01-08,0,-1.6]],
        boostThreshold: 100,
        borderWidth: 0,
        nullColor: '#EFEFEF',
        colsize: 24 * 36e5, // one day
        tooltip: {
            headerFormat: 'Temperature<br/>',
            pointFormat: '{point.x:%e %b, %Y} {point.y}:00: <b>{point.value} ℃</b>'
        },
        turboThreshold: Number.MAX_VALUE // #3404, remove after 4.0.5 release
    }]

});

Automatically scroll to a grid cell under cursor during zoom in/out

I have a grid of cells which can be zoom in/out via mouse wheel by changing cells size.
It works ok, except it doesn’t “follow” grid position on the screen when zooming in/out.

Here is an example snippet, if you position cursor on cell 13 and start zoom w/mouse wheel, the cell moves away from the cursor.

let cols = 5,
    rows = 5,
    zoom = 12,
    zoomMin = 1,
    zoomMax = 25,
    mouseDown,
    clientX,
    clientY;

for(let i = 0, cell = document.createElement("div"); i < cols*rows; i++)
{
  cell.textContent = i + 1;
  table.appendChild(cell);
  cell = cell.cloneNode(false);
}

document.body.style.setProperty("--cols", cols);
document.body.style.setProperty("--rows", rows);
setZoom(zoom);


table.addEventListener("wheel", e =>
{
  e.preventDefault();
  e.stopPropagation();
  zoom = Math.min(zoomMax, Math.max(zoomMin, zoom + (e.deltaY < 0 ? 1 : -1)));
  setZoom(zoom);
}, {passive:false});

table.addEventListener("mousedown", e =>
{
  e.preventDefault();
  table.classList.add("drag");
  mouseDown = e;
  ({clientX, clientY} = e);
  window.addEventListener("mouseup", onMouseUp);
  window.addEventListener("mousemove", onMouseMove);
});

function onMouseMove (e)
{
  if (e.clientX == clientX && e.clientY == clientY)
    return;

  table.scrollBy(clientX - e.clientX, clientY - e.clientY);
  ({clientX, clientY} = e);
}

function onMouseUp(e)
{
  table.classList.remove("drag");
  window.removeEventListener("mouseup", onMouseUp);
  window.removeEventListener("mousemove", onMouseMove);
}

function setZoom(z)
{
  document.body.style.setProperty("--zoom", ((z/10*z/10) + 1) +"em");
}
#table
{
  display: inline-grid;
  grid-template-columns: repeat(var(--cols), 1fr);
  text-align: center;
  max-width: calc(2em * var(--cols) + 0.4em);
  max-height: calc(2em * var(--rows) + 0.4em);
  overflow: auto;
  padding: 1px 0 0 1px;
  cursor: grab;
}

#table.drag
{
  cursor: grabbing;
}

#table > div
{
  border: 1px solid black;
  margin-left: -1px;
  margin-top: -1px;
  width: var(--zoom);
  height: var(--zoom);
  line-height: var(--zoom);
  padding: 0.5em;
}
<div id="table"></div>

My current thought of steps needed to follow cell under cursor during zoom:

  1. get cell under cursor
  2. get rectangle of the cell
  3. get position of the cell relative to top-left corner of the table
  4. get position of the cursor relative to top-left corner of the cell (in percent)
  5. get position of the cursor relative to top-left corner of the table (in percent)
  6. change zoom
  7. get new position of the cell relative to top-left corner of the table
  8. get new position of the cursor relative to top-left corner of the table
  9. based on percent from step 5, get new cursor position relative to top-left corner of the table
  10. based on percent from step 4, get new top-left corner of the cell relative to the cursor
  11. calculate needed scroll position of the cell based on step 3
  12. scroll table to result of step 11

This is quite complicated, and I hope there is a better/simpler formula for this.

Any tips are appreciated

Using a variable in javascript to find a certain path in a json file [duplicate]

Right now, I have this:

Javascript

    function submit() {
    var inputboxvalue = document.getElementById("airport").value

    fetch("./names.json")
    .then(response => {
       return response.json();
    })
    .then(jsondata => 
      console.log(jsondata.inputboxvalue)
    );
    }

HTML

<input class="airport" id="airport" type="search" placeholder="klax" maxlength="4" onkeypress="return (event.charCode > 64 &amp;&amp; 
event.charCode < 91) || (event.charCode > 96 &amp;&amp; event.charCode < 123)" on>
<button class="submit" id="submit" onclick="submit()">Find</button>

JSON

{
  "lax": "klax",
  "klax": "klax"
}

How can I add the variable inputboxvalue to add itself onto the json path.

Using DOM event to change colors in a constuctor

The basic idea is that I want the c.strokeStyle to change to a random color on a keydown event.

The keydown is working and logs to the console without issue but I cant figure out a way to select that specific line c.strokeStyle in the constuctor and change it using a conditional statement in the event listener.

All the classes are carbon copies of eachother so if it works for one it’ll work for all.

Is it even possible? Link to Git Repo

How to send messages from server to client with readable stream in express? [duplicate]

How to send messages from server to client with readable stream with express? I don’t want to read a file or anything, I just want to send messages and I do not want to use socket.io.

Appreciate your help in advance.

My server code:

app.post('/units.html', function(req, res, next) {

  res.write("hello once")
  res.write("hello twice");
  res.end()
  
});

My Client side code

function fetcher() {
  console.log("called fetcher")
    fetch('/units.html',
     {
       method: "POST",
       body: JSON.stringify({
         "NAME": document.getElementById("NAME").value,
       }),
       //headers: { "Content-Type": "application/json" }
       }
   )

   .then(function(response) {
     console.log("inside middle function")
     return response.text();
   })
   .then(function(data) {
    console.log(data)
   

   });
 }

Trigger function from external js script into Vue

There is a script that is loaded into my Vue app inside the mounted hook, by this way:

let recaptchaScript = document.createElement("script");
recaptchaScript.setAttribute("src", "https://sso.****.com.co/v3/****.main.js");
document.body.append(recaptchaScript);

The script is loaded, but there is a function that is injected into the window object.

Currently when I need to use that function, I do this:

mounted() {
let recaptchaScript = document.createElement("script");
recaptchaScript.setAttribute("src", process.env.VUE_APP_TAPIT_SSO_URL);
document.body.append(recaptchaScript);
    this.$nextTick(() => {
        setTimeout(() => {
            window.ssoApp.configApp(TAPIT_SSO_CONFIG);
        }, 1500);

I want to get rid the setTimeOut, but I haven’t figured it out yet how to wait for the script executes and inject that object of functions (ssoApp) into the window object without using a timer. Is there any way to do this? I’ve tried almost everything.