Saturday, March 27, 2021

JSON object comparision

 I wrote this small program for my own needs to compare two JSON objects and spit out either true or false to tell is there any difference between the objects. This was useful  in angular forms when form controls wasn't  used. The app have to notify the user that if the user navigate away from the current page making some changes in the form but without saving the form. Form controls are grouped under form group object and form group value changes can be observed to notify the changes if subscribed. In my scenario I didn't use form control but used NGMODEL which I thought was pretty straight forward. NGMODEL and Form Control  combination are deprecated so wrote this recursive brute force approach to detect changes if any. This will work for small JSON Objects but not for large JSON Objects. Language is typescript.


class ObjectComparision<T>{

  oldObject: T;
  newObject: T;

  getOldObject(): T {
    return this.oldObject;
  }

  setOldObject(tempObject: T) {
    //Object.assign(this.oldObject,tempObject) ;
    this.oldObject = Object.assign({}, tempObject);
    //this.dates(this.oldObject);

  }
  
  getNewObject(): T {
    return this.newObject
  }
  setNewObject(tempObject: T) {
    this.newObject = Object.assign({}, tempObject);

  }
  compareObject(obj: T, obj1: T): boolean {

    for (var key in obj) {
      if (this.checkPropertyInstanceIsAnObject(obj[key]) ) {

        if (this.checkObjectDifference(obj[key],obj1[key]))
         return true;
      }
      else if (this.checkPropertyInstanceIsAnArray(obj[key]) ) {
        if(this.checkArrayDifference(obj[key],obj1[key]))
          return true;
       
      }// end for if
      else {
        if (this.compare(obj1[key],
          obj[key]) == true) {

          return true;
        }
      }
    }
    return false;
  }

  
  checkObjectDifference(compare,compared) : boolean
  {
    if (this.checkIsPropertyundefined(compare) || this.checkIsPropertyundefined(compared)) {
          return true;
        }

        if (this.compareObject(compare, compared) == true) {
          return true;
        }
    return false;
  }

  checkArrayDifference(obj,obj1) : boolean
  {
    for (var element in obj) {

          if (this.checkPropertyInstanceIsAnObject(obj[element])) {
              
            if (this.checkObjectDifference(obj[element],obj1[element]))
               return true;
             
          }
          else {

            if (this.checkIsPropertyundefined(obj1[element]) 
                || this.checkIsPropertyundefined(obj[element])) {
              return true;
            }
            if (this.compare(this.obj1[element],
              obj[element]) == true) {

              return true
            }
          }
        }
    return false;
  }

  checkPropertyInstanceIsAnObject(objectT): boolean {
    return object instanceof Object

    }

    checkPropertyInstanceIsAnArray(objectT): boolean {
    return object instanceof Array

    }

    checkIsPropertyundefined(object : T) : boolean
    {
      return object === undefined
    }
  
  compare(val1: any, val2: any): boolean {
    if (val1.toString() != val2.toString())
      console.log(val1, val2)
    return (val1.toString() != val2.toString())
  }
}

example

 var obj1 = { 'id'1'name' : 'krishna'}
var obj2 = { 'id'1'name' : 'krishna_'}

var o = new ObjectComparision<any>();
 console.log(o.compareObject(objaa, objbb))
 console.log(o.compareObject(objbb,objaa))


Sunday, September 6, 2020

Importand and practical things to do , to live a fulfilling life.

 Essential / important things to do for the whose basic needs (food, clothing and shelter) are met. The following things are not something new but it's been there for a long time and all of them knew such important things. It's not a Eureka list but known boring list.

The following things are not for the people whose basic needs are not met could be many reasons for this unfortunate situation. 

