Snippets Collections
let myAge = 25;
let earlyYears = 2;
earlyYears *= 10.5;

let laterYears = (myAge-2);
console.log(laterYears);
console.log(earlyYears);

laterYears *= 4;
console.log(laterYears);

let myAgeInDogYears= (laterYears + earlyYears);
console.log(myAgeInDogYears);


let myName = "Sequan".toLowerCase();

console.log(`My name is ${myName}. I am ${myAge} years old in human years which is ${myAgeInDogYears} years old in dog years. `)
const myPet = 'armadillo';
console.log(`I own a pet ${myPet}.`);

let myName = 'Natalia';
let myCity = 'Mexico City';

console.log(`My name is ${myName}. My favorite city is ${myCity}.`)
let spaceship = {
  'Fuel Type' : 'Turbo Fuel',
  homePlanet : 'Earth'
};

// Write your code below

let greenEnergy = obj => {
  obj['Fuel Type'] = 'avocado oil';
}

let remotelyDisable = obj => {
  obj.disabled = true;
}

greenEnergy(spaceship);

remotelyDisable(spaceship);

console.log(spaceship)
let spaceship = {
  passengers: [{name: 'Space Dog'}], 
  telescope: {
    yearBuilt: 2018,
    model: "91031-XLT",
    focalLength: 2032 
  },
  crew: {
    captain: { 
      name: 'Sandra', 
      degree: 'Computer Engineering', 
      encourageTeam() { console.log('We got this!') },
     'favorite foods': ['cookies', 'cakes', 'candy', 'spinach'] }
  },
  engine: {
    model: "Nimbus2000"
  },
  nanoelectronics: {
    computer: {
      terabytes: 100,
      monitors: "HD"
    },
    'back-up': {
      battery: "Lithium",
      terabytes: 50
    }
  }
}; 

let capFave = spaceship.crew.captain['favorite foods'][0];

let firstPassenger = spaceship.passengers[0];

console.log(capFave);
console.log(firstPassenger);
let retreatMessage = 'We no longer wish to conquer your planet. It is full of dogs, which we do not care for.';

// Write your code below

let alienShip = {
  retreat() {
    console.log(retreatMessage)
  },
  takeOff() {
    console.log('Spim... Borp... Glix... Blastoff!')
  }
};

alienShip.retreat();

alienShip.takeOff();
let spaceship = {
  'Fuel Type' : 'Turbo Fuel',
  homePlanet : 'Earth',
  color: 'silver',
  'Secret Mission' : 'Discover life outside of Earth.'
};

// Write your code below

spaceship.color = 'glorious gold';

spaceship.numEngines = 9;

delete spaceship['Secret Mission'];
let spaceship = {
  'Fuel Type' : 'Turbo Fuel',
  'Active Mission' : true,
  homePlanet : 'Earth', 
  numCrew: 5
 };

let propName =  'Active Mission';

// Write your code below

let isActive = spaceship['Active Mission'];

console.log(spaceship[propName]);
let spaceship = {
  homePlanet: 'Earth',
  color: 'silver',
  'Fuel Type': 'Turbo Fuel',
  numCrew: 5,
  flightPath: ['Venus', 'Mars', 'Saturn']
};

// Write your code below

let crewCount = spaceship.numCrew;

let planetArray = spaceship.flightPath;
  document.addEventListener('DOMContentLoaded', function() {
var toggleSoundButton = document.querySelector('.toggle_sound');
var icon = document.querySelector('.toggle_sound i');
var heroBackgroundVideo = document.querySelector('.video video');
toggleSoundButton.addEventListener('click', function (event) {
if (heroBackgroundVideo.muted !== false){
	 
heroBackgroundVideo.muted=false;
icon.classList.add("fa-volume-up");
} else {
	 
heroBackgroundVideo.muted=true;
icon.classList.remove("fa-volume-up");
} }); }); 
tell application "Google Chrome"
    tell active tab of front window
        execute javascript "document.getElementsByClassName('artdeco-button artdeco-button--2 artdeco-button--secondary ember-view m1')[0].click();"
    end tell
end tell
class MDFooterSelectorLocalizationForm extends HTMLElement {
        constructor() {
            super();
            this.elements = {
                selectorCountry: this.querySelector("#md-footer-selector__country"),
                selectorLanguage: this.querySelector("#md-footer-selector__language")
            };
            this.elements.selectorCountry.addEventListener('change', this.onItemChange.bind(this));
            this.elements.selectorLanguage.addEventListener('change', this.onItemChange.bind(this));
        }
 
        onItemChange() {
            const form = this.querySelector('form');
 
            let countrySelector = document.getElementById('md-footer-selector__country');
            let countryCode = countrySelector[countrySelector.selectedIndex].dataset.country;
            let countryCodeDomain = document.domain;
 
            if (typeof document.domain.split('.')[2] !== 'undefined') {
                countryCodeDomain = document.domain.split('.')[1]+'.'+document.domain.split('.')[2];
            }
            document.cookie = `mdApp_countryCodeDomain=${countryCode}; domain=${countryCodeDomain}; path=/; max-age=${60 * 60 * 24 * 60};`;
 
            if (form) {
                form.submit();
            }
        }
    }
    customElements.define('md-footer-selector__form', MDFooterSelectorLocalizationForm);
class MDFooterSelectorLocalizationForm extends HTMLElement {
        constructor() {
            super();
            this.elements = {
                selectorCountry: this.querySelector("#md-footer-selector__country"),
                selectorLanguage: this.querySelector("#md-footer-selector__language")
            };
            this.elements.selectorCountry.addEventListener('change', this.onItemChange.bind(this));
            this.elements.selectorLanguage.addEventListener('change', this.onItemChange.bind(this));
        }

        onItemChange() {
            const form = this.querySelector('form');

            let countrySelector = document.getElementById('md-footer-selector__country');
            let countryCode = countrySelector[countrySelector.selectedIndex].dataset.country;
            let countryCodeDomain = document.domain;

            if (typeof document.domain.split('.')[2] !== 'undefined') {
                countryCodeDomain = document.domain.split('.')[1]+'.'+document.domain.split('.')[2];
            }
            document.cookie = `mdApp_countryCodeDomain=${countryCode}; domain=${countryCodeDomain}; path=/; max-age=${60 * 60 * 24 * 60};`;

            if (form) {
                form.submit();
            }
        }
    }
    customElements.define('md-footer-selector__form', MDFooterSelectorLocalizationForm);
var faturasFechadas = [
    { 
        "valorFatura": {
            "valor": -1665.46, 
            "moeda": "R$" 
            
        },
        "dataFechamento": "2025-03-26T00:00:00", 
    },
    { 
        "valorFatura": {
            "valor": -1665.46, 
            "moeda": "R$" 
            
        }, 
        "dataFechamento": "2025-03-26T00:00:00"
    }
];
    
var detalhesFatura = {
    "numeroCartao": "xxxxxxxxxxxx1193",
    "detalhesLancamentoParcela": {
        "quantidadeParcelas": 12,
        "numeroParcelaTransacao": 7
        
    },
    "dataVencimentoFatura": "2025-03-01T00:00:00"
}

var result = faturasFechadas.map(function(el) {
    var o = Object.assign({}, el);
    o.detalhesFatura = detalhesFatura;
    return o;
});

console.log(JSON.stringify(result));
//Math object can not be changed
console.log(Math.PI);


function randomSelection(arr){
   let index = Math.floor(Math.random()*arr.length);
   return arr[index];
}

let happiness = ['Hope','Joy','Peace','Love','Kindness','Puppies','Kittens','Tortoise'];

for (i=0; i < 8; i++){
   console.log(randomSelection(happiness));
}
let giraffe = {
  species: "Reticulated Giraffe",
  name: "Cynthia",
  weight: 1500,
  age: 15,
  diet: "leaves"
};

function birthday(animal) {
    animal.age = animal.age + 1;
    return animal;
}

console.log(giraffe.age);

birthday(giraffe);

console.log(giraffe.age);
let giraffe = {
  species: "Reticulated Giraffe",
  name: "Cynthia",
  weight: 1500,
  age: 15,
  diet: "leaves"
};

for (item in giraffe) {
   console.log(item + ", " + giraffe[item]);
}

let spaceship = {
    crew: {
    captain: { 
        name: 'Lily', 
        degree: 'Computer Engineering', 
        cheerTeam() { console.log('You got this!') } 
        },
    'chief officer': { 
        name: 'Dan', 
        degree: 'Aerospace Engineering', 
        agree() { console.log('I agree, captain!') } 
        },
    medic: { 
        name: 'Clementine', 
        degree: 'Physics', 
        announce() { console.log(`Jets on!`) } },
    translator: {
        name: 'Shauna', 
        degree: 'Conservation Science', 
        powerFuel() { console.log('The tank is full!') } 
        }
    }
}; 

// Write your code below
for (let crewMember in spaceship.crew) {
  console.log(`${crewMember}: ${spaceship.crew[crewMember].name}`);
}
for (let crewMember in spaceship.crew) {
  console.log(`${spaceship.crew[crewMember].name}: ${spaceship.crew[crewMember].degree}`);
let tortoiseOne = {
    species: "Galapagos Tortoise",
    name: "Pete",
    weight: 919,
    age: 85,
    diet: ["pumpkins", "lettuce", "cabbage"]
};
//In the case of Pete, our zoo's friendly Galapagos Tortoise, the object tortoiseOne has several properties for his species, name, weight, age, and diet. If we wanted to add a method to our object, we might add a function that returns a helpful statement for the general public.
let tortoiseOne = {
    species: "Galapagos Tortoise",
    name: "Pete",
    weight: 919,
    age: 85,
    diet: ["pumpkins", "lettuce", "cabbage"],
    sign: function() {
        return this.name + " is a " + this.species;
    }
 };
//In the example above, on line 8, we see a keyword which is new to us. Programmers use the this keyword when they call an object's property from within the object itself. We could use the object's name instead of this, but this is shorter and easier to read. For example, the method, sign, could have a return statement of tortoiseOne.name + " is a " + tortoiseOne.species". However, that return statement is bulky and will get more difficult to read with more references to the tortoiseOne object.

let tortoiseTwo = {
    species: "Galapagos Tortoise",
    name: "Pete",
    weight: 919
};

console.log(tortoiseTwo);

tortoiseTwo["age"] = 120;
tortoiseTwo["speed"] = 'Faster than the hare.'

console.log(tortoiseTwo);
console.log(tortoiseTwo.age);
@wire(callout2Apex,{id: this.recordId})
faturaAbertaWired({ error, data }) {
  if (data) {
    this.arr = JSON.parse(data).keyFromJSON;
    this.loaded = true;
  } else if (error) {
    this.loaded = false;
  };
}
// Move file to another Google Drive Folder

function moveFileToAnotherFolder(fileID, targetFolderID) {
  var file = DriveApp.getFileById(fileID);

  // Remove the file from all parent folders
  var parents = file.getParents();
  while (parents.hasNext()) {
    var parent = parents.next();
    parent.removeFile(file);
  }

  DriveApp.getFolderById(targetFolderID).addFile(file);
}
new Date('2020-02-21' + 'T00:00');

// or

new Date('2020-02-21T00:00');

//or

const dateFromDateInput = '2020-02-21';
const dateFromTimeInput = '05:00';
cosnt baseDate = (new Date(`${dateFromDateInput}T${dateFromTimeInput}`));

//then, now you can use date-fns getUnixTime to turn it into timestamp
//turn timestamp into human readable date with fromUnixTime 
function getObjectDataByKey( field, theObject ){
	// get data
	return field.split('.').reduce((o,i)=> o[i], theObject);
}

// a simple object
const myObject = {
  name: 'John',
  lastname: 'Doe',
  data: {
    birthDate: '01/01/1970',
    placeOfBirth: 'San Francisco'
  }
}

// variable representing a key of the object
const field = 'data.birthDate';

console.log ( getObjectDataByKey ( field , myObject ) );
//will print
//01/01/1970

// also simple key will return correct value
console.log ( getObjectDataByKey ( 'name' , myObject) );
//will print
//John
const logVisibleLightWaves = () => {
  let lightWaves = 'Moonlight';
	let region = 'The Arctic';
  // Add if statement here:
  if (region === 'The Arctic'){
    let lightWaves = 'Northern Lights';
    console.log(lightWaves);
  }
  console.log(lightWaves);
};

logVisibleLightWaves();
1. git checkout dev-david
2. git rebase master
3. git add .
4. git rebase --continue

===
Successfully rebased and updated refs/heads/dev-david.
==
5. git push origin dev-david --force
6. git checkout master
7. git merge dev-david 
8. git push

git rebase --continue
git rebase --abort
const getSleepHours = day => {
  if (day === 'monday') {
    return 8;
  } 
  else if(day === 'tuesday'){
    return 7;
  }
  else if(day === 'wednesday'){
    return 3;
  }
  else if(day === 'thursday'){
    return 8;
  }
  else if(day === 'friday'){
    return 5;
  }
  else if(day === 'saturday'){
    return 6;
  }
  else if(day === 'sunday'){
    return 9;
  }
  else
  return 'Error!'
};
console.log(getSleepHours('wednesday'));

const getActualSleepHours = () => 
getSleepHours('monday') +
getSleepHours('tuesday') +
getSleepHours('wednesday') +
getSleepHours('thursday') +
getSleepHours('friday') +
getSleepHours('saturday') +
getSleepHours('sunday');

console.log(getActualSleepHours());


const getIdealSleepHours = () =>{
  let idealHours = 8;
  return idealHours * 7;
};

const calculateSleepDebt = () =>{
const actualSleepHours = getActualSleepHours();
const idealSleepHours = getIdealSleepHours();

if (actualSleepHours === idealSleepHours){
  console.log('Good Job you got just the right amount of sleep');
}
else if(actualSleepHours > idealSleepHours){
  console.log('You got' + (idealSleepHours - actualSleepHours) + 'hours more sleep than you needed');
}
else if (actualSleepHours < idealSleepHours){
  console.log('Hey you need to get about'+ " "+(idealSleepHours- actualSleepHours)+' ' + 'hours of some more rest!');
}
else {
  console.log('Error! Something went wrong, check your code');
}
};

calculateSleepDebt();
const data = ['a', 'b', 'c', 'd'],
      [last] = data.slice(-1);

console.log(last);
<html>
</head>
    <link
        rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/css/intlTelInput.css"
      />

<script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/intlTelInput.min.js"></script>

   <script>
    const phoneInputField = document.querySelector("#phone");
    const phoneInput = window.intlTelInput(phoneInputField, {
        // preferredCountries: ["us", "mz", "sa", "za"],
        // initialCountry: "auto",
        // geoIpLookup: getIp,
        utilsScript:
        "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js",
    });

    const info = document.querySelector(".alert-info");

    function process(event) {
    event.preventDefault();
      
    const phoneNumber = phoneInput.getNumber();

    info.style.display = "";
    info.innerHTML = `Phone number in E.164 format: <strong>${phoneNumber}</strong>`;
    }

    function getIp(callback) {
     fetch('https://ipinfo.io/json?token=<your token>', { headers: { 'Accept': 'application/json' }})
       .then((resp) => resp.json())
       .catch(() => {
         return {
           country: 'us',
         };
       })
       .then((resp) => callback(resp.country));
    }
 </script>

</head>

 <body>
    <div class="container">
        <form id="login" onsubmit="process(event)">
          <p>Enter your phone number:</p>
          <input id="phone" type="tel" name="phone" />
          <input type="submit" class="btn" value="Verify" />
        </form>
        <div class="alert alert-info" style="display: none;"></div>
    </div>
 </body>
 </html>
function onOpen() {
  var ui = SpreadsheetApp.getUi();
  // Or DocumentApp or FormApp.
  ui.createMenu('Custom Menu')
      .addItem('First item', 'menuItem1')
      .addSeparator()
      .addSubMenu(ui.createMenu('Sub-menu')
          .addItem('Second item', 'menuItem2'))
      .addToUi();
}

function menuItem1() {
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
     .alert('You clicked the first menu item!');
}

function menuItem2() {
  SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
     .alert('You clicked the second menu item!');
}
https://docs.google.com/forms/d/e/xxxx/viewform
   ?entry.1808207196=EMPLOYEEID&entry.1663131167=EMPLOYEENAME
   &entry.1819275928=2020-06-03&entry.2071782719=Female
   &entry.175059757=Hyderabad
const getUserChoice = userInput => {
  userInput = userInput.toLowerCase();
  if (userInput === 'rock' || userInput === 'paper' || userInput === "scissors" || userInput === 'bomb') {
  return userInput;
} else {
  console.log('Error!');
}
};



const getComputerChoice = ( ) =>{
randomNumber = Math.floor(Math.random() * 3);
switch (randomNumber) {
  case 0:
    return 'rock';
  case 1:
    return 'paper';
    case 2:
    return 'scissors';
  
}
}; 


const determineWinner = (userChoice, computerChoice) => {
if (userChoice === computerChoice){
  return 'This game is a tie';
}
if (userChoice === 'rock'){
  if (computerChoice === 'paper'){
    return 'Looks like you lost!';
  } else{
    return 'Congrats you won!!!';
  }
}
if (userChoice === 'paper'){
  if( computerChoice === 'scissors'){
    return 'Looks like you lost!';
  } else{
    return 'Congrats you won!!!';
  }
}
if (userChoice === 'scissors'){
  if (computerChoice === 'rock'){
    return 'Looks like you lost!';
  }else{
    return 'Congrats you won';
  }
}
if (userChoice === 'bomb'){
  return 'You got the answers Sway!!! You Win!!'
}
};

console.log(determineWinner('rock','scissors'));
console.log(determineWinner('rock','paper'));
console.log(determineWinner('paper','paper'));
console.log(determineWinner('bomb','paper'));



const playGame =() =>{
const userChoice = getUserChoice('rock');
const computerChoice = getComputerChoice();
console.log(`You threw: ${userChoice}`);
console.log(`The Computer threw: ${computerChoice}`);

console.log(determineWinner(userChoice,computerChoice))
};

playGame();
npx cap open ios #abrir o projecto no xcode

npx cap open android #abrir o projecto no android
<dict>
+  <key>NSCameraUsageDescription</key>
+  <string>To be able to scan barcodes</string>
</dict>
<?xml version="1.0" encoding="utf-8"?>
<manifest
  xmlns:android="http://schemas.android.com/apk/res/android"
+  xmlns:tools="http://schemas.android.com/tools" <-- adicionas esta linha não removendo nada e seguindo esta lógica

  package="com.example">

  <application
+    android:hardwareAccelerated="true" <-- adicionas esta linha não removendo nada e seguindo esta lógica
  >
  </application>

+  <uses-permission android:name="android.permission.CAMERA" /><-- adicionas esta linha não removendo nada e seguindo esta lógica

+  <uses-sdk tools:overrideLibrary="com.google.zxing.client.android" /><-- adicionas esta linha não removendo nada e seguindo esta lógica
</manifest>
ionic build --prod

#caso quiseres colocar a app para android dás o seguinte comando:
npm install @capacitor/android
npx cap add android

#caso quiseres colocar a app para iOS dás o seguinte comando:
npm install @capacitor/ios
npx cap add ios


#no final dão estes dois ultimos comandos

npx cap sync
npx cap copy Android ou ios #dependendo do qual escolheram
...

<ion-content class="scanner-hide" *ngIf="scanStatus == false">
  <div class="padding-container center">
    <ion-button color="primary" (click)="scanCode()"><ion-icon slot="start" name="qr-code-outline"></ion-icon> Scanear Código</ion-button> <!-- Botão que chama a função do scanner-->
  </div>
  <ion-card>
    <ion-card-content><h1>{{ result }}</h1></ion-card-content> <!-- mostra o resultado do scan -->
  </ion-card>
  
  <div class="scanner-ui"> <!-- Quando estamos a scanear, chama esta classe-->
    ...Scanner Interface
    </div>
    <div class="ad-spot"></div>
</ion-content>
...
import { BarcodeScanner } from '@capacitor-community/barcode-scanner';



...



export class HomePage {
  public scanStatus:boolean = false; // no inicio da página, coloca o estado do código qr para falso
  public result:any;

  constructor() {}


  async scanCode () {

    this.setPermissions(); /* chama as permissões à camera */
  
    BarcodeScanner.hideBackground(); // coloca o fundo transparente
    this.scanStatus = true; // ao mudar esta variável para true, estamos a puxar o qr code scanner 
    document.body.classList.add("qrscanner"); // adiciona a classe css que fizemos no global
    const result = await BarcodeScanner.startScan(); // começa a fazer scan e espera por um result
  
  // se o qr scanner detectou algum número, então ele faz o código abaixo
    if (result.hasContent) {

        
        this.scanStatus = false; //como é obvio, ele tem de desligar o scanner ao obter o resultado
        BarcodeScanner.stopScan(); //para o scan
        this.result = result.content; // passa o resultado para a variável global result
        BarcodeScanner.showBackground(); //volta a mostrar o fundo
        document.body.classList.remove("qrscanner"); //remove a classe css que criamos no global
    
    }
  }

  async setPermissions(){
    const status = await BarcodeScanner.checkPermission({ force: true }); /* força a permissão para true, caso o utilizador não aceite, o scanner não funciona */
    if (status.granted) {
      // the user granted permission
      return true; // se o utilizador aceitou as permissões retorna true
    }
  
      return false; // se o utilizador não aceitou retorna false
  }
}
const { v4: uuidv4 } = require('uuid');
uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
$('#element').attr('style', function(i, style)
{
    return style && style.replace(/display[^;]+;?/g, '');
});
c.addGreenBackground = function() {
  $timeout( function() { //timeout needed because we have to wait for the MRVS to be populated with the new values
    $scope.page.g_form.getDisplayValue('u_applicable_services').split(',').filter(function (el) {return el != null;}).forEach(function(el){
      if (el && $("td:contains('" + el.trim() + "')").length>0)
        $("td:contains('" + el.trim() + "')").parent().css("background-color", "#98fb98");
    })
  }, 500);
}
const plantNeedsWater = (day) => {
  if (day === 'Wednesday') {
    return true;
  } else {
    return false;
  }
};
//the above function can be refactored to this since it has only one parameter

const plantNeedsWater = day => day === 'Wednesday' ? true : false;

console.log(plantNeedsWater("Tuesday"));
let programmingLanguages = ["JavaScript", "Python", "Java", "C#"];
console.log(programmingLanguages[-1]);
console.log(programmingLanguages[100]);

let javaScriptFrameworks = ["React", "Angular", "Ember"];
console.log(javaScriptFrameworks);

// Set the value of index 2 to be "Vue"
javaScriptFrameworks[2] = "Vue";

// Notice the value at index 2 is now "Vue"
console.log(javaScriptFrameworks);

let charles = ['coder', 'Tech', 47, 23, 350];
charles.sort();
console.log(charles);


let groceryBag = ['bananas', 'apples', 'edamame', 'chips', 'cucumbers', 'milk', 'cheese'];
let selectedItems = [];

selectedItems = groceryBag.slice(2, 5).sort();
console.log(selectedItems);

let shuttleCrews = [
   ['Robert Gibson', 'Mark Lee', 'Mae Jemison'],
   ['Kent Rominger', 'Ellen Ochoa', 'Bernard Harris'],
   ['Eilen Collins', 'Winston Scott',  'Catherin Coleman']
];

console.log(shuttleCrews[0][2]);
console.log(shuttleCrews[1][1]);
console.log(shuttleCrews[2][1]);

let sshuttleCrews = [
   ['Robert Gibson', 'Mark Lee', 'Mae Jemison'],
   ['Kent Rominger', 'Ellen Ochoa', 'Bernard Harris'],
   ['Eilen Collins', 'Winston Scott',  'Catherin Coleman']
];

let newCrew = ['Mark Polansky', 'Robert Curbeam', 'Joan Higginbotham'];

// Add a new crew array to the end of shuttleCrews
sshuttleCrews.push(newCrew);
console.log(sshuttleCrews[3][2]);

// Reverse the order of the crew at index 1
sshuttleCrews[1].reverse();
console.log(sshuttleCrews[1]);
// Declare and initialize the variables for exercise 1 here:
let engineIndicatorLight = "red blinking";
let spaceSuitsOn = true;
let shuttleCabinReady = true;
let crewStatus = spaceSuitsOn && shuttleCabinReady;
let computerStatusCode = 200;
let shuttleSpeed = 15000


// BEFORE running the code, predict what will be printed to the console by the following statements:

if (engineIndicatorLight === "green") {
   console.log("engines have started");
} else if (engineIndicatorLight === "green blinking") {
   console.log("engines are preparing to start");
} else {
   console.log("engines are off");
}



let tool = 'marker';

// Use short circuit evaluation to assign  writingUtensil variable below:
let writingUtensil = tool || "pen";

console.log(`The ${writingUtensil} is mightier than the sword.`);



let stopLight = 'yellow';
 
if (stopLight === 'red') {
  console.log('Stop!');
} else if (stopLight === 'yellow') {
  console.log('Slow down.');
} else if (stopLight === 'green') {
  console.log('Go!');
} else {
  console.log('Caution, unknown!');
}
function hello(name) {
   return `Hello, ${name}!`;
}

console.log(hello("Lamar"));

//In this example, name is a parameter. It is part of the function definition, and behaves like a variable that exists only within the function.The value "Lamar" that is used when we invoke the function on line 5 is an argument. It is a specific value that is used during the function call.The difference between a parameter and an argument is the same as that between a variable and a value. A variable refers to a specific value, just like a parameter refers to a specific argument when a function is called. Like a value, an argument is a concrete piece of data.

function hello(name = "World") {
   return `Hello, ${name}!`;
}

console.log(hello());
console.log(hello("Lamar"));
//this example modifies the hello function to use a default value for name. If name is not defined when hello is called, it will use the default value.

function monitorCount(rows, columns) {
  return rows * columns;
}

const numOfMonitors = monitorCount(5, 4);

console.log(numOfMonitors);


// examples below of "helper functions" when a functions uses info from a different function

function monitorCount(rows, columns) {
  return rows * columns;
}

function costOfMonitors(rows, columns){
  return monitorCount(rows, columns) *200;
}

const totalCost = costOfMonitors(5,4);

console.log(totalCost);

//Function expressions
const plantNeedsWater = function(day) {
  if(day === 'Wednesday'){
    return true;
  }
  else{
    return false;
  }
}

console.log(plantNeedsWater("Tuesday"));

const canvas = document.querySelector('#glcanvas');
main();

//
// Start here
//
function main() {
  const gl = canvas.getContext('webgl');
  // If we don't have a GL context, give up now

  if (!gl) {
    alert('Unable to initialize WebGL. Your browser or machine may not support it.');
    return;
  }

  // Vertex shader program

  const vsSource = `
    attribute vec4 aVertexPosition;

    uniform mat4 uModelViewMatrix;
    uniform mat4 uProjectionMatrix;

    void main() {
      // We don't need the projection:
      //gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;

      // Instead we pass through each vertex position as-is:
      gl_Position = aVertexPosition;
    }
  `;

  // Fragment shader program

  const fsSource = `
    precision mediump float;


    // Require resolution (canvas size) as an input
    uniform vec3 uResolution;
      
    void main() {

      // Calculate relative coordinates (uv)
      vec2 uv = gl_FragCoord.xy / uResolution.xy;

      gl_FragColor = vec4(uv.x, uv.y, 0., 1.0);
    }
  `;  

  // Initialize a shader program; this is where all the lighting
  // for the vertices and so forth is established.
  const shaderProgram = initShaderProgram(gl, vsSource, fsSource);

  // Collect all the info needed to use the shader program.
  // Look up which attribute our shader program is using
  // for aVertexPosition and look up uniform locations.
  const programInfo = {
    program: shaderProgram,
    attribLocations: {
      vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'),
    },
    uniformLocations: {
      projectionMatrix: gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'),
      modelViewMatrix: gl.getUniformLocation(shaderProgram, 'uModelViewMatrix'),
      resolution: gl.getUniformLocation(shaderProgram, 'uResolution'),
    },
  };

  // Here's where we call the routine that builds all the
  // objects we'll be drawing.
  const buffers = initBuffers(gl);

  // Draw the scene
  drawScene(gl, programInfo, buffers);
}

//
// initBuffers
//
// Initialize the buffers we'll need. For this demo, we just
// have one object -- a simple two-dimensional square.
//
function initBuffers(gl) {

  // Create a buffer for the square's positions.

  const positionBuffer = gl.createBuffer();

  // Select the positionBuffer as the one to apply buffer
  // operations to from here out.

  gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);

  // Now create an array of positions for the square.

  const positions = [
     1.0,  1.0,
    -1.0,  1.0,
     1.0, -1.0,
    -1.0, -1.0,
  ];

  // Now pass the list of positions into WebGL to build the
  // shape. We do this by creating a Float32Array from the
  // JavaScript array, then use it to fill the current buffer.

  gl.bufferData(gl.ARRAY_BUFFER,
                new Float32Array(positions),
                gl.STATIC_DRAW);

  return {
    position: positionBuffer,
  };
}

