How to validate that an array with dates is arranged newer to older and vice versa

I am still very much a newbie to JS and had a question for which I cannot find an answer for.

I have an array such as:

[
                2000-03-22 12:00 AM
                2000-03-21 12:00 AM
                2000-03-17 12:00 AM
                2000-03-17 12:00 AM
                2000-03-15 12:00 AM
                2000-03-15 12:00 AM
                2000-03-15 12:00 AM
                2000-03-11 12:00 AM
]

The actual array is much longer. I need to do a for loop (if best) to check if the dates are arranged in a newer to older or older to newer manner. I don’t need to sort them using JS, I already have the list sorted by default.

I have done validations between two dates before, however, I am not sure how to approach an entire array of dates.

Thank you in advance!

TypeScript custom function not recognized in shared utility class

I have a TypeScript class implements an Interface with the following declarations. In the class I imported the .js at the beginning of the class file and implemented every function. All works fine, until I added a new function in the Interface and implemented the new function in the class. When the project is published to an IIS host, the Edge browser doesn’t recognize the additional function until I compiled the project several times. However, the new function is immediately recognized at compile time. Does any know why?

export interface ICommonUtility {
  isDate(aDate: Date): boolean;
  isEmpty($this: any): boolean;
  isTheSame($this: any, oldValue: string, currentValue: string): boolean;
  getCRUD($this: any, oldValue: string, currentValue: string): string;
  getControlValue($this: any): number;
  resetControlValue($this: any, newValue: string)
  getTextPixels(someText: string, font: any);
  breakLongSentence(thisSelectElement);
}
/// <reference path="../../node_modules/@types/jquery/jquery.d.ts" />

import { ICommonUtility } from "../appModels/ICommonUtility.js";

export class Utility implements ICommonUtility {
  isDate(aDate: Date): boolean {
   
  }

  isEmpty($this: any): boolean {
    
  }

  isTheSame($this: any, oldValue: string, currentValue: string): boolean {

  }

  getCRUD($this: any, oldValue: string, currentValue: string): string {
    
  }

  getControlValue($thisControl: any, valueSource: string = 'other'): any {
 
  }

  resetControlValue($thisControl: any, newValue: string) {

}

  getTextPixels(someText: string, font: any) {

  }

  breakLongSentence(thisSelectElement: any) {

  }
}

React Javascript: Rendering user data on screen and inserting data into function

I am building a letter interval application. Basically, I want users to be able to type in letters within an input element, and have that data be used in a function that ive built and then have that data rendered in an intervel. I have the user data rendering on the screen in a H1 tag no problem, whoever, I am having trouble inserting the user data into the interval function which ultimately renders interval letters on the screen. Any help will be greatly appreciated!!

This is the code:

import React, { useState } from "react";
import Chalkboard from "../chalkboard/chalkboard";
import StartStop from "../startStopButtons/startStopButtons";

function IntervalFunction() {
  var _timer;
  var vowels = "aeiouy".split("");

  // Function that starts the letter interval
  const startFunction = () => {
    var allLetters = "abcdefghijklmnopqrstuvwxyz".split("");
    getRandom(allLetters);
  };

  // Stops startFunction
  const stopButton = () => {
    clearTimeout(_timer);
    clearTimeout(getRandom);
  };

  // letter interval function
  function getRandom(letters) {
    var randomSet = letters[Math.floor(Math.random() * letters.length)];
    console.log("set random", randomSet);
    document.getElementById("demo3").innerHTML = randomSet;
    _timer = setTimeout(() => getRandom(letters), 1000);
  }

  
  //state function that renders user input on screen
  const [data, setData] = useState(null);
  function getData(e) {
    setData(e.target.value);
  }

  function handleSubmit(e) {
    e.preventDefault();
  }
  //function that grabs user input and insert into function
  const inputValue = () => {
    var userSet = { getData };
    getRandom(userSet);
  };

  return (
    <div>
      <h1>Letter Interval Application</h1>

      <Chalkboard />

      <h1>Your custom letter set:</h1>
      <h1>{data}</h1>
      <form onSubmit={handleSubmit}>
        <input onChange={getData} className="inputField" type="text" placeholder="Enter letters here, separate by commas" />
        <button onClick={startFunction} onClick={inputValue} value="Start">
          Start
        </button>
      </form>

      <StartStop clickStop={stopButton} />

    </div>
  );
}

