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

    return -1;
};
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);
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]] } });
<!doctype html>
<html lang="en">
  <head>
    <!-- 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">
		
		<title>U Chen Daily | Home111</title>
  </head>
  <body>
		<div class="container-fluid" style="background: #1f52a3;">
			<div class="row">
				<div class="col-2"></div>
				<div class="col-8">
					<h1 style="text-align: center; color: #e6e8eb; margin: 20px 0;">U Chen Daily</h1>
				</div>
				<div class="col-2"></div>
			</div>
		</div>
		<nav class="navbar navbar-expand-lg navbar-light bg-light">
			<a class="navbar-brand" href="#">Navbar</a>
			<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
				<span class="navbar-toggler-icon"></span>
			</button>
			
			<div class="collapse navbar-collapse" id="navbarSupportedContent">
				<ul class="navbar-nav mr-auto">
					<li class="nav-item active">
						<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
					</li>
					<li class="nav-item">
						<a class="nav-link" href="#">Link</a>
					</li>
					<li class="nav-item dropdown">
						<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
							Dropdown
						</a>
						<div class="dropdown-menu" aria-labelledby="navbarDropdown">
							<a class="dropdown-item" href="#">Action</a>
							<a class="dropdown-item" href="#">Another action</a>
							<div class="dropdown-divider"></div>
							<a class="dropdown-item" href="#">Something else here</a>
						</div>
					</li>
					<li class="nav-item">
						<a class="nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a>
					</li>
				</ul>
				<form class="form-inline my-2 my-lg-0">
					<input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
					<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
				</form>
			</div>
		</nav>
		<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>
		<div class="container-fluid bg-light" style="padding: 30px 0;">
			<div class="row" style="margin: 0 50px;">
				<div class="col-sm">
					<h5>Top News</h5>
				</div>
				<div class="col-sm">
				</div>
				<div class="col-sm">
				</div>
			</div>
			
			<div class="card-deck" style="margin: 15px 50px;">
				<div class="card mb-4">
					<img class="card-img-top img-fluid" src="https://via.placeholder.com/350x200" alt="Card image cap">
					<div class="card-body">
						<h5 class="card-title text-uppercase text-light">Covid-19: 89 new cases, two new deaths bring total to 136</h5>
						<!-- <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> -->
					</div>
					<div class="card-footer border-0">
						<div class="row">
							<div class="col-6 card-text text-light text-uppercase">
								Nation
							</div>
							<div class="col-6 card-text text-light text-right text-uppercase">
								30 Sept 2020
							</div>
						</div>
					</div>
				</div>
				<div class="card mb-4">
					<img class="card-img-top img-fluid" src="https://via.placeholder.com/350x200" alt="Card image cap">
					<div class="card-body">
						<h5 class="card-title text-uppercase text-light">Covid-19 spreading faster in Selangor than in Sabah, says Health DG</h5>
						<!-- <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> -->
					</div>
					<div class="card-footer border-0">
						<div class="row">
							<div class="col-6 card-text text-light text-uppercase">
								Nation
							</div>
							<div class="col-6 card-text text-light text-right text-uppercase">
								30 Sept 2020
							</div>
						</div>
					</div>
				</div>
				<div class="w-100 d-none d-sm-block d-lg-none"><!-- wrap every 2 on sm--></div>
				<div class="card mb-4">
					<img class="card-img-top img-fluid" src="https://via.placeholder.com/350x200" alt="Card image cap">
					<div class="card-body">
						<h5 class="card-title text-uppercase text-light">What happens if you don’t complete the e-Census 2020?</h5>
						<!-- <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> -->
					</div>
					<div class="card-footer border-0">
						<div class="row">
							<div class="col-6 card-text text-light text-uppercase">
								Nation
							</div>
							<div class="col-6 card-text text-light text-right text-uppercase">
								30 Sept 2020
							</div>
						</div>
					</div>
				</div>
				<div class="card mb-4">
					<img class="card-img-top img-fluid" src="https://via.placeholder.com/350x200" alt="Card image cap">
					<div class="card-body">
						<h5 class="card-title text-uppercase text-light">Bukit Aman to resubmit papers to AGC on minister's violation of...</h5>
						<!-- <p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> -->
					</div>
					<div class="card-footer border-0">
						<div class="row">
							<div class="col-6 card-text text-light text-uppercase">
								Nation
							</div>
							<div class="col-6 card-text text-light text-right text-uppercase">
								30 Sept 2020
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>

    <!-- 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>
  </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");
  });
});
import uuid from 'uuid/v4'

export default function getTestIDs() {
  if (process.env.NODE_ENV !== 'test') return {}

  let ids = new Map()
  let proxy = new Proxy({}, {
    get: function(obj, prop) {
      if (ids.has(prop) === false) {
        ids.set(prop, uuid())
      }
      return ids.get(prop)
    }
  })
  return proxy
}
function getOffset( el ) {
    var _x = 0;
    var _y = 0;
    while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
        _x += el.offsetLeft - el.scrollLeft;
        _y += el.offsetTop - el.scrollTop;
        el = el.offsetParent;
    }
    return { top: _y, left: _x };
}
var x = getOffset( document.getElementById(%27yourElId%27) ).left; 
function bookRentData(bookData) {

   bookData.forEach((book) => {

      //generate random sku number

      const sku = book.sku
      var random = sku[Math.floor(Math.random() * sku.length - 1)];
      document.getElementById("message").innerHTML = sku[random];   

      });
        wrap.innerHTML += `<tr>
                             <td>${book.sku}</td>
                             <td>${book.price}</td>
                          </tr>`
   }
const playThe = (funky) => {
  return funky + " music";
}

const playThe = funky => {
  return funky + " music";
}

const playThe = funky => funky + " music";

