CAUTION!

CAUTION! DANGER ZONE ahead. Beware of misinformation on the open internet. Contents of the site are mere opinions and are not always facts!

Sunday, September 11, 2016

Thursday, August 18, 2016

formspree for your static page, suitable for github pages.

Formspree home has all the information you need to set up a form for email submission without a mail server of your own, like the github pages.

If you think,
- The thank you page is not necessary for your site.
- And you do not want to reload the page.
- And you cannot whitelist formspree for CORS (example, the github pages).
- And there should be something that can be done on the client side.

continue reading...

I have reasoned out it is not possible without a thank you page. If you would like to know more, continue reading...

Option 1 with a form leads you to formspree's standard thank you page due to the form's action. I'm happy formspree supports our custom thank you page too.

Now, you need dynamic handling of the response and AJAX is the way...

Option 2 with AJAX request returns error response due to CORS request even though the mail is successfully sent.

How can you now differentiate the CORS error from the rest. You don't want to give false hopes for the form submitter, do you!

This is not possible from the client side or with the response alone. W3C specifies that CORS failures should be handled the same way as network errors and the response headers shouldn't be completely revealed by the browsers. If you want to have a non standard check anyway which is not recommended, you can check for status code 0 on chrome.

Long story Short - AJAX response cannot distinguish an error is due to un-whitelisted CORS request made to a expected domain.

Turns out CORS response was the motive of this post!

If you think its not convincing - or probably have a hack, leave a comment!

Wednesday, June 8, 2016

Set up NFS volume on Windows client.

Steps to work on a remote NFS workspace (Hosted on linux) from the Windows client machine.

GOAL:
- Work from the Windows local machine on a remote NFS workspace.
solution: Mount the remote NFS volume on the client Windows machine.
- Set up an editor to work with the workspace.
solution: Sublime Text is a good fit for C++ and various other languages, currently almost FREE!


1. Set up windows as NFS client. 
  • Click “start” -> search for “windows features” -> click “Turn Windows features on or off” -> “select services for NFS”

  2. Set up user credentials for write access. [WARNING! A hacker who gains access to this machine can get the UID and GID of the remote server]
  •  click start -> search for “regedit” -> goto “HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ClientForNFS\CurrentVersion\Default” -> right click “new”
  • Create DWORD(32-bit) keys as shown below.


  • Find UID and GID :
           - goto to the remote server machine -> enter “id” at the bash shell -> the UID and GID are in decimal.

3. Mount NWS to your local machine.

  • Open Cmd and enter,
          mount IP_Addr:/vol/vol_nfs_janani z: (replace volume name and drive letter)

  • Find the new drive under "my Computer".


4. Download Sublime Text 3 from https://www.sublimetext.com/
  •  Configure the workspace.
  •  Goto “File” -> Goto “Open Folder” -> open your workspace (on the mount drive)
  •  Goto “Project” ->click “save  project as..” (to open it next time)

5. Some sublime short cuts:
   end search: Esc
   Find in current file: Ctrl + F
   Find in complete folder : Ctrl + Shift + F (double click the line to open the line in the file)
   Goto Anything/ open file: Ctrl + P
   Function list : Ctrl + R
   Navigate Fwd: Alt + Shift + -
   Navigate Bck: Alt + -
   Goto Line : Ctrl + G
   Goto Definition: F12
   Automatic auto completion!

Recommended sublime Plug in's: Cscope, 

This is the basic use of this editor. Documentation has more. 

Tuesday, May 10, 2016

Typedef's must learn to be stronger

A typedef is aliasing a type.

Syntax: typedef type name
Example: typedef int length

Uses:

1. Give meaningful shorter names for really long type names. Specially, in case of template types and function pointers.
typedef myLongLongMeaningfulType tMeaningfulType
typedef std::map<int,std::map<int, std::vector<int> > > doubleIndexMap;

2. Change the underlying type when needed.
Requirement:  I am writing a math library with support for unsigned integers of 8 bit long.

without Typedef,
uint8_t add (uint8_t a, uint8_t b);

Why only 8 bit long!... The same library can handle 16 bit integers.
Uh-Oh! I must change all the types throughout the library.

with Typedef's,
typedef uint8_t supportType_t;
supportType_t add (supportType_t a, supportType_t b);

voila, I can now support 16 bit integers with a single change!!
typedef uint16_t supportType_t;