export default IntervalFunction;

Thanks so much for reading.

hide privateKey from nodeJS on Heroku?

I’ve integrate BrainTree Drop-in UI for checkout payment in nodeJS. It’s only a demonstration that I needed to create. I had no issues, it was easy enough. The only thing that I would like to do is to hide merchantId, publicKey and privateKey from the code. I would like to add them directly in Heroku Config Vars. I know how to do all this in Python, but I have no idea how to do it in JavaScript. I show you the code changing the keys:

const express = require('express');
const router = express.Router();
const braintree = require('braintree');

router.post('/', (req, res, next) => {
  const gateway = new braintree.BraintreeGateway({
    environment: braintree.Environment.Sandbox,
    // Use your own credentials from the sandbox Control Panel here
    merchantId: 'h43jgh5g3gl4543',
    publicKey: 'hj45j4h5lh45hl4h5l',
    privateKey: 'b5hbhbb45bhbh4kfndnfdkkfnd'
  });

  // Use the payment method nonce here
  const nonceFromTheClient = req.body.paymentMethodNonce;
  // Create a new transaction for $10
  const newTransaction = gateway.transaction.sale({
    amount: '10.00',
    paymentMethodNonce: nonceFromTheClient,
    options: {
      // This option requests the funds from the transaction
      // once it has been authorized successfully
      submitForSettlement: true
    }
  }, (error, result) => {
      if (result) {
        res.send(result);
      } else {
        res.status(500).send(error);
      }
  });
});

module.exports = router;

How can I assign those values to Variables that I can then pass to Heroku Config Vars?

Thank you very much for your help!

How can I use CreateScriptProcessor for real time audio time stretching algorithm in JavaScript?

I want to use a time stretch Algorithm in my project but I don’t know where should I call my function TimeStretchAlgorithm().

const TimeStretchAlgorithm = (playbackspeed)=>{
 // algorithm codes
}


let node1 = audioCtx.createScriptProcessor(4096, 1, 1);
node1.onaudioprocess = function (e) {
   let inputBuffer = e.inputBuffer;
   let outputBuffer = e.outputBuffer;

   for (let channel = 0; channel < outputBuffer.numberOfChannels; channel++) {
        let inputData = inputBuffer.getChannelData(channel);
        let outputData = outputBuffer.getChannelData(channel);

        let playbackspeed = 0.7;
        outputData = TimeStretchAlgorithm(playbackspeed);
      }
  }

How to have an image rotated to a random degree when webpage is loaded? (JavaScript)

I’m trying to create a small project that has the user guess the degree of rotation of an image and then gives a paragraph that tells the user how many degrees the image is rotated and how many degrees they are off. I tried setting the image’s rotation to a random amount between 0 and 359 using Math.random() at line 2, and then using the transform style on the image outside of any function. I was hoping by setting the rotation outside of a function that it would occur as soon as the page is loaded but that is not working (I am new to coding). How can I fix this? Here’s my JS code:

let image = document.getElementById(`image`)
let rotation = Math.floor(Math.random() * 359)
let degrees = document.getElementById(`degrees`)
let submitButton = document.getElementById(`submitButton`)
let difference
let rotationParagraph = document.getElementById(`rotationParagraph`)

image.style.transform = `rotate(${rotation.value}deg)`

submitButton.addEventListener(`click`, guessRotation)

