Tuesday 24 January 2017

Handle special numbers not handled by libphonenumber.

libphonenumber is Google's common Java, C++ and JavaScript library for parsing, formatting, and validating international phone numbers. 

Project on GitHub is here - https://github.com/googlei18n/libphonenumber

to add it to your android project use -

 compile 'com.googlecode.libphonenumber:libphonenumber:8.0.1'

Use :

public static boolean isSpecialNumber(PhoneNumber number) {
    if (number.getCountryCode() == 31) {
        // handle special M2M numbers: 11 digits starting with 097[0-8]        
        final Pattern regex = Pattern.compile("^97[0-8][0-9]{8}$");
        Matcher m = regex.matcher(String.valueOf(number.getNationalNumber()));
        return m.matches();
    }
    return false;
}


public void handleSpecialCases(Phonenumber.PhoneNumber phoneNumber) {
    PhoneNumberUtil util = PhoneNumberUtil.getInstance();

    // Argentina numbering rules
    int argCode = util.getCountryCodeForRegion("AR");
    if (phoneNumber.getCountryCode() == argCode) {
        // forcibly add the 9 between country code and national number
        long nsn = phoneNumber.getNationalNumber();
        if (firstDigit(nsn) != 9) {
            phoneNumber.setNationalNumber(addSignificantDigits(nsn, 9));
        }
    }
}

private int firstDigit(long n) {
    while (n < -9 || 9 < n) n /= 10;
    return (int) Math.abs(n);
}

private long addSignificantDigits(long n, int ds) {
    final long orig = n;
    int count = 1;
    while (n < -9 || 9 < n) {
        n /= 10;
        count++;
    }
    long power = ds * (long) Math.pow(10, count);
    return orig + power;
}

Sunday 8 January 2017

conquer the asynchronous behavior of callbacks.

Hey, I'm writing after a long time. Okay so why am I writing here? (even I don't know).

Anyways, one of the pains in my ass has been controlling the asynchronous behavior of callbacks and synchronizing it with my code control statements.

Example : Using addValueEventListener in firebase. What happens actually Firebase loads and synchronizes data asynchronously. Now you know what all difficulties may be faced due to this. Consider one example:



private boolean checkQuizStartTime()
{
    FirebaseDatabase database = FirebaseDatabase.getInstance();

    final int[] flag = {0};

    DatabaseReference mainDbRef = database.getReferenceFromUrl("https://....com/");

    DatabaseReference quizStartTime = mainDbRef.child("quiz_start");

    quizStartTime.addValueEventListener(new ValueEventListener() {
        @Override        public void onDataChange(DataSnapshot dataSnapshot) {

            String value = dataSnapshot.getValue(String.class);
            if (value.equals("yes"))
                flag[0] = 1;
            else                flag[0] = 0;
        }

        @Override        public void onCancelled(DatabaseError databaseError) {

        }
    });

    return flag[0] == 1;
}

The Method I wrote above always returns false no matter what value is present at key "start_quiz". Again the reason is the asynchronous execution of the callback. By the time the value of flag[0] gets updated the methods returns.

Anyways there as much trivial (jugadu in Hindi) solutions to it. Previously when I use to encounter such situation I use this trivial method only. The example in this situation you can use SharedPreference when you store the value inside the onDataChanged method and later you can access the value stored inside the SharedPreference file.


Another way can be waiting for few seconds until the asynchronous call gets completed and updated the value written inside the onDataChanged method. You can use Handler like this:



new android.os.Handler().postDelayed(
        new Runnable() {
    public void run() {
    }
}, 2000);


But doing all these things may work for some particular test instances. But this is not going to make our application scalable. So let us try to understand the reason behind this and learn proper concepts for it.



You have two choices for dealing with the asynchronous nature of this loading:
  1. squash the asynchronous bug (usually accompanied by muttering of phrases like: "it was a mistake, these people don't know what they're doing")
  2. embrace the asynchronous beast (usually accompanied by quite some hours of cursing, but after a while by peace and better behaved applications)

make the asynchronous call behave synchronously


For this we can use Semaphore class, we can create its object before the callback and use release method on its object inside the onDataChagned method.

Semaphore semaphore = new Semaphore(0);
....callback
onDataChanged()
....semaphore.release();


But there are problems I faced on my android. It blocked my app however it worked fine on JVM.

A more Ideal way is to 

embrace the asynchronous nature of data synchronization in Firebase


If you instead choose to embrace asynchronous programming, you should rethink your application's logic.
You currently have "First load the bookmarks. Then load the sample data. And then load even more."
With an asynchronous loading model, you should think like "Whenever the bookmarks have loaded, I want to load the sample data. Whenever the sample data has loaded, I want to load even more." The bonus of thinking this way is that it also works when the data can be changed and thus synchronized multiple times: "Whenever the bookmarks change, I want to also load the sample data. Whenever the sample data changes, I want to load even more."
In code, this leads to nested calls or event chains:
private boolean checkQuizStartTime()
{
    FirebaseDatabase database = FirebaseDatabase.getInstance();

    final int[] flag = {0};

    DatabaseReference mainDbRef = database.getReferenceFromUrl("https://-.,,.com/");

    DatabaseReference quizStartTime = mainDbRef.child("quiz_start");

    quizStartTime.addValueEventListener(new ValueEventListener() {
        @Override        public void onDataChange(DataSnapshot dataSnapshot) {

            String value = dataSnapshot.getValue(String.class);
            myMethod(value);
        }

        @Override        public void onCancelled(DatabaseError databaseError) {

        }
    });

    return flag[0] == 1;
}
In the above code, we don't just wait for a single value event, we instead deal with all of them. This means that whenever the bookmarks are changed, the isonDataChange executed and we (re)load the sample data (or whatever other action fits your application's needs).