//
// Draw the scene.
//
function drawScene(gl, programInfo, buffers) {
  gl.clearColor(0.0, 0.0, 0.0, 1.0);  // Clear to black, fully opaque
  gl.clearDepth(1.0);                 // Clear everything
  gl.enable(gl.DEPTH_TEST);           // Enable depth testing
  gl.depthFunc(gl.LEQUAL);            // Near things obscure far things

  // Clear the canvas before we start drawing on it.

  gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

  // Create a perspective matrix, a special matrix that is
  // used to simulate the distortion of perspective in a camera.
  // Our field of view is 45 degrees, with a width/height
  // ratio that matches the display size of the canvas
  // and we only want to see objects between 0.1 units
  // and 100 units away from the camera.

  const fieldOfView = 45 * Math.PI / 180;   // in radians
  const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
  const zNear = 0.1;
  const zFar = 100.0;
  const projectionMatrix = mat4.create();

  // note: glmatrix.js always has the first argument
  // as the destination to receive the result.
  mat4.perspective(projectionMatrix,
                   fieldOfView,
                   aspect,
                   zNear,
                   zFar);

  // Set the drawing position to the "identity" point, which is
  // the center of the scene.
  const modelViewMatrix = mat4.create();

  // Now move the drawing position a bit to where we want to
  // start drawing the square.

  mat4.translate(modelViewMatrix,     // destination matrix
                 modelViewMatrix,     // matrix to translate
                 [-0.0, 0.0, -6]);  // amount to translate

  // Tell WebGL how to pull out the positions from the position
  // buffer into the vertexPosition attribute.
  {
    const numComponents = 2;
    const type = gl.FLOAT;
    const normalize = false;
    const stride = 0;
    const offset = 0;
    gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);
    gl.vertexAttribPointer(
        programInfo.attribLocations.vertexPosition,
        numComponents,
        type,
        normalize,
        stride,
        offset);
    gl.enableVertexAttribArray(
        programInfo.attribLocations.vertexPosition);
  }

  // Tell WebGL to use our program when drawing

  gl.useProgram(programInfo.program);

  // Set the shader uniforms

  gl.uniformMatrix4fv(
      programInfo.uniformLocations.projectionMatrix,
      false,
      projectionMatrix);
  gl.uniformMatrix4fv(
      programInfo.uniformLocations.modelViewMatrix,
      false,
      modelViewMatrix);
  
  gl.uniform3f(programInfo.uniformLocations.resolution, canvas.width, canvas.height, 1.0);  

  {
    const offset = 0;
    const vertexCount = 4;
    gl.drawArrays(gl.TRIANGLE_STRIP, offset, vertexCount);
  }
}

//
// Initialize a shader program, so WebGL knows how to draw our data
//
function initShaderProgram(gl, vsSource, fsSource) {
  const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
  const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);

  // Create the shader program

  const shaderProgram = gl.createProgram();
  gl.attachShader(shaderProgram, vertexShader);
  gl.attachShader(shaderProgram, fragmentShader);
  gl.linkProgram(shaderProgram);

  // If creating the shader program failed, alert

  if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
    alert('Unable to initialize the shader program: ' + gl.getProgramInfoLog(shaderProgram));
    return null;
  }

  return shaderProgram;
}

//
// creates a shader of the given type, uploads the source and
// compiles it.
//
function loadShader(gl, type, source) {
  const shader = gl.createShader(type);

  // Send the source to the shader object

  gl.shaderSource(shader, source);

  // Compile the shader program

  gl.compileShader(shader);

  // See if it compiled successfully

  if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
    alert('An error occurred compiling the shaders: ' + gl.getShaderInfoLog(shader));
    gl.deleteShader(shader);
    return null;
  }

  return shader;
}
const changeToFunkyColor = (domElement) => {
  const r = Math.random() * 255;
  const g = Math.random() * 255;
  const b = Math.random() * 255;
 
  domElement.style.background = `rgb(${r}, ${g}, ${b})`;
}
async function myFetch() {
    try {
        /* Request */
        let res = await fetch('https://reqres.in/api/users/2');
        /* Check response */
        let resChecked;
        if (res.ok) { /* If successful: */
            console.log("Request successful"); 
            resChecked = res; 
            let data = await resChecked.json();
            console.log(data);
        } else { /* If unsuccessful: */
            console.log("Request unsuccessful");
        }
    } catch (err) {
        console.log(err);
    }
}

myFetch() // Prints data object containing information about user 2
fetch('https://reqres.in/api/users/2', {
    method: "DELETE",
    headers: {
        'Content-type': 'application/json'
    }
})
.then(res => {
    if (res.ok) { console.log("HTTP request successful") }
    else { console.log("HTTP request unsuccessful") }
    return res
})
.then(res => res.json())
.then(data => console.log(data))
.catch(error => console.log(error))
fetch('https://reqres.in/api/users/2', {
    method: "PUT", 
    headers: {
        'Content-type': 'application/json'
    },
    body: JSON.stringify(
        { name: "Capitain Anonymous"}
    )
})
.then(res => {
    if (res.ok) { console.log("HTTP request successful") }
    else { console.log("HTTP request unsuccessful") }
    return res
})
.then(res => res.json())
.then(data => console.log(data))
.catch(error => console.log(error))
const url = 'https://jsonplaceholder.typicode.com/users';

let data = {
  name: 'Sammy'
}

let request = new Request(url, {
  method: 'POST',
  body: JSON.stringify(data),
  headers: new Headers({
    'Content-Type': 'application/json; charset=UTF-8'
  })
});

fetch(request)
  .then(function() {
    // Handle response you get from the API
  });
function sumToN(n) {
   let sum = 0;
   for (let i = 0; i <= n; i++) {
      sum += i;
   }
   return sum;
}

console.log(sumToN(3));
//Notice that sumToN does not print anything; the output comes from the final line of the program, which prints the value returned by the function call sumToN(3).

function isEven(n) {
   if (n % 2 === 0) {
      return true;
   } else {
      return false;
   }
}

console.log(isEven(4));
console.log(isEven(7));
let names = ["Lena", "James", "Julio"];

for (let i = 0; i < names.length; i++) {
   console.log(names[i]);
}
//Following this pattern, we can create a function that prints any array of names.
function printNames(names) {
   for (let i = 0; i < names.length; i++) {
      console.log(names[i]);
   }
}
//Notice that there is nothing about this function that forces names to actually contain names, or even strings. The function will work the same for any array it is given. Therefore, a better name for this function would be printArray.Our function can be used the same way as each of the built-in functions, such as console.log, by calling it. Remember that calling a function triggers its actions to be carried out.

function printArray(names) {
   for (let i = 0; i < names.length; i++) {
      console.log(names[i]);
   }
}

printArray(["Lena", "James", "Julio"]);
console.log("---");
printArray(["orange", "apple", "pear"]);

function sayHello() {
   console.log("Hello, World!");
}
sayHello();

function sayThanks(name) {
  console.log('Thank you for your purchase '+ name + '! We appreciate your business.');
}

sayThanks("Cole");

///example of functions with default values

function makeShoppingList(item1 = 'milk', item2 = 'bread', item3 = 'eggs'){
  console.log(`Remember to buy ${item1}`);
  console.log(`Remember to buy ${item2}`);
  console.log(`Remember to buy ${item3}`);
}

const doSomething = (name, value) => {
  setValues(values => ({ ...values, [name]: value }))
}
let max: number = 10000;

for (let n = 1; n < max; n++) {
  let dist1: number = x1 + (v1 * n);
  let dist2: number = x2 + (v2 * n);
  if (dist1 === dist2) return 'YES';        
}

return 'NO';
module.exports = {
  networks: {
    development: {
    host: "127.0.0.1",	 // Localhost (default: none)
    port: 7545,		 // Standard Ethereum port (default: none)
    network_id: "*",	 // Any network (default: none)
    },
  },
    contracts_build_directory: "./artifacts/",
    
  // Configure your compilers
  compilers: {
    solc: {	
      version: "^0.8.7",
    
    // See the solidity docs for advice
    // about optimization and evmVersion
      optimizer: {
      enabled: false,
      runs: 200
      },
      evmVersion: "byzantium"
    }
  }
  };
  
const HelloWeb3 = artifacts.require("HelloWeb3");

module.exports = function (deployer) {
    deployer.deploy(HelloWeb3);
};
import PlausibleProvider from "next-plausible";

function MyApp({ Component, pageProps }) {
  return 
  	<PlausibleProvider domain="<Your domain>">
  		<Component {...pageProps} />
  	</PlausibleProvider>
}

export default MyApp
import Document, {Html, Head, Main, NextScript} from 'next/document'

class MyDocument extends Document {
    render() {
        return (
            <Html>
                <Head>
                    <base href="/"></base>
                    <script async defer data-domain="<your-domain.com>" src="https://plausible.io/js/plausible.js"></script>

                </Head>
                <body>
                <Main/>
                <NextScript/>
                </body>
            </Html>
        )
    }
}

export default MyDocument
var inputvalue = document.querySelector('#cityinput')
var btn = document.querySelector('#sub')
var city = document.querySelector('#cityoutput')
var description = document.querySelector('#description')
var temp = document.querySelector('#temp')
var wind = document.querySelector('#wind')
 
apikey = "de9fd8a722542a526890360832401551"
 
function convertion(val) {
    return (val - 273).toFixed(2)
}
 
btn.addEventListener('click', function () {
 
    fetch('https://api.openweathermap.org/data/2.5/weather?q='+inputvalue.value+'&appid='+apikey)
        .then(res => res.json())
 
        .then(data => {
 
            var namevalue = data['name']
            var descri = data['weather']['0']['description']
            var tempature = data['main']['temp']
            var wndspd = data['wind']['speed']
 
            city.innerHTML = `Weather of <span>${namevalue}<span>`;
            temp.innerHTML = `Temparature : <span>${convertion(tempature)} C</span>`
            description.innerHTML = `Sky Condition : <span>${descri}<span>`
            wind.innerHTML = `Wind Speed : <span>${wndspd} km/h<span>`
        })
 
        .catch(err => alert('Entered City Name is Wrong, Please try again!'))
})
function deepCopy(obj){
    let toString = Object.prototype.toString;
    if(typeof obj !== 'object') return obj;
    if(obj === null) return null;
    if(Array.isArray(obj)) return obj.map(deepCopy);
    let newObj = {};
    for(let key in obj){
        if(toString.call(obj[key])==='[object Date]'){
            newObj[key] = new Date(obj[key])
        } else if(toString.call(obj[key])==='[object RegExp]'){
            newObj[key] = new RegExp(obj[key])
        }else{
            newObj[key] = deepCopy(obj[key]);
        }
    }
    return newObj;
}
var dragAndDrop = document.createElement('div');
dragAndDrop.innerHTML = 'Drag and Drop';
dragAndDrop.style.width = '100px';
dragAndDrop.style.height = '100px';
dragAndDrop.style.backgroundColor = 'red';
dragAndDrop.style.position = 'absolute';
dragAndDrop.style.top = '0px';
dragAndDrop.style.left = '0px';
dragAndDrop.style.cursor = 'pointer';
dragAndDrop.style.zIndex = '9999';
document.body.appendChild(dragAndDrop);
var mouseX = 0;
var mouseY = 0;
var offsetX = 0;
var offsetY = 0;
var isDown = false;
dragAndDrop.addEventListener('mousedown', function(e) {
  isDown = true;
  offsetX = dragAndDrop.offsetLeft - e.clientX;
  offsetY = dragAndDrop.offsetTop - e.clientY;
});
document.addEventListener('mouseup', function() {
  isDown = false;
});
document.addEventListener('mousemove', function(e) {
  mouseX = e.clientX;
  mouseY = e.clientY;
  if (isDown) {
    dragAndDrop.style.left = (mouseX + offsetX) + 'px';
    dragAndDrop.style.top = (mouseY + offsetY) + 'px';
  }
});
var SingletonFactory = (function(){
    function SingletonClass() {
        //do stuff
    }
    var instance;
    return {
        getInstance: function(){
            if (instance == null) {
                instance = new SingletonClass();
                // Hide the constructor so the returned object can't be new'd...
                instance.constructor = null;
            }
            return instance;
        }
   };
})();

class RentalUnit {
  constructor(address, costPerYear) {
    this._address = address;
    this._costPerYear = costPerYear;
  }
 
  get address() {
    return this._address;
  }
 
  get costPerYear() {
    return this._costPerYear;
  }
 
  calculateMonthly() {
    return this.costPerYear / 12; 
  }
}
 
class Apartment extends RentalUnit {
  constructor(address, costPerYear, numberOfBedrooms) {
    super(address, costPerYear);
    this._numberOfBedrooms = numberOfBedrooms;
  }
 
  get numberOfBedrooms() {
    return this._numberOfBedrooms;
  }
}
// apply open credit memo(s) to invoice [assumption under the same AR account]
	var objCustPaymtRec = record.transform({
		fromType : record.Type.INVOICE,
		fromId : intInvoiceId,
		toType : record.Type.CUSTOMER_PAYMENT,
		isDynamic : true
	});
 <LoaderWrapper loading={this.state.loading}>
        <View style={styles.main}>
          {this.props.totalQuizCount > 0 && this.state.filter === "ALL" ? (
            <View style={styles.filterContainer}>
              {filters.map((filter) => (
                <View style={styles.filter} key={filter.id}>
                  <QuizFilterTab
                    filterName={filter.name}
                    active={filter.id === this.state.filter}
                    // TODO: find a way to get the total number efficiently
                    itemCount={20}
                    onPress={() => this.fetchPracticeQuiz(filter.id)}
                    key={filter.id}
                  />
                </View>
              ))}
            </View>
          ) : (
            <View style={styles.noContentContainer}>
              <QuizEmptyScreen />
            </View>
          )}

          {this.state.filter !== "ALL" && this.props.totalQuizCount === 0 ? (
            <ScrollView>
              <FlatList
                data={Object.values(this.props.quizSections)}
                renderItem={this.renderItem}
                keyExtractor={(item) => item.id}
              />
            </ScrollView>
          ) : (
            <View style={styles.noContentContainer}>
              <QuizEmptyScreen />
            </View>
          )}
        </View>
      </LoaderWrapper>
var new_str2 = end_date.toString();
      var end_day = new_str2.substring(8, 10);
      log.debug("end_day", end_day);


var rec_create_date_time = new Date();
      var rec_create_date = rec_create_date_time.getFullYear() +
        "-" +
        (rec_create_date_time.getMonth() + 1) +
        "-" +
        rec_create_date_time.getDate();
      var rec_create_time =
        rec_create_date_time.getHours() +
        ":" +
        rec_create_date_time.getMinutes() +
        ":" +
        rec_create_date_time.getSeconds();
      var rec_create_date_time_str = rec_create_date + " " + rec_create_time;
      log.debug("rec_create_date_time_str", rec_create_date_time_str);
 $('.slider-for').slick({
  slidesToShow: 1,
  slidesToScroll: 1,
  arrows: false,
  fade: true,
  asNavFor: '.slider-nav'
});
$('.slider-nav').slick({
  slidesToShow: 3,
  slidesToScroll: 1,
  asNavFor: '.slider-for',
  dots: true,
  centerMode: true,
  focusOnSelect: true
});
				
dataNonDaily = JSON.stringify(dataNonDaily);
// return masked string
function maskify(cc) {
  const text = cc.replace(/\s/g,'').replace(/\w(?=\w{4})/gi,'#');
  return text
}
maskify('1')
/*
* Solution 1
*/
const vowels = ['a','e','i','o','u']
function disemvowel(str) {
  const text = str.split('');
  const textWithoutVowels = text.filter(el => !vowels.includes(el.toLowerCase()))
  return textWithoutVowels.join('')
}
disemvowel('This website is for losers LOL!"), "Ths wbst s fr lsrs LL!')

