August 12, 2017

Matrix Multiplication | C Programming

09:00 Posted by Durga swaroop Perla , , , No comments
We have discussed about Matrix arithmetic in my recent youtube tutorial.


In that, I have already shown how Matrix addition and subtraction can be done and asked you to try multiplication themselves. Hopefully you have been able to do that Or atleast tried it out before coming here to see my solution.

For this example, I have taken two matrices as follows.

                                       

Matrix1 has 3 rows and 4 columns and Matrix2 has 4 rows and 3 columns. And now, the code to multiply these two matrices.
#include "stdio.h"
main() {

    int matrix1[3][4] = { {1,2,3,4}, {3,4,1,2}, {4,1,2,3} };
    int matrix2[4][3] = { {0,1,2}, {1,2,0}, {2,0,1}, {1,0,2} };
    
    // Values from the matrices. No. of columns in matrix1 = No. of rows in matrix2. Matrix Multiplication possible
    int rows1 = 3, cols1 = 4, rows2 = 4, cols2 = 3;        
    
    // Initialize the resultant matrix with all zeroes
    int mult_matrix[3][3] = {0};
    
    // Loop variables
    int i=0, j=0, k=0;
        
    for(i = 0; i < rows1; i++) {
        for(j = 0; j < cols2; j++) {
            for(k = 0; k < cols1; k++) {
                // Since we are initializing with zero, we can add new values to the previous value to get the final value
                mult_matrix[i][j] += matrix1[i][k] * matrix2[k][j];
            }
        }
    }
    
    //  Print the new matrix
    for(i = 0; i < rows1; i++) {
        for(j = 0; j < cols2; j++) {
            printf("%d ", mult_matrix[i][j]);
        }
        printf("\n");
    }
}

And when you run this program, you get the following output as one would expect:
12 5 13
8 11 11
8 6 16

Press any key to continue . . .
The comments, along with the explanation in the video should be enough for you to understand this code directly.But, do reach out on social media for any queries.

That's all for this article.
As, always, Have a happy reading and Stay Awesome !

If you have liked this article and would like to see more, subscribe to our Facebook and G+ pages.

Facebook page @ Facebook.com/freblogg

Google Plus Page @ Google.com/freblogg

March 04, 2017

Today I Learned | Petrov's Defense | Russian Opening

01:08 Posted by Durga swaroop Perla , , , No comments
As you can probably guess from the title of this article, I am an amateur Chess player and certainly a beginner when it comes to Opening theory. My chess journey has a lot of turns and several starts and stops. Hopefully by sharing things I learn, I can get better.
So, Today learned about one of the famous chess openings - Petrov's Defence, named after Russian chess master Alexander Petrov. This opening is also sometimes referred to as Russian Opening. And this is my analysis of the opening. I will try to analyse all the possible combinations I can think of how insignificant they may be just so that this is beginner friendly.
The play starts quite formally with 1. e4 e5 2. Nf3 Nf6, leading us to this comfortable symmetric position

Petrov Defense picture 1

Here's how it looks from the Black side.

Petrov Defense picture 2

From here easily the most seen move is White capturing the pawn on e5 with the move 3. Nxe5, giving us

Petrov Defense picture 3

Now, If you are a fan of symmetry like me, you might expect black to follow suit as well taking the e4 pawn. But that can prove fatal for Black. Not sure how? Let's explore. So, if Black side plays 3. ... Nxe4, we get this symmetric position on the board as expected.

Petrov Defense picture 4

Here white has an easier move of 4. Qe2 threatening the Knight.

Petrov Defense picture 5

Now, If black wanted to continue symmetry and played 4. ... Qe7, it would be really worse as the next moves would be 5. Qxe4 Qxe5 and Wham Bam Thank you Ma'am, because black just lost its Queen.
Now, another possible line from 4. Qe2 is 4. ... Nf6 with black retreating its Knight.

Petrov Defense picture 6

Now, Is this fine for Black? The answer is still No. Notice that the White Queen and the Black King are on the 'E' file. So, If the white player just moves his Knight out of the way, you will have a discovered check from the Queen.

