How to pass params through a function?

Good Day,

I am not sure how I can pass params in a function, currently I want to store an access token in one function and then pass the params into another function, is there something I am missing or doing wrong?

{
  var token = zauthorization().access_token;

  var header = 
  {
    "Authorization":"Zoho-oauthtoken " + token
  }

  return header
}

function module(access_token)
{

   var options = 
  {
    "method":"get",
    "headers": header
  }
  
  var url = "https://recruit.zoho.com/recruit/v2/CustomModule1"
  var res = UrlFetchApp.fetch(url,options)
  return JSON.parse(res)
}

So in short I am not sure how I can pass the header into my next function, I need to have it done that way to go onto the next function, I need to create another function after this which will allow me to access data in a specific module so I can have the counted rows returned, I just need to know how to pass parameters in a new function from another function that can be used.

I need a unique ID sequence number generator, I know I could just use a small MySQL instance, but is there no other way?

I need a unique ID sequence number generator (not necessarily distributed, but would be cool if it is), i know I could just use a small MySQL instance, but is there no other way?

Twitter built Snowflake https://github.com/twitter-archive/snowflake/tree/snowflake-2010

But it is not maintained anymore. I just require a solution that I can implement on e.g a digital ocean droplet. nothing fancy.

But a distributed solution would be much cooler, so that a single server can’t be a bottleneck. Well, building a distributed solution of a normal solution is not a problem I think, you just make a prefix before the ID to indicate the server; this is also done in sharded SQL.

https://www.callicoder.com/distributed-unique-ID-sequence-number-generator/

I know I can solve it easy with a small SQL DB instance like I always do

But I’ve just wondered if there is not any other way to solve that problem.

React: setTimeout not clearing within useEffect hook

Currently my app switches to the /about page after 5s of an intro on the /home page.
I want to break this timeout if someone manually changes the page.

For this I have a state of introDisplayed which is false by default. By clicking on a link within the app the introDisplayed is becoming true

Why is the setTimeout within the useEffect not clearing?
For reference I have listed all of my attempts on this matter.

clarification:
I’ve tried adding introDisplayed alone as well as with history and setIntroDisplayed as suggested by eslint and it doesn’t change anything in this case

const Page = ({ introDisplayed, setIntroDisplayed }) => {

  const history = useHistory()

  const location = useLocation()

  // useEffect(() => {
  //   if (introDisplayed === false) {
  //     setTimeout(() => {
  //       setIntroDisplayed(true)
  //       history.push("/about")
  //     }, 5000)
  //   } else clearTimeout()
  // })
  // useEffect(() => {
  //   if (introDisplayed === false) {
  //     var timer = setTimeout(() => {
  //       setIntroDisplayed(true)
  //       history.push("/about")
  //     }, 5000)
  //   } else clearTimeout(timer)
  // })
  useEffect(() => {
    const timer = setTimeout(() => {
      setIntroDisplayed(true)
      history.push("/about")
    }, 1000)
    if (introDisplayed === true) {
      return () => clearTimeout(timer)
    }
  })

  return ()
}

Javascript add each part of username to keywords array for web-socket queries?

I am trying to add the keywords of a user’s username for faster querying using websocket events.

In my userSchema I have keywords index set to true:

  keywords: {
      // for live search of username
      type: [String],
      index: true,
    },

For example if a user’s username is ‘johnsmith’, I need to save an array with the following..

user.keywords = [j, jo, joh, john, johns, johnsm, johnsmi, johnsmit, johnsmith]

I will be doing this in my userSchema.pre(‘save’).

Below is what I am going for but how would I append the username to the parts array and then set user.keywords = parts?? Am I properly indexing the user.keywords property??

Thank you!

userSchema.pre(`save`, async function (next) {
  const user = this

  if (user.isModified(`username`)) {
    let parts = []
    for (let i = 0; i < user.username.length; i++) {
      parts.push(*???*)
    }
    user.keywords = parts
  }

  next()
})

Need Help Urgently! Program unable to update user’s new address and display in textfields