/*
* Solution 2
*/
function disemvowel(str) {
  const noVowels = str.replace(/[aeiou]/gi, '');
  return noVowels
}
disemvowel('This website is for losers LOL!"), "Ths wbst s fr lsrs LL!')
export function idbPromise(storeName, method, object) {
  return new Promise((resolve, reject) => {
    // open connection to the database `shop-shop` with the version of 1
    const request = window.indexedDB.open('shop-shop', 1);

    // create variables to hold reference to the database, transaction (tx), and object store
    let db, tx, store;

    // if version has changed (or if this is the first time using the database), run this method and create the three object stores 
    request.onupgradeneeded = function(e) {
      const db = request.result;
      // create object store for each type of data and set "primary" key index to be the `_id` of the data
      db.createObjectStore('products', { keyPath: '_id' });
      db.createObjectStore('categories', { keyPath: '_id' });
      db.createObjectStore('cart', { keyPath: '_id' });
    };

    // handle any errors with connecting
    request.onerror = function(e) {
      console.log('There was an error');
    };
    
    // on database open success
	request.onsuccess = function(e) {
 	// save a reference of the database to the `db` variable
 	 db = request.result;
 	// open a transaction do whatever we pass into `storeName` (must match one of the 		object store names)
 	tx = db.transaction(storeName, 'readwrite');
  	// save a reference to that object store
  	store = tx.objectStore(storeName);

 	 // if there's any errors, let us know
 	 db.onerror = function(e) {
    console.log('error', e);
  };
      
    switch (method) {
  		case 'put':
   		store.put(object);
    	resolve(object);
    	break;
  	case 'get':
    	const all = store.getAll();
    	all.onsuccess = function() {
      		resolve(all.result);
    	};
    	break;
  	case 'delete':
    	store.delete(object._id);
    	break;
  	default:
    	console.log('No valid method');
    	break;
}

  // when the transaction is complete, close the connection
  tx.oncomplete = function() {
    db.close();
  };
};
    
    

  });
}
// pagination
                //     let currentPage = response.meta.current_page;
                //     let lastPage = response.meta.last_page;
                //     var pagination = ''
                //     var page_first = 0
                //     var page_last = 0
                //     if (response.meta && (response.meta.total > 5)) {
                //         if (lastPage <= 5) {
                //             page_first = 1;
                //             page_last = lastPage;
                //         } else {
                //             if (currentPage <= 3) {
                //                 page_first = 1;
                //                 page_last = 5;
                //             } else if (currentPage >= lastPage - 2) {
                //                 page_first = lastPage - 4;
                //                 page_last = lastPage;
                //             } else {
                //                 page_first = currentPage - 2;
                //                 page_last = currentPage + 2;
                //             }
                //         }

                //         pagination +=
                //             `<nav class="navigation mt-4">
                //     <div>
                //         <span class="pagination-detail d-none d-md-block">${response.meta.to ?? 0} dari ${response.meta.total } siswa</span>
                //     </div>
                //     <ul class="pagination mb-0">
                //         <li class='page-item cursor-pointer ${currentPage == 1 ? 'disabled' : ''}'>
                //             <a class="page-link page-daily grey-3" data-page="1"  tabindex="-1">&lt;</a>
                //         </li>`;
                //         for (page_first; page_first <= page_last; page_first++) {
                //             pagination += `
                //         <li class="page-item cursor-pointer">
                //             <a class="page-link page-daily ${page_first == currentPage ? 'bg-blue-tp font-w700 blue' : 'grey-6'}" data-page="${page_first}">${page_first}</a>
                //         </li>`;
                //         }
                //         pagination += `
                //         <li class="page-item cursor-pointer ${currentPage == lastPage ? 'disabled' : ''}">
                //             <a class="page-link grey-3 page-daily" data-page="${lastPage}">&gt;</a>
                //         </li>
                //     </ul>
                // </nav>`;
                //     }
                    // console.log({pagination, response, currentPage, lastPage})
                    // $('#dataAbsences').html(html)
                    // $('#pageAbsence').html(pagination)
            // end pagination
// Parent
import Child from './Child';

function App() {
  
  const pull_data = (data) => {
    console.log(data); // LOGS DATA FROM CHILD (My name is Dean Winchester... &)
  }
  
  return (
    <div className='App'>
      <Child
        func={pull_data}
      />
    </div>
  );
}

export default App;




// Child
const Child = (props) => {
  
  props.func('My name is Dean Winchester & this is my brother Sammie');
  
  return (
    <>
      <h1>I am the Child Component!</h1>
    </>
  );
}

export default Child;
const arrMin = arr => Math.min(...arr);
// arrMin([20, 10, 5, 10]) -> 5
var blobToBase64 = function(blob, callback) {
    var reader = new FileReader();
    reader.onload = function() {
        var dataUrl = reader.result;
        var base64 = dataUrl.split(',')[1];
        callback(base64);
    };
    reader.readAsDataURL(blob);
};
var reader = new FileReader();
reader.readAsDataURL(blob); 
reader.onloadend = function() {
  var base64data = reader.result;                
  console.log(base64data);
}
// create services folder and api file
import axios from "axios";

export const api = axios.create({
  baseURL: " http://localhost:3333",
});

// on the page where the useEffect is located
import { api } from "./services/api";

 useEffect(() => {
    async function getData() {
      const response = await api.get("/episodes");
      setData(response.data);
    }
    getData();
  }, []);
import React from "react";

interface Props {
  style?: string;
  type: "button" | "submit" | "reset";
  title?: string;
  icon?: React.ReactNode;
  onClick: () => void;
}

// Button component could accept text, icons and/or styles as props
// style and onClick props are mandatory
export const Button = ({ style, type, title, icon, onClick }: Props) => {
  return (
    <button className={style} type={type} onClick={onClick}>
      <span>{icon}</span>
      {title}
    </button>
  );
};
import React, { useState } from "react";
import { Button } from "./Button";

// data is an array of objects const data = [{id:1, url: "https://..."}, ...]
import { data } from "../data/carouselData";

export const Carrousel = () => {
  const [index, setIndex] = useState(0);

  // when buttons are clicked, the state (index) would increased or decreased
  // to avoid the code crash when index reachs its min and max values, conditios are set on click 	events 
  function handlePreviousBtn() {
    index > 0 ? setIndex(index - 1) : setIndex(data.length - 1);
  }

  function handleNextBtn() {
    index < data.length - 1 ? setIndex(index + 1) : setIndex(0);
  }

  return (
    // carousel has width 100% and specif height
    <div className="carousel">
      {/* Button is a custom component */}
      <Button
        style="carousel--btn left-4"
        type="button"
        title="left"
        onClick={() => handlePreviousBtn()}
      />
      <Button
        style="carousel--btn right-4"
        type="button"
        title="right"
        onClick={() => handleNextBtn()}
      />
		{/* carousel--item and carousel--item-img has widht and heigth 100% */}
      <div className="carousel--item">
        {/* also carousel--item-img has object-contain style prop */}
        <img
          className="carousel--item-img"
          src={data[index].url}
          alt="Random Image"
        />
      </div>
    </div>
  );
};
function renderIndexStudentAbsence2(data, total_non_daily) {
            html = "";
            totalData = 0;
            statusPresence = "";
            studentGroupOrCounselor = "";
            studentGroupName = "";
            totalDataGroup = Object.keys(data).length;
            if (totalDataGroup === 1) {
                studentGroupName = '|' + Object.keys(data).pop();
            }
            html += `
                <div class="table-responsive table-report-period mt-4">
                    <table class="table">
                        <thead class="no-cell-hover">
                            <tr class="text-left">
                                ${totalDataGroup === 1 ? `` : `<th class="text-left" rowspan="2">${isWikrama === "1" ? `Rayon` : `Rombel`}</th>`}
                                <th class="text-left" rowspan="2">No.</th>
                                <th class="text-left" rowspan="2">Nama</th>
                                <th class="text-center" colspan="2">Absensi Hari Ini</th>
                                ${total_non_daily === 0 ? `` : `<th class="text-center" colspan="4">JP yang Tidak Dihadiri</th>`}
                            </tr>
                            <tr>
                                <th class="text-left">Status</th>
                                <th class="text-left">Keterangan</th>
                                ${total_non_daily === 0 ? `` : `
                                                                <th class="text-left">JP ke-</th>
                                                                <th class="text-left">Status</th>
                                                                <th class="text-left">Pelajaran</th>
                                                                <th class="text-left">Guru Mapel</th>    
                                                                `}
                            </tr>
                        </thead>
                        <tbody class="index-absence-student-loading-destop">`

            $.each(data, function(key, value) {
                totalJp = 0;
                totalNumber = 1;
                totalDaily = value.length;

                let total = value.reduce((val, element) => {
                    return val + element.non_daily.length
                }, 0);

                var rowspanGroup = value.length + total;

                // console.log({
                //     total,
                //     rowspanGroup,
                //     totalDaily
                // });

                $.each(value, function(key, value) {
                    if (value.non_daily.length !== 0) {
                        totalJp = value.non_daily.length;
                    }
                })

                totalDataStudent = value.length;

                if (totalDataStudent > 1) {
                    totalJpFinal = totalJp * totalDataStudent + totalDataStudent;
                } else {
                    totalJpFinal = totalJp * totalDataStudent;
                }

                totalRowGroup = 0;

                if (totalJpFinal === 0) {
                    totalRowGroup = totalDataStudent;
                } else {
                    totalRowGroup = totalJpFinal + 1;
                }

                if (totalDaily === 1) {
                    totalJpValue = 0;
                    $.each(value, function(index, value) {
                        if (value.daily.status === "SICK") {
                            statusPresence = "Sakit";
                        } else if (value.daily.status === "UNKNOWN") {
                            statusPresence = "Alpha";
                        } else {
                            statusPresence = "Izin";
                        }

                        if (isWikrama === "1") {
                            studentGroupOrCounselor =
                                `${value.name} ${value.nis} | ${value.student_group.name}`;
                        } else {
                            studentGroupOrCounselor = `${value.name} ${value.nis}`;
                        }
                        no = index + 1;
                        var lengthMonDaily = value.non_daily.length;
                        var rowspanStudent = lengthMonDaily + 1;
                        html += `
                            <tr>
                            ${totalDataGroup === 1 ? `` : `<td class="text-left align-top" width="90px" rowspan="${rowspanGroup}">${key}</td>`}
                        `
                        html += `
                            <td class="text-right align-top" width="60px" rowspan="${totalJp + 1}">${no++}.</td>
                            <td class="text-left align-top" width="240px" rowspan="${totalJp + 1}">${studentGroupOrCounselor}</td>
                            <td class="text-left align-top" width="75px" rowspan="${totalJp + 1}">${statusPresence}</td>
                            <td class="text-left align-top" width="200px" rowspan="${totalJp + 1}">${value.daily.note === null || value.daily.note === "null" ? `<span class="font-w400 font-13 grey-6">Tidak ada keterangan.</span>` : `<span class="font-w400 font-13 black-1">${value.daily.note}</span>`}</td>
                    `
                        if (total_non_daily !== 0) {
                            if (value.non_daily.length === 0) {
                                html += `
                                    <td class="text-left grey-6" width="60px" colspan="4">Jam pelajaran belum diatur. Hubungi Waka. Kurikulum untuk melakukan pengaturan sehingga guru dapat menginput absen per JP dan laporannya tampil pada halaman ini.</td>
                                `
                            } else {
                                value.non_daily.sort(function(a, b) {
                                    var dateA = parseInt(a.school_hour.order),
                                        dateB = parseInt(b.school_hour.order);
                                    return dateA - dateB;
                                });
                                $.each(value.non_daily, function(key, value) {
                                    statusJp = "";
                                    if (value.status === "SICK") {
                                        statusJp = "Sakit";
                                    } else if (value.status === "UNKNOWN") {
                                        statusJp = "Alpha";
                                    } else {
                                        statusJp = "Izin";
                                    }
                                    html += `
                                    <tr>
                                        <td class="text-left" width="60px">${value.school_hour.order}</td>
                                        <td class="text-left cursor-pointer btn-edit-status-absence" width="75px">${statusJp}</td>
                                        <td class="text-left" width="240px">${value.subject_name}</td>
                                        <td class="text-left" width="240px">${value.teacher}</td>
                                    </tr>
                                `
                                })
                            }
                        }
                        html += `</tr>`
                    })
                } else {
                    html += `<tr>
                            ${totalDataGroup === 1 ? `` : `<td class="text-left align-top" width="90px" rowspan="${rowspanGroup}">${key}</td>`}
                        </tr>`

                    totalJpValue = 0;
                    $.each(value, function(index, value) {
                        if (value.daily.status === "SICK") {
                            statusPresence = "Sakit";
                        } else if (value.daily.status === "UNKNOWN") {
                            statusPresence = "Alpha";
                        } else {
                            statusPresence = "Izin";
                        }

                        if (isWikrama === "1") {
                            studentGroupOrCounselor =
                                `${value.name} ${value.nis} | ${value.student_group.name}`;
                        } else {
                            studentGroupOrCounselor = `${value.name} ${value.nis}`;
                        }
                        no = index + 1;

                        var lengthMonDaily = value.non_daily.length;
                        var rowspanStudent = lengthMonDaily + 1;

                        if (value.non_daily.length === 0) {
                            html += `
                                <tr>
                                    <td class="text-right align-top" width="60px">${no++}.</td>
                                    <td class="text-left align-top" width="240px">${studentGroupOrCounselor}</td>
                                    <td class="text-left align-top" width="75px">${statusPresence}</td>
                                    <td class="text-left align-top" width="200px">${value.daily.note === null || value.daily.note === "null" ? `<span class="font-w400 font-13 grey-6">Tidak ada keterangan.</span>` : `<span class="font-w400 font-13 black-1">${value.daily.note}</span>`}</td>
                            `
                            if (total_non_daily !== 0) {
                                html += `
                                    <td class="text-left grey-6" width="60px" colspan="4">Jam pelajaran belum diatur. Hubungi Waka. Kurikulum untuk melakukan pengaturan sehingga guru dapat menginput absen per JP dan laporannya tampil pada halaman ini.</td>
                                </tr>
                                `
                            }
                        } else {
                            html += `
                                <tr>
                                    <td class="text-right align-top" width="60px" rowspan="${totalJp + 1}">${no++}.</td>
                                    <td class="text-left align-top" width="240px" rowspan="${totalJp + 1}">${studentGroupOrCounselor}</td>
                                    <td class="text-left align-top" width="75px" rowspan="${totalJp + 1}">${statusPresence}</td>
                                    <td class="text-left align-top" width="200px" rowspan="${totalJp + 1}">${value.daily.note === null || value.daily.note === "null" ? `<span class="font-w400 font-13 grey-6">Tidak ada keterangan.</span>` : `<span class="font-w400 font-13 black-1">${value.daily.note}</span>`}</td>
                                </tr>
                            `
                            if (total_non_daily !== 0) {
                                if (value.non_daily.length === 0) {
                                    html += `
                                <tr>
                                    <td class="text-left grey-6" width="60px" colspan="4">Jam pelajaran belum diatur. Hubungi Waka. Kurikulum untuk melakukan pengaturan sehingga guru dapat menginput absen per JP dan laporannya tampil pada halaman ini.</td>
                                </tr>
                                `
                                } else {
                                    value.non_daily.sort(function(a, b) {
                                        var dateA = parseInt(a.school_hour.order),
                                            dateB = parseInt(b.school_hour.order);
                                        return dateA - dateB;
                                    });
                                    $.each(value.non_daily, function(key, value) {
                                        statusJp = "";
                                        if (value.status === "SICK") {
                                            statusJp = "Sakit";
                                        } else if (value.status === "UNKNOWN") {
                                            statusJp = "Alpha";
                                        } else {
                                            statusJp = "Izin";
                                        }
                                        html += `
                                            <tr>
                                                <td class="text-left" width="60px">${value.school_hour.order}</td>
                                                <td class="text-left cursor-pointer btn-edit-status-absence" width="75px">${statusJp}</td>
                                                <td class="text-left" width="240px">${value.subject_name}</td>
                                                <td class="text-left" width="240px">${value.teacher}</td>
                                            </tr>
                                        `
                                    })
                                }
                            }
                        }

                    })
                }
            })

            html += `
                    </tbody>
                </table>
            </div>
            `


            $('#name-student-group').html(studentGroupName);
            return html;
        }
I am getting this issue when using owl carousal and scrolling the images.

So get solved just adding below CSS in your page.






.owl-carousel {
-ms-touch-action: pan-y;
touch-action: pan-y;
}


or 

.owl-carousel {
-ms-touch-action: none;
touch-action: none;
}
// Write your code here   
let x1Position = x1
let x2Position = x2
const x1BiggerAndFaster = x1 >= x2 && v1 >= v2
const x2BiggerAndFaster = x2 >= x1 && v2 >= v1
do {
  const positionMatch = x1Position === x2Position;
  if (positionMatch) {
    return 'YES';
  }
  const x1PositionPassedx2Positon = (x1 >= x2) && (x1Position < x2Position)
  const x2PositionPassedx1Positon = (x2 >= x1) && (x2Position < x1Position)
  const cannotMatch = x1BiggerAndFaster || x2BiggerAndFaster || x1PositionPassedx2Positon || x2PositionPassedx1Positon
  if (cannotMatch) {
    return 'NO';
  }
  x1Position += v1
  x2Position += v2
} while (true)
const createFile = (filename, folderId, mimeType, content) => {
  const docs = () => {
    const d = DocumentApp.create(filename);
    d.getBody().editAsText().setText(content);
    d.saveAndClose();
    return d.getId();
  }
  const slides = () => {
    const s = SlidesApp.create(filename);
    s.getSlides()[0].insertTextBox(content);
    s.saveAndClose();
    return s.getId();
  }
  const sheets = () => {
    const s = SpreadsheetApp.create(filename);
    s.getSheets()[0].getRange("A1").setValue(content);
    SpreadsheetApp.flush();
    return s.getId();
  }
  const convert = {
    [MimeType.GOOGLE_DOCS]: docs,
    [MimeType.GOOGLE_SLIDES]: slides,
    [MimeType.GOOGLE_SHEETS]: sheets,
    [MimeType.MICROSOFT_WORD]: docs,
    [MimeType.MICROSOFT_POWERPOINT]: slides,
    [MimeType.MICROSOFT_EXCEL]: sheets,
    [MimeType.OPENDOCUMENT_TEXT]: docs,
    [MimeType.OPENDOCUMENT_PRESENTATION]: slides,
    [MimeType.OPENDOCUMENT_SPREADSHEET]: sheets,
  };
  const fileId = convert[mimeType]();
  if (mimeType.includes("google")) {
    Drive.Files.patch({parents: [{id: folderId}]}, fileId);
    return fileId;
  }
  const url = `https://www.googleapis.com/drive/v3/files/${fileId}/export?mimeType=${mimeType}`;
  const blob = UrlFetchApp.fetch(url, {headers: {authorization: `Bearer ${ScriptApp.getOAuthToken()}`}}).getBlob();
  const id = Drive.Files.insert({title: filename, parents: [{id: folderId}]}, blob);
  DriveApp.getFileById(fileId).setTrashed(true);
  return id;
}

// Please run this function.
function main() {
  var ss = SpreadsheetApp.openById('1MUwH0Cm1cwHcTWSCGPp2SePbzs_4QQmtjwOEWOrOkMw');
  var sheetName = ss.getSheetByName("Sheet2");
  var get = sheetName.getRange(2,3).getValue();

  const filename = "sample";
  const folderId = "1rsicZccurujGp5Ye5HUecBIAPf3_h5Pc";
  const mimeType = MimeType.GOOGLE_SLIDES;
  const fileId = createFile(filename, folderId, mimeType, get);
  console.log(fileId);
}
var onErrObj = {}
function myFunction(){

 try{
  // function code goes here;
  // add more elements to onErrObj as desired;
 }catch(e){
      onErrObj['data1'] = 'someData';
      onErrObj['data'] = 'some Other Data';
      errHandler(e,'myFunction');
 }

 function errHandler(e,strFunc){
      var message = e.message+'\n in file: '+e.fileName+' on line: '+e.lineNumber;
      var sendto = 'yourname@youremail.com';
      var subject = 'My App encountered an error occured in '+strFunc;
      var errProps = JSON.stringify(this.onError);
      message = subject+'\n'+message+'\n onError: '+errProps;
      GmailApp.sendEmail(sendto, subject, message); 
}
outJSON = [{
  team: "TeamA",
  name: "Ahmed",
  field3: "val3"
}, {
  team: "TeamB",
  name: "Ahmed",
  field3: "val43"
}, {
  team: "TeamA",
  name: "Ahmed",
  field3: "val55"
}]

var groupBy = function(xs, key) {
  return xs.reduce(function(rv, x) {
    (rv[x[key]] = rv[x[key]] || []).push(x);
    return rv;
  }, {});
};
var groubedByTeam = groupBy(outJSON, 'team')
console.log(groubedByTeam);
1.rec.save() is not needed after var rec=record.load({}) when we just want to read data from rec.
document.getElementById("id_of_tag_to_be_changed").type="text"; 
import * as nodemailer from "nodemailer";

//config nodemailer transporter using environment variables
const transporter = nodemailer.createTransport({
	host: `${process.env.AWS_SMTP_HOST}` ,
	auth: {
		user: `${process.env.AWS_ACCESS_KEY_ID}`,
		pass: `${process.env.AWS_SECRET_ACCESS_KEY}`
	}
});

export const emailSender = async (data) => {
  try {
    const response = await transporter.sendMail({
      from: process.env.EMAIL_FROM,
      to: process.env.EMAIL_TO || data.email,
      subject: process.env.EMAIL_SUBJECT || data.subject,
      html: `<DOCTYPE html>
            <html>
            <body>
			  ${data.message}
			</body>
			</html>
		`
    });
    return response?.messageId
      	? { success: true }
  		: { success: false, error: "Failed to send email" };
  } catch ( error ){
    console.log("ERROR", error.message);
    return { success: false, error: error.message };
  }
}
1.Credit Memo
Transactions > Customers > Issue Credit Memos

2.Invoices
Transactions > sales > Create Invoices
// 2.0
/**
 * @NScriptType UserEventScript
 * @NApiVersion 2.x
 */
define(["N/ui/serverWidget", "N/runtime"], function (ui, runtime) {
    var exports = {};
    
    function beforeLoad(scriptContext) {
        showBonusEligibility(scriptContext.form);
    }
    
    function showBonusEligibility(form) {
        // Doesn't make sense to modify the form if the 
        if (!wasTriggeredFromUi(runtime.executionContext)) {
            return;
        }
        
        // Continue with form modification...
    }

    function wasTriggeredFromUi(context) {
        // Context can be compared to enumeration from runtime module
        return (context === runtime.ContextType.USER_INTERFACE);
    }
    
    exports.beforeLoad = beforeLoad;
    return exports;
});
"dependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "17.0.2",
    "react-dom": "17.0.2",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
},
<!DOCTYPE html>
<html> 
<head> 
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> 
  <title>Google Maps Multiple Markers</title> 
  <script src="http://maps.google.com/maps/api/js?key=YOUR_API_KEY" 
          type="text/javascript"></script>
</head> 
<body>
  <div id="map" style="width: 500px; height: 400px;"></div>

  <script type="text/javascript">
    var locations = [
      ['Bondi Beach', -33.890542, 151.274856, 4],
      ['Coogee Beach', -33.923036, 151.259052, 5],
      ['Cronulla Beach', -34.028249, 151.157507, 3],
      ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
      ['Maroubra Beach', -33.950198, 151.259302, 1]
    ];
    
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center: new google.maps.LatLng(-33.92, 151.25),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    
    var infowindow = new google.maps.InfoWindow();

    var marker, i;
    
    for (i = 0; i < locations.length; i++) {  
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });
      
      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }
  </script>
</body>
</html>
// helpers
import { getDataWithNonDuplicatedEntries } from "./getSetDataList";
import { filterData } from "./filterData";
import { reduceData } from "./reduceData";

type DataListType = {
  idade: string;
  quantidade: string;
};

export const groupData = (
  data: any[],
  filterProperty: string,
  reduceProperty: string,
  property: any
) => {
  // declare and empty array to save the results
  let dataList: any = [];

  // set a new list with no duplicated entries
  const list: number[] = getDataWithNonDuplicatedEntries(data, property);
  console.log(list);

  // then, for each item of the list...
  list.forEach((item) => {
    // filter elements
    const filteredData = filterData(data, filterProperty, item);
    console.log(filteredData);

    // get the total by age on the filtered data
    const age = reduceData(filteredData, reduceProperty);

    // finally, pass the results into an object
    const obj = {
      idade: item,
      quantidade: age,
    };
    dataList.push(obj);
  });

  return dataList;
};
import React from 'react';
import Card from './components/Card'
import './index.css'; 