// You can call all of these functions like: `playThe('blues')`
var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
   var Person = mongoose.model('Person', yourSchema);
   // find each person with a name contains 'Ghost'
   Person.findOne({ "name" : { $regex: /Ghost/, $options: 'i' } },
          function (err, person) {
                 if (err) return handleError(err);
                 console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation);

   });
function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = deg2rad(lat2-lat1);  // deg2rad below
  var dLon = deg2rad(lon2-lon1); 
  var a = 
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
    Math.sin(dLon/2) * Math.sin(dLon/2)
    ; 
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
  var d = R * c; // Distance in km
  return d;
}

function deg2rad(deg) {
  return deg * (Math.PI/180)
}
items = [ {id:1, value:3, perc:0.5}, {id:2, value:2, perc:0.3}, {id:3, value:1, perc:0.2} ]
items.sort(function (a, b){
    return (b.value - a.value)
})

Ordenar ascendentemente por perc
items.sort(function (a, b) {
    return (a.perc - b.perc)
})
function toObject(arr) {
  var rv = {};
  for (var i = 0; i < arr.length; ++i)
    rv[i] = arr[i];
  return rv;
}
amount
	.toFixed(2)
    .toString()
    .replace(/\B(?=(\d{3})+(?!\d))/g, ",")
    
// or

amount
	.toLocaleString('en-US', { style: 'currency', currency: 'USD' });
var fs = require('fs');

fs.createReadStream('test.log').pipe(fs.createWriteStream('newLog.log'));
<ol><li><a href="#return">I want to return my purchase! What do I do?</a></li><li><a href="#return-a-gift">I would like to return a gift that was sent to me. How do I do that?</a></li><li><a href="#exchange">Can I exchange my order instead of returning it?</a></li><li><a href="#label-and-misplaced">I printed out my label and misplaced it. How can I retrieve it again?</a></li><li><a href="#does-it-take">How long does it take for me to get a refund?</a></li><li><a href="#international-returns">Do your pre-paid labels cover international returns?</a></li><li><a href="#gift-card-cert-return">I am returning an item purchased with a Gift Certificate or Gift Card, how does that work?</a></li><li><a href="#I only see the option to return my order through UPS on the website. Am I able to return through USPS instead?">I only see the option to return my order through UPS on the website. Am I able to return through USPS instead?</a></li></ol>
var t0 = performance.now();

for (let i = 0; i < 10000; i++) {   
    // Do stuff here 
}  

// Do some other stuff here

var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " ms.")
let old_arr = ["A", "A", "B", "C", "D", "E", "F", "F"]
let new_arr = [...new Set(old_arr)];

new_arr
["A", "B", "C", "D", "E", "F"]

// 社区优秀解法
var lengthOfLIS = function(nums) {
    let n = nums.length;
    if(n <= 1){
        return n;
    }

    let tail = [nums[0]];
    for(let i = 0;i < n;i++){
        // 比tail数组最后一个元素大,则添加到数组尾部
        if(nums[i] > tail[tail.length-1]){
            tail.push(nums[i]);
        }else{
            let left = 0;
            let right = tail.length-1;
            while(left < right){
                let mid = (left + right) >> 1;
                if(tail[mid] < nums[i]){
                    left = mid + 1;
                }else{
                    right = mid;
                }
            }

            // 上面二分查找代码,不断逼近与nums[i]最靠近的tail元素
            // 最后left位置的元素是比nums[i]大的最小元素,则调整tail数组
            // 显然根据逻辑推理,将nums[left]替换为nums[i]并不会改变
            // 原来tail的升序列状态,同时尽量降低tail中"山峰"出现
            tail[left] = nums[i];
        }
    }

    return tail.length;
};
// Coupon Env
		$( 'div.woocommerce' ).on( 'click', '.coupon-env .coupon-enter', function( ev ) {
			ev.preventDefault();
			
			var $couponEnv = $( this ).parent(),
				$input = $couponEnv.find('.form-control');
			
			$couponEnv.addClass('coupon-visible');

			setTimeout(function(){ $input.focus(); }, 200);
		} ).on( 'click', '.coupon-env .close-coupon', function( ev ) {
			ev.preventDefault();
			
			$( this ).closest( '.coupon-env' ).removeClass('coupon-visible');
		} );
const mySet = new Set();
// adding items
mySet.add("a new item");
// searching for a item
mySet.has("a new item");
// getting the set  size
mySet.size()
// getting all items inside a set
mySet.values()
// removing item
mySet.delete("a new item");
// removing all items inside a set
mySet.clear()
// from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
function isSuperset(set, subset) {
    for (var elem of subset) {
        if (!set.has(elem)) {
            return false;
        }
    }
    return true;
}
function union(setA, setB) {
    var _union = new Set(setA);
    for (var elem of setB) {
        _union.add(elem);
    }
    return _union;
}

function intersection(setA, setB) {
    var _intersection = new Set();
    for (var elem of setB) {
        if (setA.has(elem)) {
            _intersection.add(elem);
        }
    }
    return _intersection;
}


function difference(setA, setB) {
    var _difference = new Set(setA);
    for (var elem of setB) {
        _difference.delete(elem);
    }
    return _difference;
}

//Examples
var setA = new Set([1, 2, 3, 4]),
    setB = new Set([2, 3]),
    setC = new Set([3, 4, 5, 6]);

isSuperset(setA, setB); // => true
union(setA, setC); // => Set [1, 2, 3, 4, 5, 6]
intersection(setA, setC); // => Set [3, 4]
difference(setA, setC); // => Set [1, 2]
var mySet = new Set();

mySet.add(1); // Set [ 1 ]
mySet.add(5); // Set [ 1, 5 ]
mySet.add(5); // Set [ 1, 5 ]
mySet.add('some text'); // Set [ 1, 5, 'some text' ]
var o = {a: 1, b: 2};
mySet.add(o);

mySet.add({a: 1, b: 2}); // o is referencing a different object so this is okay