1. Take care of your health(Eat in Moderation).  You need to have a clear purpose why you should eat in moderation. Most of the time the motivation is to loose weight  or bring down your cholesterol or glucose level to the normal range. This purpose should become strong intent in your mind. If the intent is strong then you will indulge into action without any external force or external motivation from outside. If the intention is not strong then eating in moderation is not a worthy pursuit since you will fail and can become emotionally draining. So wait to fall sick and a kick from the doctors would help you in forming strong intentions so as Psychological counselling will help if there are any emotional blockages . Without the purpose and intention the resolve will not be strong enough to adopt "Eating in Moderation". 

 There are people who live longer just eating crappy food without any fitness regime such people are exception to the rule but not a common occurrence. There are people who eat and do exercise and still suffer premature death. Probably there are genetic or emotional reasons for such problems. I have seen people who eat good food but mentally unstable not they have mental disease but their emotional state is not balanced. Reasons could be many for such unstable conditions and to list all of them is an impossible task. Most of the people fall in the middle when eating in moderation is adopted they will see marginal improvements in their health but for some that could be life changing.

The key factors for taking care of your health are eat in moderation(what is moderation is relative and will differ from person to person). Eat in moderation according to your age but  moderation may not be applicable to adults in their 20s who are into rigorous fitness regiment or labors who work hard on the field or factories. Listening to your body is very important to differentiate when to start and stop eating. The first few days will be a challenge when adopting a new habit. To adopt to a new habit a healthy support group is very vital to discuss your mental challenges  and problems in choosing food that could be filling and satisfying.  If not able to follow any thing just remember the key thing if your stomach is lighter and not heavy means you have eaten in moderation.  following this simple thing will take a long way to promote decent health if not optimum. 

A suggestion for meat eaters would be to cut down on red meat if not avoid and embrace white meat like chicken and fish which can satisfy all your nutritional requirements with out consuming red meat.  I would prefer Organic meat over conventional meat. If possible refrain from meat eating at least for one or two days in a month so same goes for diary products as well. Consume low fat  organic milk and organic cheese which will be easy on your stomach.if your allergic to caesin protein try A2 milk which are available at whole foods but check your local grocery stores. Vegetables in nature except for few are nasty in taste and makes you puke so it's better to make it tastier by adding ingredients by the way millions of recipes are available online as long as you are willing to devote sometime for healthy cooking.  

Regarding Junk foods you need to consume junk foods but in small to moderate quantities, suppression is as dangerous  if not more dangerous as eating only junk foods. The mind is a weird component if you suppress something it creates the urge to eat more I don't know why but the nature of the mind  is to remember negative things most of the times not the positive things as we all know that we remember the disrespect but not the respect given to us. Please be careful while playing with your mind because we don't know who we are until we encounter challenges most of them fall and few rise above the challenges to permanently alter their habits.

Eating in moderation is a long process until it becomes a habit where the senses are under control whenever we see or smell the food.  In all this process do not feel guilt if you can't keep up the habit it's Okay if you can't keep up the habit rather feeling bad or guilt. The guilt is not going to help you in promoting any healthy habits  or move away from negative it's just stays there and you become two different person one with guilt and one with bad habits. It's better to pursue bad habits if you can't control without guilt. But I believe most of the people has decent amount of will power to over come most of the bad habits but for some help is required to adjust. Another possibility is the urge will always be there  to eat crappy food but using determination as a tool we may postpone it for a while but determine requires tremendous amount of energy which is limited in supply so habit doesn't require energy as it's an autonomous activity not even you respond to something, it just happens. 

In summary include vegetables, white meat, fruits, moderate carbs , low fat diary , moderate junk foods  as part of your daily intake and moderate exercise like walking, running, swimming will add more help in controlling your urges in the initial stages of transitioning to moderate eating. 


2. Quiet time. Humans needs  to invest  some time for themselves. Why we need quite time because we need to spend time with ourselves to experience some sense of temporary peace alas permanent peace means death or spiritual enlightenment.  For some  spending time with themselves can be a dangerous thing as this may not a suitable option to pursue. Before we venture into quiet time activities we should have a clear understanding what quiet time means and why we need it. Break is different from quite time.Behaving crazily with our selves is not a quite time. Including just one person in any activity is not a quite time. Watching movie is not a quite time. A broad definition would be an activity which doesn't stimulate your senses too much can be called as quite time means resting the body and senses. Why we need quite time because spending time with your self satisfies your mind because all through the day we do activities to satisfy other people which includes family , organization and managers. We do those activities because we love them that's why. I have never understood love thyself but doing quite activity for myself have resulted in temporary inner peace. 


