How to call exact same function on two different html classes?

All am trying to do is, just incorporate a function which shorts the paragraphs and add “Show more” and “Show less” when show more is already opened. Its working on single html element but when i use it on another one, it just uses the two ones option to the first one.

Here is my function:

! function(e) {
    "object" == typeof module && "object" == typeof module.exports ? e(require("jquery"), window, document) : e(jQuery, window, document)
}(function(e, s, t, n) {
    e.fn.shorten = function(s) {
        "use strict";
        var n = {
            mode: 1,
            showChars: 100,
            minHideChars: 10,
            ellipsesText: "...",
            moreText: 'Show more',
            lessText: 'Show less',
            onLess: function() {},
            onMore: function() {},
            errMsg: null,
            force: !1
        };
        var more_button = '<button type="button" style="width: 100%;background-color: white;height: 30px;border-color: black;margin-top: 20px;margin-bottom: 20px;color: black;" class="btn btn-lg btn-primary"><span><span>Show more</span></span></button>';
        var less_button = '<button type="button" style="width: 100%;background-color: white;height: 30px;border-color: black;margin-top: 20px;margin-bottom: 20px;color: black;" class="btn btn-lg btn-primary"><span><span>Show less</span></span></button>'
        return s && e.extend(n, s), e(this).data("jquery.shorten") && !n.force ? !1 : (e(this).data("jquery.shorten", !0), e(t).off("click", ".morelink"), e(t).on({
            click: function() {
                var s = e(this);
                var zz = n.mode === 2 ? more_button : n.moreText;
                var zx = n.mode === 2 ? less_button : n.lessText;
                return s.hasClass("less") ? (s.removeClass("less"), s.html(zz), s.parent().prev().prev().show(), s.parent().prev().hide(0, function() {
                    n.onLess()
                })) : (s.addClass("less"), s.html(zx), s.parent().prev().prev().hide(), s.parent().prev().show(0, function() {
                    n.onMore()
                })), !1
            }
        }, ".morelink"), this.each(function() {
            var s = e(this),
                t = s.html().trim(),
                r = t.length,
                o = t.substr(n.showChars, r - n.showChars).indexOf(" "),
                i = n.showChars + o;
            if (r > i + n.minHideChars) {
                var l = t.substr(0, i);
                if (l.indexOf("<") >= 0) {
                    for (var a = !1, h = "", c = 0, f = [], u = null, d = 0, p = 0; i >= p; d++) {
                        if ("<" != t[d] || a || (a = !0, u = t.substring(d + 1, t.indexOf(">", d)), "/" == u[0] ? u != "/" + f[0] ? n.errMsg = "ERROR en HTML: the top of the stack should be the tag that closes" : f.shift() : "br" != u.toLowerCase() && f.unshift(u)), a && ">" == t[d] && (a = !1), a) h += t.charAt(d);
                        else if (i >= c) h += t.charAt(d), c++;
                        else if (f.length > 0) {
                            for (j = 0; j < f.length; j++) h += "</" + f[j] + ">";
                            break
                        }
                        p++
                    }
                    l = e("<div/>").html(h + '<span class="ellip">' + n.ellipsesText + "</span>").html()
                } else l += n.ellipsesText;
                var blur_style = (n.mode === 2) ? "-webkit-mask-image: linear-gradient(#fff,#fff,rgba(255,255,255,0));" : "";
                var _temp_button = n.mode === 2 ? more_button : n.moreText;
                var m = '<div class="shortcontent" style="'+ blur_style +'">' + l + '</div><div class="allcontent">' + t + '</div><span><a href="javascript://nop/" class="morelink" style="text-decoration: underline;color:black;">' + _temp_button + "</a></span>";
                s.html(m), s.find(".allcontent").hide(), e(".shortcontent > *:last", s).css("margin-bottom", 0)
            }
        }))
    }
});

And here is how i apply on html :

$('.overview-1477').shorten({
    showChars: 250,
    mode: 1,
    moreText: 'Show more',
    lessText: 'read less'
});
$('.course_content_2544').shorten({
    showChars: 600,
    mode: 2,
}); 

