Snippets Collections
// SHA

function sha256(plain: any) {
  // returns promise ArrayBuffer
  const encoder = new TextEncoder();
  const data = encoder.encode(plain);
  return window.crypto.subtle.digest('SHA-256', data);
}

function base64urlencode(a: any) {
  // Convert the ArrayBuffer to string using Uint8 array.
  // btoa takes chars from 0-255 and base64 encodes.
  // Then convert the base64 encoded to base64url encoded.
  // (replace + with -, replace / with _, trim trailing =)
  // @ts-ignore
  return btoa(String.fromCharCode.apply(null, new Uint8Array(a)))
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=+$/, '');
}

export async function pkceChallengeFromVerifier(v: any) {
  const hashed = await sha256(v);
  return base64urlencode(hashed);
}
/* note sure wy but Google fonts do not display on some Mac.
Here is your solution. Just add "!important" and you will be good to go */



        h1 {
            font-family: 'Montserrat', serif !important;
        }
var express = require('express');
var app = express();

app.get('/', function (req, res) {
    res.send('<b>My</b> first express http server');
});

// 1) Add a route that answers to all request types
app.route('/article')
.get(function(req, res) {
    res.send('Get the article');
})
.post(function(req, res) {
    res.send('Add an article');
})
.put(function(req, res) {
    res.send('Update the article');
});

// 2) Use a wildcard for a route
// answers to : theANYman, thebatman, thesuperman
app.get('/the*man', function(req, res) {
    res.send('the*man');
});

// 3) Use regular expressions in routes
// responds to : batmobile, batwing, batcave, batarang
app.get(/bat/, function(req, res) {
    res.send('/bat/');
});

app.use(function(req, res, next) {
    res.status(404).send("Sorry, that route doesn't exist. Have a nice day :)");
});

app.listen(3000, function () {
    console.log('Example app listening on port 3000.');
});
// will need a HTML page with "root"

import React from "react";
import ReactDOM from "react-dom";

const date = new Date();
const currentTime = date.getHours();
const currentMins = date.getMinutes();

let greeting;

const customSyle = {
  color: ""
};

if (currentTime < 12) {
  greeting = "good morning";
  customSyle.color = "red";
} else if (currentTime < 18) {
  greeting = "good evening";
  customSyle.color = "blue";
} else {
  greeting = "good night";
  customSyle.color = "puprle";
}

ReactDOM.render(
  <h1 className="heading" style={customSyle}>
    {currentTime + ":" + currentMins + " " + greeting}
  </h1>,

  document.getElementById("root")
);
(() => {
let d = new Date()
let year = d.getFullYear().toString()
let month = d.getMonth() < 9 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1
let date = d.getDate() < 10 ? '0' + d.getDate() : d.getDate().toString()
let hour = d.getHours() < 10 ? '0' + d.getHours() : d.getHours().toString()
let minutes = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes().toString()
let seconds = d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds().toString()
let day
switch (d.getDay()) {
  case 0:
      day = "sunday"
  break
   case 1:
     day = "monday"
   break
   case 2:
     day = "tuesday"
     break
   case 3:
     day = "wednesday"
     break
   case 4:
     day = "thursday"
     break
   case 5:
     day = "friday"
     break
   case 6:
     day = "saturday"
     break
    default:
    day = ''
  }
return {
  formattedDate: d.toLocaleString().split(", ")[0],
  formattedTime: d.toLocaleString().split(" ")[1],
  day,
  yyyy: year,
  mm: month,
  dd: date,
  hh: hour,
  mm: minutes,
  ss: seconds,
  timestamp:[year, month, date, hour, minutes].join(''),
  timestampA:[year, month, date, hour, minutes].join("-"),
  timestampB: `y${year}m${month}d${date}h${hour}m${minutes}s${seconds}`
}
})()

app.get('/:id/tracker.png', function(request, response, next) {
    var emailId = request.param.id;
    var buf = new Buffer([
        0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00,
        0x80, 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x2c,
        0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02,
        0x02, 0x44, 0x01, 0x00, 0x3b
    ]);
    response.set('Content-Type', 'image/png');
    response.end(buf, 'binary');
    db.findOne({ id: emailId }, function(error, email) {
        if(error) return next(error);
        app.emit('event:opened', email);
    });
});

app.on('event:opened', function(email) {
    console.log('Email was opened');
    console.log(email.to);
    console.log(email.subject);
});
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
// instead of
if (accessible) {
console.log(“It’s open!”);
}
// use
accessible && console.log(“It’s open!”);
const robotFactory = (model, mobile) => {
return {
model: model,
mobile: mobile,
beep(){
  console.log('Beep Boop');
}
}
};
// parameters and entered in an order, check robotFactory const.
const tinCan = robotFactory('P-500', true);
tinCan.beep();
console.log(tinCan);
const person = {
  _age: 37,
  set age(newAge){
    if (typeof newAge === 'number'){
      this._age = newAge;
    } else {
      console.log('You must assign a number to age');
    }
  }
};

/*
We can perform a check for what value is being assigned to this._age.
When we use the setter method, only values that are numbers will reassign this._age
There are different outputs depending on what values are used to reassign this._age.

*/
const robot = {
  _model: '1E78V2',
  _energyLevel: 100,
  get energyLevel(){
    if(typeof this._energyLevel === 'number') {
      return 'My current energy level is ' + this._energyLevel
    } else {
      return "System malfunction: cannot retrieve energy level"
    }
  }
};

console.log(robot.energyLevel);





/*
Getters can perform an action on the data when getting a property.
Getters can return different values using conditionals.
In a getter, we can access the properties of the calling object using this.
The functionality of our code is easier for other developers to understand.
*/
const example = {
  name: 'mark',
  color: 'red',
  giveDetails(){
    console.log(`${this.example} is a ${this.color} something.`)
  }
}
const user = {
name: "joe",
age: 32,
occupation: "Web Developer"

};

for (const [key, value] of Object.entries(user)) {
console.log(`${key} => ${value}`);
}
const example = {
  model: '1E78V2',
  energyLevel: 100,
provideInfo() {
return `I am ${this.model} and my current energy level is ${this.energyLevel}.`  
}
};
console.log(example.provideInfo());
const input = 'dude whats up yo';
const vowels = ['a', 'e', 'i', 'u', 'o'];
let resultArray = [];


for (let i=0; i< input.length; i++){
/* prints each item in array
console.log(input[i]);
 prints index of each item in array
console.log(i);
*/

for(let j=0; j<vowels.length; j++){
  if(input[i]===vowels[j]){
    if(input[i]==='e'){
      resultArray.push('ee')
    }
    else if (input[i]==='u'){
      resultArray.push('uu');
    }
    else{
      resultArray.push(input[i]);
    }
  }
}
}
console.log(resultArray.join('').toUpperCase());
const xArray = ["1' 2", "3", "4", "5"];

for (let i = 0; i < xArray.length; i++){
  console.log(xArray[i]);
  if (xArray[i] === '4'){
    break;
  }
}

console.log("Sample code");
//HMTL

<div class="container">

 <div id="a" class="box">Div A</div>
<div id="b" class="box">Div B</div>
<div id="c" class="box">Div C</div>
<div id="d" class="box">Div D</div>
<div id="e" class="box">Div E</div>
<div id="f" class="box">Div F</div>

</div>


//CSS
body {
  font-family: arial;
  font-weight: 600;
  color: white;
  font-size: 2em;
}
.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  padding: 10%;
  text-align: center;
  grid-gap: 40px;
}

.box {
   background-color: green;
   padding: 20px;
  
}

#a {


}

#a:hover {
     grid-column: 1 / 4;
     grid-row: 1/6;
}

#a:hover ~ #b {
    background: #ccc;
        grid-column: 4;
}

#a:hover ~ #c {
    background: #ccc;
        grid-column: 4;
}

#a:hover ~ #d {
    background: #ccc;
            grid-column: 4;

}

#a:hover ~ #e {
    background: #ccc;
            grid-column: 4;

}

#a:hover ~ #f {
    background: #ccc;
            grid-column: 4;

}

#b:hover {
     grid-column: 1 / 4;
     grid-row: 1/6;
}

#b:hover ~ #a {
    background: #ccc;
        grid-column: 4;
}

#b:hover ~ #c {
    background: #ccc;
        grid-column: 4;
}

#b:hover ~ #d {
    background: #ccc;
            grid-column: 4;

}

#b:hover ~ #e {
    background: #ccc;
            grid-column: 4;

}

#b:hover ~ #f {
    background: #ccc;
            grid-column: 4;

}
document.getElementsByTagName('video')[0].requestPictureInPicture();
 const ageSum = ages.reduce(function(total, age) {
   return total + age;
 }, 0);
 const sortedCompanies  = companies.sort(function(c1, c2) {
   if(c1.start > c2.start) {
     return 1;
   } else {
    return -1;
   }
 });

 const sortedCompanies = companies.sort((a, b) => (a.start > b.start ? 1 : -1));

// Sort ages
 const sortAges = ages.sort((a, b) => a - b);
 const companyNames = companies.map(function(company) {
   return company.name;
 });
    //? GETTER - GET All Technologies sorted by Date Modified
    allTechnologiesDateSorted(state) {
      return state.allTechnologies.sort((a,b) => (a.dateModified.split("-").join("") < b.dateModified.split("-").join("") ? 1 : -1));
    },
var Number = prompt("Insert number between 0 and 100");

 if (0<Number<50){
       console.log("Low value");
}else if(50<=Number<100){
       console.log("High value");
}else{
       console.log("not a valid number");
}
let nodeCounter = 1;

function addChild() {
    let p = document.createElement("p");
    p.setAttribute('class', 'pnode');
    p.innerHTML = `new node created #${nodeCounter}`;
    document.getElementById("div1").appendChild(p);
    nodeCounter++;
}
let nodeCounter = 1;

function addChild() {
    let p = document.createElement("p");
    p.setAttribute('class', 'pnode');
    p.innerHTML = `new node created #${nodeCounter}`;
    document.getElementById("div1").appendChild(p);
    nodeCounter++;
}
// Example Arrays
let filterArrayB = ['aa', 'ab', 'ac', 'ad', 'ae', 'af', 'ag']
let filterArrayA = ['aa', 'ab', 'ac', 'ae', 'af', 'ag']

// This only works if there is a 1 item difference 
compare = (a,b) => {
  let inBoth = []
  let missingItem = []
  a.forEach(item => {
    for (let i=0; i<b.length; i++){
      if (item == b[i]){
        inBoth.push(item) 
        if (i == b.length) return
      } 
      if (a.length < b.length) {
        b.forEach(item => {
          if (!a.includes(item)){
            missingItem = item
          }
        })
      } else {
          a.forEach(item => {
          if (!b.includes(item)){
            missingItem = item
          }
        })
      }
      
    }
  })
  return missingItem
}

compare(filterArrayA, filterArrayB)
import React from 'react';
import ReactDOM from 'react-dom';

class MyForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = { username: '' };
  }
  myChangeHandler = (event) => {
    this.setState({username: event.target.value});
  }
  render() {
    return (
      <form>
      <h1>Hello {this.state.username}</h1>
      <p>Enter your name:</p>
      <input
        type='text'
        onChange={this.myChangeHandler}
      />
      </form>
    );
  }
}

ReactDOM.render(<MyForm />, document.getElementById('root'));
    // Make a request for a user with a given ID
  axios.get('/user?ID=12345')
    .then(function (response) {
      // handle success
      console.log(response);
    })
    .catch(function (error) {
      // handle error
      console.log(error);
    })
     .then(function () {
      // always executed
    }); 


 // Optionally the request above could also be done as
  axios.get('/user', {
      params: {
        ID: 12345
      }
    })
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    })
    .then(function () {
      // always executed
    }); 

  // Want to use async/await? Add the `async` keyword to your outer function/method.
   async function getUser() {
    try {
      const response = await axios.get('/user?ID=12345');
      console.log(response);
    } catch (error) {
      console.error(error);
    }
  } 


document.onmouseover = function(event){
    var elem = event.target;

    if (elem.id !== 'menu4IMDBlink' && elem.parentNode.id !== "menu4IMDBlink" && document.getElementById("menu4IMDBlink")) {
        document.getElementById("menu4IMDBlink").remove();
    }

    if ((elem.tagName == 'A' || elem.parentNode.tagName == 'A') && elem.className !== "menu_link") {
        var elemHref = elem.tagName == 'A' ?  elem.href : elem.parentNode.href;
        var matchArr = elemHref.match(/\/tt(\d+)[\/\?]/);

        if (matchArr && matchArr[1] && !document.getElementById("menu4IMDBlink")) {
            var menuDiv = document.createElement("div");
            menuDiv.id = "menu4IMDBlink";
            menuDiv.style.zIndex = 6999;
            menuDiv.style.position = "fixed";
            menuDiv.style.backgroundColor = "#EEE";

            var rect = elem.getBoundingClientRect();
            var menuTop = rect.top + rect.height;
            menuDiv.style.top = menuTop + "px"
            menuDiv.style.left = rect.left + "px";
            
            var a = document.createElement("a");
            a.href = "https://www.imdb.com/title/tt" + matchArr[1] + "/episodes?season=-1"
            a.target = "_blank";
            a.innerText = "episodes";
            a.className = "menu_link";
            menuDiv.appendChild(a);
            
            menuDiv.innerHTML += "&nbsp;";
            a = document.createElement("a");
            a.href = "https://opensubtitles.org/uk/search2?IMDBID=" + matchArr[1];
            a.target = "_blank";
            a.innerText = "subs";
            a.className = "menu_link";
            menuDiv.appendChild(a);
            
            menuDiv.innerHTML += "&nbsp;";
            a = document.createElement("a");
            a.href = "https://rarbgmirror.org/torrents.php?imdb=tt" + matchArr[1];
            a.target = "_blank";
            a.innerText = "rarbg";
            a.className = "menu_link";
            menuDiv.appendChild(a);

            document.body.appendChild(menuDiv);
        }
    }
}
// in gastby-browser.js
exports.shouldUpdateScroll = ({
  routerProps: { location },
  getSavedScrollPosition,
}) => {
  const { pathname } = location
  // list of routes for the scroll-to-top-hook
  const scrollToTopRoutes = [`/privacy-policy`, `/page-2`]
  // if the new route is part of the list above, scroll to top (0, 0)
  if (scrollToTopRoutes.indexOf(pathname) !== -1) {
    window.scrollTo(0, 0)
  }

  return false
}
JSON.stringify(obj, null, “\t”);
const hello = (name = mandatory()) => { return console.log(`Hello: ${name}!`)};
hello(’Rick’);
const a = '';
const b = "";
const c = null;
const d = undefined;
const e = NaN;
const f = false;
const g = 1;

console.log(!!a); 
console.log(!!b);
console.log(!!c);
console.log(!!d);
console.log(!!e);
console.log(!!f);
console.log(!!g);
let names= ['Evelyn', 'Harper', 'Jackson', 'Avery', 'Jack', 'Eleanor', 'Carter'];
const chooseName = () =>{
	let randomName = names[Math.floor(Math.random() * names.length)];
	return randomName;
}
console.log('Random name:', chooseName(names));
const removeDuplicatesFromArray = arr => [...new Set(arr)];
removeDuplicatesFromArray([1,1,2,3,4,4,4,true,true,'foo','foo']);
const fetch_retry = async (url, options, n) => {
    try {
       response = await fetch(url, options);
       if (response === 200) {
         return response;
       }else{
         throw new Error(response)
       }
    } catch(err) {
      //.1      
      if (n === 1) throw err;
   
      //2.
      response = await fetch_retry(url, options, n - 1);
      if (response === 200) {
         return response;
      }else{
         throw new Error(response)
      }
    }
};
let response = fetch_retry("/someUrl/json", options, 10);
const fetch_retry = async (url, options, n) => {
    let error;
    for (let i = 0; i < n; i++) {
        
        try {
            response = await fetch(url, options);
            if (response === 200) {
               return response;
            }else{
               throw new Error(response)
            }
        } catch (err) {
           error = err;     
           //1.           
           if (i + 1 === n) throw err;
        }
    }
    throw error;
};
let response = fetch_retry("/someUrl/json", options, 10);
const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion)');

const reduceMotionChanges = () => {
  if (pefersReducedMotion.matches) {
    // Handle reduced motion
  }
}

prefersReducedMotion.addListener(reduceMotionChanges)
// NOTE - See Vue Date Filter for best example - this is 'Vue Date Filter 2'
// which may be helpful in a different way
// the other one accounts for time zone

import DateFilter from './filters/date'
// require('firebase/firestore')
// import { firestorePlugin } from 'vuefire';
// import { db } from './components/fbConfig.js';

