Change an Array Value if Duplicate

I have an array which holds the multiple same values in same categories. And I want to If the data is duplicate and the category is ‘Sales’ I want 1 of them to change to ‘Service’ and vice versa.

From above snippet, you can see ‘Lane Assist’ is duplicate in ‘Sales‘ category and ‘Bandenafdichtset’ is duplicate in ‘Service‘ category and I changed them as vice versa.

Getting Query String Values Without a Hash in the URL

$location.search() returns empty? Angular does not remove the query before the hash bang in URL. According to AngularJS documentation,  hash bang URL format is:

http://example.com/#!/bar?baz=23

So if you have no hash bang in your URL (e.g. http://example.com/bar?baz=23), and try to get query string value, then you can use this snippet.

function getQueryParams(queryParam, url) 
{
        var pageUrl = url || window.location.search.substring(1);
        var urlVariables = pageUrl.split(/[&||?]/);
        var response = null;

        for (var i = 0; i < urlVariables.length; i += 1) {
            var param = urlVariables[i];
            var paramName = (param || '').split('=');

            if (paramName[0] === queryParam) {
                response = paramName[1];
            }
        }
        return response;
}
    
console.log(getQueryParams('baz', 'http://example.com/bar?baz=23'));

This code is also with pure JavaScript (withour AngularJS).

Change Bower Default Directory And Folder

Bower is the client-side dependencies manager. The developer can easily manage their client-side dependencies with the Bower. By default when you install any package (e.g jQyery, Bootstrap etc) through Bower, then a bower_components folder will create in the project’s root directory and store all the files inside it. So the default directory of bower installation is ROOT and folder is bower_components
But if you want to change the Bower default directory and folder then you have to follow these following steps.

Remove bower_components (if exist) from your project root directory

 

Create .bowerrc file in your project’s root directory

 

Paste these code in .bowerrc file and modify DIRECTORY_NAME & FOLDER_NAME

{
  "directory": "DIRECTORY_NAME/FOLDER_NAME"
}

Then finally run bower install command.

Hope these will helpful to configure your Bower directory and folder name.

Avoid Too Much Complexity to the Code, Instead of Returning Often and Early.

Code readability is really important part of programming. The readable and cleaner code is easily manageable and customizable. The programmers don’t take it seriously but it’s important.  Actually, there is always an ongoing debate, but returning often, and returning early will make your code much cleaner looking and readable.

public function saveUser($data = [], $sendEmail)
    {
        // Checking data is exiest or not
        if ($data) {
            $isSaved = $this->UserModel->save($data);

            // Checking if the data is successfully stored or not.
            if ($isSaved) {
                //  If stored then doing some other work

                // send the email to the user
                if ($sendEmail) {
                    // send the email
                }

            } else {
                // Otherwise return false
                return false;
            }
        } else {
            // Otherwise return false
            return false;
        }
    }

If you look over the above code snippet, then you can see there is some nested if-else. And code quickly becomes unreadable and complex. You have to have a deep look to understand this sort of code.

public function saveUser($data = [], $sendEmail)
    {
        if(!$data)
        {
            // If data not exiest then return.
            return false;
        }

        $isSaved = $this->UserModel->save($data);
        if (!$isSaved) {
            // If data not saved then return.
            return false;
        }

        if (!$sendEmail) {
            // send the email
        }
        
        // If everything good, then return true.
        return true;
    }

Now see this code snippet, this code is much easier to read and very cleaner look. Both snippets are doing same work but the second one is much more readable and clearer than first one. And this can be easily manageable & customizable. so that avoid too much complexity to the code, instead of returning often and early.

Loading Model Inside Another Model and Controller in CakePHP 3

Sometimes it necessary to load a model inside another model as well as another controller in CakePHP. This article will help you to load a model from another model & controller with CakePHP 3

Load From Model:
$anotherTable = TableRegistry::get('AnotherTable');
$data = $anotherTable->find('list');

CakePHP TableRegistry is a factory of the Table object. It comes with a lot of static function and get() one of them. TableRegistry::get() provides an instance of Table. You can see an example from above snippet.

Load From Controller:
$this->loadModel('AnotherModel');
$data = $this->AnotherModel->find('list');

If you need to load a model from the controller which does not default model of the controller. You can use loadModel() function to get an instance of another model.

Start Counting After Scroll on Specific Element

Sometimes it’s important to do some activities when a specific element is visible on the web page. So something needs to be trigger when that element is showing on the web page. Suppose you want to start counting after scroll on that specific element. Here is the code for that.

HTML CODE:
<div class="container">
  <h2 class="well well-lg" style="margin-top: 200px;">Scroll Down</h2>
  <h2 class="well well-lg" style="margin-top: 200px;">Scroll Down</h2>
  <div class="jumbotron text-center" style="margin-top: 200px;">
    <div class="container">
      <div class="col-lg-3">
        <h2>Total Sales</h2>
        <h1 class="counter">967</h1>
      </div>
      <div class="col-lg-3">
        <h2>Total Sales</h2>
        <h1 class="counter">967</h1>
      </div>
      <div class="col-lg-3">
        <h2>Total Sales</h2>
        <h1 class="counter">967</h1>
      </div>
      <div class="col-lg-3">
        <h2>Total Sales</h2>
        <h1 class="counter">967</h1>
      </div>
    </div>
  </div>
</div>
JAVASCRIPT CODE:
function isCounterElementVisible($element) {
  var topView = $(window).scrollTop();
  var botView = topView + $(window).height();
  var topElement = $element.offset().top;
  var botElement = topElement + $element.height();
  return ((botElement <= botView) && (topElement >= topView));
}

$(window).scroll(function() {
  $(".counter").each(function() {
    isOnView = isCounterElementVisible($(this));
    if (isOnView && !$(this).hasClass('visibled')) {
      $(this).addClass('visibled');
      $(this).prop('Counter', 0).animate({
        Counter: $(this).text()
      }, {
        duration: 3000,
        easing: 'swing',
        step: function(now) {
          $(this).text(Math.ceil(now));
        }
      });
    }
  });
});

See Demo:

How to Fix Error: ngRepeat:dupes Duplicate Key in Repeater in AngularJS

Error: ngRepeat:dupes Duplicate Key in Repeater is the most common problem we are facing when we work with AngularJS. Why does it happen? It’s happened when there is any duplicate key is exist in ngRepeat expression. By default, AngularJS uses keys to populate the dom elements. So if there is any duplicate key found in ngRepeat expression, then the error happens.

Example:

Now assume we have data like this format. Here 5 is the duplicate number. And when we try to use ngRepeat expression and we will get Error: ngRepeat:dupes Duplicate Key in Repeater.

$scope.numbers = [1, 2, 3, 4, 5, 5];
<p ng-repeat="number in numbers">
    {{ number }}
</p>

To fixed this problem you have to use track by $index with ng-repeat.

<p ng-repeat="number in numbers track by $index">
    {{ number }}
</p>

The problem will be solved after using track by $index with ng-repeat.

Implement Non-Blocking Session in PHP

As we all know Session is the most important component in the web application. Before describing the non-blocking session, I would like too little introduce about PHP Session. The session is the way to store data for each user against a unique session ID. By default, session usages file to storing the session data. When session_start() is called then PHP creates a unique identifier number for that particular session. And sent that number to users browser to save that number. Contiguous create a new file with the same name of the unique identification number. And browser will use that unique identification number to communicate with that server. To know more about How Does PHP Session Works read this article.

Non-Blocking Session

What Does Session Locking:

When web server getting the concurrent request which involves with PHP Session. Then the first request will engage the Session file to work with it and locked that Session file. And rest of the request who also have to engage with Session, they will be blocked (waiting for the unlock of the Session file). When the first request did its activities then release the Session file and then the second request will engage with The session. And this happened until the last request is served. This is actually called Session Looking. To understand more about Session Locking read this article.

Non-Blocking Session:

To improve the application performance we need to avoid this problem. To avoid the PHP Session blocking we can start the session and then close the session. This will unlock the session file and allow the remaining requests to engage with Session, even before the previous request has served.

session_write_close(); function need to call to close the session.

This trick works great if you do not need to read anything in session while your another process is engaged with the session. With this technique, you still able to read the $_SESSION data while the session is engaged with another request.

Example Script:

// start the session
session_start();
// read/write to session
$_SESSION['login_time'] = time();
// close the session
session_write_close();
// now do my long-running code.
// still able to read from session, but not write
$twitterId = $_SESSION['userId'];