Power function

In C/C++ (and also other languages), we have the built in power function to raise a number to a given power. What if we need to calculate the power of a number to 100, like \(2^{100}\)? This is often the case in competitive programming. Maybe we'll run a loop 100 times and calculate it, but this is so inefficient. So, we need to find a power function which can calculate the power to a given number really fast.

Let's consider the expression \(2^{100}\). We can rewrite this to \((2^{50})^{2}\) and the result will not change. Now, we have a smaller power to calculate, right? We can again, rewrite the previous expression to \(((2^{25})^{2})^{2}\). Note that, it was possible to rewrite the expression by halving the power inside the parenthesis only because the power was even. If we were try and rewrite an odd power, it wouldn't be possible. We cannot divide an odd number to half evenly (e.g 25 cannot be divided by 2 evenly). What can we do then? We can just multiply the number itself to balance the power (increase the power by one, to make it odd). Let's rewrite the last expression:
$$
((2^{24+1}))^{2})^{2}
\\ = ((2*2^{24}))^{2})^{2}
\\ = ((2*(2^{12})^{2})^{2})^{2}
$$ The result is still the same. We can go on like this until the power becomes zero. We can see that this pattern keeps repeating and after each step, its calculating a smaller state, its a recursive problem! Here's a picture taken from http://www.shafaetsplanet.com/planetcoding/?p=936 demonstrating the recurring steps.

Implementation in code:
int POW(int x, int p) {
   // x^0 = 1 where x is any number
   if (p == 0) return 1;
   
   // if the power is not even, then multiply the number
   // itself to balance it as stated in the post
   if (p % 2 != 0) {
    int n = POW(x, p/2);
    return x * n * n;
   } else {
    int n = POW(x, p/2);
    return n * n;
   }
}

LightOJ 1000 - Greetings from LightOJ

In this problem, we're asked to just add two input numbers and print them out accordingly. Here's the code.


#include <bits/stdc++.h>
using namespace std;

int main() {
  int T, i=1;
  scanf("%d", &T);
  while (T-- > 0) {
    int a, b;
    scanf("%d %d", &a, &b);
    printf("Case %d: %d\n", i++, a+b);
  }
  
  return 0;
}

Enabling gzip compression in django

GZip compression allows the server to compress data before it is sent (on the fly) and the upon arrival of the data on client side, the browser does the unzipping/decompression of the data and shows it to the user. Enabling gzip compression can help you save about 50% plus bandwidth, thus not only making your site more responsive, but also saving huge amount of cost. Here's how you enable gzip compression in Django:

Open your settings.py file and find the MIDDLEWARE_CLASSES tuple. Add the following at the top:

MIDDLEWARE_CLASSES = (
    'django.middleware.gzip.GZipMiddleware',
    # ...
)

And, that's it! You can also enable gzip compression from your Apache, Ngingx and other servers too, look up their documentation.

Constructors in C++

A constructor, as its name implies, is used to create (construct) objects. It's like any another function but with exceptions -
A constructor is always associated with a class and this function does not return anything and thus it does not have any return type associated with it.
It is used only for aiding in creation of objects. Let's look at how a normal function looks:

// this function has a return type of 'int'
int add(int a, int b) {
 return a + b;
}

Name of the function is add, its return type is int (i.e it returns an integer after it is done with its operations) and it takes in two parameters - a and b.
Now, let's say we have a Box class and for creating a Box we need to follow some steps, we cannot just create one out of nothing. For example, we cannot create a Box without the required width and height obviously! Here's how a constructor for the Box class might look like:

class Box {
public:
 // Box is the name of the constructor function
 // ITS NAME IS ALWAYS THE SAME AS ITS CLASS NAME
 // Since, a constructor function does not return anything,
 // it does not have a return type before its name
 Box(int width, int height) {
  // this constructor takes width and height

  /*
  Possible steps to make a Box object

  1.  Get a cardboard
  2.  Get the desired width and height
  3.  Make (construct) the box by
   cutting the cardboard according to width/height
  */
 }
};

Here, we defined a constructor for the Box class. Notice, the name of the constructor function is the same its class name and that it has no return type. Let's complete the definition of our class and use it in code.

#include <iostream>
using namespace std;