function guessRotation() {
  difference = `Math.abs(${rotation.value} - ${degrees.value})`
  rotationParagraph.innerHTML = `Rotation is ${rotation.value}. You were off by ${difference.value}.`
}

HTML code:

<!DOCTYPE html>
<html>

<head>
  <title>Guess the Rotation</title>
  <link href="style.css" rel="stylesheet">
  <script src="script.js" defer>

  </script>
</head>

<body>
  <h1>Guess the Rotation</h1>

  <!-- image that will be rotated -->
  <div id="object">
    <image src="connection.jpg" width="200" style="transform: rotate" id="image">
  </div>

  <!-- side panel -->
  <div id="sidePanel">
    <p id="">How many degrees is the image rotated?</p>
    <input type="number" min="0" max="359" placeholder="0-359" id="degrees">
    <button id="submitButton">Submit</button>
    <p id="rotationParagraph"></p>
  </div>
</body>

</html>

CSS code:

#object, 
#sidePanel {
  /* puts the image and side panel side by side */
  display: inline-block;

  /* makes the image and side panel aligned at the top */
  vertical-align: top;
}

#image {
  /* gives dimensions and a border to the image */
  border: 1px solid black;

  /* puts empty space to the right of the box to separate it from the side panel */
  margin-right: 30px;
  margin-bottom: 30px;
  margin-top: 30px;
}

I tried setting the image’s rotation to a random amount between 0 and 359 using Math.random at line 2, and then using the transform style on the image outside of any function.

I tried adding the rotation in CSS using “rand(0, 359)deg” as the rotation amount and nothing changed.

Using PDF.js to render to an offscreen canvas

The goal is to render pages of a pdf to an offsrceen canvas to that I can copy portions of the page to a visible canvas. As a first step, the code below is intended to render the entire first page of a pdf. It renders to an offscreen canvas, then copies from offscreen to the visible canvas. Or that was my intention. Nothing appears.

<!doctype html>

<html lang="en">
<head>
  <!--The pdf.js stuff, from Mozilla.-->
  <script src="pdf.js"></script>
  <script src="pdf.worker.min.js"></script>
  <style>
    canvas { border: 1px solid black; }
  </style>
</head>

<body onload="main()">

<canvas id="pdf_renderer"></canvas>

<script>

var myState = {
  pdf: null,
  zoom: 1,
  testcvs: null
}

async function main() {

  await openDocument();
  await getpage(1);
  
  var canvas = document.getElementById("pdf_renderer");
  var ctx = canvas.getContext('2d');
  
  canvas.width = myState.testcvs.width;
  canvas.height = myState.testcvs.height;
  
  ctx.drawImage(myState.testcvs,0,0);
}

async function openDocument() {
  await pdfjsLib.getDocument('ex01gear.pdf').then((pdf) => {
    myState.pdf = pdf;
  });
}

async function getpage(pagenum) {

  await myState.pdf.getPage(pagenum).then((page) => {
    
    var offcanvas = document.createElement('canvas');
    var offctx = offcanvas.getContext('2d');
    var viewport = page.getViewport(myState.zoom);
    
    offcanvas.width = viewport.width;
    offcanvas.height = viewport.height;

    page.render({
      canvasContext: offctx,
      viewport: viewport
    });

    myState.testcvs = offcanvas;
  }); 
}

</script>

</body>
</html>

Django with Javascript form not returning to View

I am trying to learn Javascript by developing an interactive form in Django. The form presents a Select list that allows multiple selections. As one or more tests in the list are selected the Javascript updates a list on the page with the current selections. When I press Submit, I expect to return to the View but instead I get a 405 Error and am not directed to the success URL. I added a Print statement to the form_valid method in the View and it never executes. Not sure how to get where I want to go.

