Merge Overlapping Intervals

Every thing has to merge…
Merge – combine, coalesce; absorb,team up ; join, consolidate; unite

Merge Overlapping Intervals :

Given a set of time intervals in any order, merge all overlapping intervals into one and output the result which should have only mutually exclusive intervals.

Let the intervals be represented as pairs of integers for simplicity.

For example: let the given set of intervals be {{1,3}, {2,4}, {5,7}, {6,8} }.

The intervals {1,3} and {2,4} overlap with each other, so they should be merged and become {1, 4}.

Similarly {5, 7} and {6, 8} should be merged and become {5, 8}

Final List will be {1,4} & {5,8}

A simple approach is to start from the first interval and compare it with all other intervals for overlapping, if it overlaps with any other interval, then remove the other interval from list and merge the other into the first interval. Repeat the same steps for remaining intervals after first.

Following is the detailed step by step algorithm :

1. Sort the intervals based on increasing order of starting time.
2. Push the first interval on to a stack.
3. For each interval do the following
a. If the current interval does not overlap with the stack top, push it.
b. If the current interval overlaps with stack top and ending time of current interval is more than that of stack top, update stack top with the ending time of current interval.
4. At the end stack contains the merged intervals.

Advertisements

Visualization – constructing life from a space inside our brains

 

If you were ever involved in competitions or sports, chances are your coach asked you to imagine winning. How does it look, feel and sound? At the time, it might have seemed strange: reclining in a dark room, eyes closed, listening to imaginary scenarios. But there’s science behind visualization practices.

After all, Visualization is based on manipulating thought patterns through suggestions. Visualization actually have neurophysiological profiles. Nothing is being done to you; instead, it’s you who is tapping into something deep within the brain folds, accessing your creative power.

Successful people all over the world use visualization to spawn dreams into reality realms. Visualization is just concentrated dreaming. It’s mind over matter. It’s constructing life from a space inside our brains.

When digging a little deeper, visualization becomes less about winning and more about self-improvement than anything else. With visualization, you can create a world built from your own energies and desires. There are so many reasons why it will help you grow as a person. And there are so many ways you can do it.

Here are a few of the things that visualization can do for your well-being when it becomes part of your routine:

Visualization builds courage :

Visualization provides plenty of strength and courage to tackle daunting tasks. Afraid to get on stage? Nervous about an upcoming performance? Unsure of how to win that competition? Using visualization triggers hormones and synapses that make it easier to achieve those goals. When you’ve already envisioned the scenario, the real thing will feel familiar and much more feasible. It will be as if you’ve done it before. And inside your brain, you have.

Visualization combats negativity :

Visualization brings moments of positivity in a world sometimes full of negativity. So often, people respond to dreams with statements like, How will you do that? or That’s going to be so hard to accomplish. And yeah, sure, it will be hard, but you’re totally up for the challenge. During a visualization session, you get to live out your dreams despite what others say. It’s an effective way to battle that negative voice inside your own head, too.

Visualization bolsters creativity :

Visualization allows creative moments to exist, something the mind desperately needs. We tend to exist in scheduled spaces and confines of time. Fostering a practice that gives your mind a break from the mundane will be a relief to your psyche. Our brains need breaks—ones full of promise and fantastical visions, ones free from the chains of social constructs and full of creativity.

Visualization gathers energies :

Visualization fulfills the law of attraction, which facilitates dream building. Energy goes where attention flows. Want something badly enough? Then go ahead and dwell on it in healthy, optimistic ways. The more you visualize yourself living the life you want, the sooner universal energies will align with you to give you what you want. But don’t forget that being proactive is required and supports your visualization practice.

Visualization fosters purpose :

Visualization develops belief in self and creates a fulfilling life. When we lose hope, we lose so much. Hope is a catalyst for change. A life longing for something is worth the effort. Discover what you long for and visualize it every chance you get. You won’t be sorry. Actually, you’ll be amazed at how that personalized longing will propel you in directions you didn’t think were possible. Visualization can make that happen, but first you’ve got to believe.

