In ReactJS application Using Format.js library how can I convert date to date and time

I am new to React & Format.js. I need to do a small task which I am not able to do so. Please help me to convert date to date and time in my react js app format.js they used as a component it is written like this.

I also followed this article but not able to understand

 <FormattedDate value={new Date(data.situDate)} year="numeric" month="short" day="2-digit" />

and inside the data it is like this response

"situDate":"2021-12-07T15:56:47.661+00:00"

I needed to show like in this format

27 oct. 2020 16:24:22

How renew greenlock-express certificates forcefully at any time?

I have CA certificates files in “greenlock.d/live/URL_PATH/”. It’s expiration date is Aug 2022.

But I want to renew them right now to check whether they are renewing or not. Please suggest me how can I renew them at any time?

What I have done:

I have tried number of solutions like:

  • Tried Some commands
  • Changing renewal time (“renewAt”) in “greenlock.d/config.json”

Code:

app.js

'use strict';

var app = function(req, res) {
    res.end('Hello, Encrypted World!');
};

module.exports = app;

server.js

'use strict';

var beapp = require('./app.js');

require('greenlock-express')
    .init({
        packageRoot: __dirname,
        maintainerEmail: "EMAIL_ID",
        configDir: './greenlock.d',
        cluster: true
    })
    // .serve(beapp);
    .ready(httpsWorker);
function httpsWorker(glx) {
    var httpsServer = glx.httpsServer(null, beapp);
    httpsServer.listen(443, "0.0.0.0", function () {
        console.info("Listening on ", httpsServer.address());
    });
}

greenlock.d/config.json

{
  "defaults": {
    "store": {
      "basePath": "./greenlock.d",
      "module": "greenlock-store-fs"
    },
    "challenges": {
      "http-01": {
        "module": "acme-http-01-standalone"
      }
    },
    "renewOffset": "-45d",
    "renewStagger": "3d",
    "accountKeyType": "EC-P256",
    "serverKeyType": "RSA-2048",
    "subscriberEmail": "EMAIL_ID"
  },
  "sites": [
    {
      "subject": "URL_PATH",
      "altnames": [
        "URL_PATH"
      ],
      "renewAt": 1
    }
  ]
}

Angular change PUT request to PATCH

I am calling an API for updating Project name, description and using ID. I have a PUT request that updates all the data. But I want to update only Project name and description. I am not able to perform the PATCH call provider. Can someone tell me how to call the PATCH request
thanks.

This is my PUT request. And I want PATCH request

put(apiUrl, data) {
const apiURL = environment.endPointUrl + apiUrl;
const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    AuthenticationKey: `${CryptoJS.AES.decrypt(
      localStorage.getItem('UAuthToken') == null
        ? ''
        : localStorage.getItem('UAuthToken'),
      environment.EncryptionKey
    ).toString(CryptoJS.enc.Utf8)}`,
  }),
};
return this.http.put(apiURL, data, httpOptions);

}

This is my Service.ts

UpdateProject(data){
const apiURL = 'http://192.168.1.22:8080/TestExpress/projects/updateProject/projectDescription/projectId/projectName';
return this.callProvider.put(apiURL, data);

}

Custom Validator function with Button on Client Click – Javascript

I have a textbox to which I have assigned a CustomValidator which has a ClientValidationFunction=”txtcheck”

ASPX:

<asp:TextBox ID="txt1"  MaxLength="10" CssClass="class1" Width="90%" runat="server"></asp:TextBox>
<asp:CustomValidator runat="server" ID="valtxt1" ControlToValidate="txt1" ValidateEmptyText="true" ValidationGroup="Save" Display="Dynamic"
                        ClientValidationFunction="txtcheck" Font-Italic="True"></asp:CustomValidator>
<asp:Button ID="btnSave" Text="Save" CausesValidation="True" runat="server" ValidationGroup="Save" OnClientClick="show()" UseSubmitBehavior="false" />

Javascript :

The alert messge is mandatory as it is required.

function txtcheck(source, args) {
Alert('incorrect value');
args.IsValid = false;
}

function show(){
var validated = Page_ClientValidate('valSave');
    if (validated) {
-- show some data.
      }
}

On click of Save Button I do a Page_ClientValidate to check other controls.

The issue is, on click of Save; txtcheck() is getting called twice.
Once via the CustomValidator & other when I do the Page_ClientValidate. Due to this the Alert message is also shown twice.

Pls guide as to how to call the txtcheck() only once & show alert once.

