Wednesday, July 7, 2021

Remove Null and Empty Keys from Json [Jackson Library]

import com.fasterxml.jackson.databind.JsonNode;


import java.util.Iterator;


/**

 * @author: Bhupendra Singh

 * @date 7/6/21 7:57 PM

 */

public class RemoveNullAndEmptyFromJson {

    /**

     * This method removes null/empty nodes from JsonNode.

     *

     * @param jsonNode

     * @return

     */

    public void removeNullAndEmptyNodesFromJsonNode(final JsonNode jsonNode) {


        if (jsonNode == null) {

            return;

        }

        if (jsonNode.isObject()) {

            final Iterator<JsonNode> iterator = jsonNode.iterator();

            while (iterator.hasNext()) {

                final JsonNode child = iterator.next();

                if (child.isNull() || child.isEmpty(null)) {

                    iterator.remove();

                } else {

                    removeNullAndEmptyNodesFromJsonNode(child);

                }

            }

        } else if (jsonNode.isArray()) {

            jsonNode.forEach(this::removeNullAndEmptyNodesFromJsonNode);

        }

    }

}

Remove given Key from the Json [Jackson library]

    /**

     * This method removes given key from JsonNode.

     *

     * @param jsonNode

     * @return

     */

    public static void removeGivenKeyFromJsonNode(@NonNull final JsonNode jsonNode,

                                                                                            @NonNull final String key) {

        if (jsonNode.isObject()) {

            final Iterator<String> iterator = jsonNode.fieldNames();

            while (iterator.hasNext()) {

                final String currentNodeName = iterator.next();

                final JsonNode currentNode = jsonNode.get(currentNodeName);


                if (StringUtils.equals(currentNodeName, key)) {

                    iterator.remove(); //To avoid concurrentModificationException

                    ((ObjectNode) jsonNode).remove(currentNodeName);

                } else {

                    // If field is Array then again search in all the array nodes.

                    if (currentNode.isArray()) {

                        removeGivenKeyFromJsonNode(currentNode, key);

                    }

                    removeGivenKeyFromJsonNode(currentNode, key);

                }

            }

        } else if (jsonNode.isArray()) {

            jsonNode.forEach(arrayElement -> {

                removeGivenKeyFromJsonNode(arrayElement, key);

            });

        }

    }

Traverse a Json using Jackson

import com.fasterxml.jackson.databind.JsonNode;

import com.fasterxml.jackson.databind.node.ObjectNode;

import org.apache.commons.lang3.StringUtils;


import java.util.Iterator;

import java.util.Map;

import java.util.Objects;


/**

 * @author: Bhupendra Singh@

 * @date 7/6/21 7:12 PM

 */

public class Traverse {

    /**

     * Traverse a Json using Jackson and also change the value of specific keys.

     *

     * @param jsonNode

     */

    public void traverse(final JsonNode jsonNode) {

        final Iterator<Map.Entry<String, JsonNode>> fieldsIterator = jsonNode.fields();

        while (fieldsIterator.hasNext()) {

            final Map.Entry<String, JsonNode> field = fieldsIterator.next();

            final String key = field.getKey();

            if (StringUtils.containsIgnoreCase(key, "KeyToBeChanged") && Objects.nonNull(

                field.getValue()) && !StringUtils.equalsIgnoreCase(field.getValue().toString(), "null")) {

                ((ObjectNode) jsonNode).put(key, "Value");

            }

            final JsonNode value = field.getValue();

            if (value.isContainerNode()) {

                traverse(value); // RECURSIVE CALL

            }

        }

    }


    /**

     * This method converts any json string to json node.

     *

     * @param jsonString

     * @return

     */

    public JsonNode toJsonNode(@NonNull final String jsonString) {

        try {

            return objectMapper.readTree(jsonString);

        } catch (final Exception e) {

            throw new RuntimeException("Failed to deserialize to JSONObject", e);

        }

    }

}


Convert EPOCH to Desired time format

import lombok.NonNull;


import java.time.Instant;

import java.time.ZoneOffset;

import java.time.ZonedDateTime;

import java.time.format.DateTimeFormatter;


/**

 * @author: Bhupendra Singh@

 * @date 7/6/21 6:59 PM

 */

public class EPOCHToLocalDateTime {

    /**

     * This methods converts the date from epoch to "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" UTC format.

     * @param dateTime

     * @return

     */

    public String convertEPOCHToLocalDateTimeFormat(@NonNull final String dateTime) {

        // ZoneOffset.UTC can be replaced with desired zone.

        final ZonedDateTime zonedDateTime = 

                   Instant.ofEpochMilli(Long.parseLong(dateTime)).atZone(ZoneOffset.UTC);

        // "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" can be replaced with desired pattern.

        final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

        return zonedDateTime.format(formatter);

    }

}

Tuesday, February 24, 2015

Interview Questions of Veveo,Toppr.com,PressPlay.com,KLA Tencor,Symantec,CouponDunia.com

Veveo Interview Questions:

Telephonic :

sizeof operator implementation \
Sol :
#include <iostream>
#define mysizeof(type) (size_t)((type*)0+1)
using namespace std;