views.py
class OrderTestsViewForJS(ListView):
    model = Universal_Test_File
    context_object_name = "testlist"
    success_url = '/list-patient/'
    template_name = "lab/order_tests_js.html"

    def get_context_data(self, *args, **kwargs):
        patient = get_object_or_404(Patient, pk=self.kwargs['pk'])
        context = super(OrderTestsViewForJS, self).get_context_data(**kwargs)
        context['patient'] = patient
        return context

    def form_valid(self, form):

        print("in form valid")
        return super().form_valid(form)
stripped down template.html
{% extends 'base.html' %}
{% block title %}Order Tests{% endblock title %}
{%load static%}
{% block content  %}


 
<div class="card mt-5 ">
    <div class="card-header text-center">
      NovaDev Order Tests Module
    </div>
    <div class="card-body">
        <div class="row">
            <div class="col-3 m-5"> 
            <form action="" method="post">
                {% csrf_token %}
                <select id="select_tests" name="select_tests" multiple >
                {% for test in testlist %}
                   <option value = "{{test.service_id}}" > {{test.test_name}}</option>
                {%endfor%}    
                </select>   
                <div class="row">
                    <div class="col m-5">        
                    <input id="done" type="submit"/>
                </div>
                </div>    
            </form>
            
        </div> 
        <div class="col-6"> 
            <p class= mt-5>Select one or more tests using Shift and Control (Command on a Mac)</p>
            <p class= mt-5>Orders will NOT be saved in this DEMO portfolio system</p>
            <p id="orderedtestlist">Tests Ordered</p>
            <p></p>
        </div>
    </div>
     
    </div>
</div> 

{% endblock content  %}

javascript
"use strict";

const $ = selector => document.querySelector(selector);

document.addEventListener("DOMContentLoaded", () => {
    $("#select_tests").addEventListener("change", () => {
        const orders = $("#select_tests").selectedOptions;

        let test_ary = []
        for (var i = 0; i < orders.length; i++) {
            test_ary[test_ary.length] = orders[i];
            displayTests(test_ary);
        }

        // test_ary now has only the selected test numbers
        //console.log(test_ary)
        // for test name
        //text = document.createTextNode(orders[i].text);

    });

    $("#done").addEventListener("click", () => {

        $("#done").submit();
    });
});

const displayTests = lst => {

    const ul = document.createElement("ul");
    ul.classList.add("testlist"); // a css class for formatting

    // create a li tag for each test selected and add to ul
    for (let test of lst) {
        const li = document.createElement("li");
        const txt = document.createTextNode(test.text);
        // you have the test number in test.value if needed
        li.appendChild(txt);
        ul.appendChild(li);
        console.log(txt)
    }

    // if no ul element yet, add it. otherwise replace it.
    const parent = $("#orderedtestlist");
    const nodeul = $("#orderedtestlist ul");
    //const node = parent.nodeul;
    if (nodeul == null) {
        console.log(parent)
        parent.appendChild(ul);
    } else {
        //console.log(node)
        nodeul.parentNode.replaceChild(ul, nodeul);
    }

}

So the Javascript works great – builds a UL every time the selection is changed and displays it. When you hit submit the idea is that you will return to View and the View will look at the form data and if valid, return to the success url. Never returns to the view though. The JS is for display purposes only. I want Django to process the form data as if the JS were not there.

How to solve this error in Javascript that I keep on getting?

Problem Statement: I need to design a simple html form that takes a limit as input and displays Fibonacci series up to the input given.

But I keep on getting this error:
testFiboForNonZeroPositiveInput:
Check for the logic and check if the correct output is displayed in div with id ‘result’

testFiboForZeroInput:
Check for the logic and check if the correct output is displayed in div with id ‘result’

TEST CASE FAILED

Here is my code:
index.html

<!DOCTYPE html>
<html lang="en">
<head>
<title>Fibonacci Series</title>
<script src="script.js"></script>
</head>
<body>
<form onsubmit=" return getFibonacci()">
  <label for="Enter the number to get a fibonacci">Enter the number to get a fibonacci</label>
  <input type="number" id="fibo" name="fibo"><br>
  
  <input type="submit" value="Get Fibonacci Numbers" id="fibobtn">