I’m trying to make a user profiles page where user can see their address and allow them to edit and save a new address (not locally!). Program is able to fetch data from backend then after using componentDidMount() method the user’s address renders only once after reload. Then I used componentDidUpdate() to keep displaying the user’s address upon reloading page but the same thing is happening. I was trying to render the values through componentdidupdate but it didn’t work because the component is mounting before there is a user provided and I don’t know how to do that. componentdidupdate causes an infinite loop of updates. I’m really stuck on this issue.

Not really sure how to get my program to update the user’s address and keep displaying it upon refresh until user wants to edit? Please help

Note: deleted addressLine2, city, state, zipCode for convenience.

Address.jsx
**

 import React, {Component} from 'react';

 import {Button} from 'react-bootstrap';

 import axios from 'axios';

 class Address extends Component {

 constructor(props) {

 super(props)

 this.state ={

  userDetails: null,

 addressLine1: '',

 updatedAt: null } }

 handleFirstAddLineChange = (event) => {

 this.setState({addressLine1: event.target.value}) }

 setUserDetails = (user) => {

 this.setState({ userDetails: user}) }

 componentDidMount(){

 const user = this.props.currentUser

 if (user){const authResponse = user.getAuthResponse();

 axios .get(`http://127.0.0.1:8085/api/users?idToken=${authResponse.id_token}`) 
 .then(res => {this.setState(res.data.addresses[0]) this.setUserDetails(res.data) }); 
 }}

 onSubmit = (event) => {event.preventDefault();

 const insertAddress = (googleUser) => {

  const addressInfo = { addresses: [{addressLine1: this.state.addressLine1 }]};

  const authResponse = googleUser.getAuthResponse();

 const idToken = authResponse.id_token;

 const user = googleUser.profileObj;

 user.addresses = addressInfo.addresses; axios.put(`http://127.0.0.1:8085/api/users? 
idToken=${idToken}`, user) .then(authResponse => this.setState({updatedAt: 
 authResponse.data.updatedAt})); };

insertAddress(this.props.currentUser) }

 componentDidUpdate(prevProps) {

if (this.props.currentUser !== prevProps.currentUser) { this.setState({ curr: 
 this.props.currentUser}); console.log("changed")}}

render() {return (<form onSubmit={this.onSubmit}>

<h1 className="main-container">Address </h1>

<div className="main-container">

<label> Address Line 1: </label>

<input className="input" type='text' value={this.state.addressLine1} onChange= 
{this.handleFirstAddLineChange}/> </div>

</div> <Button className="btn" type="submit">Save Changes</Button>

</form> );}}

export default Address;

Unable to pass argument from outer scope in Node.js file system function?

I’ve noticed that arguments are not being recognized in Node.js filesystem when wrapped with (). Can anyone explain why this is happening please? My expectation was the even when wrapped in (), it will work just like forEach() function?

const fs = require('fs');
const path = require('path');
const root = path.resolve(__dirname);

fs.readdir(root, (error, filenames) => {
   filenames.forEach( filename => {
      const filePath = path.join(root, filename);
      fs.unlink( (filePath, err) => {
         // Throws error saying 'filePath' is not defined..?
      });
   });
});

Uncaught SyntaxError: Unexpected token ‘:’

I am having error when adding this code in my webpack.config.js Uncaught SyntaxError: Unexpected token ‘:’

const webpack = require('webpack');
const dotenv = require('dotenv');

dotenv.config();

module.exports = {
  //...
  plugins: [
    // ...
    new webpack.DefinePlugin({
       'process.env': JSON.stringify(process.env)
    })
    // ...
  ]
  //...
}

app.js

'use strict';
const dotenv = require('dotenv');
const config = dotenv.config();
const {API_KEYS} =config.parsed;

....

console.log("keys ",API_KEYS)

....

How to remove extra space in template literals?

When I create template literals, I would use the trim() to remove extra space. But I noticed when I do this inside a JS function, it still creates extra tabs or white space.

  function BottlesOfBeer()  {
    
        for (i = 99; i>=1; i--) {
    
            if (i === 1) {        
                var oneBottle = "1 bottle of beer on the wall, 1 bottle of beer.n" +
                                "Take one down and pass it around, no more bottles of beer on the wall.n" +
                                "No more bottles of beer on the wall, no more bottles of beer.n" +
                                "Go to the store and buy some more, 99 bottles of beer on the wall.";        
                
                console.log(oneBottle);
            } else {
                            
                var lineOne = `
                ${i} bottles of beer on the wall, ${i} bottles of beer.
                Take one down pass it around, ${i - 1} bottles of beer on the wall.
                `.trim();
    
                console.log(lineOne);        
            }
        }
    }
    
    BottlesOfBeer();