class Box {
 int box_width;
 int box_height;

public:
 // Box is the name of the constructor function
 // ITS NAME IS ALWAYS THE SAME AS ITS CLASS NAME
 // Since, a constructor function does not return anything,
 // it does not have a return type before its name
 Box(int width, int height) {
  // this constructor takes width and height

  /*
  Possible steps to make a Box object

  1.  Get a cardboard
  2.  Get the desired width and height
  3.  Make (construct) the box by
   cutting the cardboard according to width/height
  */

  box_width = width;
  box_height = height;

  cout << "Making a new box..." << endl;
  cout << "Gathering some cardboard..." << endl;
  cout << "Width: " << box_width << endl << "Height: " << box_height << endl;
  cout << "Making the box with the given width and height..." << endl;
  cout << "Done! Enjoy your new box" << endl;
 }
};

int main() {
 // Create a Box object named b
 Box b(30, 20);

 return 0;
}

Now, run this program yourself and enjoy making new boxes!

Classes and Objects in C++ and real life

Class. Object. They are used frequently in the land of object oriented programming (OOP). Classes and objects are nothing mysterious. Look around you, there are so many objects - table, chair, mobile, TV, fridge, etc. All of these are real life objects.

Manufacturers use blueprints to create these objects. The blueprints define how every object of a particular type of product (say iPhone 7) will look like and how they'll behave. Since, all the iPhone 7 objects are created from a single iPhone 7 blueprint, they all look and behave the same, for example - they all have a camera at the back, they can make calls, etc. In our OOP land, these blueprints are known as Class. A class defines how an object will be created, the properties it'll have and the actions that can be performed on that object.

Now let's observe an object. Each object has its own properties, for example, think of your mobile phone - it has properties like "the phone is switched on/off", "the phone's brightness level is set to 5", "the phone is in vibration mode" and so on. Apart from the properties that your mobile has, you can also do stuffs (perform some action) with it - "switch on/off the phone", "increase brightness level", "make a call", "text to someone", etc. This is exactly what an object in OOP is. An object has properties and functions/methods (which perform an action).

Now that we know what an object and a class is, let's see how they're defined in code by creating a Mobile class:

#include <iostream>
using namespace std;

class Mobile {
 // name of the mobile
 string mobile_name;
 // volume level of the mobile
 int volume_level;
 // brightness level of the mobile
 int brightness_level;
 // by default the phone is off
 bool phone_is_on = false;
};

We defined a Mobile blueprint (class) which has properties - mobile_name, volume_level, brightness_level and phone_is_on (which denotes the phone is either on/off). Now, let's define some actions for the Mobile class.

class Mobile {
 // name of the mobile
 string mobile_name;
 // volume level of the mobile
 int volume_level;
 // brightness level of the mobile
 int brightness_level;
 // by default the phone is off
 bool phone_is_on = false;

public:
 void toggle_phone_state() {
  if (phone_is_on == false) {
   cout << "Phone is switched on." << endl;
   phone_is_on = true;
  } else {
   cout << "Phone is switched off." << endl;
   phone_is_on = false;
  }
 }

 void set_volume(int vol) {
  volume_level = vol;
 }

 void set_brightness(int brightness) {
  brightness_level = brightness;
 }
};

Now, we have defined actions for the class. Notice, how actions (methods/member functions) are just plain ordinary functions. Let's use this blueprint (class) to create an object.

#include <iostream>
using namespace std;

class Mobile {
 // name of the mobile
 string mobile_name;
 // volume level of the mobile
 int volume_level;
 // brightness level of the mobile
 int brightness_level;
 // by default the phone is off
 bool phone_is_on = false;

public:
 void toggle_phone_state() {
  if (phone_is_on == false) {
   cout << "Phone is switched on." << endl;
   phone_is_on = true;
  } else {
   cout << "Phone is switched off." << endl;
   phone_is_on = false;
  }
 }

 void set_volume(int vol) {
  cout << "New volume is: " << vol << endl;
  volume_level = vol;
 }

 void set_brightness(int brightness) {
  cout << "New brightness is: " << brightness << endl;
  brightness_level = brightness;
 }
};

int main() {
 // Create an object of class Mobile named - my_android
 Mobile my_android;
 // perform actions on the my_android object by using a dot and the action name
 // my_android . action_name();
 my_android.toggle_phone_state();
 my_android.set_volume(5);
 my_android.set_brightness(3);

 return 0;
}

NOTE: You may have noticed a public keyword. Its okay to not understand it for now, just write it as it is.
Now, you can create as many Mobiles as you want. Go and run the program!

Function overloading in C++: Basic