So when mode === 1 then it should show moreText and lessText but when mode === 2 then another design elements are added.

But when i use this on to call for two elements, both the elements work based on last configs.

So i need to tweak the code, to work on different elements but no idea where i have missed. Please help

How can I catch CORS request did not succeed and display it to the user on my frontend?

I’m creating a front-end to a back-end I’ve created. I’ve got my system working where if the back end is online, the front-end displays the requested data from my back-end API. I currently do this using the JavaScript fetch function like this:

fetch("http://localhost:3001/public-key")
.then((response) => response.json())
.then(returnedKey => {
    this.setState({ publicKey: returnedKey })
})
.catch(err => {
    console.log("error")
    this.setState({ publicKey: "Error" })
});

What I want to do is catch the CORS request did not succeed message when my back-end is down and set the state of publicKey to an error so it displays “error” to the user, however the way I’m trying to do it with catch doesn’t seem to be working.

Any insight would be greatly appreciated.

How to change a Javascript object with a dynamic path?

Im trying to change a variable list with newList. The problem is that i dont know how to change the list when it got path added with a function.

Add string to object

Object.byString = function(o, s) {
    s = s.replace(/[(w+)]/g, '.$1'); // convert indexes to properties
    s = s.replace(/^./, '');           // strip a leading dot
    var a = s.split('.');
    for (var i = 0, n = a.length; i < n; ++i) {
        var k = a[i];
        if (k in o) {
            o = o[k];
        } else {
            return;
        }
    }
    return o;
}

Return path

function getPath2(){
   const split = get("path").split('~');
   var newSplit = "";
   for (key in split){
      if(!split[key] == ""){  
        newSplit = newSplit + "."+split[key]+"";
      }
   }
   return newSplit;
   }
//  this works
//  {afas: {…}, fa: {…}, fas: {…}, af: {…}}
console.log(Object.byString(list, getPath2()));

//  this works
// {afas: {…}, fa: {…}, af: {…}, fas: {…}}
console.log(newList);

// This is not working
Object.byString(list, newPath) = newList;

Error I get back:
script.js:420 Uncaught ReferenceError: Invalid left-hand side in assignment
at HTMLLIElement. (script.js:420:32)

Angular: canactivate auth gaurd issue

I am learning angular 13 & i am stuck at point, below is the code

this is my authservice file

export class AuthService {
  loggedIn = false;

  isAuthenticated() {
    const promise = new Promise(
      (resolve, reject) => {
        setTimeout(() => {
          resolve(this.loggedIn);
        }, 800);
      }
    );
    return promise;
  }
}

i am getting this error

this is my auth guard service file

import { Injectable } from '@angular/core';
import {
  ActivatedRouteSnapshot,
  CanActivate,
  Router,
  RouterStateSnapshot,
} from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';

@Injectable()
export class AuthGuardService implements CanActivate {
  constructor(private authService: AuthService, private router: Router) {}

  canActivate(route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return this.authService.isAuthenticated()
      .then(
        (authenticated: boolean) => {
          if (authenticated) {
            return true;
          } else {
            this.router.navigate(['/']);
          }
        }
      );
    }
}

screenshot of error
enter image description here

Can anybody help me??

Start date in javascript