Vue.config.productionTip = false;

export const port = () => '3000';
let app = '';

Vue.use(VueRouter);
Vue.use(store);
Vue.filter('date', DateFilter)
export default (value) => {
  const date = new Date(value)
  if (!value) return ""
  else return date.toLocaleString(['en-US'], {month: 'short', day: '2-digit', year: 'numeric'})

  // THE DATE MAY BE OFF DUE TO TIME ZONES - USE toLocaleDateString and add a timezone to prevent that
  // as long as time isn't being used, this is the better option:
  return date.toLocaleDateString(['en-US'], {month: 'short', day: '2-digit', year: 'numeric', timeZone: 'UTC'})

}
function isValid(str){
 return !/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
export const addParensToFormatAreaCode = (phone?: string) => {
  const phoneParts = phone?.split("-");
  if (phoneParts !== undefined && phoneParts[0] !== "") {
    const phoneJoin: string = `(${phoneParts[0]}) ${phoneParts[1]}-${phoneParts[2]}`;
    return phoneJoin;
  }
  return strings.DEFAULT;
};
<!DOCTYPE html>
<html>
<body>
​
<h2>JavaScript Array Methods</h2> 
​
<h2>shift()</h2>
​
<p>The shift() method removes the first element of an array (and "shifts" all other elements to the left):</p>
​
<p id="demo1"></p>
<p id="demo2"></p>
​
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
fruits.shift();
document.getElementById("demo2").innerHTML = fruits;
</script>
​
</body>
</html>
​
<!DOCTYPE html>
<html>
<body>
​
<h2>JavaScript Array Methods</h2> 
​
<h2>join()</h2>
​
<p>The join() method joins array elements into a string.</p>
​
<p>It this example we have used " * " as a separator between the elements:</p>
​
<p id="demo"></p>
​
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
</script>
​
</body>
</html>
​
<!DOCTYPE html>
<html>
<body>
​
<h2>JavaScript Expressions</h2>
​
<p>Expressions compute to values.</p>
​
<p id="demo"></p>
​
<script>
document.getElementById("demo").innerHTML = 5 * 10;
</script>
​
</body>
</html>
​
<!DOCTYPE html>
<html>
<body>
​
<h2>JavaScript Arrays</h2>
​
<p id="demo"></p>
​
<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
​
</body>
</html>
​
​
<!DOCTYPE html>
<html>
<body>
​
<h2>JavaScript Numbers</h2>
​
<p>If you add two numeric strings, the result will be a concatenated string:</p>
​
<p id="demo"></p>
​
<script>
var x = "10";
var y = "20";
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>
​
</body>
</html>
​
​
​
<!DOCTYPE html>
<html>
<body>
​
<h2>JavaScript Numbers</h2>
​
<p>If you add two numbers, the result will be a number:</p>
​
<p id="demo"></p>
​
<script>
var x = 10;
var y = 20;
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>
​
</body>
</html>
​
​
​
<!DOCTYPE html>
<html>
<body>
​
<h2>JavaScript String Properties</h2>
​
<p>The length property returns the length of a string:</p>
​
<p id="demo"></p>
​
<script>
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
document.getElementById("demo").innerHTML = sln;
</script>
​
</body>
</html>
​
​
<!DOCTYPE html>
<html>
<body>
​
<h2>JavaScript Strings</h2>
​
<p id="demo"></p>
​
<script>
var x = "John Doe";  // String written inside quotes
document.getElementById("demo").innerHTML = x;
</script>
​
</body>
</html>
​
<!DOCTYPE html>
<html>
<body>
​
<button onclick="document.getElementById('demo').innerHTML=Date()">The time is?</button>
​
<p id="demo"></p>
​
</body>
</html>
​
const StyledMotionComponent = styled(motion.div)`

  /* ----- styles go here ----- */

`
 {"countries":[
    {
        "name":"USA",

        "grandfathers":[
            {
                "gFName":"Steve",
                "grandfathersKid":[
                    {
                        "gFKName": "Linda",
                        "kid": [{
                            "name": "Steve JR", 
                            "friends": [{
                                "name": "Kriss|John|Martin|Steven"
                            }]
                        }
                        ]
                    }

                ]
            }
        ]
    }
]}
function countdown(i) {
    console.log(i)  if (i <= 1) {  // base case
        return;
    } else {     // recursive case
        countdown(i - 1);
    }
}

countdown(5);    // This is the initial call to the function.
<!DOCTYPE html>
<html>
<body>
​
<h2>JavaScript Functions</h2>
​
<p>This example calls a function which performs a calculation and returns the result:</p>
​
<p id="demo"></p>
​
<script>
var x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;
​
function myFunction(a, b) {
  return a * b;
}
</script>
​
</body>
</html>
​
<!DOCTYPE html>
<html>
<body>
​
<h2>The += Operator</h2>
​
<p id="demo"></p>
​
<script>
var x = 10;
x += 5;
document.getElementById("demo").innerHTML = x;
</script>
​
</body>
</html>
​
<!DOCTYPE html>
<html>
<body>
​
<h2>JavaScript Operators</h2>
​
<p>x = 5, y = 2, calculate z = x + y, and display z:</p>
​
<p id="demo"></p>
​
<script>
var x = 5;
var y = 2;
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>
​
</body>
</html>
​
<!DOCTYPE html>
<html>
<body>
​
<h1 id="myH"></h1>
<p id="myP"></p>
​
<script>
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
*/
document.getElementById("myH").innerHTML = "JavaScript Comments";
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>
​
</body>
</html>
​
<!DOCTYPE html>
<html>
<body>
​
<h2>JavaScript Comments</h2>
​
<p id="demo"></p>
​
<script>
var x = 5;    // Declare x, give it the value of 5
var y = x + 2;  // Declare y, give it the value of x + 2 
// Write y to demo:
document.getElementById("demo").innerHTML = y;
</script>
​
​
</body>
</html>
​
var clearTable = function(tableId) {
  var tableToClear = document.getElementById(tableId);
  while (tableToClear.rows.length > 1) {
    tableToClear.deleteRow(1);
  }
}
var buildTable = function(tableId, tData) {
  var tableRef = document.getElementById(tableId);
  tData.forEach(dataObj => {
    var row = tableRef.insertRow(1);
    Object.values(dataObj).forEach(val => {
      var dataColumn = document.createElement("td");
      dataColumn.innerHTML = val;
      row.appendChild(dataColumn);
    });
  });
}
`Pomoci zpětné uvozovky vytvoříte speciální řetězec, který lze psát na více 
 řádků a dají se do něj vkládat výrazy ${ 1+2 }, proměnné ${ x+y }, pole ${ seznam[0] },
 objekty ${ uzivatelske.jmeno } a dokonce ihned volané funkce ${ function() { return x+y; }() } 
 nebo metody ${ "sidon".toUpperCase() }.`
function pow(x, n) {
  return (n == 1) ? x : (x * pow(x, n - 1));
}
      {arr.map(({ what ever you want to get from map }) => (
        <div>
			code goes here to display through html elements
        </div>
      ))}
const myObject= {
  'Age': '25',
  'Gender': 'Male',
  'Nationality': 'Australian'
};

const myMap = new Map(Object.entries(myObject)); //object to map
const anotherObject = Object.fromEntries(myMap) // map to object
const collectionName = 'databases' // this is my collection name
const ref = firebase.firestore().collection(collectionName);
ref.onSnapshot((snapshot) => {
  snapshot.forEach((doc) => {
    const data = doc.data();
    // ...
  });
});
alert( Boolean("0") ); // true
alert( Boolean(" ") ); // spaces, also true (any non-empty string is true)
<!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
	
    <!-- U Chen CSS -->
	<link rel="stylesheet" href="homeStyle.css">
	
	<!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
	
	<!-- Font Awesome Icons -->
	<script src="https://kit.fontawesome.com/a076d05399.js"></script>
add_action('wp_head', 'add_gtm');

function add_gtm() {
	?>
	{{INSERT SCRIPT HERE}}
<?
}

add_action( 'wp_body_open', 'add_gtm_no_script' );

function add_gtm_no_script() {
	?>
	{{INSERT SCRIPT HERE}}
<?
}
<button type="submit" id="customers_filter" onclick="checkWhetherTheTableContainsSearchResults()"
                                class="btn filter-button d-inline-block ml-3">
                                Filter
                            </button>
                            
<input id="search-hidden-input" hidden name="searchValue">

<script>
function checkWhetherTheTableContainsSearchResults() {
        let search = location.search.substring(1)
            searchInputElement = document.getElementById('search-hidden-input');
        
        if(search != '') {
            searchInputElement.setAttribute('value', search);
        }
    }
</script>
    
// If the filter is to work on search results, the original search parameter has to be passed into the request array.
        // Thus, the request array will return more than one parameter 
        // AND
        // one of the parameters will be searchValue
        // WHICH
        // will contain the entire search parameter (key + value)

        if ((count($request->all()) > 1) && (isset($request->searchValue))) {
            if (strpos($request->searchValue, '=')) {
                $string = $request->searchValue;
                $array = explode('=', $string);
                $request->searchValue = $array[1];
            }
        }
<div (mouseover)="changeText=true" (mouseout)="changeText=false">
  <span *ngIf="!changeText">Hide</span>
  <span *ngIf="changeText">Show</span>
</div>
(?:\d\s*)?[A-Z]?[a-z]+\s*\d+(?:[:-]\d+)?(?:\s*-\s*\d+)?(?::\d+|(?:\s*[A-Z]?[a-z]+\s*\d+:\d+))?
numbers.forEach((number, index, array) => {
    console.log(array);
});

numbers.forEach((number, index) => {
    console.log('Index: ' + index + ' Value: ' + number);
});
numbers.forEach(function(number) {
    console.log(number);
});

numbers.forEach(function() {
    // code
});
const str = 'To be, or not to be, that is the question.' 

console.log(str.includes('To be'))        // true
console.log(str.includes('question'))     // true
console.log(str.includes('nonexistent'))  // false
console.log(str.includes('To be', 1))     // false
console.log(str.includes('TO BE'))        // false
console.log(str.includes(''))             // true
function sayHi(phrase, who) {
  alert( phrase + ', ' + who );
}

setTimeout(sayHi, 1000, "Hello", "John"); // Hello, John
var tables = [
    { "art":"A","count":"0","name":"name1","ean":"802.0079.127","marker":"null","stammkost":"A","tablename":"IWEO_IWBB_01062015" },
    { "art":"A","count":"0","name":"2","ean":"657.7406.559","marker":"null","stammkost":"A","tablename":"IWEO_IWBB_02062015" }
];

tables.forEach(function(table) {
    var tableName = table.name;
    console.log(tableName);
});
function tick() {
  //get the mins of the current time
  var mins = new Date().getMinutes();
  if (mins == "00") {
    alert('Do stuff');
  }
  console.log('Tick ' + mins);
}

setInterval(tick, 1000);
console.log("entering try-catch statement");

try {
  console.log("entering try block");
  throw "thrown message";
  console.log("this message is never seen");
}
catch (e) {
  console.log("entering catch block");
  console.log(e);
  console.log("leaving catch block");
}
finally {
  console.log("entering and leaving the finally block");
}

console.log("leaving try-catch statement");
fruits.forEach(function(item, index, array) {
  console.log(item, index)
})
// Apple 0
// Banana 1
if (array.includes(value) === false) array.push(value);
function intDiv(a,b)
{
var result = a/b;
if(result>=0)
return Math.floor(result);
else
return Math.ceil(result);
}

const num1 = [1, 2, 3];
const num2 = [4, 5, 6];
const num3 = [7, 8, 9];

const numbers = num1.concat(num2, num3);

console.log(numbers); 
// results in [1, 2, 3, 4, 5, 6, 7, 8, 9]
const letters = ['a', 'b', 'c'];
const numbers = [1, 2, 3];

letters.concat(numbers);
// result in ['a', 'b', 'c', 1, 2, 3]
function example(…) {
    return condition1 ? value1
         : condition2 ? value2
         : condition3 ? value3
         : value4;
}

// Equivalent to:

function example(…) {
    if (condition1) { return value1; }
    else if (condition2) { return value2; }
    else if (condition3) { return value3; }
    else { return value4; }
}
// BASH
mkdir src
mkdir build
touch src/index.ts
touch .gitignore
touch README.md
tsc -y
npm init -y
npm install nodemon concurrently @types/express --save-dev

// package.json
...
"scripts": {
  "start:build": "tsc -w",
  "start:run": "nodemon ./build/index.js",
  "start": "concurrently npm:start:*"
},
...

// tsconfig.json
...
"outDir": "./build",
"rootDir": "./src",
...

// .gitignore
node_modules
*.env

// README.md
### Start
```bash
npm run start
```

// src/index.ts
import express from 'express'
const port = 3000
const app = express()

console.log("Hello, World!!!")

logSomething("This is a string that I'm logging")

app.listen(port, () => {
  console.log(`Listening on port ${port}`)
})
//capitalize only the first letter of the string. 
function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}
//capitalize all words of a string. 
function capitalizeWords(string) {
    return string.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
};
var array = [267, 306, 108];
var largest = Math.max.apply(Math, array); // 306
var date, daytoset; // given: a Date object and a integer representing the week day

var currentDay = date.getDay();
var distance = daytoset - currentDay;
date.setDate(date.getDate() + distance);
let rand = Math.random()
rand < 0.5 ? gender = 0 : gender = 1
this.name = `${gender ? '👩‍💼' : '👨‍💼'} ${faker.name.firstName(gender)} ${faker.name.lastName(gender)}`
import * as Yup from 'yup';

validationSchema: Yup.object({
  password: Yup.string().required('Password is required'),
  passwordConfirmation: Yup.string()
     .oneOf([Yup.ref('password'), null], 'Passwords must match')
});
const fs = require('fs');
const path = require('path');
const dirPath = path.join(__dirname, '/pictures');

fs.mkdirSync(dirPath);
const bookModule = (function() {
  // private
  let title = ‘JavaScript’;
  let price = 15;
  // public
  return {
    printTitle: function () {
      console.log(title);
    }
  }
})();
bookModule.printTitle(); // JavaScript
const utils = (function () {
  let instance;
  
  function initialize() {
    return {
      sum: function (a, b) {
        return a + b;
      }
    };
  }
  return {
    getInstance: function () {
      if (!instance) {
        instance = initialize();
      }
      return instance;
    }
  };
})();
let sum = utils.getInstance().sum(3, 5); // 8
function Book(title, price) {
  this.title = title;
  this.price = price;
  this.printTitle = () => console.log(this.title);
}
function BookPrototype(prototype) {
  this.prototype = prototype;
  this.clone = () => {
    let book = new Book();
    book.title = prototype.title;
    book.price = prototype.price;
    
    return book;
  };
}
let sampleBook = new Book(‘JavaScript’, 15);
let prototype = new BookPrototype(sampleBook);
let book = prototype.clone();
book.printTitle();
// Using {} to create empty objects:
let person = {};
// Using Object() to create empty objects:
let person = new Object();
// Using function constructor:
function Person(name, age) {
  this.name = name;
  this.age = age;
  this.showName = () => console.log(this.name);
}
let person = new Person(‘Amy’, 28);
person.showName();
function getBook(bookId) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      let book = {
        title: ‘JavaScript’,
        authorId: ‘123’
      }
    
      resolve(book);
    }, 500);
  });
}
function getAuthor(authorId) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      let author = {
        name: ‘Amy’,
        age: 28
      }
      resolve(author);
    }, 500);
  });
}
async function fetchData() {
  let book = await getBook(2020);
  let author = await getAuthor(book.authorId);
  console.log(author)
}
fetchData(); // { name: ‘Amy’, age: 28 }
const copyToClipboard = str => {
  const el = document.createElement('textarea');
  el.value = str;
  el.setAttribute('readonly', '');
  el.style.position = 'absolute';
  el.style.left = '-9999px';
  document.body.appendChild(el);
  const selected =
    document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
  if (selected) {
    document.getSelection().removeAllRanges();
    document.getSelection().addRange(selected);
  }
};

// Example
copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard.
const getURLParameters = url =>
  (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
    (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
    {}
  );

// Examples
getURLParameters('http://url.com/page?n=Adam&s=Smith'); // {n: 'Adam', s: 'Smith'}
getURLParameters('google.com'); // {}
const detectDeviceType = () =>
  /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
    ? 'Mobile'
    : 'Desktop';

// Example
detectDeviceType(); // "Mobile" or "Desktop"
const scrollToTop = () => {
  const c = document.documentElement.scrollTop || document.body.scrollTop;
  if (c > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, c - c / 8);
  }
};

// Example
scrollToTop();
const getScrollPosition = (el = window) => ({
  x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
  y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});