Petrov Defense picture 7

Now, If he can manage to threaten one of your big players with the knight along with the discovered check, that would just be deadly. White has two ways it can proceed from here to try to extract maximum damage.
One possible line is white playing 5. Nxf7+, forking your Queen and Rook along with the discovered check.

Petrov Defense picture 8

But, this position is actually not good for White as black can just take on f7 with 5. ... Kxf7 coming out of the check and getting a piece in return.

Petrov Defense picture 9

Here White lost a Knight for just a pawn. Though black has lost the ability to castle, the lead in material should more than make up for it if he/she plays carefully. So, we saw 5. Nxf7+ is a bad move.
What else is there? How about 5. Nc6+ ? You have a deadly discovered check along with a direct threat to the black Queen.

Petrov Defense picture 10

Now, if you are playing with black pieces here, all is not done at. You're certainly in a grave position but with a bit of thought we can try to come out with the least bit of damage.
So, after 5. Nc6+, you have to first get your king to safety. You've got two ways. With the Bishop or the Queen. Let's see what happens if we try Bishop. So, you move 5. ... Be7.

Petrov Defense picture 11

Now, the White Knight will just jump at the opportunity and take your Queen with 6. Nxd8. You lost the Queen but you got a Knight while losing your ability to Castle.
So, How about 5. ... Qe7? Knight will still take on e7 with 6. Nxe7 and you take it back with the Bishop, all the while getting ready to castle on the Kingside in the next move. Doesn't look like a bad move.

Petrov Defense picture 12

So, that is your best move if you managed to get to that position. But, you should never get to that position because you should never take on e4 in 3. ... Nxe4. That's a bad move.
Let's get back to the position of 3. Nxe5.

Petrov Defense picture 3

Let's see what the black side can do now. Instead of taking the pawn, black can try to get the white knight away from its base by playing 3. ... d6.

Petrov Defense picture 13

White of-course retreats its Knight on to f3 or d3, preferably f3 to avoid blocking the light square bishop.

Petrov Defense picture 14

Now, black can take on the pawn freely and is better equipped to deal with the subsequent pin from Qe2.
So, that concludes my little analysis of this famous opening. There are a lot of variations possible around this main line and obviously we can't cover all of them. So, do setup the board and practice all the variations for yourself to get the hang of it.
That's it for this analysis. See you next time.

Follow FreBlogg on Facebook for more interesting articles.

February 20, 2017

Git Cherrypick

14:26 Posted by Durga swaroop Perla , , No comments
Cherrypick is one of the most useful commands in Git. It is used to apply a commit that is present on another branch, on the current branch. Let's see an example to understand this better.

Let’s say you have two branches feature1 and feature2 as in the following picture.



Now, the green commit 5 on branch 2, has some interesting code that you want on feature1. How would you get that? You are probably thinking about merge/rebase. But with that you will get all the other green commits from 1–4 as well, which you don’t want.
Cherrypick for the rescue!.

Assuming you are on feature1, all you have to say is

git cherry-pick green5 (Assuming 'green5' is the commit id)

And that’s it. You will have the green5 commit on your orange4 commit like in this picture as you wanted.



Notice, that the green commit is no longer “5” but has been changed to “5′”. This is to show that, though the changes (change set is the git term) in the commit remain the same, Git will generate a new commit hash for this because hashes take parent node also into account.

And that is all you need to know about Cherry picking. So, Go ahead and pick some cherries!


For more interesting articles,
Subscribe to Freblogg's RSS feed. Its a great way to get all the new articles directly.
Follow FreBlogg on Facebook and follow @durgaswaroop on Twitter

January 31, 2017

Git Merge Vs. Git Rebase

09:00 Posted by Durga swaroop Perla , , , , No comments
Merge and Rebase are two strategies available in Git to combine two ( or more) branches into one branch.
Let’s say we have two branches feature1 and feature2 that have diverged from a common commit “a” to have four commits each.



Now we want to combine both the features into a single branch. Merge and Rebase are our options. Let’s see what each of them can do.

Git Merge:

Merge will seem like a fairly obvious thing, if you look at the end result. It is pretty much like taking two threads and tying them up in a knot.



Here the commit ‘b’, has the information regarding all the commits in feature1 and feature2. So, Merge preserves the history of the repository.

Git Rebase:

Rebase on the other hand doesn’t preserve the history. It quite literally re-bases one branch on top of the other i.e., it changes the base of the branch. Let’s see rebasing with the same example.
Let’s say I want to rebase feature1 onto feature2, what that means is that I want all the commits in the branch feature1 on top of the commits of feature2. So, after rebase your commit history would look like the following.

           

As you see in the picture, the base of feature1 which was previously the commit “a”, has been shifted to the green commit “4”. Hence the name Re-Base. Here feature1 is sitting on top of feature2 as opposed to being on “a”.

Do note that I have added a next to the numbers of feature branch making them 1’, 2′ and so on, to indicate that the orange 1′ commit is different from the orange 1 commit. This is because each commit, apart from storing the changes to the files, stores the information regarding its parent. So, If a parent to a commit changes, even it has the exact sames modifications to the files, will be treated as a different commit by Git, which means we have changed the Git commit history.

Also Anyone who looks at the commit history now, would think that feature1 was added after feature2 which is not what actually happened. If this is the end result you’re going for, then it’s absolutely fine but if you want to show that feature1 and feature2 both started off simultaneously, then you need to use Merge.

Both Merge and Rebase have their pros and cons. Merge keeps the history of the repository but can make it hard for someone to understand and follow what’s going on at a particular stage when there are multiple merges. Rebase on the other hand ‘rewrites’ history (read - creates new history) but makes the repo look cleaner and is much easier to look at.

What you want to use depends on your need. A lot of companies make merges mandatory when adding stuff to master branch because they want to see the history of all changes. And a few companies/Open source projects mandate rebasing as it keeps the flow simple and easy to follow. Use the one that suits your workflow.

Fun Fact:
There is a merge strategy called Octopus merge, where you merge multiple branches into one. For more info on this: Understanding Git Octopus Merge | FreBlogg



For more interesting articles,
Subscribe to Freblogg's RSS feed. Its a great way to get all the new articles directly.
Follow FreBlogg on Facebook and follow @durgaswaroop on Twitter

December 21, 2016

Understanding Git Octopus Merge

05:00 Posted by Durga swaroop Perla , , , , No comments

The Code for Git merge is one of the most sophisticated pieces of software ever written. There is so much stuff that goes inside during a merge that its just mind boggling. Just for that alone, Linus could be considered a programming genius. Too bad for other geniuses, he has Linux kernel on his resume :-D.

Git Logo

As the title suggests this article is about Octopus Merge in Git. For this I hope you know what a basic Git merge is and what it means to merge. If you're completely unfamiliar with Git, then I've no idea what you're doing here. You better read up on some Git 101 before jumping to this article.

Anyway, Just to brush up, this is how a simple/familiar Git merge goes ..

We have a branch called feature that diverged from master at the second commit and went to have two commits of its own.

Master and Feature branches in Git

Note: For the branch pictures in this article I am using a Git GUI tool called Git Kraken. I have been trying it a few days now and it looks quite promising. I am a fan of its clean and minimalist UI and have been using it extensively for the beautiful visualization of branches. And above all, It is free for personal non-commercial use. So, you can try it out for free.