What are different activities that we can do to consider it that as a quiet time. Active activities include playing chess against a computer , writing, reading ,solving puzzles, reading a book, playing music, deep thinking on your professional or personal problems. Every individual can come up with their own list as long as it meets the definition. Such activities should not be result oriented but rather pleasure oriented. As long as it involves less use of our five senses means naturally the mind will result in peace by itself. At first it may require some effort but it's worth for a balanced living.  Find a place where nobody will disturb you and set a time and amount of time you are going to spend on the activity. At first choose an activity that interest and in the process you will find out about the likability of the chosen activity and an opportunity to explore new activities. Set a time where it's comfortable and not taking time away from essential activities.

Passive activities include meditation, walking or slow jogging in nature, drawing , observing nature which include ourselves, watching your mind without any intervention, listening to  melodious music with closed eyes,   chanting, prayer to GOD or nature,  watching your breath on the nostrils, Contemplation, Concentrating on an object. In short very very less brain stimulation. Find a quite place without much disturbance which can come in the form of people and external noise. 

Will continue in part -II 

Monday, April 6, 2020

longest substring sequence but not so perfect

using System;

public class Program
{
public static void Main()
{
Console.WriteLine("Hello World");
String input ="aoaboooobcdefooo";
string input1="zbcdeabf";
int posx=0;int posy=0;;
int[,] table = new int[input1.Length,input.Length];
string output= "";
//populate table with zeroes.

for(int j=0;j<input1.Length;j++)
{
int i=0;

while(i<input.Length)
{
if (input1[j]==input[i])
{
table[j,i]=table[j-1,i-1]+1;
if(table[j,i]>table[j-1,i-1])
{
   posy=j;posx=i;
}
}
else{
if(i>0 && j>0)
    table[j,i]=table[j-1,i-1];
}
i=i+1;
}
}
//print the letters.
while(table[posy,posx]>0)
{
output=output+input1[table[posy,posx]].ToString();
Console.WriteLine(posy.ToString()+posx.ToString());
posy--; posx--;
}
Console.WriteLine(output);
}
}

Monday, November 25, 2019

Teaching Kids or Coaching Kids

It was writing time or more to say a struggle time with my son to make him a better writer. His 5th grade teacher gave him an assignment to write about something of his interest using punctuation. My sons with his turbulent thoughts and racing mind raked the sentence without proper punctuation and just want  to get out of the writing captivity.  I wonder why the parents have to struggle with kids to educate the kids especially writing or solving problem while the kids are becoming rebellious to it. Is the system to be blamed or ourselves. Probably nothing is working for us as parents and he is diagnosed with ADHD. What is the utility value of forcing a child who is not interested in writing with a kid of average intelligence. The compass of internal motivation or inherent thrist is always the predictor of being good at anything. The school system which mass manufacture students and torture in the name of creating a career  for the kid is partly to blame for such a disaster and merciless crushing of the young soul. Education is important  but how to pursue it especially in this age of complex layers of knowledge and internet is a different challenge than 19th century education system. This complex problem requires different customized approach catered to the need and ability of the children. There are children who are going to be brilliant and excel academically so those children has to be nurtured properly and differently since they are the jewels and probably the people who will shape the society in STEM or political endevour. The other kids who are average but have different interest and intuition should be directed towards their intuition and capability and make the process of education as enjoyable as possible  with little instructions from the teacher. The process of discovery is what kindles a human being in the pursuit of knowledge and happiness.
How many of us in our career actually write at length and produce useful content for others to read and comprehend. Is it not our education system should to kindle the curiosity in children and encourage the process of self discovery about seeking the knowledge out of pleasure rather out of career captivity. This question has been asked countless times by people of various capacities but there is no proper political will or a solution in sight. This torture of bending the kids to assimilate them into this education system is the approach of showing light to the blind man. Rather blind man should be treated as a blind man and requires different set of approaches to develop skills that he is capable of. Every human being will contribute to the welfare of the society in any form. Agreed there  are some basic which every kid has to learn like number sense, basic vocabulary and critical reasoning which are indispensable skills and important to any endeavor the kids under take.
The root of all evil is one size fits all.  how do we teach these skills in a less painful way.
Every kids learn at their own pace. Every kid will reach their finish line but at their pace and will.
As we parents compare ourselves with other family on money, fame and wealth and not surprisingly we pass such dubious quality to our children without much effort. Kids learn by seeing and doing but not by saying. We brought them into this world in the process of being happy but we parent have a responsibility to protect our kids from this on slaught of educational system.