3. Document Types.
typedef uint8_t length_t; // always stores lengths in uint8 format.
typedef uint8_t area_t; // always stores area's in uint8 format.

The typedef's are weakly typed and cause problems. During syntax and semantic analysis (C++ is not context free grammar), all the alias types are resolved to the same underlying type.

typedef uint8_t length_t;
typedef uint8_t area_t;
length_t
and
area_t
are still uint8.

1. No type safety: The synonym types can be used interchangeably or together,
length_t m_boxLength = 10_CM;
area_t m_boxArea = 100_SQCM;

length_t getLength()
{
     return m_boxArea; // Bug, no compiler warning. both area and length are uint8
}

if(box1.getLength() == box2.getArea()) // Bug, no compiler warning. both area and length are uint8

2. Prevent overloading: Both aliases are actually the same types.

Boost library provides a wrapper to achieve strong type'ing with typedef's with a macro BOOST_STRONG_TYPEDEF.

Epilogue:
There are reasons why no proposal's for strong typedef (N1706 and N1891) made it to the standard. Could be simply because it can be achieved with a wrapper. Not delving deeper into this!

Saturday, April 23, 2016

Hands-on with Cordova

A record of solutions to issues that were resolved to deploy a HTML Android app using Cordova. Only those that are not answered by search engines!

Development Environment:

Processor: x64 
OS: Windows 8.1 Pro
JDK: 1.7.0_75
Android : up to date
     SDK tools: 25.1.1
     Platform tools : 23.1
     Build Tools: 23.0.3
Cordova:  5.1.1
Test Device: Asus Zenfone 4 A450CG (Android v4.4.2 KitKat, 1.2 GHz, 1GB)


Work In Progress:

1. Deploying apk to the device connected via USB.
Error: Error code 1 for command: cmd with args: /s,/c,"D:\WorkSpace\CordovaApp\App\platforms\android\gradlew cdvBuildDebug -b D:\WorkSpace\CordovaApp\App\platforms\android\build.gradle -PcdvBuildArch=x86 -Dorg.gradle.daemon=true -Pandroid.useDeprecatedNdk=true"

*Soln*
Background: Custom icons and splash screens (cordova-plugin-splashscreen) are configured in config.xml.
RCA:
:processDebugResourcesD:\WorkSpace\CordovaApp\App\platforms\android\build\intermediates\manifests\full\debug\AndroidManifest.xml:24:23-37 : AAPT: No resource found that matches the given name (at 'icon' with value '@drawable/icon').  FAILED
FAILURE: Build failed with an exception.
Fix: Make sure the res directory configured is spelled correctly and present in the root directory of the app (D:\WorkSpace\CordovaApp\App\res).


Monday, March 28, 2016

User defined literal

User defined literals are literals for user defined types. After having the user defined types (class) and user defined operators (operator overloading), we now have user defined constants (literals) in C++11.

Ex: If cattle is the user defined type, 10_cows, 20_bulls etc can be user defined literals.

It wouldn't have been fair if integers had to be initialized only as decimal!!

int X = 0XFF;  // Nah! not possible
int Y = 0888;  // yeah, i got it right. Its a decimal 888
int Z = 0110;  // Sadly, I'm still not upgraded to C++14 and i understand only decimal!!!

User defined literals add more readability/ meaning to the user defined types by explicitly stating what the literals mean than leaving it to the programmer to assume or to investigate its usage to find out how the literals are actually used.

cMoney m1(10); // Do you think I'm worth 10USD? I'm worth 10INR. Check out my implementation!
cMoney m2(10.5_inr); // We both know what I'm worth of :)

Programmers can use his/her choice of the units rather than having to convert the literals to the desired (an implementation detail) units manually. The programmer can be assured that the inputs to objects are treated as desired.

cMoney m1(10); // I'm worth 10INR. If you don't think so, init my worth in INR!!

Improves maintainability since the units can be extended

cMoney m2(10.5_inr);
cMoney m2(10.5_usd); oops, it should have been a different unit!

Let us see an example to define and use them.

class cMoney
{
          private:
          long double value; // always store in USD
          // Accept money only in acceptable currencies. 
          // The acceptable currencies will be defined by the user defined literals.
          cMoney(long double money): value(money) {}// private, force strong types.
          public:
          cMoney() : value(0) {} 
          cMoney(const cMoney& money): value(money.value) {}
          // define user defined literals. 
          // I will accept money only in the below currencies. 
          // And We both are sure how much money we are dealing with.
          friend cMoney operator"" _usd(long double val);
          friend cMoney operator"" _inr(long double val);
};