class App extends React.Component{
    state = {
      image_id:51
    }
    
    changeAvatar=()=>{
     this.setState({
        image_id:65
      })
    }
    
    render(){
     return(
            <div className="container">
            <div className="row">
                <Card name="James Smith" job="Pilot" image_id={this.state.image_id}/>
                <Card name="Jessica Jones" job="Nurse" image_id={28}/>
                <Card name="Tom Hanks" job="Lawyer" image_id={68}/>
            </div>
            <div className="row">
                <div className="col-md-3">
                <a onClick={this.changeAvatar} className="changeAvatar" href="#"> Change Avatar </a>
                </div>
            </div>
            </div>
        );
    }
}

export default App;
import React from'react';

class App extends React.Component {
  render() {
    return(
        <div className="container">
          <div className="row">
            <div className="col-md-4">
              <div className="card">
                <img className="card-img-top"src="https://i.pravatar.cc/150?img=52"alt="Card image cap"/>
                  <div className="card-body">
                    <h5 className="card-title">Card title</h5>
                    <p className="card-text">Some quick example text to build on the card title and make up the</p>
                    <a href="#" className="btn btn-primary"> Go somewhere </a>
                  </div>
              </div>
            </div>
          </div>
        </div>
      );
    }
}

export default App;
function lenOfNum(num) {
  num = Math.abs(num)
  if(num < 10 && num >= 0){
    return 1
  }
  let len = 0
  while(num > 1){
    num = num / 10
    len++
    }
  return len
}
<Router>
	<NavLink 
	to='users' 
	className={({ isActive }) => isActive ? "navlink--active" : "navlink"} 
	style={({ isActive }) => ({color: isActive ? "#ffffff" : undefined})}>
	Users
	</NavLink>	
</Router>
function debounce(func, timeout = 300){
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => { func.apply(this, args); }, timeout);
  };
}
function saveInput(){
  console.log('Saving data');
}
const processChange = debounce(() => saveInput());
// Assuming N/search is imported as `s`
var mySalesOrderSearch = s.create({
    type: 'salesorder'
    // Use the summary property of a Column to perform grouping/summarizing
    columns: [{
        name: 'salesrep',
        summary: s.Summary.GROUP
    },{
        name: 'internalid',
        summary: s.Summary.COUNT
    }],
    filters: [{
        name: 'mainline',
        operator: 'is',
        values: ['T']
    }]
});

mySalesOrderSearch.run().each(function (result) {
    var repId = result.getValue({
        "name": "salesrep",
        "summary": s.Summary.GROUP
    });
    var repName = result.getText({
        "name": "salesrep",
        "summary": s.Summary.GROUP
    });
    var orderCount = parseInt(result.getValue({
            "name": "internalid",
            "summary": s.Summary.COUNT
    }), 10);

    log.debug({
        "title": "Order Count by Sales Rep",
        "details": repName + " has sold " + orderCount + " orders."
    });
    return true;
});
function flatten(arr) {
  let flat = []
  
  for(let prop of arr){
    if(Array.isArray(prop)){
      flat.push(...flattan(prop))
    } else {
      flat.push(prop)
    }
  }
  return flat
}
const exphbs = require('express-handlebars');
const hbs = exphbs.create({});

app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
function test(a = "ay", b = "bee") {
  console.log(`a = ${a}, b = ${b}`);
}
test();             // "a = ay, b = bee"
test(1);            // "a = 1, b = bee"
test(undefined, 2); // "a = ay, b = 2"
test(1, 2);         // "a = 1, b = 2"
interface Observer{
   update:() => void;
}

class ConcreteObserverA implements Observer {
   update() {
        console.log(this.constructor.name,"has been updated");
   }
}

class ConcreteObserverB implements Observer {
   update () {
        console.log(this.constructor.name,"has been updated");
   }
}
class Subject {
    private _name = "";

    private observerCollection:Observer[] = [];

    get name() {
        return this._name;
    }

    set name(val:string) {
        this._name=val;
        this.notifyObservers();
    }

    registerObserver(...o:Observer[]) {
            this.observerCollection.push(...o);
    }

    unregisterObserver(o:Observer) { 
        this.observerCollection = this.observerCollection.filter (e => e! == o);
    }

    notifyObservers() {
        this.observerCollection.forEach(o => o.update() );
    }
}

const subject = new Subject();
const oA = new ConcreteObserverA();
const oB = new ConcreteObserverB();
subject.registerObserver(oA, oB);

subject.name = "Jau, jau!";
// Create a candidate
app.post('/api/candidate', ({ body }, res) => {
  const errors = inputCheck(body, 'first_name', 'last_name', 'industry_connected');
  if (errors) {
    res.status(400).json({ error: errors });
    return;
  }

const sql = `INSERT INTO candidates (first_name, last_name, industry_connected)
  VALUES (?,?,?)`;
const params = [body.first_name, body.last_name, body.industry_connected];

db.query(sql, params, (err, result) => {
  if (err) {
    res.status(400).json({ error: err.message });
    return;
  }
  res.json({
    message: 'success',
    data: body
  });
});
});
// Delete a candidate
app.delete('/api/candidate/:id', (req, res) => {
  const sql = `DELETE FROM candidates WHERE id = ?`;
  const params = [req.params.id];

  db.query(sql, params, (err, result) => {
    if (err) {
      res.statusMessage(400).json({ error: res.message });
    } else if (!result.affectedRows) {
      res.json({
        message: 'Candidate not found'
      });
    } else {
      res.json({
        message: 'deleted',
        changes: result.affectedRows,
        id: req.params.id
      });
    }
  });
});
// Get a single candidate
app.get('/api/candidate/:id', (req, res) => {
  const sql = `SELECT * FROM candidates WHERE id = ?`;
  const params = [req.params.id];

  db.query(sql, params, (err, row) => {
    if (err) {
      res.status(400).json({ error: err.message });
      return;
    }
    res.json({
      message: 'success',
      data: row
    });
  });
});
// Get all candidates
app.get('/api/candidates', (req, res) => {
  const sql = `SELECT * FROM candidates`;

  db.query(sql, (err, rows) => {
    if (err) {
      res.status(500).json({ error: err.message });
      return;
    }
    res.json({
      message: 'success',
      data: rows
    });
  });
});
const reduceData = (data: any[], property: string) => {
  const result = data.reduce((acc, amount) => {
    return acc + Number(amount[property]);
  }, 0);
  return result;
};
${pay.remark === null ? `-` : `${pay.remark}`}
============html====================
  
  <div class="slide-bg"></div>
 
=============css==============
    
    .slide-bg{
        height: 100vh;
        width: 100%;
        background-position: center center;
        background-repeat: no-repeat;
        background-size: cover;
        backface-visibility: hidden;
        animation: slidbg 25s ease-in-out infinite ;
        background-image: url(../images/banner-1.png);
}
 
@keyframes slidbg {
 
    0% {
        background-image: url(../images/banner-1.png);
    }
 
    25% {
        background-image: url(../images/banner-2.png);
    }
 
    50% {
        background-image: url(../images/banner-1.png);
    }
 
    75% {
        background-image: url(../images/banner-2.png);
    }
 
    100% {
        background-image: url(../images/banner-1.png);
    }
}

import { useNavigate } from 'react-router-dom';
const navigate = useNavigate();
navigate('/home');
const promise = new Promise((resolve, reject) => {  
    let condition;
    
    if(condition is met) {    
        resolve('Promise is resolved successfully.');  
    } else {    
        reject('Promise is rejected');  
    }
});
for (i = 0; i < 26; i++) {

  var li = document.createElement("li");
  li.innerHTML = "letter " + (i+10).toString(36) + " ";
  li.style.listStyle = "none";
  li.style.display = "inline";
  document.getElementById("letter-main").appendChild(li);

}
function getSubstringCount(s) {
    // Write your code here
    let [current, prev, result] = [1, 0, 0]
    
    for(let i=1; i<s.length; i++){
        let left = s[i-1]
        let right = s[i]
        if(left == right){
            current++
        } else {
            prev = current
            current = 1
        }
        if(prev >= current){
            result++
        }
    }
    return result
}
app.post("/charge", (req, res) => {
  try {
    stripe.customers
      .create({
        name: req.body.name,
        email: req.body.email,
        source: req.body.stripeToken
      })
      .then(customer =>
        stripe.charges.create({
          amount: 199,
          currency: "usd",
          customer: customer.id
        })
      )
      .then(() => res.render("completed.html"))
      .then(() =>
        key.addKey(req.body.name, req.body.email)
          .catch(console.error)
      )
      .catch(err => console.log(err));
  } catch (err) {
    res.send(err);
  }
}
function beforeLoad(scriptContext) {

        log.audit('Line No.: 31','Before Load START');
        if (runtime.executionContext == 'USERINTERFACE') {
Action	Payment PostBack
Revenue Management	Platform Extension
Bank Connectivity	Portlet
Bank Statement Parser	Promotions
Bundle Installation	Custom Record Action
Client	RESTlet
Rate Adjustor	REST Web Services
CSV Import	Scheduled Script
Custom GL Lines	SDF Installation
Custom Mass Update	Shipping Partners
Dataset Builder Plug-in	Suitelet
Debugger	Tax Engine
Email Capture	User Event Script
Financial Institution Connectivity	User Interface
Financial Institution Parser	SOAP Web Services
Map/Reduce	Workbook Builder Plug-in
Other	Workflow
Payment Processing

From <https://7315200-sb1.app.netsuite.com/app/common/scripting/scriptrecord.nl?id=893> 
const nReadlines = require('n-readlines');
const path = require("path");
const file = path.join(__dirname, "./", "nums-to-test.txt");
const lines = new nReadlines(file);
const nReadlines = require('n-readlines');
const broadbandLines = new nReadlines('nums-to-test.txt');

let line;
let lineNumber = 1;

while (line = broadbandLines.next()) {
    if(/^#.*$/.test(line.toString())) {
        continue;
    }
    //console.log(`Line ${lineNumber} has: ${line.toString('utf-8')}`);
    lineNumber++;
    let fields = line.toString().split("\t");
    console.log(fields[0]);
    console.log(fields[1]);
}
let values = ["Saab", "Volvo", "BMW"];
values.sort((a, b) => b.localeCompare(a))
//find fibonacci numbers

function fib(n){
  if(n >=3 ){
    return fib(n-1) + fib(n-2)
  } else {
    return 1;
  }
}

console.log(fib(10))
function bubbleSort(arr){
  let len = arr.length;
  let cost = 0;
  
  for(let i=0; i<len; i++){
    for(let j=0; j<len-1; j++){
      if(arr[j] > arr[j+1]){
        swap(arr, j, j+1);
      }
    }
  }
  return arr
}

let unsortedArr = [0, 5, 6, 8, 2, 1, 3, 7, 4, 10, 12, 11]

console.log(bubbleSort(unsortedArr))
const num = 325987e-6; // Equals to 0. 325987
// The notation essentially says, "Take 325987 and multiply it by 10^-6.
const num = 3.125e7;
// => 31250000
// The notation essentially says, "Take 3.125 and multiply it by 10^7".
class ParentComponent extends Component {    
    render() {    
        return (        
            <ChildComponent name="First Child" />    
        );  
    }
}

const ChildComponent = (props) => {    
    return <p>{props.name}</p>; 
};
// This library is imported to enable async/await keywords in the Codecademy Code Editor
import "regenerator-runtime/runtime";
import React from 'react';
import { Thought } from '../Thought.js';
import {AddThoughtForm} from '../AddThoughtForm.js';
import {App} from '../App.js'
import { waitFor, render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';

// This library is imported to mimic user interactions (which you'll learn about next!)
import userEvent from '@testing-library/user-event';

test('"Oreos are delicious" should not appear' , () => {
  render(<App/>);
  // Add testing logic here
  const emptyThought = screen.queryByText("Oreos are delicious")
  expect(emptyThought).toBeNull()

});

test('Should show new thought to be present' , async () => {
  render(<App/>);

  // The code below mimics a user posting a thought with text 'Oreos are delicious'
  const addThoughtInput = screen.getByRole('input');
  const addButton = screen.getByRole('submit')
  userEvent.type(addThoughtInput, 'Oreos are delicious');
  userEvent.click(addButton)

  // Modify testing logic here
  const thought = await screen.findByText('Oreos are delicious');
  expect(thought).toBeInTheDocument();
});
import App from './components/App';
import { render, screen } from '@testing-library/react';
 
test('should show text content as Goodbye', async () => {
  // Render App
  render(<App />);
  // Extract button node 
  const button = screen.getByRole('button');
  // click button
  userEvent.click(button);
  // Wait for the text 'Goodbye!' to appear
  const header = await screen.findByText('Goodbye!');
  // Assert header to exist in the DOM
  expect(header).toBeInTheDocument();
});
import { render, screen, cleanup } from '@testing-library/react';
import GroceryList from './components/GroceryList';
import userEvent from '@testing-library/user-event';
 
test('should mark the first checkbox as checked', () => {
  // render the grocery list
  render(<GroceryList />);
  // grab the apple item
  const appleItem = screen.getByLabelText('Apples');
  // simulate a "click" on the apple checkbox
  userEvent.click(appleItem);
  // assert that the apple checkbox was checked
  expect(appleItem).toBeChecked();
});
// file: __tests__/recipes.js
 
import { findRecipe } from './recipes.js'; 
 
// import the actual module
import apiRequest from './api-request.js';
 
// then tell Jest to use the mocked version!
jest.mock('./api-request.js');
 
test("get the full recipe for a dish", async () => {
  // arrange  
  const dish = "Pesto";
  const expectedValue = { "Magical Deliciousness": "3 cups" };
 
  // set the resolved value for the next call to apiRequest  
  const mockResponse = {
    status: "mock",
    data: { "Magical Deliciousness": "3 cups" }
  }
  apiRequest.mockResolvedValueOnce(mockResponse);
 
  // act  
  const actualRecipe = await findRecipe(dish);
 
  // assertion
  expect(actualRecipe).toEqual(expectedValue);
});
const httpRequest = jest.fn(()=> {
  Promise.resolve({
    status: '',
    data: []
  })
});
export default httpRequest;
// file: utils/__mocks__/api-request.js
const apiRequest = jest.fn(() => {
  return Promise.resolve({ 
    status: "", 
    data: {} 
  });
});
 
export default apiRequest;
test("correctly fetches a list of countries", (done) => {
  //arrange
  const inputLanguageCode = "es" 
  const expectedValue ="Argentina"
  
  //act
  countryListLookup(inputLanguageCode, (result) =>{
    //assertions
    try{
      expect(result).toBeDefined();
    done();
    }
    catch(error){
      done(error)
    }
    
  });
});
function addVote() {
    const newVotes = [...votes];
    newVotes[selected] += 1;
    setSelected(selected);
    setVotes(newVotes);
  }
const html = `<!DOCTYPE html>
<body>
  <h1>Hello World</h1>
  <p>This markup was generated by a Cloudflare Worker.</p>
</body>`;



async function handleRequest(request) {
  return new Response(html, {
    headers: {
      'content-type': 'text/html;charset=UTF-8',
    },
  });

}



addEventListener('fetch', event => {
  return event.respondWith(handleRequest(event.request));

});
let searchObj = {}
for(let [key, value] of searchParams.entries()) {
  searchObj[key] = value
}
    $('.tabs-nav a').on('click', function (event) {
        event.preventDefault();
        $('.tabs-nav li').removeClass('tab-active');
        $(this).parent().addClass('tab-active');
        $('.tabs-stage section').hide();
        $($(this).attr('href')).show();

        if ($('#tab-1').css('display') == 'none') {
            $('.box-filters').hide();
        } else {
            $('.box-filters').show();
        }
    });
// Function that returns true if n
// is prime else returns false
function isPrime(n)
{
    // Corner cases
    if (n <= 1) return false;
    if (n <= 3) return true;
     
    // This is checked so that we can skip
    // middle five numbers in below loop
    if (n%2 == 0 || n%3 == 0) return false;
     
    for (let i=5; i*i<=n; i=i+6)
        if (n%i == 0 || n%(i+2) == 0)
        return false;
     
    return true;
}
// It seems like something happened to these strings
// Can you figure out how to clear up the chaos?
// Write a function that joins these strings together such that they form the following words:
// 'Javascript', 'Countryside', and 'Downtown'
// You might want to apply basic JS string methods such as replace(), split(), slice() etc

function myFunction (a, b) {

 	b = b.split('').reverse().join	('')
	return a.concat(b).replace(/[^a-zA-Z ]/g, '')

}

myFunction('java', 'tpi%rcs')   // returns 'javascript'
myFunction('c%ountry', 'edis')	// returns 'countryside'
myFunction('down', 'nw%ot')		// returns 'downtown'
var senderId = -5;
var recipientEmail = 'notify@myCompany.com';
var timeStamp = new Date().getUTCMilliseconds();
var recipientId = 12;
var fileObj = file.load({
id: 88
});
email.send({
author: senderId,
recipients: recipientId,
subject: 'Test Sample Email Module',
body: 'email body',
attachments: [fileObj],
relatedRecords: {
entityId: recipientId,
customRecord:{
id:recordId,
recordType: recordTypeId //an integer value
}
}
});













//EMAIL BODY

var emailBody = 'Dear ' + nextApprName + ',';

                emailBody += '<br/><br/>There is Vendor Bill pending for your urgent action. Kindly review the transaction.';

                emailBody += '<br/>Transaction Number: ' + tranId;

                emailBody += '<br/>Vendor Name: ' + vendorName;

                emailBody += '<br/>Subsidiary: ' + subsidiary;

                emailBody += '<br/>Transaction Date: ' + tranDate;

                emailBody += '<br/>Currency: ' + currency;

                emailBody += '<br/>Amount: ' + amt;

                emailBody += '<br/>Vendor Bill #: <a href="' + billRecUrl + '">' + refNo + '</a>';




emailBody += '<br/>Vendor Bill #: <a href="' + billRecUrl + '">' + refNo + '</a>'; 
do this to give a name to that the link will be hidden in the name.





 function NullCheck(variable) {
        try {
            if (variable != '' && variable != 0 && variable != -1 && variable != '[]' && variable != null && variable != 'null' && variable != 'NULL' && variable != undefined && variable != false && variable != 'false' && variable != 'F') {
                return true
            } else {
                return false
            }
        } catch (err) {
            console.log('Error in NullCheck', err)
        }
    }
let number = "10145";


//put number into array of arrays like 10145 becomes [ [ '1', '0' ], [ '1', '4', '5' ] ]
let numArray = number.split("");
const chunkRight = (arr, size) => {
    const rm = arr.length % size;
    
    return rm ?
      [arr.slice(0, rm), ..._.chunk(arr.slice(rm), size)]
      :
      _.chunk(arr, size);
};
const result = chunkRight(numArray, 3);
/Suitescripts/MyBundleDir/Part1/clientScript.js
/Suitescripts/MyBundleDir/Part1/ueScript.js
if (n < 0) alert(`Power ${n} is not supported`);
// a) on load:
import './override.css'
function onMount() {
  // this should be code that's safe to run eagerly (no danger of race conditions of any kind). Application codebase will call onMount() as soon as it can.
  ...
}

// b) on demand (UI events)
window.bonsaiCallback = function () {
  ...
  // any synchronous code can happen right away, but for any communication with our application codebase, there should be a way how to send a message (event):
  application.send(...)
}

// Listener for messages from application
application.receive((msg) => {...})
import React, { useState } from 'react';
import styled from 'styled-components';
const Button = styled.button`
  /* Same as above */
`;
const ButtonToggle = styled(Button)`
  opacity: 0.6;
  ${({ active }) =>
    active &&
    `
    opacity: 1;
  `}
`;
const ButtonGroup = styled.div`
  display: flex;
`;
const types = ['Cash', 'Credit Card', 'Bitcoin'];
function ToggleGroup() {
  const [active, setActive] = useState(types[0]);
  return (
    <ButtonGroup>
      {types.map(type => (
        <ButtonToggle
          key={type}
          active={active === type}
          onClick={() => setActive(type)}
        >
          {type}
        </ButtonToggle>
      ))}
    </ButtonGroup>
  );
}
<?php

add_filter( 'woocommerce_checkout_fields', 'xa_remove_billing_checkout_fields' );
function xa_remove_billing_checkout_fields( $fields ) {
    // change below for the method
    $shipping_method ='local_pickup:1'; 
    // change below for the list of fields
    $hide_fields = array( 'billing_address_1', 'billing_address_2', 'billing_city', 'billing_state', 'billing_postcode' );

    $chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
    // uncomment below line and reload checkout page to check current $chosen_methods
     print_r($chosen_methods);
    $chosen_shipping = $chosen_methods[0];

    foreach($hide_fields as $field ) {
        if ($chosen_shipping == $shipping_method) {
            $fields['billing'][$field]['required'] = false;
            $fields['billing'][$field]['class'][] = 'hide';
        }
        $fields['billing'][$field]['class'][] = 'billing-dynamic';
    }

    return $fields;
}

add_action( 'wp_footer', 'cart_update_script', 999 );
function cart_update_script() {
    if (is_checkout()) :
    ?>
    <style>
        .hide {display: none!important;}
    </style>
    <script>
        jQuery( function( $ ) {

            // woocommerce_params is required to continue, ensure the object exists
            if ( typeof woocommerce_params === 'undefined' ) {
                return false;
            }

            $(document).on( 'change', '#shipping_method input[type="radio"]', function() {
                // change local_pickup:1 accordingly 
                $('.billing-dynamic').toggleClass('hide', this.value == 'local_pickup:1');
            });
        });
    </script>
    <?php
    endif;
}
function goBack() {
  window.history.back();
}
setTimeout(function() {
    setTimeout("location.reload(true);");
}, 1500);
let arr = ['foo', 'bar', 10, 'qux'];

// arr.splice(<index>, <steps>, [elements ...]);

arr.splice(1, 1);			// Removes 1 item at index 1
// => ['foo', 10, 'qux']

arr.splice(2, 1, 'tmp');	// Replaces 1 item at index 2 with 'tmp'
// => ['foo', 10, 'tmp']

arr.splice(0, 1, 'x', 'y');	// Inserts 'x' and 'y' replacing 1 item at index 0
// => ['x', 'y', 10, 'tmp']
//The regular expressions:
//emailRegex: To prevent matching multiple @ signs:
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
//nameRegex: between 2 and 255 characters, prevents symbols and numbers. Also prevents spaces
const nameRegex = /^[a-zA-Z]{2,255}$/;
//passwordRegex: Between 8 and 255 characters, atlest one uppercase, one lowercase, one symbol and one number
const passwordRegex = /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,255}$/;



/*
.matches(
  /^.*(?=.{8,})((?=.*[!@#$%^&*()\-_=+{};:,<.>]){1})(?=.*\d)((?=.*[a-z]){1})((?=.*[A-Z]){1}).*$/,
  "At least one upper case, number and symbol"
)

- Cyliric /^[аАбБвВгГдДеЕёЁжЖзЗиИйЙкКлЛмМнНоОпПрРсСтТуУфФхХцЦчЧшШщЩъЪыЫьЬэЭюЮяЯ]+$/
/^[a-zA-Z\-_ ’'‘ÆÐƎƏƐƔIJŊŒẞÞǷȜæðǝəɛɣijŋœĸſßþƿȝĄƁÇĐƊĘĦĮƘŁØƠŞȘŢȚŦŲƯY̨Ƴąɓçđɗęħįƙłøơşșţțŧųưy̨ƴÁÀÂÄǍĂĀÃÅǺĄÆǼǢƁĆĊĈČÇĎḌĐƊÐÉÈĖÊËĚĔĒĘẸƎƏƐĠĜǦĞĢƔáàâäǎăāãåǻąæǽǣɓćċĉčçďḍđɗðéèėêëěĕēęẹǝəɛġĝǧğģɣĤḤĦIÍÌİÎÏǏĬĪĨĮỊIJĴĶƘĹĻŁĽĿʼNŃN̈ŇÑŅŊÓÒÔÖǑŎŌÕŐỌØǾƠŒĥḥħıíìiîïǐĭīĩįịijĵķƙĸĺļłľŀʼnńn̈ňñņŋóòôöǒŏōõőọøǿơœŔŘŖŚŜŠŞȘṢẞŤŢṬŦÞÚÙÛÜǓŬŪŨŰŮŲỤƯẂẀŴẄǷÝỲŶŸȲỸƳŹŻŽẒŕřŗſśŝšşșṣßťţṭŧþúùûüǔŭūũűůųụưẃẁŵẅƿýỳŷÿȳỹƴźżžẓ]$/.test(myString)

*/

//For testing
console.log(emailRegex.test('user@email.com'));
console.log(nameRegex.test('firstname'));
console.log(nameRegex.test('lastname'));
console.log(passwordRegex.test('password'));
document.addEventListener('contextmenu', event => event.preventDefault());
//First install required package:
npm i bcrypt

//import bcrypt
import * as bcrypt from 'bcrypt';

//hashing the password using the hash function
const recievedPassword = 'password';
const hashedPassword = await bcrypt.hash(recievedPassword, await bcrypt.genSalt());

//To compare/check a password, use the compare function:
const isMatch = await bcrypt.compare(recievedPassword, hashedPassword);
console.log('passwords: ', isMatch);
let fruit = 'apple';
let fruits = ["apple", "banana", "mango", "orange", "grapes"];

const isArray = (arr) => Array.isArray(arr);

console.log(isArray.(fruit)); //output - false
console.log(isArray.(fruits)), //output- true
const redirect = url => location.href = url

/* call redirect (url) whenever you want to redirect the user to a specific url */
let arr1 = [];
let arr2 = [2, 4, 6, 8, 10];

const arr1IsEmpty = !(Array.isArray(arr1) && arr1.length >0);
const arr2IsEmpty = !(Array.isArray(arr2) && arr2.length >0);

console.log(arr1IsEmpty); //output - true
console.log(arr2IsEmpty); // output - false
const elem = document.querySelector(' .text-input');

const isFocus = elem == document.activeElemnt;

/* isFocus will be true if elem will have focus, and isFocus will be false if elem will not have focus */
let email = 'xyz@gmail.com';
le getDomain = email.substring(email.indexOf('@') + 1);

console.log(getDomain); // output - gmail.com
const randomString = Math.random().toString(36).slice(2);
console.log(randomString); //output- r0zf1xfqcr (the string will be random )
//Longhand 
if (value === 1 || value === 'one' || value === 2 || value === 'two') { 
    // Execute some code 
} 
// Shorthand 1
if ([1, 'one', 2, 'two'].indexOf(value) >= 0) { 
   // Execute some code 
}
// Shorthand 2
if ([1, 'one', 2, 'two'].includes(value)) { 
   // Execute some code 
}
//This function allows you to set the token length and allowed characters.
//tokenLength = 64
function generateToken(64) {
    var generatedToken = '';
    var allowedCharacters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    for(var i = 0; i < n; i++) {
        generatedToken += allowedCharacters[Math.floor(Math.random() * allowedCharacters.length)];
    }
	console.log(generatedToken);
    return generatedToken;
}


//Get current date and time
var currentDate = new Date();

//Get current date and time and add +n hours. Acts as an expiration date
var expirationDate = new Date();
expirationDate.setHours(expirationDate.getHours() + 2);

//Check if date has expired
if (currentDate > expirationDate) {
	return {
		message: 'Expired'
	}
}

//To get a 24 hour time
var date = new Date();
console.log(date.toLocaleString('en-GB'));
/* 
	https://www.youtube.com/watch?v=q0E1hbcj-NI
    Browsersync + Sass + Gulp in 15 minutes
    
	install as devDependencies:
	npm install browser-sync cssnano gulp gulp-cli gulp-postcss gulp-sass gulp-terser sass -D    
*/

// run gulp by typing on terminal : gulp
// error: gulp-sass no longer has a default Sass compiler; please set one yourself.

const { src, dest, watch, series } = require("gulp");
const sass = require("gulp-sass");
const postcss = require("gulp-postcss");
const cssnano = require("cssnano");
const terser = require("gulp-terser");
const browsersync = require("browser-sync").create();

// sass task
function sassTask() {
  return src("./sass/style.scss", { sourcemaps: true })
    .pipe(sass())
    .pipe(postcss([cssnano()]))
    .pipe(dest("dist/css", { sourcemaps: "." }));
}

// javascript task
function jsTask() {
  return src("./js/index.js", { sourcemaps: true })
    .pipe(terser())
    .pipe(dest("dist/js", { sourcemaps: "." }));
}

// browsersync
function browserSyncServer(callback) {
  browsersync.init({
    server: {
      baseDir: ".",
    },
  });
  callback();
}

function browserSyncReload(callback) {
  browsersync.reload();
  callback();
}

// watch task
function watchTask() {
  watch("*.html", browserSyncReload);
  watch(
    ["./sass/**/*.scss", ".js/**/*.js"],
    series(sassTask, jsTask, browserSyncReload)
  );
}

// gulp workflow
exports.default = series(sassTask, jsTask, browserSyncServer, watchTask);
<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Strings</h1>
<h2>The split() Method</h2>

<p>split() splits a string into an array of substrings, and returns the array:</p>

<p id="demo"></p>

<script>
let text = " 0.00 ";
const myArray = text.trim().split(".");

document.getElementById("demo").innerHTML = myArray[1]; 
</script>

</body>
</html>
<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Global Methods</h1>
<h2>The parseFloat() Method</h2>

<p>parseFloat() parses a string and returns the first number:</p>

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
new Number(parseFloat(" 0.00 ")).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})
</script>

</body>
</html>
var number = 123456.789;

// request a currency format
console.log(number.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' }));
// → 123.456,79 €

// the Japanese yen doesn't use a minor unit
console.log(number.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' }))
// → ¥123,457

// limit to three significant digits
console.log(number.toLocaleString('en-IN', { maximumSignificantDigits: 3 }));
// → 1,23,000

// Use the host default language with options for number formatting
var num = 30000.65;
console.log(num.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2}));
// → "30,000.65" where English is the default language, or
// → "30.000,65" where German is the default language, or
// → "30 000,65" where French is the default language
var num = 2046430.123;
num.toLocaleString(undefined, {
  minimumFractionDigits: 2,
  maximumFractionDigits: 2
}) // 2,046,430.12
// https://www.digitalocean.com/community/tutorials/how-to-use-the-javascript-fetch-api-to-get-data-pt

function createNode(element) {
    return document.createElement(element);
}

function append(parent, el) {
  return parent.appendChild(el);
}

const ul = document.getElementById('authors');
const url = 'https://randomuser.me/api/?results=10';

fetch(url)
.then((resp) => resp.json())
.then(function(data) {
  let authors = data.results;
  return authors.map(function(author) {
    let li = createNode('li');
    let img = createNode('img');
    let span = createNode('span');
    img.src = author.picture.medium;
    span.innerHTML = `${author.name.first} ${author.name.last}`;
    append(li, img);
    append(li, span);
    append(ul, li);
  })
})
.catch(function(error) {
  console.log(error);
});
function createNode(element) {
  return document.createElement(element);
}

function append(parent, el) {
  return parent.appendChild(el);
}
https://www.youtube.com/watch?v=d2ve7xQNco8
const id = itemToBeReplaced.id 
const updatedData = arr.map(item => (item.id === id ? { ...item, props: 'some value to be replaced' } : item));
function iter(rec, listName, cb){
    var lim = rec.getLineCount({sublistId:listName});
    var i = 0;
    var getV = function (fld){
        return rec.getSublistValue({sublistId:listName, fieldId:fld, line:i});
    };
    var setV = function(fld, val){
        rec.setSublistValue({sublistId:listName, fieldId:fld, line:i, value:val});
    };
    for(; i< lim; i++){
        cb(i, getV, setV);
    }
}
process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});
function readLine() {
    return input_stdin_array[input_currentline++];
}
function Node(data){
    this.data=data;
    this.next=null;
}
function Solution(){

	this.insert=function(head,data){
          //complete this method
          var newNode = new Node(data);

        if (head === null || typeof head === 'undefined') {
            head = newNode;  
        } else if (head.next === null) {
            head.next = newNode;
        } else {
            var next = head.next;
            while(next.next) {
                next = next.next
            }
            next.next = newNode;
        }
        
        return head;
    };

	this.display=function(head){
        var start=head;
            while(start){
                process.stdout.write(start.data+" ");
                start=start.next;
            }
    };
}
function main(){
    var T=parseInt(readLine());
    var head=null;
    var mylist=new Solution();
    for(i=0;i<T;i++){
        var data=parseInt(readLine());
        head=mylist.insert(head,data);
    }
    mylist.display(head);
}		
class Difference:
    def __init__(self, a):
        self.__elements = a
    def computeDifference(self):
        maximum = 0
        for i in range(len(self.__elements)):
            for j in range(len(self.__elements)):
                absolute = abs(self.__elements[i] - self.__elements[j])
                if absolute > maximum:
                    maximum = absolute
        self.maximumDifference = maximum