Function overloading is an interesting concept and its very useful in some scenarios. So, what is function overloading? Function overloading means defining multiple functions with the same name which differ in either their parameter numbers, parameter types or both. Let's see an example to clear things out:
Let's say we want to define an add function. Depending on the type of its parameters, it'll return different values. For example, when you pass two integers 5 and 3 it'll return 8. When you pass 5.05 and 2.90 it'll return 7.95, when you pass two strings - "hello " and "world" it'll concatenate (join) them together and return "hello world". Here's how we do can do it -

#include <iostream>
using namespace std;

// add two 'int' and return their sum
int add(int a, int b) {
 return a + b;
}

// add two 'double' and return their sum
double add(double a, double b) {
 return a + b;
}

// concatenate (join) two 'string' and return the result
string add(string a, string b) {
 return a + b;
}

// this function just adds 5 to any number it is supplied
int add(int x) {
 return x + 5;
}

int main() {
 // this add(5, 3) will call the function at line 5
 cout << add(5, 3) << endl;

 // this add(5.05, 2.90) will call the function at line 10
 cout << add(5.05, 2.90) << endl;

 // this add("hello ", "world") will call the function at line 15
 cout << add("hello ", "world") << endl;

 // this add(10) will call the funciton at line 20
 cout << add(10) << endl;number

 return 0;
}

The output will be:

8
7.95
hello world
15

As you can see, depending on the type and/or number of arguments supplied, the compiler is smart enough to call the correct function.
Function overloading is also possible in the context of a class. You can have multiple overloaded functions as members of the same class. Not only that, even constructors can be overridden.

NOTE: Return type of a function is never taken into consideration in case of function overloading. Always keep that in mind.

Default parameters in C++

In C++, you can define a default value for parameter(s) of a function. Here's how you do it:

#include <iostream>
using namespace std;

void show_info(string name = "Pantha", int age = 20) {
 cout << name << " is " << age << " years old." << endl;
}

int main() {
 show_info();
 show_info("Beck");
 show_info("Tony", 22);

 return 0;
}

Here, we have defined a function named show_info which takes two arguments - name and age. We also set a default value for name = "Pantha" (which is of type string) and also, the default value for age = 20. Then we call the function show_info three times - three different ways (in this case). Its as easy as that!
One more thing that you should be aware of is, you cannot change the position of arguments while calling the function. For example, you CANNOT DO the following:

show_info(20, "Andy");

That's all!

C++ vector basics

What is a container (in our day to day life)? A container is something that holds some stuffs. In that sense, arrays that we declare in C++ can also be called containers. They hold some values together under one name (the name of the array). Here's how we define an array of ints:

int x[3] = {10, 30, 5};