I have a four week work schedule start date should be 2022-03-01.
I made code to do that but the problem is:
In java script you can not write start date as it should, but must be at least one month before real start date, and if you change start date, you get different results.
I tried many start dates until I found the best start date is 20-01-27 the result is:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-ui-timepicker-addon/1.6.3/jquery-ui-timepicker-addon.min.js"></script>
</head>
<body>
    <div class="container">
        <div class="majed" id="schema">
            <form id="myFormsch">
      
                <label for="Datum">Datum:</label>
                <span>
                <input type="text" readonly=""  id="date"placeholder="Klick och välj datum">
                </span>
                <label for="dag">Dag:</label>
                <span>
                <input type="text" readonly="" id="day">
                 </span>
                <label for="Arbetar">Ulf:</label>
                <input type="text" readonly="" id="Arbetar">
            </form>
        </div>
       
        
        
        <script>
      
            $(function () {
                var weekStart = new Date(2022, 01, 27);

                var roster =
                ['Sun week 1 Day 1','Mon week 1 Day 2','Tue week 1 Day 3','Wed week 1 Day 4','Thu week 1 Day 5','Fri week 1 Day 6','Sat week 1 Day 7',
 'Sun week 2 Day 8','Mon week 2 Day 9','Tue week 2 Day 10','Wed week 2 Day 11','Thu week 2 Day 12','Fri week 2 Day 13','Sat week 2 Day 14',
 'Sun week 3 Day 15','Mon week 3 Day 16','Tue week 3 Day 17','Wed week 3 Day 18','Thu week 3 Day 19','Fri week 3 Day 20','Sat week 3 Day 21',
 'Sun week 4 Day 22','Mon week 4 Day 23','Tue week 4 Day 24','Wed week 4 Day 25','Thu week 4 Day 26','Fri week 4 Day 27','Sat week 4 Day 28'];


           
               
                $('#date').datepicker({
                     firstDay: 1 ,
                     dateFormat: "yy-mm-dd",
                    minDate: weekStart,
                    onSelect: function (dateText, inst) {
                        var date = $(this).datepicker('getDate');
                        var d = new Date(dateText);
                        $.datepicker.iso8601Week(d);
                        
   
   
                        var days = Math.floor((date.getTime() - weekStart.getTime()) / (24 * 60 * 60 * 1000)) ;
                        var week = Math.floor((days / 7) % 4);
                         $('#week').val(week +1);
                        $('#day').val($.datepicker.formatDate('DD', date) +" " +"Week"+" "+ ($.datepicker.iso8601Week(d)))  ;
                        $('#Arbetar').val(roster[(week) * 7 + date.getDay()]);
                        
                       
                    }
                });
            });
        </script>
    </div> 
</body>
</html>

2022-04-03 Sun week 1 Day 1 wrong
it should be sun week 2 day 8 but it is sun week 1 day 1.
I do not know how to solve the problem,
Do you have suggestions for the problem?, please help me
thanks

Get points of user that is currently logged in from realtime database

I want to get the points and show to the owner of that account when he is logged in I tried reading firebase documentation but I couldn’t made it here is the code that I use for assigning the random key and saving the child data

const autoid = firebase.database().ref("user").push().key;
firebase.database().ref("user").child(autoid).set({


Email :email,

Password : password,



Points :"500"

});

Picture of database

i want whenever the user is login get his points from database and show it on their profile.

Discord JS: Cannot find Module

I’m working on implementing slash commands to my bot. For that I made a deploy-commands.js which is located in ./src/deploy-commands.js. My commands are located in ./src/commands/. At the moment my only command is a simple ping.js. With the following code I’m trying to read the commands in my commands folder and push them into an array.

require("dotenv").config()
const fs = require("fs")
const { REST } = require("@discordjs/rest")
const { Routes } = require('discord-api-types/v9')
const commands = []

const CommandFiles = fs.readdirSync("./src/commands").filter(file => file.endsWith(".js"))

CommandFiles.forEach(commandFile => {
    const command = require(`.commands/${commandFile}`)
    commands.push(command.data.toJSON())
})


const restClient = new REST({version: "9"}).setToken(process.env.DISCORD_BOT_TOKEN)



restClient.put(Routes.applicationGuildCommands(process.env.DISCORD_APPLICATION_ID, process.env.DISCORD_GUILD_ID),
{body: commands})
.then(() => console.log("Commands wurden geladen!"))
.catch(console.error)

Also I created a script in my package.json to easily run the deploy-commands.js file. Now when I run my script via npm run deployCommands I get the following error:

Error: Cannot find module '.commands/ping.js'
Require stack:
- C:UsersnilsiDesktopDiscord Botsrcdeploy-commands.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at C:UsersnilsiDesktopDiscord Botsrcdeploy-commands.js:13:21
    at Array.forEach (<anonymous>)
    at Object.<anonymous> (C:UsersnilsiDesktopDiscord Botsrcdeploy-commands.js:12:14)
    at Module._compile (node:internal/modules/cjs/loader:1103:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
    at Module.load (node:internal/modules/cjs/loader:981:32) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ 'C:\Users\nilsi\Desktop\Discord Bot\src\deploy-commands.js' ]
}

how do i make the html code appear on top of the animation and not behind it

I tried putting this in CSS p{ z-index: 99 !important; } it didn’t work
I Just want to make everything in html appear on top of the animation
here is the code::

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
  </head>
  <body>
    
    <div id="container">
      <p>hellpo</p>
    </div>
<script id="vertex-shader" type="no-js">
  void main()   {
    gl_Position = vec4( position, 1.0 );
  }
</script>
<script id="fragment-shader" type="no-js">
  uniform float iGlobalTime;
  uniform vec2 iResolution;

  const int NUM_STEPS = 8;
  const float PI        = 3.1415;
  const float EPSILON   = 1e-3;
  float EPSILON_NRM = 0.1 / iResolution.x;

  // sea variables
  const int ITER_GEOMETRY = 3;
  const int ITER_FRAGMENT = 5;
  const float SEA_HEIGHT = 0.6;
  const float SEA_CHOPPY = 1.0;
  const float SEA_SPEED = 1.0;
  const float SEA_FREQ = 0.16;
  const vec3 SEA_BASE = vec3(0.1,0.19,0.22);
  const vec3 SEA_WATER_COLOR = vec3(0.8,0.9,0.6);
  float SEA_TIME = iGlobalTime * SEA_SPEED;
  mat2 octave_m = mat2(1.6,1.2,-1.2,1.6);

  mat3 fromEuler(vec3 ang) {
    vec2 a1 = vec2(sin(ang.x),cos(ang.x));
    vec2 a2 = vec2(sin(ang.y),cos(ang.y));
    vec2 a3 = vec2(sin(ang.z),cos(ang.z));
    mat3 m;
    m[0] = vec3(
        a1.y*a3.y+a1.x*a2.x*a3.x,
        a1.y*a2.x*a3.x+a3.y*a1.x,
        -a2.y*a3.x
    );
    m[1] = vec3(-a2.y*a1.x,a1.y*a2.y,a2.x);
    m[2] = vec3(
        a3.y*a1.x*a2.x+a1.y*a3.x,
      a1.x*a3.x-a1.y*a3.y*a2.x,
      a2.y*a3.y
    );
    return m;
  }

  float hash( vec2 p ) {
    float h = dot(p,vec2(127.1,311.7)); 
    return fract(sin(h)*43758.5453123);
  }

  float noise( in vec2 p ) {
    vec2 i = floor(p);
    vec2 f = fract(p);  
    vec2 u = f * f * (3.0 - 2.0 * f);
    return -1.0 + 2.0 * mix(
        mix(
        hash(i + vec2(0.0,0.0)
      ), 
        hash(i + vec2(1.0,0.0)), u.x),
        mix(hash(i + vec2(0.0,1.0) ), 
        hash(i + vec2(1.0,1.0) ), u.x), 
      u.y
    );
  }

  float diffuse(vec3 n,vec3 l,float p) {
    return pow(dot(n,l) * 0.4 + 0.6,p);
  }

  float specular(vec3 n,vec3 l,vec3 e,float s) {    
    float nrm = (s + 8.0) / (3.1415 * 8.0);
    return pow(max(dot(reflect(e,n),l),0.0),s) * nrm;
  }

  vec3 getSkyColor(vec3 e) {
    e.y = max(e.y, 0.0);
    vec3 ret;
    ret.x = pow(1.0 - e.y, 2.0);
    ret.y = 1.0 - e.y;
    ret.z = 0.6+(1.0 - e.y) * 0.4;
    return ret;
  }


  float sea_octave(vec2 uv, float choppy) {
    uv += noise(uv);         
    vec2 wv = 1.0 - abs(sin(uv));
    vec2 swv = abs(cos(uv));    
    wv = mix(wv, swv, wv);
    return pow(1.0 - pow(wv.x * wv.y, 0.65), choppy);
  }

  float map(vec3 p) {
    float freq = SEA_FREQ;
    float amp = SEA_HEIGHT;
    float choppy = SEA_CHOPPY;
    vec2 uv = p.xz; 
    uv.x *= 0.75;

    float d, h = 0.0;    
    for(int i = 0; i < ITER_GEOMETRY; i++) {        
      d = sea_octave((uv + SEA_TIME) * freq, choppy);
      d += sea_octave((uv - SEA_TIME) * freq, choppy);
      h += d * amp;        
      uv *= octave_m;
      freq *= 1.9; 
      amp *= 0.22;
      choppy = mix(choppy, 1.0, 0.2);
    }
    return p.y - h;
  }

  float map_detailed(vec3 p) {
      float freq = SEA_FREQ;
      float amp = SEA_HEIGHT;
      float choppy = SEA_CHOPPY;
      vec2 uv = p.xz;
      uv.x *= 0.75;

      float d, h = 0.0;    
      for(int i = 0; i < ITER_FRAGMENT; i++) {        
        d = sea_octave((uv+SEA_TIME) * freq, choppy);
        d += sea_octave((uv-SEA_TIME) * freq, choppy);
        h += d * amp;        
        uv *= octave_m;
        freq *= 1.9; 
        amp *= 0.22;
        choppy = mix(choppy,1.0,0.2);
      }
      return p.y - h;
  }

  vec3 getSeaColor(
    vec3 p,
    vec3 n, 
    vec3 l, 
    vec3 eye, 
    vec3 dist
  ) {  
    float fresnel = 1.0 - max(dot(n,-eye),0.0);
    fresnel = pow(fresnel,3.0) * 0.65;

    vec3 reflected = getSkyColor(reflect(eye,n));    
    vec3 refracted = SEA_BASE + diffuse(n,l,80.0) * SEA_WATER_COLOR * 0.12; 

    vec3 color = mix(refracted,reflected,fresnel);

    float atten = max(1.0 - dot(dist,dist) * 0.001, 0.0);
    color += SEA_WATER_COLOR * (p.y - SEA_HEIGHT) * 0.18 * atten;

    color += vec3(specular(n,l,eye,60.0));

    return color;
  }

  // tracing
  vec3 getNormal(vec3 p, float eps) {
    vec3 n;
    n.y = map_detailed(p);    
    n.x = map_detailed(vec3(p.x+eps,p.y,p.z)) - n.y;
    n.z = map_detailed(vec3(p.x,p.y,p.z+eps)) - n.y;
    n.y = eps;
    return normalize(n);
  }

  float heightMapTracing(vec3 ori, vec3 dir, out vec3 p) {  
    float tm = 0.0;
    float tx = 1000.0;    
    float hx = map(ori + dir * tx);

    if(hx > 0.0) {
      return tx;   
    }

    float hm = map(ori + dir * tm);    
    float tmid = 0.0;
    for(int i = 0; i < NUM_STEPS; i++) {
      tmid = mix(tm,tx, hm/(hm-hx));                   
      p = ori + dir * tmid;                   
      float hmid = map(p);
      if(hmid < 0.0) {
        tx = tmid;
        hx = hmid;
      } else {
        tm = tmid;
        hm = hmid;
       }
    }
    return tmid;
  }

  void main() {
    vec2 uv = gl_FragCoord.xy / iResolution.xy;
    uv = uv * 2.0 - 1.0;
    uv.x *= iResolution.x / iResolution.y;    
    float time = iGlobalTime * 0.3;

    // ray
    vec3 ang = vec3(
      sin(time*3.0)*0.1,sin(time)*0.2+0.3,time
    );    
    vec3 ori = vec3(0.0,3.5,time*5.0);
    vec3 dir = normalize(
      vec3(uv.xy,-2.0)
    );
    dir.z += length(uv) * 0.15;
    dir = normalize(dir);

    // tracing
    vec3 p;
    heightMapTracing(ori,dir,p);
    vec3 dist = p - ori;
    vec3 n = getNormal(
      p,
      dot(dist,dist) * EPSILON_NRM
    );
    vec3 light = normalize(vec3(0.0,1.0,0.8)); 

    // color
    vec3 color = mix(
      getSkyColor(dir),
      getSeaColor(p,n,light,dir,dist),
      pow(smoothstep(0.0,-0.05,dir.y),0.3)
    );

    // post
    gl_FragColor = vec4(pow(color,vec3(0.75)), 1.0);
  }