Friday, October 11, 2019

SQL Server Query to convert the List of strings into comma delimited string

The following code was fun to convert the list of strings into comma delimited string.
create table x(destinationTableName varchar(8000))
insert into table x('a')
insert into table x('b')
insert into table x('c')
insert into table x('d')
insert into table x('e')
insert into table x('f')

WITH expression_name (sequence,destinationTableName)
AS
(
    -- Anchor member
select cast(no as int) no,cast(destinationtableName as varchar(8000))+',' as destinationtableName from
    (select row_number() over( order by red_code) as no,destinationtableName from red_searchdomain where
  insertRecords =1) x
  where no =1
    UNION ALL
    -- Recursive member that references expression_name.
    select cast(y.no as int) no,cast(expression_name.destinationtableName+y.destinationtableName+',' as varchar(8000)) destinationtableName from expression_name
join (select row_number() over( order by red_code) as no,destinationtableName from red_searchdomain where
  insertRecords =1) y
  on y.no = expression_name.sequence+1

)
-- references expression name
SELECT substring(destinationTableName,1,len(destinationTableName)-1)
FROM   expression_name where sequence =(select max(sequence) from expression_name)

Wednesday, September 4, 2019

Permutation and Combination of Strings using Recursion

My program to generate combination of unique letters.  Given a string "ABC" the program will out put "ABC","ACB","BAC","BCA","CAB","CBA". I struggled with this program for a long time to come up with my own solution in c# which is so effective but satisfying. recursion are pretty amazing to train the brain. The problem with recursion if you go all the way down how it works you will loose the track and you get confused actually how it works. Let's say you have a problem and if you can come up with how you can divide a problem into one sub problem and solve it that's it you don't have go down the rabbit hole of visualizing how recursion works. 

public static void Permute(string s,string substr,string doNotInclude)
        {
            if(substr.Length==s.Length)
            {
                Console.WriteLine(substr);
               // ++counter;
                return;
            }
            for(int j=0;j<s.Length;j++)
            {
                if (doNotInclude.IndexOf(j.ToString())==-1)
                {
                    string result=s.Substring(j,1);
                    Permute(s,substr+result,doNotInclude+j.ToString());
                }
            }
               
        }

       Permute("abcdefgh","","");

Saturday, August 31, 2019

Recursion Generating Sub String Given a String.

I was hitting my hard for  the past 24 hours to generate sub strings out of a string. I am not particular ly good at programming(its a gift given to only few) but the kick to think hard enough about a problem is something fulfilling and satisfying. Here is the code below to generate sub strings out of a string in the order  of the string.

public class Program
    {
        static String OPEN_BRACKET = "{";
        static String CLOSED_BRACKET = "}";
        static String EMPTY_STRING = "";
        public static void Main(string[] args)
        {
            //Your code goes here
            Console.WriteLine("Hello, world!");
            recur("Operation",0,"",0);
        }
       
        public static void recur(String s, int index, String out1,int StartPos)
{
            if (s.Length==out1.Replace("{","").Replace("}","").Length)
            {
System.Console.WriteLine(out1);
                return;
            }


        int cntr=1;
for (int j = index;j<s.Length ; j++)
{
String sub_str = OPEN_BRACKET + s.Substring(StartPos, cntr)
+ CLOSED_BRACKET;
            cntr=cntr+1;
recur(s, j + 1, out1 + sub_str,j+1);
}
}
  }
}