• Delete shell history

    You can login as the user you want to delete history from and then use the following command. For example if you want to delete from root

    sudo -i
    cat /dev/null > ~/.bash_history && history -c && exit
    
  • Automate total backups using crontab

    sudo crontab -e
    

    The following cronjobs will run every hour. Make sure you replace the database connection string values (make sure you have the right privileges on the database being used.) and backup folder paths with the appropriate ones.

    0 * * * * cd /cron/backup && tar -zcvf backup.tar.gz /var/www/html/
    0 * * * *  mysqldump -u user_name -p'password' db_name> /cron/backup/backup.sql
    

    Now save the changes and restart the cron service.

    Ctrl+O
    Enter
    Ctrl+X
    sudo service cron restart
    
  • Optimize all the tables in your database using cronjobs

    This php script repairs and optimizes all the tables in the selected database. Make sure you provide the right values in the connection string.

    Script

    optimize.php

     $tablename)
       {
           if(mysqli_query($link,"REPAIR TABLE `$tablename`")) 
               { 
               echo '\nRepair Success: '.$tablename;
                }
           else 
             die(mysqli_error($link));
           if(mysqli_query($link,"OPTIMIZE TABLE `$tablename`")) 
              { 
               echo '\nOptmize Success: '.$tablename;
              }
           else
              die(mysqli_error($link));
       }
    }
    
    mysqli_close($link);
    
    

    Cronjob

    crontab -e
    0 * * * * php /var/www/html/optimize.php
    Ctrl+O
    Enter
    Ctrl+X
    sudo service cron restart
    
  • Learn how to schedule MySQL jobs

    I am using MariaDB 5.x for this post. However this should work on most recent MySQL databases.
    Make sure that MySQL server is running and login with the root or with the user that has privileges of creating events on the database you would like to use.

    mysql -u root -p password123 db_name
    SET GLOBAL event_scheduler = ON;
    

    (or)

    mysql -u root -p
    SET GLOBAL event_scheduler = ON;
    use db_name;
    
    CREATE EVENT e_hourly
        ON SCHEDULE
          EVERY 1 HOUR
        COMMENT 'Clears out not active users after 24 hours of link being sent.'
        DO
          DELETE FROM Users_table WHERE activated='n' AND DATEDIFF( NOW(),  time ) >1;
    

    The above statement will create an event that runs every hour starting from the moment you execute this script. But if you want it to start executing at some other time (ex: January 30th 2018 at 00:00), then you can use the START command in the following way.

    CREATE EVENT 
      ON SCHEDULE 
        EVERY 1 DAY
          STARTS '2018-01-30 00:00:00'
        COMMENT 'Clears out not active users after 24 hours of link being sent.'
    DO
    DELETE FROM Users_table_message WHERE activated='n' AND DATEDIFF( NOW(),  time ) >1;
    
    SHOW EVENTS;

    Cronjobs using Crontab

    This can also be done directly using crontab and scheduling a cronjob. Consider the following code for example.

    crontab -e

    This will usually open crontab file with the nano editor.

    #!/bin/bash
    mysql --user=root --password=password123 --database=db_name --execute="DELETE FROM Users_table WHERE activated='n' AND DATEDIFF( NOW(),  time ) >1"
    

    Now to save the changes to disk and exit while using the nano editor, use the following commands.

    Ctrl+O
    Enter
    Ctrl+X
    

    Scripts

    You can also use php scripts to run the mysql query. For example the following script runs every hour.

    0 * * * * /usr/local/bin/php /var/www/html/clean_mysql_script.php
    
  • Disable Jetpack Site Stats

    Make sure you are logged into the WordPress admin console and that you have necessary permissions to toggle the Jetpack modules and navigate to the following link after replacing the domain name with yours. Here you should be able to easily activate and deactivate the Jetpack list of modules easily.
    https://www.url-here.com/wp-admin/admin.php?page=jetpack_modules

  • Hopper Tower Problem using Dynamic Programming

    Write a function to determine whether a person can reach the other end of the array if he starts at index 0 and if he cannot hop more than the value contained at that index.

    var jumper = [];
    var arr = [4, 0, 0, 1];
    
    function hopper(index) {
      if (index + arr[index] >= arr.length) {
        jumper[index] = true;
        return;
      } else {
        for (var i = index + 1; i <= index + arr[index]; i++) {
          if (jumper[i]) {
            jumper[index] = true;
            return;
          }
        }
        jumper[index] = false;
      }
    }
    
    function isReachable() {
      for (var j = arr.length - 1; j >= 0; j--) {
        hopper(j);
      }
      return jumper[0];
    }
    
    isReachable()
    

    Output

    isReachable => true
    jumper => [true, false, false, true]
    

    Time Complexity: O(n^2)
    Space Complexity: O(n)
    Demo

    Get Minimum Hops

    To get the minimum hops, now we need to keep track of the hops at each index using another array or we can create a Data Structure (here Object) to keep track of them.

    var jumper = [];
    var mjumper = [];
    var arr = [4, 1, 1, 1];
    
    function hopper(index) {
      if (index + arr[index] >= arr.length) {
        jumper[index] = true;
        mjumper[index] = 1;
      } else {
        for (var i = index + 1; i <= index + arr[index]; i++) {
          if (jumper[i]) {
            if (jumper[index]) {
              mjumper[index] = Math.min(mjumper[i] + 1, mjumper[index]);
            } else {
              jumper[index] = true;
              mjumper[index] = mjumper[i] + 1;
            }
          }
        }
        if (!jumper[index]) {
          jumper[index] = false;
        }
      }
    }
    
    function getMinimumSteps() {
      for (var j = arr.length - 1; j >= 0; j--) {
        hopper(j);
      }
    
      if (jumper[0])
        return mjumper[0];
      else return -1;
    }
    
    getMinimumSteps();
    

    Output

    1
    

    Time Complexity: O(n^2)
    Space Complexity: O(n)
    Demo

  • SimpleJS lightweight javascript library

    SimpleJS is a lightweight javascript library to get you started on plane javascript project that doesn’t need libraries to start with.
    Some of the major functionality includes the following.

    • Manipulate Cookies.
    • Make GET, POST calls with JSON data.
    • Load attributes to an element by passing an object.
    • Insert element before an element in DOM.
    • Get Parent element in DOM.
  • Calculate time ago string in Angular 5

    github

    import {timeAgo} from './time-ago.ts';
    ...
    // Pass Date Object and it returns a string.
    timeAgo(new Date());
    

    You need to pass a date object and this method returns a string. This is compatible with Angular 5.0.3.

  • Using bootstrap 4 modal with Angular 5

    Make sure you have jquery and bootstrap installed.
    or else you can use the following commands.

    npm i jquery bootstrap@4.0.0-beta.2 --save
    

    If you are using angular-cli, then you need to include the jquery in the scripts section of .angular-cli.json file. The same goes with bootstrap files as well. My file looks somewhat similar to the following.

    "styles": [
            "../node_modules/bootstrap/dist/css/bootstrap.min.css",
            "../node_modules/font-awesome/css/font-awesome.min.css",
            "styles.scss"
          ],
          "scripts": [
            "../node_modules/jquery/dist/jquery.slim.min.js",
            "../node_modules/popper.js/dist/umd/popper.min.js",
            "../node_modules/bootstrap/dist/js/bootstrap.min.js"
          ],
    

    Here is the HTML you would want to use to trigger the modal to show up. The fade class is removed from the modal with id = “exampleModal” when the button with the attributes data-toggle = “modal” data-target = “#exampleModal” is clicked.

    HTML

    
    
    
    
    
    

    Programmatically

    If you want trigger the opening and closing of the modal programmatically, then use the following in your methods inside the component with the above HTML after installing the required.

    npm install @types/jquery --save
    

    This is the best approach if all that we want to use is the modal. We can avoid the overhead of an angular wrapper around bootstrap jQuery functions.
    Now in the component in which you are using jQuery import it as the following.

    import * as $ from 'jquery';
    
    // opening
    $('#modalTrigger').click();
    
    // closing
     $('#postJobModalClose').click();
    
  • Using multiple guards for a route in Angular

    The canActivate( ) method which should be overridden, should return only one of the following types

    • Observable<boolean>
    • Promise<boolean>
    • boolean

    The multiple routes work like an ‘&&’ condition in javascript, i.e., angular won’t execute the later guards, if the first one fails.

    app-routing.module

    import {NgModule} from '@angular/core';
    import {Routes, RouterModule} from '@angular/router';
    
    import {HomeComponent} from './home.component';
    import {GuardOne} from './guard-one.guard';
    import {GuardTwo} from './guard-two.guard';
    
    const routes: Routes = [
        {
            path: '',
            redirectTo: '/home',
            pathMatch: 'full'
        },
        {
            path: 'home',
            canActivate: [GuardOne, GuardTwo],
            component: HomeComponent,
        }
    ];
    
    @NgModule({
        imports: [RouterModule.forRoot(routes)],
        exports: [RouterModule]
    })
    export class AppRoutingModule {
    }
    

    guard-one.guard

    import {Injectable} from '@angular/core';
    import {Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
    
    import {LoginService} from './user.service';
    
    @Injectable()
    export class GuardOne implements CanActivate {
    
        constructor(private router: Router, private userLoginSer: LoginService) {
        }
    
        canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
            if (!this.userLoginSer.user) {
             // you can send them to some other route like this.
             // this.router.navigate(['/nonUserHome']);
                return false;
            } else {
                return true;
            }
        }
    }
    

    guard-two.guard

    import {Injectable} from '@angular/core';
    import {Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot} from '@angular/router';
    
    import {LoginService} from './user.service';
    
    @Injectable()
    export class GuardTwo implements CanActivate {
    
        constructor(private router: Router, private userLoginSer: LoginService) {
        }
    
        canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
            if (!this.userLoginSer.login) {
             // you can send them to some other route like this.
             // this.router.navigate(['/login']);
                return false;
            } else {
                return true;
            }
        }
    }
    

    The login service that is being used above can be somewhat like this:

    guard-two.guard

    import {Injectable} from '@angular/core';
    import {HttpClient} from '@angular/common/http';
    
    @Injectable()
    export class LoginService {
        login = true;
        user = true;
    
        constructor(private http: HttpClient) {
        }
    }
    

    For these files to work, you need to add them to the app.module.ts and also use in the main component where you would like to use the router.