</script>
    
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r77/three.min.js"></script>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
    <script src="script.js"></script>
  </body>
</html>

css

body {
  overflow: hidden; 
  margin: 0; 
}
p{ z-index: 99 !important; }

JavaScript

var container, 
    renderer, 
    scene, 
    camera, 
    mesh, 
    start = Date.now(),
    fov = 30;

var clock = new THREE.Clock();

var timeUniform = {
    iGlobalTime: {
        type: 'f',
        value: 0.1
    },
    iResolution: {
        type: 'v2',
        value: new THREE.Vector2()
    }
};

timeUniform.iResolution.value.x = window.innerWidth;
timeUniform.iResolution.value.y = window.innerHeight;

window.addEventListener('load', function() {
  container = document.getElementById('container');
  scene = new THREE.Scene();
  
  camera = new THREE.PerspectiveCamera( 
    fov, 
    window.innerWidth / window.innerHeight, 
    1, 
    10000
  );
  camera.position.x = 20;    
  camera.position.y = 10;    
  camera.position.z = 20;
  camera.lookAt(scene.position);
  scene.add(camera);
  
  var axis = new THREE.AxisHelper(10);
  scene.add (axis);
  
  material = new THREE.ShaderMaterial({
    uniforms: timeUniform,
    vertexShader: document.getElementById('vertex-shader').textContent,
    fragmentShader: document.getElementById('fragment-shader').textContent
  });
  
  var water = new THREE.Mesh(
    new THREE.PlaneBufferGeometry(window.innerWidth, window.innerHeight, 40), material
  );
  scene.add(water);
  
  var geometry = new THREE.SphereGeometry( 10, 32, 32 );
  var material = new THREE.MeshBasicMaterial( {color: 0xffff00} );
  var sphere = new THREE.Mesh( geometry, material );
  scene.add( sphere );

  renderer = new THREE.WebGLRenderer();
  renderer.setSize( window.innerWidth, window.innerHeight );
  
  container.appendChild( renderer.domElement );

  render();
});