# End of Difference class

_ = input()
a = [int(e) for e in input().split(' ')]

d = Difference(a)
d.computeDifference()

print(d.maximumDifference)
process.stdin.resume();
process.stdin.setEncoding('ascii');

var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;

process.stdin.on('data', function (data) {
    input_stdin += data;
});

process.stdin.on('end', function () {
    input_stdin_array = input_stdin.split("\n");
    main();    
});
function readLine() {
    return input_stdin_array[input_currentline++];
}

//Write your code here
class Calculator {
    constructor (n, p) {
        this.n = n;
        this.p = p;
    }
    
    power(n, p) {
        if (n<0 || p <0) return ("n and p should be non-negative")
        else return Math.pow(n,p)
    }
}
function main(){
    var myCalculator=new Calculator();
    var T=parseInt(readLine());
    while(T-->0){
        var num = (readLine().split(" "));
        try{
            var n=parseInt(num[0]);
            var p=parseInt(num[1]);
            var ans=myCalculator.power(n,p);
            console.log(ans);
        }
        catch(e){
            console.log(e);
        }

    }
}
function getCurrentTime() {
  // Get the current 'global' time from an API using Promise
  return new Promise((resolve, reject) => {
    setTimeout(function() {
      var didSucceed = Math.random() >= 0.5;
      didSucceed ? resolve(new Date()) : reject('Error');
    }, 2000);
  })
}
getCurrentTime()
  .then(currentTime => getCurrentTime())
  .then(currentTime => {
    console.log('The current time is: ' + currentTime);
    return true;
  })
  .catch(err => console.log('There was an error:' + err))
$('input[name="name_of_your_radiobutton"]:checked').val();
!$("input:radio[value='7'][name='employee-type']").prop('checked')
'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', function(inputStdin) {
    inputString += inputStdin;
});

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

function readLine() {
    return inputString[currentLine++];
}

function reverseString(str) {
  return (str === '') ? '' : reverseString(str.substr(1)) + str.charAt(0);
}

function main() {
    var n = parseInt(readLine());
    var arr = [];
    
    while(n != 0){
        if (n%2 == 0)
            arr.push(0);
        if (n%2 == 1)
            arr.push(1);
        n = Math.floor(n/2);
    }
    
    var max = 0;
    var cur = 0;

    
    for (var i = 0, len = arr.length; i < len; i++) {
        if (arr[i] == 1)
            cur++;
        else if (arr[i] == 0){
            if (cur > max)
                max = cur;
            cur = 0;
        }
    }
    
    if (cur > max)
        max = cur;
    
    console.log(max); 
}
'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', function(inputStdin) {
    inputString += inputStdin;
});

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

function readLine() {
    return inputString[currentLine++];
}


function main() {
    const n = parseInt(readLine().trim(), 10);

    const a = readLine().replace(/\s+$/g, '').split(' ').map(aTemp => parseInt(aTemp, 10));

    var numberOfSwaps = 0;
    for (var i = 0; i < n; i++) {
    
    var item;
    for (var j = 0; j < n - 1; j++) {
    
        if (a[j] > a[j + 1]) {
            item = a[j];
            a[j]= a[j + 1];
            a[j + 1] = item;
            numberOfSwaps++;
        }
    }
   
   
    if (numberOfSwaps == 0) {
        break;
    }
   
}
    
   console.log("Array is sorted in", numberOfSwaps,"swaps.");
   console.log("First Element:", a[0]);
   console.log("Last Element:", a[a.length-1]);
    
}
import java.io.*;
import java.util.*;

interface AdvancedArithmetic{
   int divisorSum(int n);
}
class Calculator implements AdvancedArithmetic {
    public int divisorSum(int n) {
         
        int sum = 0;
        for (int i = 1; i <= n; i++)
            if (n % i == 0) sum += i;
        return sum;
        
    }
}

class Solution {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        scan.close();
        
      	AdvancedArithmetic myCalculator = new Calculator(); 
        int sum = myCalculator.divisorSum(n);
        System.out.println("I implemented: " + myCalculator.getClass().getInterfaces()[0].getName() );
        System.out.println(sum);
    }
}
function Animal(){ 
  this.type = "animal"
}
   
function Dog(){ 
  this.name = "dog"
}
 
Dog.prototype = new Animal()
 
var PavlovPet = new Dog(); 
 
console.log(PavlovPet.__proto__ === Dog.prototype)
console.log(Dog.prototype.__proto__ === Animal.prototype)
Blob b = Blob.valueOf('Test Data');
    	
Attachment attachment = new Attachment();
attachment.ParentId = parentId;
attachment.Name = 'Test Attachment for Parent';
attachment.Body = b;

insert(attachment);
function isInViewport(element) {
  const rect = element.getBoundingClientRect();
  const height = innerHeight || document.documentElement.clientHeight;
  const width = innerWidth || document.documentElement.clientWidth;
  return (
    rect.top >= 0 &&
    rect.left >= 0 &&
    rect.bottom <= height &&
    rect.right <= width
  );
}
<!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>
</head>
<body>

    <form action="/action_page.php">
        <label for="fname">First name:</label>
        <input type="text" id="fname" name="fname"><br><br>
        <label for="lname">Last name:</label>
        <input type="text" id="lname" name="lname"><br><br>
        <input type="submit" value="Submit">
      </form>

<script src="https://unpkg.com/hotkeys-js/dist/hotkeys.min.js"></script>

<script type="text/javascript">
hotkeys('alt+z,alt+x,alt+c,alt+v,alt+b,alt+n,alt+m,alt+1', function (event, handler){
  switch (handler.key) {
    case 'alt+z': document.getElementById("fname").value = "alt+z";
      break;
    case 'alt+x': document.getElementById("fname").value = "alt+x";
      break;
    case 'alt+c': document.getElementById("fname").value = "alt+c";
      break;
    case 'alt+v': document.getElementById("fname").value = "alt+v";
      break;
    case 'alt+b': document.getElementById("fname").value = "alt+b";
      break;
    case 'alt+n': document.getElementById("fname").value = "alt+n";
      break;
    case 'alt+m': document.getElementById("fname").value = "alt+m";
      break;
    case 'alt+1': document.getElementById("fname").value = "alt+1";
      break;
    default: alert(event);
  }
});
</script>
</body>
</html>
function Student() {
}

Student.prototype.sayName = function() {
  console.log(this.name)
}

function EighthGrader(name) {
  this.name = name
  this.grade = 8
}

EighthGrader.prototype = Object.create(Student.prototype)

const carl = new EighthGrader("carl")
carl.sayName() // console.logs "carl"
carl.grade // 8
function reEscape(s) {
    return s.replace(/([.*+?^$|(){}\[\]])/mg, "\\$1");
}

// ...

var re = new RegExp(reEscape(pattern), "mg");
this.markup = this.markup.replace(re, value);
var counter = setInterval(updatedCount, 100);
var upto=0;

function updatedCount() {
  var count = document.getElementById('counter');
  count.innerHTML= ++upto;
  if(upto === 50) {
    clearInterval(counter);
  }
}
It's a project that has been close to my heart for years and I haven't found the time to create it, especially since my wife and two daughters are in this field.
'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', function(inputStdin) {
    inputString += inputStdin;
});

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

function readLine() {
    return inputString[currentLine++];
}



function main() {
    const S = readLine();
    
    try {
        
        console.log(parseInt(S).toString().replace('NaN', 'Bad String'));
    } catch (err) {
        console.log("Bad String");
    }
}
function element_list(el,depth) {
    console.log(el+' '+depth);
    for(var i=0; i<el.children.length; i++) {
        element_list(el.children[i],depth+1);
    }
}
element_list(document,0);
history.pushState(null, null, location.href);
        window.onpopstate = function (){
          history.go(1);
        };
//Count Divisors
// Sample code to perform I/O:

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
   main(stdin_input);
});

function main(input) {
    const data= input.toString().split("\n");
    
    console.log(divisors(data[0]));       // Writing output to STDOUT
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail



// Write your code here
// Sample code to perform I/O:
//Enter your code here

function divisors(s) {
    
    var arr = s.split(" ").map(item => Number(item));
    
    
    const l = arr[0];
    const r = arr[1];

    const k = arr[2];

    
    var count =0;

    for (var i=l; i<=r; i++) {
        if ((i % k)==0) count++
        
    }
    
    return count; 
    
}
     
//Palindromic String
// Sample code to perform I/O:

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
   main(stdin_input);
});

function main(input) {
  
  var data= input.toString().split("\n");
    process.stdout.write(palindrome(data[0]));       // Writing output to STDOUT
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail



// Write your code here
// Sample code to perform I/O:
//Enter your code here
function palindrome(s) {
    
    var len = s.length;
    var midle = Math.floor(len/2);

    for (var i= 0; i<midle; i++) {
        if (s[i] !== s[len-1-i]) return "NO"
    }    
    return "YES";    
}
     

//Toggle String
// Sample code to perform I/O:

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
   main(stdin_input);
});

function main(input) {
    var data= input.toString().split("\n");

    process.stdout.write(toggle(data[0]));       // Writing output to STDOUT
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail



// Write your code here
// Sample code to perform I/O:
//Enter your code here


function toggle(s) {
    var ss="";
    for (var i= 0; i<s.length; i++) {
        
        if (s[i] >= 'a' && s[i] <= 'z') {
           ss= ss+String.fromCharCode(s.charCodeAt(i) - 32);
        } else if (s[i] >= 'A' && s[i] <= 'Z') {
            ss= ss+String.fromCharCode(s.charCodeAt(i) + 32);
         
        }
            
    }    
    return ss;    
}
     
// Roy and Profile Picture
// Sample code to perform I/O:

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
   main(stdin_input);
});

function main(input) {
    //process.stdout.write("Hi, " + input + ".\n");       // Writing output to STDOUT
var data= input.toString().split("\n");

const L= parseInt(data[0],10);
const N= parseInt(data[1],10);
var W = 0;
var H = 0;
var ligne = "";
for (var WH=0; WH<N; WH++) {
    ligne = data[2+WH].split(" ");
    
    W = ligne[0,0];
    H = ligne[0,1];

   if (W < L || H < L)
               console.log("UPLOAD ANOTHER")
    else if (W == H && W >= L && H >= L) console.log("ACCEPTED")
    else console.log("CROP IT");
   
}

}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail



// Write your code here
// Sample code to perform I/O:
//Enter your code here
// Life, the Universe, and Everything
// Sample code to perform I/O:

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
   main(stdin_input);
});

function main(input) {
    //process.stdout.write("Hi, " + input + ".\n");       // Writing output to STDOUT
var data= input.toString().split("\n");
var arr = data.map(item => Number(item));

const flag = true;
var i = 0;
while (flag)  {
    
    if (arr[i]==42) {
        break;
    } else console.log(arr[i]);
    i++; 
}   

}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail



// Write your code here
// Sample code to perform I/O:
//Enter your code here
'use strict';

var _input = '';
var _index = 0;
process.stdin.on('data', (data) => { _input += data; });
process.stdin.on('end', () => {
    _input = _input.split(new RegExp('\n'));
    main();    
});
function readLine() { return _input[_index++]; }

/**** Ignore above this line. ****/

class Book {
    constructor(title, author) {
        if (this.constructor === Book) {
            throw new TypeError('Do not attempt to directly instantiate an abstract class.'); 
        }
        else {
            this.title = title;
            this.author = author;
        }
    }
    
    display() {
        console.log('Implement the \'display\' method!')
    }
}

// Declare your class here.
    /**   
    *   Class Constructor
    *   
    *   @param title The book's title.
    *   @param author The book's author.
    *   @param price The book's price.
    **/
    // Write your constructor here
    
    /**   
    *   Method Name: display
    *   
    *   Print the title, author, and price in the specified format.
    **/
    // Write your method here
    
// End class

class MyBook extends Book{

    /**   
    *   Class Constructor
    *   
    *   @param title The book's title.
    *   @param author The book's author.
    *   @param price The book's price.
    **/
    // Write your constructor here
    constructor(title, author, price) {
        super(title, author);
        this.price = price;
    }
    /**   
    *   Method Name: display
    *   
    *   Print the title, author, and price in the specified format.
    **/
    // Write your method here
    display() {
        console.log('Title: ' + this.title);
        console.log('Author: ' + this.author);
        console.log('Price: ' + this.price);
    }
    
// End class
}



function main() {
    let title = readLine()
    let author = readLine()
    let price = +readLine()

    let book = new MyBook(title, author, price)
    book.display()
}
'use strict';

var _input = '';
var _index = 0;
process.stdin.on('data', (data) => { _input += data; });
process.stdin.on('end', () => {
    _input = _input.split(new RegExp('[ \n]+'));
    main();    
});
function read() { return _input[_index++]; }

/**** Ignore above this line. ****/

class Person {
    constructor(firstName, lastName, identification) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.idNumber = identification;
    }
    
    printPerson() {
        console.log(
            "Name: " + this.lastName + ", " + this.firstName 
            + "\nID: " + this.idNumber
        )
    }
}

