Category: Uncategorized

  • Check if input is a number in PHP 7.1.x

    is_int()

    The is_int() doesn’t tell you if the string is actually a number, instead it returns false.

    
    

    If you convert your string numeric into an int and then do this, only then will it work. But there is a problem with this approach, while converting string to an int, we use intval(). This converts strings to 0's.

    
    

    is_numeric()

    So the best way to find out whether a variable is an actual numeric or not is to use this php function.

    
    
  • Delete Cookies in JavaScript

    Deleting a cookie stored in a browser using JavaScript is very easy. For example if you have a cookie named token in your browser and want to delete it, all you have to do is provide the cookie name and set it to a past date. This deletes it immediately. You can take a look at cookies in chrome’s developer tools.
    Cookies

    function setCookie(name, value, days) {
      var d = new Date();
      d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
      var expires = 'expires=' + d.toUTCString();
      document.cookie = name + '=' + value + ';' + expires + ';path=/';
    }
    
    function deleteCookie(name) {
      document.cookie = name + '=;expires=' + new Date(1970, 0, 1).toUTCString() + ';path=/'
    }
    
    setCookie('token', 'value here', 1);
    
    deleteCookie('token');
    

    Demo

  • Add HTTP Intercepter in Angular 4

    Creating a HTTP Intercepter

    Angular V4.4.4
    We need to inherit the ‘HttpIntercepter’ class and override the ‘intercept’ method to be able to intercept all the HTTP requests you make using ‘HttpClient’.
    auth-interceptor.ts

    import {Injectable} from '@angular/core';
    import {Observable} from 'rxjs/Observable';
    // import 'rxjs/add/operator/do';
    import {HttpEvent, HttpResponse, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http';
     
    @Injectable()
    export class AuthInterceptor implements HttpInterceptor {
      constructor(private auth: AuthService) {}
     
      intercept(req: HttpRequest, next: HttpHandler): Observable> {
        // Clone the request as it is immutable. You can also save the original request in the following way
        // const prevReq = req.clone();
        const authReq = req.clone({headers: req.headers.set('Authorization', 'Bearer ' + getToken())});
        // or you can use the shorter version of the same.
        //const authReq = req.clone({setHeaders: {Authorization: 'Bearer ' + getToken()}});
        // Pass on the cloned request instead of the original request.
        return next.handle(authReq);
        /* you can test the above function by doing a console.log() here. For this you will need to import 'HttpResponse' and the 'do' operator.
         .do(event => {
            if (event instanceof HttpResponse) {    
              console.log(getToken());
            }
          });
       */
      }
    }

    Updating app.module.ts

    Now you need to include the ‘AuthInterceptor’ class as part of our main app module providers after you have imported ‘HTTP_INTERCEPTORS’.
    app.module.ts

    import {NgModule} from '@angular/core';
    import {AuthInterceptor} from './auth-interceptor'
    import {HTTP_INTERCEPTORS} from '@angular/common/http';
    
    @NgModule({
      providers: [{
        provide: HTTP_INTERCEPTORS,
        useClass: AuthInterceptor,
        multi: true,
      }],
    })
    export class AppModule {}
    
  • Simple Javascript function to convert to timeAgo.js

    Calculate the time difference for javascript date objects in years, months, days, hours, minutes and seconds. Whether they are in the future or in the past. The function accounts for all very easily. Since this is a lightweight function you can easily use this as part of any application, without incurring much overhead.

    Code

    var timeAgo = function(date) {
      var d = new Date();
      var UTCsecondsNow = (d.getTime() + d.getTimezoneOffset() * 60 * 1000);
      var UTCseconds = (date.getTime() + date.getTimezoneOffset() * 60 * 1000);
      var diff = UTCsecondsNow - UTCseconds;
      var tense = 'ago';
      if (diff < 0) {
        tense = 'later';
        diff = Math.abs(diff);
      }
      if (diff === 0) return 0;
      // 365.25 * 24 * 60 * 60 * 1000
      var years = singular(Math.round(diff / 31557600000), 'Year');
      if (years)
        return years + tense;
      var months = singular(Math.round(diff / 2592000000), 'Month');
      if (months)
        return months + tense;
      var days = singular(Math.round(diff / 86400000), 'Day');
      if (days)
        return days + tense;
      var hours = singular(Math.round(diff / 3600000), 'Hour');
      if (hours)
        return hours + tense;
      var mins = singular(Math.round(diff / 60000), 'Minute');
      if (mins)
        return mins + tense;
      var secs = singular(Math.round(diff / 1000), 'Second');
      if (secs)
        return secs + tense;
    };
    
    var singular = function(num, str) {
      if (num > 1) {
        if (num === 1)
          return '1 ' + str + ' ';
        else
          return num + ' ' + str + 's ';
      }
      return '';
    };
    

    Usage

    timeAgo( new Date('2016-12-04T11:45:00.000Z') )

    Output

    10 Months ago

  • Refresh your app automatically in the browser with gulp & livereload

    Add livereload to your dev in 5 mins

    You will need to install gulp-server-livereload for this. This utilizes web sockets. Make sure you have a compatible version of node+npm before you run this. This will install gulp-server-livereload as a dev dependency in your node modules folder and add it to your package.json file.

    npm i gulp-server-livereload --save -D

    Add the following code to gulpfile.js and run gulp livereload, it should open up your default browser and load your app at localhost:8000.
    Note: Make sure you have an index.html file in your app inside the public folder.

    var gulp = require('gulp');
    var server = require('gulp-server-livereload');
    gulp.task('livereload', function() {
      gulp.src('public')
        .pipe(server({
          livereload: true,
          directoryListing: false,
          open: true
        }));
    });
    
  • Invalid Object & Array Manipulations in Vue.js 2

    Objects

      let obj = {name: 'Shiva'
                 occupation: 'coder'}
    delete obj.name
    // or delete obj['name']
    obj.name = 'Charan'
    // or obj['name'] = 'Charan'
    

    This is how you would usually set delete/add/set properties in Javascript. But Vue.js 2 can’t detect the changes if the object is manipulated in this fashion.
    For it to be able to detect these changes, use the following.

    Vue.set(obj, 'name', 'Shiva')
    

    or

    this.$set(obj, 'name', 'Shiva')
    

    Arrays

    Similarly for arrays, if we use the following, then Vue.js 2 fails to detect the changes in state.

    let arr = [1,2,3,4]
    arr[0] = 9
    

    You will have to use the following commands to be able to deal with the above situation and many others.
    Vue.js 2 has wrapped methods to help us create work arounds for such issues.

    // Vue.set
    this.$set(arr, 0, 9)
    // or
    arr.splice(0, 1, 9)

    Wrapped methods

    • push()
    • pop()
    • shift()
    • unshift()
    • splice()
    • sort()
    • reverse()
  • async & await in ES2017/ES8

    async

    Adding an async keyword to a function makes it asynchronous as the name itself suggests and it also return a promise instead of the value. We can define an ES6 function as async using the following syntax. This works with the old function syntax as well.

    let myFunc = async() => {
      return 'Hi I am async!';
    };
    console.log(myFunc());
    // logs Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: "Hi I am async!"}
    
    /* Resolving a promise */
    myFunc().then((result) => {
      console.log(result);
    // logs: Hi I am async!
    }).catch((err) => {
      console.log(err);
    });
    

    await

    The await keyword can only be used inside an async function. When used, while calling an async function, it resolves the promise and returns the value.
    The above code can be made more readable, by using the await keyword.

    let myFunc = async() => {
      return 'Hi I am async!';
    };
    let finalSync = async() => {
      console.log(await firstAsyncFunc());
    // logs: Hi I am async
    };
    finalSync();
    

    Here is a live example of asynchronous functions in action. Although the first function is called first, we don’t have to wait until the promise is resolved to a result by await, instead we can see rest of the functions calls and their promises being resolved earlier.
    Code

    let firstAsyncFunc = async() => {
      setTimeout(function() {
        console.log('First');
      }, 3000);
    };
    let secondAsyncFunc = async() => {
      console.log('Second');
    };
    let thirdAsyncFunc = async() => {
      return 'Third';
    };
    let finalSync = async() => {
      await firstAsyncFunc();
      await secondAsyncFunc();
      console.log(await thirdAsyncFunc());
    };
    finalSync();
    

    Output

    Second
    Third
    First
    

    Demo

    Sequential calls vs Parallel calls

    The following is an example of sequential asynchronous function calls

    let finalSync = async() => {
      await firstAsyncFunc();
      await secondAsyncFunc();
    };
    finalSync();
    

    If you want to make asynchronous function calls simultaneously, then you could use Promise.all and supply it with an array of asynchronous functions and then use await to return the result after all the calls are made.

    let finalSync = async () => {
      await Promise.all([async1(), async2()]);
    }
    finalSync();
    
  • ES2016/ES7 in 5 Minutes

    The ECMAScript 2016 has just two small changes.

    Array.prototype.includes()

    Return type: boolean

    Usage

    let numbers = [1, 2, 3, 4];
    let arr = new Array('a', 'b', 'c', 'd');
    console.log(numbers.includes(2));
    console.log(numbers.includes(8));
    console.log(arr.includes('a'));
    

    Output

    true
    false
    true
    

    Demo

    This replaces the array.indexOf(element) which returns the index if the element is found or -1 if it isnt. This new function allows you to check for NaN (Not a Number) and this works on objects in a array too, but they must match the instance being passed.

    The Exponentiation Operator (**)

    Usage

    let num1 = 3;
    let num2 = 2;
    console.log(3 ** 2);

    Output

    9
    

    Demo

    This replaces the Math.pow(3, 2) function. This new operator allows for infix notation.

  • Vuex with vue-router and Bootstrap/jQuery

    This post talks about using the vue-router (official router for Vue.js 2) alongside Vuex (state management pattern + library).

    Using Vuex, gives you the ability to debug code easily, and switch between states in your chrome browser. For this you will need to install the Vue.js devtools chrome extension, and open the dev-tools in a page that uses Vue.js and then navigate to the Vue tab and choose the Vuex icon (usually 2nd from left).

    In the following code, the ability to add/delete widget objects is implemented using mutations in Vuex. Here mutations are synchronous calls that can alter the state. This state can be easily accessed through the mapGetters in Vuex. Following this pattern keeps the state management pretty clean in larger applications, where multiple parts of the applications get to access/alter the state.

    Note: You can also make asynchronous calls using actions in Vuex but, that part has not been included in the following code.

    I have used bootstrap for quick styling. The router is setup with the widgets view as default. This code was built using the default vue-cli webpack template, which makes life easier for running unit tests, end to end tests and also building production ready code.

    vuejs 2.0

    This is the default view of the demo application. Below you can view the debugging capabilities of Vuex.

    vuex

    Code (github)

  • Learn Angular CLI in 5 minutes

    Install

    Make sure you have node and npm installed and that they are available via the PATH variable on Windows.

    npm install -g @angular/cli

    Create a new application

    This following command will create a new application called collegestash in your current directory.
    This does npm install too by default. Here the –routing flag tells it to create a router and add it to the project. The –style scss also specifies that this project will be using scss (Saas) instead of css for styling.

    ng new collegestash --routing --style scss
     cd collegestash

    If you would like to be careful before you execute a command you can supply the -d flag which indicates a dry-run flag. The changes will not be written to disk, but you will be able to see the changes it will make in case the dry-run flag isn’t supplied.

    ng new cs -d
    
    
    installing ng You specified the dry-run flag, so no changes will be written. create .editorconfig create README.md create src\app\app.component.css create src\app\app.component.html create src\app\app.component.spec.ts create src\app\app.component.ts create src\app\app.module.ts create src\assets\.gitkeep create src\environments\environment.prod.ts create src\environments\environment.ts create src\favicon.ico create src\index.html create src\main.ts create src\polyfills.ts create src\styles.css create src\test.ts create src\tsconfig.app.json create src\tsconfig.spec.json create src\typings.d.ts create .angular-cli.json create e2e\app.e2e-spec.ts create e2e\app.po.ts create e2e\tsconfig.e2e.json create karma.conf.js create package.json create protractor.conf.js create tsconfig.json create tslint.json Project 'cs' successfully created.

    Component

    ng g c login
    

    or

    ng generate component login
    

    This generates a component called login in a separate folder.

    Service

    ng g s login
    

    or

    ng generate service login
    

    This generates a service called login but doesn’t add the provider, and generates it in the main folder. You need to specify --flat false to generate this in it's own folder. You can also the module in which you would like to include this by using the -m flag.

    ng g s login -m app.module --flat false
    

    If you know the folder where you would like to place the service. Then you could do the following to put it in a specific folder.

    ng g s login/login -m app.module
    

    Classes, Interfaces & enums

    Generate typescript classes, interfaces and enums.

    ng g cl models/classname
    ng g i models/interfacename
    ng g e models/enumname
    

    Pipes

    Generate a pipe.

    ng g p pipes/pipename

    Modules

    The following command generates a module called login in it’s own folder by default. No spec file is generated by default, hence we need to specify explicitly. You need to manually add this to your app.module to make sure they are linked together. Extra routing module gets created along with the required module.

    ng g m login –spec true --routing 
    

    Guard

    Generate a guard for routing.

    ng -g guard auth 
    

    Build

    This should build the application and output the files in build bundles with webpack runtime, app code, polyfills, styles, angular and other vendor files. You can supply the --prod flag to make sure the app is ready for production.

    ng build

    To be able to view sources, install the following and run the next command.

    npm i source-map-explorer –save-dev
    node_modules/ .bin/source-map-explorer dist/main.bundle.js
    

    ng build

    Build Environment vs Build Target

    Build Environment - Choosing an Environment
    Build Target - Refers to choosing whether or not to optimize.

    Serve

    This serves the app and opens it in your default browser.

    ng serve -o

    Add External Libraries

    You can use the angular-cli.json file and add them to styles and scripts arrays.

    Eject

    You can get away from the angular-cli dependency in the project.

    ng eject

    Unit Tests

    Runs all unit tests in the project, namely *.spec.ts files. Watches for changes and re runs them. So if you open this in a new terminal then this will, automatically detect the changes you make in the other terminal to the files in the project.

    ng test
    ng test -sr

    Setting the single run flag, can be best for use in Continuous Integration.
    (or)

    ng test -w false

    Setting watch to false gets the same result as above.

    ng test -cc
    

    The above command is for code coverage which is in the coverage folder by default unless something different is specified in the angular-cli.json file.

    End to end Testing

    This runs the end to end tests.

    ng e2e