Any help is greatly appreciated.

complex object manipulation

I have an array:

const arr = [
    {
        countries : {countryCode :"US", value: true},
        vendors:  [{vendorName: 'TES', value: true}, {vendorName: 'HPEFS', value: true}]
    },
    {
        countries : {countryCode :"CA", value: true},
        vendors:  [{vendorName: 'TES', value: true}, {vendorName: 'HPEFS', value: false}]
    }
];

expected result:  [{vendor: "TES", countries: [US, CA]}, {vendor: "HPEFS", countries: [US]}]

Any idea is appreciated, Thanks in advance

Handling form content with JavaScript and Perl

I have a music project in Perl which also requires some JavaScript but I seem to be stuck.
I need to execute a program (ffplay) as a command-line application so it runs without displaying a GUI window. The Perl handles the server end of things (sqlite database access). I need JavaScript because I display track names as a button, which when clicked is supposed to run ‘ffplay’ to play the track named in the button code. But the button click requires JavaScript.

When I click a track name button, it only displays the first track, no matter which one I
click.

The following code is in a ‘while’ loop extracting track names from the DB.

print<<EndHTML;
<script>
function process(form) {
    var form=document.Player
        alert ("Track: " + form.Player.Track.value)
}
</script>
EndHTML

print qq{<form name="Player">};
print qq{<input type="button" onClick="process(this.form)" class="alphaButton" name="Track" value="$Track"><br/>};
print qq{</form>};

Google Drive API doesn’t show files inline

I am trying to show a file from the Google Drive API inline so that the browser will display it. So far when I request the file it only downloads it. But when I add some code to make it show it in line I get the error “Failed to load PDF document”.

Here is my code:

const googleFile = new Request(`https://www.googleapis.com/drive/v3/files/${FileID}?alt=media`, {
      method: "GET",
      headers: {
        "Authorization": `Bearer ${googletoken}`,
      },
    });
const googleFileResponse = new Response(fetch(googleFile), {
      headers: {
        'Content-Disposition': 'inline',
      }
    });
    return googleFileResponse

Thanks for your help.

angular asynchronous request from multiple methods

From ngOnchanges I called the method _generateLocationFormForApproval and it has an output which is this.absoluteUri. After calling _generateLocationFormForApproval the next call is _pageEventDealsForApprovalList. Now I want to access the result from _generateLocationFormForApproval whic is this.absoluteUri inside _pageEventDealsForApprovalList after its result but it is giving me undefined although this.absoluteUri has a value.

Any idea ? with the asynchronous call ? Thansk.

#code

  ngOnChanges(changes: SimpleChanges): void {
      if(this.dealId) {
        this._generateLocationFormForApproval();
        this._pageEventDealsForApprovalList();
      }
    }
    
    
    
    private  _generateLocationFormForApproval() {
      this.dealService.generateLocationSubmission(this.dealId)
      .subscribe({
        next: (res) => {
          if (res.isSuccess) {
            this.absoluteUri = res.data.absoluteUri;
          }
        },
        error: err => this.notificationService.showError(err),
        complete: noop,
      });
    }
    
private _pageEventDealsForApprovalList() {
  console.log("1")
  console.log("this.absoluteUrithis.absoluteUri" , this.absoluteUri)
  this.searchInput = '';
  const status = [DEAL.STATUS.FORAPPROVAL, DEAL.STATUS.APPROVED]
  this.dealType = [];
  this.isLoading = true;
  this.dealService
    .getAllDeals(
      status,
      this.accountId,
      this.transaction.id,
      this.table.pageIndex + 1,
      this.table.pageSize,
      this.searchInput,
      this.table.sortParams,
      this.table.sortDirs,
      this.dealType
    )
    .pipe(finalize(() => (this.isLoading = false)))
    .subscribe((res) => {
        if(res) {
          console.log("this.uri" , this.absoluteUri)
        }
    }, (err) => this.notificationService.showError(err)
  );
}

scroll the textarea content and a child div with parent div only in react

I have a child div of line numbers and a textarea inside a parent div. So what I required is only parent div should be scrollable, neither textarea nor child div. Also height of the parent should be fixed to 170px.

enter image description here

