Thursday, 15 December 2016

Configure the Project Specific Git Author/User Credential

If you working for two projects (may be one for work specific and another personal project) and you would like to configure the Git Author/User credential different for both, I mean as a project specific rather than as a global one.

You may have configured or can set as global credential as:
# To check the git configuration
git config -l

# To set the global git configuration
git config --global user.name "RC"
git config --global user.email "rc@example.com"
Now to change the credential for a project. First go the the project branch and check what's the credential it has and override with new credential using below command
# Go to the project folder first and make sure you already have git initiated.
cd ~/apps/project_folder

# To check the git configuration
git config -l

# To overwrite the name
git config user.name "RC Pro"

# To overwrite the email
git config user.email "personal@example.com"

Then, you all set for that.

Check Git for more

Monday, 26 September 2016

AngularJS filter to Translate input and replace variable separately afterwards into the translated input

Translate input and replace the variable afterwards on the string with variable placeholder ie. [variable].

First create AngularJs filter fiel called translate-input-var-and-replace.js and save with below content:
/* Translate input and replace the variable afterwards on the string with variable placeholder ie. [variable]. */
myapp.filter('translateInputWithVarReplace', ['$filter', function($filter) {
    return function(input, replaceVariable) {
        input = $filter('translate')(input);
        return input.replace(RegExp(/\[(.*?)\]/g), replaceVariable);
    };
}]);


Usage:
// The 'translated_string' should have the value containing the [variable] in the string. 
// translated_string = 'There will be [variable] people watching this movie.';

 var output = $filter('translateInputWithVarReplace')('translated_string', '545');

Expected Output:
There will be 545 people watching this movie.

Merging two or more JavaScript Objects using AngularJS

Please use below steps to merge two or more JavaScript Objects using AngularJS

// Object one
var jsObjectA = {title:'Buddha is born in Nepal', famous:'Gautum Buddha', country:'Nepal', district:'Bhirawa'};

// Object two
var jsObjectB = {religion:'Buddhism', zone:'Lumbini', district:'Kapilvastu'};

// Merging above two objects
var mergeObject = angular.extend({}, jsObjectA, jsObjectB); 

Expected Output:
{title:'Buddha is born in Nepal', famous:'Gautum Buddha', country:'Nepal', religion:'Buddhism', zone:'Lumbini', district:'Kapilvastu'};

Tuesday, 30 August 2016

AngularJS String Replace filter in the Template File

Please find follow the below steps to replace the string on the Template file using AngularJS filter:

1. Create the filter file called string-replace.js and add the following code.
myapp.filter('stringReplace', [ function() {
    return function(input, search, replace) {
        input = input.split(search);
        
        var x;
        var result = '';
        var prefix = '';
        for (x in input ) {
            result += prefix + input[x];
            prefix = replace;
        }

        return result;
        //return input.replace(search, replace);
    };
}]);

2. Then, in html template file, adopt the below example to use the filer.
{{your_string_variable_here | stringReplace:'searchParameterHere':'replaceParameterHere'}}

Example:
{{"GLOBAL_WARMING_NEEDS_TO_CONTROL_BY_EVERYONE" | stringReplace:'_':'-'}}

Output: GLOBAL-WARMING-NEEDS-TO-CONTROL-BY-EVERYONE

Monday, 6 June 2016

Resolving the issue with Gulp "Warning: gulp version mismatch:"

If you are getting the following types error:
[14:32:54] Warning: gulp version mismatch:
[14:32:54] Global gulp is 3.9.1
[14:32:54] Local gulp is 3.9.0
[14:32:56] Using gulpfile C:\xampp\htdocs\myproject\gulpfile.js
[14:32:56] Starting 'default'...
[14:32:56] Starting 'scripts'...
To resolve the issue,
First, go to your project root folder then run below two commands
npm update gulp -g 
npm update gulp

Thursday, 12 May 2016

List of Laravel Artisan Shortcuts (Alias) for Windows and MacOS

I would like to share the list of command alias I have created on my local to minimise the keystrokes with the Team.

Please go to the project root location via command line and just copy the below line (one line string) and run it:

alias cda="composer dump-autoload"; alias ci="composer install"; alias cu="composer update"; alias bi="bower install"; alias bu="bower update"; alias gi="gulp install"; alias ni="npm install"; alias pa="php artisan"; alias pam="php artisan migrate"; alias pamr="php artisan migrate:rollback"; alias pads="php artisan db:seed"; alias pades="php artisan db-exporter:seed"; alias pamm="php artisan make:migration"; alias pamc="php artisan make:controller"; alias pammd="php artisan make:model"; alias t="phpunit"; alias dat="php artisan app:droptables"; alias ga="git add"; alias gaa="git add ."; alias gc="git commit -m"; alias gp="git push"; alias gs="git status"; alias gl="git log"

