Friday, April 21, 2017

We were looking at an exercise involving sum of all numbers formed by subsequences in  the digits representing a number. This method was called Int GetSumOfAllSubsequences(List<int>A, int start, int end) 
We did this by choosing different numbers but we can also put to use the fact the number of such subsequences is represented by repetitions.  A digit will appear as many times as it is chosen in this combination. Therefore the sum is the accumulation of repetitions times the digit value. 
Let's take an example and see the pattern: 
a0, a1, a2 
can be combined as a0 + a1 + a2  + a0a1 + a1a2 + a0a2 + (a0a1a2 ) = 4(a0+a1+a2) where 4 = 1 + 2 + 1 
For a0,a1,a2,a3 we have 8(a0+a1+a2+a3) and 8 = 1 +3 + 3 + 1 
and these are infact the sum of the binomial coefficients. 
Int GetSumOfAllSubsequences(List<int>A, int start, int end) 
{ 
If (start>end) return 0; 
If (start==end)return A[start]; 
Int sum = A.Sum(); 
int sumofallsubsequences= 0 
For (int n = 1; n <=A.Count; n++) 
       Sumofallsubsequences += sum * GetNChoosekDP(A.Count-1, n-1) 
Return sumofallsubsequences; 
}
Said another way each element can either be taken or left from the subsequence. This happens in a total of Math.Pow(2, A,Count-1) ways. Therefore we could calculate the sum of all subsequences as :
A.Sum() x Math.Pow(2, A.Count-1)
Notice that this is in fact the summation of all the binomial coefficients, Specifically,
Coefficients              Total
         1                      Math.Pow(2,0)
       1   1                   Math.Pow(2,1)
     1   2  1                 Math.Pow(2,2)
and so on
If we were to find the subsequence sums that are divisible by m, we note that we were multiplying the sum of all elements with the sum of binomial coefficients. If one of the two components is divisible by m, then sum of all subsequences would also be divisible by m.We could therefore find the sub patterns to find the divisibility by m. If we want to enumerate subsequences that are individually divisible by m, then we would use the combine method with the condition for individual combinations to be added to the result only when their sum is divisible by m.
We could translate this problem as find if there is any subset in the sequence that has sum 1x m, 2 x m, 3 x m, ... n x m where n x m <= sequence.sum()
void PrintIsSubsequenceSumDivisibleBy(List<int>seq, int m)
{
   for (int sum = m; sum <= seq.sum(); sum=sum+m)
         if (IsSubSeqSum(seq, seq.Count, sum))
             Console.WriteLine(sum);
}
bool IsSubSeqSum(List<int> seq, int n, int sum)
{
if (sum == 0) return true;
if (sum < 0) return false;
if (n == 0 && sum != 0) return false;
if (seq[n-1] > sum)
     return IsSubSeqSum(seq, n-1, sum);
return IsSubSeqSum(seq, n-1, sum) || IsSubSeqSum(seq, n-1, sum-seq[n-1]);
}

Thursday, April 20, 2017

In this blog, I have previously mentioned how aesthetics in design improve the appeal of the product. To summarize, some of the virtues that enhance aesthetics include the following:
1) mastery of complex systems and self-assembly 
2) passion for versatility 
3) redesign in a positive and constructive way 
4) knack for making information clear and engaging 
5) metaphysical appreciation of bodily functions 
6) infusing objects with elegance and intelligence
In addition, today I cite articles which emphasize that customer experience is also governed by psychological factors. Given an uncertain unprecedented tool, an audience may abandon careful analysis and instead resort to mental shortcuts – that almost always lead to the wrong answer. It turns out that the smarter we are the more likely we are to make such mistakes. This is the claim made by Cognitive sophistication which does not attenuate the bias blind spot paper by West RF. 
The researchers treat these observances as “cognitive bias” and “anchoring bias” both of which play very much into product design and marketing. 
Cognitive bias is when we make interpretations from surface facts. For example, if a pencil and eraser cost a dollar and ten cents and the pencil is a dollar more than the eraser, how much is the eraser? The answer is five cents not the ten cents if we did not rush to the answer 
Anchoring bias is when we make interpretations from the first observation and use it thereafter for subsequent deductions. If we are wrong from the start, everything else follows accordingly. 
The paper cited above goes into length explaining how bias forms. When we take the bias away from the social domain, it is easier to observe that it is all the more difficult to detect in one's own judgement. Furthermore, according to them, people who are aware of their own biases are not able to overcome them.  The more intelligent we are the worse it gets. There is therefore a universal appeal in something that is simpler. 
This is where minimalistic design helps. Meerkat, Teleparty and Snapchat are among the companies that are known for the "dumb" simplicity of their apps which contributed to their success. There is a 80/20 rule to such designs. "Keep the features that 80% of the users will use. Kill the ones that only 20% will use."
#codingexercise
Find sum of subsequences of a given sequence of positive integers that are divisible by m
We could translate this problem as find if there is any subset in the sequence that has sum 1x m, 2 x m, 3 x m, ... n x m where n x m <= sequence.sum()
void PrintSubsequenceSumDivisibleBy(List<int>seq, int m)
{
   for (int sum = m; sum <= seq.sum(); sum=sum+m)
         if (IsSubSeqSum(seq, seq.Count, sum))
             Console.WriteLine(sum);
}
bool IsSubSeqSum(List<int> seq, int n, int sum)
{
if (sum == 0) return true;
if (sum < 0) return false;
if (n == 0 && sum != 0) return false;
if (seq[n-1] > sum)
     return IsSubSeqSum(seq, n-1, sum);
return IsSubSeqSum(seq, n-1, sum) || IsSubSeqSum(seq, n-1, sum-seq[n-1]);
}