class Student extends Person {
    /*	
    *   Class Constructor
    *   
    *   @param firstName - A string denoting the Person's first name.
    *   @param lastName - A string denoting the Person's last name.
    *   @param id - An integer denoting the Person's ID number.
    *   @param scores - An array of integers denoting the Person's test scores.
    */
    // Write your constructor here

    /*	
    *   Method Name: calculate
    *   @return A character denoting the grade.
    */
    // Write your method here
     constructor(firstName, lastName, id, scores) {
        super(firstName, lastName, id, scores);

        this.scores = scores;
    }

    calculate() {
        const average = this.scores.reduce((target, score) => { return target + score }) / this.scores.length;

        const range = (average < 70)
            ? Math.ceil((100 - average) / 15)
            : Math.floor((100 - average - 1) / 10);
        let letter = '';

        switch (range) {
            case -1:
            case 0:
                letter = 'O';
                break;

            case 1:
                letter = 'E';
                break;

            case 2:
                letter = 'A';
                break;

            case 3:
                letter = 'P';
                break;

            case 4:
                letter = 'D';
                break;

            default:
                letter = 'T';
                break;
        }

        return letter;
    }
    
}

function main() {
    let firstName = read()
    let lastName = read()
    let id = +read()
    let numScores = +read()
    let testScores = new Array(numScores)
    
    for (var i = 0; i < numScores; i++) {
        testScores[i] = +read()  
    }

    let s = new Student(firstName, lastName, id, testScores)
    s.printPerson()
    s.calculate()
    console.log('Grade: ' + s.calculate())
}
'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', function(inputStdin) {
    inputString += inputStdin;
});

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

function readLine() {
    return inputString[currentLine++];
}



function main() {

    let arr = Array(6);

    for (let i = 0; i < 6; i++) {
        arr[i] = readLine().replace(/\s+$/g, '').split(' ').map(arrTemp => parseInt(arrTemp, 10));
    }
    
    //
    
    var sumarr = [];
    
    var h = 0;
    for (var i = 0; i < 4; i++) {
        for (var j = 0; j < 4; j++) {
            sumarr[h] = arr[i][j] + arr[i][j+1] + arr[i][j+2]
                    + arr[i+1][j+1] + arr[i+2][j] + arr[i+2][j+1]
                    + arr[i+2][j+2];
            h++;
        }
    }

    sumarr.sort();
    
    var max = -99999;
    for (var x = 0; x < 16; x++){
        if (sumarr[x] > max)
            max = sumarr[x];
    }
    
    console.log(max);
}
function processData(input) {
    //Enter your code here
    const lines = input.split("\n");
    const n = parseInt(lines[0]);
    const phoneBook = new Map();
    
    for (var i =1; i<=n; i++ ) {
        const arr = lines[i].split(" ");
        const name = arr[0];
        const phone = arr[1];
        phoneBook.set(name, phone);
    }
    
    
    for (var j=n+1; j<=lines.length-1; j++ ) {
      
        if (phoneBook.has(lines[j])) {
           console.log(lines[j]+"="+phoneBook.get(lines[j])); 
        } else {
            console.log("Not found");
        }
    }
    
    
   
}

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});
// Cost of balloons
// Sample code to perform I/O:

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
   main(stdin_input);
});

function main(input) {
    process.stdout.write(costBallons(input));       // Writing output to STDOUT
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail



// Write your code here
// Sample code to perform I/O:
//Enter your code here
function costBallons(data) {
    
    data= data.toString().split("\n");
    let answer =[];

    let ligne = 0;
    // Number of test    
    let tests = Number(data[ligne]);
    //console.log("Number of tests ", tests);
    ligne = 1;
    for (let t=1; t<=tests; t++ ) {
      //  console.log("Num test : ", t);
        
       // console.log(" ----- Cost ------ ");
        
        let costs = data[ligne].split(" ").map((item)=> Number(item));
        //for (let costX = 0; costX<costs.length; costX++) {
        //    console.log(costs[costX]);
            
        //}

        //console.log(" ----- Participants ------ ");
        ligne = ligne + 1;
        let participants =  Number(data[ligne]);
        ligne = ligne +1;
        //console.log(participants);
        let sumColone1=0;
        let sumColone2 = 0;
        //console.log(" ----- Status ------ ");
        for (let status=0; status<participants; status++) {
            let stat  = data[ligne+status].split(" ").map((item)=> Number(item));
          //  console.log(stat);
            // Calcul somme colonne 
            sumColone1 = sumColone1 + stat[status,0];
            sumColone2 = sumColone2 + stat[status,1];
            
        }
        //console.log(sumColone1);
        //console.log(sumColone2);

        // Cost green and cost purple
        costGreen = costs[0];
        costPurple = costs[1];

        // Case 1 
        sum1 = costGreen*sumColone1 + costPurple*sumColone2;
        //console.log(sum1);
        // Case 2 
        sum2 = costPurple*sumColone1 + costGreen*sumColone2; 
        //console.log(sum2);
        // 
        answer.push(Math.min(sum1,sum2));

        ligne = ligne +participants;
        

    }
    
    //let participants = Number(data[2]);
    //let status = 

    
    return answer.join("\n").toString();

}
// Best Index
// Sample code to perform I/O:

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
   main(stdin_input);
});

function main(input) {
    var data= input.toString().split("\n");

    //process.stdout.write(bestIndex(data[1], parseInt(data[0])));
    console.log(bestIndex(data[1], parseInt(data[0])));
           // Writing output to STDOUT
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail



// Write your code here
// Sample code to perform I/O:
//Enter your code here
function bestIndex(input,n) {
   

    let arr = input.split(" ").map((item)=>Number(item));

    let max = -Infinity;

    for (let i = 0; i<n; i++) {
        if (i>0) arr[i] = arr[i]+arr[i-1];
    }    
        
    
    for (let j = 0; j<n; j++) {
        let left = n- j;

        let sum =0;
        let k =Math.trunc(((-1+Math.sqrt((8*left+1)))/2));

        sum=arr[Math.trunc((k*(k+1))/2+j-1)];

        if (j!=0) {sum-=arr[j-1];}
        if (max<sum) {max=sum;}
        


        
    }    

    
    return max.toString();

}
//Implement a function which convert the given boolean value into its string representation.

//Note: Only valid inputs will be given.

function booleanToString(b){
  return b.toString();
}
//mplement a function which convert the given boolean value into its string representation.

//Note: Only valid inputs will be given.

function booleanToString(b){
  if(b){
    //just return a string
    return "true";
  }else{
    //just return a string
    return "false";
  }
}
// Divisible
// Sample code to perform I/O:

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
   main(stdin_input);
});

function main(input) {
    var data= input.toString().split("\n");

    process.stdout.write(divisible(data[1], parseInt(data[0])));
           // Writing output to STDOUT
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail



// Write your code here
// Sample code to perform I/O:
//Enter your code here

function divisible(input,n) {
   
    const arr = input.split(" ");
    let firstHalf = arr.slice(0,n/2);
    let secondHalf = arr.slice(n/2, n);

   
    let sumOdd = 0;
    let sumEven =0;

    let number= "";
    for (let i=0; i<n/2; i++) {
        number = number + firstHalf[i].substr(0,1);
        
    }

    for (let i=0; i<n/2; i++) {
        number = number + secondHalf[i].substr(secondHalf[i].length-1,1);
        
    }

    for (let i=0; i<n; i++) {
        let digit = parseInt(number.substr(i,1),10);
   
        if (i % 2 == 0) {
            sumOdd = sumOdd + digit;
        } else {
            sumEven = sumEven + digit;
        }
    } 

   
    if ((sumOdd - sumEven) % 11 == 0) {
        return 'OUI'
    } else { return "NON"};
    

    

}
    
    
// Divisibility
// Sample code to perform I/O:

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
   main(stdin_input);
});

function main(input) {
    var data= input.toString().split("\n");

    process.stdout.write(divisible(data[1], parseInt(data[0])));
           // Writing output to STDOUT
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail



// Write your code here
// Sample code to perform I/O:
//Enter your code here

function divisible(input,n) {
   

    const arr = input.split(" ");
    
    let number="";
    for (let i=0; i<n; i++) {
       
        number=number+arr[i].substr(arr[i].length-1,1);

    } 

    
    if (parseInt(number.substr(number.length-1,1))!=0) {
        return "No";
    } else { return "Yes";}
    
 

}
//Zoos

// Sample code to perform I/O:

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
   main(stdin_input);
});

function main(input) {
    var data= input.toString().split("\n");
    process.stdout.write(check(data[0]));       // Writing output to STDOUT
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail



// Write your code here
// Sample code to perform I/O:
//Enter your code here
function check(data) {

    const n=data.length;
    let x = 0;
    let y = 0;

    for (let i=0; i<n; i++) {
        if (data[i]=="z") {
            x++ ;
        } else {
            if (data[i]=="o") {
                y++;
            } 
        }
    }

    if (2 * x == y) {
        return "Yes";
    } else { return "No";}


}
//Number of steps in Hackerearth
// Sample code to perform I/O:

process.stdin.resume();
process.stdin.setEncoding("utf-8");
var stdin_input = "";

process.stdin.on("data", function (input) {
    stdin_input += input;                               // Reading input from STDIN
});

process.stdin.on("end", function () {
   main(stdin_input);
});

function main(input) {

    var data = input.split('\n');
    var num = parseInt(data[0],10); 

    var aa = data[1].split(' ').map(function(item) { return parseInt(item, 10);});

var bb = data[2].split(' ').map(function(item) { return parseInt(item, 10);});

   process.stdout.write(f(aa,bb));
   //console.log(f(aa,bb));
   
   // Writing output to STDOUT
 
}

// Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail



// Write your code here
// Sample code to perform I/O:
//Enter your code here

function f(A, B){
  const n = A.length;
  const m = Math.min(...A);
  let result;
  
  for (let t=m; t>=0; t--){
    result = 0;
    
    for (let i=0; i<n; i++){
      if ((A[i] - t) % B[i] == 0){
        result = result + (A[i] - t) / B[i];
        
      } else {
        result = -1;
        break;
      }
    }
    
    if (result > -1)
      return result.toString();
  }
  
  return result.toString();
}
class Foo extends React.Component {
  render() {
    return (
      <Link to='/bar' className='disabled-link'>Bar</Link>
    );
  }
}
AND CSS 
.disabled-link {
  pointer-events: none;
}
document.addEventListener("DOMContentLoaded", function () {

    let bgSlideShows = document.querySelectorAll('#bgslideshow01 > .slideshow');
    let myIndex = 1;
    
    function slideShow() {
        bgSlideShows.forEach(slide => {
            slide.style.display = 'none';
        });
        bgSlideShows[myIndex - 1].style.display = 'block';
        if (myIndex === bgSlideShows.length) {
            myIndex = 1;
        }
        myIndex++;
        setTimeout(slideShow, 7000);
    }
    slideShow();
   
});
const Component = ({ receiveAmount, sendAmount }) => {
  const prevAmount = useRef({ receiveAmount, sendAmount }).current;
  useEffect(() => {
    if (prevAmount.receiveAmount !== receiveAmount) {
     // process here
    }
    if (prevAmount.sendAmount !== sendAmount) {
     // process here
    }
    return () => { 
      prevAmount.receiveAmount = receiveAmount;
      prevAmount.sendAmount = sendAmount;
    };
  }, [receiveAmount, sendAmount]);
};
//Iterate through the array and multiply a number by 10 if it is greater than or equal to 5.
const timesTenIfOverFive = [23, 9, 11, 2, 10, 6];
// ADD CODE HERE
for(let i = 0; i < timesTenIfOverFive.length; i++){
  if(timesTenIfOverFive[i] >= 5){
    timesTenIfOverFive[i] *= 10;
  } 
  
}

// Uncomment the line below to check your work!
console.log(timesTenIfOverFive); // -> should print [230, 90, 110, 2, 100, 60]
Handlebars.registerHelper('check', function(value, comparator) {
    return (value === comparator) ? 'No content' : value;
});
// considering this array of objects
const orders = [
  {
    id: 101,
    server: "Mindy Kaling",
    subtotal: 473,
    tax: 24,
  },
  {
    id: 102,
    server: "Nina Totenberg",
    subtotal: 1053,
    tax: 52,
  },
  {
    id: 103,
    server: "Serena Williams",
    subtotal: 1497,
    tax: 75,
  },
  {
    id: 104,
    server: "Mindy Kaling",
    subtotal: 251,
    tax: 12,
  },
  {
    id: 105,
    server: "Malala Yousafzai",
    subtotal: 1715,
    tax: 85,
  },
  {
    id: 106,
    server: "Nina Totenberg",
    subtotal: 320,
    tax: 16,
  },
];

// we have to check if there is any duplicate entry on the list
// create an objet to hold all the servers
// use reduce by passing two params: the new object and orders
function renderByServers(orders) {
    const servers = {};

    const result = orders.reduce((servers, order) => {
      const { server, subtotal, tax } = order;

      // first, check if the server is undefined: if yes, set it to 0
      // if(servers[server] === undefined){}
      if (!servers[server]) {
        servers[server] = 0;
      }
      // otherwise, calculate the reduce by adding to the server the sum of subtotal + tax
      servers[server] += subtotal + tax;
      return servers;
    }, {});

    return result;
  }
  // this function returns an object - that is not possible to use .map() once map is for arrays
  // also, an object cannot be passed by as children
  console.log(renderByServers(orders));

  // but is possible to get the keys or values of the object converted in array, and from there, map() if is necessary
  console.log(Object.keys(renderByServers(orders)));
  console.log(Object.values(renderByServers(orders)));
// if using a forEach() to associate each key-value pairs into an array of objects
  function combiningArraysIntoKeyPairValues() {
    var arr1 = 'declare your first array here';
    var arr2 = 'declare your second array here';
    // ps: you must consider that both array has same length?
    
    var combinedObj = {};
    let arr = [];

    arr1.forEach((item, index) => {
       combinedObj = { name: item, amount: arr2[index] };
      arr.push(combinedObj);
    });

    return arr;
  }
  console.log(combiningArraysIntoKeyPairValues());
const express = require('express');
const cors = require('cors');
const { MongoClient, ServerApiVersion } = require('mongodb');
const { config } = require('dotenv');
const app = express();
const port = process.env.PORT || 5000;

require('dotenv').config();
// middleware

app.use(cors());
app.use(express.json());

app.get('/', (req, res) => {
    res.send('Volunteer Server is running');

})
app.listen(port, () => {
    console.log('listening port',port);
})
<!-- Remove Fundrasing Features OFF from SS -->
<script type="text/javascript">
    // <![CDATA[
    var collection = document.getElementsByClassName("tpl-main-content-side");
    collection[0].style.display = "none";
    // ]]>
</script>


<!-- Toggle Fundrasing Thermometer ON from SS -->
<!-- Paste this code into the WYSIWYG HTML area for a project -->
<script type="text/javascript">
    // <![CDATA[
    var container = document.getElementsByClassName("tpl-main-content-side");
    var button = document.getElementsByClassName("tpl-start-a-campaign");
    container[0].style.display = "block";
    button[0].style.display = "none";
    // ]]>
</script>
(function ($) {

    $.fn.flexipage = function (options) {

        // build main options before element iteration
        var opts = $.extend({}, $.fn.flexipage.defaults, options);
        $.fn.flexipage.options = opts;


        //builds pager 
        function buildPager($target, HTML) {
            if (opts.pager_selector == false) {
                $target.after('<div id="scrollable"><ul class="pager">' + HTML + '</ul></div>')
                opts.pager_selector = ".pager"
            } else {
                $(opts.pager_selector, $.fn.flexipage.options.parent_cont).html(HTML)
            }
        }

        // iterate and reformat each matched element

        return this.each(function () {
            if (opts.pager == true) opts.navigation == false;
            if (opts.navigation == true) opts.pager == false;

            var $target = $(this);
            $target.data("opts", opts)

            opts.wrapper = $target.closest('div')
            opts.actual = opts.firstpage;
            opts.total_pages = Math.ceil(($(opts.element, $target).length) / opts.perpage);

            if (opts.pager == true) opts.navigation == false;
            if (opts.navigation == true) opts.pager == false;

            // if pager is set to true
            if (opts.pager == true) {
                (opts.showcounter == true) ? opts.showcounter = '<li><span class="actual"></span>/<span class="total">' + opts.total_pages + '</span></li>' : opts.showcounter = ' ';
                var pagerHTML = '<li class="prev"><a href="#">' + opts.prev_txt + '</a></li>' + opts.showcounter +
                    '<li class="next"><a href="#">' + opts.next_txt + '</a></li>';

                buildPager($target, pagerHTML)

                //click event for next page 
                $(opts.pager_selector + ' li.next a', opts.wrapper).click(function (e) {
                    e.preventDefault();

                    if (opts.actual <= (opts.total_pages - 1)) {
                        $target.selectPage(opts.actual + 1);
                    };
                });

                //click event for prev page 
                $(opts.pager_selector + ' li.prev a', opts.wrapper).click(function (e) {
                    e.preventDefault();

                    if (opts.actual <= (opts.total_pages + 1)) {
                        $target.selectPage(opts.actual - 1);
                    };
                })
            };

            //if navigation is set to true
            if (opts.navigation == true) {
                var navigationHTML = "";
                var actual;

                for (var i = 1; i <= opts.total_pages; i++) {
                    (opts.firstpage == i) ? actual = ' class="active" ' : actual = '';
                    navigationHTML += '<li' + actual + '><a rel="' + i + '" href="#">' + i + '</a></li>';
                };

                buildPager($target, navigationHTML)

                // CLICK EVENTS
                $(opts.pager_selector + ' li a', opts.wrapper).click(function (e) {
                    e.preventDefault();
                    var topage = $(this).attr('rel');
                    if (topage <= opts.total_pages && topage > 0) {
                        $target.selectPage(topage);
                    };
                })
            };

            //if carousel set to true
            if (opts.carousel == true) {
                opts.elements = $(opts.element, $target);
                $target.wrap('<div class="flexiwrap"></div>')
                $target.parent().css({
                    overflow: 'hidden',
                    position: 'relative'
                })
                $target.css({
                    overflow: 'hidden',
                    position: 'absolute',
                    top: '0px',
                    left: '0px'
                })
                opts.distances = [];

                for (var i = 0; i <= opts.total_pages; i++) {
                    opts.distances[i] = (i * opts.perpage) * $($(opts.elements[i]), $target).width();
                };
            };

            //show first page, first time
            $target.selectPage(opts.firstpage);

        });
    };


    //show pages function
    $.fn.selectPage = function (n) {
        var parent = $(this)
        var opts = parent.data('opts')


        if (n == "next") {
            (opts.actual < opts.total_pages) ? n = opts.actual + 1 : n = opts.total_pages;
        }

        if (n == "prev") {
            if (opts.actual > 0) n = opts.actual - 1;
        }

        if (n == 0 || n == undefined) n = 1;

        if (n > 1) var $selected_items = $(opts.element + ':lt(' + (n * opts.perpage) + '):gt(' + (((n - 1) * opts.perpage) - 1) + ')', parent);
        else var $selected_items = $(opts.element + ':lt(' + (n * opts.perpage) + ')', parent);

        if (opts.carousel == true) {
            parent.animate({
                left: '-' + opts.distances[n - 1] + 'px'
            }, opts.speed, opts.animation)
        } else {
            $selected_items.css(opts.visible_css)
            $(opts.element, parent).not($selected_items).css(opts.hidden_css)
        }

        if (opts.navigation == true) {
            $(opts.pager_selector + ' li', opts.wrapper).removeClass('active')
            $(opts.pager_selector + ' li:eq(' + (n - 1) + ')', opts.wrapper).addClass('active')
        };

        if (opts.pager == true) {
            $(opts.pager_selector + ' .actual', opts.wrapper).html(n);
            $(opts.pager_selector + ' .disabled', opts.wrapper).removeClass('disabled');
            if (n == opts.total_pages) $(opts.pager_selector + ' .next', opts.wrapper).addClass('disabled');
            if (n == 1) $(opts.pager_selector + ' .prev', opts.wrapper).addClass('disabled');
        };
        opts.actual = parseInt(n);
    };


    // plugin defaults
    $.fn.flexipage.defaults = {
        element: "li",
        pager: true,
        next_txt: "Next &raquo;",
        prev_txt: "&laquo; Prev",
        pager_selector: false,
        perpage: 5,
        showcounter: true,
        hidden_css: {
            display: 'none'
        },
        visible_css: {
            display: 'block'
        },
        firstpage: 1,
        navigation: false,
        carousel: false,
        speed: 300,
        animation: 'linear'
    };


})(jQuery);
 	
	const fetchData = async () => {
        navigator.geolocation.getCurrentPosition(function(position) {
            /**
             * update in usestate array 
             */
            setLat(position.coords.latitude);
            setLong(position.coords.longitude);
        });
// window.location.search = ?name=sai

const params = new URLSearchParams(window.location.search);

const name = params.get("name");

console.log(name); // "sai"
// Supported in IE 9-11
const people = [
  {id: 1, name: 'John'},
  {id: 2, name: 'Adam'},
];

const isFound = people.some(element => {
  if (element.id === 1) {
    return true;
  }

  return false;
});

console.log(isFound); // 👉️ true

if (isFound) {
  // object is contained in array
}
const box = document.getElementById('box');

// 👇️ add 2 event listeners
box.addEventListener('click', function handleClick() {
  console.log('box clicked first');
});

box.addEventListener('click', function handleClick() {
  console.log('box clicked second');
});

// ✅ Remove event listeners from Element
box.replaceWith(box.cloneNode(true));
/* CODE FOR DEMONSTRATION PURPOSES */
function setFontAndBackgroundColorCell() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];
  var cell = sheet.getRange('B2');
  cell.setFontColor('yellow');
  cell.setBackground('red');
  cell.setValue('TEST');
}
/* CODE FOR DEMONSTRATION PURPOSES */
const then = new Date('2022-01-24T09:30:20');
const now = new Date();

const msBetweenDates = Math.abs(then.getTime() - now.getTime());

// 👇️ convert ms to hours                  min  sec   ms
const hoursBetweenDates = msBetweenDates / (60 * 60 * 1000);

console.log(hoursBetweenDates);

if (hoursBetweenDates < 24) {
  console.log('date is within 24 hours');
} else {
  console.log('date is NOT within 24 hours');
}
import React, { useEffect, useRef } from 'react';

const [counter, setCounter] = useState(0);
const didMount = useRef(false);

const doSomething = () => {
  setCounter(123);
}

useEffect(() => {
  // Return early, if this is the first render:
  if ( !didMount.current ) {
    return didMount.current = true;
  }
  // Paste code to be executed on subsequent renders:
  console.log('Do something after counter has changed', counter);
}, [counter]);
Содержиь хотя бы 1 цифру и хотя бы одну заглавную букву