mySet.has(1); // true
mySet.has(3); // false, 3 has not been added to the set
mySet.has(5);              // true
mySet.has(Math.sqrt(25));  // true
mySet.has('Some Text'.toLowerCase()); // true
mySet.has(o); // true

mySet.size; // 5

mySet.delete(5); // removes 5 from the set
mySet.has(5);    // false, 5 has been removed

mySet.size; // 4, we just removed one value
console.log(mySet);// Set [ 1, "some text", Object {a: 1, b: 2}, Object {a: 1, b: 2} ]
subset(secondSet) {
  if (secondSet.size() < this.size()) {
    return false
  }
  
  return this.values().every(value => secondSet.has(value))
}
difference(secondSet) {
  const differenceSet = new Set()
  const firstSetValues = this.values()
  firstSetValues.forEach(value => {
    if (!secondSet.has(value)) {
      differenceSet.add(value)
    }
  })
  return differenceSet
}
intersection(secondSet) {
  const intersectionSet = new Set()
  const firstSetValues = this.values()
  const secondSetValues = secondSet.values()
  const allValues = [...firstSetValues, ...secondSetValues]
  allValues.forEach(
    value =>
      secondSet.has(value) && 
      this.has(value) && 
      intersectionSet.add(value),
  )
  return intersectionSet
}
union(secondSet) {
  const unionSet = new Set()
  const firstSetValues = this.values()
  const secondSetValues = secondSet.values()
  const allSetValues = [...firstSetValues, ...secondSetValues]
  allSetValues.forEach(value => unionSet.add(value))
  return unionSet
}
values(){
  let valuesList = []
  for(let value in items){
    valuesList.push(value)
  }
  return valuesList
}
delete(item){
  if(!this.has(item)){
    return false
  }
  delete items[item]
  size--
  return true
}
delete(item){
  if(!this.has(item)){
    return false
  }
  delete items[item]
  size--
  return true
}
add(item){
  if(this.has(item)){
    return false
  }
  items[item] = item
  size++
  return true
}
<script>
var year = new Date();
year = year.getFullYear();
jQuery(function($){
	$('#footer-info').html('&copy; ' + year + ' <a href="https://thisweekinworcester.com">This Week In Worcester</a> | All Rights Reserved');
});
</script>
<?php 
  
function startsWith($string, $startString) { 
  $len = strlen($startString); 
  return (substr($string, 0, $len) === $startString); 
} 

// usage
echo startsWith("cat", "c"); // true
echo startsWith("dog", "x"); // false

?> 
var str = " a b    c d e   f g   ";
var newStr = str.trim();
// "a b    c d e   f g"
$(document).ready(function(){
        $('.btnWrapper button').click(function(){
            $('.btnWrapper button').removeClass('active');
            $(this).addClass('active');
            var realtion = $(this).data('relation');
            $('.translatedText>div').removeClass('active');
            $('.translatedText').find('#' + realtion).addClass('active');
        });
        
    });
function startsWith($string, $startString) {
  return strncmp($string, $startString, strlen($startString)) === 0;
}
The includes array method checks whether the string "Gold" is contained as an item in the array, not whether one of the array items contains the substring. You'd want to use some with the includes string method for that:

Ressources.some(res => res.includes("Gold"))
filteredList() {
      return this.postList.filter(post => {
        return post.title.toLowerCase().includes(this.search.toLowerCase())
      })
    }
for (let step = 0; step < 5; step++) {
  // Runs 5 times, with values of step 0 through 4.
  console.log('Walking east one step');
}
await sleep(1000)
function sleep(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  });
} 
import PropTypes from 'prop-types'
render() {
  return 'Look ma, no spans!';
}

 
import React from 'react';
import Card from './Card';

function CardList ({jobs}) {
  return (
    jobs.map((job,i) => {
      return (
        <Card
          key={i}
          id={jobs[i].id}
          name={jobs[i].name}
          langs={jobs[i].langs} 
        />
     );
  );
}

export default CardList;
db.Foo.aggregate(
  {$unwind: "$bars"},
  {$lookup: {
    from:"bar",
    localField: "bars",
    foreignField: "_id",
    as: "bar"

   }},
   {$match: {
    "bar.testprop": true
   }}
)
chrome.tabs.executeScript( {
	code: "window.getSelection().toString();"
}, function(selection) {
	// selected contains text including line breaks
	var selected = selection[0];
});
let fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
let citrus = fruits.slice(1, 3)

// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
// citrus contains ['Orange','Lemon']
function moveCursorToEnd(el) {
    if (typeof el.selectionStart == "number") {
        el.selectionStart = el.selectionEnd = el.value.length;
    } else if (typeof el.createTextRange != "undefined") {
        el.focus();
        var range = el.createTextRange();
        range.collapse(false);
        range.select();
    }
}
  scalar DateTime
  scalar Upload

  input addUser {
    Email: String!
    Password: String
    FirstName: String!
    LastName: String!
    Age: DateTime!
    JobTitle: String!
    File: Upload
  }

  type Mutation {
    register(input: addUser!): Boolean
  }
buttons.forEach((button) => {
  button.addEventListener('click', () => {
    console.log("forEach worked");
  });
});
//Replace the closeSelf() function in iframe page to the following

function closeSelf() {
   parent.window.postMessage("removetheiframe", "*");
}

//and on the parent page, add the following code to listen when the iframe sends a message :

function receiveMessage(event){
   if (event.data=="removetheiframe"){
      var element = document.getElementById('iframe-element');
      element.parentNode.removeChild(element);
   }
}
window.addEventListener("message", receiveMessage, false);
export function asyncWrap(promise) {
  return promise.then(result => [null, result]).catch(err => [err]);
}
<script type="text/javascript">
function loadXMLDoc() {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE) {   // XMLHttpRequest.DONE == 4
           if (xmlhttp.status == 200) {
               document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
           }
           else if (xmlhttp.status == 400) {
              alert('There was an error 400');
           }
           else {
               alert('something else other than 200 was returned');
           }
        }
    };

    xmlhttp.open("GET", "ajax_info.txt", true);
    xmlhttp.send();
}
</script>
let unboundSlice = Array.prototype.slice
let slice = Function.prototype.call.bind(unboundSlice)