// Example
getScrollPosition(); // {x: 0, y: 200}
document.querySelectorAll('body a').forEach((val) => {
  let linkCheck = new RegExp('/' + window.location.host + '/')
  if (!linkCheck.test(val.href)) {
    val.setAttribute('target', '_blank')
    val.setAttribute('rel', 'noreferrer noopener')
  }
})


//Replace 'body a' with desired selector
// filterProperty i.e. 'id' or 'name'
function GetDuplicates(array, filterProperty) {
	//lookup with our intended filter to get the duplicates by a given property
    const lookup = array.reduce((a, e) => {
        a[e.filterProperty] = ++a[e.filterProperty] || 0;
        return a;
    }, {});
    
    let duplicates = array.filter(e => lookup[e.filterProperty]);
    
    return duplicates;
}
// filterProperty i.e. 'id' or 'name'
function GetUniqueItems(array, filterProperty) {
	return array
    .map(e => e['filterProperty'])
    .map((e, i, final) => final.indexOf(e) === i && i)
    .filter(obj=> array[obj])
    .map(e => array[e]);
}
    <Router>
        <div className="app">
            <GlobalContextProvider>
                <Header />
                <Switch>
                    <Route path="/CodeSystem" component={PageCodeSystem} />
                    <Route path="/ValueSet" component={PageValueSet} />
                    <Route path="/RefSets" component={PageRefSets} />
                    <Route path="/" exact component={HomePage} />
                </Switch>
            </GlobalContextProvider>
        </div>
    </Router>
var points = [40, 100, 1, 5, 25, 10];
points.sort((a,b) => a-b)
import { useNetInfo } from '@react-native-community/netinfo';

const useAppNetworkInfo = () => {
  const netInfo = useNetInfo();
  const count = useRef(0);
  const isConnected = useRef(false);
  useEffect(() => {
    if (count.current > -1) {
      if (netInfo?.isConnected && netInfo?.isInternetReachable) {
        if (!isConnected.current) {
          if (count.current > 2) {
            Toast.success(i18next.t('global.onlineAlert', 10));
          }
        }
        const socket = GlobalLib.SocketClient.get();
        if (socket && typeof socket.open === 'function') {
          socket.open();
        }
        isConnected.current = true;
      } else {
        if (isConnected.current) {
          Toast.offline(i18next.t('global.offlineAlert', 10));
        }
        isConnected.current = false;
      }
    }
    count.current = count.current + 1;
  }, [netInfo]);
};
import { useEffect, useRef } from 'react';
import { useSelector } from 'react-redux';

const useAppSocket = () => {
  const token = useSelector(selectAccessToken());
  const user = useSelector(selectUser());
  const { set: setChatAccount } = useSharedValue(
    AppConstants.sharedValueKey.CHAT_ACCOUNT,
    {},
  );
  const socket = useRef(null);
  useEffect(() => {
    if (user && token) {
      socket.current = new SocketClient({
        userId: user.id,
        userIdentityName: user.identityName,
        token: token,
        onSocketError: () => {},
        onChatInfo: setChatAccount,
      });
      GlobalLib.SocketClient.set(socket.current);
    }
  }, [token, user, setChatAccount]);

  return {
    get: GlobalLib.SocketClient.get,
    socket,
  };
};
import { useCallback, useEffect } from 'react';
import { useDispatch, useSelector, useStore } from 'react-redux';
import { combineReducers } from 'redux';

// add to store object
// const reducerMap = {
// };
// store.reducerMap = reducerMap;
//


const useSharedValue = (key, defaultValue) => {
  const reducer = useCallback(
    (state = defaultValue, action) => {
      switch (action.type) {
        case `SHARED_VALUE_ACTION_KEY/${key}`:
          return action.payload.value;

        default:
          return state;
      }
    },
    [key, defaultValue],
  );
  const action = useCallback(
    value => ({
      type: `SHARED_VALUE_ACTION_KEY/${key}`,
      payload: { value },
    }),
    [key],
  );
  const selector = useCallback(() => state => state[key] || defaultValue, [
    defaultValue,
    key,
  ]);

  const store = useStore();
  useEffect(() => {
    if (store?.reducerMap) {
      store.replaceReducer(
        combineReducers({
          ...store.reducerMap,
          [key]: reducer,
        }),
      );
      store.reducerMap[key] = reducer;
    }
  }, [store, reducer, key]);

  const data = useSelector(selector());
  const dispatch = useDispatch();
  const set = useCallback(value => dispatch(action(value)), [dispatch, action]);

  return {
    data,
    set,
  };
};
import { useCallback, useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';

/**
 * @description Get me API hook. Perform the get me API call when component mounted
 * @returns {Object}
 */
const useLogout = () => {
  const dispatch = useDispatch();
  const token = useSelector(selectAccessToken());
  const Loading = useRef(GlobalLib.Loading.get());
  const callLogout = useCallback(async () => {
    try {
      Loading.current.show();
      await ApiLib.authApi.postApiV1AuthLogout(
        UtilLib.getAuthorizationHeaders(token),
      );
      dispatch(updateAccessToken(null));
      dispatch(updateUser({}));
      NavigationServiceLib.reset(screens.Launch);
    } catch (error) {
    } finally {
      Loading.current.hide();
    }
  }, [dispatch, token]);
  return {
    logout: callLogout,
  };
};
import { useCallback, useRef, useState } from 'react';
import { useAsync } from 'react-async';
import SplashScreen from 'react-native-splash-screen';

/**
 * @description Get me API hook. Perform the get me API call when component mounted
 * @returns {Object}
 */
const useGetMe = () => {
  const dispatch = useDispatch();
  const token = useSelector(selectAccessToken());
  const lastCallInstance = useRef(null);
  const getUserProfile = useCallback(
    async ({ accessToken }) => {
      if (lastCallInstance.current) {
        clearTimeout(lastCallInstance.current);
      }
      const cancelToken = setTimeout(async () => {
        try {
          const { data } = await ApiLib.accountApi.getApiV1AccountsMe(
            UtilLib.getAuthorizationHeaders(accessToken),
          );
          SplashScreen.hide();
          dispatch(updateUser(data?.data));
          await UtilLib.delay(1000);
          NavigationServiceLib.reset(screens.Main);
        } catch (error) {
          await UtilLib.delay(1000);
          SplashScreen.hide();
          NavigationServiceLib.reset(screens.Login);
        }
      }, 1000);
      lastCallInstance.current = cancelToken;
    },
    [dispatch],
  );
  useAsync({ promiseFn: getUserProfile, accessToken: token, watch: token });
};
var scrollToTopBtn = document.querySelector(".scrollToTopBtn")

var rootElement = document.documentElement

​

function handleScroll() {

  // Do something on scroll

  var scrollTotal = rootElement.scrollHeight - rootElement.clientHeight

  if ((rootElement.scrollTop / scrollTotal ) > 0.0) {
8
    // Show button

    scrollToTopBtn.classList.add("showBtn")

  } else {

    // Hide button

    scrollToTopBtn.classList.remove("showBtn")

  }

}

​

function scrollToTop() {

  // Scroll to top logic

  rootElement.scrollTo({

    top: 0,

    behavior: "smooth"

  })

}

scrollToTopBtn.addEventListener("click", scrollToTop)
1. Number 
2. String
3. Boolean
4. Undefined
5. Null
6. Symbol (new in ECMAScript 6)
7. Object


!==
===
>=
<=
>
<


var
let (new in ECMAScript 6)
const (new in ECMAScript 6)


if
else
else if
ternary operator
switch


&&
||
!


var a = function name() {}
function name() {}
return
() => (fat arrow function — new in ECMAScript 6)


Array
Object


or
while
do 
forEach (new in ECMAScript 5) 
forin (new in ECMAScript 5) 
forof (new in ECMAScript 5)


LET and CONST variables 
Hoisting variables (LET and CONST) 
Arrow => function short hand 
Arrow functions and THIS
Function default parameter values
Object literals short hand
Rest … operator 
Spread … operator 
For Of Loop
Template literals
Destructing arrays[ ] with default parameters
Destructing {Objects} with alias
// Get wrapper
const get = async (url, callback) => {   
  const response = await fetch(url)   
  const status = await response.status      
  if (callback) callback[status](await response.json()) 
}  
// Get usage based callback
get(url, {   
  200: body => doSomething,   
  401: body => showSignInModal,   
  403: body => redirectToSafeArea,   
  422: body => showModalWithInstruction 
})
// GET Request.
fetch('https://api.github.com/users/rich-harris')
  // Handle success
  .then(response => response.json())  // convert to json
  .then(json => console.log(json))    // print data to console
  .catch(err => console.log('Request Failed', err)); // Catch errors
<!-- beforebegin -->
<p>
  <!-- afterbegin -->
  foo
  <!-- beforeend -->
</p>
<!-- afterend -->

list.insertAdjacentHTML('beforebegin', myDiv);
image.src = 'http://placekitten.com/200/300';
image.width = 250;
image.classList.add('cute');
image.alt = 'Cute Kitten';
var scale = Math.min( 
  availableWidth / contentWidth, 
  availableHeight / contentHeight 
);
<script>
  import Toggle from "svelte-toggle@1.0.0";

  let toggled = false;
</script>

<svelte:head>
	<!-- override REPL button margin rule -->
	<style>button{margin:0}</style>
</svelte:head>
        
<Toggle
  label="My toggle label"
  switchColor="#eee"
  toggledColor="#24a148"
  untoggledColor="#fa4d56"
  on="On"
  off="Off"
  bind:toggled />
<Input
     placeholder="Flight name"
     size="large"
     value={this.state.someVal || ''}
     onChange={this.onChange}
   />
onChange = (e) => {
  this.setState({someVal: e.target.value})
}
var repoNameEl = document.querySelector('#repo-name');
var issueContainerEl = document.querySelector('#issues-container');
var limitWarningEl = document.querySelector('#limit-warning');

var getRepoName = function () {
  // Where is this value coming from?
  // TODO: from the URL and returns a string.  
  var queryString = document.location.search;
  //splits string into array.
  var repoName = queryString.split('=')[1];//takes second element of array/repor name

  if (repoName) {
    repoNameEl.textContent = repoName;

    getRepoIssues(repoName);  //calls repo issues for that repo
  } else {
    // Under what condition will this run?
    // TODO: Write your answer here 
    document.location.replace('./index.html');
  }
};

var getRepoIssues = function (repo) {
  var apiUrl = 'https://api.github.com/repos/' + repo + '/issues?direction=asc';

  fetch(apiUrl).then(function (response) {
    if (response.ok) {
      response.json().then(function (data) {
        displayIssues(data);

        // What is this checking for? Under what condition will this be `true`?
        // TODO: link is a response from the github there are more than 30 issues.
        if (response.headers.get('Link')) {
          displayWarning(repo);
        }
      });
    } else {
      document.location.replace('./index.html');
    }
  });
};

var displayIssues = function (issues) {
  // Is there a difference between this and `!issues.length`?
  // TODO: Write your answer here
  if (issues.length === 0) {
    issueContainerEl.textContent = 'This repo has no open issues!';
    return;
  }

  for (var i = 0; i < issues.length; i++) {
    var issueEl = document.createElement('a');
    issueEl.classList = 'list-item flex-row justify-space-between align-center';
    issueEl.setAttribute('href', issues[i].html_url);
    issueEl.setAttribute('target', '_blank');

    var titleEl = document.createElement('span');
    titleEl.textContent = issues[i].title;
    issueEl.appendChild(titleEl);

    var typeEl = document.createElement('span');

    if (issues[i].pull_request) {
      typeEl.textContent = '(Pull request)';
    } else {
      typeEl.textContent = '(Issue)';
    }

    issueEl.appendChild(typeEl);

    issueContainerEl.appendChild(issueEl);
  }
};

// What does this function do?
// TODO: if 'link' is returned, this runs to create a link to the issues.
var displayWarning = function (repo) {
  limitWarningEl.textContent = 'To see more than 30 issues, visit ';

  var linkEl = document.createElement('a');
  linkEl.textContent = 'GitHub.com';
  linkEl.setAttribute('href', 'https://github.com/' + repo + '/issues');
  linkEl.setAttribute('target', '_blank');

  // Where does this appear on the page?
  // TODO: appends it to the bottom of the page
  limitWarningEl.appendChild(linkEl);
};

getRepoName();
var buttonClickHandler = function (event) {
  // What is `event.target` referencing?
  // TODO: Write your answer here
  var language = event.target.getAttribute('data-language');
 //event target uses get attribute from the 
  // Why is this `if` block in place?
  // TODO: Write your answer here
  if (language) {
    getFeaturedRepos(language);

    repoContainerEl.textContent = '';
  }
};
var buttonClickHandler = function (event) {
  // What is `event.target` referencing?
  // TODO: Write your answer here
  var language = event.target.getAttribute('data-language');
 //event target uses get attribute from the 
  // Why is this `if` block in place?
  // TODO: Write your answer here
  if (language) {
    getFeaturedRepos(language);

    repoContainerEl.textContent = '';
  }
};
const findLastIndex = (array, predicate) => {
    let l = array.length;
    while (l--) {
        if (predicate(array[l], l, array)) {
            return l;
        }
    }

    return -1;
};
<!-- beforebegin -->
<p>
  <!-- afterbegin -->
  foo
  <!-- beforeend -->
</p>
<!-- afterend -->

beforeBtn.addEventListener('click', function() {
  var tempDiv = document.createElement('div');
  tempDiv.style.backgroundColor = randomColor();
  if (activeElem) {
    activeElem.insertAdjacentElement('beforebegin', tempDiv);
  }
  setListener(tempDiv);
});

afterBtn.addEventListener('click', function() {
  var tempDiv = document.createElement('div');
  tempDiv.style.backgroundColor = randomColor();
  if (activeElem) {
    activeElem.insertAdjacentElement('afterend', tempDiv);
  }
  setListener(tempDiv);
});
interface IIsObject {
  (item: any): boolean;
}

interface IObject {
  [key: string]: any;
}

interface IDeepMerge {
  (target: IObject, ...sources: Array<IObject>): IObject;
}

/**
 * @description Method to check if an item is an object. Date and Function are considered
 * an object, so if you need to exclude those, please update the method accordingly.
 * @param item - The item that needs to be checked
 * @return {Boolean} Whether or not @item is an object
 */
export const isObject: IIsObject = (item: any): boolean => {
  return (item === Object(item) && !Array.isArray(item));
};

/**
 * @description Method to perform a deep merge of objects
 * @param {Object} target - The targeted object that needs to be merged with the supplied @sources
 * @param {Array<Object>} sources - The source(s) that will be used to update the @target object
 * @return {Object} The final merged object
 */
export const deepMerge: IDeepMerge = (target: IObject, ...sources: Array<IObject>): IObject => {
  // return the target if no sources passed
  if (!sources.length) {
    return target;
  }

  const result: IObject = target;

  if (isObject(result)) {
    const len: number = sources.length;

    for (let i = 0; i < len; i += 1) {
      const elm: any = sources[i];

      if (isObject(elm)) {
        for (const key in elm) {
          if (elm.hasOwnProperty(key)) {
            if (isObject(elm[key])) {
              if (!result[key] || !isObject(result[key])) {
                result[key] = {};
              }
              deepMerge(result[key], elm[key]);
            } else {
              if (Array.isArray(result[key]) && Array.isArray(elm[key])) {
                // concatenate the two arrays and remove any duplicate primitive values
                result[key] = Array.from(new Set(result[key].concat(elm[key])));
              } else {
                result[key] = elm[key];
              }
            }
          }
        }
      }
    }
  }

  return result;
};
import { BrowserModule, BrowserTransferStateModule } from '@angular/platform-browser';
import { isDevMode, NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ServiceWorkerModule } from '@angular/service-worker';
import { environment } from '../environments/environment';

import { AngularFireModule } from '@angular/fire';
import { AngularFireStorageModule } from '@angular/fire/storage';

import {
  AngularFireAnalyticsModule,
  DEBUG_MODE as ANALYTICS_DEBUG_MODE,
  ScreenTrackingService,
  UserTrackingService
} from '@angular/fire/analytics';

import { FirestoreComponent } from './firestore/firestore.component';

import { AngularFireDatabaseModule, URL as DATABASE_URL } from '@angular/fire/database';
import { AngularFireAuthModule } from '@angular/fire/auth';
import { AngularFirestoreModule, SETTINGS as FIRESTORE_SETTINGS } from '@angular/fire/firestore';
import { AngularFireMessagingModule } from '@angular/fire/messaging';
import { AngularFireFunctionsModule, ORIGIN as FUNCTIONS_ORIGIN } from '@angular/fire/functions';
import { AngularFireRemoteConfigModule, SETTINGS as REMOTE_CONFIG_SETTINGS } from '@angular/fire/remote-config';
import { AngularFirePerformanceModule, PerformanceMonitoringService } from '@angular/fire/performance';
import { AngularFireAuthGuardModule } from '@angular/fire/auth-guard';
import { DatabaseComponent } from './database/database.component';
import { StorageComponent } from './storage/storage.component';
import { RemoteConfigComponent } from './remote-config/remote-config.component';
import { HomeComponent } from './home/home.component';
import { AuthComponent } from './auth/auth.component';
import { MessagingComponent } from './messaging/messaging.component';

const shouldUseEmulator = () => false;

@NgModule({
  declarations: [
    AppComponent,
    StorageComponent,
    FirestoreComponent,
    DatabaseComponent,
    RemoteConfigComponent,
    HomeComponent,
    AuthComponent,
    MessagingComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'serverApp' }),
    BrowserTransferStateModule,
    AppRoutingModule,
    ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production }),
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireStorageModule,
    AngularFireAnalyticsModule,
    AngularFireAuthModule,
    AngularFireDatabaseModule,
    AngularFirestoreModule.enablePersistence({ synchronizeTabs: true }),
    AngularFireMessagingModule,
    AngularFireFunctionsModule,
    AngularFireRemoteConfigModule,
    AngularFirePerformanceModule,
    AngularFireAuthGuardModule
  ],
  providers: [
    UserTrackingService,
    ScreenTrackingService,
    PerformanceMonitoringService,
    {
      provide: ANALYTICS_DEBUG_MODE,
      useFactory: () => isDevMode()
    },
    {
      provide: DATABASE_URL,
      useFactory: () => shouldUseEmulator() ? `http://localhost:9000?ns=${environment.firebase.projectId}` : undefined
    },
    { provide: FIRESTORE_SETTINGS, useFactory: () => shouldUseEmulator() ? { host: 'localhost:8080', ssl: false } : {} },
    { provide: FUNCTIONS_ORIGIN, useFactory: () => shouldUseEmulator() ? 'http://localhost:9999' : undefined },
    { provide: REMOTE_CONFIG_SETTINGS, useFactory: () => isDevMode() ? { minimumFetchIntervalMillis: 10_000 } : {} }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}