Wednesday, April 19, 2017

Using Saltstack to set up Containers on any salt minion 
Introduction: Saltstack is a communication and relay mechanism between a salt master and several hundreds of minions. The communication happens over a super fast messaging and guaranteed delivery message bus called ZeroMQ. Commands issued at the master go over encrypted channel to the salt minion and are executed locally. Individual commands and batches can be executed seamlessly between minions of different flavors in a platform agnostic manner. 
Dedicated high density Linux flavor minions can host Linux Containers that behave like individual VMs. These containers can be configured to be on the same network and released to customers for access via SSH. Configuration and setup of these containers involve the use of shell commands within the container and LXC commands on the container host. These are easily invoked from the saltmaster and so the create, update and delete of containers can easily take place on command line via salt and ssh  
Salt also has flexibility in organizing scripts and states based on flavor, version and release. This let us determine the set of customization scripts to run on the container.  If there are states that affect all containers globally, then we can apply them via pillars. Otherwise we can even target minion Linux hosts by pools of predetermined list. This is especially helpful to release containers of different os flavors and they are best suited for configuring static ip addresses on all new containers. 
In addition, Salt has access to databases where it can look up and save any information it wants for the containers spun up using its framework.  This way the infrastructure knows which containers belong to which users. This is helpful because we want to authorize create, update and delete of containers to their respective owners. Actions such as taking snapshots and restoring snapshots as well as making clones from both containers and snapshots should be user driven where they leverage a portal that works with Salt framework.  Typically such a portal automates actions that the administrator would take via salt commands from the salt master. This makes the framework reusable by both administrators and users and streamlines the actions to the well known salt syntax.  
Finally, each container can also automatically become a salt minion registered with the same master, therefore it can also be managed independently as a minion. This is a significant win for management because all new instances become automatically available for regular maintenance and system administration activities. The same concept is available in public clouds where a system management center can interact with instances in any public cloud and on-premise system using  an agent on that instance. By installing salt-minion service on the new containers, they become first class citizens in the salt framework and are available to be managed just  like the rest of the inventory. Both the host and the container can now be prepared from Saltstack.
Conclusion: Containers are no different than virtual machines for users. If the virtual machines are managed by a central framework, we can reuse the same framework by promoting containers at par with the virtual machines. 
#codingexercise
Find ways an integer can be expressed as a sum of nth power of unique natural numbers
There are two numbers given x and . We have to find the number of ways x can be expressed as nth power of unique natural numbers.
        static int GetPower(int x, int n, int i, int sum)
        {
            int count = 0;
            int power = (int)Math.Pow(i, n);
            while (sum + power < x)
            {
                count += GetPower(x, n, i + 1, sum + power);
                i++;
                power = (int)Math.Pow(i, n);
            }
            if (power + sum == x)
            {
                // Console.WriteLine("power={0}, sum={1}", power, sum);
                count++;
            }
            return count;
        }
power=9, sum=1
Count = 1

Tuesday, April 18, 2017

We were discussing OSX Spotlight Search on Mac for remote folders, those that can grow arbitrarily large and served over different file protocols. In these cases, the usual method is to connect the shares using Finder application, then to do the following:
To enable spotlight indexing on a network drive, we give the following command:
mdutil /Volumes/name -i on
To disable the indexing of a connected network drive, we give the following command:
mdutil /Volumes/name -i off
To check the status of indexing on a connected network drive, we give the following command:
mdutil /Volumes/name –s
To re-index a mounted drive, we goto preferences > spotlight > privacy
drag a folder or drive into the ‘ignore’ list and then remove the item we just added.
#codingexercise
Find the largest sum in a zigzag path from top to bottom of a matrix where zigzag means no two adjacent rows have the same column values selected