The detail of the above string shortcut is below (if you want other way, feel free to change it with your comfort):

#Composer
alias cda="composer dump-autoload"
alias ci="composer install"
alias cu="composer update"

# Bower
alias bi="bower install"
alias bu="bower update"

# Gulp
alias gi="gulp install"
alias ggw="gulp && gulp watch"
# NPM alias ni="npm install" # Laravel alias pa="php artisan" alias pam="php artisan migrate" alias pamr="php artisan migrate:rollback" alias pads="php artisan db:seed" alias pades="php artisan db-exporter:seed" alias pamm="php artisan make:migration" alias pamc="php artisan make:controller" alias pammd="php artisan make:model" alias t="phpunit" # Laravel Custom alias dat="php artisan app:droptables" # Git alias ga="git add" alias gaa="git add ." alias gc="git commit -m" alias gp="git push" alias gs="git status" alias gl="git log"

Wednesday, 27 April 2016

Declare or concatenate two variables as a single variable in view (HTML) file using AngularJS

To Concatenate the two variable value using delimiter/underscore(_) in HTML using AngularJS
To print the same variable inline
{{new_variable}}
To Sum up and print the same variable inline, however for this, both variable_1 and variable_2 must have numerical values
{{new_variable}}

Friday, 15 April 2016

AngularJS DataTable Plugin Rending the HTML with Angular Event Tigger such as ng-click

To make the Angular action trigger from the DataTable plugin, you just need add the below code within the loadDataTable Function.

// Define this function first.
function createdRow(row, data, dataIndex) 
{
 // Recompiling so we can bind Angular directive to the DT
 $compile(angular.element(row).contents())(scope);
}

// Then, add the below line with the "DTOptionsBuilder.newOptions()"
.withOption('createdRow', createdRow);

Please find the sample complete function with above added code.
function getUsersDataTable(scope, $state, $stateParams, DTOptionsBuilder, DTColumnBuilder, DTColumnDefBuilder, $compile, $filter)
{
 scope.searchQuery = '';

 scope.dtInstanceCallback = function (dtInstance) {
  var datatableObj = dtInstance.DataTable;
  scope.tableInstance = datatableObj;
 };
 scope.searchTable = function () {
  var query = scope.searchQuery;

  scope.tableInstance.search(query).draw();
 };
   
 scope.dtOptions = DTOptionsBuilder.newOptions()
  .withOption('ajax', {
   dataSrc: 'data',
   url: 'api/v1/admin/users',
   type: 'GET'
  })
  .withOption('processing', true)
  .withOption('serverSide', true)
  //.withOption("sScrollX", "100%")
  .withDOM('rt<"table-tools-group"<"dt-paginate-wrapper"p><"dt-info-wrapper"i><"dt-length-wrapper"l><"clear">><"clear">')
  .withPaginationType('full')
  .withOption('createdRow', createdRow);

 function createdRow(row, data, dataIndex) 
 {
  // Recompiling so we can bind Angular directive to the DT
  $compile(angular.element(row).contents())(scope);
 }

 scope.dtColumns = [
  DTColumnBuilder.newColumn('id').withTitle('').renderWith(actionEditHtml).notSortable(),
  DTColumnBuilder.newColumn('first_name').withTitle('Name')
   .renderWith(function (data, type, full) {
    return full.first_name + ' ' + full.last_name;
   })
 ];
      
 function actionEditHtml(data, type, full, meta)
 {
  return '' +
   'edit';
 }     
  scope.edit = function (id) {
  console.log('edit id', id);
 }
}
Then, call the above function from the Angular Controller
/* Calling the above function from the Angular Controller */
getUsersDataTable($scope, $state, $stateParams, DTOptionsBuilder, DTColumnBuilder, DTColumnDefBuilder, $compile, $filter);

Below is the HTML Code for view file.

 
  

Adding the AngurJS filter to Capitalize the first word, all words or all UPPERCASE

First, create the file 'capitalize.js' with the following contents.
/* capitalize.js file contents */

myapp.filter('capitalize', function() {
    return function(input, all) {
        var reg = (all) ? /([^\W_]+[^\s-]*) */g : /([^\W_]+[^\s-]*)/;
        return (!!input) ? input.replace(reg, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}) : '';
    };
});