<div id="result"></div>
</form>


</body>
</html>

script.js

function getFibonacci(){
    var fib=document.getElementById("fibo").value;
    var text;
    var arr=[];
    if (fib.length===0){
        text="Please, specify a number.";
        document.getElementById("result").innerHTML = text;
    }
    else if (fib<0){
        text="Please, specify a positive number.";
        document.getElementById("result").innerHTML = text;
    }
    else{
        var  n1 = 0, n2 = 1, nextTerm, i;
        

        for (i = 0; i <= fib; i++) {
            arr.push(n1);
            nextTerm = n1 + n2;
            n1 = n2;
            n2 = nextTerm;
    
        
        }
        var newStr = arr.join(' ').trim()
        document.getElementById("result").innerHTML=newStr;
    
    }
    return false;
}

Everything seems to work fine and I get the Fibonacci series and the other messages as required but my test cases fail due to this error. Please tell me what to do to fix this issue.

Express.js websocket server crashes when I refresh my browser

I have a simple Express.js app which starts a websocket server and then the front-end connects to this server. When I start both the back-end Express.js server and the front-end server, everything works fine and I can see the incoming messages from the back-end being logged in the front-end each second.

However, when I refresh my browser, the Express.js server crashes and logs this:

Error: WebSocket is not open: readyState 3 (CLOSED)

The Express.js code looks like this:

    import * as WebSocket from 'ws';
    const wss = new WebSocket.Server({ server });
    
    const connect = function () {
        const wss = new WebSocket.Server({ server });
        wss.on('connection', (ws) => {
            ws.send(createMessage());
    
            setInterval(() => {
                ws.send(generateMsg());
            }, 1000);
    
            ws.on('error', (err) => {
                console.warn(`Client disconnected - reason: ${err}`);
                setTimeout(() => {
                    connect();
                }, 1000)
            })
        });
    }
    
    connect();

And in my front-end, I have this:

private subject = webSocket("ws://localhost:8999");

connect() {
    this.subject.subscribe(
      (msg) => {
        console.log(msg);
      },
      err => {
        setTimeout(() => {
          this.connect();
        }, 1000)
      },
      () => console.log('complete')
    );
  }

connect();

Any ideas why the reconnection between the front-end and the back-end doesn’t work?

I’m having a problem passing an argument to a function in typescript

guys. I’m new to Typescript and I’m having trouble passing arguments to a function in Typescript. This function is called when I render a form modal.But I end up getting two errors:

“Argument of type ‘Promise<AxiosResponse>’ is not assignable to parameter of type ‘(data: Record<string, unknown>) => Promise’.”

“Type ‘Promise<AxiosResponse>’ provides no match for the signature ‘(data: Record<string, unknown>): Promise’.”

  function openModal(activity) {
    const data = ref({
      name: activity.name,
    })     

    formRender.render(activity, updateActivity(activity.id,{name:data.value.name}))
  }

This would be the function:

export function updateActivity(id: number, data: Record<string, unknown>) {
 return http.patch(`/${id}`, { name: data.name })
}

Dynamics 365 How to force a leading space on Input control

I hope someone can help me as I am new to Dynamics.

There is a requirement in Dynamics 365 that says that an input field should have 6 characters min and allow spaces.

This is all good and I can do this with Javascript, but the requirement also states that the input can allow leading and trailing spaces(ie. _Rfbq2) the underscore is an example of a space, my challenge is that Dynamics 365 removes the leading or trailing spaces and this is a requirement as there is an integrated that uses this input, which can have leading and trailing spaces.

Is there a way I can force the leading space in Dynamics and override the OOB functionality that removes these spaces, is this something I can do with JS and regex somehow, any assistance would be appreciated as I have said I am mew to Dynamics

How to model nested enums in TypeScript?