99 bottles of beer on the wall, 99 bottles of beer.
            Take one down pass it around, 98 bottles of beer on the wall.
98 bottles of beer on the wall, 98 bottles of beer.

You can see how the first line appears normally, but the second one has all the necessary tabs.

How can add my burger.price to my Item.price to create the Total?

I am looking to have my burger.price (if there is a custom burger in the cart) to be added to the total with the item.price. Any help would be great! I am new to using vue and vuex.

<template>
<div>
  <b-button v-b-modal.modal-1>Cart({{numInCart}})</b-button>
  <b-modal id="modal-1" size="xl" title="Shopping Cart" ok-title="Checkout" cancel-title="Continue Shopping">
    <table class="table">
      <tbody>
      <!-- replace in cart with custom burger -->
      <tr v-for="(item, index) in cart" :key="item.id">
        <td>{{ item.name }}</td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td>{{ item.price | dollars }}</td>
        <td>
          <button class="btn btn-sm btn-danger" @click="removeFromCart(index)">&times;</button>
        </td>
      </tr>
        <tr>
        <th>Name</th>
        <th>Bun Type</th>
        <th>Cooked Style</th>
        <th>Cheese Type</th>
        <th>Toppings</th>
      </tr>
      <tr v-for="(burger) in customBurger" :key="burger">
        <td>{{burger.name = "Custom Burger"}}</td>
        <td>{{burger.bun}}</td>
        <td>{{burger.cookedStyle}}</td>
        <td>{{burger.cheese}}</td>
        <td>{{burger.toppings}}</td>
        <td>{{burger.price | dollars }}</td>
        <td>
          <button class="btn btn-sm btn-danger" @click="removeCustomBurger(customBurger)">&times;</button>
        </td>
      </tr>
      <tr>
        <th></th>
        <th>{{ total | dollars }}</th>
        <th></th>
      </tr>
      </tbody>
    </table>
  </b-modal>
</div>
</template>

<script>
import { dollars } from '../models/filters'

export default {
  name: 'ShoppingCart',
  computed: {
    customBurger() {
      return this.$store.getters.customBurger;
    },
    inCart() { return this.$store.getters.inCart; },
    numInCart() { return this.inCart.length; },
    cart() {
      return this.$store.getters.inCart.map((cartItem) => {
        return this.$store.getters.forSale.find((forSaleItem) => {
          return cartItem === forSaleItem.invId;
        });
      });
    },
    total() {
      return this.cart.reduce((acc, cur) => acc + cur.price, 0);
    },
  },
  filters: {
    dollars,
  },
  methods: {
    removeFromCart(index) { this.$store.dispatch('removeFromCart', index); },
    removeCustomBurger(){this.$store.dispatch('removeCustomBurger');},
  },
};
</script>

I’ve been meaning to learn C# and wanted sto write something like this Javascript code. How would i go about doing it

An example of what I’m trying to do:
Adding the first and last numbers until only two digits remain:

num = 1234567:

1+7 = 8

2+6 = 8

3+5 = 8

4 remains

So the first result is: 8884. Now everything is added again:

8+8 = 16

8+4 = 12

The result is 1612. Again everything is summed up:

1+2 = 3

6+1 = 7

The result is 37 – which is also the final result.

The Javascript code:

function sum(num) {
    var numString = num.toString();
    var newString = "";
    while (numString.length > 1) {
        newString += (parseInt(numString[0]) + parseInt(numString[numString.length - 1])).toString();
        numString = numString.substring(1, numString.length - 1);
    }
    newString += numString;

    if (newString.length > 2) {
        console.log(newString)
        return sum(newString);
    }  else {
         return newString;
      }
}

How to correctly apply global scripts with Nextjs