int main() {

cout<<mysizeof(double);
return 0;
}


1. Inorder Successor

2. char *p = malloc(1024);
              p = p-2;
              *p = 2;
    How will you detect memory corruption.
3. Hash table,modulo,bucketing
4. char *p = malloc(1024)
char *q  =p+512;
for(int i=0;i<1024;i++)
 p[i] = i;

free(q);

for(int i=0;i<1024;i++)
 printf("%c",p[i]);

What will be output.

5. 25 horses puzzle
6. Dot on forehead puzzle
7. strcat implementation
8. structure padding and alignment
9. Code mymalloc() and myfree()

Toppr.com Interview Questions :



1. Find local minima in an array

2. Train arrival and departure time is given
     how many minimum number of platform will be required (Segment tree solution n log n)
3. Mobile number pad is given. you can move only like a chess Knight
    print all different 10 digit numbers.
    1616161616
http://stackoverflow.com/questions/2893470/generate-10-digit-number-using-a-phone-keypad

Ans: http://ideone.com/BplzQo


Pressplay Interview Questions:


1. 25 horses puzzle
2. Coin on the table puzzle
3. {cat,dog,acte}
     number of occurrences of all words cat : 2,dog : 1,acte : 1

 C/C++ interview questions


KLA Tencor Interview Questions:


                   1. Deep copy vs Shallow copy
                   2. What happens when an object is created using new operator.
                   3. How to restrict object to be created on heap
                   4. Singleton class
                   5. What will you write in class if we have given you char *x;(Rule of three)

Symantec Interview Questions:


                 1. Methods distinguished only by return type can be overloaded or                          not?
                 2. Inside static method can we use this pointer?
                 3. Why we need static method (When we need only one copy of                                method)
                 4. Difference between dangling pointer and NULL
                 5. Why we need pure virtual functions ()
                 6. What is Zombie process
                      ()

CouponDunia.com Interview Questions :


1. Online test
 a.Given a string of characters, convert it to its shortest possible representation. To shorten a string, you can replace the continuous occurrences of a character with the count of those occurrences for ex: [count]@[character]. Make sure that you shorten the string only if needed.

Sample Input: aaaazzzz
Sample Output: 4@a4@z


Sample Input: aaaawwaaaaapppp
Sample Output: 4@aww5@a4@p


Based on the programming language you have selected, you will see a function stub. You only have to complete the function. The rest of the program is already written behind the scenes

string condenseString(string str) {
    string temp;int j=0;
for(int i=0;i<str.size();i++)
    {
    int count = 1;
    while(str[i]==str[i+1] && (i+1) < str.size())
        {
        count++;
        i++;
    }
    if(count>3)
        {
        temp.push_back(count+'0');
        temp.push_back('@');
        temp.push_back(str[i]);
    }
    else
        {
        while(count>0)
            {
            temp.push_back(str[i]);
            count--;
        }
    }
}
return temp;
}

b.A petrol pump buys and sells petrol at the daily standard price declared by the state government. Suppose we are given an array of n integers representing the standard prices of petrol per litre for n consecutive days. Write a function to determine the price and day at which the petrol pump must buy and then sell petrol in order to make a profit and maximize it.

Sample Input:
70 72 73 78 79 74 77

Sample Output:
1 70
5 79

where, in the output, row 1 shows that you buy on day 1 at Rs.70 (numbers separated by a single space) and row 2 shows that you sell on day 5 at Rs.79 (numbers separated by a single space).

Assume that none of the test cases will have ambiguous answers and that we will never make a loss. You must always buy at some price and sell at some price.


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

/*
 * Complete the function below.
 */
void calculateProfit(vector < int > prices) {
    //int buy=prices[prices.size()-1],sell=0,day2=prices.size()-1,day1=0;
    int day2=prices.size()-1,day1=0;
    //cout<<"day2"<<day2<<"day1"<<day1<<endl;
    for(int i= prices.size()-1;i>=0;i--)
        {
            if(prices[i]>prices[day2] && day2 > day1)
                {
                    day2 = i;
                }
            else
                {
                    if(prices[i]<prices[day1] && i<day2 )
                        {
                        day1 = i;
                    }
                }
        }
    cout<<day1+1<<" "<<prices[day1]<<endl;
    cout<<day2+1<<" "<<prices[day2]<<endl;
}

int main() {
    
    int _prices_size;
    cin >> _prices_size;
    //cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n'); 
    vector<int> _prices;
    int _prices_item;
    for(int _prices_i=0; _prices_i<_prices_size; _prices_i++) {
        cin >> _prices_item;
        _prices.push_back(_prices_item);
    }
    
    calculateProfit(_prices);
    
    return 0;
}
C.
 You are given a list of words a baby can speak. There is a recorder that can convert the baby's speech to text, but it cannot recognize pauses, so it does not put spaces in between the words.

Write a program that can convert the baby's recorded speech into words spoken by the baby (existing in the baby dictionary). Every part of the text is actually a word, so if the program outputs one word and the rest as garbled text, it won't be correct. Every test case will have only one correct answer (assume your test case wont contain any phrase that can have more than one correct answer)