I’m currently working on the CVSS v3.1 implementation in TypeScript. Here is the specification. The most interesting part for my question is probably Table 15: Base, Temporal and Environmental Vectors. Let’s have a look at the Environmental metric group. Here we have the metrics Confidentiality Requirement, Integrity Requirement, etc. Each metric has possible values, e.g. Not Defined(X), High(H), Medium(M), and Low(L). I thought that’s a pretty good use case for enums and records.

I looked at all examples I could find online but most examples are pretty simple and their value type is always the same. My value type depends on the key.

Here is what I currently have. I tried to keep it simple and use only two metrics.

enum EnvironmentalMetric {
  ConfidentialityRequirement = 'CR',
  IntegrityRequirement = 'IR',
}

// references EnvironmentalMetric.ConfidentialityRequirement (CR)
enum ConfidentialityRequirement {
  NotDefined = 'X',
  Low = 'L',
  Medium = 'M',
  High = 'H',
}

// references EnvironmentalMetric.IntegrityRequirement (IR)
enum IntegrityRequirement {
  NotDefined = 'X',
  Low = 'L',
  Medium = 'M',
  High = 'H',
}

In the end I’d like to have two loops, an outer loop over all metrics and an inner loop for each metric value. So I tried to define a nested record. For every metric value I need to have some information like a textual description and a numeric value. This numeric value is required afterwards to calculate a score. So accessing this value in a type safe manner is also required.

interface Information {
  text: string
  value: number
}

// can I improve this?
interface Metrics {
  text: string
  metrics:
    | Record<ConfidentialityRequirement, Information>
    | Record<IntegrityRequirement, Information>
}

const foo: Record<EnvironmentalMetric, Metrics> = {
  [EnvironmentalMetric.ConfidentialityRequirement]: {
    text: 'Confidentiality Requirement',
    metrics: {
      [ConfidentialityRequirement.NotDefined]: {
        text: 'Not Defined',
        value: 1,
      },
      [ConfidentialityRequirement.Low]: { text: 'Low', value: 1 },
      [ConfidentialityRequirement.Medium]: { text: 'Medium', value: 1 },
      [ConfidentialityRequirement.High]: { text: 'High', value: 1 },
    },
  },
  [EnvironmentalMetric.IntegrityRequirement]: {
      text: 'Integrity Requirement',
      metrics: {
          [IntegrityRequirement.NotDefined]: { text: 'Not Defined', value: 1 },
          [IntegrityRequirement.Low]: { text: 'Low', value: 1 },
          [IntegrityRequirement.Medium]: { text: 'Medium', value: 1 },
          [IntegrityRequirement.High]: { text: 'High', value: 1 },
      }
  }
}

// this should have type "Record<ConfidentialityRequirement, Information>"
// but has "Record<ConfidentialityRequirement, Information> | Record<IntegrityRequirement, Information>"
const a = better.CR.metrics

// this should have type "Record<IntegrityRequirement, Information>"
// but has "Record<ConfidentialityRequirement, Information> | Record<IntegrityRequirement, Information>"
const b = better.IR.metrics

My questions are:

  • Can I improve my Metrics interface so I don’t have to use the union type?
  • Can I somehow make the “getters” type safe? So can I somehow say “whenever I get the value at key EnvironmentalMetric.ConfidentialityRequirement TypeScript knows it is of type Record<ConfidentialityRequirement, Information>“.

I also tried using native Map, which works, but accessing values is quite annoying because every value can be undefined.

Any ideas? Thank you very much!

Searching for a number with a wildcard using oData

I have a numeric SQL column that I’m wanting to search on but I’m not able to find an oData equivalent.

For example, in SQL I would use:

SELECT * FROM MyTable WHERE Id LIKE '%123%'

I’ve tried the following for oData but no luck:

contains(Id,123)
contains(Id,'123')

The error I get is:

The query specified in the URI is not valid. No function signature for the function with name 'contains' matches the specified arguments.

Any ideas?