I’m trying to apply a global fade-in animation to all components in my application. I’ve added the classname fadeIn to all the elements and set the opacity to 0 by default. I then use js to change that to 1 when the element comes into view.

Below is how I am applying this so far. It does work but there is a major issue and I’m sure it’s not the best method and firstly would love to know any better methods.

The major issue is that it only works on the first render. But if I navigate to another page and then come back, all elements are hidden with the opacity 0 and the script does not execute.

Appreciate any advice on how to either solve the current issue, or a better way to execute it.

_app.js

function MyApp({ Component, pageProps }) {

  return <Provider store={store}>
    <Layout>
      <PersistGate persistor={persistor}>
        <Component {...pageProps} />
      </PersistGate>
      <FadeIn />
    </Layout>
  </Provider>
}

export default MyApp

FadeIn component

import React, { useEffect, useState } from 'react'
import Script from 'next/script'
import ReactDOM from 'react-dom';

export default function FadeIn() {

  const myScript = (
    <Script src='/utils/scripts/appearOnScroll.js' strategy="afterInteractive" />
  )

  return ReactDOM.createPortal(myScript, document.getElementById('doc-root'));

}

appearOnScroll.js

(function () {
  const faders = document.querySelectorAll('.fade-in');
  const faderOptions = {
    threshold: 1
  };
  const appearOnScroll = new IntersectionObserver(function (
    entries,
    appearOnScroll
  ) {
    entries.forEach(entry => {
      if (!entry.isIntersecting) {
        return;
      } else {
        entry.target.classList.add('appear');
        appearOnScroll.unobserve(entry.target);
      }
    })
  }, faderOptions);

  faders.forEach(fader => {
    appearOnScroll.observer(fader);
  });
})();

how to show a Blog detail link in Angular

I want to show the Detail of a Blog in a different link in Angular. I already have a Blog file (blog.component.ts) and an Angular service where I can get all the blogs data from an API backend made with Strapi. There is one button in every single blog, which allows you to view the detail or complete Blog in a different link calling the unique ID, that is named ‘pagina.component.ts’.
For that purpose, I think I must call the ID of every single Blog.

Here is my blog.component.html, where I already have the list of my blogs:

<section class="articles">

  <article class="blue-article" *ngFor="let data of datas; index as i">
    <div class="articles-header">
      <time>{{ data.fecha }}</time>
      <span class="articles-header-tag-blue">{{ data.relevante }}</span>
      <span class="articles-header-category">
        <a href="#" class="blue" title="">{{ data.category.name }}</a>
      </span>
    </div>
    <div class="articles-content">
      <h1><a title="">{{ data.title }}</a></h1>
      <!--<img *ngIf="!data.image" class="foto" [src]="data.image.name" alt="foto">-->
      <div *ngIf="data.image">
        <img
          src="http://localhost:1337{{ data.image.url }}"
          alt="foto"
          width="100%"
        />
      </div>
      <p>
        {{ data.content }}
      </p>
      <h3>{{ data.description }}</h3>
    </div>
    <div class="articles-footer">
      <ul class="articles-footer-info">
        <li><a href="#" class="light-link" title=""><i class="pe-7s-comment"></i> 7 Respuestas</a>
        </li>
        <li><a href="#" class="light-link" title=""><i class="pe-7s-like"></i> 1221</a></li>
      </ul>

      <a [routerLink]="['./pagina',i]" class="btn">Leer más</a>

    </div>
  </article>
</section>

Here is my blog.component.ts file


import { Component, OnInit } from '@angular/core';
import { Meta, Title } from '@angular/platform-browser';
import { StrapiService } from '../../../services/strapi.service';

import { Router } from '@angular/router';

@Component({
  selector: 'app-blog',
  templateUrl: './blog.component.html',
  styleUrls: ['./blog.component.scss']
})
export class BlogComponent implements OnInit {

  datas:any=[];
  errores:string="";

  constructor(
    public strapiserv:StrapiService,
    private router: Router
  ) { }

  ngOnInit(): void {

    this.title.setTitle('Blog');

    this.strapiserv.getData().subscribe(res=>{

        this.datas= res as string[];

    }, error =>{
      console.log(error);
        if(error.status == 0){
            this.errores="Código del error: "+error.status+" n Ha ocurrido un error del lado del cliente o un error de red.";
        }else{
            this.errores="Código del error: "+error.status+"nn"+error.statusText;
        }
    })

  }


}

