Saturday, March 4, 2017

Non Recursive Pre-Order Traversal

public IEnumerator PreOrderTraversal()
        {
            if (Head != null)
            {
                Stack> stack = new Stack>();
                BinaryTreeNode current = Head;
                stack.Push(null);

                while (stack.Count!=0)
                {
                    if (current != null)
                    {
                        yield return current.Value;
                        if (current.Right != null)
                            stack.Push(current.Right);
                        if (current.Left != null)
                        {
                            current = current.Left;
                        }
                        else
                        {
                            current = stack.Pop();
                        }
                    }
                }
            }
        }

Non Recursive In-Order Traversal C#

 public IEnumerator InOrderTraversal()
        {
            BinaryTreeNode current = Head;
            Stack> stack = new Stack>();
            stack.Push(null);

            while (stack.Count != 0)
            {
                while (current != null)
                {
                    stack.Push(current);
                    current = current.Left;
                }
                current = stack.Pop();
                if (current != null)
                {
                    yield return current.Value;
                    current = current.Right;
                }
            }
        }

Monday, February 22, 2016

Does ISNULL check improve query performance

Today I came across something very interesting:


I had a query with a inner join between 2 tables and few more criteria in the where condition along with one condition like "int1

Both the tables had about 1 million records each. A simple select on both tables individually as well as joined returned all the records within 20 seconds. However when full query was executed on sql server, it continued to run for 3 hours, taking 100% CPU cycle and no results. I was wondering, why filtering should take that long.


I started adding conditions to where clause one after another and ran the query to see which where clause is taking more time. Everything worked fine. At the end I added the condition "int1

But a nagging feeling was there that something is not alright. Why should addition of an extra check improve performance. Am I missing something?


Next started the Google research "Does ISNULL check improve query performance". I landed on a link with exact same question.


The answer startled me :).


when I added the ISNULL condition, it did not use the existing execution plan. it created a new one for itself based on latest SQL server statistics.  Hence it completed fast. Execution plan for my query was based on old statistics and hence it was slow.


I update the statistics of my database by executing following:


EXEC sp_updatestats


This forced all the execution plan to get recreated again. A after this my original query ran as fast as other queries.


Conclusion: ISNULL check does not improve performance.

Monday, August 17, 2015

Hackerrank : Caeser Cipher in C#

//caeser cipher
int n = Convert.ToInt32(Console.ReadLine());

string s = Console.ReadLine();

int offset = Convert.ToInt32(Console.ReadLine());

char[] final = new char[n];

for (int i = 0; i < n; i++)



{
//bool ischar = false;

bool isSmall = false;

int curchar = (int)s[i];

if(curchar >= 97 && curchar <= 122)



{
isSmall = true;



curchar = curchar - 32;

}
if (curchar >= 65 && curchar <= 90)



{
int newChar = curchar + offset;

while(newChar >90)


{ newChar = newChar - 26; }
final[i] = isSmall ? (char)(newChar + 32) : (char)(newChar);

Console.Write(final[i]);



}
else



{

final[i] = s[i];
Console.Write(final[i]);



}

}
Console.ReadLine();

Find if 2 strings are anagram or not

/* find if 2 strings are anagram or not like silent and listen*/
string str1 = Console.ReadLine();
string str2 = Console.ReadLine();
bool isAnagram = true;
int strLen = str1.Length;
int[] arr = new int[256];
if(strLen == str2.Length)
{
for (int i = 0; i < strLen; i++)
{
arr[(int)str1[i]]++;
arr[(int)str2[i]]--;
}
foreach (int i in arr)
{
if (i > 0)
{
isAnagram = false;
break;
}
}
}
else
{
isAnagram = false;
}

Linked list: Pairwise swap

private static void SwapEveryTwoNodes(LinkedList l)
        {
            if (l == null || l.head == null)
                return;
            Node cur = l.head;
            Node next = cur.next;
            Node pre = null;
            if (cur == null || next == null)
                return;
            l.head = l.head.next;
            //in every iteration, there should be minimum 3 pointer change. Before next iteration begins,
            //ensure that the pointer to previos node is saved.           
          
            while (cur != null && next != null)
            {
                // cur =1, next = 2
                cur.next = next.next; //1.next=3
                next.next = cur; // 2.next=1
                if(pre!=null) // this check is only for first iteration
                    pre.next = next; //connect the left side of the LL with the swapped nodes
                pre = cur; //Save previous step
                cur = cur.next; //next odd numbered node
                next = cur!=null? cur.next:null; //next even numbered node              
            }
        }