Now you want to add those cool new changes on the feature branch to master. The way you do it is by merging (Let's not talk about Rebasing for now. We will look at it another time). So, when you merge this is how it looks like.

Git merge master feature

This is all the usual stuff that we are all familiar with.

Now there is another type of merge called the The Octopus Merge. At least some of you must have heard about it either from an online video or from a colleague in your office that seems to know everything. Either way the Octopus merge is a really fun way of Merging. You probably won't get to do this at your work as a lot of companies think this complicates things and we all know how much Companies hate complexity. Anyway, Let's see what it looks like. I have a local git repository with three branches branch1, branch2, branch3 along with master. All four of these branches have two extra commits from the point they diverged.

Git octopus pre image

Now if you want to merge them, the usual way would be to merge two branches at a time to finally get to the final combination after three merges like so.

The usual way to merge branches in Git

This may seem fine and might actually be the only way you would think about this if not for the Octopus merge. You have three merge commits here and as we know merge commits are noise. They pollute the history of your repository and interrupt the story told by your Git history. So, how about keeping the noise low by just having one Merge commit instead of three. How you ask? Octopus, My friend. All hail the great and mighty Octopus. So, the way you perform an Octopus is by merging all the branches at once on to the master. To do that you give a command like this

Git merge octopus

This will merge all the three branches to master. The branches will look something like this. Do you see the reference of Octopus now?

Octopus Git merge

Now, if you know anything about octopuses, you might be wondering that we only have four legs here while an Octopus has 8. Well you are right. Octopuses do have 8 legs (technically 6 as two of them are used as hands) but 4 is good enough. Actually any merge can be called Octopus if you're merging three or more branches.

If you are using Git for sometime, you might be wondering, If Octopus is so freaking cool, why haven't more people heard about it and Why are more people not using it. Well, you are right my friend. Octopus is awesome for sure, but as I said it certainly does complicate things a lot especially when dealing with merge conflicts. Merge is hard enough as it is when dealing with just two branches. But if you are merging 5 or 10 branches together it feels like you're doing a complex surgery. You have to be really careful in that case and I am not even sure if any modern GUI tools support diffing 10-way. Also a lot of people tend to go overboard with Octopus.

Look at this message where Linus Torvalds yells (pleasantly) at a guy for creating an Octopus with 66 branches. Imagine that for a second. 66 branches! I wouldn't want to be the guy that handles merge conflicts on that one! Linux aptly says

that's not an octopus, that's a Cthulhu merge

Cthulu Image

So, a lot of companies don't really use this. A lot of people won't even consider this for their Merge strategies.

A rule of thumb to follow with Octopus is to never overdo it. An 8-way octopus merge though borders on crazy hard and insane, is fine but more than that is an overkill. The situations where you have to merge more than 5 or 6 branches tend to be very rare and in those cases may be you can go for an Octopus on a subset of branches at a time and do a Octopus for those. Or may be rethink your merging strategy.

Either way, I hope this article helped you in understanding something new and gives you some ideas for dealing with complex merges. I hope you will educate your peers and colleagues about this new merge and share this article with them

Well, That is all for this article folks. See you again in the next one. Until then, Good Bye.


For more interesting articles,

Subscribe to Freblogg's RSS feed. Its a great way to get all the new articles directly.

Follow FreBlogg on Facebook and follow @durgaswaroop on Twitter

Special Thanks to Git Kraken team at Axosoft for developing a great tool like Kraken.

Attributions:

Cthulhu Image : https://commons.wikimedia.org/wiki/File:Cthulhu_and_R'lyeh.jpg

October 13, 2016

Navigating In Vim II | Your First Lesson in Vim

12:00 Posted by Durga swaroop Perla , , No comments

This is the fourth article in the series titled, "Your First Lesson In Vim". These articles are written with a goal of helping out new Vim users by teaching the awesomeness of the Vim editor and there by extending the Vim community. Vim though quite powerful, has a bad rep for being hard to learn and hard to get started with. So, even when someone is interested in learning about Vim, that infamous learning curve seem to be scaring them off. This series is going to put an end to all of that.

Vim Logo

In the last article Navigating in Vim I, we have seen a lot of Vim motions. Most of these fall under the category of word-motions (:help word-motions). We will learn some more motions in this article. And in case you still haven't tried Vim Adventures you should do it. It will help you a lot with getting the hang of Vim motions and getting around in vim.

Here are the list of Vim motions for this article.

Motion What it does?
0 Go to the STARTING of the CURRENT LINE
^ Go to the FIRST NBC* of the CURRENT LINE
- Go to the FIRST NBC* of the PREVIOUS LINE
+ Go to the FIRST NBC* of the NEXT LINE
$ Go to the END of the CURRENT LINE
g_ Go to the LAST NBC* of the CURRENT LINE
f{char} Find a character FORWARD in the current line (Usage: to go to first occurance of c, you type fc)
F{char} Find a character BACKWARD in the current line (Usage: to go to first occurance of c to the left of the cursor, you type Fc)
t{char} Like f but places the cursor before the character (Mnemonic : t - till)
T{char} Like T but places the cursor after the character
gg Move the cursor to the first line (compare this with H)
G Move the cursor to the last line (compare this with L)

* NBC - Non Blank Character

Line motions Vim picture

These motions let you move very fast between lines. You can go to any character you want on the current line with just 2 or at 3 keys, which is insanely fast compared to any other text editor. The last two motions (gg, G) are super useful and are certainly two of my most used commands.

Now we have one final set of motions to learn called Text Object motions (:help object-motions). Text objects is an important concept in Vim and we will cover that in depth in a future article. For now let's look at these motions.

Text Object Motions

Motion What it does?
( Go to the beginning of the PREVIOUS sentence
) Go to the beginning of the NEXT sentence
{ Go one paragraph BACKWARD
} Go one paragraph FORWARD

These four motions are very useful too. Especially if you're a programmer, the { and } will make navigating the code base a breeze.

And with that, we have covered all the basic Vim motions for you to get started. There is just one more important thing you need to know in conjunction with Motions. I haven't told you about this till now because I wanted you to get a full grasp of Vim motions before I explain this. Anyway, here it goes ..

Every Vim Motion takes a count before it

That's it. It might seem simple and it is simple, but its usefulness is just immeasurable.

Let's say you have to move eight lines down. To go eight lines down you don't have to frantically type jjjjjjjj. Just simply type *8j*. Similarly 4k to go four lines above, 6w to go to the sixth word from the cursor and so on. This is just such a useful feature that quite literally Sky is the limit for what you can do with this. Want to go to the second e after the cursor? Try 2fe and your cursor lands directly on e. Similarly to go to the ending of the 5th line below just do 5$ and B.A.M!

This opens up a whole new world of combinations for you to use and I hope you will make use of all of them. With these motions you can move to any place you want in the file with minimal number of keystrokes and your ultimate aim should be to accomplish everything with the minimum possible number of keystrokes. Be a Vim Ninja and conquer the world!

Vim ninja image

Well, That is all for this article folks. Will see you again in the next one. Until then, Keep practicing and Happy Vimming!

← Prev Next →




For more Vim stuff : vimtutorials.org

Follow FreBlogg on Facebook for more interesting articles.

Attributions:

Vim Logo - Vim Replacement Icon http://wolfrosch.com/works/goodies/vim (CC BY-NC-ND 3.0)

Vim Ninja image - https://goo.gl/QgTrsY (Originally from Practical Vim by Drew Neal)

October 09, 2016

Navigating in Vim I | Your First Lesson In Vim

00:00 Posted by Durga swaroop Perla , , No comments

This is the third article in a series titled, "Your First Lesson In Vim". These articles are written with a goal of helping out new Vim users by teaching the awesomeness of the Vim editor there by extending the Vim community. Vim though quite powerful, has a bad rep for being hard to learn and hard to get started with. So, even when someone is interested in learning about Vim, that infamous learning curve seem to be scaring them off. Hopefully this series will put those fears to bed.

Vim Logo

In the last article How To Exit Vim, we have seen what Vim modes are and what they do. So, If you know about Visual Mode, Insert Mode, Command Mode and Normal Mode, then continue with this article. Otherwise take a look again at the previous article. Vim modes are really important to understand this article and the upcoming ones.

I wanted this to be a part of the previous article but since this is really important and has a lot of potential information to discuss, I decided to give this its own full article. We will be spending most of our time in Normal mode here as that is where we will navigate in the file. You have seen how you navigate in Vim using h j k l. If you haven't figured out already, Vim's main philosophy is increasing your productivity and because of this some of the things Vim does might seem different compared to the usual way you are used to in other editors. Using h j k l is one of those things.

vim navigation

We have covered this in the last article but as promised I will expand about it here. If you look at your keyboard you will see that h j k l are on your Home Row (unless you are using Dvorak Keyboard, in which case this article probably won't help you much). Having the navigation keys on the home row is such an advantage as you don't have to move your fingers at all to access them. Going to the arrow keys for navigating is tiresome and time consuming. Don't think so? Well try it out yourself. Rest your fingers on their normal positions on the Home row (a s d f - j k l ;) and try to hit the UP arrow and come back. Did you see the travel involved in that? Do it again and see how you have moved your hand away from the keys and came back. Do it 5 more times and tell me If i am wrong when I say its just unnecessary travel, Especially since you have the navigation keys right on the home row in Vim. This is one of the reasons why Vim users are usually pretty fast. They don't keep moving their hands on and off the keyboard every time you have to go up or down. And again this could save you from potential RSI injuries.

qwerty keyboard

So, I strongly advise you to stop using UP and DOWN arrow keys. To use the h j k l keys more, try playing Vim Adventures. Its a fun game where you go around the textland collecting characters using Vim's navigation controls. It will help you use the h j k l keys and just after a couple of tries it becomes muscle memory.

One more thing that you won't see Vim users (#VimRocks) using is Mouse. The argument against using Mouse is the same one as that for the arrow keys. You are taking your hands off your main row which not only breaks your typing flow but also is just plain annoying. Its the same for mouse except you're moving your hand even further which makes it that much worse.

Getting rid of Arrow keys and Mouse is not an easy thing. This is cert ainly something that takes time to get used to. But once you do, you will be that much faster in your work flow.

Vim Motions

Vim Motions are the amazing things that make Vim users so fast. You already know about h j k l. Motions are just about anything that moves your cursor from one place to another. Apart from that you also have w W b B e E H M L. Let's see what they do.


Command What it does?
w Move the cursor to the starting of the next word
W Move the cursor to the starting of the next WORD
b Move the cursor to the starting of the previous word (Mnemonic - back)
B Move the cursor to the starting of the previous WORD
e Move the cursor to the end of the current word (Mnemonic - end)
E Move the cursor to the end of the current WORD
H Move the cursor to the First line of the current visible screen (Mnemonic - High)
M Move the cursor to the Middle line of the current visible screen (Mnemonic - Middle)
L Move the cursor to the Last line of the current visible screen (Mnemonic - Low)

The usage of H M L commands should be clear with this image below. They move your cursor to first, middle and last line of the screen respectively.

vim hml motions

To understand about w b e and their upper case variants we have to understand how word and WORD are defined in Vim. From the official documentation (:help word),

A word consists of a sequence of letters, digits and underscores, or a sequence of other non-blank characters, separated with white space (spaces, tabs, )

A WORD consists of a sequence of non-blank characters, separated with white space

In short, a group of characters with out a space between them is a WORD and there can be multiple words in that. With that definition let's take a look at some examples and identify the number of words and the number of WORDS in them.

Word # of words # of WORDS
hello world 2 (hello,world) 2 (hello,world)
hello-world 3 (hello,-,world) 1 (hello-world)
hello_world 1 (hello_world) 1 (hello_world)

Once you understood the difference between word and WORD, all the motions explained in the first table would be clear. Just to make the foundation firm, try them out yourself. Type something in a file and try to see what each of the w b e W B E H M L commands are doing and how they are moving the cursor. All the motions we have covered in this article are called Word motions (:help word-motions). There are some more Vim motion commands that you need to know to quickly navigate with ease. To keep this article simple, we will end this discussion here and will pickup again in the next article where we will discuss about the other motion commands. So, Keep practicing these motions combined with other commands discussed in How To Exit Vim and you would be really fast already. Fast like a Puma!


Well, That is all for this article folks. Will see you again in the next one. Until then, Keep practicing and Happy Vimming!

← Prev Next →




For more Vim stuff : vimtutorials.org

Follow FreBlogg on Facebook for more interesting articles.

Attributions:

Vim Logo - Vim Replacement Icon http://wolfrosch.com/works/goodies/vim (CC BY-NC-ND 3.0)