CodeChrist - This is a personal blog which I write to help follow coders

If you like it, feel free to comment and appreciate the good work


Following are the some features of CodeChrist

  • Easy to navigate and use.
  • You can subscibe for emails
  • CodeChrist is beautiful on every screen size (try resizing your browser!)
by · 2 comments:

A tutorial on how to get Profile Picture, email, etc through Google Plus and Facebook in ASP.net MVC

I am assuming you have already got Client Secret and Client Id from Google Plus Api.

Now in Startup.Auth.cs remove the below code
 
//app.UseFacebookAuthentication(

            //   appId: "",

            //   appSecret: "");
and paste this
 var googleOptions = new GoogleOAuth2AuthenticationOptions()
            {
                ClientId = "9ac07032788-agi11p78tp105iqkodc8tebie14jbd7i.apps.googleusercontent.com",
                ClientSecret = "B1cvuBL5rBPUNh1molEBkVLVl",
                Provider = new GoogleOAuth2AuthenticationProvider()
                {
                    OnAuthenticated = (context) =>
                    {
                        context.Identity.AddClaim(new Claim("urn:google:name", context.Identity.FindFirstValue(ClaimTypes.Name)));
                        context.Identity.AddClaim(new Claim("urn:google:email", context.Identity.FindFirstValue(ClaimTypes.Email)));
                        //This following line is need to retrieve the profile image
                        context.Identity.AddClaim(new System.Security.Claims.Claim("urn:google:accesstoken", context.AccessToken, ClaimValueTypes.String, "Google"));

                        return Task.FromResult(0);
                    }
                }
            };

            app.UseGoogleAuthentication(googleOptions);
And in AccountController.cs change the method ExternalLoginCallback as
 
  
        // GET: /Account/ExternalLoginCallback
        [AllowAnonymous]
        public async Task ExternalLoginCallback(string returnUrl)
        {
     
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
            if (loginInfo == null)
            {
                return RedirectToAction("Login");
            }
            var accessToken = loginInfo.ExternalIdentity.Claims.Where(c => c.Type.Equals("urn:google:accesstoken")).Select(c => c.Value).FirstOrDefault();
            Uri apiRequestUri = new Uri("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + accessToken);
            dynamic userPicture;
            //request profile image
            using (var webClient = new System.Net.WebClient())
                {
                var json = webClient.DownloadString(apiRequestUri);
                dynamic resul = JsonConvert.DeserializeObject(json);
                userPicture = resul.picture;
            }
            this.Session["userPicture"] = userPicture;

 
            // Sign in the user with this external login provider if the user already has a login
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
            switch (result)
            {
                case SignInStatus.Success:
                    return RedirectToLocal(returnUrl);
                case SignInStatus.LockedOut:
                    return View("Lockout");
                case SignInStatus.RequiresVerification:
                    return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
                case SignInStatus.Failure:
                default:
                    // If the user does not have an account, then prompt the user to create an account
                    ViewBag.ReturnUrl = returnUrl;
                    ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                    return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
            }
            //get access token to use in profile image request
           
        }

Now you can access image anywhere in project, because we have put it in Session variable. To show image, you can try this
 
@{
    ViewBag.Title = "About";
}
@ViewBag.Title

@ViewBag.Message
@HttpContext.Current.Session["userPicture"]
This is your image
@HttpContext.Current.Session["hello"] Use this area to provide additional information.
It will look something like this
Read More
by · No comments:

How to check programmatically if an application is installed or not in Android?

If the application is already installed in the device the application is open automatically.
Otherwise install the particular application.

    public class Example extends Activity {
  1.     @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            //Put the package name here...
            boolean installed = appInstalledOrNot("com.Ch.Example.pack");  
            if(installed) {
                //This intent will help you to launch if the package is already installed
                Intent LaunchIntent = getPackageManager()
                    .getLaunchIntentForPackage("com.Ch.Example.pack");
                startActivity(LaunchIntent);
    
                System.out.println("App is already installed on your phone");         
            } else {
                System.out.println("App is not currently installed on your phone");
            }
        }
    
        private boolean appInstalledOrNot(String uri) {
            PackageManager pm = getPackageManager();
            boolean app_installed;
            try {
                pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
                app_installed = true;
            }
            catch (PackageManager.NameNotFoundException e) {
                app_installed = false;
            }
            return app_installed;
        }
    }

Read More
by · No comments:

Window 8.1 Product Key

Window 8.1 Key

Enter the below key without hypens. This key works only on windows 8.1