<body onload="window.alert('Document is loaded!');">
[{value:5}, {value:10}].map(item => item.value).reduce((previousValue, currentValue) => {return previousValue + currentValue })

>> 15
var something = (function() {
    var executed = false;
    return function() {
        if (!executed) {
            executed = true;
            // do something
        }
    };
})();

something(); // "do something" happens
something(); // nothing happens
// Store an array in local storage

// The array to store
var array = [1, 2, 3];
// Store after JSON stringifying (is this a verb?) it
localStorage.setItem('myArray', JSON.stringify(array));

// Get an array from local storage

// Retrieve the array from local storage
var array = localStorage.getItem('myArray');
// Parse it to something usable in js
array = JSON.parse(array);
const useRemoteTable = ({ promiseFn, searchOption, defaultOrder, columnSchema = [] }) => {
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(10);
  const [order, setOrder] = useState(defaultOrder);
  const [reloadTimeStamp, setTimeStamp] = useState(Date.now());

  const onChange = (onChangeNest) => (pagination, filter, sorter, ...args) => {
    if (pagination.current !== page) {
      setPage(pagination.current);
    }
    if (pagination.pageSize !== limit) {
      setPage(1);
      setLimit(pagination.pageSize);
    }
    if (!isEmpty(sorter) && sorter.column) {
      const newOrder = map(columnSchema, (item, index) =>
        index === sorter.column?.columnIndex ? sorter.order : false
      );
      setOrder(newOrder);
    } else {
      setOrder(undefined);
    }
    onChangeNest(pagination, filter, sorter, ...args);
  };

  const reload = useCallback(() => {
    setTimeStamp(Date.now());
  }, []);

  useEffect(() => {
    setPage(1);
  }, [searchOption]);

  const watchWalue = useMemo(
    () => ({
      limit,
      page,
      order,
      searchOption,
      reload: reloadTimeStamp
    }),
    [limit, order, page, reloadTimeStamp, searchOption]
  );

  const { data, error, isPending } = useAsync({
    promiseFn,
    searchOption,
    watch: watchWalue,
    pagination: {
      order: getOrderFromTableToAPI(order),
      orderField: columnSchema[findIndex(order, (i) => i)],
      skip: (page - 1) * limit,
      limit
    }
  });
  return {
    loading: isPending,
    reload,
    page,
    limit,
    error,
    data,
    order,
    onChange
  };
};
var numArray = [140000, 104, 99];
numArray.sort(function(a, b) {
  return a - b;
});

console.log(numArray);
const httpPost = (url, data, callback, err = console.error) => {
  const request = new XMLHttpRequest();
  request.open('POST', url, true);
  request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
  request.onload = () => callback(request.responseText);
  request.onerror = () => err(request);
  request.send(data);
};

const newPost = {
  userId: 1,
  id: 1337,
  title: 'Foo',
  body: 'bar bar bar'
};
const data = JSON.stringify(newPost);
httpPost(
  'https://jsonplaceholder.typicode.com/posts',
  data,
  console.log
); 

// Logs: {"userId": 1, "id": 1337, "title": "Foo", "body": "bar bar bar"}
const httpGet = (url, callback, err = console.error) => {
  const request = new XMLHttpRequest();
  request.open('GET', url, true);
  request.onload = () => callback(request.responseText);
  request.onerror = () => err(request);
  request.send();
};

httpGet(
  'https://jsonplaceholder.typicode.com/posts/1',
  console.log
); 

// Logs: {"userId": 1, "id": 1, "title": "sample title", "body": "my text"}
const formToObject = form =>
  Array.from(new FormData(form)).reduce(
    (acc, [key, value]) => ({
      ...acc,
      [key]: value
    }),
    {}
  );

// Example
formToObject(document.querySelector('#form')); // { email: 'test@email.com', name: 'Test Name' }
const currentURL = () => window.location.href;

// Example
currentURL(); // 'https://google.com'
const detectDeviceType = () =>
  /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
    ? 'Mobile'
    : 'Desktop';

// Example
detectDeviceType(); // "Mobile" or "Desktop"
const scrollToTop = () => {
  const c = document.documentElement.scrollTop || document.body.scrollTop;
  if (c > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, c - c / 8);
  }
};

// Example
scrollToTop();
import java.util.Scanner;

class U1_L4_Activity_Two {
    public static void main(String[] args) {
      
       /* Write your code here */
       Scanner scan = new Scanner(System.in);
       int inches;
       int feet;
       
       System.out.println("How many inches?");
       inches = scan.nextInt();
       
       feet = inches/12;
       System.out.println(inches + "\" equals " + feet + "\'" );
       
Scanner scan = new Scanner (System.in);
        
        System.out.println("Enter a radius:");
        double r = scan.nextDouble();
        System.out.println("Circumference: " + (2*3.14*r));
        System.out.println("Area: " + 3.14*r*r);
const formatDuration = ms => {
  if (ms < 0) ms = -ms;
  const time = {
    day: Math.floor(ms / 86400000),
    hour: Math.floor(ms / 3600000) % 24,
    minute: Math.floor(ms / 60000) % 60,
    second: Math.floor(ms / 1000) % 60,
    millisecond: Math.floor(ms) % 1000
  };
  return Object.entries(time)
    .filter(val => val[1] !== 0)
    .map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`)
    .join(', ');
};

// Examples
formatDuration(1001); // '1 second, 1 millisecond'
formatDuration(34325055574); // '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds'
router.post("/user", async (req, res) => {
  try {
    var user = new User(req.body);
    await user.save();
    res.status(200).send(user);
  } catch (error) {
    if (error.name === "ValidationError") {
      let errors = {};

      Object.keys(error.errors).forEach((key) => {
        errors[key] = error.errors[key].message;
      });

      return res.status(400).send(errors);
    }
    res.status(500).send("Something went wrong");
  }
});
const express = require('express')
const { graphqlHTTP } = require("express-graphql");
const {
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLString,
  GraphQLList,
  GraphQLInt,
  GraphQLNonNull
} = require('graphql')
const app = express()
const port = 3000

// Sample Data
const authors = [
	{ id: 1, name: 'Dan Brown' },
	{ id: 2, name: 'J. R. R. Tolkien' },
	{ id: 3, name: 'Brent Weeks' }
]

const books = [
	{ id: 1, name: 'The Lost Symbol', authorId: 1 },
	{ id: 2, name: 'Angels and Demons', authorId: 1 },
	{ id: 3, name: 'The Davinci Code', authorId: 1 },
	{ id: 4, name: 'The Fellowship of the Ring', authorId: 2 },
	{ id: 5, name: 'The Two Towers', authorId: 2 },
	{ id: 6, name: 'The Return of the King', authorId: 2 },
	{ id: 7, name: 'The Way of Shadows', authorId: 3 },
	{ id: 8, name: 'Beyond the Shadows', authorId: 3 }
]

const BookType = new GraphQLObjectType({
  name: 'Book',
  description: 'This represents a book written by an author',
  fields: () => ({
    id: { type: GraphQLNonNull(GraphQLInt) },
    name: { type: GraphQLNonNull(GraphQLString) },
    authorId: { type: GraphQLNonNull(GraphQLInt) },
    author: {
      type: AuthorType, // AuthorType is defined below the same way that BookType is defined above
      resolve: (book) => {
        return authors.find(author => author.id === book.authorId)
      }
    }
  })
})

const AuthorType = new GraphQLObjectType({
  name: 'Author',
  description: 'This represents the author of a book',
  fields: () => ({
    id: { type: GraphQLNonNull(GraphQLInt) },
    name: { type: GraphQLNonNull(GraphQLString) }
  })
})

const RootQueryType = new GraphQLObjectType({
  name: 'Query',
  description: 'Root Query',
  fields: () => ({
    books: {
      type: new GraphQLList(BookType),
      description: "List of books",
      resolve: () => books
    }
  })
})

const schema = new GraphQLSchema({
  query: RootQueryType
})



app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphiql: true
}))


app.get('/', (req, res) => {
  res.send(`<a href="http://localhost:${port}/graphql">GraphiQL</a>`)
})

// QUERY:
// 
// {
// 	books {
//     id
//   	name
//     author {
//       name
//     }
// 	}
// }

// RESULT
// 
// {
//   "data": {
//     "books": [
//       {
//         "id": 1,
//         "name": "The Lost Symbol",
//         "author": {
//           "name": "Dan Brown"
//         }
//       },
//       {
//         "id": 2,
//         "name": "Angels and Demons",
//         "author": {
//           "name": "Dan Brown"
//         }
//       }, //...
//     ]
//   }
// }

app.listen(port, () => {
  console.log(`App listening on http://localhost:${port}`)
});
const inicio = performance.now();

// Codigo a chequear 

const fin= perfomance.now();

console.log( fin - inicio );
Reset = "\x1b[0m"
Bright = "\x1b[1m"
Dim = "\x1b[2m"
Underscore = "\x1b[4m"
Blink = "\x1b[5m"
Reverse = "\x1b[7m"
Hidden = "\x1b[8m"

FgBlack = "\x1b[30m"
FgRed = "\x1b[31m"
FgGreen = "\x1b[32m"
FgYellow = "\x1b[33m"
FgBlue = "\x1b[34m"
FgMagenta = "\x1b[35m"
FgCyan = "\x1b[36m"
FgWhite = "\x1b[37m"

BgBlack = "\x1b[40m"
BgRed = "\x1b[41m"
BgGreen = "\x1b[42m"
BgYellow = "\x1b[43m"
BgBlue = "\x1b[44m"
BgMagenta = "\x1b[45m"
BgCyan = "\x1b[46m"
BgWhite = "\x1b[47m"
import update from 'immutability-helper';

const oldArray = [
    {name: 'Stacey', age: 55},
    {name: 'John', age: 77},
    {name: 'Kim', age: 62},
];

// add an item
const newArray = update(oldArray, {$push: [
    {name: 'Trevor', age: 45},
]});

// replace an item
const itemIndex = 1; // replace *John* at index `1`
const newValue = {name: 'Kevin', age: 25};
const newArray = update(oldArray, { [itemIndex]: {$set: newValue} });

// modify an item
const itemIndex = 1; // modify *John* at index `1`
const newArray = update(oldArray, {
    [itemIndex]: {$merge, {
        age: 85, // change John's age to 85
    }}
});         

// remove an item
const itemIndex = 0; // delete *Stacey* at index `0`
const newArray = update(oldArray, {$splice: [[itemIndex, 1]] } });
<html lang="en">
	<head>
		<!--using external files-->
		<?php require('import.html') ?>
		
		<title>U Chen Daily | Home</title>
	</head>
	<style>
		@media only screen and (min-width: 893px) {
		.card-img-top{
		width: 100%;
		height: 15vw; 
		object-fit: cover;
		}
		}
		
		.card-body{
		background: #1f52a3;
		}
		
		.card-footer{
		background: #1f52a3;
		}
		
		.h5{
		color: #1f52a3;
		}
		
		.card-text{
		font-size: 12px;
		}
	</style>
	<body class="bg-light">
		<!--using external files-->
		<?php require('header.php'); ?>
		<div id="carouselExampleCaptions" class="carousel slide" data-ride="carousel">
			<ol class="carousel-indicators">
				<li data-target="#carouselExampleCaptions" data-slide-to="0" class="active"></li>
				<li data-target="#carouselExampleCaptions" data-slide-to="1"></li>
				<li data-target="#carouselExampleCaptions" data-slide-to="2"></li>
			</ol>
			<div class="carousel-inner">
				<div class="carousel-item active">
					<img src="https://via.placeholder.com/1500x550" class="d-block w-100" alt="...">
					<div class="carousel-caption d-none d-sm-block">
						<h5>First slide label</h5>
						<p>Nulla vitae elit libero, a pharetra augue mollis interdum.</p>
					</div>
				</div>
				<div class="carousel-item">
					<img src="https://via.placeholder.com/1500x550" class="d-block w-100" alt="...">
					<div class="carousel-caption d-none d-sm-block">
						<h5>Second slide label</h5>
						<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
					</div>
				</div>
				<div class="carousel-item">
					<img src="https://via.placeholder.com/1500x550" class="d-block w-100" alt="...">
					<div class="carousel-caption d-none d-sm-block">
						<h5>Third slide label</h5>
						<p>Praesent commodo cursus magna, vel scelerisque nisl consectetur.</p>
					</div>
				</div>
			</div>
			<a class="carousel-control-prev" href="#carouselExampleCaptions" role="button" data-slide="prev">
				<span class="carousel-control-prev-icon" aria-hidden="true"></span>
				<span class="sr-only">Previous</span>
			</a>
			<a class="carousel-control-next" href="#carouselExampleCaptions" role="button" data-slide="next">
				<span class="carousel-control-next-icon" aria-hidden="true"></span>
				<span class="sr-only">Next</span>
			</a>
		</div>
		<!--4 latest news START-->
		<div class="container-fluid bg-light" style="padding: 40px 0 0;">
			<div class="row" style="margin: 0 50px;">
				<div class="col-6">
					<h5 style="color: #1f52a3;">Latest News</h5>
				</div>
				
				<div class="col-6 d-flex justify-content-end">
					<a href="" class="btn btn-link font-weight-bold" style="color: #1f52a3;">MORE NEWS <i class="fas fa-angle-double-right" style="font-size: 18px;"></i></a>
				</div>
			</div>
			
			<div class="card-deck" style="margin: 10px 50px;">
				<?php
					$dbc = mysqli_connect('localhost', 'root', '');	//connect database
					mysqli_select_db($dbc, 'news');	//select database
					
					$query = 'SELECT * FROM news ORDER BY news_datetime DESC LIMIT 4';
					$runQuery = mysqli_query($dbc, $query);
				?>
				<!--news card START-->
				<?php
					if($runQuery){
						foreach($runQuery as $row){
						?>
						<div class="card mb-4">
							<a href="/205CDE/Assignment/news.php?id=<?php echo $row['news_id'] ?>">
								<img class="card-img-top" 
								src="<?php 
									if(empty($row['news_image'])){
										echo 'https://via.placeholder.com/350x250';
										}else{
										echo $row['news_image'];
									}
								?>" alt="Card image cap">
							</a>
							<div class="card-body">
								<a href="/205CDE/Assignment/news.php?id=<?php echo $row['news_id']; ?>">
									<h5 class="card-title text-uppercase text-light d-md-none d-lg-block">
										<?php 
											if(strlen($row['news_title']) > 50){
												echo substr($row['news_title'], 0, 50).'...';
												}else{
												echo $row['news_title'];
											}
										?>
									</h5>
									<h5 class="card-title text-uppercase text-light d-none d-md-block d-lg-none">
										<?php 
											if(strlen($row['news_title']) > 106){
												echo substr($row['news_title'], 0, 106).'...';
												}else{
												echo $row['news_title'];
											}
										?>
									</h5>
								</a>
							</div>
							<div class="card-footer border-0">
								<div class="row">
									<div class="col-6 card-text text-light text-uppercase"><i class="fas fa-hashtag"></i>
										<?php echo $row['news_category']; ?>
									</div>
									<div class="col-6 card-text text-light text-right text-uppercase"><i class="far fa-clock"></i>
										<?php echo date('d-M-Y', strtotime($row['news_datetime']));?>
									</div>
								</div>
							</div>
						</div>
						<div class="w-100 d-none d-sm-block d-lg-none"><!-- wrap every 2 on sm--></div>
						<?php
						}
						}else{
						echo "ERROR! No record found!";
					}
					mysqli_close($dbc);
				?>
				<!--news card END-->
			</div>
		</div>
		<!--4 latest news END-->
		<!--4 nation news START-->
		<div class="container-fluid bg-light" style="padding: 20px 0 0;">
			<div class="row" style="margin: 0 50px;">
				<div class="col-sm">
					<h5 style="color: #1f52a3;">Nation News</h5>
				</div>
				<div class="col-sm">
				</div>
				<div class="col-sm">
				</div>
			</div>
			
			<div class="card-deck" style="margin: 10px 50px;">
				<?php
					$dbc = mysqli_connect('localhost', 'root', '');	//connect database
					mysqli_select_db($dbc, 'news');	//select database
					
					$query = 'SELECT * FROM news WHERE news_category="Nation" ORDER BY news_datetime DESC LIMIT 4';
					$runQuery = mysqli_query($dbc, $query);
				?>
				<!--news card START-->
				<?php
					if($runQuery){
						foreach($runQuery as $row){
						?>
						<div class="card mb-4">
							<a href="/205CDE/Assignment/news.php?id=<?php echo $row['news_id'] ?>">
								<img class="card-img-top" 
								src="<?php 
									if(empty($row['news_image'])){
										echo 'https://via.placeholder.com/350x250';
										}else{
										echo $row['news_image'];
									}
								?>" alt="Card image cap">
							</a>
							<div class="card-body">
								<a href="/205CDE/Assignment/news.php?id=<?php echo $row['news_id']; ?>">
									<h5 class="card-title text-uppercase text-light d-md-none d-lg-block">
										<?php 
											if(strlen($row['news_title']) > 50){
												echo substr($row['news_title'], 0, 50).'...';
												}else{
												echo $row['news_title'];
											}
										?>
									</h5>
									<h5 class="card-title text-uppercase text-light d-none d-md-block d-lg-none">
										<?php 
											if(strlen($row['news_title']) > 106){
												echo substr($row['news_title'], 0, 106).'...';
												}else{
												echo $row['news_title'];
											}
										?>
									</h5>
								</a>
							</div>
							<div class="card-footer border-0">
								<div class="row">
									<div class="col-6 card-text text-light text-uppercase"><i class="fas fa-hashtag"></i>
										<?php echo $row['news_category']; ?>
									</div>
									<div class="col-6 card-text text-light text-right text-uppercase"><i class="far fa-clock"></i>
										<?php echo date('d-M-Y', strtotime($row['news_datetime']));?>
									</div>
								</div>
							</div>
						</div>
						<div class="w-100 d-none d-sm-block d-lg-none"><!-- wrap every 2 on sm--></div>
						<?php	
						}
						}else{
						echo "ERROR! No record found!";
					}
					mysqli_close($dbc);
				?>
				<!--news card END-->
			</div>
		</div>
		<!--4 nation news END-->
		<!--4 world news START-->
		<div class="container-fluid bg-light" style="padding: 20px 0 0;">
			<div class="row" style="margin: 0 50px;">
				<div class="col-sm">
					<h5 style="color: #1f52a3;">World News</h5>
				</div>
				<div class="col-sm">
				</div>
				<div class="col-sm">
				</div>
			</div>
			
			<div class="card-deck" style="margin: 10px 50px;">
				<?php
					$dbc = mysqli_connect('localhost', 'root', '');	//connect database
					mysqli_select_db($dbc, 'news');	//select database
					
					$query = 'SELECT * FROM news WHERE news_category="World" ORDER BY news_datetime DESC LIMIT 4';
					$runQuery = mysqli_query($dbc, $query);
				?>
				<!--news card START-->
				<?php
					if($runQuery){
						foreach($runQuery as $row){
						?>
						<div class="card mb-4">
							<a href="/205CDE/Assignment/news.php?id=<?php echo $row['news_id'] ?>">
								<img class="card-img-top" 
								src="<?php 
									if(empty($row['news_image'])){
										echo 'https://via.placeholder.com/350x250';
										}else{
										echo $row['news_image'];
									}
								?>" alt="Card image cap">
							</a>
							<div class="card-body">
								<a href="/205CDE/Assignment/news.php?id=<?php echo $row['news_id']; ?>">
									<h5 class="card-title text-uppercase text-light d-md-none d-lg-block">
										<?php 
											if(strlen($row['news_title']) > 50){
												echo substr($row['news_title'], 0, 50).'...';
												}else{
												echo $row['news_title'];
											}
										?>
									</h5>
									<h5 class="card-title text-uppercase text-light d-none d-md-block d-lg-none">
										<?php 
											if(strlen($row['news_title']) > 106){
												echo substr($row['news_title'], 0, 106).'...';
												}else{
												echo $row['news_title'];
											}
										?>
									</h5>
								</a>
							</div>
							<div class="card-footer border-0">
								<div class="row">
									<div class="col-6 card-text text-light text-uppercase"><i class="fas fa-hashtag"></i>
										<?php echo $row['news_category']; ?>
									</div>
									<div class="col-6 card-text text-light text-right text-uppercase"><i class="far fa-clock"></i>
										<?php echo date('d-M-Y', strtotime($row['news_datetime']));?>
									</div>
								</div>
							</div>
						</div>
						<div class="w-100 d-none d-sm-block d-lg-none"><!-- wrap every 2 on sm--></div>
						<?php
						}
						}else{
						echo "ERROR! No record found!";
					}
					mysqli_close($dbc);
				?>
				<!--news card END-->
			</div>
		</div>
		<!--4 world news END-->
		<!--4 entertainment news START-->
		<div class="container-fluid bg-light" style="padding: 20px 0 0; margin-bottom: 40px;">
			<div class="row" style="margin: 0 50px;">
				<div class="col-sm">
					<h5 style="color: #1f52a3;">Entertainment News</h5>
				</div>
				<div class="col-sm">
				</div>
				<div class="col-sm">
				</div>
			</div>
			
			<div class="card-deck" style="margin: 10px 50px;">
				<?php
					$dbc = mysqli_connect('localhost', 'root', '');	//connect database
					mysqli_select_db($dbc, 'news');	//select database
					
					$query = 'SELECT * FROM news WHERE news_category="Entertainment" ORDER BY news_datetime DESC LIMIT 4';
					$runQuery = mysqli_query($dbc, $query);
				?>
				<!--news card START-->
				<?php
					if($runQuery){
						foreach($runQuery as $row){
						?>
						<div class="card mb-4">
							<a href="/205CDE/Assignment/news.php?id=<?php echo $row['news_id'] ?>">
								<img class="card-img-top" 
								src="<?php 
									if(empty($row['news_image'])){
										echo 'https://via.placeholder.com/350x250';
										}else{
										echo $row['news_image'];
									}
								?>" alt="Card image cap">
							</a>
							<div class="card-body">
								<a href="/205CDE/Assignment/news.php?id=<?php echo $row['news_id']; ?>">
									<h5 class="card-title text-uppercase text-light d-md-none d-lg-block">
										<?php 
											if(strlen($row['news_title']) > 50){
												echo substr($row['news_title'], 0, 50).'...';
												}else{
												echo $row['news_title'];
											}
										?>
									</h5>
									<h5 class="card-title text-uppercase text-light d-none d-md-block d-lg-none">
										<?php 
											if(strlen($row['news_title']) > 106){
												echo substr($row['news_title'], 0, 106).'...';
												}else{
												echo $row['news_title'];
											}
										?>
									</h5>
								</a>
							</div>
							<div class="card-footer border-0">
								<div class="row">
									<div class="col-6 card-text text-light text-uppercase"><i class="fas fa-hashtag"></i>
										<?php echo $row['news_category']; ?>
									</div>
									<div class="col-6 card-text text-light text-right text-uppercase"><i class="far fa-clock"></i>
										<?php echo date('d-M-Y', strtotime($row['news_datetime']));?>
									</div>
								</div>
							</div>
						</div>
						<div class="w-100 d-none d-sm-block d-lg-none"><!-- wrap every 2 on sm--></div>
						<?php
						}
						}else{
						echo "ERROR! No record found!";
					}
					mysqli_close($dbc);
				?>
				<!--news card END-->
			</div>
		</div>
		<!--4 entertainment news END-->
		<!--using external files-->
		<?php require('footer.html'); ?>
	</body>