Then use the below example to adopt the code in your contexts;
To Capitalize the first word only
{{name | capitalize}} 
OUTPUT: "Hello world nepal"

To Capitalize the all words
{{name | capitalize:true}} 
OUTPUT: "Hello World Nepal"

The below example is for Data Table (angular-laravel library) rending html case:
/* In Data table rending html case */

var data = 'hello world nepal';
.renderWith(function (data, type, full) {
 return $filter('capitalize')(data)
})

// OUTPUT: "Hello world nepal"

.renderWith(function (data, type, full) {
 return $filter('capitalize')(data, true)
})
// OUTPUT: "Hello World Nepal"

/* and, For UPPERCASE */
.renderWith(function (data, type, full) {
 return data.toUpperCase();
})

// OUTPUT: "HELLO WORLD NEPAL"

Thursday, 31 March 2016

Get All First Letters or Abbreviation of Each Words of the sentence as a Abbreviated String using PHP

Please use the below function to pull all First Letters of Each Words of the sentence as a abbreviated String using PHP.

/**
 * Get the first letters or abbreviation of each words and as a uppercase string format.
 * @param $string Pass the parsing string
 * @return string String
 */
function getFirstLettersOfWords($string) {}
OR 
function getStringAbbreviation($string) 
{
 // Match the first letters of each words using regular expression.
 $matchFound= preg_match_all('/(\w)(\w+)/', $string, $matches);

 // Concatenate all the matched first letters as a string in upper case.
 $abbreviatedString= strtoupper( implode('', $matches[1]) );

 return $abbreviatedString;
}

Function Usage

$string1 = 'Distributor / Sub-Distributor';
$output1 = getStringAbbreviation($string1);

// Output: DSD

$string2 = 'Consultant (Registration, Licensing, Visa)';
$output2 = getStringAbbreviation($string2);

// Output: CRLV

Tuesday, 29 March 2016

Create the migrations for database views using php artisan in Laravel

Please follow the steps to create a sql views for Laravel using PHP Artisan using below step.

Step 1. Run below command:
php artisan make:migration create__views

Step 2. Open the migration file and add the below code:
    /**
    * Run the migrations.
    *
    * @return void
    */
    public function up()
    {
     //
     DB::statement("
      CREATE VIEW views_overall_status AS
      (
       SELECT er.id AS auth_users_entity_roles_id, er.auth_users_id,
        e.checklists_id, c.overall_status_id AS status_id, s.name AS status_name
       
       FROM `auth_users_entity_roles` er
        LEFT JOIN entities e ON e.id=er.entities_id
        LEFT JOIN `checklists` c ON c.id=e.checklists_id
        LEFT JOIN `status` s ON s.id = c.overall_status_id
        
       WHERE s.slug = 'operating_risks' AND e.deleted_at IS NULL
        AND c.deleted_at IS NULL
      )
     ");
    }
    
    /**
    * Reverse the migrations.
    *
    * @return void
    */
    public function down()
    {
     //
     DB::statement('DROP VIEW IF EXISTS views_overall_status');
    }

Step 3. To call and run the SQL Views via Laravel query
    $items = $DB::table('views_entities_by_overall_status')
                ->select('status_id', 'status_name', 'status_name_trans_text_id',
                    $DB::raw('count(entities_id) as counts')
                )
                ->groupBy('status_id')
                ->orderBy('counts' , 'desc')
                ->whereIn('entities_id', Auth::user()->getEntityRoleEntityIDs())
                ->get();
    print_r($items);

Hope that helps. Please let me know if anyone has better solution!!

Friday, 18 March 2016

How to User Current Version of Syntax Highlighter on Google Blogger


In order to install & use it on Google Blogger, follow the below steps:
  • First, go to your Template Layout-> Backup/ Restore  on the top right of the page to download your template as a backup.
  • After downloading your template, then click Edit HTML for Layout & then paste the below code in your Template before your < / head > tag ends.
Note: This below information is for the integrating the latest released (current) version; more information can be found at: http://alexgorbatchev.com/SyntaxHighlighter/integration.html

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 


Please let me know if you need further information.

Thursday, 10 March 2016

To Write a Sample Join Query in Laravel 5.2

Please follow the example below to write the the Multiple Join Query on Laravel 5.2
// NOTE: Please do not forgot add below line at the top to use DB instance
USE DB;
$whereClause = array( $this->table.".checklists_id" => 1 );
$items = DB::table($this->table)
->join('approval_states', 'approval_states.id', '=', $this->table.'.approval_state_id')
->join('approval_levels', 'approval_levels.id', '=', 'approval_level_conditions.approval_levels_id')
->select(
 $this->table.'.*',
 'approval_levels.name as level_name', 'approval_levels.level',
 'approval_states.state', 
 DB::raw("IF( approval_states.state='Approved','1','0' ) AS state_value")
)
->where($whereClause)
->where($this->table.'.deleted_at', null) // to ignore the soft deleted records.
->get();


Output Query (will produce the following JOIN query):
SELECT `approval_checklists`.*, `approval_levels`.`name` AS `level_name`, `approval_levels`.`level`, `approval_states`.`state`, 
IF( approval_states.state='Approved','1','0' ) AS state_value FROM `approval_checklists` 
INNER JOIN `approval_states` ON `approval_states`.`id` = `approval_checklists`.`approval_state_id` 
INNER JOIN `approval_levels` ON `approval_levels`.`id` = `approval_level_conditions`.`approval_levels_id` 
WHERE (`approval_levels`.`checklists_id` = 1) 
AND `approval_checklists`.`deleted_at` IS NULL

Hope it helps!!!

Writing the Subquery in Laravel 5.2

Please follow the example below to write the the Sub Query on Laravel 5.2:
// NOTE: Please do not forgot add below line at the top to use DB instance
USE DB;
$result = static::select('id')
->where( 'id', '!=', $currentLevelId)
->where('level', '>', DB::raw("(SELECT level FROM " . $this->table . " WHERE id='".$currentLevelId."')") )
->orderBy('level')->first();

Will produce the below subquery:
SELECT * FROM `approval_levels` WHERE `id` != 2 AND `level` > (SELECT LEVEL
FROM approval_levels WHERE id='2') ORDER BY `level` ASC LIMIT 1
Another Example:
$data = DB::table("items")
 ->select("items.*","items_count.price_group","items_count.quantity")
 ->join(DB::raw("(SELECT 
   items_count.id,
   GROUP_CONCAT(items_count.price) as price_group,
   FROM items_count
   GROUP BY items_count.id
   ) as items_count"),function($join){
  $join->on("items_count.id","=","items.id");
 })
 ->groupBy("items.id")
 ->get();