Integrating salesforce SOAP API using C# .NET

Salesforce can be integrated with any .NET based application through the salesforce SOAP API. This article will show how to connect to salesforce and consume data within ASP.NET application.

Before we begin, there are a set of prerequisites that you need to get done in order to interact with salesforce API using the C# .NET.

  • Username and Password (salesforce logins)
  • SOAP API (WSDL file)
  • Security Token

Username and Password

You can register for a developer license in case you don’t have a user name and password at https://developer.salesforce.com/signup

SOAP API (WSDL file)

To get WSDL SOAP API, need to login salesforce and click “Set up” on right top Corner. Then go Develop > API and right click on “Generate Enterprise WSDL” under Enterprise WSDL (as we using “Enterprise WSDL” web service) and click on “Save Link as….” to save (enterprise.wsdl) file to somewhere in your computer.

Security Token

My Setting > Personal > Reset My Security Token

.NET Application

Let’s start exploring the SOAP API functionality by creating a sample .Net application and connect into Salesforce.

Here are the steps that can be taken to setup the Enterprise WSDL:

Create new ASP.NET Empty Web Site

Adding a Web Service Reference to website

select “Add Service Reference”.

Click “Advanced..”

Click “Add Web Reference…”

In Add Web Reference dialog type path of saved “enterprise.wsdl” file in URL: and click “Enter” then change Web reference name to “SFDC” then click “Add Reference”.

Now Salesforce SOAP API added into our website

Now that the base website is created and a reference setup to the Enterprise WSDL, we can transition to writing code that calls the API.

The first step is to have Salesforce authenticate us as a user. Once the authentication with Salesforce is successful, additional authentication information, such as the Session ID and URL will be returned. This information is needed for subsequent API calls.

The Session ID can be cached in your application for periods less than the timeout period. Go to “Setup > Security Controls > Session Settings” to see what your timeout is.

Here is example code showing how to authenticate against Salesforce :

using SFDC;
protected void Page_Load(object sender, EventArgs e)
{
    bool ConnectionStatus;
    ConnectionStatus = ConnectSFDC();
    //rest of the code
}

public bool ConnectSFDC()
{
     string userName = "ujjwaladatta@uzval.com";
     string password = "...";
     string securityToken = ".........";

     System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
     SforceService sfdcBinding = null;
     LoginResult currentLoginResult = null;

     sfdcBinding = new SforceService();
     try
       {
           currentLoginResult = sfdcBinding.login(userName, password + securityToken);
       }
     catch (System.Web.Services.Protocols.SoapException ex)
       {
                // This is likley to be caused by bad username or password
                sfdcBinding = null
                //lOG ex
                return false;
        }
      catch (Exception ex)
        {
              // This is something else, probably communication issue
                sfdcBinding = null;
                //lOG ex
                return false;
        }
       //Change the binding to the new endpoint
       sfdcBinding.Url = currentLoginResult.serverUrl;
       //Create a new session header object and set the session id to that returned by the login
       sfdcBinding.SessionHeaderValue = new SessionHeader();
       sfdcBinding.SessionHeaderValue.sessionId = currentLoginResult.sessionId;
       // create required sessions 
       return true;
 }

Validating SMTP host information

How can I test SMTP is up and running via C# before sending a message?

You can try calling GetStream() to your server and see if it responds with a message starting with 220. Of course this test doesn’t guarantee you that you will succeed sending the mail later, but it is a good indication.