</html>				
let request = obj => {
    return new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest();
        xhr.open(obj.method || "GET", obj.url);
        if (obj.headers) {
            Object.keys(obj.headers).forEach(key => {
                xhr.setRequestHeader(key, obj.headers[key]);
            });
        }
        xhr.onload = () => {
            if (xhr.status >= 200 && xhr.status < 300) {
                resolve(xhr.response);
            } else {
                reject(xhr.statusText);
            }
        };
        xhr.onerror = () => reject(xhr.statusText);
        xhr.send(obj.body);
    });
};


request({url: "employees.json"})
    .then(data => {
        let employees = JSON.parse(data);
        let html = "";
        employees.forEach(employee => {
            html += `
                <div>
                    <img src='${employee.picture}'/>
                    <div>
                        ${employee.firstName} ${employee.lastName}
                        <p>${employee.phone}</p>
                    </div>
                </div>`;
        });
        document.getElementById("list").innerHTML = html;
    })
    .catch(error => {
        console.log(error);
    });
var image = new Image();
var base64 = 'iVBORw0K...'
image.src = `data:image/png;base64,${base64}`;
document.body.appendChild(image);
fetch(%27https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits%27)
  .then(response => response.json())
  .then(commits => alert(commits[0].author.login));
window.scrollTo(0,document.body.scrollHeight);
new Date(date).toISOString().split('T')[0]
<!DOCTYPE html>
<html>
<body>
​
<h2>My First JavaScript</h2>
​
<button type="button"
onclick="document.getElementById('demo').innerHTML = Date()">
Click me to display Date and Time.</button>
​
<p id="demo"></p>
​
</body>
</html> 
​
var touchmoved;
$('button').on('touchend', function(e){
    if(touchmoved != true){
        // button click action
    }
}).on('touchmove', function(e){
    touchmoved = true;
}).on('touchstart', function(){
    touchmoved = false;
});
function User(name) {
  this.name = name;
  this.isAdmin = false;
}

let user = new User("Jack");
function User(name, age) {
  return {
    name,
    age,
  }
};

let user = User("Tom", 23);
// Cell.js
import React, { Component } from 'react';

export default class Cell extends Component {

  render() {
    const cellSize = {
      width: this.props.size,
      height: this.props.size
    }

    return (
      <div style={cellSize}>
      </div>
    );
  }
}
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Select box event</title>
<script type="text/javascript">
    function swapImage(hash) {
        document.getElementById('imageSwap').src = hash + '.jpg';
    }
</script>
</head>
<body>

<div id="builder_image">
    <img src="rw_blue.jpg" id="imageSwap" alt="" />
</div>

<select name="option3" onchange="swapImage(this.options[selectedIndex].label)">
    <option value="No thanks" selected="selected" label="rw_blue">No thanks</option>
    <option value="Blue" label="rw_blue">Blue</option>
    <option value="Black" label="rw_black">Black</option>
    <option value="Red" label="rw_red">Red</option>
</select>

</body>
</html>
<script type="text/javascript">
function test()
{
    alert(window.document.pic.src);
     //alert msg print like http://localhost/test/pic1.png
    if (document.pic.src=='http://localhost/test/pic1.png'){

document.pic.src='pic2.png';
} 
else if (document.pic.src=='http://localhost/test/pic2.png'){

document.pic.src='pic1.png';
}
}
</script>
<img src="pic1.png" name="pic" onclick="test()"/>
var delayInMilliseconds = 1000; //1 second

setTimeout(function() {
  //your code to be executed after 1 second
}, delayInMilliseconds);
Promise
  .all([ p1, p2, p3 ])
  .then(([ v1, v2, v3 ]) => {
    // Values always correspond to the order of promises,
    // not the order they resolved in (i.e. v1 corresponds to p1)
  });

Promise
  .race([ p1, p2, p3 ])
  .then(val => {
    // val will take the value of the first resolved promise
  });
  
 // Promise.all() turns an array of promises into a promise of an array.
 // If any promise is rejected, the error will pass through.
 // Promise.race() passes throuh the first settled promise.
test('the data is peanut butter', () => {
  expect.assertions(1);
  return fetchData().then(data => {
    expect(data).toBe('peanut butter');
  });
});
test('the data is peanut butter', done => {
  function callback(data) {
    expect(data).toBe('peanut butter');
    done();
  }

  fetchData(callback);
});
const pages = Array.prototype.slice.call(document.querySelectorAll('a.page-numbers'))
pages.map((page, index) => {
  const oldUrl = page.getAttribute('href')
  const patt = /\/[0-9]{1,2}\//;
  const result = oldUrl.match(patt)
  const result2 = '/page' + result
  const url = oldUrl.replace(result, result2)
  page.setAttribute('href', url)
});
//The ready event occurs after the HTML document has been loaded
$(document).ready(function () {
    
});

// The onload event occurs later, when all content (e.g. images) also has been loaded.
$(window).load(function() {
    SearchAction(); // used to autoload a grid    
});
{
    "name": "Highlight some phrases",
    "description": "Hightlight some pre defined text after page loads",
    "version": "0.1",
    "permissions": [
        "tabs","<all_urls>"
    ],
    "browser_action": {
        "default_icon": "icon.png"
    },
    "content_scripts": [
        {
        "matches": [
            "http://*/*",
            "https://*/*"
            ],
        "js": ["content.js"],
        "run_at": "document_end"    // Pay attention to this line
        }
    ], 
    "manifest_version": 2
}
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }

console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }
render() {
  const elements = ['one', 'two', 'three'];

  const items = []

  for (const [index, value] of elements.entries()) {
    items.push(<li key={index}>{value}</li>)
  }

  return (
    <div>
      {items}
    </div>
  )
}

////////// or:

render: function() {
  const elements = ['one', 'two', 'three'];
  return (
    <ul>
      {elements.map((value, index) => {
        return <li key={index}>{value}</li>
      })}
    </ul>
  )
}
/*
Disapproved Extensions Report Script.
This scripts generates an email if there are some non-removed disapproved extensions.
Disapproval reasons are taken from PLACEHOLDER_FEED_ITEM_REPORT.
Check the nameMapping veriable below for the list of supported extensions.
Email message could also include a long list of dissaproved remarketing feed items, so adjust settings to skip this if necessary.

Developed by Dmytro Bulakh, 2020, bulakh@ppchead.com
*/


// SCRIPT SETIINGS:

// EMAIL:  add recipients emails, like ['john@doe.com', 'doe@john.com']
// If there are no emails, like [] , the script would only log the report
var EMAIL = ['john@doe.com']

// SKIP DYNAMIC REMARKETING: set to true to skip remarketing feed items report or false otherwise

var SKIP_DYNAMIC_REMARKETING = true