(You can define an array in other ways too, but let's not get into that here). This array, which is named x, is an array of 3 integers. Now, what if we wanted to add another integer, say 500, to this array, how would we do so? Maybe you're thinking of creating another array with size 4 and copying all the previous values into the new array including the new value we just wanted to put. Or even better, instead of increasing the size to 4, double the size of the new array so that we don't have to resize it frequently. But all this boilerplate code for just a simple operation! What if there was a data structure (a container) which would automatically increase its size as we put items into it and shrink itself as we purge items from it? Welcome std::vector (resides in the <vector> header)! vector is a container which is very similar to an array, in simpler terms, you can think of vectors as an array and you can almost always use it in place of an array. Its a very convenient data type which is provided by the Standard Template Library (STL) in the std namespace. So, let's see how we can define a vector and use it.

#include <iostream>
#include <vector>
using namespace std;

int main() {
 // this is our plain old array
 int x[3] = {10, 30, 5};

 // and this is our new vector!
 // this statement is equivalent to saying,
 // I want a vector named 'v' which will hold 'int' values
 vector<int> v;

 // now, lets insert values into the vector v
 v.push_back(10);
 v.push_back(30);
 v.push_back(5);

 // See? We did not specify the size of the vector
 // while declaring, it automatically grew in size
 // to accommodate for the new values

 // now, we can iterate over the vector just like an array!
 // NOTE: We can get the size of a vector very easily
 // by calling its size() method
 for (int i = 0; i < v.size(); i++) {
  cout << v[i] << endl;
 }

 // EXTRA! When you use a vector, you can use another
 // version of for loop known as for-each, which is available
 // in C++11 and up
 for (int i : v) {
  cout << i << endl;
 }

 return 0;
}

That's it for the basics!

Tip: Downloading files faster (for slow downloads)

If your internet connection has a good speed but one of your downloads is taking too much time, then its happening most probably because of server location. To download such files faster, try using a free proxy site such as https://hide.me/en/proxy for downloading the file. If your download is still slow, try selecting a different location for your proxy browsing. 

Learning Django - 2

This is the second post among a series of posts about my django learning experience.

I'll start clean and set things up for the whole development process. I'll be using, Ubuntu, Python 3 (https://www.python.org/downloads), virtualenv (https://virtualenv.pypa.io) so that I don't have any dependency conflicts with my other projects, pip for installing these tools and obviously django. Considering that I have the latest python 3 installed (pip comes packaged by default), I ran the following command ($ denotes a terminal session):

$ # Use the sudo command if necessary (only applicable for *nix systems, n/a for windows)
$ [sudo] pip install virtualenv
$ virtualenv virtual_folder
$ cd virtual_folder
$ source bin/activate

This installed virtualenv (short for Virtual Environment) and created a directory named virtual_folder for holding the new virtual environment. cd-ed into it and activated the virtual environment. Deactivating is easy, just run deactivate and it'll deactivate itself. Next, I'll install django with this command:

$ [sudo] pip install django

After django is installed, a terminal restart was needed to load in the new binary. Then I created a project named website with this:

$ django-admin startproject website

A new directory named website is created in the current directory. This contains all the necessary backbone for running a simple django server. cd (change the terminal's directory to point to it) into it. Now, the initial configuration is done and its time for a test run! Run this command:

$ python manage.py runserver

And it should start a server in the localhost at port 8000 or whichever is printed in your terminal. Visit: http://127.0.0.1:8000/ to view the new django server up and running! I'll be explaining in short, what each file is and why its necessary in my next post.

This is it for the initial setups.

Learning Django - 1

I'll be writing a series of posts as I continue my journey to learning django from scratch (note, I already know to some extent and use django but I felt like I had a gap somewhere in the middle). So, this is the first post of the a series of posts I'm going to write about django as I continue my journey learning it!

First, what is Django anyway? Django is a web (application) development framework for the Python programming language. It's available at https://www.djangoproject.com
As of writing this, the latest available version is 1.11.3 which I'll be using over the course of my learning path. Some of the prominent features of django include security right from the start, scalability (Instagram runs on Django, although there are other technologies in their stack for managing different parts of the whole infrastructure), built in ORM for database access, built in template system, etc. Django's philosophy towards development is the MVC (Model View Controller) pattern as described here in detail: https://docs.djangoproject.com/en/1.11/faq/general/#django-appears-to-be-a-mvc-framework-but-you-call-the-controller-the-view-and-the-view-the-template-how-come-you-don-t-use-the-standard-names

That's all for the first post!

UI design

Screenshots of the UI I'm designing and working on, for one of my current projects.





Shortcut: String to number in JS

Put a + (plus) operator in front of a string to convert it into a number.

+'12' (string) => 12 (number)
let x = '40'; (string)
+x => 40 (number)
There are three types of people.

  1. People who complain about the flow
  2. People who do nothing and go with the flow
  3. People who go with the flow and change the flow themselves

Now, you choose which one you want to be, do nothing, complain or change?

Structures in C

An introduction to structures (struct) in C.



Reactive Extensions (Rx) Programming

Reactive extensions (Rx) is a set of tools/API available for almost any popular languages/platforms out there, which aids in a new way of asynchronous programming (well, not completely new :p).

Most of the time, the way we write programs, we query data from a data source and wait for that data set to be ready. Once the data from the source is ready, only then we can perform different kinds of operation on it. This waiting process is blocking or synchronous i.e it blocks the program execution and waits for the data to be loaded. What if there was a mechanism that allowed the data source to push data to us and we could perform various kinds of operations on the data as it comes? Welcome to Reactive Extensions (Rx). Rx allows us to do exactly this. It exposes a set of types (Observables  & Observers) and operators (operations we can perform on those types) to aid us in asynchronous programming. This way, we don't need to wait for the data by blocking the program execution. Besides, we can perform operations on the data as it comes rather than wait for the whole data set to be ready. Its quite similar to event driven programming where you subscribe to an event by passing a callback and the system will execute the callback whenever an event happens. Although, Rx is much more powerful than just ordinary event driven mechanism.

Switching remote URL in git

  1. Open terminal.
  2. Change the current working directory to your local project.
  3. Use the command (this will list the current remote URL):
    • git remote -v
  4. Then issue the following command (this will change the remote URL):
    • git remote set-url origin https://your-git-rep-url.git/
  5. Verify that the remote URL has changed:
    • git remote -v

Power function

In C/C++ (and also other languages), we have the built in power function to raise a number to a given power. What if we need to calculate ...