public static class SmtpChecker
    {
        public static bool Check(out string returnMessage)
        {
            try
            {
                using (TcpClient smtp = new TcpClient(ConfigurationManager.AppSettings.Get("SMTPServer").ToString(),Convert.ToInt16(ConfigurationManager.AppSettings.Get("SMTPPort")) ))
                using (StreamReader reader = new StreamReader(smtp.GetStream()))
                {
                    returnMessage = reader.ReadLine();
                    //validate the reasponse
                    if (returnMessage.StartsWith("220", StringComparison.InvariantCulture))
                    {
                        // MailServer responds with: 220 HostName ESMTP
                        //Send QUIT as recommended by RFC 821 
                        try
                        {
                            using (StreamWriter w = new StreamWriter(smtp.GetStream()))
                            {
                                w.WriteLine("QUIT");
                                w.Flush();
                                string result = reader.ReadLine();
                            }
                        }
                        catch (Exception ex)
                        {
                            returnMessage = ex.Message;
                            return false;
                        }

                        return true;
                    }
                    else
                    {
                        returnMessage = "";
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                returnMessage = ex.Message;
                return false;
            }
        }
    }

and here’s the list of codes to expect :

Reply codes in numerical order
Code – Meaning
200 – (nonstandard success response, see rfc876)
211 – System status, or system help reply
214 – Help message
220 – Service ready
221 – Service closing transmission channel
250 – Requested mail action okay, completed
251 – User not local; will forward to
252 – Cannot VRFY user, but will accept message and attempt delivery
354 – Start mail input; end with .
421 – Service not available, closing transmission channel
450 – Requested mail action not taken: mailbox unavailable
451 – Requested action aborted: local error in processing
452 – Requested action not taken: insufficient system storage
500 – Syntax error, command unrecognised
501 – Syntax error in parameters or arguments
502 – Command not implemented
503 – Bad sequence of commands
504 – Command parameter not implemented
521 – does not accept mail (see rfc1846)
530 – Access denied (???a Sendmailism)
550 – Requested action not taken: mailbox unavailable
551 – User not local; please try
552 – Requested mail action aborted: exceeded storage allocation
553 – Requested action not taken: mailbox name not allowed
554 – Transaction failed

Dependency Injection in C#

Dependency Injection (DI, wikipedia) is a design pattern that reduces hard-coded dependencies between your classes by injecting these dependencies at run-time, instead of during design-time. Technically, Dependency Injection is a mechanism that allows the implementation of another, more high-level, design pattern called Inversion of Control (IoC, wikipedia). The purpose of both patterns is to reduce hard-coded dependencies (or ‘coupling’) between your classes.

 What are dependencies?

 Suppose that you are building a web application that is going to send e-mails to visitors that have entered a form. In object-oriented code, it is important to separate responsibilities. So you’ll probably end up with a class that handles the form input (FormHandler) and a class that is responsible for sending the e-mails (MailSender).

The MailHandler class looks like this:

public class MailSender
{
    public void Send(string toAddress, string subject)
    {
        Console.WriteLine(“Sending mail to [{0}] with subject [{1}]”, toAddress, subject);
    }
}

your FormHandler class will look like this:

public class FormHandler
{
   public void Handle(string toAddress)
     {
        MailSender mailSender = new MailSender();
        mailSender.Send(toAddress, “This is concrete code implementation example”);
     }
}

Although there’s nothing wrong with this code, it is creating a dependency between the FormHandler and MailSender classes.

The dependency is created at line MailSender mailSender = new MailSender();.

Using the New keyword in your code to instantiate a class implies that you are creating a dependency. From a practical point of view, you are telling your FormHandler class to use a concrete implementation of the MailSender class. There’s no flexibility. ‘But why’, you ask, ‘is this a bad thing?’. Let’s take a look at some reasons …

Why are dependencies a bad thing?

  • You can’t use multiple implementations of the MailSender class
  • It makes unit testing (nearly) impossible

The bottom-line is that your FormHandler shouldn’t know what concrete implementation of the MailSender is used. What concrete implementation is used, should be determined outside of your classes. That way, you can swap out the MailSender with another implementation if the need arises. If you are writing unit tests for the FormHandler, you can swap out the MailSender class with a mocked version.

we have to do is rewrite our code to use Interfaces. This is required for Dependency Injection, but is good practice anyways. An interfaces is basically a contract between classes that force one class to behave exactly as described by the interface. The contract can be implemented by other implementations (different class, same behavior).

We create a very straightforward interface for the MailSender class:

public interface IMailSender
{
    void Send(string toAddress, string subject);
}

We also rewrite the MailSender class to implement the IMailSender interface:

public class MailSender : IMailSender
{
    public void Send(string toAddress, string subject)
    {
        Console.WriteLine(“Sending mail to [{0}] with subject [{1}]”, toAddress, subject);
    }
}

We’ve basically told C# that the concrete implementation of our MailSender class follows the IMailSender interface (or contract). It is now possible to create other concrete implementations that follow the same interface but do different things ‘under the hood’,

for example:

public class MockMailSender : IMailSender
{
    public void Send(string toAddress, string subject)
   {
       Console.WriteLine(“Mocking mail to [{0}] with subject [{1}]”, toAddress, subject);
   }
}

Right now, we can change which concrete implementation is used by our FormHandler by rewriting the code where the class is instantiated:

public class FormHandler
{
    public void Handle(string toAddress)
    {
         IMailSender mailSender = new MockMailSender();
        mailSender.Send(toAddress, “This is still a concrete implementation “);
    }
}

Of course, this already adds a lot of flexibility to our code, as we can swap out which concrete implementation of IMailService is used by changing line IMailSender mailSender = new MockMailSender();.

Although C# will now force you to implement the IMailSender interface to the letter, your code will already improve a lot by using interfaces. The next step is to implement manual dependency injection to get rid of this code change that is required to change which implementation is used.

Implementing manual dependency injection:

 Basically, we’re going to pass the dependency in through the constructor of the FormHandler class. This way, the code that is using the FormHandler can determine which concrete implementation of IMailSender to use:

public class FormHandler
{
     private readonly IMailSender mailSender;

     public FormHandler(IMailSender mailSender)
     {
          this.mailSender = mailSender;
     }

    public void Handle(string toAddress)
     {
          mailSender.Send(toAddress, “This is manual dependency injection”);
      }
}

The code that creates our FormHandler has to pass in a concrete implementation of IMailService. This means that control is now inverted; instead of the FormHandler deciding which implementation to use, the calling code does. This is the whole point of Inversion of Control, of which Dependency Injection is just one approach. The calling code (the code that uses the FormHandler and now controls the dependencies) looks like this:

class Program
{
    static void Main(string[] args)
    {
        IMailSender mailSender = new MockMailSender();
        FormHandler formHandler = new FormHandler(mailSender);
        formHandler.Handle(“contact@uzval.com”);

        Console.ReadLine();
     }
}

 Concluding thoughts:

 Dependency Injection is a difficult concept to grasp if you’ve never used it before. Just give it a try, and you’ll see how flexible it makes your code. Especially when you’re writing unit tests you’ll quickly see the benefits. In that case, you can easily swap in mock implementations of dependencies. If anything, it makes your code a lot cleaner and sort of forces you to write better code.

Asynchronous Programming with Async and Await in .NET

You can avoid performance bottlenecks and enhance the overall responsiveness of your application by using Asynchronous Programming.

What is Asynchronous Programming?

Asynchronous programming is writing code that allows several things to happen at the same time without “blocking”, or waiting for other things to complete. This is different from synchronous programming, in which everything happens in the order it is written.

Let’s see example. Say I have a class called ContentManagement, which has both synchronous and asynchronous methods:

public class ContentManagement  
{
    public string GetContent()
    {
        Thread.Sleep(2000);
        return "content";
    }

    public int GetCount()
    {
        Thread.Sleep(5000);
        return 4;
    }

    public string GetName()
    {
        Thread.Sleep(3000);
        return "UZVAL";
    }

    public async Task<string> GetContentAsync()
    {
        await Task.Delay(2000);
        return "content";
    }

    public async Task<int> GetCountAsync()
    {
        await Task.Delay(5000);
        return 4;
    }

    public async Task<string> GetNameAsync()
    {
        await Task.Delay(3000);
        return "UZVAL";
    }
}

Now let’s write an MVC controller, like so:

public class HomeController : Controller  
{
    [HttpGet]
    public ActionResult Index()
    {
        Stopwatch watch = new Stopwatch();
        watch.Start();
        ContentManagement service = new ContentManagement();
        var content = service.GetContent();
        var count = service.GetCount();
        var name = service.GetName();

        watch.Stop();
        ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;
        return View("Index");
    }

    [HttpGet]
    public async Task<ActionResult> IndexAsync()
    {
        Stopwatch watch = new Stopwatch();
        watch.Start();
        ContentManagement service = new ContentManagement();
        var contentTask = service.GetContentAsync();
        var countTask = service.GetCountAsync();
        var nameTask = service.GetNameAsync();

        var content = await contentTask;
        var count = await countTask;
        var name = await nameTask;
        watch.Stop();
        ViewBag.WatchMilliseconds = watch.ElapsedMilliseconds;
        return View("IndexAsync");
    }
}

async : This tells the compiler that this method can run asynchronously.

await : This tells the compiler that we will ultimately need the result of the async method.

Notice what these two action methods are doing. In both cases, the action methods are calling the methods in the ContentManagement service, but in one they are doing it asynchronously.

On our Index view, we have an output : 

Time Elapsed : 10000 ms

On our IndexAsync view, we have an output : 

Time Elapsed : 5000 ms

Where did we get that number? The longest-running of the three tasks takes 5 seconds. By designing this to use async, we cut our total execution time in half! That’s a lot of speedup to be gained from writing a little extra code.

(or) it will be like

Task[] tasks = new Task[Ids.Count];

int i = 0;

foreach (string id in Ids)
{
tasks[i++] = Task.Factory.StartNew(() => DoWorkInParallel(id));
}

Task.WaitAll(tasks.ToArray());

Potential Issues :

When we mark a method as async, the compiler generates a state machine in the background; this is extra code. If we write good, stable asynchronous code, the amount of time it takes to create this extra structure won’t impact us at all, since the benefits of running asynchronously outweigh the cost of building the state machine. However, if our async method doesn’t have an await, the method will run synchronously, and we will have spent extra time creating the state machine that we didn’t use.

There’s one other potential problem to be aware of. We cannot call an asynchronous method from a synchronous one. Because async and await should go together in all cases, we pretty much have to have async on all methods, all the way down. This is why we needed separate async methods in the ContentManagement class earlier.

List To DataTable and Vice Versa using C#

public class ObjectConverter
 {
     public DataTable ListToDataTable(List items)
     { 
          DataTable dataTable = new DataTable(typeof(T).Name);
          //Get all the properties
          PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public |         BindingFlags.Instance);
          foreach (PropertyInfo prop in Props)
          {
            //Setting column names as Property names
            dataTable.Columns.Add(prop.Name);
          }
          foreach (T item in items)
          {
            var values = new object[Props.Length];
            for (int i = 0; i < Props.Length; i++)
             {
               //inserting property values to datatable rows
               values[i] = Props[i].GetValue(item, null);
             }
            dataTable.Rows.Add(values);
          }
          return dataTable;
     }

     public static List DataTableToList(DataTable dt)
     {
       List lstdata = new List();
       foreach (DataRow row in dt.Rows)
        {
           T item = GetItem(row);
           lstdata.Add(item);
        }
        return lstdata;
      }

      private static T GetItem(DataRow dr)
      {
        Type temp = typeof(T);
        T obj = Activator.CreateInstance();

        foreach (DataColumn column in dr.Table.Columns)
        {
          foreach (PropertyInfo pro in temp.GetProperties())
          {
            if (pro.Name == column.ColumnName)
               pro.SetValue(obj, dr[column.ColumnName], null);
            else
               continue;
          }
        }
        return obj;
       }
 }
Calling : 
 ObjectConverter converter = new ObjectConverter();
 
 DataTable dtstudentDetails=new DataTable();
 dtstudentDetails = converter.ListToDataTable(lststudentDetails); 

 List lststudentDetails = new List(); 
 lststudentDetails = converter.DataTableToList(dtstudentDetails);