Monday, April 8, 2013

Unrecognized configuration section system.web.extensions when upgrading to ASP.NET 4.0

Recently I upgraded my solution to VS 2010. My solution contained almost 30 projects. After upgrading when I ran the solution for the first time I got following error:

Unrecognized configuration section system.web.extensions when upgrading to ASP.NET 4.0

After some googling it was certain that the error was due to upgrade but I could not find exact solution. Then I opened my machine.config file (located at C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Config).
It had the "system.web.extensions" section. Suddenly I noticed that the entire text in the machine.config was in small letters(system.web.extensions) whereas in my projects' we.config, the first letter of every word was in capital letters. (System.Web.Extensions). When I changed my web.config to small case, the solution worked.

One complete day wasted on such small silly thing!!!!

Thursday, May 31, 2012

Find if backup file is complete or not

Frequently we get back up files from our clients to resolve their issues. But sometimes by the time the backup file reaches us, it gets corrupted either while creating the back up or while compressing or while uploading to ftp site or while downloading from the ftp site.
When we try to restore such file, we may get different error messages.

One message that I got recently was: Specified cast is not valid. (SqlManagerUI)

One very good way to find out if the backup file is incomplete is to execute following command

RESTORE HEADERONLY FROM DISK = 'C:\TEST.BAK'

It will show something like the below message which implies that the backup is not complete:



Similarly if you want to see what will be the space requirement for the restored back file it terms of the mdf and ldf, you can execute following:

RESTORE FILELISTONLY FROM DISK = N'v:\MyBackup.bak'




Monday, December 12, 2011

How to Archive SQL error Logs

To create a new error log, execute following:

1. Restart the sql server service. It will create a new error log
2. Execute following:
Exec ('DBCC ErrorLog')
3. Execute following:
Exec Sp_Cycle_Errorlog

Tuesday, April 19, 2011

To find what caused a postback

Sometimes there could be multiple controls on UI and it may be difficult to figure out which control caused the postback while debugging.

1. On aspx/ascx page use following:

Request.Form["__EVENTTARGET"]

2. on a class file use following:

this.Page.Request.Form["__EVENTTARGET"]

Saturday, March 5, 2011

Take responsibility

Recently I came across the book named "License to live" written by Priya Kumar.

Though I had never heard of the writer or the book, I just bought the book.

The book is a short novel about someone who is lost in corporate maze. Her situation is similar to all the people who have achieved every professional success at a very short age, who has fulfilled all their dreams and they do not know what next? Those who think that they have all the happiness they have ever craved for in their life and yet they are not happy. It’s about a person who has lost the very purpose of living.

And then she meets someone she thinks who can change her life.
Through that person she is able to view her future, in fact multiple and drastically different versions. Few are really something that she wants to be where she is happy and content with her life and few that does not want to be where she has lost complete control of her life. There she realizes that any of these futures can be hers provided she works towards it.

Then she comes across her Past. The parts of past which she wants to bury because she has not been able to forgive herself for those parts of the past. Though she is very successful at present but the burden of past is not allowing her to enjoy the fruits of hard work. There she realizes that she has to let go of the past so that she can be happy in present.

But the most difficult part comes when she meets her present. Then she finds herself in time trap as she is never living in her present. She can see the reflections of her past and the imagination of her future but not her present. There she accepts the fact that she has to take responsibility. Only if she takes responsibility of her present, she can make her future better and she will not have anything to regret about the past.

While reading the book, though the situation was very hypothetical, I was able to relate to most of the parts of the book. So many times we are so worried about tomorrow that we forget to live today. We forget that today’s conscious effort will make a better tomorrow and a better yesterday.

So Many time we have a simple excuse "I hardly find time to do this" or "I am too busy" but we forget the fact that everyone in the world gets same 24 hours in a day. We compare ourselves with our neighbors/competitors and complain that they have got too many resources which I do not have. But we forget that even we have a number of resources which they do not have.

Life gives equal opportunities to everyone in some way or other and it’s up to us how we make use of those opportunities.

Monday, January 24, 2011

Inspiration

As I have mentioned in my last post I was inspired to learn SQL server in detail after I started following Pinal Dave's Blog.

Similarly few months back I saw my friend was reading something on her PC. The title in big letters appeared very attractive.

I asked her what it that she is reading is.
She said: Robin Sharma’s' Blogs.

"Robin Sharma? Isn’t it that guy who wrote "the monk who sold his ferrari"

"Yeah"

I asked her for the URL.

I found the blogs from Robin Sharma very inspiring.