function list() {
  return slice(arguments)
}

let list1 = list(1, 2, 3) // [1, 2, 3]
// Using slice, create newCar from myCar.
let myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } }
let myCar = [myHonda, 2, 'cherry condition', 'purchased 1997']
let newCar = myCar.slice(0, 2)

// Display the values of myCar, newCar, and the color of myHonda
//  referenced from both arrays.
console.log('myCar = ' + JSON.stringify(myCar))
console.log('newCar = ' + JSON.stringify(newCar))
console.log('myCar[0].color = ' + myCar[0].color)
console.log('newCar[0].color = ' + newCar[0].color)

// Change the color of myHonda.
myHonda.color = 'purple'
console.log('The new color of my Honda is ' + myHonda.color)

// Display the color of myHonda referenced from both arrays.
console.log('myCar[0].color = ' + myCar[0].color)
console.log('newCar[0].color = ' + newCar[0].color)
$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType
});
                                package com.rizki.mufrizal.belajar.spring.boot.domain

import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.mapping.Document
import org.springframework.data.mongodb.core.mapping.Field

/**
 *
 * @Author Rizki Mufrizal <mufrizalrizki@gmail.com>
 * @Web <https://RizkiMufrizal.github.com>
 * @Since 12 January 2017
 * @Time 10:13 PM
 * @Project Belajar-Spring-Boot
 * @Package com.rizki.mufrizal.belajar.spring.boot.domain
 * @File Barang
 *
 */
@Document(collection = "tb_barang")
class Barang implements Serializable {

    @Id
    @Field(value = "id_barang")
    String idBarang

    @Field(value = "nama_barang")
    String namaBarang

    @Field(value = "jenis_barang")
    JenisBarang jenisBarang

    @Field(value = "tanggal_kadaluarsa")
    Date tanggalKadaluarsa

    @Field(value = "harga_satuan_barang")
    BigDecimal hargaSatuanBarang

    @Field(value = "jumlah_barang_tersedia")
    Integer jumlahBarangTersedia

}
                                
    let data = {"classA":[{"date":"01-01","present":49,"absent":14},{"date":"02-01","present":39,"absent":24},{"date":"03-01","present":35,"absent":28}],"classB":[{"date":"01-01","present":49,"absent":14},{"date":"02-01","present":39,"absent":24},{"date":"03-01","present":35,"absent":28}],"classC":[{"date":"01-01","present":49,"absent":14},{"date":"02-01","present":39,"absent":24},{"date":"03-01","present":35,"absent":28}]}

    let newData = [];

    for (let [key, value] of Object.entries(data)) {
        newData.push({class:key, ...value[value.length - 1]});
    }

    console.log(newData);
                                
const chunkIntoN = (arr, n) => {
  const size = Math.ceil(arr.length / n);
  return Array.from({ length: n }, (v, i) =>
    arr.slice(i * size, i * size + size)
  );
}
EXAMPLES
chunkIntoN([1, 2, 3, 4, 5, 6, 7], 4); // [[1,2], [3,4], [5,6], [7]]                                
                                
const renameKeys = (keysMap, obj) =>
  Object.keys(obj).reduce(
    (acc, key) => ({
      ...acc,
      ...{ [keysMap[key] || key]: obj[key] }
    }),
    {}
  );
EXAMPLES
const obj = { name: 'Bobo', job: 'Front-End Master', shoeSize: 100 };
renameKeys({ name: 'firstName', job: 'passion' }, obj); // { firstName: 'Bobo', passion: 'Front-End Master', shoeSize: 100 }
                             
                                
                                
function drawLine( color, xInit, yInit, xEnd, yEnd, canvas)
{
    canvas.beginPath();
    canvas.strokeStyle=color;
    canvas.lineWidth=grosorLinea;
    canvas.moveTo(xInit, yInit);
    canvas.lineTo(xEnd, yEnd);
    canvas.stroke();
    canvas.closePath();
}
const object1 = {
  a: 'somestring',
  b: 42
};

for (let [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}
document.addEventListener('keydown', function (event) {
  var esc = event.which == 27,
      nl = event.which == 13,
      el = event.target,
      input = el.nodeName != 'INPUT' && el.nodeName != 'TEXTAREA',
      data = {};

  if (input) {
    if (esc) {
      // restore state
      document.execCommand('undo');
      el.blur();
    } else if (nl) {
      // save
      data[el.getAttribute('data-name')] = el.innerHTML;

      // we could send an ajax request to update the field
      /*
      $.ajax({
        url: window.location.toString(),
        data: data,
        type: 'post'
      });
      */
      log(JSON.stringify(data));

      el.blur();
      event.preventDefault();
    }
  }
}, true);

function log(s) {
  document.getElementById('debug').innerHTML = 'value changed to: ' + s;
}
                                
 foo += -bar + (bar += 5);
// foo and bar are now 15
                                
var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname + window.location.search
                                
  function LightenDarkenColor(col, amt) {
  
    var usePound = false;
  
    if (col[0] == "#") {
        col = col.slice(1);
        usePound = true;
    }
 
    var num = parseInt(col,16);
 
    var r = (num >> 16) + amt;
 
    if (r > 255) r = 255;
    else if  (r < 0) r = 0;
 
    var b = ((num >> 8) & 0x00FF) + amt;
 
    if (b > 255) b = 255;
    else if  (b < 0) b = 0;
 
    var g = (num & 0x0000FF) + amt;
 
    if (g > 255) g = 255;
    else if (g < 0) g = 0;
 
    return (usePound?"#":"") + (g | (b << 8) | (r << 16)).toString(16);
  
}
                                
 var myArray = [
  "Apples",
  "Bananas",
  "Pears"
];

var randomItem = myArray[Math.floor(Math.random()*myArray.length)];
                                
const mapObject = (arr, fn) =>
  arr.reduce((acc, el, i) => {
    acc[el] = fn(el, i, arr);
    return acc;
  }, {});
  
EXAMPLES
mapObject([1, 2, 3], a => a * a); // { 1: 1, 2: 4, 3: 9 }                                
                                
const get = (from, ...selectors) =>
  [...selectors].map(s =>
    s
      .replace(/\[([^\[\]]*)\]/g, '.$1.')
      .split('.')
      .filter(t => t !== '')
      .reduce((prev, cur) => prev && prev[cur], from)
  );
EXAMPLES
const obj = { selector: { to: { val: 'val to select' } }, target: [1, 2, { a: 'test' }] };
get(obj, 'selector.to.val', 'target[0]', 'target[2].a'); // ['val to select', 1, 'test']                                
                                
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?name=Adam&surname=Smith'); // {name: 'Adam', surname: 'Smith'}
getURLParameters('google.com'); // {}                                
                                
$("p").css("background-color", "yellow");
$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: function (result) {
       alert("The result is "+result);
	}
});
                                
 const isRequired = () => { throw new Error('param is required'); };