function main() {

  // PlaceholderType mapping as of API version v201809 (https://developers.google.com/adwords/api/docs/appendix/placeholders)
  var nameMapping = {
    "1": "Sitelink",
    "2": "Call",
    "3": "App",
    "7": "Location",
    "30": "Affiliate location",
    "17": "Callout",
    "24": "Structured snippet",
    "31": "Message",
    "35": "Price",
    "38": "Promotion",
    "10": "Ad customizers",
    "12": "Dynamic remarketing item: Education",
    "13": "Dynamic remarketing item: Flights",
    "14": "Dynamic remarketing item: Custom Feed",
    "15": "Dynamic remarketing item: Hotels",
    "16": "Dynamic remarketing item: Real estate",
    "17": "Dynamic remarketing item: Travel",
    "19": "Dynamic remarketing item: Local",
    "20": "Dynamic remarketing item: Jobs"
  }

  var query = "SELECT PlaceholderType, DisapprovalShortNames, FeedId, FeedItemId, AttributeValues, Status " +
    "FROM PLACEHOLDER_FEED_ITEM_REPORT " +
    "WHERE DisapprovalShortNames != '' " +
    "AND Status != REMOVED " +
    "DURING TODAY"

  var report = AdsApp.report(query)
  var rows = report.rows(), values = [], iterator = {}, reasons = {}, total = 0
  var unknownTypes = {}
  while (rows.hasNext()) {
    var row = rows.next()
    if (SKIP_DYNAMIC_REMARKETING && nameMapping[row.PlaceholderType] && nameMapping[row.PlaceholderType].match('Dynamic')) continue
    row.ExtensionType = nameMapping[row.PlaceholderType]
    total++
    if (!row.ExtensionType) {
      if (!unknownTypes[row.PlaceholderType]) unknownTypes[row.PlaceholderType] = 0.0
      unknownTypes[row.PlaceholderType]++
      continue
    }
    iterator[row.ExtensionType] = iterator[row.ExtensionType] || []
    iterator[row.ExtensionType].push({
      'id': row.FeedItemId,
      'attr': row.AttributeValues,
      'status': row.Status
    })
    reasons[row.FeedItemId] = row.DisapprovalShortNames
    if (values.indexOf(row.DisapprovalShortNames) == -1) {
      values.push(row.DisapprovalShortNames)
    }
  }
  if (total < 1) {
    Logger.log('found no dissaproved extensions')
    return 'no dissaproved'
  }

  var message = ''
  for (var type in iterator) {
    message += '\n>>' + type + ': ' + (iterator[type].length) + ' disapproved extensions:\n'
    Logger.log('there are %s disapproved %s extensions:', iterator[type].length, type)
    var typeMessage = iterator[type].map(function (item) {
      var reason = JSON.parse(reasons[item.id])[0].split('\t')[0]
      return 'reason: ' + reason + ' (id:' + item.id + ')\n' + flat(JSON.parse(item.attr))
    })
    message += typeMessage.join('\n') + '\n'
  }
  Logger.log(message)

  if (EMAIL && EMAIL.length && EMAIL.length > 0) { 
    MailApp.sendEmail(EMAIL, 'Disapproved Extensions Report for ' + AdsApp.currentAccount().getName(), message)
  }
}

// Helper function for displaying extensions
function flat(record) {
  var s = []
  for (var key in record) {
    if (key > 3) {
      s.push('...')
      break
    }
    var val = record[key].join ? record[key].join(',') : record[key]
    s.push(val)
  }
  return s.join('\n')
}
/******************************************
* ETA vs RSA Test
* @version: 1.0
* @author: Naman Jindal (Optmyzr)
* March 2, 2020
*******************************************/

var LOOKBACK_DAYS = 30; // Number of Days to look back for stats
var EMAILS = ['example@example.com']; // Array of Emails separated by comma
var CAMPAIGN_NAME_CONTAINS = ''; // Case Insensitive
var CAMPAIGN_NAME_DOES_NOT_CONTAIN = ''; // Case Insensitive


// Do not edit anything below this line

function main() {
  
  var DATE_RANGE = getAdWordsFormattedDate(LOOKBACK_DAYS, 'yyyyMMdd') + ',' + getAdWordsFormattedDate(1, 'yyyyMMdd');
  
  var adMap = {}, agMap = {};
  var query = [
    'SELECT Id, AdGroupId, AdType, Status FROM AD_PERFORMANCE_REPORT',
    'WHERE CampaignStatus = ENABLED and AdGroupStatus = ENABLED',
    'and AdType IN [RESPONSIVE_SEARCH_AD, EXPANDED_TEXT_AD]',
    CAMPAIGN_NAME_CONTAINS ? 'and CampaignName CONTAINS_IGNORE_CASE "' + CAMPAIGN_NAME_CONTAINS + '"' : '',
    CAMPAIGN_NAME_DOES_NOT_CONTAIN ? 'and CampaignName DOES_NOT_CONTAIN_IGNORE_CASE "' + CAMPAIGN_NAME_DOES_NOT_CONTAIN + '"' : '',
    'DURING', DATE_RANGE
  ].join(' ');
  
  var rows = AdsApp.report(query, {'includeZeroImpressions': false }).rows();
  while(rows.hasNext()) {
   var row = rows.next();
    var key = [row.AdGroupId, row.Id].join('-');
    adMap[key] = row.AdType;
    
     if(!agMap[row.AdGroupId] ) { 
       agMap[row.AdGroupId] = {
         'Responsive search ad': 0, 'Expanded text ad': 0
       }; 
     }
    
    if(row.Status == 'enabled') {
     agMap[row.AdGroupId][row.AdType]++;
    }
  }
  
  
  var agIds = Object.keys(agMap)
  var initMap = {
    'ETA': 0, 'RSA': 0,
    'Responsive search ad': { 'Impressions': 0, 'Clicks': 0, 'Conversions': 0, 'Cost': 0, 'ConversionValue': 0 } ,
    'Expanded text ad': { 'Impressions': 0, 'Clicks': 0, 'Conversions': 0, 'Cost': 0, 'ConversionValue': 0 } 
  };
    
  var statsMap = {};
  var query = [
    'SELECT',
    'Query, CampaignName, AdGroupName, AdGroupId, CreativeId, Impressions, Clicks, Conversions, Cost, ConversionValue',
    'FROM SEARCH_QUERY_PERFORMANCE_REPORT',
    'WHERE CampaignStatus = ENABLED and AdGroupStatus = ENABLED',
    CAMPAIGN_NAME_CONTAINS ? 'and CampaignName CONTAINS_IGNORE_CASE "' + CAMPAIGN_NAME_CONTAINS + '"' : '',
    CAMPAIGN_NAME_DOES_NOT_CONTAIN ? 'and CampaignName DOES_NOT_CONTAIN_IGNORE_CASE "' + CAMPAIGN_NAME_DOES_NOT_CONTAIN + '"' : '',
    agIds.length < 10000 ? 'and AdGroupId IN [' + agIds.join(',') + ']' : '',
    'DURING', DATE_RANGE
  ].join(' ');
  
  var rows = AdsApp.report(query, {'includeZeroImpressions': false }).rows();
  while(rows.hasNext()) {
   var row = rows.next();
    var adKey = [row.AdGroupId, row.CreativeId].join('-');
    var adType = adMap[adKey];
    if(!initMap[adType]) {
      continue; 
    }
    
    var agRow = agMap[row.AdGroupId];
    if(!agRow) {
      agRow = { 'Responsive search ad': 0, 'Expanded text ad': 0 }
    }
    
    var key = [row.Query, row.AdGroupName, row.CampaignName].join('!~!');
    
    if(!statsMap[key]) {
      statsMap[key] = JSON.parse(JSON.stringify(initMap));
    }
    
    statsMap[key]['ETA'] = agRow['Expanded text ad'];
    statsMap[key]['RSA'] = agRow['Responsive search ad'];
    
    row.Impressions = parseFloat(row.Impressions);
    row.Clicks = parseFloat(row.Clicks);
    row.Cost = parseFloat(row.Cost.toString().replace(/,/g, ''));
    row.Conversions = parseFloat(row.Conversions.toString().replace(/,/g, ''));
    row.ConversionValue = parseFloat(row.ConversionValue.toString().replace(/,/g, ''));
    
    statsMap[key][adType].Impressions += row.Impressions;
    statsMap[key][adType].Clicks += row.Clicks;
    statsMap[key][adType].Cost += row.Cost;
    statsMap[key][adType].Conversions += row.Conversions;
    statsMap[key][adType].ConversionValue += row.ConversionValue;
  }
  
  var output = [];
  var results = {
    'rsa':  { 'incrementalClicks': 0, 'incrementalConversions': 0 },
    'all':  { 'incrementalClicks': 0, 'incrementalConversions': 0 }
  }
  
  for(var key in statsMap) {
    var row = statsMap[key];
    var out =  key.split('!~!');
    out.push(row['ETA'], row['RSA']);
    
    var rsaRow = row['Responsive search ad']; 
    rsaRow.Ctr = rsaRow.Impressions > 0 ? rsaRow.Clicks / rsaRow.Impressions : 0;
    rsaRow.CPI = rsaRow.Impressions > 0 ? rsaRow.Conversions / rsaRow.Impressions : 0;
    rsaRow.CPA = rsaRow.Conversions > 0 ? rsaRow.Cost / rsaRow.Conversions : 0;
    rsaRow.Cpc = rsaRow.Clicks > 0 ? rsaRow.Cost / rsaRow.Clicks : 0;
    rsaRow.ROAS = rsaRow.Cost > 0 ? rsaRow.ConversionValue / rsaRow.Cost : 0;
    
    out.push(rsaRow.Impressions, rsaRow.Clicks, rsaRow.Conversions, rsaRow.Ctr, rsaRow.CPI, rsaRow.Cost, rsaRow.CPA, rsaRow.ROAS);
    
    var etaRow = row['Expanded text ad'];
    etaRow.Ctr = etaRow.Impressions > 0 ? etaRow.Clicks / etaRow.Impressions : 0;
    etaRow.CPI = etaRow.Impressions > 0 ? etaRow.Conversions / etaRow.Impressions : 0;
    etaRow.CPA = etaRow.Conversions > 0 ? etaRow.Cost / etaRow.Conversions : 0;
    etaRow.Cpc = etaRow.Clicks > 0 ? etaRow.Cost / etaRow.Clicks : 0;
    etaRow.ROAS = etaRow.Cost > 0 ? etaRow.ConversionValue / etaRow.Cost : 0;
    
    out.push(etaRow.Impressions, etaRow.Clicks, etaRow.Conversions, etaRow.Ctr, etaRow.CPI, etaRow.Cost, etaRow.CPA, etaRow.ROAS);
    
    var incrementalClicks = rsaRow.Impressions * (rsaRow.Ctr - etaRow.Ctr);
    var incrementalConversions = rsaRow.Impressions * (rsaRow.CPI - etaRow.CPI);
    var incrementalCost = rsaRow.Clicks * (rsaRow.Cpc - etaRow.Cpc);
    
    var recommendation = '';
    if(row['ETA'] == 0) {
      recommendation = 'Test ETAs';
    } else if(row['RSA'] == 0) {
      recommendation = 'Test RSAs';
    } else if(incrementalConversions > 0) {
      recommendation = 'SKAG query with existing RSA';
    } else if(incrementalConversions < 0) {
      recommendation = 'SKAG query with existing ETA';
    } else if(etaRow.Impressions == 0) {
      recommendation = 'Test ETAs';
    } else if(rsaRow.Impressions == 0) {
      recommendation = 'Test RSAs';
    } 
    
    if(row['ETA'] == 0 && etaRow.Impressions == 0) {
      results['rsa'].incrementalClicks += incrementalClicks;
      results['rsa'].incrementalConversions += incrementalConversions;
    }
    
    if(etaRow.Impressions > 0 && rsaRow.Impressions > 0) {
      results['all'].incrementalClicks += incrementalClicks;
      results['all'].incrementalConversions += incrementalConversions;
    }
    
    out.push(incrementalClicks, incrementalConversions, incrementalCost, recommendation);
    
    output.push(out);
  }
  
  if(!output.length) {
    Logger.log('No Data found');
    return;   
  }
  
  var TEMPLATE_URL = 'https://docs.google.com/spreadsheets/d/1AAk_Vsdq0LezvezOarzhOzVXsQq5BN-EKMRtGX-eDVQ/edit';
  var template = SpreadsheetApp.openByUrl(TEMPLATE_URL);
  
  var now = getAdWordsFormattedDate(0, 'MMM d, yyyy')
  var name = AdsApp.currentAccount().getName() + ' - ETA vs RSA (' + now + ')';
  var ss = template.copy(name);
  var reportUrl = ss.getUrl();
  Logger.log('Report URL: ' + reportUrl);
  ss.addEditors(EMAILS);
  
  ss.getSheets()[0].getRange(3,1,output.length,output[0].length).setValues(output);
  
  sendEmail(results, reportUrl);
}

function sendEmail(results, reportUrl) {
  var sub = AdsApp.currentAccount().getName() + ' - ETA vs RSA Test Report';
  var msg = 'Hi,\n\nPlease find below summary of latest test results:\n';
  
  var rsaResults = results['rsa'];
  if(rsaResults.incrementalClicks > 0) {
    msg += 'You got ' + Math.round(rsaResults.incrementalClicks) + 'more clicks and ' + Math.round(rsaResults.incrementalConversions)  + ' more convversions from queries that only triggered with RSA ads.\n';
  }
  
  var change = ''
  if(results['all'].incrementalConversions > 0) {
    change = 'gained';
  } else if(results['all'].incrementalConversions < 0) {
    change = 'lost';
  }
  
  if(change) {
    msg += 'For queries that showed both RSA and ETA ads, you ' + change + ' ' + Math.round(results['all'].incrementalConversions) + ' conversions.\n';
  }
  
  msg += '\n\n' + reportUrl;
  msg +- '\n\nThanks';
  
  MailApp.sendEmail(EMAILS.join(','), sub, msg);
}

function getAdWordsFormattedDate(d, format){
  var date = new Date();
  date.setDate(date.getDate() - d);
  return Utilities.formatDate(date,AdWordsApp.currentAccount().getTimeZone(),format);
}
 Save
/**
*
* Report Trending Search Terms
*
* Creates a Google Sheets report containing two sheets:
*
* 1. Sheet with trending search terms for Last Week versus Week Before last Week
* 2. Sheet with trending search terms for Last Week versus Same Week Last Year
*
* @author: Nils Rooijmans
*
* contact nils@nilsrooijmans.com for questions and a High Performance MCC version of the script	
*/


/*** ADD YOUR CONFIGURATION HERE ***/

var SPREADSHEET_URL = "";  //insert a new blank spreadsheet url between quotes
var EMAIL_ADDRESSES = ""; //insert your email between quotes
var EMAIL_SUBJECT = "Search Terms Trends for Account - XYZ"; // replace XYZ with the account/client name


/*** NO NEED TO CHANGE ANYTHING BELOW THIS LINE ***/

var IMPRESSIONS_MIN = 10; //igore search terms with less impresssions last week 
var IMPRESSIONS_MIN_ABS_DIFFERENCE = 50; // ignore search terms with absolute difference that is smaller then the value you set here
var IMPRESSIONS_MIN_REL_DIFFERENCE = 0.2; // ignore search terms with relative difference that is smaller then the value you set here

var DEBUG = true;
var SEND_EMAIL = true; // set to false if you do not want to send alert email
var EMAIL_BODY = "";


/*** DO NOT CHANGE ANYTHING BELOW THIS LINE ***/

function main() {
    
  var searchtermsLastWeek = {};
  var searchtermsWeekBeforeLastWeek = {};
  var searchtermsLastWeekLastYear = {};
  
  var trendingSearchterms_LastWeek_vs_WeekBefore = {};
  var trendingSearchterms_LastWeek_vs_LastYear = {};
  
  searchtermsLastWeek = getSearchterms("lastWeek"); 
  searchtermsWeekBeforeLastWeek = getSearchterms("weekBeforeLastWeek"); 
  searchtermsLastWeekLastYear = getSearchterms("lastWeekLastYear"); 
    
  
  debug("Nr of searchterms last week: "+Object.keys(searchtermsLastWeek).length);
  debug("Nr of searchterms week before last week: "+Object.keys(searchtermsWeekBeforeLastWeek).length);
  debug("Nr of searchterms week last week last year: "+Object.keys(searchtermsLastWeekLastYear).length);
  
  trendingSearchterms_LastWeek_vs_WeekBefore = getTrendingSearchterms(searchtermsLastWeek, searchtermsWeekBeforeLastWeek);
  trendingSearchterms_LastWeek_vs_LastYear = getTrendingSearchterms(searchtermsLastWeek, searchtermsLastWeekLastYear);
  
  debug("Nr of trending searchterms LastWeek_vs_WeekBefore: "+Object.keys(trendingSearchterms_LastWeek_vs_WeekBefore).length);
  debug("Nr of trending searchterms LastWeek_vs_LastYear: "+Object.keys(trendingSearchterms_LastWeek_vs_LastYear).length);
  
  generateReport(trendingSearchterms_LastWeek_vs_WeekBefore, trendingSearchterms_LastWeek_vs_LastYear);

  // send email
  if (SEND_EMAIL) {
   
    var emailBody = 
        "\nNumber of trending search terms: " + ( Object.keys(trendingSearchterms_LastWeek_vs_WeekBefore).length + Object.keys(trendingSearchterms_LastWeek_vs_LastYear).length ) + "\n" + 
        "See details: "+ SPREADSHEET_URL+ "\n---\n\n" + EMAIL_BODY + "\n"+
    		"For more FREE Google Ads Scripts to improve your results and make your working day feel like a breeze, visit https://nilsrooijmans.com \n" + 
      	"---\n" + 
      	"This email is generated by a copy of the free Google Ads Script - Trending Search Terms, (C) Nils Rooijmans \n" +
      	"---\n";

    MailApp.sendEmail(EMAIL_ADDRESSES, EMAIL_SUBJECT, emailBody);
    debug("Report email sent");
  }
}


