Browse Month: January 2018

Higher Order Function in Swift PART 2

Let’s start with FlatMap where few point need to cover. So lets begin,


Flatmap is used to flatten a collection of collections.

        let temp_Dictionary = [["k1":"v1","k2":"v2"],["k3":"v3","k4":"v4"]]
        let flatMap_1 = temp_Dictionary.flatMap { $0 }
        //[(key: "k2", value: "v2"), (key: "k1", value: "v1"), (key: "k3", value: "v3"), (key: "k4", value: "v4")]

It returns an array of tuples after flatmapping. We have to convert it to an array

        var flatMap_dictionary = [String: String]()
        flatMap_1.forEach {
            flatMap_dictionary[$0.0] = $0.1
        //["k2": "v2", "k4": "v4", "k3": "v3", "k1": "v1"]


Sort an array simply by describing how you want the sort to work. You can do this simply by indicating the direction of the sort with a > or <.

So let’s try to sort simple name array as:

        let names = ["Sagar", "Savita", "Trupti", "Shravan", "Abdul", "Pragati", "amrita"]
        //["Abdul", "Pragati", "Sagar", "Savita", "Shravan", "Trupti", "amrita"]

Great, but what about “amrita” starts with a lower case letter?🤔🙄😟.

To ignore case, compare the lower case versions of the names:

        sortedNames = []
        sortedNames = names.sorted(by: {
            $0.lowercased() < $1.lowercased() 
        //["Abdul", "amrita", "Pragati", "Sagar", "Savita", "Shravan", "Trupti"]

That WORKS!!!!!!!!😀😃😃😄

Now let’s try out something more complex like below:,😮😯😧

For user-visible sorted lists, we should always use localized comparisons.

Fortunately, strings have another property called localizedLowercase.

        let sortedAcc_lastName = people.sorted(by: {
        $0.lastName.localizedLowercase < $1.lastName.localizedLowercase } )
        //[HigherOrderFunctions.ViewController.Nano_Emp(firstName: "Shravan", lastName: "Gundawar"), HigherOrderFunctions.ViewController.Nano_Emp(firstName: "Savita", lastName: "Kakade"), HigherOrderFunctions.ViewController.Nano_Emp(firstName: "Trupti", lastName: "Karale"), HigherOrderFunctions.ViewController.Nano_Emp(firstName: "Sager", lastName: "Rode"), HigherOrderFunctions.ViewController.Nano_Emp(firstName: "paragati", lastName: "Rode"), HigherOrderFunctions.ViewController.Nano_Emp(firstName: "Adul", lastName: "Shaikh")]

This will sort according to lastName only.Obviously the first names need to be compared as well. You can achieve this by putting the two comparisons into a tuple.

       let sortedComplete = people.sorted(by: {
       ($0.firstName.localizedLowercase,$0.lastName.localizedLowercase) <
        } )
       //[HigherOrderFunctions.ViewController.Nano_Emp(firstName: "Adul", lastName: "Shaikh"), HigherOrderFunctions.ViewController.Nano_Emp(firstName: "paragati", lastName: "Rode"), HigherOrderFunctions.ViewController.Nano_Emp(firstName: "Sager", lastName: "Rode"), HigherOrderFunctions.ViewController.Nano_Emp(firstName: "Savita", lastName: "Kakade"), HigherOrderFunctions.ViewController.Nano_Emp(firstName: "Shravan", lastName: "Gundawar"), HigherOrderFunctions.ViewController.Nano_Emp(firstName: "Trupti", lastName: "Karale")]



Generate a true/false by checking if any element in your array satisfies a condition. Related to filter, but returns a Bool, rather than an array.

eg. Let’s say we need to know if our fruits array contains a seven letter name.

         let sevenCharWord = names.contains { $0.characters.count == 7 }


Drops elements from your array while a condition is true, stops checking when it encounters an element that shouldn’t be dropped.

Let’s say we want to drop all elements at the beginning of the array that doesn’t contain the letter ‘s’.

           let name = names.drop { $0.contains("s") }
           //[ "Trupti",  "Abdul", "Pragati", "amrita"]



You’re probably familiar with the first property that retrieves the first element of an array, but did you know you can pass in a condition to get only the first element that meets that condition?

Let’s say we want the first element of the array that contains the letter ‘r’.

        let nameWithR = names.first { $0.contains("r") }


The forEach higher order function is a cool tool for your programming arsenal – basically short-hand for the for-inloop.

Let’s say we want print the lowercase version of every name in our Names array.

      names.forEach { print($0.lowercased(), terminator: " ") }
      //sagar savita trupti shravan abdul pragati amrita


The partition method partitions the elements of your array based on a condition. Elements that meet the condition are placed last in the array.

      names.partition(by: { $0.contains("i") })
      //["Sagar", "Abdul", "Shravan", "Trupti", "Savita", "Pragati", "amrita"]


You may be familiar with the components method on String, used to split a String based on a separator.
To use the split method on a String, you would use it on the String.characters property, which is a String.CharacterType, which adopts the Collection protocol, giving characters access to many of the same cool higher order functions that Array has access to. Once you’ve separated String characters with split, you’ll have an array of something called a SubSequence, that you can pass in when initialising a String – you can do this on each element of your new array using the map higher order function to end up with an array of Strings.

For Example,

        let str = "I can't believe it! These higher order functions are like magic. Don't you think? Well, maybe not magic, but pretty useful all the same."
        let  sen1  =str.characters.spilt { $0 == "."  || $0 == "!"  || $0 == "?"  }
        let sen ={ String($0) }
        //["I can\'t believe it", " These higher order functions are like magic", " Don\'t you think", " Well, maybe not magic, but pretty useful all the same"]


So here we have seen most of Higher Order Function. Hope you like this.
Thanks For Reading 😁🤪

Move View/ScrollView to keep TextField visible when keyboard appears!

There is a very common but tricky part comes while handling textfields position when keyboard appears. Its sometimes become headache for developers to handle such small but tricky issue. When keyboard appears then some textfields get covered and user can’t see while editing it.

There are some solutions to handle this but many of them works only for the first time. And then doesn’t work.
I have found one best solution and it works great always and I have modified this code to work on Swift 4. I have used XCode 9.1 for this tutorial code.

Lets do it.

You will have to create new project to try this. Design your storyboard like the image from below link.

And set delegate of all textFields to ViewController.

Now in your ViewController class you can use it like below


import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

     @IBOutlet weak var myScrollView: UIScrollView!

     @IBOutlet weak var constraintContentHeight: NSLayoutConstraint!

     override func viewDidLoad() {



override func viewWillAppear(_ animated:Bool) {


//1  Add this observers to observe keyboard shown and hidden events
      NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(aNotification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

     NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(aNotification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)


override func viewWillDisappear(_ animated: Bool) {


//2  Remove the observers added for keyboard from your ViewController

     NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)

     NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)


var activeField: UITextField?

// MARK: – UITextField Delegates

//3  ViewController activeField is an object of UITextField which will be used to manage and resign current active textField 

func textFieldShouldReturn(_ textField: UITextField) -> Bool {


     return true


func textFieldDidBeginEditing(_ textField: UITextField) {

     activeField = textField


func textFieldDidEndEditing(_ textField: UITextField) {

     activeField = nil


// Called when the UIKeyboardWillHide is sent

//4  This method is called from selector. So it requires @objc keyword and this method will adjust your scrollView (here myScrollView  😉)  and textFields to show as original.

@objc func keyboardWillBeHidden(aNotification: NSNotification) {

     let contentInsets: UIEdgeInsets = .zero

     self.myScrollView.contentInset = contentInsets

     self.myScrollView.scrollIndicatorInsets = contentInsets


// Called when the UIKeyboardWillShow is sent

This method will adjust your scrollView
and will show textFields above the keyboard.
keyboardWillShow(aNotification: NSNotification) {

     var info = aNotification.userInfo!

     let kbSize: CGSize = ((info[“UIKeyboardFrameEndUserInfoKey”] as? CGRect)?.size)!

     print(“kbSize = \(kbSize)”)

     let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0)

     myScrollView.contentInset = contentInsets

     myScrollView.scrollIndicatorInsets = contentInsets

     var aRect: CGRect = self.view.frame

     aRect.size.height -= kbSize.height

     if !aRect.contains(activeField!.frame.origin) {

          self.myScrollView.scrollRectToVisible(activeField!.frame, animated: true)



} // Class End

TestRail-Test Case Management Tool.

TestRail is a comprehensive web-based test case management software to efficiently manage, track and organize software testing efforts. Its intuitive web-based user interface makes it easy to create test cases, manage test runs and coordinate the entire testing process. Track and follow the status of individual tests, milestones and projects with dashboards and activity reports. Get real-time insights into the testing progress and boost productivity with personalized todo lists, filters and email notifications.

Getting started with TestRail

TestRail allows team members to enter test cases, organize test suites, execute test runs and track their results, all from a modern and easy to use web interface. Teams benefit from four main advantages when adopting TestRail:

  • Manage test cases, suites and test runs
    The traditional way of managing and documenting test cases on paper, in wikis, bug tracking tools or general document management systems quickly reaches its limits. TestRail enables you to create, manage and organize test cases and suites within an optimized user interface and application structure.
  • Boosting testing productivity
    TestRail’s todo lists, filters and email notifications help coordinate test runs and increase the productivity and responsibility of testers. The goal is to make sure that every team member knows his tasks at all times and that team leads can assign new tasks to testers depending on their workload.
  • Real-time insights into your testing progress
    To make important project decisions, it is critical to have access to detailed information about the testing progress and test results. Questions such as “How many percent of a test run have we successfully completed?”, “How are we progressing on the upcoming milestone?” or “Which tests have been executed in the past 24 hours?” can only be answered efficiently by using a comprehensive test case management software such as TestRail, and TestRail makes these details readily available.
  • Organize and track software testing efforts
    The organization and coordination of multiple parallel tests, be it for different projects or releases, is often complex and time-consuming. To not lose track of your testing efforts, TestRail helps you manage important software-specific data and structures such as project milestones and makes it easy to integrate with bug tracking tools.

The dashboard

After logging in to TestRail, the first page you usually see is the dashboard. The dashboard provides you with an overview of available projects, recent project activities and your todos. When you navigate to a project (by clicking on a project title), you switch to the project view and land on the project’s overview page, showing project details such as test suites, active test runs, project activity and so on. Whenever you need to switch to another project, just return to the dashboard by clicking the link in the upper left corner.

Test cases and suites

A test case in TestRail consists of a description of the test’s prerequisites, a list of test steps and the expected result. A test case can ideally be verified by a single tester in a short period of time and confirms a specific functionality, documents a task or verifies a project artifact.

In TestRail, test cases are organized into test suites. A test suite is a collection of test cases and is often created for specific project modules or areas. How you organize your test suites depends on the size of your project. If you have a lot of test cases for a project module, it is recommended to further break down your test suites and create suites for specific features or functionality. Ideally, a test suite consists of 50-1000 test cases.

Test runs and tests

To run a test and enter test results for the cases you added, you start a test run for a particular test suite. While a test suite is just like a plan that specifies how an application is tested, a test run is an actual test you are conducting.For most projects you will most likely start multiple test runs for a particular test suite over time. For example, if you are releasing multiple versions of a software program, you might want to conduct a test run for each new release. Likewise, you can have multiple test runs for a particular test suite active at the same time. This can make sense if you want to execute a particular test suite for multiple configurations (such as different operating systems). You can then start a test run for each different configuration you want to test against.

The following test statuses are available by default:

  • Untested
    By default, new tests have the status Untested. Once a test result has been added to a test, it can never receive the Untested status again.
  • Passed
    A test is marked as Passed when a tester verified the test steps and the expected results.
  • Failed
    A tester marks a test as Failed if one of the specified test steps resulted in an error or if the expected result differs from the actual test result.
  • Retest
    If a developer or tester determines that a test should be tested again, she marks the test as Retest. E.g., if a test originally failed and the developer fixed the problem, the developer can mark it to be retested.
  • Blocked
    The Blocked status is used to signal that a test cannot be executed currently because of some external dependency (such as a bug that needs to be fixed before being able to complete to test). It is often used in combination with the Retest status.

Projects and milestones

Projects are the main organizational unit in TestRail. It is generally recommended to create a TestRail project for every real software project you want to manage within TestRail. All other data such as test suites, runs, test results, milestones etc. are directly associated with a specific project. See the following illustration to see how the different entities relate to each other:


You can also add your project milestones to TestRail. A milestone can be any project milestone you deem to be important, such as a planned public software release, an internal test version or a new beta release for an important customer. Once you have added your milestones to TestRail, you can assign test runs to specific milestones

Test plans and configurations

When you need to manage multiple test runs and configurations for a single project, TestRail’s test plans come in handy. A test plan allows you to start multiple test runs at once, either if you have many test suites or if you want to test against multiple configurations (where a configuration can be anything you need to test your project against, such as different operating systems or web browsers).


To create a test plan, simply click the Add Test Plan button from the Test Runs & Results page. Now just select one or more test suites from the sidebar to add them to the plan. Just like you do with a single test run, you can configure all properties of the test runs such as the name, the cases you want to include and so on.



To dos and notifications

Tests can be assigned to team members. You can either assign tests when a run is created or do so afterwards from the run or test pages. Once a test has been assigned to a user, the test appears on the user’s todo list. Every user has its own todo list for each project she’s working on, while the Dashboard provides a quick way to see the user’s todos for all projects. The todo page can also be used to view the todos of other team members or the entire team at once, providing an easy way for team leads to assign tests to team members with the least workload.


Another relevant feature are email notifications. Email notifications help test owners to learn about test changes made by other users. For example, if a test has been assigned to a user (i.e. the test owner) and another user adds a comment or result to the test, the test owner is notified by email. It is also possible to subscribe to tests of other users or even entire runs by clicking the small email icons on the relevant pages.

Tracking progress and activity

Besides making it easier to manage test suites and enter test results, providing an easy way for all team members to track the test progress is one of TestRail’s most useful features. You can view the test results and testing activity of runs, milestones and entire projects on the individual resource pages.


You can choose between the status, activity and progress view on the test run and milestone pages from the sidebar, while you can switch between the project history and test results on the project’s overview page. Additional reporting features can be found on the Reports tab

Implement CAPTCHA In CodeIgniter

CAPTCHA is a randomly generated string (or a set of images) that appears when verification is required. It is an essential requirement for cutting down the spam at a website. In many cases, it is the only line of defense a website has against bots that spam websites.

CAPTCHA in CodeIgniter

In this tutorial, I will demonstrate how you can easily implement CAPTCHA in your CodeIgniter projects.

Create Controller

The process starts with the creation of the Controller.

Create a file named captcha.php in the Controller folder. Open the file in your code editor and add the following code to it:

Code Explanation

Here is a brief explanation of the various components of the Controller code:

Load CAPTCHA Helper

Form Submission

CAPTCHA Configuration


Create the View

The next step is the creation of the View. for this, create a folder in the View folder. Go into the folder and create another folder with the name captcha. inside this folder, create a file named index.php. Add the following code to the file:

Another Method of Calling CAPTCHA with Validation

Here is another method that is used to call in CAPTCHA through CodeIgniter helper and then validate it.

Integration of Chat Library and Firebase in iOS Project

Group chat is a very easy and good approach for having the communication in any mobile application. Today we are going to dive into an implementation of “Group Chat Using Firebase”.

While implementing this functionality in mobile application the very important and challenging task is creating an UserInterface for chatting screen, so for designing this screen we will go with the “JSQMessageViewController” it is an open source library for chatting.

Let’s see the procedure for implementing  “JSQMessageViewController”  to design chat screen. For more info you can take help from this link 

First of all create a new swift project, Now open terminal window and enter the command : cd (your project path).

After this command we will enter into our project folder, for using JSQMessageViewController we need to install pods into our project.


Procedure to install PODS : 

  1. Run “pod init” command on terminal. (It will create a Podfile into our project folder)
  2. open that created Podfile and enter pods for JSQMessageViewController (ie.pod JSQMessagesViewController)
  3. Now Save the file and close it.
  4. Again go to terminal window and run “pod install” command. (It will install all the dependencies of JSQMessagesViewController to our project and also create a new project file with .xcworkspace extension).
  5. Now open projectName.xcworkspace file in xcode.

We are done with all prerequisites for chat screen design,  JSQMessagesViewController have used collectionView for showing message bubble, so to display the message bubble into our project we need to implement all DataSource & Delegates for CollectionView created by JSQMessagesViewController.


It is very important to display all chat messages taken place in chat group so that need to be pushed/dump somewhere and retrieve  from somewhere. So for achieving this we are going to use “FIREBASE“.

Firebase is a mobile and web application development platform. It also provides a realtime database, so to achieve the above mentioned scenario we will use the firebase as a database.To create an environment for using firebase into our app we need to follow some steps to setup some prerequisites, please take a reference from this link for more info.

Steps to integrate firebase into our project :

  1. Go to this link  
  2. Login with your gmail credentials.
  3. click on “Go To Console” on top right corner.
  4. Now need to create a new app space, on firebase for our app. To create app space on firebase click on “Add Project”
  5. Fill up all the required information on the given popup and click on “CreateProject”.
  6. Now go to “Authentication” tab on left hand side, click on sign-in methods and enable “Email/Password” by clicking that field.
  7. Go to “Project Setting” -> “General” -> “Add firebase to your app” and fill all the information and complete the procedure. At the end it will create a .plist file that you need to add into our project.
  8. After importing .plist file to our project it’s time to install PODS for firebase.
  • Open existing Podfile from project.
  • Add pod ‘Firebase/Core’ to Podfile, save and close the file.
  • Follow all the steps whichever we done for installing JSQMessagesViewController pods.


Now you are perfectly ready with environment to implement chatting app in iOS using firebase as a realtime database.