Sum values of nested JSON objects in JavaScript filtered by dates

I have some JSON data in this structure:

"Sensor": "14829304",
    "DATA": {
        "Rainfall": {
            "2022-01-11": {
                "T1": {
                    "MM": "3.94",
                    "CONFIRMED": "T"
                },
                "T2": {
                    "MM": "3.91",
                    "CONFIRMED": "T"
                }
              }
            },
     "Temperature": {
            "2022-01-11": {
                "T1": {
                    "MM": "9.32",
                    "CONFIRMED": "T"
                },
                "T2": {
                    "MM": "9.44",
                    "CONFIRMED": "T"
                }
              }

Where I receive multiple readings in a day and for multiple days across the year.

I would like to be able to sum up all of the rainfall in the data and then also sum up all of the rainfall for a defined time period like yesterday, last month or between two dates.

I have tried to use map and reduce on the object, but I’m struggling to get it to work.

Any pointers to help me along, please?

Writing an algorithm that looks for array duplicates

I have all the pieces in my brain to write this algorithm for Apps Script, but I’m having trouble piecing it together. I’m hoping to tap into the collective knowledge for a little support.

I have a script that imports our school’s daily attendance records and pulls out a list of students who were tardy and what class they were tardy for. On another tab, there is a running tally of students and the number of tardies they have earned.

Here is an example of the daily import:

Daily Import

Notice that some students might have more than one tardy in a day.

And here is the (pre-import) running tally:

enter image description here

Where I am struggling is with the update of the running tally. I need a script that:

  1. Counts the number of tardies for each student that day (in the example, Bob has 2, Linda has 2, and Gene and Tina each have 1).
  2. It takes that information and adds it to the running tally on the other tab. In our example, the updated tally would look like this:

enter image description here

Notice that since Gene hadn’t previously been tardy to any classes, his name was added to the sheet.

Any ideas? I know a nested for loop will be needed, but I’m having a hard time getting a proper count when looking for repeats in two separate arrays. Also, note that our school actually has around 290 students (and they are often changing), so just writing a script that counts from a master list of students isn’t very practical.

TIA

Why is process.env.WHATEVER !== undefined if I set to undefined after it is set?

I have the following test script….

> process.env.SOMETHING === undefined
true
> process.env.SOMETHING = "asdsad";
'asdsad'
> process.env.SOMETHING === undefined
false
> process.env.SOMETHING = undefined
undefined
> process.env.SOMETHING === undefined
false
> process.env.SOMETHING == null
false
> !process.env.SOMETHING
false
> process.env.SOMETHING === "undefined"
true

Why does it get converted to a string?

AG Grid: Receiving “invalid row index for ensureIndexVisible” for valid row indexes

I am receiving “invalid row index for ensureIndexVisible” for valid row indexes.

For example:

invalid row index for ensureIndexVisible: 0
invalid row index for ensureIndexVisible: 3

I am not implementing getRowNodeId. Instead, I am letting AG Grid build the IDs, but the problem occurs either way I try it.

Here’s the related code in the component:

gridOptions = {
    onGridReady: (params: any) => {
        params.api.sizeColumnsToFit();
    },
    onRowClicked: (params: any) => {
      localStorage.setItem('lastDeveloper', params.node.id.toString());
      this.router.navigate(['developers', params.node.data.id], { state: params.node.data });
    },
    onFirstDataRendered: (params: any) => {
      const lastDeveloperSelected = localStorage.getItem('lastDeveloper');
        if (lastDeveloperSelected) {
          params.api.ensureIndexVisible(lastDeveloperSelected, 'middle');
        }
    }
  }

How can i Toogle between 2 icons without reloading page in wordpress

i’m working in wordpress website,and i want to toogle between 2 icons carts one whene the cart is empty and the seconde display whene add items to the cart,
i add this code:

<span class="wd-tools-icon <?php echo esc_attr( $icon_classes ); ?>">
            
    <?php if ( ! WC()->cart->is_empty() ) { ?>
        <img id="https:/.../images/cart.svg" class="wd-custom-icon" alt="" height="20.738" width="17.626">      
                            
    <?php } else{ ?>        
        <img decoding="async" src="https:/.../images/empty-cart.svg.svg" class="wd-custom-icon" alt="" height="20.738" width="17.626">      

   <?php } ?>                   

   <?php if ( '2' == $params['style'] || '5' == $params['style'] ) : ?>
        <?php woodmart_cart_count(); ?>
   <?php endif; ?>
</span>

but i need to refresh the page for displaying the cart;
i’m looking for a way make me toogle between the 2 icons without reloading the page,a will be thankful for any suggestion

what is wrong to display if condition correctly?

var arr = [{
  name: "John Doe"
}, {
  name: "jamal"
}, {
  name: "Badr"
}, {
  name: "mohsen"
}] 

arr.forEach((val) => {
  firstLetter = val.name.split(" ")[0].split("")[0];
});

for (var i = 0; i < arr.length; i++) {
  if (firstLetter == "J" || firstLetter == "j") {
    console.log("Goodbye " + arr[i].name);
  } else {
    console.log("Hello " + arr[i].name);
  };
};

Get selected value in dropdown list using JavaScript scrape [duplicate]

Further to the question posed here Get selected value in dropdown list using JavaScript

I have the below element on the page and I’m trying to display the selected value 1.

<select name="entity:is_the_settlor_a_trustee:0:" style="">
    <option value=""> </option>
    <option selected="selected" value="1">Yes</option>
    <option value="2">No</option></select>

However the field name is complex, I can’t figure out how to call the name I’ve tried the below to no avail

var e = document.getElementByName("entity:is_the_settlor_a_trustee:0:");
var strUser = e.value;document.write(strUser);

Access API key with separate words [duplicate]

I’m doing a call to an API (https://gitlab.com/-/snippets/2041384/raw/master/data.json), and what i received is this

{
  "title": "No Activity",
  "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
  "programType": "series",
  "images": {
    "Poster Art": {
      "url": "https://streamcoimg-a.akamaihd.net/000/106/36/10636-PosterArt-9add943c5e62c2d89f6d31458d33508a.jpg",
      "width": 1000,
      "height": 1500
    }
  },
  "releaseYear": 2015
},

How can i access “Poster Art”??

I can access all of them but that one, i’ve looked for it but i found nothing.

Is there any way to change the key name??

Any hint would be very much appreciated.

Thanks!

SyntaxError when attempting to construct Node.js Module object

$ cat test.js
'use strict';

console.log(process.versions.node);

new require('module').constructor('/foo/bar/baz');
$ node test.js
16.0.0
undefined:3
/foo/bar/baz
^

SyntaxError: Invalid regular expression flags

This behaviour is very odd! I’m hoping someone can explain it to me. I see no syntax error here.

Interestingly, new module.constructor('/foo/bar/baz') works in the REPL.

Importing Data from module type script into Google Maps API Web Application

So I’m currently having an issue with my code, where if I try and import data from a module js file into file creating the Google Maps API map on my web application, the map fails to load.

The module js file is named dataSets.js, and the value datasets in that file contains the data I wish to import. I add the line export default datasets at the end of that file, but when I try and add the line import datasets from ‘queryDatabase.js’ to the top of my api code file, the function creating the map is “grayed out”. Is there any fix around this?

translate curl to google apps script

hi guys i need help i need translate curl code to google apps script

curl -X POST
-H ‘accept: application/json’
-H ‘content-type: application/json’
-H ‘Authorization: Bearer YOUR_ACCESS_TOKEN’
‘https://api.mercadopago.com/v1/payments’
-d ‘{
“transaction_amount”: 100,
“token”: “ff8080814c11e237014c1ff593b57b4d”,
“description”: “Blue shirt”,
“installments”: 1,
“payment_method_id”: “visa”,
“issuer_id”: 310,
“payer”: {
“email”: “[email protected]”
}
}’

javascript text animation delay issues

Okay, so I have created this javascript text-animation that has a delay when writing text to
my p element “output”. The animation works just fine…but I decided that I wanted to add text color to specific words in my “message” parameter. I made that happen by using this code:

function write(message,clear,delay) {
    if(clear == true) clearMessage();
    if(typeof delay != "number") delay = game.message.delay;
    let q = undefined;
    let output = document.getElementById("output");
    let applyingColor = false;
    let dest = output;
    for(var i = 0 ; i < message.length ; i++) {
        let cur = i;
        let letter = message.charAt(i);
        let wait = delay*i;
        

        q = setTimeout(() => {
            if(letter == "<") {
                letter = "";
                applyingColor = true;
                let color = undefined;
                let a = message.substring(cur+1,message.length);
                let colorSig = a.substring(0,a.indexOf("/"));
                color = colorSig;

                let span = document.createElement("span");
                span.style.color = color;
                output.appendChild(span);
                dest = span;
            } else if(letter == ">") {
                letter = "";
                dest = output;
            } else if(letter == "|") {
                letter = "<br>";
            }
            if(applyingColor) {
                if(letter != "/") {
                    return;
                } else {
                    applyingColor = false;
                    return;
                }
            }
            dest.innerHTML += letter;
        },wait);

        writingQueue.push(q);
    }
}

the code above delays each character while also checking for very specific text such as
<rgb(255,0,0)/ this is red>. the “<” and the “>” are starting and ending signifiers for the colored text, while the “/” is used to mark where the end of the color goes. The text you want to be colored would go before “>” and after “/”. and that makes it red! or any color you want. But I noticed a small detail. Whenever you use this, it creates an additional delay. For example if you did something like…

write("Hello, foo! My name is <red/ bar>!");

it would delay the “b” in “bar” longer than it would delay the “f” in “foo”.

I think the problem is being caused by

if(applyingColor) {
    if(letter != "/") {
        return
    } else {
        applyingColor = false
        return
    }
}

at around the bottom body of the q = setTimeout(...).
What this code above does is skip over any letters that are not “/” while applyingColor is true, then turns it to false when it eventually reaches that wonderful little marker (“/”) and returns one last time.

Honestly I dont know how to fix this. I’ve been working on this for hours now and my head hurts a lot. I could really use some help!

Oh! I forgot to mention. You can just ignore the “clear” and “delay” parameters. I do not believe they are relevant to my issue. The delay parameter is just the delay between each character. I have it to where it has a default value right now. And clear is just to clear previous text and clear out the writingQueue variable.

Construct functions and factory functions in TypeScript

TL;DR
The questions are:

  1. Is there a way to use factory functions in TypeScript without using the as any part?
  2. How popular are factory functions in TypeScript community? Are they even used? Or the best choice here would be just to go with classes?
  3. What are the main use cases of Construct signatures in TypeScript?

Some context:

I was going through the handbook on typesrciptlang.org and saw this example about Construct signatures:

type SomeConstructor = {
  new (s: string): SomeObject;
};
function fn(ctor: SomeConstructor) {
  return new ctor("hello");
}

I thought that this would be a good place to use factory function:

let factoryFunc = (s:string) => {
   return {s};
}

let v = new factoryFunc("some text");

but this would give the following error:
'new' expression, whose target lacks a construct signature, implicitly has an 'any' type.
I have also tried to write it as:
let v:SomeConstructor = new factoryFunc("some text");
but this would result in the same error.

I found this workaround:
let v = new (factoryFunc as any)("some text");
While it does fix the problem if that is the only way to use factory functions in TypeScript, then it seems a bit weird to me.

Asynchronous readline loop without async / await

I’d like to be using this function (which runs fine on my laptop), or something like it, on my embedded device. But two problems:

  1. Node.JS on our device is so old that the JavaScript doesn’t support async / await. Given our hundreds of units in the field, updating is probably impractical.
  2. Even if that weren’t a problem, we have another problem: the file may be tens of megabytes in size, not something that could fit in memory all at once. And this for-await loop will set thousands of asynchronous tasks into motion, more or less all at once.

async function sendOldData(pathname) {
    const reader = ReadLine.createInterface({
      input: fs.createReadStream(pathname), 
      crlfDelay: Infinity
     })
    for await (const line of reader) {
      record = JSON.parse(line);
      sendOldRecord(record);
    }
}

function sendOldRecord(record) {...}

Promises work in this old version. I’m sure there is a graceful syntax for doing this sequentially with Promises:

read one line
massage its data
send that data to our server

sequentially, but asynchronously, so that the JavaScript event loop is not blocked while the data is sent to the server.

Please, could someone suggest the right syntax for doing this in my outdated JavaScript?