function generateReport(trendingSearchterms_LastWeek_vs_WeekBefore, trendingSearchterms_LastWeek_vs_LastYear) {
    
  var rowsThisYear  = getReportRows(trendingSearchterms_LastWeek_vs_WeekBefore);
  var rowsLastYear  = getReportRows(trendingSearchterms_LastWeek_vs_LastYear);
    
  
  var spreadsheet = SpreadsheetApp.openByUrl(SPREADSHEET_URL) ;
  if (!spreadsheet) {
    Logger.log("Cannot open new reporting spreadsheet") ;
    return ;
  }

  // First, generate the sheet for this year's data
  var sheet=spreadsheet.getSheetByName('LastWeek_vs_WeekBefore');
    
  if (!sheet) {
    Logger.log("Cannot open exisiting reporting sheet 'LastWeek_vs_WeekBefore', creating new one") ;
    spreadsheet.insertSheet('LastWeek_vs_WeekBefore');
    var sheet=spreadsheet.getSheetByName('LastWeek_vs_WeekBefore');
  }
  
  generateReportSheet(sheet, rowsThisYear); 
  debug("-> Generated report sheet: "+sheet.getName());
 
  
  // Second, generate the sheet for this year's data
  var sheet=spreadsheet.getSheetByName('LastWeek_vs_LastYear');
    
  if (!sheet) {
    Logger.log("Cannot open exisiting reporting sheet 'LastWeek_vs_LastYear' , creating new one") ;
    spreadsheet.insertSheet('LastWeek_vs_LastYear');
    var sheet=spreadsheet.getSheetByName('LastWeek_vs_LastYear');
  }
  
  generateReportSheet(sheet, rowsLastYear);
  debug("-> Generated report sheet: "+sheet.getName());
}


function generateReportSheet(sheet, rows) {
  
  debug("--> Generating report sheet: "+sheet.getName());

  if (sheet.getName()=='LastWeek_vs_WeekBefore') {
    var header = [
      "Searchterm",
      "Impressions Last Week",
      "Impressions week Before Last Week",
      "Diff",
      "Relative Diff (%)"
    ];
  } else if (sheet.getName()=='LastWeek_vs_LastYear') {
    var header = [  
      "Searchterm",
      "Impressions Last Week",
      "Impressions Last Week Last Year",
      "Diff",
      "Relative Diff (%)"
    ];  
  } else {
    Logger.log("### ERROR: name of sheet not recognized");
  }
  
  
  sheet.clear();
  sheet.clearConditionalFormatRules();
  sheet.appendRow(header);
  var range = sheet.getRange(1,1,1,header.length);
  range.setFontWeight("bold");
  
  var rules = sheet.getConditionalFormatRules();
  
  if ( !(rows.length < 1) ) { range = sheet.getRange(2,1,rows.length,5); var diffRange = [sheet.getRange("E2:E"+ (2+rows.length))]; var rule = SpreadsheetApp.newConditionalFormatRule().whenNumberGreaterThan(100).setFontColor("#32CD32").setRanges(diffRange).build(); rules.push(rule); var rule = SpreadsheetApp.newConditionalFormatRule().whenNumberLessThan(-50).setFontColor("#FF8C00").setRanges(diffRange).build(); rules.push(rule); sheet.setConditionalFormatRules(rules); range.setValues(rows); range.sort([{column: 4, ascending: false}]); } else { debug("ZERO trending search terms"); } } function getReportRows(trendingSearchTermObject) { var rows = []; for (var searchterm in trendingSearchTermObject) { var impressions_period1 = trendingSearchTermObject[searchterm].impressions_1; var impressions_period2 = trendingSearchTermObject[searchterm].impressions_2; var absoluteDiff = impressions_period1-impressions_period2; var relativeDiff = (((impressions_period1-impressions_period2)/impressions_period2)*100).toFixed(0); rows.push([searchterm, impressions_period1, impressions_period2, absoluteDiff, relativeDiff]); } return rows; } function getTrendingSearchterms(searchtermsPeriod_1,searchtermsPeriod_2) { var trendingSearchTerms = {}; for (var searchterm in searchtermsPeriod_1) { if (searchtermsPeriod_1.hasOwnProperty(searchterm)) { var impressions1 = searchtermsPeriod_1[searchterm]; if (searchtermsPeriod_2.hasOwnProperty(searchterm)) { var impressions2 = searchtermsPeriod_2[searchterm]; } else { var impressions2 = 0; } if (Math.abs(impressions1-impressions2) > IMPRESSIONS_MIN_ABS_DIFFERENCE && 
          Math.abs((impressions1-impressions2)/impressions2) > IMPRESSIONS_MIN_REL_DIFFERENCE ) {
        
         var searchTermObject = {};
        
         searchTermObject.impressions_1 = impressions1;     
         searchTermObject.impressions_2 = impressions2;
        
         trendingSearchTerms[searchterm] = searchTermObject;
      }
    }
  }
  
 
  // now add searchterms that were not present in data from period_1
  for (var searchterm in searchtermsPeriod_2) {
    
    if (searchtermsPeriod_2.hasOwnProperty(searchterm)) {
      
      var impressions2 = searchtermsPeriod_2[searchterm];
      
      if (!searchtermsPeriod_1.hasOwnProperty(searchterm)) { // searchterm not present in data from period_1
        var impressions1 = 0;
 
        if (Math.abs(impressions1-impressions2) > IMPRESSIONS_MIN_ABS_DIFFERENCE && 
            Math.abs((impressions1-impressions2)/impressions2) > IMPRESSIONS_MIN_REL_DIFFERENCE ) {

           var searchTermObject = {};

           searchTermObject.impressions_1 = impressions1;     
           searchTermObject.impressions_2 = impressions2;

           trendingSearchTerms[searchterm] = searchTermObject;
        }
      }
    }
  }   
  
  return trendingSearchTerms;
}



function getSearchterms(period) {
  
  var searchtermObject = {};
  var periodString;
  
  switch(period) {    
    case "today" :
      periodString = "TODAY"; 
      break;
    case "yesterday" :
      periodString = "YESTERDAY";
      break;
    case "dayBeforeYesterday" :
      periodString = dates(2) + "," + dates(2);
      break;
    case "lastWeek" :
      periodString = dates(7) + "," + dates(1);
      break;
    case "weekBeforeLastWeek" :
      periodString = dates(14) + "," + dates(8);
      break; 
    case "lastWeekLastYear" :
      periodString = dates(372) + "," + dates(366);
      break;      
    default :
      Logger.log("### ERROR: Could not recognize the period for which to add search terms");
  }
  
  var awqlQuery="SELECT Query, Impressions FROM SEARCH_QUERY_PERFORMANCE_REPORT WHERE Impressions > "+IMPRESSIONS_MIN+" DURING "+periodString;   
  debug("awqlQuery: "+awqlQuery);
  
  var rows=AdWordsApp.report(awqlQuery).rows(); 
  
  while (rows.hasNext()) {
    var row = rows.next();
    var searchterm = row['Query'];
    var impressions = numericalize(row['Impressions']);
    
    if (searchtermObject.hasOwnProperty(searchterm)) {
      searchtermObject[searchterm] += impressions;
    } else {
      searchtermObject[searchterm] = impressions;      
    }    
  }
  
  return searchtermObject;
}


function numericalize(string){
  return parseFloat(string.toString().replace(/\,/g, ''));
}


function debug(string) {
  if (DEBUG == true) {
    Logger.log(string);
  }
}


// return date x days before today
function dates(x){ 
 var MILLIS_PER_DAY = 1000 * 60 * 60 * 24;
 var now = new Date();
 var date = new Date(now.getTime() - x * MILLIS_PER_DAY);
 var timeZone = AdWordsApp.currentAccount().getTimeZone();
 var output = Utilities.formatDate(date, timeZone, 'yyyyMMdd')
 return output;
}
/**
*
* Report Disapproved Ads
*
* Creates a report indicating which ads are disapproved, including the reason why
* Sends an alert via email whenever ads are disapproved
*
* @author: Nils Rooijmans
*
* contact nils@nilsrooijmans.com for questions and the MCC version of the script 
*/
  
 
// CHANGE SETTINGS HERE
 
var SPREADSHEET_URL = "";  //insert a new blank spreadsheet url between the quotes
var EMAIL = ""; //insert your email adresses between the quotes
 
 
// NO CHANGES NEEDED BELOW THIS LINE
 
var SHEET_REPORT_HEADER = [
    "Campaign Name", 
    "AdGroup Name", 
    "AdID",
    "Ad Type",
    "Ad Status",
    "Disapproval Reason"
  ];
 
 
function main() {
 
  // first we clear the report sheet and add header
  prepareSpreadsheet();  
   
  // now let's check for disapprovals
  var disapprovedAds = getDisApprovedAds();    
   
  // finally, let's report on any issues
  if (disapprovedAds.length > 0) { // there is at least one issue
    Logger.log("Total NR of Ads Disapproved: "+disapprovedAds.length);
    reportResults(disapprovedAds);
  }  
}
 
 
function prepareSpreadsheet() {
 
  var ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
  var sheet = ss.getActiveSheet();
  sheet.clear(); //remove earlies alerts
  sheet.clearConditionalFormatRules();
  sheet.appendRow(SHEET_REPORT_HEADER);
}
 
 
function getDisApprovedAds() {
   
  var issues = [];
   
  var whereClause = "WHERE CampaignStatus = 'ENABLED' AND AdGroupStatus = 'ENABLED' AND Status = 'ENABLED' AND CombinedApprovalStatus = 'DISAPPROVED' ";
   
  var awqlQuery = "SELECT CampaignName, AdGroupName, Id, AdType, CombinedApprovalStatus, PolicySummary FROM AD_PERFORMANCE_REPORT "+whereClause;
   
  //debug("awqlQuery: "+awqlQuery);
   
  var rows=AdsApp.report(awqlQuery).rows() ; 
   
  while (rows.hasNext()) {
     
    var row=rows.next() ;
     
    var campaignName = row["CampaignName"];
    var adGroupName = row["AdGroupName"];
    var adId = row["Id"];
    var adType = row["AdType"];
    var approvalStatus = row["CombinedApprovalStatus"];
    var policySummary = row["PolicySummary"];
 
    issues.push([
        campaignName,
        adGroupName,
        adId,  
        adType,
        approvalStatus, 
        policySummary
    ]);  
  } 
  return issues;
}
 
 
function reportResults(results) {
 
    var ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
    var sheet = ss.getActiveSheet();
    var lastRow = sheet.getLastRow();
 
    // write issues to sheet
    var range = sheet.getRange(lastRow+1, 1, results.length, SHEET_REPORT_HEADER.length);
    range.setValues(results);
 
    // send the email
    var emailBody = 
      "Number of Ads Disapproved: " + results.length + "\n" + 
      "See details: "+ SPREADSHEET_URL + "\n\n" +
      "For more FREE Google Ads Scripts to improve your results and make your working day feel like a breeze, visit https://nilsrooijmans.com \n" + 
      "---\n" + 
      "This email is generated by a copy of the free Google Ads Script - Disapproved Ads Checker, (C) Nils Rooijmans \n" +
      "---\n";
 
    MailApp.sendEmail(EMAIL, "[GOOGLE ADS ALERT] - Disapproved Ads", emailBody);
}
router.get("/search/:page", (req, res, next) => {
  const resultsPerPage = 5;
  const page = req.params.page >= 1 ? req.params.page : 1;
  const query = req.query.search;

  Product.find({ name: query })
    .select("name")
    .sort({ name: "asc" })
    .limit(resultsPerPage)
    .skip(resultsPerPage * page)
    .then((results) => {
      return res.status(200).send(results);
    })
    .catch((err) => {
      return res.status(500).send(err);
    });
});
<script       src="myscript.js"></script>

<script async src="myscript.js"></script>

<script defer src="myscript.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name=description content="">
    <meta name=viewport content="width=device-width, initial-scale=1">
    <title>First Component</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.0-beta.1/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.0-beta.1/JSXTransformer.js"></script>
</head>
<body>
    <script type="text/jsx">
    /** @jsx React.DOM */
    var APP = React.createClass({
        render: function() {
            return (
                <h1>Hello World</h1>
            );
        }
    });

    React.renderComponent(<APP />, document.body);
    </script>
</body>
</html>
userSchema.pre('save', async function(next){
    if (!this.isModified('password')) return next()
    this.password = await bcrypt.hash(this.password, 8)

    next()
})
function processQ() {
   // ... this will be called on each .push
}

var myEventsQ = [];
myEventsQ.push = function() { Array.prototype.push.apply(this, arguments);  processQ();};
var videoEmbed = {
    invoke: function(){

        $('body').html(function(i, html) {
            return videoEmbed.convertVideo(html);
        });

    },
    convertVideo: function(html){
        var pattern1 = /(?:http?s?:\/\/)?(?:www\.)?(?:vimeo\.com)\/?(.+)/g;
        var pattern2 = /(?:http?s?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?(.+)/g;

        if(pattern1.test(html)){
            console.log("html", html);

           var replacement = '<iframe width="420" height="345" src="//player.vimeo.com/video/$1" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>';

           var html = html.replace(pattern1, replacement);
        }


        if(pattern2.test(html)){
              console.log("html", html);

           var replacement = '<iframe width="420" height="345" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>';

            var html = html.replace(pattern2, replacement);
        } 


        return html;
    }
}






setTimeout(function(){
    videoEmbed.invoke();
},3000);
import { masa } from 'masa';

masa(new Date('2020-08-17')).format('[hari] dddd, [tanggal] D MMMM YYYY');
// hari Senin, tanggal 17 Agustus 2020
var payload = (new global.JSON().encode(request.body.data));
function validateEmail(email) 
    {
        var re = /\S+@\S+\.\S+/;
        return re.test(email);
    }
    
console.log(validateEmail('anystring@anystring.anystring'));
//You must require fs and path before this action can be done
//set this on the top of the model
const imagePath = 'uploads/image'


//Create a virtual with the schema name e.g.
blogSchema.virual('imagePath').get(function(){
if(this.image != null){
return path.join('/', imagePath, this.image)
}
})

//exports the imagePath as like this
module.exports.imagePath = imagePath 


//go to the route and require it with the model name e.g.
const uploadPath = path.join("public", BlogModel.imagePath);

//set your function for unlink and call it on the delete route
function removeImage(image){
	fs.unlink(uploadPath, image), (err)=>{
    if(err) console.log(err)
    })
}