Following is Jsx code

      <div
        style={{
          display: 'flex',
          overflowY: 'auto',
          height: '150px',
        }}
      >
        <div style={{ marginRight: '10px' }}>
          {lineNumbers?.map((item: any) => (
            <TextWrapper
              key={item}
              text={`${item}`}
              className={'marginTB2'}
            />
          ))}
        </div>
       
        <textarea
          rows={6}
          value={enteredAdrs}
          onChange={(e) => {
            setEnteredAdrs(e.target.value)
          }}
          onBlur={handleManualData}
          onKeyDown={handleKeyDown}
        /> 
        
      </div>

following is css code

 textarea{
    background-color: #151414;
    color: #fff;
    padding: 0;
    line-height: 157%;
    box-sizing: border-box;
    border: none;
    margin: 0;
    width: 100%;
    resize: none !important;
    height: 100%;
  }

  textarea:focus{
    box-shadow: none !important;
    outline: none;
  }

can i get selected option country from intl-tel-input (PHP EDIT DATA)

I’m new and right now i’m practicing create form with two fields (phone number and country). I’m using intl-tel-input from https://github.com/jackocnr/intl-tel-input and i wonder can i get selected option country using PHP while the data using intl-tel-input. Here’s my HTML & PHP code

<div class="form-group">
    <label for="exampleFormControlInput1">Country of Origin</label>
    <select class="custom-select" id="country" name="country" value="<?=$pecah2['origin_country'] ?>" <?php if($pecah2['origin_country'] = $pecah2['origin_country']){echo 'selected="selected"';} ?>></select>
</div>
<div class="form-group">
    <label for="exampleFormControlInput1">Phone Number</label><br>
    <input type="text" class="form-control" name="phonenumber" id="phone" required value="<?= $pecah2['phone_number'] ?>">
</div>

JS

<script src="https://code.jquery.com/jquery-3.6.0.min.js" type="text/javascript"></script>
<script src="assets/build/js/intlTelInput.js" type="text/javascript"></script>
<script src="assets/build/js/intlTelInput.min.js" type="text/javascript"></script>
<script>
   var input = document.querySelector("#phone");
   var countryData = window.intlTelInputGlobals.getCountryData();
   var addressDropdown = document.querySelector('#client_country');
   var iti = window.intlTelInput(input, {
       utilsScript :'assets/build/js/utils.js'
   });
   for (var i = 0; i < countryData.length; i++){
       var country = countryData[i];
       var optionNode = document.createElement("option");
                        optionNode.value = country.iso2;
       var textNode = document.createTextNode(country.name);
                        optionNode.appendChild(textNode);
                        addressDropdown.appendChild(optionNode);
                       }

      addressDropdown.value = iti.getSelectedCountryData().iso2;
                       
      input.addEventListener('countrychange',function(){
                        addressDropdown.value = iti.getSelectedCountryData().iso2;
                       });

      addressDropdown.addEventListener('change', function(){
                        iti.setCountry(this.value);
                       });
</script>

i’m practicing by different youtube videos by the way

How to update a javascript object keys value using the index of an object

I have an array of object like

const test = [{id: 1, text: "Test"}, { id: 2 , text: "Test 2" } ]
const index =  test.findIndex((listItem) => listItem === test[0])

Here I am trying to update the value of text key using the index.

I have a solution like this:

 const editItemText = (value) => {
    const newList = replaceItemAtIndex(todoList, index, {
      ...item,
      text: value,
    });

    setTodoList(newList);
  };
  
const replaceItemAtIndex =  [...arr.slice(0, index), newValue, ...arr.slice(index + 1)];

is there any other option to do so ? Also How does the given solution works ?

Thanks.

Creating and accessing unique html div via javascript

Part of my script using the below to create the div.

days += <div class="day${i}">${i}</div>;

My question is how do I access it?

document.querySelector(“.day8”).addEventListener(“click”, () => {

Using this method works with other divs I have created but doesn’t seem to work with divs inside divs… The structure is “day” inside of “days”.

Sorry if this is not clear.

please, I can’t handle the eventlistener

I’m working on my college’s project and it’s kinda like a web-text-based game, where the player come and play. so I’m interesting in a click event on a document to change the context and I did it with the code below…. the problem is that it’s keep repeating everything and I can’t even type in the input!!

const homepage = document.querySelector('#homepage')

document.addEventListener('click',function(){
/*I console.log to check that the function is still repeating*/
console.log('check')
homepage.innerHTML = `<div> hello what's your name? </div>`
document.addEventListener('click',function() {
homepage.innerHTML = `<div> my name is <br> 
<input id="name"> </input> <br>
<button> submit </button<
`
})
})
#homepage {
  text-align: center;
}
<body>
<div id = "homepage"> click to change the content </div>