Skip to main content

Posts

Showing posts from 2014

Streams and Pipelines in UNIX environments

Linux shells use three standard I/O streams, each of which is associated with a well-known file descriptor:   stdout is the standard output stream , which displays output from commands. It has file descriptor 1. stderr is the standard error stream , which displays error output from commands. It has file descriptor 2. stdin is the standard input stream , which provides input to commands. It has file descriptor 0. Redirecting output ls x* z* >stdout.txt 2>stderr.txt Standard output in the first file and the errors in the second file. Output redirection using n> usually overwrites existing files. You can control this with the noclobber option of the set builtin. ls x* z* 2>&1 >output.txt This will redirect all errors to standard output and standard output is redirected to the file. The errors will be displayed in the terminal and the output is written to a file.   ls x* z*

grep useful commands

a_file ------- boot book booze machine boots bungie bark aardvark broken$tuff robots grep "boo" a_file  boot book booze boots grep -n "boo" a_file 1:boot 2:book 3:booze 5:boots grep -vn "boo" a_file 4:machine 6:bungie 7:bark 8:aaradvark 9:robots grep -c "boo" a_file 4 grep -l "boo" * Prints out the file names grep -i "BOO" a_file ignores case grep -x "boo" a_file  exact matches echo "i want to search for this text" > search grep -f search a_file

Embedding tex in pdf figures

It's often required to include latex symbols in publication ready figures. For example Greek symbols in LaTex can be written as \alpha which appear as the actual alpha symbol when compiled. The same effect can be embedded in figures and these figures can be separately compiled for convenience. This means that you don't have to create any intermediate files (such as pstex) in your actual tex file but rather have standalone pdf figures. You need to have a few things in hand and this is done in Ubuntu (or any Linux system) 1. Dia 2. fig2pdf (sudo apt-get install fig2pdf) - this will install a whole range of other converters, fig2eps etc. 3. XFig (this will be installed from the fig2pdf command itself) 4. Latex (comes with the Ubuntu distribution) OK. In Ubuntu you can test if everything is available by typing in the commands, e.g. if you type fig2pdf it should know the command and should tell you the usage. Now we proceed to create a figure in Dia. You see that t

Playing with prime numbers

A prime number is a number that is divisible only by itself, for example the first few prime numbers are 2,3,5,7,11,13,17,..... The straightforward way to find all prime numbers is to iterate through the numbers and see each number meets a specific criterion. The program does this by, Check if the number ends with a 2,4,5,6,8 or a 0. If this is the case it's not prime. Check if the number is divisible by 3 or 7, then it's not prime These 2 conditions alone doesn't suffice. For example take the number 1079, this is divisible by 13, so we have to check if each number can be divided by any other prime numbers which are lower than the number itself. But there's a shortcut. We don't have to check with every prime number lower than the number. Take the prime number 37. We take it's square root rounded down, which is 6. Then we check the prime numbers only upto 7 because otherwise we do unnecessary checks, e.g. we can check 2*6. 3*6, 5*6 but as soon as we go 7*6

B'day paradox problem

Birthday paradox problem is to fill a room with n people and get the probability of at least 2 people having the same b'day. This is given for 25 people as 1-(364.363.362....341)/(365^24). This can be done using the following snippet in C++. http://en.wikipedia.org/wiki/Birthday_problem#Calculating_the_probability void bDayParadox() {     float result = 1.0;     int numerator = 364.0;     for (int i = 0; i < 24; i++) {         result = result * (numerator / 365.0);                numerator = numerator - 1.0;     }     std::cout << 1.0-result << std::endl; }

Finding the factorial of any number

This is an interesting problem that I did to polish up my coding + analytical skills.  I required to get the factorial of any number (1 to 15 here). Because you need to handle large numbers this had to be done via a custom multiplier. Given the first few factorials: 1! = 1 2! = 2 x 1 = 2 3! = 3 x 2 x 1 = 6 4! = 4 x 3 x 2 x 1 = 24 What is the sum of the first 15 factorials, NOT INCLUDING 0!? Source : http://www.cstutoringcenter.com/problems/problems.php?id=1 Rendering...

Setting up google test and google mock