cMoney operator"" _usd(long double val)
{
          return cMoney(val);
}

cMoney operator"" _inr(long double val)
{
          return cMoney(CurrencyConversion::ConvertTo<CurrencyConversion::INR, CurrencyConversion::USD>(val));
}
//...
cMoney m1(10); // ERROR! private constructor
cMoney m2(10.5_inr); // public user defined literal creates the object with appropriate conversion and then copy creates the object.

Run the above code here.

The same can be achieved without user defined literals too! for example, one class for each unit that gets the money in the desired unit. or with generic programming.

Is it really a deal breaker? I will leave that for you to decide! An interesting discussion on SO that answers possible questions is worth looking at.

Sunday, December 27, 2015

Concurrency and Multithreading


Concurrency is running code/ accomplishing tasks simultaneously within a process. This is achieved by threads. Prior to C++11, it was not supported by the language and needed platform specific API's. Thus, such code could not be ported to different platfoms.

One of the prominent improvement to the C++11 standard is the introduction of concurrency/ multi threading built into the language.

Before jumping into the language specific's, let us take this opportunity to see how threads are useful.

This cartoon dipicts why we need threads and how they are helpful. The store clerk takes orders from customers and leaves notes about the order so that the cook gets them done. Imagine the cook played roles of both the cook and the clerk. One person had to take order and then get it done. Meanwhile, any other customer coming to the shop have to wait untill the first order is delivered or may have to leave! Since the clerk and the cook work CONCURRENTLY one can take orders and the other can get the orders ready. Depending on the number of customers coming to the store, the number of clerks and cooks can be increased to attend to all the customers. Clerks and cooks here represent the threads. The goal here is to not keep the customers waiting. So, threads are units of a process that work concurrently to get the job done.

Extensions C++11 has added to the standard library to support multi-threading are
<thread>
,
<mutex>
,
<condition_variable>
and
<future>
.

1. <thread>: An example thread that say's Hello!
void Hello(std::string who)
{
    std::cout << "Hello " << who << "!" << std::endl;
}

int main()
{
    std::string who("world");
    std::thread myThread(Hello, who); // create myThread to run Hello with parameter who
    // while myThread is busy saying Hello. I shall finish other tasks.
    myThread.join(); // wait for myThread to complete
    std::cout << "Thread finished saying Hello!";
    return 0;
}

main
spawns a new thread with
std::thread
and runs function
Hello
with the parameter
who
. Both the main thread and
myThread
now run concurrently. main thread then waits to make sure
myThread
finishes execution.

Now that the tasks are running concurrently, there is great performance and scalability achieved. But, this achievement hits a bottleneck when the threads need to co-ordinate or SYNCHRONIZE for various reasons. One of the main reasons being contending for a shared scarce resource like memory, files, database connections etc.

Consider two threads had to read from and write to a memory location. If the memory is not synchronized between the threads, the data would be corrupted. This is called the data race. Again, when the threads run in an non-deterministic order, the software could produce undefined behavior. This is called the race condition.

C++11 has
<mutex>
for synchronizing the threads.

2. <mutex>: A mutex - MUTual EXclusion - allows only one thread to access a shared resource at a given time. For simplicity, let us synchronize a global variable between the main thread and the worker thread.
std::mutex protector; // mutex to be locked by the threads that contend for who.
std::string who; // shared data/ memory
void Hello()
{
    protector.lock(); // lock the data so that main is not using it.
    std::cout << "Hello " << who << "!" << std::endl;
    protector.unlock(); // unlock the data so that main can continue using it.
}

int main()
{
    protector.lock(); // lock the data so that Hello thread is not using it.
    std::thread myThread(Hello); // create myThread to run Hello
    who = "world";
    protector.unlock(); // Unlock the data so that Hello thread can continue using it.
    // while myThread is busy saying Hello. I shall finish other tasks.
    myThread.join(); // wait for myThread to complete
    std::cout << "Thread finished saying Hello!";
    return 0;
}

when two threads are using the same data, it must be assured that only one thread must access the data for a defined behavior. In the above code, main thread locks the mutex protector so that no other thread will use it. It releases the mutex when it is no longer using the data. Meanwhile,
Hello
thread tries to lock the mutex and since it is being used by the main thread, it waits untill freed by main thread and then acquires the lock. This way, mutexes assure data integrity between the threads.