XHQ8N-C3MCJ-RQXB6-WCHYG-C9WKB
Read More
by · No comments:

SPOJ 61. Brackets Solution

www.spoj.com/problems/BRCKTS/
This is another problem on Segment Trees. Although this is a basic/easy level problem.
In input a string of brackets will be given. The brackets can be open brackets or close brackets. Among these words we will distinguish correct bracket expressions. These are such bracket words in which the brackets can be matched into pairs such that
  • every pair consists of an opening bracket and a closing bracket appearing further in the bracket word
  • for every pair the part of the word between the brackets of this pair has equal number of opening and closing brackets . 
This means that the string can be of form 1.)  ()()   2.) (())   3.)   ((())) ,etc
But not of the form 1.)  )(  2.)  ))((   3.)  ())(()
If the string is of first form answer will be YES else if of second form answer will be NO.

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

#define MAX 300005

struct DATA{
    int open_brackets;
    int close_brackets;
    DATA(){
        open_brackets=close_brackets = 0;
    }
};

DATA sum[4*MAX];
char str[MAX];

void build_tree(int node, int a, int b){
    if(a>b){
        return;
    }
    if(a==b){
        if(str[a]=='('){      
            sum[node].open_brackets = 1;
            sum[node].close_brackets = 0;
        }
        else{
            sum[node].open_brackets = 0;
            sum[node].close_brackets = 1;
        }
    //    cout<<" sum["<<node<<"] "<<str[node]<<" "<<sum[node].open_brackets<<" "<<sum[node].close_brackets<<" ";
        return;
    }
  
    build_tree(2*node, a, (a+b)/2);
    build_tree((2*node)+1,((a+b)/2)+1, b);
  
    int ol = sum[2*node].open_brackets;
    int cl = sum[2*node].close_brackets;
  
    int orr = sum[2*node+1].open_brackets;
    int crr = sum[2*node+1].close_brackets;
  
    if(ol>=crr){
        sum[node].open_brackets = ol + orr - crr;
    }
    else {
        sum[node].open_brackets = orr;
    }
    if(ol<=crr){
        sum[node].close_brackets = cl+crr-ol;
    }
    else{
        sum[node].close_brackets = cl;
    }
//    cout<<" sum["<<node<<"] "<<str[node]<<" "<<sum[node].open_brackets<<" "<<sum[node].close_brackets<<" ";
}

void update_tree(int node, int a, int b, int val){
    if(a>b){
        return;
    }
  
    if(a==b){
        if(str[val]=='('){
            sum[node].open_brackets--;
            sum[node].close_brackets++;
            str[val] = ')';
        }
        else{
            sum[node].open_brackets++;
            sum[node].close_brackets--;
            str[val] = '(';
        }
        //cout<<str<<endl;
        return;
    }
    if(val <=(a+b)/2){
        update_tree(2*node, a, (a+b)/2,val);
     }
     else{
        update_tree((2*node)+1,((a+b)/2)+1, b,val);
    }
  
    int ol = sum[2*node].open_brackets;
    int cl = sum[2*node].close_brackets;
    int orr = sum[2*node+1].open_brackets;
    int crr = sum[2*node+1].close_brackets;
  
    if(ol>=crr){
        sum[node].open_brackets = ol + orr - crr;
    }
    else {
        sum[node].open_brackets = orr;
    }
    if(ol<=crr){
        sum[node].close_brackets = cl+crr-ol;
    }
    else{
        sum[node].close_brackets = cl;
    }
}
int main() {
    int stlen, m, k;
  
    for(int i = 1; i<=10; i++){
        printf("Test %d:\n",i);
        scanf("%d",&stlen);
        scanf("%s", str);
        stlen--;
        build_tree(1,0,stlen);
        scanf("%d",&m);
        while(m--){
            scanf("%d",&k);
            if(k==0){
                if(str[0]==')'){
                    cout<<"NO\n";
                }
                else{
                //    cout<<sum[1].open_brackets<<" "<<sum[1].close_brackets;
                    if(sum[1].close_brackets==0&&sum[1].open_brackets==0){
                        printf("YES\n");
                    }
                    else{
                        printf("NO\n");
                    }
                }
              
            }
            else{
                update_tree(1,0,stlen,k-1);
            }
        }
    }
    return 0;
}
Read More
by · No comments:

Unable to scan WhatsApp QR code ?

As you know that WhatsApp has released a web-version for its android, windows and ios WhatsApp app.
It is available on https://web.whatsapp.com/

But some users are not able to scan the QR code. So if you are one of them, you may try some of these steps -

1) Update your WhatsApp to the latest version availabe. This will most probably solve the issue.