This can be done with dynamic programming starting from a cell (i, j) and ending at a cell on the bottom row
int GetZigZagDP(int[,] M int i,
                                int j, int n)
{
   if (i == n-1)
     return M[i,j];
   // We now consider all the candidates in the next row
   int sum = 0;
   for (int k=0; k<n; k++)
     if (k != j)
       sum = max(sum, GetZigZagDP(M, i+1, k, n));

   return sum + M[i, j];
}


This holds true for right triangle matrix  as well starting at position (i,j)
int GetTrianglePathSumDP(int[,] M, int i, int j, int n)
{
if (j >= M[i].columns) return 0;
if ( i == n-1) return M[i,j];
int sum = 0;
for (int k = 0; k <= i + 1; k++)
     if (k == j || k == j+1)
         sum = Math.Max(0, GetTrianglePathSumDP(M, i+1, k, n));
return sum + M[i,j];
}
sums.max();
For example:
2
4 1
1 2 7
Sums:
10
6 8
1 2 7

Monday, April 17, 2017

OSX spotlight search on external folders
OSX allows external folders to be connected on the MacBook. These folders can be accessed over file system protocols that support either linux only or both linux and Windows platforms. Usually external folders are larger than any on the local disk because they are sought to expand the capacity of the local storage. These remote folders can be quite large ranging from a few Gigabytes all the way to order of terabytes.
Spotlight search enables user to quickly lookup a file based on some content words. Files that appear in the results are already indexed so the lookup is faster than scanning tools like grep. Spotlight search works based on populating an index from existing folders. This index can be arbitrarily large depending on the amount of data indexed.
External files and folders can be added to Spotlight search, by way of configuration. We go to System Preferences, Spotlight and Privacy and add folders and disks through the plus sign at the bottom left.
We can exclude some folders to reduce the load on Spotlight. Folders that are included must have connectivity for the duration of the indexing until the indexes are built. We can start and stop the indexing using command line tools like mdutil.
Where external files and folders are added, their index can become larger than usual. Typically the metadata is stored in a hidden folder .Spotlight-V100 at the root of the indexed volume. When indexes and the data are both large, it would benefit to separate the index from the data on the disk because they have different access. The values of the attributes that get stored in the metadata folder depends on the com.apple.metadata:kMDItemFinderComment.
Usually the Spotlight preferences involve Search results and privacy tabs which can help with customizing the Spotlight search.
Indexes may get out of date as new contents are added and the folders are included or excluded from Spotlight search. Rebuilding the index works in these regards.

#codingexercise
Given a right triangle of numbers, find the largest of the sum of numbers that appear on the paths starting from the top towards the base, so that on each path the next number is located directly below or below-and-one-place-to-the-right.
void GetMaxSumTriangle(int[,] M, int n, ref List<int> sums)
{
if (n== 0) { sums[0] += M[0,0]; return; }
GetMaxSumTriangle(M,n-1, ref sums);
sums[0] = M[n-1, 0] + M[n,0];
for (int j = 1; j <=n; j++){
     top = (j <n ? M[n-1, j] + M[n,j] : 0)
     topleft = (j-1>=0 ? M[n-1,j-1] + M[n,j] : 0)
     sums[j] = Math.max(top, topleft) + sums[j];
}
}
sums.max();
For example:
2
4 1
1 2 7
Sums:
2
6 3
7 8 10

The critical path changes at every level.

Sunday, April 16, 2017


For a given string formed from letters a,b,and c, find all subsequences of the form a..b...c.. where the a, b, and c can be repeated any number of times homogenously.
subsequences are considered different if the indexes of the subsequences are different
For example:
Input  : abbc
Output : 3
Subsequences are abc, abc and abbc

Input  : abcabc
Output : 7
Subsequences are abc, abc, abbc, aabc
abcc, abc and abc
int GetCountABC(string s)
{
int a = 0;
int ab = 0;
int abc = 0;
for (int i = 0; i <=s.length; i++)
{
if (s[i] = 'a')
    a = 1 + 2*a;
else if (s[i] == 'b')
    ab = a + 2*ab;
else
   abc = ab + 2*abc;
}
return abc;
}
// Alternatively, we could even try to enumerate them based on their occurrence after we separate out the mandatory abc or as many abc as we can form
// untested but only to illustrate the pattern
Int GetCountABC(List<int>Str, int start, int end)
{
If (start>=end-2) return 0;
Var A = Str.Select(x => x == 'a');
Var B = Str.Select(x => x == 'b');
Var C = Str.Select(x => x == 'c');
int count = 1; // for abc
int n  = A.Count + B.Count + C.Count - 3
For (int k = 1; k <=n; k++)
       count += GetNChooseKDP(n, k);
return count;
}