Mutexes can also be used to resolve race conditions by protecting the entire code sections that need to be executed in a definite order.

Here is an analogy to understand mutex better.

A public restroom is used by many, a shared resource. So, there must be a synchronization mechanism that lets others know when it is being used by one. The physical lock indicates the status of the restroom and keeps others out. Similarly, when two threads are used, they are synchronised using mutex and lock. The thread that is using the resource, locks the corresponding mutex and other threads keep waiting untill released by the thread.

Hence, Mutexes helps in synchronising the threads.

Care must be taken to avoid Deadlock's.  Deadlock is a state when a thread is stuck infinitely waiting for a resource which could be accquired by another thread indefinitely. It can happen so that two threads accquire resources required by each other and wait for the resource accquired by the other.


Most common measures taken to prevent such deadlocks are,

  • The threads accquire resources in the same order irrespective of the order of its usage. 
  • If the mutexes are used to avoid data races, They must be held for as less time as possible.
  • Whenever possible, design to acquire only one mutex at a given time. 

What does not require synchronization is the thread local storage. The data, local to a particular thread. C++11 has introduced an additional storage class specifier
thread_local
which creates one instance of the variable for each of the lifetime of the thread's.

<mutex> header also defines classes for scope based locking of mutexes.

3. <condition_variable> : When multiple threads are used for various reasons, sometimes there is a need for one or more threads to wait for a particular thread to finish it's job. This can be demonstrated with a simple producer-consumer problem. The producer notifies the consumer whenever it produces data to be consumed. Thus, the consumer waits untill there is data produced. Also, the producer waits to be notified by the consumer to produce more data. The condition variables are used for this purpose. The waiting threads are blocked untill notified/ signalled. Once the condition variable is signaled, the thread is resumed accquiring the lock.

Sequence of operations performed by the waiting threads,
- Accquire the mutex.
- Wait to be notified.
- Check the notification variable and continue excution, when woke up my the notifier.
- Release the mutex.

Sequence of operations performed by the notifier,
- Perform the operations that other threads are waiting for.
- Accquire the mutex.
- Modify the notification variable.
- [optional] Release the mutex.
- Notify the waiting threads.

Now, why do we need a notification variable afterall!? It is because of spurious wake up's. It means the waiting threads could be woke up even if they weren't signalled.

A non realistic example to see how to use condition variables.
std::mutex protector;
std::string who; // shared data
std::condition_variable conditionCheck;
bool isComplete = false;

void worker_thread()
{
    // Wait until main() finishes its task.
    protector.lock();
    // Beware of spurious wake up. Check the notification variable to make sure the condition variable is signalled.
    while(!isComplete)  // If it is a spurious wake up, wait till main signals.
         conditionCheck.wait(protector); // give up lock and wait for main to signal

    // lock is automatically re accquired
    std::cout << "Hello " << who << "!" << std::endl;

    protector.unlock();
}

int main()
{
    std::thread myThread(worker_thread);

    protector.lock();
    who = "world";
    isComplete = true;
    protector.unlock();

    conditionCheck.notify_one();

    myThread.join(); // wait for myThread to complete
    std::cout << "Thread finished saying Hello!";
    return 0;
}

4. <future> : When one thread (say A) returns a value to be used by another thread (say B), It can be done so safely with future and promise. A sets the value in a promise and B reads the value from the corresponding future.
void setVal(std::promise<int>& prom) {
  prom.set_value (100);
}

int main ()
{
     // Make a promise.
     std::promise<int> prom; 

     // Promise to be fulfilled in the future.                 
     std::future<int> fut = prom.get_future();
     
     // My thread will fulfil the promise in the future.
     std::thread myThread(setVal, std::ref(prom)); // Pass by reference so that it can set the value in the future obtained.

     // Meanwhile, do other stuff. 

     // Get the value set by the promise or wait till it is set.
     int val = fut.get(); // future is not even ref type, How does it have the value set by the promise!!!!  

     myThread.join();
     return 0;
}

The future can be retrieved only once from the promise. That is because it is moved to the instance when it is first retrieved. Use a
std::shared_future
if multiple threads needs the value from the future.

The standard library provides a much cleaner API that hides the thread creation and promises, the
std::async
API.
// Execute setVal asynchronously and return future for the return value.

 std::future<int> fut = std::async(std::launch::async,  setVal); // How do we know the future type!! It is the same as the type as std::result_of setVal functon