Here is my Angular service named ‘strapi.service.ts’


import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
@Injectable({
  providedIn: 'root'
})
export class StrapiService {

  REST_API: string ='http://localhost:1337/articles';
  //https://strapi-dot-gmal-api-313723.uc.r.appspot.com/
  httpHeaders = new HttpHeaders().set('Content-Type', 'application/json');
  constructor(private httpClient: HttpClient) { }


  getData():Observable<any>{
    console.log();
    let API=this.REST_API;
    return this.httpClient.get(API,{headers:this.httpHeaders}) .pipe(
      map((data:any) => { 
      
        return data;
      }), catchError( error => {
        return throwError(error);
      })
    )
    
  }

  /*getItem( idx:number ){
    return this.data[idx];
  }*/
 
 
}

And Here is my pagina.component.ts file where I want to show the complete detailed Blog


import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Router } from '@angular/router';

import { StrapiService } from '../../../../services/strapi.service';

@Component({
  selector: 'app-pagina',
  templateUrl: './pagina.component.html',
  styleUrls: ['./pagina.component.scss']
})
export class PaginaComponent implements OnInit {

  data:any = {};


  constructor( private activatedRoute: ActivatedRoute,
           private router: Router,
           public strapiserv:StrapiService
    ){ 

    this.activatedRoute.params.subscribe( params => {
      this.data = this.strapiserv.getData( params['id'] );
    });

  }

  ngOnInit(): void {
  }

}
 

My routes are:

const routes: Routes = [
    { path: 'blog', component: BlogComponent },
    { path: 'pagina/:id', component: PaginaComponent },
];

Is there an another way to get date instead of getting it from user’s device

I want to make an application that will only open at a specific date. I use new date() to do that, but new date() get time from the user’s device and the the user can open it by changing the time on its own device.

Example:

  let setdate = new Date('2021-12-10')
   let currentdate = new Date()
   console.log(setdate)
   if(setdate.getDate() == currentdate.getDate()){
    document.getElementById("result").style.display = 'revert'
   }
<div id=result style="display:none">Open now!!!</div>

If I don’t do anything with the time of my device, it won’t do anything. But if I change the date on my device to the specific date, then the area could open.

Could anyone suggests me a better way that could prevent this situation or is there an another way to get date instead of getting it from user’s device

Thanks for any responds!!!

Colores :root dinamicos desde sass al cargar pagina

Necesito de su ayuda para resolver la siguiente inquietud
quisiera cambiar los colores del :root del css desde los datos cargados de mi servidor (DB).Tengo una sass con los estilos `
$color-primary: #56b4d8;

$theme-colors: (
primary: $color-primary,
secondary: #56b4d8,
success: #0ebd65,
info: #198ae3,
warning: #fed713,
danger: #e64b4b,
light: #f8f9fa,
dark: #1a1a1a);`

mi requerimiento es necesito cambiar estos colores desde el servidor al cargar la imagen, quizas exista alguna manera de pasarle datos a las varibales de sass $

الجمال واللياقة البدنية

الجمال واللياقة البدنية

يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين – كمال اجسام – العناية بالوجه – العناية بالجسم – العناية بالبشرة – العناية بالشعر

يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين – كمال اجسام – العناية بالوجه – العناية بالجسم – العناية بالبشرة – العناية بالشعر

يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين – كمال اجسام – العناية بالوجه – العناية بالجسم – العناية بالبشرة – العناية بالشعر

يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين – كمال اجسام – العناية بالوجه – العناية بالجسم – العناية بالبشرة – العناية بالشعر

يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين – كمال اجسام – العناية بالوجه – العناية بالجسم – العناية بالبشرة – العناية بالشعر

يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين – كمال اجسام – العناية بالوجه – العناية بالجسم – العناية بالبشرة – العناية بالشعر

يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين – كمال اجسام – العناية بالوجه – العناية بالجسم – العناية بالبشرة – العناية بالشعر