Hope it helps!

Thursday, 28 January 2016

Confirm Message when refresh or close or forward or backward the page via Javascript and AngularJs

To prevent accidental closing of page on the browser, you can set the Confirm Message when refresh or close or forward or backward the page via Javascript and AngularJs.

On Plain javascript, however you can also add the below code into AngularJs Controller
// Event Trigger when refreshing/Closing the page.
        var myEvent = window.attachEvent || window.addEventListener;
        var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compatable

        myEvent(chkevent, function(e) { // For >=IE7, Chrome, Firefox
            var confirmationMessage = 'Submission form not complete yet, Are you sure you want to leave this page?';  // a space
            (e || window.event).returnValue = confirmationMessage;
            return confirmationMessage;
        });        

On AngularJs State Changes, put the below code inside the particular controller.
// Event Trigger when clicking browser Back or Forward buttons
        $scope.$on('$locationChangeStart', function( event ) {
            $scope.pagePreventAlert();
            event.preventDefault();
        });

Sample AlertService 
I have created the sample AlertService AngularJs Service to prompt the alert, Please add the below factory into your code.
app.factory('AlertService', ['$rootScope', '$mdDialog', '$mdMedia',
    function ($rootScope, $mdDialog, $mdMedia) {

        var AlertService = {};

        return {

            onBeforeUnloadAlert: function(aData) {

                var data = aData;

                // Event Trigger when refreshing/Closing the page.
                var myEvent = window.attachEvent || window.addEventListener;
                var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compatable

                myEvent(chkevent, function(e) { // For >=IE7, Chrome, Firefox
                    var confirmationMessage = data.msgContent; // or a space
                    (e || window.event).returnValue = confirmationMessage;
                    return confirmationMessage;
                });

                // Event Trigger when clicking browser Back or Forward buttons
                $rootScope.$on('$locationChangeStart', function(e) {

                    // Appending dialog to document.body to cover sidenav in docs app
                    // Modal dialogs should fully cover application
                    // to prevent interaction outside of dialog
                    $mdDialog.show(
                        $mdDialog.alert()
                            //.parent(angular.element(document.querySelector('#popupContainer')))
                            .clickOutsideToClose(true)
                            .title(data.msgTitle)
                            .textContent(data.msgContent)
                            //.ariaLabel('Alert Dialog Demo')
                            .ok('Ok')
                            .targetEvent(e)
                    );

                    e.preventDefault();
                });
            }

        };

        return AlertService;
    }
])