window.addEventListener('resize',function() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
});

function render() {
  timeUniform.iGlobalTime.value += clock.getDelta();
  renderer.render(scene, camera);
  requestAnimationFrame(render);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Load several HTML pages one after the other

For an info screen I use different HTML pages that run through. For this I use the following line in the code to load the new page after a few seconds.

<meta http-equiv="refresh" content="16; URL=openinghours.html">

Thus, each HTML file specifies which is the next page.

Due to new information I have to delete some HTML pages from the run or add new ones every few weeks. For this also in other files the name of the next page must be updated.

Is there a simple way with Javascript or similar that I can centrally define which pages are shown in which order without always having to define this in the each HTML file?

Issue with Mongodb pre-defined javascript

I keep getting, Missing ";" before statement error in Mongodb Atlas Online. I am new to this, and I fail to see why the following lines gives this error:

const counter = await counterCollection.findOneAndUpdate({_id: changeEvent.ns },{ $inc: { seq_value: 1 }}, { returnNewDocument: true, upsert : true});

AND:

const updateRes = await targetCollection.updateOne({_id: docId},{ $set: doc});

Full code:

exports = function(changeEvent) {
  const docId = changeEvent.fullDocument._id;
  
  const counterCollection = context.services.get("Cluster0").db(changeEvent.ns.db).collection("counters");
  const targetCollection = context.services.get("Cluster0").db(changedEvent.ns.db).collection(changeEvent.ns.coll);
  const counter = await counterCollection.findOneAndUpdate({_id: changeEvent.ns },{ $inc: { seq_value: 1 }}, { returnNewDocument: true, upsert : true});
  
  const doc = {};
  doc[`${changeEvent.ns.coll}Id`] = counter.seq_value;
  const updateRes = await targetCollection.updateOne({_id: docId},{ $set: doc});
  console.log(`Updated ${JSON.stringify(changeEvent.ns)} with counter ${counter.seq_value} result: ${JSON.stringify(updateRes)}`);
};

enter image description here

get cells in range and paste as values Apps script

I have a range A2:Z5000 that i am trying to paste as values in the same exact range (turn formulas into fixed values)

In range A2 i have a ImportData formula fetching data from a csv file.

My script goes like:

var sheet = SpreadsheetApp.getActive().getSheetByName('MYSQLimport');
sheet.getRange("A2:Z5000").copyTo(sheet.getRange("A2:Z5000"), {contentsOnly:true});

but it erases the content instead of setting it as values…

JS alter JSON value to match key

I have the following JSON and I am trying to alter it to have the same key and value string:

var icons = {
      "123": 63103,
      "alarm-fill": 61697,
      "alarm": 61698
}

I’m trying the following code:

var newIcons = [];

for (var key in icons) {
    if (icons.hasOwnProperty(key)) {
        newIcons.key = key;
    }
}

console.log(newIcons);

It should return the following:

{
  "123": "123",
  "alarm-fill": "alarm-fill",
  "alarm": "alarm"
}

How to retrieve email and password from key parent that is assigned to an user while making an account

I want to get the points and show to the owner of that account when he is logged in I tried reading firebase documentation but I couldn’t made it here is the code that I use for assigning the random key and saving the child data

const autoid = firebase.database().ref("user").push().key;
firebase.database().ref("user").child(autoid).set({

Email :email,
Password : password,
Points :”500″

})
As in the image shown i want logged in user to get their respective points shown in their profile.

How destructure an object starting from a constant?

I have a utils/constant.js file with:

// Key of total elements in remote collection
export const TOTAL_ELEMENTS = "totalElements";

I need to access to totalElements via the constant.

import { TOTAL_ELEMENTS } from "./constants.js";
[...]
let data = {
    content: "foo",
    totalElements: 54
};

if(TOTAL_ELEMENTS in data) {
    // pseudocode, of course it doesn't work.
    // of course in my case need to return 54
    const { TOTAL_ELEMENTS } = data;
    return TOTAL_ELEMENTS;
}

cann’t fill the value of the inputs by jquery

I want to fill the value of the rows of a table into textboxes by clicking a button. this is what I have done

  <table id="tbl_Features" class="col-md-12 table table-bordered table-hover  table-condensed table-responsive">
                                <thead>
                                    <tr>
                                        <th>
                                            Name
                                        </th>
                                        <th>
                                            Value
                                        </th>
                                        <th>

                                        </th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach (var item in Model)
                                    {
                                        <tr >
                                            <td id="displayName@{@item.Id}">
                                                @item.DisplayName
                                            </td>
                                            <td  id="Value@{@item.Id}">
                                                @item.Value
                                            </td>
                                            <th>
                                                <div class="dropdown">
                                                    <button class="btn bg-blue dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                                        Operation
                                                    </button>
                                                    <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">                                                            

                                                        <a href="#" onclick="FillFeaturetoEdit(@item.Id)" class="dropdown-item">edit</a>

                                                    </div>
                                                </div>
                                            </th>
                                        </tr>
                                    }
                                </tbody>
                            </table>

This is the jquery for that

  function FillFeaturetoEdit(id){
        debugger;
         var row = $("#displayName"+id);   
         var valueItem= row.text();
         $("#txtDisplayName").val(valueItem);
         row = $("#Value"+id);  
         valueItem= row.text();
         $("#txtValue").val(valueItem);
    }

but anytime I click the edit button although the row.text() and ValueItem show the right value but inputs(txtDisplayName and txtValue) value are empty