Monday, October 10, 2022

Shell Script to detect events in ADB Logcat in a loop

The following shell script performs an action (tap) on the screen, then checks that a particular event does not happen on the device. It then performs another action (press back button) and then checks the target event happens only once. Then it closes a process and iterates through the same steps in a loop 50 times.

#!/bin/sh

# Clean up any reminiscent from previous run of the script
rm -rf script_logs
mkdir script_logs
for i in {1..50}
do
	echo $i
	echo "Clearing device logs"
	adb logcat -c
	echo "Starting log recording"
	adb logcat >> script_logs/script_logs$i.txt &
	logcat_pid=$!
	echo "Clicking at a point on the screen"
	adb shell input tap 200 300
	echo "Waiting for 4 seconds for event to happen and logs generated"
	sleep 4
	events=`grep "<log_pattern>" script_logs/script_logs$i.txt | wc -l`
	if [ $events == 0 ]
	then
		echo "No event found"
	else
		echo "$events were found, the test failed"
		kill -9 $logcat_pid
		exit 1
	fi
	adb shell input keyevent KEYCODE_BACK
	echo "Waiting for 4 seconds for another event"
	sleep 4
	echo "Checking how many events were sent"
	events=`grep "<log_pattern>" script_logs/script_logs$i.txt | wc -l`
	if [ $events == 1 ]
	then
		echo "One and only one event was found"
	else
		echo "$events were found, the test failed"
		kill -9 $logcat_pid
		exit 1
	fi
	echo "Killing target process"
	pid=`adb shell pidof <process_name>`
	adb shell kill -9 $pid
	echo "Stopping logcat"
	kill -9 $logcat_pid
	sleep 2
done

Pass by Pointer vs Pass by Reference in C++

Variables can be passed by pointer and by reference. Both produce the same result and have the same effect on the arguments passed in the calling function. The difference is that the pointer stores the address to a variable whereas a reference refers to an existing variable in a different name.

Reference: https://www.tutorialspoint.com/passing-by-pointer-vs-passing-by-reference-in-cplusplus

Pass by Pointer:

Code: 
#include <iostream>

using namespace std;

void swapNum(int* a, int* b) {
    int t = *a;
    *a = *b;
    *b = t;
}

int main()
{
    int i = 1;
    int j = 2;
    cout << "Before swapping " << i << " " << j << endl;
    swapNum(&i, &j);
    cout << "After swapping " << i << " " << j << endl;
    return 0;
}
Output:
Before swapping 1 2
After swapping 2 1

Pass by Reference:

Code: 
#include <iostream>

using namespace std;

void swapNum(int& a, int& b) {
    int t = a;
    a = b;
    b = t;
}

int main()
{
    int i = 1;
    int j = 2;
    cout << "Before swapping " << i << " " << j << endl;
    swapNum(i, j);
    cout << "After swapping " << i << " " << j << endl;
    return 0;
} 
Output:
Before swapping 1 2
After swapping 2 1  

Sunday, September 25, 2022

C++ Program for Tree Iterator

Problem

Given n-ary (n children per node) tree, write a C++ iterator to iterate over all the nodes.

Solution

Iterator Interface

One of the potential interface is as follows:

/**
* If there are more children to be traversed in the current layer
* @param index
* @return True if there are children yet to be traversed, false otherwise
*/
virtual bool hasMoreChildren(int index);

/**
* Move to child at index in a layer
* @param index
*/
virtual void moveToChildAt(int index);

/**
* Print the current node
* @param index
*/
virtual void printNode();

Implementation

For implementing the iterator, we will use a stack to keep track of the node being traversed in the tree.

private:
Node* mCurrentNode = nullptr;
std::stack<Node*> mNodeStack;
};

The mCurrentNode and mNodeStack are used in the implementation as follows:

C++ Code

bool TreeIterator::hasMoreChildren(int index) {
if (mNodeStack.empty()) return false;
mCurrentNode = mNodeStack.top();
// If no children, return false.
if (mCurrentNode->children().empty()) {
mNodeStack.pop();
if (!mNodeStack.empty()) {
mCurrentNode = mNodeStack.top();
}
return false;
}
auto it = mCurrentNode->children().begin();
it += index;
// If all children in this layer are traversed, return false.
if (it == mCurrentNode->children().end()) {
mNodeStack.pop();
if (!mNodeStack.empty()) {
mCurrentNode = mNodeStack.top();
}
return false;
}
// There are more children to be drawn, return true
return true;
}

void TreeIterator::moveToChildAt(int index) {
if (mCurrentNode->children().empty()) {
// No children, nothing to do in current layer
return;
}
auto it = mCurrentNode->children().begin();
it += index;
if (it == mCurrentNode->children().end()) {
// All children visited once, nothing to do in current layer
return;
}
mNodeStack.push(*it);
mCurrentNode = mNodeStack.top();
}

void TreeIterator::printNode() {
cout << mCurrentNode->data() << endl;
}

Using the iterator

/**
* Recursively traverse the tree hierarchy
*/
void traverse() {
int i = 0;
while (hasChildren(i)) {
moveToChildAt(i);
traverse();
i++;
}
}

int main() {
TreeIterator *it;
it->traverse();
}

Explanation

The above code is a recursively traverses the children of each node in the tree. The stack maintains the current node at the top and the index passed from the traverse() method determines how many children of a particular node have been visited.

Alternate Solutions

Alternate solutions may use the following approach.

Visitor Pattern

Yet to write a working code, but this approach would mark a node as visited once it has been traversed to keep track of which child of a particular node should be visited next.

Parent Tracking

This requires modifying the tree node to contain a pointer to the parent node so that the mCurrentNode can be moved to the parent when all the children of a particular node are visited.

Python code to find the time difference between all occurrences of a pair of events in a log file

from datetime import datetime
import re

def parse_file(filename, expression1, expression2):
    lines = tuple(open(filename, 'r'))
    expression1Found = False
    expression2Found = False
    pattern = '(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1]) (2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9].[0-9][0-9][0-9]'

    for line in lines:
        if expression1 in line:
            timeString1 = re.search(pattern, line).group()
            expression1Found = True
        if expression2 in line:
            timeString2 = re.search(pattern, line).group()
            expression2Found = True

        if expression1Found and expression2Found:
            timePattern = '%m-%d %H:%M:%S.%f'
            epoch = datetime(1970, 1, 1)
            time1 = (datetime.strptime(timeString1, timePattern) - epoch)
            time2 = (datetime.strptime(timeString2, timePattern) - epoch)
            if int((time2 - time1).total_seconds() * 1000) > 1:
                print(int((time2 - time1).total_seconds() * 1000))

            # Reset and start searching for the next pair of occurrences of expression1 and expression2
            expression1Found = False
            expression2Found = False

if __name__ == "__main__":
    parse_file('filepath', 'even1', 'event2')