function validate(password) {
  return /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9]{6,}$/.test(password);
}
dsDate2DDMM = function (date) {
    date = date instanceof Date ? date : date.Value;
    let year = date.getFullYear();
    if (year <= 1900) {
        return null;
    }
    let month = date.getMonth() + 1;
    let day = date.getDate();
    return ((day < 10 ? '0' + day : day) + '/' + (month < 10 ? '0' + month : month));
}
dsDate2String = function (date) {
    date = date instanceof Date ? date : date.Value;
    let year = date.getFullYear();
    if (year <= 1900) {
        return null;
    }
    let month = date.getMonth() + 1;
    let day = date.getDate();
    if (sLang == 'en-US') {
        return ((month < 10 ? '0' + month : month) + '/' + (day < 10 ? '0' + day : day) + '/' + year.toString());
    } else {
        return ((day < 10 ? '0' + day : day) + '/' + (month < 10 ? '0' + month : month) + '/' + year.toString());
    }
}
const navigate = useNavigate()
navigate(-1)
const arr = [1, [2, [3, 4, [5, [6, 7, 8]]]]];

const flatArr = (arr) =>
  arr.reduce(
    (acc, curr) =>
      Array.isArray(curr) ? [...acc, ...flatArr(curr)] : [...acc, curr],
    []
  );
{
  "manifest_version":2,
  "version":"1.0",
  "name":"Test",
  "content_scripts":[
   {
    "matches":["<all_urls>"],
    "js":["main.js"]
   }
  ],
  "web_accessible_resources": [
        "pp.jpg"
  ]
}
// Check
document.getElementById("checkbox").checked = true;

// Uncheck
document.getElementById("checkbox").checked = false;
const getToken = (request) => {
  const authorizationHeader = request.get("authorization");
  if (
    authorizationHeader &&
    authorizationHeader.toLowerCase().startsWith("bearer ")
  ) {
    return authorizationHeader.substring(7);
  }
  return null;
};
export const setStyles = (styles) => {
  const range = document.createRange()
  const arr = []
  Object.entries(styles).forEach(([key]) => {
    const obj = JSON.stringify(styles[key], null,'\t')
      .replace(/"/g,'')
      .replace(/,\n/g,';')
      .replace(/\}/g, ';}')
    arr.push(`.${key}${obj}`)
  });
  const res = `<style>${[...arr].join('')}</style>`
  const frag = range.createContextualFragment(res)
  document.querySelector("head").append(frag)
}
export const setModalStyles = (modalStyles) => {
  const range = document.createRange();
  let res = "";
  Object.entries(modalStyles).forEach(([key]) => {
    const obj = JSON.stringify(modalStyles[key], null, "\t")
      .replace(/"/g, "")
      .replace(/,\n/g, ";")
      .replace(/\}/g, ";}");
    res = `<style>.${key}${obj},</style>`;
  });
  const frag = range.createContextualFragment(res);
  document.querySelector("head").append(frag);
};
   function encryptByDES(message, key){
	    	var keyHex = CryptoJS.enc.Utf8.parse(key);
	    	//var keyHex = CryptoJS.enc.Base64.parse(key);
	    	var encryptd = CryptoJS.TripleDES.encrypt(message, keyHex, {
	    		iv: keyHex,
	    		mode: CryptoJS.mode.ECB
	    	});
	    	return encryptd;
	    }
<iframe loading="lazy" width="100%" height="355" border="0" style="border: 0;" src="https://fastcast4u.com/player/george2772/" allow="autoplay"></iframe>
      <div class="block md:flex overflow-hidden w-full">

      <div class=" md:w-1/2  bg-white rounded shadow-lg p-5 m-5">
        Test
      </div>

      <div class="md:w-1/2 bg-white rounded shadow-lg p-5 m-5">
        Test
      </div>

      </div>
<div class="row-start-1 row-span-1 col-start-1 col-span-12">
import { device } from './device';

const CardWrapper = styled.div`
  display: flex;
  // Mobile friendly by default
  flex-direction: column;

  border: 1px solid gray;
  box-shadow: 5px 5px #ccc;
  padding: 10px;
  margin: 10px;

  // Switch to rows on large devices
  @media ${device.laptop} {
    flex-direction: row;
  }
`;
const Login = () => {
    const setToken = function(e) {
    if (
      e.origin === origin &&
      e.data &&
      e.data.command === 'token-ready' &&
      e.data.info &&
      e.data.info.token
    ) {
      localStorage.setItem('jwt', e.data.info.token);

      e.source.postMessage(
        {
          command: 'info',
          info: {
            complete: true,
          },
        },
        e.origin
      );
    }
  };

  
  window.addEventListener('message', setToken, false);

  const login = () => {
    window.open(loginUri);
  };

  return (<button onClick={login}>Login</button>
}
// decorator lights is a function which receives the class as an argument
let lights = function(tree) {
  // The behaviour of the class is modified here
  tree.treeLights = 'Christmas lights'
}

@lights  // the decorator is applied here
class ChristmasTree {}

console.log(ChristmasTree.treeLights);  // logs Christmas lights
function log(fn) {
  return function(actualValue) {
    const modifiedActualValue = `Logged value: ${actualValue}`;
    fn(modifiedActualValue);
  }
}

const logger = log(console.log);

logger('Pera');
//Logged value: Pera
$('mydiv').on('DOMSubtreeModified', function(){
  console.log('changed');
});
const mongoose = require('mongoose')
const supertest = require('supertest')
const app = require('../app')

const api = supertest(app)

test('notes are returned as json', async () => {
  await api
    .get('/api/notes')
    .expect(200)
    .expect('Content-Type', /application\/json/)
})

afterAll(() => {
  mongoose.connection.close()
})
const mostLikes = (array) => {
  const authorsAndLikesArray = _(array)
    .groupBy("author")
    .map((objs, key) => ({
      author: key,
      totalLikes: _.sumBy(objs, "likes"),
    }))
    .value();
  const sorted = _.sortBy(authorsAndLikesArray, "totalLikes").reverse();
  return sorted
};
{
    field: 'fullAddress',
    headerName: 'Address',
    tooltip: (params) => 'Address: ' + params.value
}
//HTML
<div class="container">
      <div class="box box-1"></div>
      <div class="box box-2"></div>
      <div class="box box-3"></div>
      <div class="box box-4"></div>
      <div class="box box-5"></div>
</div>

//CSS
.container {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}

.box {
  width: calc(50% - 2rem);
  height: 100px;
  border-radius: 20px;
  margin: 1rem;
  transform: translateY(50px);
  opacity: 0;
  transition: all 0.5s;
}

.box-1 {
  background-color: coral;
}
.box-2 {
  background-color: cornflowerblue;
}
.box-3 {
  background-color: palegoldenrod;
}
.box-4 {
  background-color: violet;
}
.box-5 {
  background-color: palegreen;
}

.inView {
  opacity: 1;
  transform: translateY(0px);
}

//Javascript
const boxes = document.querySelectorAll('.box');

window.addEventListener('scroll', fadeIn);

function fadeIn() {
  boxes.forEach((box) => {
    //get viewport-point where the transition should happen
    let distanceInView =
      box.getBoundingClientRect().top - window.innerHeight + 20;

    if (distanceInView < 0) {
      box.classList.add('inView');
    } else {
      box.classList.remove('inView');
    }
  });
}

//call function if elements are already on screen when pafge loads
fadeIn();
var numArray = [140000, 104, 99];
numArray.sort(function(a, b) {
  return a - b;
});

console.log(numArray);
// Scroll to specific values
// scrollTo is the same
window.scroll({
  top: 2500, 
  left: 0, 
  behavior: 'smooth'
});

// Scroll certain amounts from current position 
window.scrollBy({ 
  top: 100, // could be negative value
  left: 0, 
  behavior: 'smooth' 
});

// Scroll to a certain element
document.querySelector('.hello').scrollIntoView({ 
  behavior: 'smooth' 
});
fetch('http://example.com/songs')
	.then(response => response.json())
	.then(data => console.log(data))
	.catch(err => console.error(err));
$(document).ready(function () {

    var intervaltime = $('#intervaltime').val();
    //LoadData();
    var table = $('#tbl_1').DataTable({
        "ajax": {
            method: 'POST',
            url: '/Home/GetDataPrevious',
            contentType: "application/json; charset=utf-8",
            dataSrc: ''
        },
        "columnDefs": [
            { className: "Title", "targets": [0] }
        ],
        "columns": [
            { "data": "timeZone"}
        ],
        "filter": true,
        "paging": false,
        "info": false,
        "searching": false,
        "ordering": true,

        "createdRow": function (row, data, index) {
            var tr = $(row).closest('tr');
            var thisrow = table.row(tr);
            let list = data.dashboarddetails;
            let html = '<table class="display">';
            html += '<thead>';
            html += '<tr>';
            html += '<th style="background-color: #009879;color: #ffffff;">Branch</th>';
            html += '<th style="background-color: #009879;color: #ffffff;">Total No of Orders</th>';
            html += '<th style="background-color: #009879;color: #ffffff;"># In Kitchen (Ordered)</th>';
            html += '<th style="background-color: #009879;color: #ffffff;"># with Kitchen Delay</th>';
            html += '<th style="background-color: #009879;color: #ffffff;"># Kitchen Ready</th>';
            html += '<th style="background-color: #009879;color: #ffffff;"># with window time</th>';
            html += '<th style="background-color: #009879;color: #ffffff;"># Driver Assigned</th>';
            html += '<th style="background-color: #009879;color: #ffffff;"># Delivered</th>';
            html += '<th style="background-color: #009879;color: #ffffff;">Expected Delivery Time</th>';
            html += '<th style="background-color: #009879;color: #ffffff;"># with Delivery Delay</th>';
            html += '<th style="background-color: #009879;color: #ffffff;">Dispatcher Notifications (Updated from Dispatcher Screen)</th>';

            html += '</tr>';
            html += '</thead>';
            html += '<tbody>';
            for (let i = 0; i < list.length; i++){
                html += '<tr>';
                html += '<td>';
                html += list[i].branch;
                html += '</td>';
                html += '<td>';
                html += list[i].totalOrders;
                html += '</td>';
                html += '<td>';
                html += list[i].ordersInKitchen;
                html += '</td>';
                html += '<td>';
                html += list[i].ordersKitchenDelay;
                html += '</td>';
                html += '<td>';
                html += list[i].ordersKitchenReady;
                html += '</td>';
                html += '<td>';
                html += list[i].ordersWaitingDelay;
                html += '</td>';
                html += '<td>';
                html += list[i].ordersAssigned;
                html += '</td>';
                html += '<td>';
                html += list[i].ordersDelivered;
                html += '</td>';
                html += '<td>';
                html += list[i].expectedDeliveryTime;
                html += '</td>';
                html += '<td>';
                html += list[i].ordersDeliveryDelay;
                html += '</td>';
                html += '<td>';
                html += list[i].memo;
                html += '</td>';
                html += '</tr>';
            }
            html += '</tbody>';
            html += '</table>';

            thisrow.child(html).show();
            tr.addClass('shown');
        }
    });


    var intervalsec = intervaltime * 1000;

    setInterval(function () { table.ajax.reload(); }, intervalsec);
});
// ex. importing multiple exports:
import { MyClass, MyOtherClass } from "./MyClass";
// ex. giving a named import a different name by using "as":
import { MyClass2 as MyClass2Alias } from "./MyClass2";

// use MyClass, MyOtherClass, and MyClass2Alias here
//HTML
 <div class="cursors">
    <div></div>
 </div>

//CSS style the element
/* Style the cursor */
.cursors div {
  position: absolute;
  top: 0;
  left: 0;
  width: 25px;
  height: 25px;
  background: url('imgs/home/bub.svg') no-repeat center/ cover;
  border-radius: 50%;
  z-index: 10000;
  /* Prevent from getting in the way when links are clicked */
  pointer-events: none;
  /* Move the ball to the center of the cursor */
  transform: translate(-50%, -50%);
  opacity: 1;
  transition: opacity 0.3s;
}

//Javascript

// CURSOR
const cursor = document.querySelector('.cursors');
const circle = cursor.querySelector('div');
const elementsWitoutCursor = document.querySelectorAll('.hide-cursor');

//Animate cursor
let aimX = 0;
let aimY = 0;

let currentX = 0;
let currentY = 0;
let speed = 0.2;
const animate = () => {
  currentX += (aimX - currentX) * speed;
  currentY += (aimY - currentY) * speed;
  circle.style.left = currentX + 'px';
  circle.style.top = currentY + 'px';

  requestAnimationFrame(animate);
};

animate();

document.addEventListener('mousemove', (event) => {
  aimX = event.pageX;
  aimY = event.pageY;
});

//hide the cursor when hovering over elements with a specific class
elementsWitoutCursor.forEach((element) => {
  element.addEventListener('mouseover', () => {
    circle.classList.add('invisible');
  });
  element.addEventListener('mouseout', () => {
    circle.classList.remove('invisible');
  });
});
preventZeroFirst($event)

	preventZeroFirst(e) {
		if (/^0/.test(e.target.value)) {
			e.target.value = e.target.value.replace(/^0/, "")
		}
    },
<ul>
                            <li className='group'>
                                <div 
                                className='flex items-center px-5 py-3 text-gray-600 text-lg 
                                                hover:text-blue-700 hover:bg-slate-200 cursor-pointer'
                                onClick={ () => setShowDropdown(showDropdown === "Submenu 1" ? undefined : "Submenu 1") }
                                >
                                    <FiHome
                                        className='h-85 w-5 text-gray-500 mr-2'
                                    />
                                    Inicio
                                </div>

                                { showDropdown === "Submenu 1" &&  (

                                    <div /* className='
                                        opacity-0 h-0 group-hover:opacity-100 group-hover:h-auto 
                                        transition linear duration-500 delay-150' */
                            /*             className= {`opacity-0 h-0 ${ showDropdown ? 
                                        "group-hover:opacity-100 group-hover:h-auto transition linear duration-500 delay-150" 
                                        : "" } ` // AQUI SIRVE BIEN PERO AL SALIR DEL BOTÖN SE OCULTA POR EL HOVER } */

                                    /*  className= {`opacity-0 h-0 ${ showDropdown ? 
                                        "opacity-100 h-auto transition linear duration-500 delay-150" 
                                        : "" } `
                                    }  */
                                        >
                                    
                                        <ul className='bg-white'>
                                            <li className="py-3 px-6 hover:bg-slate-200">Test</li>
                                            <li className="py-3 px-6 hover:bg-slate-200">Test</li>
                                        </ul>

                                    </div>
                                )
                                
                                
                                
                                }
                            </li>
                        </ul>
//The below is HTML from the Widget: Vendor Validation
//It was modifed per DMND0063775 Make ACH fields mandatory
//This is the HTML around the field: Financial Institution Name

 <div ng-if="data.terms == 'ach'" class ="row">
           <div class="col-md-6">
              <div class="form-group">
                <label for="cs_email">Financial Institution Name*</label>
                <input ng-model="data.financial_name" id="rNumber" placeholder="" type="text" name="Financial Institution Name" class="form-control" required="required">
                <div class="help-block with-errors"></div>
              </div>
            </div>
            </div>
 var preloader = document.getElementById("loading");
    var body = document.querySelector("body");
    var html = document.querySelector("html");
    document.addEventListener("DOMContentLoaded", function () {
      setTimeout(function loader() {
        preloader.style.display = "none";
        body.classList.remove("no-scroll-y");
        body.classList.add("no-scroll-x");
        html.classList.add("no-scroll-x");
      }, 1500);
    });
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");

var data = "some really long string greater than 50k characters";
// write content to a new row created, no 50k error!
sheet.appendRow([data]);

var lastRowRange = sheet.getRange(sheet.getLastRow(), 1);

// copy newly created content to desired range
var outputRange = sheet.getRange("A1");
lastRowRange.copyTo(outputRange);

// clear newly created row
lastRowRange.clearContent();
export type Language = 'EN' | 'DE' | 'IT';

export interface Document {
  generic: string;
  languages: {
    [key in Language]: string[];
  }
}
enum possibleTypes { 'foo', 'bar' };
type Types {
    [key in keyof typeof possibleTypes]: boolean
}
function myFunction(){
  var spreadsheetId = 'some Id'
  var csvFileId = 'some Id'
  var sheet = SpreadsheetApp.openById(spreadsheetId).getSheetByName('Sheet1');
  sheet.clear();
  
  getCSVData(csvFileId, spreadsheetId);
}

function getCSVData(csvFileId, spreadsheetId){
  var data = DriveApp.getFileById(csvFileId)
  .getBlob()
  .getDataAsString();
  var sheetId = SpreadsheetApp.openById(spreadsheetId)
  .getSheets()[0]
  .getSheetId();
    
  var resource = {
    requests: [
      {
        pasteData: {
          data: data,
          coordinate: { sheetId: sheetId,
                       rowIndex: 0,
                       columnIndex: 0 },
          type: 'PASTE_VALUES',
          delimiter: ","
        },
      }
    ],
    includeSpreadsheetInResponse: true,
  };
  Sheets.Spreadsheets.batchUpdate(resource, spreadsheetId);
}
function SLSalesImportFromGmail() {
  var ss = SpreadsheetApp.getActive(); // Get the spreadsheet file once

  //gets first(latest) message with set label
  var threads = GmailApp.getUserLabelByName('South Loop').getThreads(0,1);
  if (threads && threads.length > 0) {
    var message = threads[0].getMessages()[0];

    // Get all of the attachments and loop through them.
    var attachments = message.getAttachments(); 
    for (var i = 0; i < attachments.length; i++) {
      var attachment = attachments[i];
      var title = attachment.getName();

      // Is the attachment a CSV file
      attachment.setContentTypeFromExtension();
      var table = Utilities.parseCsv(attachment.getDataAsString());
      if (attachment.getContentType() === "text/csv") {
        // Update the specified sheets
        // Clears the sheet of values & formatting and inserts the new table
        // using the Apps Script built-in CSV parser.
        switch (title) { 
          case "Sales.csv":
            ss.getSheetByName("South Loop Sales").getRange("A:M").clear();
            ss.getSheetByName("South Loop Sales").getRange(1, 1, table.length, table[0].length).setValues(table);
            break;
          case "Labor.csv":
            ss.getSheetByName("South Loop Labor").getRange("A:M").clear();
            ss.getSheetByName("South Loop Labor").getRange(1, 1, table.length, table[0].length).setValues(table);
            break;
          case "ServerPerformance.csv":
            ss.getSheetByName("South Loop Servers").getRange("A:M").clear();
            ss.getSheetByName("South Loop Servers").getRange(1, 1, table.length, table[0].length).setValues(table);            
            break;
        }
      }      
    }
    if (message.getSubject().indexOf('END OF DAY') !== -1) {
      SLlogTodaysSales();
      SLlogTodaysServers();
    }
    if (message.getSubject().indexOf('END OF WEEK') !== -1) {
      SLlogTodaysSales();
      SLlogTodaysServers();
      SLlogWeeksLabor();
    }
    // Marks the Gmail message as read, unstars it and deletes it using Gmail API (Filter sets a star)
  message.markRead();
  message.unstar();
  Gmail.Users.Messages.remove("me", message.getId()); // Added
  }
}
**
 * @NApiVersion 2.x
 * @NScriptType ClientScript
 * @NModuleScope SameAccount
 * 
 */
define(['N/record'],function(record){
  function pageInit(context){
    var objRec=context.currentRecord;
    var itemsLength=objRec.getLineCount({
      sublistId:'item'
    });
    log.debug('itemsLength',itemsLength);
    for(var i=itemsLength-1;i>=0;i--){
      log.debug('running line ',i+' of '+itemsLength);
      /*
      var loss=objRec.getSublistValue({
        sublistId:'item',
        fieldId:'custcol_linelossreason',
        line: i
      });
      */
      //if(loss){
      objRec.removeLine({
        sublistId:'item',
        line:i,
        ignoreRecalc:true
      });
      log.debug('removed','Line '+i+' has been removed.');
     /*
      }else{
        log.debug('no removal','Line '+i+' will remain.');
      }
      */
    }
  }

  return{
    pageInit:pageInit
  }
});
    getDrawingCategoryTypes() {
      const vue = this;
      const buldingFiles = [];
      this?.request?.details?.buildings?.forEach((building, index) => {
        const types = new Set();
        building.buildingFiles?.forEach(category => types.add(category?.typeID));
        const data = Array.from(types).map(typeId => {
          const filterdData = building.buildingFiles?.filter(i => i?.typeID === typeId);
          return {
            typeId: typeId,
            typeName: filterdData[0]?.typeName,
            obj:filterdData[0],
          };
        });
        buldingFiles.push({ data: data, index: index });
      });
      console.log('bFiles',buldingFiles);
      return buldingFiles;
    },
const parser = 'babel'

function transformer (file, api) {
   const j = api.jscodeshift;
   const root = j(file.source);

   // find declaration for "moment" import
   return root.find(j.ImportDeclaration, { source: { value: 'moment'}}).forEach(path => {
	   path.value.source.value = 'dayjs'
   }).toSource();
}

module.exports = transformer
module.exports.parser = parser
import React from 'react'
import dayjs from 'moment'

const page = () => {
   return <div className={'subtitle'}>{dayjs(publishedAt).format(t('dateFormat'))}</div>;
}
jest.autoMockOff();
const defineTest = require('jscodeshift/dist/testUtils').defineTest;

defineTest(__dirname, 'transform', null, 'simple');
const parser = 'babel'

function transformer (file, api) {
	const j = api.jscodeshift;
	const root = j(file.source);

	return root.find(j.Identifier)
		.forEach(path => {
			// find declaration for "moment" identifier
			if (path.node.name === 'moment') {
				j(path).replaceWith(
					j.identifier('dayjs')
				);
			}
		})
		.toSource();
}

module.exports = transformer
module.exports.parser = parser
const storage = [
  { data: '1', status: '0' },
  { data: '2', status: '0' },
  { data: '3', status: '0' },
  { data: '4', status: '0' },
  { data: '5', status: '0' },
  { data: '6', status: '0' },
  { data: '7', status: '1' },
];

const count = storage.filter(function(item){
  if (item.status === 0) {
    return true;
  } else {
    return false;
  }
}).length; // 6
define(["N/file"], function (f) {

    /**
     * Custom module for executing N/file cookbook examples
     *
     * @NApiVersion 2.0
     * @NModuleScope SameAccount
     */
    var exports = {};

    function readFile(response) {
        var weatherFile = f.load({id: "SuiteScripts/weather.csv"});

        var weatherData = [];
        weatherFile.lines.iterator().each(function (line) {
            var w = line.value.split(",");
            weatherData.push({date: w[0], low: w[1], high: w[2]});
            return true;
        });

        response.write({output: JSON.stringify(weatherData)});
    }

    exports.readFile = readFile;
    return exports;
});
const db = {}

const updateDB = (item) => {
    if (item in db) {
        db[item] = db[item] + 1;
    }
    else {
        db[item] = 1;
    }
    console.log(db);
}
fetch('/payment', {
    method: 'POST', 
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'url': '/payment',
        "X-CSRF-Token": document.querySelector('input[name=_token]').value
    },
})
const truncate = (input) => `${input.substring(0, 25)}...`;
import React from "react";
import { Bar } from "react-chartjs-2";
import { useParams } from "react-router-dom";
import useFetch from "../../hooks/useFetch";
import Spinner from "../../shared/Spinner";
import { optionsReportsComparison } from "../shared/options";
import ChartDataLabels from "chartjs-plugin-datalabels";