And, in Your_Angular_Controller, please add "AlertService" on the controller parameter and include the below function it on each controller,
        // Page/Stage changes alert
        AlertService.onBeforeUnloadAlert({
            msgTitle: 'Form Submission Alert',
            msgContent: 'The Submission form not complete, please continue to submit the form or you may lose the information.'
        });

Wednesday, 27 January 2016

Connect to PHP with Oracle database via configuring Oracle Instant Client for Linux and Windows

PS: Create the Databases on Oracle after installing the Oracle Express Database XE 11.2, then follow the below step to enable OCI to connect to PHP.

1. Open the php.ini and uncomment the below line.
extension=php_oci8_11g.dll ; Use with Oracle 11gR2 Instant Client

2. Download the php_oci8_11g.dll files from the link below based on your version, find the "Thread Safe (TS) x86" version.

https://pecl.php.net/package/oci8/2.0.8/windows

Then, unzip the files and copy to the php/ext/ folder.

3. Next, download the "Instant Client Package - Basic" for Windows from the Oracle Instant Client page.
Because PHP is 32 bit, download the 32 bit version of Instant Client from here.

Package Name
Instant Client Package - Basic: All files required to run OCI, OCCI, and JDBC-OCI applications 
Download instantclient-basic-nt-11.2.0.4.0.zip (51,477,933 bytes)

Once downloaded, unzip the Instant Client files to C:\instantclient_11_2

4. Then, edit the Windows PATH environment setting and add C:\instantclient_11_2.
For example, on Windows XP, follow Start -> Control Panel -> System -> Advanced -> Environment Variables and edit PATH in the System Variables list.

Normally, you need to reboot Windows so the new environment is correctly set.

5. If does not work for some reason, please check the files path and location once again.

6. Also, if still does not work, you may try download this package "Microsoft Visual C++ 2012 SP1 Redistributable Package (x64)" and install it.
 (I am not sure when we would require to install it, try without it first as it may not require on your case).

Find more information for Linux and other stuff here...

Thursday, 7 January 2016

To preview the executing or last Query Log in Controllers or Models in Laravel 5

To view/preview the executing query or last executed Query Log in Laravel 5 (including Laravel 4.2, Laravel 5.0, Laravel 5.2), please add the below code and run it.
 
// This is the Sample Controller
class SampleController extends Controller
{
 public function sampleControllerFunction()
 {
  $this->owner_id = 5;
  
  // Enable the Laravel Database Query Log
  DB::enableQueryLog(); 
  
  // Run your Query here
  $item = SampleModel::where('owner_id', $this->owner_id)->first();
  SampleModel::where('owner_id', $owner_id)->forceDelete();

  // Fetch and Print the Last Database Query Log
  print_r( DB::getQueryLog() ); 
 }
}

// This is the Sample Model
class SampleModel extends Model
{
 /**
     * The database table used by the model (mysql).
     *
     * @var string
     */
 protected $table = 'owner_list';

    /**
     * The attributes that are mass assignable..
     *
     * @var string
     */
    protected $fillable = ['id', 'owner_id'];
 
 public function getItemsList()
 {
  // Enable the Laravel Database Query Log
  DB::enableQueryLog(); 

  // Run your Query here
  $item = static::where('owner_id', $this->owner_id)->first();

  // Fetch and Print the Last Database Query Log
  print_r( DB::getQueryLog() ); 
 }
 
}


Please comment me if you have any queries


Monday, 4 January 2016

Adding Foreign Key on the Existing Table in Laravel 5.2 using php artisan command

To add a foreign key to the existing Table in Laravel 5.2 using php artisan command

Please run the below command:

  
// user_id: This is the name of your column on this format
// property_list: This is the name of reference table (e.g. to table, not from table)

$ php artisan make:migration add_foreign_key_for_user_id_column_to_property_list_table --table=property_list

Find below the sample class of the foreign key migration table
 
class AddForeignKeyForUserIdColumnToPropertyListTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('property_list', function (Blueprint $table) {
            //
            $table->integer('user_id')->unsigned();
            $table->foreign('user_id')->references('id')->on('users')->onUpdate('NO ACTION')->onDelete('NO ACTION');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('property_list', function (Blueprint $table) {
            //
            $table->dropForeign('property_list_user_id_foreign');
        });
    }
}