Tuesday 9 August 2016

Using 'using namespace std;'? But why?

Consider a simple code :

#include <iostream>
using namespace std;

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int main() {

    int a;
    int b;
    a = 7;
    b = 5;
    swap(a, b);
    cout << a << b;

    return 0;
}


Now when you will try to run this code you will find that the compiler doesn't give any error. Again question is why is the compiler unable to find the error?

So this is all due to the 'using namespace std;' basically our own defined method doesn't gets called in the whole program. The std::swap method gets called and the found these values swapped.

Now this is just a small example. When we write big codes then this can be a big pain in our ass. And sorting it our will be difficult unless we are not much experienced.

Don't forget String is immutable in Java

Generally we try to manipulate the String (in Java) as we manipulate std::string in C++. But String is immutable in Java.

Now consider a program where you may need to change all the space with some string literal as "#45", then to solve this problem in place we need to use the char array to store the string. Using the String will result creation of more that one copies of String ( or one copy of String and other char array).

Consider this program :


public class Four {
    
    public static void main(String []args)
    {
        String str = new String();
        java.util.Scanner scanner = new java.util.Scanner(System.in);
        str = scanner.nextLine();
        Four obj = new Four();
        int len = str.length();
        str = obj.changedString(str, len);
        System.out.println("New String Formed : "+str);
        scanner.close();
    }
    
    public String changedString(String str, int len)
    {
        int sCount = 0;
        for(int i = 0; i < len; ++i)
        {
            if (str.charAt(i) == ' ')
                sCount++;
        }
        int newLen = (2*sCount) + len;
        
        char str2[] = new char[newLen+1];
        str2[newLen] = '\0';
        
        for (int i = len-1; i >= 0; i--) 
        {
            if (str.charAt(i) == ' ')
            {
                str2[newLen -1] = '0';
                str2[newLen -2] = '2';
                str2[newLen -3] = '%';
                newLen = newLen-3;
            }
            else
            {
                str2[newLen-1] = str.charAt(i);
                newLen = newLen - 1;
            }
        }
        return new String(str2);
    }
}


So this is not a in place algo. We need to use the char Array to make it in place.

Consider this program written in C++:


/*
program to replace all spaces in a string with '%20'. use inplace algo.
*/
#include<iostream>
#include<cstring>
int countSpaceLength(char *str, int len)
{
    int sCount = 0;
    for(int i = 0; i < len; ++i)
    {
        if(str[i] == ' ')
            sCount++;
    }
    return sCount;
}
int main()
{
    char str[500];
    std::cin.getline(str, sizeof(str));
    std::cout<<std::endl;
    int sLen = strlen(str);
    int sCount = countSpaceLength(str, sLen);
    int newStringLen = sLen + (2*sCount);
    str[newStringLen] = '\0';
    for(int i = sLen-1; i >= 0; --i)
    {
         if(str[i] == ' ')
         {
            str[newStringLen - 1] = '0';
            str[newStringLen - 2] = '2';
            str[newStringLen - 3] = '%';
            newStringLen -= 3;
         }
         else
         {
            str[newStringLen - 1] = str[i];
            newStringLen -= 1;
         }
    }
    std::cout<<"New String Formed "<<std::endl<<str<<std::endl;
    return 0;
}

We can some time use

String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);
Or we can use a StringBuilder:

StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');

System.out.println(myName);

Thanks

Thursday 30 June 2016

RestAdapter updated to Retrofit in new version of Retrofit v2 API

The RestAdapter class was renamed to Retrofit and the API was completely remade. After the API was completely remade its not only the RestAdapter class changed to the Retrofit class but method like setEndPoint() and many more method has also been changed.
Eg : when we have the dependencies as compile 'com.squareup.retrofit:retrofit:1.9.0', then we use : RestAdapter restAdapter = new RestAdapter.Builder()
        .setEndpoint("http://www.json-generator.com/api/json/get")
        .build();
Later when new version of Retrofit came i.e. Revrofit v2.0 then we have to write this : 
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://www.json-generator.com/api/json/get").build();

As of now we have the latest version of Retrofit v2.1. To know any updates about latest release of
Retrofit API visit :- http://square.github.io/retrofit/

Sunday 22 May 2016

An editorial on function to find the prime number with least time complexity :)

  • The algorithm can be improved further by observing that all primes are of the form 6m ± 1, with the exception of 2 and 3.
  • This is because all integers can be expressed as (6m + i) for some integer k and for i = −1, 0, 1, 2, 3, or 4; 2 divides (6m + 0), (6m + 2), (6m + 4); and 3 divides (6m + 3).
  • So a more efficient method is to test if n is divisible by 2 or 3, then to check through all the numbers of form 6m ± 1 ≤ √n(sqrt(n)).
  • This is 3 times as fast as testing all m up to √n.
    int CheckPrime(unsigned int number) {
        if (number <= 3 && number > 1) 
            return 1;            // as 2 and 3 are prime
        else if (number%2==0 || number%3==0) 
            return 0;     // check if number is divisible by 2 or 3
        else {
            unsigned int i;
            for (i=5; i*i<=number; i+=6) {
                if (number % i == 0 || number%(i + 2) == 0) 
                    return 0;
            }
            return 1; 
        }
    }
  • This code is written in C, in java we don't have unsigned keyword(however in java 8 it is included).