Input Variables
1) baby_words = array containing the words the baby can speak.
2) garbled_text = text given by the recorder that converted speech to text

Sample Input
garbled_text = gagagoogoo
baby_words = [gag goo gaga] 
Sample output gaga goo goo
The following outputs are wrong:
1) gag
2) gag goo
3) gag a goo goo

The output must be formatted in the following manner:
Each word must be on the same line and separated by a single space. (The example above has the correct format)

/*
 * Complete the function below.
 */
void findBabyWords(vector < string > baby_words, string garbled_text) {


}                

Sol:

using namespace std;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef pair<int, int> ii;
#define MOD 1000000007
set<string>myset;
bool main_test(string st,int start,vector<string>&vec)
{
    string x;
    if(start >= st.size()-1)
        return true;
    for(int i = start ; i < st.size() ; i++)
    {
        x.PB(st[i]);
        if(myset.find(x)!=myset.end())
        {
            vector<string >ans;
            //cout<<x<<"  ";
            bool bt = main_test(st,i+1,ans);
            //cout<<bt<<"  "<<start<<endl;
            if(bt)
            {
                vec.PB(x);
                for(int i =0 ; i < ans.size(); i++)
                    vec.PB(ans[i]);
                return true;
            }
        }

    }
    return false;
}

void findBabyWords(vector < string > baby_words, string garbled_text) {
   
    for(int i =0 ;i < baby_words.size(); i++)
    {
        cout<<baby_words[i]<<endl;
        myset.insert(baby_words[i]);
    }
    vector<string>answer;
    bool bt = main_test(garbled_text,0,

answer);
    for(int i =0 ; i< answer.size() ;i++)
    {
        cout<<answer[i]<<" ";
    }
    cout<<endl;
}

Tuesday, August 19, 2014

Invite all your facebook friends to like your facebook page


Hi,
I wanted to send request to all my facebook friend to like my page but facebook doesn't allow us to do so.
So I did some research and found something to perform required action.

Please follow below mentioned steps to invite all your friends at once to like your facebook page-:
1. Login to your facebook and go to your facebook page.
2.Click on Build Audience in right upper corner.
3.Click invite friends from the dropdown menu.
4.now open developer tool and go to console.
5. type following code snippet on console and press enter
      var inputs = document.getElementsByClassName('uiButton _1sm');
      for(var i=0; i<inputs.length;i++)
      {
           inputs[i].click();
      }



Wednesday, September 11, 2013

MAC : Hide and Unhide a file or folder using terminal


To hide, just type this:
chflags hidden /path to file or folderP
To unhide it, just change hidden to nohidden
chflags nohidden /path to file

Monday, September 9, 2013

Python: Create an XML and append child node


from xml.etree.ElementTree import ElementTree
import xml.etree.cElementTree as ET
import os

def xmlFileCreate(keyword,status):
    root = ET.Element("Results")
    doc = ET.SubElement(root, "Result")
    field1 = ET.SubElement(doc, "keyword")
    field1.text = keyword
    field2 = ET.SubElement(doc, "status")
    field2.text = status
    tree = ET.ElementTree(root)
    tree.write("filename.xml")
def appendChildNode(keyword,status):
    tree = ET.parse("filename.xml")
    root = tree.getroot()
    doc = ET.SubElement(root,"Result")
    field1 = ET.SubElement(doc, "keyword")
    field1.text = keyword
    field2 = ET.SubElement(doc, "status")
    field2.text = status
    #tree = ET.ElementTree(root)
    tree.write("filename.xml")
if __name__ == '__main__':
    keyword = "data"
    status = "Pass"
    if os.path.exists("filename.xml"):
        appendChildNode(keyword,status)
    else:
        xmlFileCreate(keyword,status)

Thursday, January 24, 2013

Python Script to Copy a file from one directory to another


import shutil
def main():
    src="Path of Source file <C:\Program Files\a.txt>"
    dst="destination directory path <E:\New Folder> "
    shutil.copy(src, dst)
if __name__ == '__main__':
    main()

Monday, September 3, 2012

Setting Up Google test framework in Visual Studio

1. Install Visual Studio.
2. Download Google test framework. http://code.google.com/p/googletest/downloads/list
3. Unzip downloaded file.
4. Go to gtest->MSVC and run gtest.sln and gtest-md.sln and make build of both in both debug and release mode.
5. For DEBUG mode
    a. Open a project or create a new project and then go to properties->c/c++->general
    b. In additional include Libraries give the path of fused-src folder
         For example if you have unzipped your gtest in F drive then F:\gtest\fused-src
    c. Now go to linker->general and in additional include Libraries give the path of Debug folder in       MSVC like F:\gtest\msvc\gtest\debug
    d. Now in linker->input in Additional dependencies put gtestd.lib; gtest_maind.lib
6. Now do the similar steps for Release mode.
one more thing you have to do is go to properties->C/C++->code generation and in Run time library for debug put Multi-Threaded Debug(/MTd) and for release mode put Multi-threaded(/MT)
If this material is relevant to you then don't forget to comment.....:-)
For any problem you can reach to bhupi.biet@gmail.com
Thanks