const hello = (name = isRequired()) => { console.log(`hello ${name}`) };

// These will throw errors
hello();
hello(undefined);

// These will not
hello(null);
hello('David');
The idea here is that it uses default parameters, like how the b parameter here has a default if you don’t send it anything:
function multiply(a, b = 1) {
  return a * b;
}                               
                                
  document.body.innerHTML = string_of_html;

// Append it instead
document.body.innerHTML += string_of_html;

                                
var person = "Hege";
var person="Hege";

A good practice is to put spaces around operators ( = + - * / ):

var x = y + z;
<html>

<input id="contact" name="address">

<script>

    var x = document.getElementById("contact").getAttribute('name');

</script>

</html>
<html>	
   
   <input id="contact" name="address">
 
 <script>

    document.getElementById("contact").attribute = "phone";
	
    //ALTERNATIVE METHOD TO CHANGE
    document.getElementById("contact").setAttribute('name', 'phone');	

  </script>

</html>
<html>	
	<div id="target">
    	<p>This is some text</p>
    </div>

  <script>

    //GET
      var divElement = document.getElementById("target").innerHTML;

    //CHANGE
      var heading = '<h1>Example text</h1>';
      document.getElementById("target").innerHTML = heading;

    //TO MAKE DIV EMPTY
        document.getElementById("target").innerHTML = '';

  </script>
  
</html>
var profile = {
  name: 'John',
  age: 25,
  isAdmin: false,
  courses: ['html', 'css', 'js']
};

var person = JSON.stringify(profile);
var contacts = '{ "people" : [' +
'{ "firstName":"Joe" , "lastName":"Smith" },' +
'{ "firstName":"Tom" , "lastName":"Hardy" },' +
'{ "firstName":"Ben" , "lastName":"Stiller" } ]}';

var newObject = JSON.parse(contacts);

const compact = arr => arr.filter(Boolean);

compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); 
var url = "http://scratch99.com/web-development/javascript/";
var urlParts = url.replace('http://','').replace('https://','').split(/[/?#]/);
var domain = urlParts[0];
var x = 1.234;
 
var y = x.toExponential(2); 
// returns y = 1.23e+0
 
var y = x.toExponential(5);  
// returns y = 1.23450e+0
parseInt("10");         // returns 10
parseInt("10.33");      // returns 10
parseInt("10 20 30");   // returns 10
parseInt("10 years");   // returns 10
parseInt("years 10");   // returns NaN 
var x = 1.2345;

var y = x.toFixed(0);
//y equals 1;

var y = x.toFixed(2);
//y equals 1.23

var y = x.toFixed(5);
//y equals 1.23400
var x = 123;

//OPTION 1
var y = x.toString();           

//OPTION 2
var y = (123).toString();        

//OPTION 3
var y = (100 + 23).toString();   

// value of y is 123 in all 3 cases.
var x = 1234;
var y = x.valueOf(); 

var y = (1234).valueOf();

var y (1000+234).valueOf();

//y equals 1234 in all 3 cases
const arrAvg = arr => arr.reduce((a,b) => a + b, 0) / arr.length
// arrAvg([20, 10, 5, 10]) -> 11.25
const arrSum = arr => arr.reduce((a,b) => a + b, 0)
// arrSum([20, 10, 5, 10]) -> 45
const arrMax = arr => Math.max(...arr);
// arrMax([20, 10, 5, 10]) -> 20
const arrMin = arr => Math.min(...arr);
// arrMin([20, 10, 5, 10]) -> 5

import numpy as np

def pagerank(M, num_iterations=100, d=0.85):
    N = M.shape[1]
    v = np.random.rand(N, 1)
    v = v / np.linalg.norm(v, 1)
    iteration = 0
    while iteration < num_iterations:
        iteration += 1
        v = d * np.matmul(M, v) + (1 - d) / N
    return v
try {
  let hello = prompt("Type hello");
  if (hello !== 'hello'){
    throw new Error("Oops, you didn't type hello");
  }
}
catch(e) {
  alert(e.message);
}
finally {
  alert('thanks for playing!');
}
module.exports = leftpad;
function leftpad (str, len, ch){
   str = String(str);
   var i = -1;
   if (!ch && ch !== 0) ch = ' ';
   len = len - str.length;
   while (++i < len){
      str = ch + str;
   }
   return str;
}
<p id="copyrightyear"></p>

<script>
   document.getElementById('copyrightyear').innerHTML
</script>
    let findMargins = (maximum: number) => {
      const _sign = maximum < 0 ? -1 : 1;
      const _maximum = Math.abs(maximum);
      const _multiplier = Math.pow(10, Math.floor(_maximum).toString().length - 1);
      return Math.ceil(_maximum / _multiplier) * _multiplier * _sign;
    }
<p id="date-stamp">Sat Dec 14 2019 16:58:20 GMT+0500 (Pakistan Standard Time)</p>

<script>
        var dateStamp = document.getElementById("date-stamp");
        var date = dateStamp.innerHTML;
        var date2 = date.substr(4, 17);
        dateStamp.innerHTML = date2;
    
</script>
<main>
	<iframe src="https://www.youtube.com/embed/KQetemT1sWc"></iframe>   
    <a href="#!" onclick="stopThis()">Stop Playing</a>
</main>

<script>
  function stopThis(){
      var iframe = container.getElementsByTagName("iframe")[0];
      var url = iframe.getAttribute('src');
      iframe.setAttribute('src', '');
      iframe.setAttribute('src', url);
  }
</script>
db.students.update(
   { _id: 1 },
   { $push: { scores: 89 } }
)
<button id="open-sesame">Open</button>

                <script>
                    var openSesame = document.getElementById('open-sesame');
                    openSesame.addEventListener("click", function(){
                        $('.sidenav').sidenav('open');
                    });
                </script>
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var slug = require('mongoose-slug-generator');

mongoose.plugin(slug);

const pageSchema = new Schema({
    title: { type: String , required: true},
    slug: { type: String, slug: "title" }
});

var Page = mongoose.model('Page', pageSchema);
module.exports = Page;
//Link javascript file in your project
<script type="text/javascript" src="/javascripts/main.js"></script>

//Link javascript file from web (usually found in documentation)
 <script src="https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js"></script>
function copyToClipboard(){

    var codeToBeCopied = document.getElementById('code-snippet').innerText;
    var emptyArea = document.createElement('TEXTAREA');
    emptyArea.innerHTML = codeToBeCopied;
    const parentElement = document.getElementById('post-title');
    parentElement.appendChild(emptyArea);

    emptyArea.select();
    document.execCommand('copy');

    parentElement.removeChild(emptyArea);
    M.toast({html: 'Code copied to clipboard'})

    }
var newForm = document.getElementById('new-form');

if ( newForm.getAttribute('class') === 'make-blue' ) {
        //  Do something
    }  
<form action="/new" method="post">
 
  <input name="title" type="text">
  <input name="description" type="text">
  <button type="submit">Submit Form</button>
 
</form>
> More steps
<h2 style="text-align:center">Modal Image Gallery</h2>
<div class="row">
  <div class="column">
    <img src="placeholder.png" style="width:100%" onclick="openModal();currentSlide(1)" class="hover-shadow cursor">
  </div>
  <div class="column">
    <img src="placeholder.png" style="width:100%" onclick="openModal();currentSlide(2)" class="hover-shadow cursor">
  </div>
  <div class="column">
    <img src="placeholder.png" style="width:100%" onclick="openModal();currentSlide(3)" class="hover-shadow cursor">
  </div>
  <div class="column">
    <img src="placeholder.png" style="width:100%" onclick="openModal();currentSlide(4)" class="hover-shadow cursor">
  </div>
</div>
<div id="myModal" class="modal">
  <span class="close cursor" onclick="closeModal()">&times;</span>
  <div class="modal-content">
    <div class="mySlides">
      <div class="numbertext">1 / 4</div>
      <img src="placeholder.png" style="width:100%">
    </div>
    <div class="mySlides">
      <div class="numbertext">2 / 4</div>
      <img src="placeholder.png" style="width:100%">
    </div>
    <div class="mySlides">
      <div class="numbertext">3 / 4</div>
      <img src="placeholder.png" style="width:100%">
    </div>
    <div class="mySlides">
      <div class="numbertext">4 / 4</div>
      <img src="placeholder.png" style="width:100%">
    </div>
    <a class="prev" onclick="plusSlides(-1)">&#10094;</a>
    <a class="next" onclick="plusSlides(1)">&#10095;</a>
    <div class="caption-container">
      <p id="caption"></p>
    </div>
    <div class="column">
      <img class="demo cursor" src="placeholder.png" style="width:100%" onclick="currentSlide(1)" alt="Sample image 1">
    </div>
    <div class="column">
      <img class="demo cursor" src="placeholder.png" style="width:100%" onclick="currentSlide(2)" alt="Sample image 2">
    </div>
    <div class="column">
      <img class="demo cursor" src="placeholder.png" style="width:100%" onclick="currentSlide(3)" alt="Sample image 3">
    </div>
    <div class="column">
      <img class="demo cursor" src="placeholder.png" style="width:100%" onclick="currentSlide(4)" alt="Sample image 4">
    </div>
  </div>
</div>
> More steps
const songs[];
const results;

for (var i, i++, i<songs.length){
    if(song[i].artist == "Drake"){
      result.push(songs[i]);
    };

// OR

const songs [];
const result = songs.filter ( song => song.artist == "Drake");
var allActionButtons = document.getElementsByClassName("action-buttons");

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

  allActionButtons[i].addEventListener('click', functionToRunWhenClicked, false);

}

var functionToRunWhenClicked = function {
  // Add some stuff here
}
<link rel="stylesheet" type="text/css" href="plugin/codemirror/lib/codemirror.css">

<body>
	<textarea class="codemirror-textarea"></textarea>
</body>

<script>

$(document).ready(function(){
    var codeText = $(".codemirror-textarea")[0];
    var editor = CodeMirror.fromTextArea(codeText, {
        lineNumbers : true
    });
});

</script>

<script type="text/javascript" src="plugin/codemirror/lib/codemirror.js"></script>
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

const exampleSchema = new Schema({
    title: { type: String , required: true},
    content: [{type: String}]
});


var Example = mongoose.model('Example', exampleSchema);
module.exports = Example;
> More steps
<h2 id="lastHeading">Thank you for reading</h2>
> More steps
<h2 class="redHeading">Welcome</h2>
<p>A passage of text</p>
<h2 class="redHeading">Thank you</h2>
> More steps
(function(){
    //
    var $posts = $('#posts li');
    var $search = $('#search');
    var cache = [];

    $posts.each(function(){
        cache.push({
            element: this,
            title: this.title.trim().toLowerCase(),
        });
    });

    function filter(){
        var query = this.value;
        console.log("query is "+query);
        cache.forEach(function(post){
            var index = 0;

            if (query) {
                index = post.title.indexOf(query);

            }
            var results = document.getElementsByClassName('search-results');
            results.innerHTML = "<li>"+cache.title+"</li>";
            post.element.style.display = index === -1 ? 'none' : '';
        });
    }

   if ('oninput' in $search[0]){
        $search.on('input', filter);
    } else {
        $search.on('keyup', filter);
    }

}());
          <!-- Intuitive Cron format input -->
          <label> Reportes Programados </label>
          <md-button-toggle md-single>
            <md-tooltip md-direction="bottom">Los reportes se pueden enviar periodicamente (cada cierto tiempo cada ciertos dias) o a una hora fija cada ciertos dias.</md-tooltip>
            <md-button v-on:click='cron_type="periodically"' v-bind:class='{"md-toggle": cron_type == "periodically"}'> <md-icon>publish</md-icon> Periodicamente </md-button>
            <!-- <md-button v-on:click='cron_type="timeFrame"' v-bind:class='{"md-toggle": cron_type == "timeFrame"}'> <md-icon>publish</md-icon> Periodicamente en un rango de tiempo</md-button> -->
            <md-button v-on:click='cron_type="fixedTime"' v-bind:class='{"md-toggle": cron_type == "fixedTime"}'> <md-icon>publish</md-icon> Hora fija recurrente </md-button>
          </md-button-toggle>

          <div v-if="cron_type==='periodically'">
            <md-button-toggle md-single>
              <md-button v-on:click='periodicity="minutes"' v-bind:class='{"md-toggle": periodicity == "minutes"}'> Minutos </md-button>
              <md-button v-on:click='periodicity="hours"' v-bind:class='{"md-toggle": periodicity == "hours"}'> Horas </md-button>
            </md-button-toggle>

            <md-input-container>
              <md-tooltip md-direction="bottom">Cada cuantos minutos será enviado el reporte.</md-tooltip>
              <label v-if="periodicity=='minutes'">¿Cada cuantos minutos?</label>
              <label v-if="periodicity=='hours'">¿Cada cuantas horas?</label>
              <md-input v-if="periodicity=='minutes'" numeric v-model='every_x_minutes'></md-input>
              <md-input v-if="periodicity=='hours'" numeric v-model='every_x_hours'></md-input>
            </md-input-container>  

            <md-button-toggle md-single>
              <md-button v-on:click='day_type="week_days"' v-bind:class='{"md-toggle": day_type == "week_days"}'> Días de la semana </md-button>
              <md-button v-on:click='day_type="month_days"' v-bind:class='{"md-toggle": day_type == "month_days"}'> Días del mes </md-button>
            </md-button-toggle>

            <md-input-container v-if="day_type=='week_days'">
              <md-tooltip md-direction="bottom">Día en que será enviado el reporte. Deje en blanco para que sea ninguno</md-tooltip>
              <label >¿Qué día de la semana?</label>
                <md-select v-model="week_day" placeholder="Día de la semana">
                  <md-option value='1'>Lunes</md-option>
                  <md-option value='2'>Martes</md-option>
                  <md-option value='3'>Miércoles</md-option>
                  <md-option value='4'>Jueves</md-option>
                  <md-option value='5'>Viernes</md-option>
                  <md-option value='6'>Sábado</md-option>
                  <md-option value='7'>Domingo</md-option>
                  <md-option value="*">Todos los días</md-option>
                </md-select>
            </md-input-container>  

            <md-input-container v-if="day_type=='month_days'">
              <md-tooltip md-direction="bottom">Día en que será enviado el reporte.</md-tooltip>
              <label >¿Qué día del mes?</label>
              <md-input numeric v-model='month_day'></md-input>
            </md-input-container>  
          </div>

          <div v-else>
            <md-input-container>
              <md-tooltip md-direction="bottom">Hora a la que el reporte será enviado en los días deseados</md-tooltip>
              <label >¿A qué hora?</label>
                <md-select v-model="recurrent_fixed_time" placeholder="Hora del día">
                  <md-option value='0'>Media noche</md-option>
                  <md-option value='1'>1:00 AM</md-option>
                  <md-option value='2'>2:00 AM</md-option>
                  <md-option value='3'>3:00 AM</md-option>
                  <md-option value='4'>4:00 AM</md-option>
                  <md-option value='5'>5:00 AM</md-option>
                  <md-option value='6'>6:00 AM</md-option>
                  <md-option value="7">7:00 AM</md-option>
                  <md-option value="8">8:00 AM</md-option>
                  <md-option value="9">9:00 AM</md-option>
                  <md-option value="10">10:00 AM</md-option>
                  <md-option value="11">11:00 AM</md-option>
                  <md-option value="12">Medio día</md-option>
                  <md-option value="13">1:00 PM</md-option>
                  <md-option value="14">2:00 PM</md-option>
                  <md-option value="15">3:00 PM</md-option>
                  <md-option value="16">4:00 PM</md-option>
                  <md-option value="17">5:00 PM</md-option>
                  <md-option value="18">6:00 PM</md-option>
                  <md-option value="19">7:00 PM</md-option>
                  <md-option value="20">8:00 PM</md-option>
                  <md-option value="21">9:00 PM</md-option>
                  <md-option value="22">10:00 PM</md-option>
                  <md-option value="23">11:00 PM</md-option>
                </md-select>
            </md-input-container>  

            <md-button-toggle md-single>
              <md-button v-on:click='day_type="week_days"' v-bind:class='{"md-toggle": day_type == "week_days"}'> Días de la semana </md-button>
              <md-button v-on:click='day_type="month_days"' v-bind:class='{"md-toggle": day_type == "month_days"}'> Días del mes </md-button>
            </md-button-toggle>

            <md-input-container v-if="day_type=='week_days'">
              <md-tooltip md-direction="bottom">Día en que será enviado el reporte. Deje en blanco para que sea ninguno</md-tooltip>
              <label >¿Qué día de la semana?</label>
                <md-select v-model="week_day" placeholder="Día de la semana">
                  <md-option value='1'>Lunes</md-option>
                  <md-option value='2'>Martes</md-option>
                  <md-option value='3'>Miércoles</md-option>
                  <md-option value='4'>Jueves</md-option>
                  <md-option value='5'>Viernes</md-option>
                  <md-option value='6'>Sábado</md-option>
                  <md-option value='7'>Domingo</md-option>
                  <md-option value="*">Todos los días</md-option>
                </md-select>
            </md-input-container>  

            <md-input-container v-if="day_type=='month_days'">
              <md-tooltip md-direction="bottom">Día en que será enviado el reporte.</md-tooltip>
              <label >¿Qué día del mes?</label>
              <md-input numeric v-model='month_day'></md-input>
            </md-input-container>  
          </div>
> More steps
var d = new Date();
var n = d.getFullYear();
<body>

	//Some HTML code here...

</body>


<script>

	//Insert javascript code here...

</script>
const randomElement = document.getElementById('someElement');
randomElement.innerHTML = '<p>changing the DOM</p>'
var eventsVariable = '"{events":[' +
    '{"location": "New York", "date": "May 1", "public": "true"},' +
    '{"location": "London", "date": "Apr 24", "public": "false"},' +
    '{"location": "San Frans", "date": "Nov 30", "public": "false"}]}';
    
bookmark
dashboard

Fri Oct 23 2020 16:29:07 GMT+0000 (UTC) https://stackoverflow.com/a/53187807

#javascript
bookmark
dashboard

Fri Oct 23 2020 13:41:09 GMT+0000 (UTC) https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement

#javascript #html
bookmark
dashboard

Fri Oct 23 2020 10:25:06 GMT+0000 (UTC) https://gist.github.com/mir4ef/c172583bdb968951d9e57fb50d44c3f7

#javascript #typescript
bookmark
dashboard

Fri Oct 23 2020 10:04:57 GMT+0000 (UTC) https://github.com/angular/angularfire/blob/master/sample/src/app/app.module.ts

#angular #javascript
bookmark
dashboard

Fri Oct 23 2020 07:41:59 GMT+0000 (UTC) https://medium.com/@gemma.stiles/breaking-down-the-dom-dd197e4f7154

#javascript
bookmark
dashboard

Fri Oct 23 2020 02:34:31 GMT+0000 (UTC) https://stackoverflow.com/questions/15748656/javascript-reduce-on-object

#javascript
bookmark
dashboard

Wed Oct 21 2020 17:11:43 GMT+0000 (UTC) https://stackoverflow.com/questions/12713564/function-in-javascript-that-can-be-called-only-once

#javascript
bookmark
dashboard

Wed Oct 21 2020 15:28:14 GMT+0000 (UTC) https://gist.github.com/nrojas13/68b79e21d0c81aa22ad762c9a4db38d0

#javascript
bookmark
dashboard

Tue Oct 20 2020 07:22:51 GMT+0000 (UTC)

#javascript #react.js
bookmark
dashboard

Mon Oct 19 2020 13:23:59 GMT+0000 (UTC) https://stackoverflow.com/questions/29349684/how-can-i-specify-the-required-node-js-version-in-package-json

#javascript
bookmark
dashboard

Sun Oct 18 2020 22:43:43 GMT+0000 (UTC) https://stackoverflow.com/questions/1063007/how-to-sort-an-array-of-integers-correctly

#javascript
bookmark
dashboard

Thu Oct 15 2020 18:03:39 GMT+0000 (UTC)

#javascript
bookmark
dashboard

Thu Oct 15 2020 17:58:25 GMT+0000 (UTC)

#javascript
bookmark
dashboard

Thu Oct 15 2020 07:34:37 GMT+0000 (UTC) https://madza.hashnode.dev/24-modern-es6-code-snippets-to-solve-practical-js-problems?guid

#javascript #date
bookmark
dashboard

Sat Oct 10 2020 17:41:42 GMT+0000 (UTC) https://stackoverflow.com/questions/61056021/improve-mongoose-validation-error-handling

#javascript #nodejs #mongoose
bookmark
dashboard

Fri Oct 09 2020 23:22:52 GMT+0000 (UTC) https://github.com/716green/graphql-express-setup/blob/main/server.js

#nodejs #javascript #graphql #express
bookmark
dashboard

Mon Oct 05 2020 12:39:26 GMT+0000 (UTC)

#perfomance #javascript #console
bookmark
dashboard

Fri Oct 02 2020 17:48:13 GMT+0000 (UTC) https://csspl.us/

#javascript #css
bookmark
dashboard

Fri Oct 02 2020 03:33:38 GMT+0000 (UTC) https://stackoverflow.com/questions/9781218/how-to-change-node-jss-console-font-color

#javascript
bookmark
dashboard

Thu Oct 01 2020 15:10:36 GMT+0000 (UTC) https://stackoverflow.com/questions/55436821/using-immutability-helper-with-array-object-map

#javascript
bookmark
dashboard