const data = {
  datasets: [
    {
      type: "line",
      label: "Dataset 1",
      borderColor: "rgb(255, 99, 132)",
      data: {
        2021: 3,
        2022: 2,
      },
      stack: "Scenario - Test analytics - Februaryy",
    },
    {
      type: "bar",
      label: "Dataset 2",
      backgroundColor: "rgb(75, 192, 192)",
      data: {
        2021: 1.25,
        2022: 1.25,
      },
      stack: "Scenario - Test analytics - February",
    },
  ],
};

const ScenarioTargets = () => {
  const { reportPk } = useParams();
  // const { data } = useFetch(`/api/analytics/get-scenario-target-chart/${reportPk}/?model-name=scope_fk&group-by=report`);

  if (!data) {
    return <Spinner />;
  } else {
    const tweakData = () =>
      data.datasets.map((d) => {
        d.barPercentage = 0.4;
        d.categoryPercentage = 0.5;
        d.borderRadius = 10;
        if (d.label === "Scope 3") {
          d.padding = { top: 20 };
          d.datalabels = {
            labels: {
              report: {
                backgroundColor: "white",
                borderRadius: 4,
                borderWidth: 1,
                borderColor: "#4a5568",
                padding: {
                  top: 2,
                  bottom: 2,
                  left: 4,
                  right: 4,
                },
                offset: 4,
                align: "end",
                anchor: "end",
                color: "#4a5568",
                font: { size: 10 },
                formatter: function (value, ctx) {
                  return ctx.dataset.info;
                },
              },
            },
          };
        }
      });
    tweakData();
    // const tweakData = () =>
    //   data.datasets.map((d) => {
    //     d.barThickness = 30;
    //     d.borderRadius = 10;
    //     delete d.stack;
    //   });
    // tweakData();

    return (
      <div className="p-10 bg-white shadow-lg rounded-box">
        <h3 className="text-xl uppercase font-bold mb-4 text-gray-700">Scenarios targets</h3>
        <p className="text-gray-500 mb-20">Evolution of carbon emissions over time to track improvement in your strategy.</p>
        <div className="flex items-center justify-center">
          <Bar options={optionsReportsComparison} data={data} plugins={[ChartDataLabels]} />
        </div>
      </div>
    );
  }
};

export default ScenarioTargets;
import { ThemeProvider, createTheme } from '@mui/styles'; ❌

import { ThemeProvider, createTheme } from '@mui/material/styles'; ✅

const theme = createTheme({
  typography: {
    allVariants: {
      fontFamily: 'serif',
      textTransform: 'none',
      fontSize: 16,
    },
  },
});

function App() {
  return (
      <ThemeProvider theme={theme}>
        ...
      </ThemeProvider>
  );
}
/*
- Implicit Binding
- Explicit Binding
- new Bindidng
- window Binding
*/
//----------------------------------------------
// where is this function invoked?
//----------------------------------------------
// var sayName = function(name) {
//   console.log('Hello, ' + name);
// };

// sayName('Vishnu!');
//----------------------------------------------
// Implicit Binding
// var me = {
//     name: 'Vishnu',
//     age: 25,
//     sayName: function() {
//         console.log(this.name);
//     }
// }

// me.sayName();   // According to implicit binding, `this` keyword is targetting the element left i.e. on the left side of the dot(.), in this case `me`
//----------------------------------------------

// var sayNameMixin = function(obj) {
//     obj.sayName = function() {
//         console.log(this.name);
//     }
// };
// var me = {
//     name: 'Vishnu',
//     age: 25
// };

// var you = {
//     name: 'unknown',
//     age: 21
// };

// sayNameMixin(me);
// sayNameMixin(you);

// me.sayName();
// you.sayName();

//----------------------------------------------

// var Person = function(name, age) {
//     return {
//         name: name,
//         age: age,
//         sayName: function() {
//             console.log(this.name);
//         },
//         mother: {
//             name: 'Mausi',
//             sayName: function() {
//                 console.log(this.name);
//             }
//         }
//     };
// };

// var jim = Person('Jim', 42);
// jim.sayName();
// jim.mother.sayName();

//----------------------------------------------
//----------------------------------------------

// Explicit Binding
// call, apply, bind

// var rand = {
//     name: 'rand',
//     age: 65,
//     // sayName: function() {
//     //     console.log('My name is ' + this.name);
//     // }
// };

// var sayName = function() {
//     console.log('My name is ' + this.name);
// };

// sayName.call(rand);

//----------------------------------------------



// var rand = {
//     name: 'rand',
//     age: 65,
//     // sayName: function() {
//     //     console.log('My name is ' + this.name);
//     // }
// };

// var sayName = function(lang1, lang2, lang3) {
//     console.log('My name is ' + this.name + ' and I know ' + lang1 + ', ' + lang2 + ', ' + lang3);
// };

// var languages = ['JS', 'C++', 'Python'];
// sayName.call(rand, languages[0], languages[1],languages[2]);

// // .apply is a similar thing as .call

// sayName.apply(rand, languages);     // .apply()


//----------------------------------------------


// var rand = {
//     name: 'rand',
//     age: 65,
//     // sayName: function() {
//     //     console.log('My name is ' + this.name);
//     // }
// };

// var sayName = function(lang1, lang2, lang3) {
//     console.log('My name is ' + this.name + ' and I know ' + lang1 + ', ' + lang2 + ', ' + lang3);
// };

// var languages = ['JS', 'C++', 'Python'];
// // sayName.call(rand, languages[0], languages[1],languages[2]);

// // .apply is a similar thing as .call

// // sayName.apply(rand, languages);     // .apply()



// var newFn = sayName.bind(rand, languages[0], languages[1],languages[2]);

// console.log('HERE');
// newFn();


//----------------------------------------------
//----------------------------------------------
//----------------------------------------------
//----------------------------------------------
//----------------------------------------------

// new Binding

// var Animal = function(color, name, type) {
//     this.color = color;
//     this.name = name;
//     this.type = type;
// }

// var Zebra = new Animal('black and white', 'Zorro', 'Zebra');

// console.log(Zebra);

//----------------------------------------------


// window Binding

var sayAge = function() {
    console.log(this.age);
};

var me = {
    age: 25
};

// sayAge.call(me);

sayAge();

window.age = 35;

sayAge();



fetch('http://catfacts-api.appspot.com/api/facts?number=99', { mode: 'no-cors'})
  .then(blob => blob.json())
  .then(data => {
    console.table(data);
    return data;
  })
  .catch(e => {
    console.log(e);
    return e;
  });
const today = new Date()
const oneMonthAgo = new Date(today.getFullYear(), today.getMonth() - 1, today.getDate())
//run before update
//condition  = current.state == 2 && current.demand.nil() && previous.state != 2

// gs.hasRole('demand_manager')  && current.state == 2 && current.demand.nil() && previous.state != 2
var demandTable = "dmn_demand";
if(GlidePluginManager.isActive('com.snc.project_management_v3')){
	demandTable = SNC.PPMConfig.getDemandTable(current.getTableName());
}

var demand = new GlideRecord(demandTable);
demand.initialize();
var fields = ['business_case', 'short_description', 'submitter', 'sys_domain', 'business_unit', 'department', 'impacted_business_units', 'business_capabilities', 'business_applications'];
for(var i in fields){
	var field = fields[i];
	if(demand.isValidField(field)){
		demand.setValue(field, current.getValue(field));
	}
}
//carry over and_or set feilds from idea to demand
demand.setValue("category","strategic");
demand.setValue('u_domain',current.module);
demand.setValue("type", "enhancement");
demand.setValue("parent", current.sys_id);
demand.setValue("idea", current.sys_id);
demand.setValue('u_sub_domain',getSubDomain(current.sys_id));
demand.setValue('assignment_group', current.u_it_assignment_group);
demand.setValue('priority',current.priority);
demand.setValue('u_growth',current.u_growth2);
demand.setValue('u_quality_safety',current.u_quality_and_safety2);
demand.setValue('u_financial',current.u_financial2);
demand.setValue('u_ppl',current.u_people2);
demand.setValue('u_it_wrk_effort',current.u_analyst_work_effort);
demand.setValue('u_complexity',current.u_complexity_of_coordination);
demand.setValue('u_training',current.u_training_needs);
demand.setValue('u_cust_wrk_effort',current.u_r_d_focus);
demand.setValue('u_prj_advanatages',current.u_epic_advantages);
demand.setValue('u_targeted_date',current.u_target_date);
demand.setValue('u_add_justification',current.u_additional_justification);
demand.setValue('u_est_loe',current.u_est_loe);//NG added 1.20.22 NOAH separation requirements

//since impacted portfolio is a list field you need to convert the values to strings in order to carry them over to the new record
var impactedPort = current.u_impacted_portfolio.toString();
if(impactedPort != ''){
demand.setValue('u_impacted_portfolios',impactedPort);	
}


demand.work_notes = current.work_notes.getJournalEntry(-1);
demand.work_notes = current.comments.getJournalEntry(-1);

var desc = current.idea_description; 
var regX = /<\/?[^>]+(>|$)/g;
var regxFormatted = desc.replace(regX, " "); //format desc with above regex
var spaceFormatted = regxFormatted.replaceAll('&nbsp;', " "); //replace all nbsp html characters with a space
finalDesc = spaceFormatted.replaceAll('&ndash;', "-"); // replace all ndash encoded html w/ ascii dash
demand.setValue("description", finalDesc);

if(GlidePluginManager.isActive('com.snc.apm')){
	demand.setValue("size", current.effort);
	if(current.pm_program)
		demand.setValue("primary_program", current.pm_program);
	if(current.start_by_fiscal_year)
		demand.setValue("start_date", new GlideDateTime(current.start_by_fiscal_year.fiscal_start_date_time).date);
	if(current.implement_by_fiscal_year)
		demand.setValue("requested_by", new GlideDateTime(current.implement_by_fiscal_year.fiscal_end_date_time).date);
	
	var demandPrice = parseFloat(current.estimated_benefit.getReferenceValue());
	demand.setValue("financial_benefit",  current.estimated_benefit.getReferenceCurrencyCode() + ';' + demandPrice);
}

var dmnId = demand.insert();
demand.get(dmnId);
current.demand = dmnId;
current.stage = 'demand';
GlideSysAttachment.copy('idea', current.sys_id, 'dmn_demand', demand.sys_id); // second paramenter is the current record and new record you created
var link = ' <a href ="/' + demandTable + '.do?sysparm_query=number%3D' + demand.getValue('number') + '">'+ demand.getValue('number') +'</a>';
var message = gs.getMessage("Demand {0} has been created");
	message = message.replace("{0}", link);
		
		gs.addInfoMessage(message);


function getSubDomain(id){
var gr = new GlideRecord('im_m2m_idea_category');
	gr.addQuery('idea',id);
	gr.query();
	if(gr.next()){
		return gr.category_id;
	}
	
}
//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

export const groupData = (data: any[], property: string) => {
  return data.reduce(function (acc, obj) {
    let key = obj[property];
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(obj);
    return acc;
  }, {});
};

// returns an object
document.body.style.padding = "40px 30px";
document.body.insertAdjacentHTML("beforeend", '<button id="pause" style="position:absolute;top:0;left:0;right:0">pause</button>')
var pauseBtn = document.getElementById("pause");
pauseBtn.onclick = function() {
	animate.paused(!animate.paused());
  pauseBtn.innerHTML = animate.paused() ? "play" : "pause";
}
import { APIGatewayProxyEvent, Context, APIGatewayProxyResult } from "aws-lambda"

export async function hello (event: APIGatewayProxyEvent, context: Context): Promise<APIGatewayProxyResult> {
  return {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Hello world',
      input: event,
    })
  }
}
function Person(name) {
  this.name = name;
  this.introduceSelf = function() {
    console.log(`Hi! I'm ${this.name}.`);
  }
}


const salva = new Person('Salva');
salva.name;
salva.introduceSelf();

const frankie = new Person('Frankie');
frankie.name;
frankie.introduceSelf();
$(window).trigger('broadcast.greatAddon', { maxVolume: 11 });
$(window).on('broadcast.greatAddon', function(msg) {
  console.log(msg.maxVolume);
});
<script type="text/javascript">
const pacificoObserver = new FontFaceObserver('Pacifico');
const robotoObserver = new FontFaceObserver('Roboto');

Promise.all([
  pacificoObserver.load(),
  robotoObserver.load()
]).then(function(){
  /* Do things */
  document.documentElement.className += " fonts-loaded";
});
</script>
for .. of
Browser support for for .. of loops looks pretty good and this seems like a super clean syntax to me:

for (const button of buttons) {
  button.addEventListener('click', () => {
    console.log("for .. of worked");
  });
}
 Save
Make an array right away
const buttons = Array.prototype.slice.apply(
  document.querySelectorAll(".js-do-thing")
);
 Save
Now you can use all the normal array functions.

buttons.forEach((button) => {
  console.log("apply worked");
});
for (const button of buttons) {
  button.addEventListener('click', () => {
    console.log("for .. of worked");
  });
}
(function() {
  var resizeTimer;
  
  // Assuming we have jQuery present
  $( window ).on( "resize", function() {
    
    // Use resizeTimer to throttle the resize handler
    clearTimeout( resizeTimer );
    resizeTimer = setTimeout(function() {

     /* Send the event to Google Analytics
      *
      * https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiEventTracking
      * _trackEvent(category, action, opt_label, opt_value, opt_noninteraction)   
      */
      var $window = $( window );
      _gaq.push( [ "_trackEvent", "User Actions", "Browser Resize", $window.width() + " x " + $window.height() ] );
    }, 1000);
  });
})();
loadCSS( 
  "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css",
  null,
  null,
  {
    "crossorigin": "anonymous",
    "integrity": "sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
  }
);
// Grab elements
//declare function expression, arrow function
//this method helps grab elements very easily
const selectElement = selector => {
    const element = document.querySelector(selector)
    if(element) return element;
    throw new Error('Something went wrong, make sure that ${selector} exists or is typed correctly.');
};

//testing the function
//console.log(selectElement('.footer'));
const dataToPost={ name:'Jenn', age: 40}

axios.post("url", dataToPost)
  .then((response) => {
  	console.log(response);
  	// do something with the response
    })
  .catch((error) => {
  	if (error.response) {
    	console.log(error.response);
        console.log("server responded");
    } else if (error.request) {
        console.log("network error");
    } else {
        console.log(error);
    }
});
// With Fetch
fetch(url)
 .then((response) => response.json())
 .then((data) => console.log(data))
 .catch((error) => console.log(error));

// With Axios
axios.get(url)
 .then((response) => console.log(response))
 .catch((error) => console.log(error));
//HTML
 <img name="slide" />
    

//Javascript
let i = 0; // Start Point
let images = []; // Images Array
let time = 3000; // Time Between Switch

// Change Image
function changeImg() {
  // Image List
  images[i] = `img-${i}.jpg`;
  images.length = 4;

  document.slide.src = images[i];
  // Check If Index Is Under Max
  if (i < images.length - 1) {
    // Add 1 to Index
    i++;
  } else {
    // Reset Back To O
    i = 0;
  }

  // Run function every x seconds
  setTimeout('changeImg()', time);
}

// Run function when page loads
window.onload = changeImg;
//HTML
<div class="form__block">
     <label for="customer-password">Password</label>
     <div class="form__input">
        <input type="password"
               name="customer-password"
               id="customer-password"
               min="6"/>
      </div>
      <div class="customer-password-icon">
         <i aria-label="click to show password" class="fa-solid fa-eye"></i>
         <i aria-label="click to hide password" class="fa-solid fa-eye-slash"></i>
 	  </div>
</div>



//Show hide Password
const togglePassword = () => {
  const passwordInput = document.getElementById('customer-password');
  const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
  passwordInput.setAttribute('type', type);

  if (type === 'text') {
    eyeIcon.style.display = 'block';
    eyeHideIcon.style.display = 'none';
  } else {
    eyeIcon.style.display = 'none';
    eyeHideIcon.style.display = 'block';
  }
};
$( document ).on( 'click', '.copy_registry_link', function(e) {
    e.preventDefault();
    this.select();
    this.setSelectionRange(0, 99999); /* For mobile devices */

    /* Copy the text inside the text field */
    navigator.clipboard.writeText(this.value);
    alert("Gift Registry link copied.");
} );
//This script generates a list for de-duplication task (for CMDB_CI maintenance)
//Note, the code below will only look at those CIs where Class = Switchport
//and NOT include State = Retired (Retired CIs are by-passed.) 

gs.log(getDuplicates('dscy_switchport', 'name'));  // look for CIs with class = Switchport)

function getDuplicates(tablename, val) {
    var dupRecords = [];
    var rtnNameArry = [];
    var count = 0;

    var gaDupCheck = new GlideAggregate(tablename);
    gaDupCheck.addEncodedQuery('sys_class_name=dscy_switchport^install_status!=7^ORinstall_status=NULL'); //Class is Switchport and not Retired
    gaDupCheck.addAggregate('COUNT', val);
    gaDupCheck.addNotNullQuery(val);
    gaDupCheck.groupBy(val);
    gaDupCheck.addHaving('COUNT', '>', 1);
    gaDupCheck.query();
    while (gaDupCheck.next()) {
        var rtnName = gaDupCheck[val].toString();
        rtnNameArry.push(rtnName);
    }

    for (var i = 0; i < rtnNameArry.length; i++) {

        var gr = new GlideRecord("dscy_switchport");
        gr.addQuery('name', rtnNameArry[i]);

        gr.query();
        while (gr.next()) {
            count++;
            dupRecords.push("" + gr.sys_id);
            gs.log(gr.name + " - " + gr.sys_class_name.getDisplayValue() + " - " + gr.sys_id);
        }
        gs.log(dupRecords.toString());

        var taskSysId = new CMDBDuplicateTaskUtils().createDuplicateTask(dupRecords.toString());
        gs.log(taskSysId);

//*** Un-comment the block below, to create task records for De-duplication		
/*========================================================================
        var remTsk = new GlideRecord("reconcile_duplicate_task");
        remTsk.addEncodedQuery("sys_created_onONToday@javascript:gs.beginningOfToday()@javascript:gs.endOfToday()");
        remTsk.addQuery('sys_id', taskSysId);
        remTsk.query();
        if (remTsk.next()) {
            remTsk.assignment_group = "ddf02f53dbb83b806a4d591e5e96190e";
            remTsk.update();
            gs.log("De-Duplication Task: " + remTsk.number + " is now assigned to the Telus CMDB Team. ");
       }
===========================================================================*/
        dupRecords.length = 0;
    }

    gs.log("Number of duplicate CIs found: " + rtnNameArry.length);
    gs.log("Total number of Affected CIs found: " + count);
    return rtnNameArry;
}
    getMasterName(index) { 
      const types = new Set()
			this.request.details.buildings[index].details.usages?.forEach((usage) => types.add(usage?.masterUsageId))
      const data = Array.from(types).map((masterUsageId) => {
        debugger
				const filterdData = this?.masterUsages.filter((i) => i?.id == masterUsageId)
				return {
					masterUsageId: masterUsageId,
					name: filterdData[0]?.name,
					// items: filterdData,
				}
			})
			return data

    },
var CalAge = Class.create();
CalAge.prototype = Object.extendsObject(global.AbstractAjaxProcessor, {
	generateAge: function() {
		var dob = this.getParameter('sysparam_id');
		var today = new GlideDateTime();
		var todayYear = today.getYearLocalTime();
		var bday = new GlideDateTime(dob.toString());
		var bdayYear = bday.getYearLocalTime();
		var age =todayYear - bdayYear;
		return age;
	},
	type: 'CalAge'
});

/** To run tyhe above code type the following code in Background script and run
var dob1 = new CalAge.generateAge('23-07-2017');
gs.print(dob1);
**/
  
  
  
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.5.+'
    }
}
apply plugin: 'android'

dependencies {
    compile files('libs/commons-io-2.4.jar')
    compile project(':libraries:actionbarsherlock')
}

android {
    compileSdkVersion 17
    buildToolsVersion "17.0.0"

    defaultConfig {
        minSdkVersion 8
        targetSdkVersion 16
    }
}
var input = document.createElement("input");

input.setAttribute("type", "hidden");

input.setAttribute("name", "name_you_want");

input.setAttribute("value", "value_you_want");

//append to form element that you want .
document.getElementById("chells").appendChild(input);
const stringTrim = (string, maxLength) => {
  if (!string) return string;
  if (maxLength < 1) return string;
  if (string.length <= maxLength) return string;
  if (maxLength === 1) return string.substring(0,1) + '...';

  const midpoint = Math.ceil(string.length / 2);
  const toRemove = string.length - maxLength;
  const leftStrip = Math.ceil(toRemove/2);
  const rightStrip = toRemove - leftStrip;
  return `${string.substring(0, midpoint - leftStrip)}...${string.substring(midpoint + rightStrip)}`
}
wp_register_script( 'jQuery', 'https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js', null, null, true );
wp_enqueue_script('jQuery');
wp_register_style( 'Font_Awesome', 'https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css' );
wp_enqueue_style('Font_Awesome');
const myObject = {
  property: 'Value!',
  otherProperty: 77,
  "obnoxious property": function() {
    // do stuff!
 }
}
<sl-drawer label="Drawer" class="drawer-scrolling">
  <div style="height: 150vh; border: dashed 2px var(--sl-color-neutral-200); padding: 0 1rem;">
    <p>Scroll down and give it a try! 👇</p>
  </div>
  <sl-button slot="footer" variant="primary">Close</sl-button>
</sl-drawer>

<sl-button>Open Drawer</sl-button>

<script>
  const drawer = document.querySelector('.drawer-scrolling');
  const openButton = drawer.nextElementSibling;
  const closeButton = drawer.querySelector('sl-button[variant="primary"]');

  openButton.addEventListener('click', () => drawer.show());
  closeButton.addEventListener('click', () => drawer.hide());
</script>
.center-container{
position: absolute;
left: 50%;
top: 50%;
transform: translate (-50%, -50%);
}



center-container {
display: grid;
place-items: center;
}


.center-container {
display: flex;
justify-content: center;
align-items: center;
 
}
const toSnakeCase = str =>
  str &&
  str
    .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
    .map(x => x.toLowerCase())
    .join('_');

console.log(toSnakeCase('camelCase'));
console.log(toSnakeCase('some text'));
console.log(toSnakeCase('some-mixed_string With spaces_underscores-and-hyphens'));
console.log(toSnakeCase('AllThe-small Things'));
console.log(toSnakeCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML'));
var x = 12345; 
console.log(typeof x) // number
x = 'string'; 
console.log(typeof x) // string
x = { key: 'value' };
console.log(typeof x) // object
// Reference: http://www.html5rocks.com/en/tutorials/speed/animations/

let lastKnownScrollPosition = 0;
let ticking = false;

function doSomething(scrollPos) {
  // Do something with the scroll position
}

document.addEventListener('scroll', function(e) {
  lastKnownScrollPosition = window.scrollY;

  if (!ticking) {
    window.requestAnimationFrame(function() {
      doSomething(lastKnownScrollPosition);
      ticking = false;
    });

    ticking = true;
  }
});