I browsed through many posts in his blogs and one of them was "60 TIPS FOR A STUNNINGLY GREAT LIFE"

I liked some of the points, laughed at some others.

Yet one point that caught my attention was "Read “As You Think”."

I got curious and immediately clicked on the link. Oh it’s another Self-help Book!!! That was my reaction.

Yet I could not contain my curiosity and searched for a synopsis.

The Synopsis was only few lines but quite inspiring.

"As we think we influence people around us. We have great power within us and we can shape decision of people around us. Decisions made by people which can change course of our lives."

ohh!! Is it!!. Let’s try.

I was going through a lot of job interviews those days and was always scared whether I'll make it or not.

I started thinking in a positive way "This person is going to ask me only the things I know. He will like my knowledge and experience and offer a job"

Every time i would go for an interview I would have only this thought in mind. It worked!!!! In a month I cleared 4 out of 5 job interviews. Amazing!!! Wasn’t it.

But mind is a devil as well. So there are some funny incidences as well. Whenever my lead would come near my desk I would say in mind "Go away". It will happen that the person would forget why he came to my desk and will go back to his desk.

There were multiple instances where I felt that the positive thinking helps.

What you think about yourself, you become that. Hence it’s really important that we control the way we think.

Thursday, January 20, 2011

Chance upon meeting with Pinal Dave

Today was like any other day. After not finding anything interesting in the usual meals of cafeteria, I decided to take a masala dosa. As I was waiting for my turn to get the dosa, I saw a familiar face. "Is he Pinal Dave?"

It was indeed Pinal Dave. First I thought "should I talk to him?". But then thought "He might be having thousands of fans like me. Why should I bother him during his lunch time".

But curiosity took better of me. How can I miss a chance to meet my technical world Idol. How can I let go of an opportunity to at least talk to the person who has inspired me to learn sql server and performance tuning.

I went to him and asked "Aren't you Pinal". He neiher was neither shocked nor impressed. Off course he would be encountering this almost every day. (He is a known personality among SQL server developers. Google any sql related problem and first few results will be from SQLAuthority blogs. )

He said "Yeah I am Pinal".

I introduced myself. But I was completely at loss of words.

Not sure what to say and how to say. I just managed to say this much “I am big fan of yours. I have been inspired a great deal by you.” He said thanks.

Again I asked "How come in Microsoft?"

He said "I came for training."

Then he asked "What are you doing here"

I told him "I work for Infosys and currently working as vendor for MS"

Then he told me that he is going to join Microsoft soon.

By then our dosa was ready. I got mine and he got his.

I was then wondering should I ask him to join us for lunch? or should I let him go his way.

Then he said He needs to find a place to sit. I got this opportunity that probably he doesn't have company and hesitantly asked "Would you mind joining us for lunch.” He accepted.

After settling for lunch and introducing him to my Infosys friends (Asha, Sowmya and Vivek) I started asking him questions one after another. All the questions that ever ran through my thoughts whenever I read his blogs.

And definitely this was my first one: How do you manage to write one blog every day. It’s really difficult to be consistent to write something every day.

He said: Yeah It’s a taxing job to do. Even simplest of the post takes 2-3 hours to write. The post he wrote yesterday took him more than a day. And he mentioned that he would be completing 1600 blogs the tomorrow.

Next question: Does he keeps his topics piled up at once or is it that he gets ideas on the fly?

He said: mostly for next 2-3 days.

Next question: Does he write all of them at once or one each day.
He said: For next 2-3 days.

He told about how he is learning new things like we do everyday by trial and error.
Even he finds his work monotonous sometimes.(Till today I used to think his job is very exciting which gives him opportunity to travel so much and meet so many people and exchange ideas).

He was very humble to say that he is not a native English speaker. (In fact I have been his follower because he writes in a very simple language)
He even showed snap of his 16 month old daughter.

He was really happy to share the info that his previous days' blog hit-count is 42,000. I was shocked. 42,000 hit count for a one blog in a day!!!!!!!!!!. That’s’ amazing.
I had asked him earlier that I want to have a photo with him. But later I forgot. Somehow after lunch he managed to find me and reminded me of the photo.
During the whole lunch I did not feel for once that that I have met him for the first time. The whole conversation went like meeting a very close and old friend after a long time and catching up.
Overall a memorable experience and I am very much thrilled.

Tuesday, November 23, 2010

DM query to troubleshoot slow running queries