Google test is a great library that one can use for unit testing. Google mock is an extension of Google test as a mocking framework which can be used to mock the behavior of interfaces. First things first, build the library gmock. I use netbeans. 1. Create a new project  as C/C++ static library 2. Include the files as "Add Existing Item"   ${GTEST_DIR}/src/gtest-all.cc and ${GMOCK_DIR}/src/gmock-all.cc 3. Include the  Directories and Headers for the compiler in project properties. ${GTEST_DIR}/include and ${GMOCK_DIR}/include and  ${GTEST_DIR} and ${GMOCK_DIR} 4. Build..... Note: It's mentioned that you need -pthread but since we are building a static library, the links are not resolved so you need to only enter them in the application linker properties. Now you'll end up with the ".a file" in the dist folder. Now create a new application as a C/C++ project. This project contains your application that should be tested or mocked using Google test f

Passing a pointer by reference

I wanted to create an array of a certain class but its size was not determined until run time. Therefore I had to of course use a pointer. Now because it was always good practice to initialize a pointer to NULL, I did so and I passed this initialized pointer to a function. This function would then new the pointer inside, seemed OK but this made the program crash. I used the function AllocateArray1 in the gist. Why did it crash? The pointer is passed by value and when the function exits the pointer being passed is not quite initialized. To verify this I used the test case 3 where I created an array, deleted it but didn't assign it back to NULL, this made sure that the pointer is still pointed to a certain memory address. The works because although the memory is deallocated we can still access the values using raw pointers, although this might crash some times due to access violation. The other option of course, which I used was to pass the pointer by reference. AllocateArra

Math Lesson - Combinations and Permutations

Very often I need to deal with combinations and permutations. This is just a recap on high school math which I tend to lose touch on. A combination doesn't care about the order, e.g. 123 is the same as 312 A permutation does Imagine there are 5 numbers 1,2,3,4,5. We need to choose 3, n=5, r=3. How many combinations? How many permutations? Permutation with repetition n^r Imagine there are 3 slots for the 3 numbers. There's 5 number we can fill the first slot. 5 numbers we can fill the second and 5 number we can fill the third. 5*5*5 permutations. Permutation without repetition n!/(n-r)! There's 5 number we can fill the first slot. 4 numbers we can fill the second and 3 number we can fill the third. 5*4*3 permutations. Combinations without repetition n!/((n-r)!r!) Imagine permutations without repetition. Now remove the sens of permutations Hence an additional r! in the denominator. Combinations with repetition (n+r-1)!/r!(n-1)! This needs an unusual appr

Array parsing in C++

Array parsing in  C++ is always done by reference, and in std there's no concept of parsing by value. From a stakoverflow question I summarize this below. The array size information is lost here. void by_pointer(int *p, int size); void by_pointer(int p[], int size); void by_pointer(int p[7], int size);   // the 7 is ignored in this context! void by_reference(int (&a)[7]); // only arrays of size 7 can be passed here! template void by_reference(int (&a)[size]); void TestMethod(char cArray[], int size) {          const char* pTest = "test";     strncpy(cArray, pTest, size);     cArray[ size-1] = '\0';     }   Usage: char cMyArray[7] =  {a}; TestMethod(cMyAray, 7}  However this can be quite tricky to understand. Take the problem of dynamic resizing of an array. unsigned int iArrSize = 10; int *iArr = new int[iArrSize]; for (int i = 0; i < 100; i++) {         if (i >= iArrSize) {             int *arr3 = new int[iArrSize*2];            

C++ tips - I

Static members in .h and .cpp A static variable in C++ when defined in a global function belongs to the file scope. If a C++ static variable is defined as a member variable, regardless of how many objects we instantiate we only have one static variable across all of the instances. The static variable can be accessed via the instance or the class variable. If a static variable is defined as member in a class declared in a .h file, the initialization should be done as [variable_type] ClassName::[variable_name] = [value] A static function can only access static variables - makes sense huh?? A static function doesn't have the this pointer class_name::static_function() - usage Friend keyword

The Mediator Pattern

Mediator pattern is used to loosely couple object interaction. If objects are tightly coupled, resuability disappears and maintenance becomes harder. A real life scenario will explain the pattern the best. Think about an airport control tower. It's task is to moderate the flight landings. If many aircrafts arrive simultaneously, only one can land at a time and the rest have to stay out from landing until signaled by the tower. This behavior exactly matches that of the mediator pattern. The aircrafts don't communicate with each other but yet they communicate through the control tower so that they can avoid disaster. The C++ code simulating the landing of planes, helicopters and private jets at an airport is simulated in this code. Assume only one airstrip. The output: Mediator Will Take Over Landing Plane Landing 1 Heli Out of the way... 2 Jet Out of the way... 3 Jet Out of the way... 4 Mediator Will Take Over Landing Heli Out of the way... 2 Jet Landing 3 Jet Ou