function distance(lat1, lon1, lat2, lon2, unit) {
    var radlat1 = Math.PI * lat1/180
    var radlat2 = Math.PI * lat2/180
    var theta = lon1-lon2
    var radtheta = Math.PI * theta/180
    var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
    if (dist > 1) {
        dist = 1;
    }
    dist = Math.acos(dist)
    dist = dist * 180/Math.PI
    dist = dist * 60 * 1.1515
    if (unit=="K") { dist = dist * 1.609344 }
    if (unit=="N") { dist = dist * 0.8684 }
    return dist
}
function numberWithCommas(x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
// Let generalize user data
app.use((req, res, next) => {
    res.locals.user = req.isAuthenticated() ? req.user : null
    return next()
})
const passport = require('passport')
const LocalStrategy = require("passport-local").Strategy;

passport.use(new LocalStrategy({
    usernameField: 'email'
}, async (email, password, done)=>{
    try{    
    const user = await User.findOne({ email })
        if (!user) return done(null, false, { message: 'User not exists' })
        if (!await user.checkPassword(password)) return done(null, false, { message: 'Incorrect Password' })
        return done(null, user)
    } catch (e) {
        
        return done(e)
    }
}
))

passport.serializeUser((user, done)=>{
    return done(null, user._id)
})

passport.deserializeUser(async (_id, done) => {
    try {
        const user = await User.findOne({ _id })
        return done(null, user)
    } catch (e) {
        return done(e)
    }
})





//place this one on the route
router.post('/login', (req, res, next) => {
  console.log(req.body.email)
  passport.authenticate('local', (err, user, info) => {
    if (err) {
      req.session.flashData = {
        message: {
          type: 'error',
          body: 'Login failed'
          }
      }
      return res.redirect('/user/login')
      }
    // Let check for user
    if (!user) {
      req.session.flashData = {
        message: {
          type: 'error',
          body: info.message
        }
      }
      return res.redirect('/user/login')
    }
    req.logIn(user, (err) => {
      if (err) {
        req.session.flashData = {
          message: {
            type: 'error',
            body: 'Login failed'
          }
        }
      }
      return res.redirect('/task/viewtask')
    })
  })(req, res, next)
})


//place this on index.js

// For Passport to work with session
app.use(passport.initialize());
app.use(passport.session());
const flashMsg = (req, res, next) => {
    if (req.session.flashData) {
        for (const key in req.session.flashData) {
            res.locals[key] = req.session.flashData[key]
        }

        req.session.flashData = null
    }
     
    next()
}

module.exports = flashMsg
const mongooseValidation = (theError) => {
    const errors = {}
    const details = errors.theError
    for (const key in details)
    {
        errors[key] = [details[key].message]
    }
    return errors
}

module.exports = mongooseValidation
Array.prototype.diff = function(arr2) {
    var ret = [];
    this.sort();
    arr2.sort();
    for(var i = 0; i < this.length; i += 1) {
        if(arr2.indexOf(this[i]) > -1){
            ret.push(this[i]);
        }
    }
    return ret;
};
var arr = [
  "apple",
  "banana",
  "cherry"
];

arr = arr.concat([
  "dragonfruit",
  "elderberry",
  "fig"
]);

console.log(arr);
class Car {
  constructor(brand) {
    this.carname = brand;
  }
  get cnam() {
    return this.carname;
  }
  set cnam(x) {
    this.carname = x;
  }
}

mycar = new Car("Ford");

document.getElementById("demo").innerHTML = mycar.cnam; //"Ford"
deleteItemById = id => {
  const filteredData = this.state.data.filter(item => item.id !== id);
  this.setState({ data: filteredData });
}

render() {
  ...

  return (   
    <FlatList 
      data={data} // Assuming this is `this.state.data`
      keyExtractor={({item}) => item.id}                
      renderItem={({item}) => (
        <View style={styles.container}>
          <SwipeView
            ...
            onSwipedLeft={() => this.deleteItemById(item.id)}
            ...
          />
        </View>  
      )}
    />
  );
}
const data = require('/path/to/data.json')

app.get('/search', function (req, res) {
  res.header("Content-Type",'application/json');
  res.send(JSON.stringify(data));
})
render() {
  return (
    <View style={styles.container}>
      <Image source={require('./assets/climbing_mountain.jpeg')} style={styles.imageContainer}>
      </Image>
      <View style={styles.overlay} />
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    width: null,
    height: null,
  },
  imageContainer: {
    flex: 1,
    width: null,
    height: null,
  },
  overlay: {
    ...StyleSheet.absoluteFillObject,
    backgroundColor: 'rgba(69,85,117,0.7)',
  }
})
"repository": {
  "type": "git",
  "url": "git://github.com/username/repository.git"
}
import React, { Component } from 'react';
import { FormErrors } from './FormErrors';
import './Form.css';

class Form extends Component {
 constructor (props) {
    super(props);
    this.state = {
      fname: '',
      lname: '',
      email: '',
      phone: '',
      formErrors: {fname: '', lname: '', email: '', phone: ''},
      fnameValid: false,
      lnameValid: false,
      emailValid: false,
      phoneValid: false,
      formValid: false
    }


    this.handleSubmit = this.handleSubmit.bind(this);
  }


    handleUserInput = (e) => {
    const name = e.target.name;
    const value = e.target.value;
    this.setState({[name]: value},
                  () => { this.validateField(name, value) });
  }

  validateField(fieldName, value) {
    let fieldValidationErrors = this.state.formErrors;
    let fnameValid = this.state.fnameValid;
    let lnameValid = this.state.lnameValid;
    let emailValid = this.state.emailValid;
    let phoneValid = this.state.phoneValid;

    switch(fieldName) {
      case 'fname':
        fnameValid = value.match(/^[a-zA-Z]*$/);
        fieldValidationErrors.first = fnameValid ? '' : ' name is invalid. ';
        fieldValidationErrors.first += value.length >= 2 ? '' : ' name should contain at least 2 chars. ';
        break;      
      case 'lname':
        lnameValid = value.match(/^[a-zA-Z]*$/) && value.length >= 2;
        fieldValidationErrors.last = lnameValid ? '' : ' name is invalid. ';
        fieldValidationErrors.last += value.length >= 2 ? '' : ' name should contain at least 2 chars. ';
        break;      
      case 'email':
        emailValid = value.match(/^([\w.%+-]+)@([\w-]+\.)+([\w]{2,})$/i);
        fieldValidationErrors.email = emailValid ? '' : ' is invalid. ';
        break;
      case 'phone':
        phoneValid = value.length == 10;
        fieldValidationErrors.phone = phoneValid ? '' : ' should contain 10 digits exactly. ';
        fieldValidationErrors.phone += value.match(/^\d+$/) ? '' : ' should contain numbers only. ';
        break;
      default:
        break;
    }
    this.setState({formErrors: fieldValidationErrors,
                    fnameValid: fnameValid,
                    lnameValid: lnameValid,
                    emailValid: emailValid,
                    phoneValid: phoneValid
                  }, this.validateForm);
  }

  validateForm() {
    this.setState({formValid: this.state.fnameValid && this.state.lnameValid && this.state.emailValid && this.state.phoneValid});
  }

  errorClass(error) {
    return(error.length === 0 ? '' : 'has-error');
  }


  handleSubmit(event) {

        const sgMail = require('@sendgrid/mail');
        sgMail.setApiKey(process.env.SENDGRID_API_KEY);
          const msg = {
          to: 'avivday@gmail.com',
          from: 'avivday@gmail.com',
          subject: 'JonesForm',
          text: 'and easy to do anywhere, even with Node.js',
          html: '<strong>and easy to do anywhere, even with Node.js</strong>',
        };
        sgMail.send(msg);
      event.preventDefault();
  }



 render () {
   return (
     <form className="demoForm" onSubmit={this.handleSubmit}>
        <div className="panel panel-default">
          <FormErrors formErrors={this.state.formErrors} />
        </div>

       <br />
        <div className={"form-group ${this.errorClass(this.state.formErrors.fname)}"}>
          <input type="text" className="form-control" name="fname"
            placeholder="First Name"
            value={this.state.fname}
            onChange={this.handleUserInput}  />
        </div>        
       <br />
       <div className={"form-group ${this.errorClass(this.state.formErrors.lname)}"}>
          <input type="text" className="form-control" name="lname"
            placeholder="Last Name"
            value={this.state.lname}
            onChange={this.handleUserInput}  />
        </div>
              <br />
        <div className={"form-group ${this.errorClass(this.state.formErrors.email)}"}>
          <input type="email" required className="form-control" name="email"
            placeholder="Email"
            value={this.state.email}
            onChange={this.handleUserInput}  />
        </div>
              <br />
        <div className={"form-group ${this.errorClass(this.state.formErrors.phone)}"}>
          <input type="text" className="form-control" name="phone"
            placeholder="Phone Number"
            value={this.state.phone}
            onChange={this.handleUserInput}  />
        </div>

       <br/>
        <button type="submit" disabled={!this.state.formValid}>Submit</button>
      </form>
   )
 }
}
export default Form;
//Form.js
class Form extends React.Component {
  constructor() {
    super();
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
    event.preventDefault();
    const data = new FormData(event.target);

    fetch('/api/form-submit-url', {
      method: 'POST',
      body: data,
    });
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label htmlFor="username">Enter username</label>
        <input id="username" name="username" type="text" />

        <label htmlFor="email">Enter your email</label>
        <input id="email" name="email" type="email" />

        <label htmlFor="birthdate">Enter your birth date</label>
        <input id="birthdate" name="birthdate" type="text" />

        <button>Send data!</button>
      </form>
    );
  }
}
//index.js

    const sgMail = require('@sendgrid/mail');
    sgMail.setApiKey(process.env.SENDGRID_API_KEY);
    const msg = {
      to: test@example.com',
      from: 'test@example.com',
      subject: 'Sending with SendGrid is Fun',
      text: 'and easy to do anywhere, even with Node.js',
      html: '<strong>and easy to do anywhere, even with Node.js</strong>',
    };

sgMail.send(msg);
function search(nameKey, myArray){
    for (var i=0; i < myArray.length; i++) {
        if (myArray[i].name === nameKey) {
            return myArray[i];
        }
    }
}

var array = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

var resultObject = search("string 1", array);
"repository": {
  "type": "git",
  "url": "git://github.com/username/repository.git"
}
const str = "Saturday night plans";
const res = str.startsWith("Sat");
console.log(res); //> true 
function palindrome(str) {
    const alphanumericOnly = str
        // 1) Lowercase the input
        .toLowerCase()
        // 2) Strip out non-alphanumeric characters
        .match(/[a-z0-9]/g);
        
    // 3) return string === reversedString
    return alphanumericOnly.join('') ===
        alphanumericOnly.reverse().join('');
}



palindrome("eye");

[1, 2, 3].join('my separator');
// "1my separator2my separator3"

[1, 2, 3].join(',');
// "1,2,3"

[1, 2, 3].join(', ');
// "1, 2, 3"

[1, 2, 3].join('sandwich');
// "1sandwich2sandwich3"
myName = 'yazeed';

myName.match(/e/);
// ["e", index: 3, input: "yazeed", groups: undefined]
myName = 'yazeed';

myName.match('e');
// ["e", index: 3, input: "yazeed", groups: undefined]
var str = "How are you doing today?";

var res = str.split(" ");
 
var str = "Hello World!";
var res = str.toLowerCase();
// `a` and `b` are arrays
const isEqual = (a, b) => JSON.stringify(a.sort()) === JSON.stringify(b.sort());
document.querySelectorAll('img')
    .forEach((img) =>
        img.addEventListener('load', () =>
            AOS.refresh()
        )
    );
const object1 = {
  name: 'Flavio'
}

const object2 = {
  age: 35
}

const object3 = {...object1, ...object2 }
        //Gets the Current Date and Time
        var todayDate = new Date();

        //Gets the Date Values
        var dd = ("0" + todayDate.getDate()).slice(-2);
        var mm = ("0" + (todayDate.getMonth() + 1)).slice(-2);
        var yyyy = todayDate.getFullYear();
        document.getElementById('currentDate').innerHTML = mm + " / " + dd + " / " + yyyy;

        //Gets the Time Values
        var hh = ("0" + todayDate.getHours()).slice(-2);
        var min = ("0" + todayDate.getMinutes()).slice(-2);
        var ss = ("0" + todayDate.getSeconds()).slice(-2);
        document.getElementById('currentTime').innerHTML = hh + " : " + min + " : " + ss;

        //Sets the Current Data
        var currentMonth = ("0" + (todayDate.getMonth() + 1)).slice(-2);
        var currentHour = (("0" + todayDate.getHours()).slice(-2)) * 100;
const x = [
    [
        1, 2, 3
    ],
    [
        5, 6, 7
    ],
    [
        'a','b'
    ]
]
const y = [].concat(...x)

console.log(y)
import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);


  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
const async = require("async");
async.eachSeries(updates, (up, next) => {
  techEntriesList.push(up.entryId);
  if (up.subJobType && up.userId) {
    up.jobId = jobId;
    updatePeopleWithCallback(jobId, up, jobUpdates, (err, technician) => {
      if (technician) technicianList.push(technician);
      console.log(Date.now());
      next();
      return;
    });
  }
});
var today = new Date().toISOString().slice(0, 10);
Date.prototype.addDays = function(days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
}

var date = new Date();

alert(date.addDays(5));
const date1 = new Date('7/13/2010');
const date2 = new Date('12/15/2010');
const diffTime = Math.abs(date2 - date1);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); 
console.log(diffTime + " milliseconds");
console.log(diffDays + " days");
var groupedCars = _.groupBy(cars, function(car) { return car.make; });
axios.get('api/mesas/ListarTodos').then(function(response){
    //console.log(response);
    me.mesas=response.data;
    me.loading=false;
}).catch(function(error){
    console.log(error);
}).finally(function(){
    setTimeout(/*call listen in a function*/, 30 * 1000);
});
{{#each myObject}}
    Key: {{@key}} Value = {{this}}
{{/each}}
setTimeout(function(){
   window.location.reload(1);
}, 5000);
     let images = document.getElementsByClassName('thumb-image');
     $('#search_templates').keyup(function (e) { 
         let search = $('#search_templates').val().toLowerCase();
         for (let i = 0; i < images.length; i++) {
             let searchVal = images[i].getAttribute('data-search');
             if (searchVal.toLowerCase().indexOf(search) > -1) {
                 images[i].style.display = "";
             }else{
                 images[i].style.display = "none";
             }
             
         }
         
     });
     
     //#search_templates is input and each image has keywords in data-search="" attribute
function createElement(type, attributes) {
  var element = document.createElement(type);
  for (var key in attributes) {
    if (key == "class") {
        element.classList.add.apply(element.classList, attributes[key]); // add all classes at once
    } else {
      element[key] = attributes[key];
    }
  }
  someElement.appendChild(element);
}
@post(%27/files%27, {
    responses: {
      %27204%27: {
        description: %27Uploaded%27,
      },
    },
  })
  async fileUpload(
    @requestBody.file()
    request: Request,
    @inject(RestBindings.Http.RESPONSE) response: Response,
  ): Promise<string> {
    console.log(request.file.filename);

    const storage = multer.diskStorage({
      destination: %27./public/uploads%27,
      filename: function (req, file, cb) {
        cb(null, %27image-%27 + Date.now() + path.extname(file.filename));
      },
    });

    const upload = multer({storage: storage}).single(%27image%27);

    upload(request, response, (err: unknown) => {
      if (err) console.log(err);
      else {
        console.log(request.file.filename);
      }
    });

    return %27Yes%27;
  }
    btns = document.getElementsByClassName("saveBtn");
    for (var i = 0; i < btns.length; i++) {
        btns[i].addEventListener("click", function () {
			//Add function here
        });
    }
var hasVScroll = document.body.scrollHeight > document.body.clientHeight;
$(document).ready(function() {
    // Check if body height is higher than window height :)
    if ($("body").height() > $(window).height()) {
        alert("Vertical Scrollbar! D:");
    }

    // Check if body width is higher than window width :)
    if ($("body").width() > $(window).width()) {
        alert("Horizontal Scrollbar! D:<");
    }
});
   window.onbeforeunload = function() {
    return "Data will be lost if you leave the page, are you sure?";
  };
<div class="fixed-action-btn show-mobile-only">
  <a class="btn-floating btn-large light-green" title="Back to Top" onclick="scrolltoTop()" id="scrollBtn">
    <i class="material-icons">keyboard_arrow_up</i>
  </a>
</div>

<script>
  // When the user scrolls down 100px from the top of the document, show the button
  window.onscroll = function () { scrollFunction() };

  function scrollFunction() {
    if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
      document.getElementById("scrollBtn").style.display = "inline-block";
    } else {
      document.getElementById("scrollBtn").style.display = "none";
    }
  }

  // When the user clicks on the button, scroll to the top of the document
  function scrolltoTop() {
    document.body.scrollTop = 0; // For Safari
    document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
  }
</script>
const a = [
    {
        k: 1, me: false, prim: false
    }, {
        k: 2, me: false, prim: false
    }, {
        k: 3, me: false, prim: false
    }, {
        k: 4, me: false, prim: false
    }, {
        k: 5, me: true, prim: true
    }, {
        k: 6, me: false, prim: false
    }
]

a
    .sort((x, y) => (x.prim === y.prim) ? 0 : x.prim ? -1 : 1)
    .sort((x, y) => (x.me === y.me) ? 0 : x.me ? -1 : 1)

console.log(a)
const myFunc = (...data) => (data.map((curVal,index,arr) => console.log(curVal,index,arr)))

myFunc('mango', 'apple', 'orange')
$("#slideshow > div:gt(0)").hide();

setInterval(function() { 
  $('#slideshow > div:first')
    .fadeOut(1000)
    .next()
    .fadeIn(1000)
    .end()
    .appendTo('#slideshow');
},  3000);
var specifiedElement = document.getElementById(%27a%27);

//I%27m using "click" but it works with any event
document.addEventListener(%27click%27, function(event) {
  var isClickInside = specifiedElement.contains(event.target);

  if (!isClickInside) {
    //the click was outside the specifiedElement, do something
  }
});
if (navigator.userAgent.indexOf('Mac OS X') != -1) {
  $("body").addClass("mac");
} else {
  $("body").addClass("pc");
}
buttons.forEach((button) => {
  button.addEventListener('click', () => {
    console.log("forEach worked");
  });
});