SELECT
[Spid] = session_Id
,ecid
,[Database] = DB_NAME(sp.dbid)
,[User] = nt_username
,[Status] = er.status
,[Wait] = wait_type
,[Individual Query] =
SUBSTRING
(
qt.text,
er.statement_start_offset/2,
(
CASE WHEN er.statement_end_offset = -1
THEN LEN(CONVERT(NVARCHAR(MAX), qt.text)) * 2
ELSE er.statement_end_offset END -
er.statement_start_offset)/2
)
,[Parent Query] = qt.text
,Program = program_name
,Hostname
,nt_domain
,start_time
FROM
sys.dm_exec_requests er INNER JOIN
sys.sysprocesses sp
ON er.session_id = sp.spid
CROSS APPLY sys.dm_exec_sql_text(er.sql_handle)as qt
WHERE
session_Id > 50 -- Ignore system spids.
AND session_Id NOT IN (@@SPID) -- Ignore this current statement.
ORDER BY 1, 2

Friday, October 29, 2010

To find the space occupied by each table in a database

-- Create the temporary table...
CREATE TABLE #tblResults
(
[name] nvarchar(50),
[rows] Bigint,
[reserved] varchar(50),
[reserved_int] int default(0),
[data] varchar(50),
[data_int] int default(0),
[index_size] varchar(50),
[index_size_int] int default(0),
[unused] varchar(18),
[unused_int] int default(0)
)




EXEC sp_MSforeachtable @command1=
"INSERT INTO #tblResults
([name],[rows],[reserved],[data],[index_size],[unused])
EXEC sp_spaceused '?'"

select * from #tblResults order by rows desc

Drop table #tblResults

Monday, August 30, 2010

Transaction Isolation levels

I was looking for some good read on transaction isolatio levels.

Following is a good article.

Ref: http://www.sql-server-performance.com/articles/dba/isolation_levels_2005_p1.aspx

Sunday, August 29, 2010

Limitation of Update through views

When modifying data through a view (that is, using INSERT or UPDATE statements) certain limitations exist depending upon the type of view.

1. Views that access multiple tables can only modify one of the tables in the view.
2. Views that use functions, specify DISTINCT, or utilize the GROUP BY clause may not be updated.
3. Views having columns with derived (i.e., computed) data in the SELECT-list
4. Views that do not contain all columns defined as NOT NULL from the tables from which they were defined

ref:http://www.craigsmullins.com/cnr_0299b.htm

Thursday, August 26, 2010

OPTION (MAXDOP 1)

If you want a query to run on a single processor in a multiprocessor system, use this option.

Ref:http://www.mssqltips.com/tip.asp?tip=1047

Thursday, August 19, 2010

Error TF80012

Today while trying to upload my Test cases to VSTS through an excel i got following error.

TF80012: The document cannot be opened because there is a problem with the installation of Visual Studio 2008 Team Foundation Office integration components. Please see the Team Foundation Installation Guide for more information.

It was working fine perfectly last week. I got this error with both VSTS 2008 and VSTS 2010.

Following solution i tried and it worked like magic:


Run the following command (from an Elevated Command Prompt if running on Windows Vista or later, or Windows Server 2008 or later):
Regsvr32.exe "C:\Program Files\Microsoft Visual Studio 8.0\Common7\IDE\PrivateAssemblies\TFSOfficeAdd-in.dll"

(Update the path, for me it was d: and Visual Studio 9 and 10)

Ref: http://support.microsoft.com/kb/947865

Thursday, August 12, 2010

SQL Server Management Studio (SSMS) Shortcuts

Some shortcuts that I use quite frequntly are

1. CTRL+R To hide the Result Window
2. For getting the definition of a SP/Function: I define a shortcut in the Keyboard Shortcuts for SP_HELPTEXT

Go to tools--> Options-->Environment-->Keyboard, I have defined CTRL+3 as SP_Helptext. Now whenever I am going through a SP/ function and come across another SP all I have to do is to select the SP name and Press CTRL+3. I get the SP definition immediately in the result window. This shorcut helps me a lot as I do not have to type/copy paste SP_Hleptext to see the definition of the SP.

3.For Commenting and Uncommenting

Commet: CTRL+K followed by CTRL+C
UnComment: CTRL+K followed by CTRL+U

Again I do not have to move my hands to the mouse to sue toolbar to comment few lines of code at once.

4.To Execute a SQl Statement: its F5. its probably the first shortcut that we learn in management studio

5. To Open a new Query Editior Window

CTRL+ N

6. To Change Database Context

CTRL+U

7. I want to search for a particular Keyword throughout the entire solution,

CTRL+SHFT+F