2) Hold your phone still for some seconds. This may also be issue. So just hold your phone still for some seconds and let the QR code scanner scan the QR code from the website.

3) Don't scan QR code from a third party app. It will not work. Use only WhatsApp to scan QR code.
Third party apps can also steal your data so beware.

4) If none of the above options worked it may be because your phone is old. Apparently web based version  is only working on new phones. It will not work on devices that have display smaller than 4 inch screen. Like with Sony Xperia Go, Samsung Galaxy Y, Samsung Galaxy Ace, etc. So if your phone's screen is smaller than 4 inch either let WhtasApp solve the issue or buy a new phone :P

Read More
by · No comments:

Fibonacci

Fibonacci sequence is a series in the following sequence0,\;1,\;1,\;2,\;3,\;5,\;8,\;13,\;21,\;34,\;55,\;89,\;144,\; \ldots\;                                                          It can be easily seen from the above sequence that it is following this recurrence relation :
F_n = F_{n-1} + F_{n-2},\!\,    
Making a program of Fibonacci series is really easy. Here we will discuss to make Fibonacci series using iterative method and recursion.

Iterative Method


In this method we simply store the previous two values in two variables and use
 F_n = F_{n-1} + F_{n-2},\!\, to calculate next value.

Recursive Method

We normally do not use recursion to find Fibonacci numbers because if we do so, we calculate each value again and again.
function fib(n)
       if n <=1 return n
       return fib(n − 1) + fib(n − 2) 
Notice that if we call, say, fib(5), we produce a call tree that calls the function on the same value many different times:
  1. fib(5)
  2. fib(4) + fib(3)
  3. (fib(3) + fib(2)) + (fib(2) + fib(1))
  4. ((fib(2) + fib(1)) + (fib(1) + fib(0))) + ((fib(1) + fib(0)) + fib(1))
  5. (((fib(1) + fib(0)) + fib(1)) + (fib(1) + fib(0))) + ((fib(1) + fib(0)) + fib(1))
Finding same values again and again is not a good option. Therefore we do not use recursion.
Here is the program using recursion
Read More
by · No comments:

QuickSort

Defination

Quicksort, or partition-exchange sort, is a sorting algorithm which follows divide and conquer algorithm. We will first study the algorithm 
then will implement the algorithm in a C++ program.

Algorithm

Quicksort first divides a large array into two smaller sub-arrays: the low elements and the high elements. Quicksort can then recursively sort the sub-arrays.
The steps are:
  1. Pick an element, called a pivot, from the array.
  2. Reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.
  3. Recursively apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of elements with greater values. 

Recursion

In the quicksort function we pass the array and quicksort sorts elements i through k (inclusive) of array A. Then we check if left is less than right. If it is true we call partition. The partition array returns us a pivot index in the array, and the array is also changed.
Now the elements on the left hand side is smaller than the value of the pivot index and the elements on right side are larger than the pivot index.

We now call the quicksort function again but now for the smaller array of left hand side of the pivot index and similarly for the array on the right hand side of the pivot. These calls are made recursively.

 quicksort(A, i, k):
  if i < k:
    p := partition(A, i, k)
    quicksort(A, i, p - 1)
    quicksort(A, p + 1, k)

 Partition    

This is the in-place partition algorithm. It partitions the portion of the array between indexes left and right, inclusively, by moving all elements less than or equal array[pivotIndex] before the pivot, and the greater elements after it.We have used last element of the array as pivot index. We compare every element of the array with the pivot index and if it is less than pivot, we swap it with array[storeIndex]. Elements with indexes less than storeIndex are less than pivot. Notice that an element may be exchanged multiple times before reaching its final place. Also, in case of pivot duplicates in the input array, they can be spread across the right subarray

  // left is the index of the leftmost element of the subarray
  // right is the index of the rightmost element of the subarray (inclusive)
  // number of elements in subarray = right-left+1
  partition(array, left, right)
     pivotIndex := array[right]
     pivotValue := array[pivotIndex]
     swap array[pivotIndex] and array[right]
     storeIndex := left
     for i from left to right - 1
         if array[i] < pivotValue
             swap array[i] and array[storeIndex]
             storeIndex := storeIndex + 1
     swap array[storeIndex] and array[right] 
      // Move pivot to its final place
     return storeIndex 

 

Program

This is implementation of quicksort in C++.
Here is Scarlett Johansson if u didn't understand anything above. I hope it will make u feel better :)

Read More