Retries with got

This is a simple script to test the retry functionality of the got library.
The code works and it retries if you add an invalid url (I’m using an invalid url for test), but it won’t stop trying after the set limit (5 attemps).
I followed the documentation on GitHub; is the problem related on the status code returned by the server (error message: Bad response: 502)? If that were the case, if you try with another valid url (I don’t have anyone) or simple disconnect your pc from the network (it throws the error connect ENETUNREACH) then you get an error that should be valid for the limit purpose (as indicated in the documentation).
Where is the error?
Thanks.

import got from "got";
import { HttpsProxyAgent, HttpsProxyAgentOptions } from "hpagent";

async function gotDownloader() {
  let proxyParametersSetup: HttpsProxyAgentOptions = {
    keepAlive: true,
    keepAliveMsecs: 1000,
    maxSockets: 256,
    maxFreeSockets: 256,
    scheduling: "lifo",
    proxy: "http://_put_your_proxy_url_here:port",
  };

  const proxyParameters = {
    agent: {
      https: new HttpsProxyAgent({ ...proxyParametersSetup }),
    },
  };

  type RetryCounter = {
    [key: string]: number;
  };
  const retryCounter: RetryCounter = {};

  const url = "https://postman-echo.com/get?foo1=bar1&foo2=bar2";
  // const url = "https://www.www.www"; // wrong url to test
  try {
    let gotIstance = got.extend({
      retry: {
        limit: 5,
        calculateDelay({ error }) {
          let valueToReturn = 0;
          let counter;
          if (!retryCounter[url]) {
            counter = retryCounter[url] = 1;
          } else {
            counter = retryCounter[url]++;
          }
          if (error.code !== "200") {
            console.error(
              `ERROR with code ${error.code} - error message: ${error.message} - parametersForDataDownload: ${url} - counter: ${counter}`
            );
            valueToReturn = 1000;
          } else {
            console.error(
              `NOT 200 ERROR - code ${error.code} - error message: ${error.message} - parametersForDataDownload: ${url} - counter: ${counter}`
            );
            valueToReturn = 0;
          }
          return valueToReturn;
        },
        methods: ["GET"],
      },
    });
    let jsonDataFromUrl = await gotIstance(encodeURI(url), {
      ...proxyParameters,
    });
    return true;
  } catch (error) {
    console.error(`GOT DOWNLOADER ERROR with url: ${url} - Error: ${error}`);
    return false;
  }
}

gotDownloader().then((returnedValue) => {
  if (returnedValue) {
    console.log(`OK-->resolve: ${returnedValue}`);
  } else {
    console.log(`KO-->reject: ${returnedValue}`);
  }
});

How can i have reusable input component?

I’m using Typescript, Vue and Vee-Validate. I’m trying to build a reusable input component and it works with one input component. But I can’t insert more than one component. I tried a few things, but it didn’t work.

Does anyone have an idea how to customize the code for multiple components?

Here is parent component

<script lang="ts">
import { Form, useField, useForm } from 'vee-validate'
import { string } from 'yup'

export default defineComponent({
    components: {}
})
</script>

<script lang="ts" setup>

const label: string = 'First Field'
const { handleSubmit, errors } = useForm({
    validationSchema: {
        query: string().required('required.'),
    },
    initialValues: {
        query: '',
    },
})
const { value: query } = useField<string>('query')
const onSubmit = handleSubmit(async () => {
    alert('Well Done')
})
</script>
<template>
    <main class="min-h-screen">
        <div class="base-container">
        Content
        </div>
        <Form @submit.prevent>
            <ChildComponent v-model="query" :label="label" placeholder="Yo" :error="errors.query" />
            <button class="bg-red-500 text-white text-sm px-4 py-2 mt-10 rounded-lg"
              type="submit" 
              @click="onSubmit"
            >
            Submit
            </button>
        </Form>
    </main>
</template>

Bad request error from UrlFetchApp when fetching the API url

I am getting the following error message: Bad request: [URL] when fetching the API URL using UrlFetchApp.
I need to pass the access token which has been received from the authorization server using a GET request.

My code is:-

function run()
 {
  var service = getOAuthService();
  var authorizationUrl = service.getAuthorizationUrl();
    Logger.log('Open the following URL and re-run the script: %s',
        authorizationUrl);
  Logger.log(JSON.stringify(service.getAccessToken(), null, 2));
  if (service.hasAccess()) {
    var url = 'https://ffa-int-service-lnhtqfum-zgvbwhku.apps.dev.aro.forgeapp.honeywell.com/get_graph_data';
    var options =
      {
        method: 'GET',
        headers: {
          'Authorization' : 'Bearer  ' + service.getAccessToken(),
        },
        muteHttpExceptions : true,
        followRedirects: true
      };
    var response = UrlFetchApp.fetch(url,options);
    var result = JSON.parse(response.getContentText());
    Logger.log(JSON.stringify(result, null, 2));
  } else {
    var authorizationUrl = service.getAuthorizationUrl();
    Logger.log('Open the following URL and re-run the script: %s',
        authorizationUrl);
  }
}

Please help me with this.

Kind regards,
Sumedh`

Unit tests fail in randomly in mocha/chai JS

I am currently testing my Express app and I decided to go with Mocha/Chai/Chai-Http.
i set my tests and most of the times the tests pass but randomly sometimes some tests fail
there is no pattern !!

here’s the code :

let chai = require('chai');
let chaiHttp = require('chai-http');
let should = chai.should();
let server = require('../../server.api').server;
chai.use(chaiHttp);

describe('Tests', () => {
   let token={ 'test' : 'test' };

   it('Endpoint', (done) => {
       chai.request(server)
           .post(POST_ENDPOINT_PATH)
           .send(token)
           .end((err,res) => {
               res.should.have.status(200);
               res.body.should.be.a('object');
               done();
           })
   })

});

i run it with the following mocha line
$ cross-env NODE_ENV=test PROJECT_NAME=projectTest mocha --timeout 20000 ./routes/projectTest/**/*.spec.js --exit

I m using chai 4.2.0 , mocha 10.0.0 and chai-http 4.3.0

How to cancel sleeping using promise?

I’m stuck at problem about sleeping in Javascript.
I need a sleep function in ms miliseconds. And I can cancel this sleeping in some place.
And in the below is my current solution (it’s still bug).

 class Delayer {
   timeoutId = null
   cancelDelay(){
      if(this.timeoutId){
        clearTimeout(this.timeoutId)
      }
   }
   delay(ms){
     return new Promise(resolve => {this.timeoutId = setTimeout(resolve,ms)})
   }
}

const delayer = new Delayer()
await delayer.delay(3000)

But, it’s not working like I expect. Because, when I call delayer.cancelDelay() (in some where) then it clear timeout and my delay promise is not resolved.

I don’t know as if my mindset is exact. Someone can help me with it. Thanks a lot.

The object empty check is not working and changing the logic

So I am doing a form validation check and I have taken ‘formErrors’ and set the errors in this object. However it is initially {} and in my code I am checking for Object.keys(formErrors).length===0 which returns true for even {}


  const [formValues, setFormValues] = useState(initialValues);
  const [formErrors, setFormErrors] = useState({});

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormValues({ ...formValues, [name]: value });
  };

  const url = '/collectdetails';

  const handleSubmit = (e) => {
    e.preventDefault();
    setFormErrors(validate(formValues));
    // setIsSubmit(true);
    console.log(noErrors);
    if (noErrors) {
      const { fullName, phoneNumber, emailAddress, role, lookingFor, company } =
        formValues;
      const data = {
        Name: fullName,
        MobileNumber: phoneNumber,
        Email: emailAddress,
        Role: role,
        LookingFor: lookingFor,
        CompanyName: company,
      };

      getDetails(url, data).then((user) => {
        const { Response } = user;

        if (Response === 'OK') {
          setCurrentUser(phoneNumber);
          navigate('/');
        }
      });
    }
  };

  useEffect(() => {
    if (Object.keys(formErrors).length === 0) {
      console.log(formErrors);
      setNoErrors(true);
    }
  }, [formErrors]);

  

So When I submit the handleSubmit() method is run and it has 2 nested checks. The first one is for noErrors which is a bool state that checks if my object is empty. I have console logged it and it returns true when the component loads as the object is {} in the beginning. Is there any way for me to put a check so that I can see if there are some keys present in the object?

Getting json object from dynamic form group by a form field

We have a dynamic form like the one below , where each fiels like location , teams we are getting as location_0 , teams_0 when we submit the form .

        <div class="form-group" id="dynamic_form">
            <div class="row">
                <div class="col-md-12 ">
                    <label for="location" class="form-label">Location</label>
                    <select class="form-select location" name="location" id="location" group="locationInput"    
                        placeholder="Location" aria-describedby="locationFeedback" required class="selectpicker"
                        multiple>
                    </select>
                </div>
                <div class="col-md-12 ">
                    <label for="teams" class="form-label">Teams</label>
                    <select class="form-select teams" name="teams" id="teams" placeholder="Teams"  group="deskUsageInput"
                        aria-describedby="teamsFeedback" required class="selectpicker" multiple>
                    </select>
                </div>

                <div class="col-md-12 ">
                    <label for="fame" class="form-label">Teams</label>
                    <select class="form-select fame" name="fame" id="fame" placeholder="Fame"  group="deskUsageInput"
                        aria-describedby="fameFeedback" required class="selectpicker" multiple>
                    </select>
                </div>

                <div class="col-md-12 ">
                    <label for="fame" class="form-label">Teams</label>
                    <select class="form-select fame" name="fame" id="fame" placeholder="Fame"  group="deskUsageInput"
                        aria-describedby="fameFeedback" required class="selectpicker" multiple>
                    </select>
                </div>

                <div class="col-md-12 ">
                    <label for="space" class="form-label">Teams</label>
                    <select class="form-select space" name="space" id="space" placeholder="Space"  group="spaceUsageInput"
                        aria-describedby="spaceFeedback" required class="selectpicker" multiple>
                    </select>
                </div>

                <div class="button-group mt-2 mb-2 col-12">
                    <a href="javascript:void(0)" class="btn btn-primary " id="plus5">Add More Advance Properties</a>
                    <a href="javascript:void(0)" class="btn btn-danger" id="minus5">Remove</a>
                </div>
            </div>

Now i want to create an output like this , where each input is grouped by the group name.

        [{
        "locationInput": {"location_0" : ["{"campusId":1}"]},
        "deskUsageInput": {
            "teams_0": [3, 6],
            "fame_0": [3, 6]
            
        },
       "spaceUsageInput": {
            "space_0": [3, 6]
        }
        },{
        "locationInput": {"location_1" : ["{"campusId":1}"]},
        "deskUsageInput": {
            "teams_1": [3, 6],
            "fame_1": [3, 6]
            
        },
       "spaceUsageInput": {
            "space_1": [3, 6]
        }
        }]

Now we want the output while iterating all input values grouped by the group field , something like this .

        $inputs.each(function () {
      var widget_attr = this.id;
      var group = this.group ; 
      var attributeName = widget_attr.toString();
        [attr_name, key] = attributeName.split('_');
        if (group !== undefined && key !== undefined) {
          grouped[group] ??= {};
          grouped[group][key] ??= {};
          grouped[group][key][attr_name] = $(this).val();
        }
      
    });

Is there a Face Aging API for free or with a charge out there? [closed]

I’m struggling to find any face aging app with an API. Something like FaceApp would work but AFAIK they don’t sell or let anybody use their technologies. Any programming language is OK, it’s fo a school project and I just need to find one.

I’m not looking for any face recognition stuff, specifically aging like FaceApp or Snapchat filters.

Any suggestions?

Use custom button for Google Sign-in

I’m working on adding Google Sign-in to the web site (Anguar 9) and found that with the new version of Google Identity Services I’m not able to use custom button (I need it to meet several project requirements). A link that shows how to use custom button is targeted to the deprecated version. So, at the moment I’ve implemented it using ‘https://apis.google.com/js/api:client.js’.
Are you going to add support of custom buttons, similar to this article – https://developers.google.com/identity/sign-in/web/build-button#building_a_button_with_a_custom_graphic

how to get the Local Variable in some function?

 var markers =[];
 function addMarker(position) {
                     

                        var marker1 = new google.maps.Marker({
                            position: position
                        });

                        markers.push(marker1);

                        console.log(markers) //1



                    }
                    console.log(markers); //2

i declared ‘markers’ as var ,’marker1′ also declared in ‘addMarker’ function.
‘1’ has a value, but ‘2’ has no value.
I want to have the same value as 1 in 2.

Dynamically link a css

My folder structure look like below:

|--js
  |-- main.js
|--css
  |--main.css
|--Folder1
  |-- c.html
|--Folder2
  |-- d.html
|--a.html
|--b.html

All the html file will be linked to the main.js and I have something like below in the js to dynamically link the main.css but this only work for html a and b. For html c and d, it expect the css folder is within the same folder.

var theorigin = window.location.origin;
var thefile = window.location.pathname.split("/").pop();
var folder = window.location.pathname.replace(thefile, "");
var newdest = theorigin + folder;

var link = document.createElement("link");
link.href = newdest + "../css/main.css";
link.type = "text/css";
link.rel = "stylesheet";
document.getElementsByTagName("head")[0].appendChild(link);

Anyone know how to achieve that? Dynamically link the css to the html regardless the folder?

Note: I know I can link the css in the html that put inside a folder by doing this<link href="../css/main.css" rel="stylesheet" />, but for some reason I dont want to do that.

How to return data from asynchronous function [duplicate]

I am trying to push data in an async function in javascript. But when I am trying to return the array it is set as an empty array. Below is the code snippet,

 const checkCalendarAlreadyBooked = async (input) => {
  let candidates = [];
  await input.map(async (data, index) => {
    let panels = data.panel;
    await panels.map(async (panel) => {
      if (await UserCalendarModel.checkCalendarBooked(input[index].start_date, input[index].end_date, panel.id)) {
        candidates.push(input[index].candidate.id);// pushing data in array
      }
    });
  });
  console.log(candidates); //This is empty always 
  return candidates;

};

Please help me to resolve this. Any help would be appreciated.