Friday, December 5, 2014

How to Edit an Excel File using C# with Excel Office Interop

Below is a simple example how to edit an Excel File using C# with Excel Office Interop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;

namespace ExcelBlog
{
    class Program
    {
        static void Main(string[] args)
        {
            var xlApp = new Excel.Application();
            var xlWorkbook = xlApp.Workbooks.Open(
                @"C:\Users\Fredy\Documents\Visual Studio 2013\Projects\ExcelApp\in.xlsx");
            var xlWorksheet = xlWorkbook.Worksheets["Sheet1"];
            var fullRow = xlWorksheet.Rows.Count;
            var lastRow = xlWorksheet.Cells[fullRow, 1].End(Excel.XlDirection.xlUp).Row;
            var dict = new Dictionary<string, IList<string>>();
            for (int i = 1; i <= lastRow; i++)
            {
                var cell = xlWorksheet.Cells[i, "A"].Value;
                xlWorksheet.Cells[i, "A"].Value = cell + "" + i;
            }
            xlWorkbook.SaveAs(@"C:\Users\Fredy\Documents\Visual Studio 2013\Projects\ExcelApp\out.xlsx");
            xlWorkbook.Close();
        }
    }
}

Monday, October 6, 2014

How to Implement Policy Classes in C++

Policy-based class design is a powerful technique described in Modern C++: Generic Programming and Design Patterns Applied book. It's similar to a strategy design pattern, but with all the type-safety thanks to the use of C++ templates.

Below is a trivial example how to design a library with policy classes.

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

template<class T>
struct HelloPolicy {
    static void saySomething(const T& t) {
        cout << "Hello World, " << t.getName() << endl;
    }
};

template<class T>
struct ByePolicy {
    static void saySomething(const T& t) {
        cout << "Bye World, " << t.getName() << endl;
    }
};

struct Foo {
    string getName() const {
        return "Foo";
    }
};

struct Bar {
    string getName() const {
        return "Bar";
    }
};

template<template <class> class Policy>
class FooPolicy : public Policy<Foo> {
public:
    void doSomething() {
        Foo foo;
        Policy<Foo>().saySomething(foo);
    }
};

template<template <class> class Policy>
class BarPolicy : public Policy<Bar> {
public:
    void doSomething() {
        Bar bar;
        Policy<Bar>().saySomething(bar);
    }
};

int main() {
    FooPolicy<HelloPolicy> f1;
    f1.doSomething();

    FooPolicy<ByePolicy> f2;
    f2.doSomething();

    BarPolicy<HelloPolicy> b1;
    b1.doSomething();

    BarPolicy<ByePolicy> b2;
    b2.doSomething();
    
    return 0;
 }
Output:
Hello World, Foo
Bye World, Foo
Hello World, Bar
Bye World, Bar

Tuesday, September 2, 2014

Java 8 Functional Interfaces

Java 8 has many functional interfaces as defined in the Javadoc. In this blog, I'm going to explain few important Java 8 functional interfaces.
  • Consumer<T>
    • Arguments: T
    • Returns: Void
  • Supplier<T>
    • Arguments: None
    • Returns: T
  • Function<T, R>
    • Arguments: T
    • Returns: R
  • Predicate<T>
    • Arguments: T
    • Returns: boolean
  • UnaryOperator<T>
    • Arguments: T
    • Returns: T
  • BinaryOperator<T>
    • Arguments: (T, T)
    • Returns: T
public class Java8 {
    public static void main(String[] args) {
        System.out.print("Consumer: ");
        Consumer<String> consumer = (s) -> {
            System.out.println(s);
        };
        consumer.accept("hello");

        System.out.print("Supplier: ");
        Supplier<String> supplier = () -> {
            return "foo";
        };
        System.out.println(supplier.get());
        
        System.out.print("Function: ");
        Function<Integer, String> function = (i) -> {
            return "func" + i;
        };
        System.out.println(function.apply(1));
        
        System.out.print("Predicate: ");
        Predicate<Integer> predicate = (i) -> {
            return i == 0;
        };
        System.out.println(predicate.test(0));
        
        System.out.print("UnaryOperator: ");
        UnaryOperator<Integer> unaryOperator = (i) -> {
            return i * 100;
        };
        System.out.println(unaryOperator.apply(2));
        
        System.out.print("BinaryOperator: ");
        BinaryOperator<Integer> binaryOperator = (i, j) -> {
            return i + j;
        };
        System.out.println(binaryOperator.apply(3, 5));
    }
}
Output:
Consumer: hello
Supplier: foo
Function: func1
Predicate: true
UnaryOperator: 200
BinaryOperator: 8

Friday, August 29, 2014

Creating Custom Serializer and Deserializer with Gson

Gson is a cool JSON library by Google. It can convert Java objects into their JSON representation and vice versa. In this blog, I'm going to show how to write custom serializer and deserializer with Gson for the following JSON structure.
{
  "root": {
    "node1-a": {
      "node2-a": {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3"
      },
      "node2-b": {
        "key4": "value4",
        "key5": "value5"
      }
    },
    "node1-b": {
      "node2-a": {
        "key1": "value1",
        "key2": "value2"
      }
    },
    "node1-c": {
      "node2-a": {
        "key1": "value1"
      }
    }
  }
}
public class Root {
    public final Map<String, Node1> map = new LinkedHashMap<String, Node1>();

    public Root put(String key, Node1 node) {
        map.put(key, node);
        return this;
    }

    /**
     * This is the next at level 1
     */
    public static class Node1 {
        public final Map<String, Node2> map = new LinkedHashMap<String, Node2>();

        public Node1 put(String key, Node2 node) {
            map.put(key, node);
            return this;
        }

        @Override
        public String toString() {
            StringBuilder builder = new StringBuilder();
            builder.append("Node1 [map=");
            builder.append(map);
            builder.append("]");
            return builder.toString();
        }
    }

    /**
     * This is the node at level 2
     */
    public static class Node2 {
        public final Map<String, String> map = new LinkedHashMap<String, String>();

        public Node2 put(String key, String value) {
            map.put(key, value);
            return this;
        }

        @Override
        public String toString() {
            StringBuilder builder = new StringBuilder();
            builder.append("Node2 [map=");
            builder.append(map);
            builder.append("]");
            return builder.toString();
        }
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Root [map=");
        builder.append(map);
        builder.append("]");
        return builder.toString();
    }
}

public class Main {
    public static void main(String[] args) throws Exception {
        Gson gson = new GsonBuilder().setPrettyPrinting()
            .registerTypeAdapter(Root.class, new RootSerializer())
            .registerTypeAdapter(Root.class, new RootDeserializer())
            .create();
        
        Root root = new Root()
            .put("node1-a", new Node1()
                .put("node2-a", new Node2()
                    .put("key1", "value1")
                    .put("key2", "value2")
                    .put("key3", "value3"))
                .put("node2-b", new Node2()
                    .put("key4", "value4")
                    .put("key5", "value5")))
            .put("node1-b", new Node1()
                .put("node2-a", new Node2()
                    .put("key1", "value1")
                    .put("key2", "value2")))
            .put("node1-c", new Node1()
                .put("node2-a", new Node2()
                    .put("key1", "value1")));
        
        gson.toJson(root, System.out);
        
        System.out.println();
        
        String json = String.join("\n", Files.readAllLines(Paths.get("test.json")));
        root = gson.fromJson(json, Root.class);
        System.out.println(root);
    }
}

public class RootSerializer implements JsonSerializer<Root> {
    @Override
    public JsonElement serialize(Root root, Type typeOfSrc,
        JsonSerializationContext context) {
        JsonObject node1JsonObj = new JsonObject();
        for (Map.Entry<String, Node1> n1Entry : root.map.entrySet()) {
            JsonObject node2JsonObj = new JsonObject();
            for (Map.Entry<String, Node2> n2Entry : n1Entry.getValue().map.entrySet()) {
                JsonObject jsonObj = new JsonObject();
                for (Map.Entry<String, String> e : n2Entry.getValue().map.entrySet()) {
                    jsonObj.addProperty(e.getKey(), e.getValue());
                }
                node2JsonObj.add(n2Entry.getKey(), jsonObj);
            }
            node1JsonObj.add(n1Entry.getKey(), node2JsonObj);
        }
        
        JsonObject rootJsonObject = new JsonObject();
        rootJsonObject.add("root", node1JsonObj);
        return rootJsonObject;
    }
}

public class RootDeserializer implements JsonDeserializer<Root> {
    @Override
    public Root deserialize(JsonElement rootJson, Type typeOfT,
        JsonDeserializationContext context) throws JsonParseException {
        Root root = new Root();
        JsonObject rootJsonObj = rootJson.getAsJsonObject();
        for (Map.Entry<String, JsonElement> rootJsonEntry : rootJsonObj.entrySet()) {
            JsonObject node1JsonObj = rootJsonEntry.getValue().getAsJsonObject();
            Node1 node1 = new Node1();
            for (Map.Entry<String, JsonElement> n1JsonEntry : node1JsonObj.entrySet()) {
                JsonObject node2JsonObj = n1JsonEntry.getValue().getAsJsonObject();
                Node2 node2 = new Node2();
                for (Map.Entry<String, JsonElement> n2JsonEntry : node2JsonObj.entrySet()) {
                    JsonObject jsonObj = n2JsonEntry.getValue().getAsJsonObject();
                    for (Map.Entry<String, JsonElement> e : jsonObj.entrySet()) {
                        node2.put(e.getKey(), e.getValue().getAsString());
                    }
                }
                node1.put(n1JsonEntry.getKey(), node2);
            }
            root.put(rootJsonEntry.getKey(), node1);
        }
        return root;
    }
}

Tuesday, July 22, 2014

How to Embed Python in C++

#include <iostream>
#include <string>
#include <Python.h>

using namespace std;

int main() {
    Py_Initialize();

    string statements =
        "a = 8\n"
        "b = 2\n"
        "c = (a * b) / 2";

    int retVal = PyRun_SimpleString(statements.c_str());
    if (retVal == 0) {
        PyObject* m = PyImport_AddModule("__main__");
        PyObject* v = PyObject_GetAttrString(m, "c");

        int c = PyInt_AsLong(v);
        cout << "c: " << c << endl;

        Py_DECREF(v);
    }
    Py_Finalize();
    return 0;
}
Output:
c: 8

Wednesday, March 26, 2014

How to Solve Diagonal Print

Given a string and a number, and print the string diagonally filling in empty space with periods and going down as many lines as the given number. So "Peter piper picked a peck of pickled peppers" with n = 10 becomes
P.........r......... .........i.........p...
.e......... .........p.........c.........e..
..t.........p.........e.........k.........r.
...e.........i.........c.........l.........s
....r.........c.........k.........e.........
..... .........k......... .........d........
......P.........e.........o......... .......
.......i.........d.........f.........P...... 
........p......... ......... .........e.....
.........e.........a.........p.........p....
package main

import (
    "fmt"
    "os"
    "strconv"
)

func main() {
    str := os.Args[1]
    n, _ := strconv.Atoi(os.Args[2])
    for i := 0; i < n; i++ {
        for k := 0; k < i; k++ {
            fmt.Print(".")
        }
        for j := 0; j < len(str)-i; j++ {
            if (j % n == 0 && j+1 < len(str)) {
                fmt.Print(string(str[j+i]))
            } else {
                fmt.Print(".")
            }
        }
        fmt.Println()
    }
}

Sunday, January 12, 2014

How to Convert a BST to a Doubly Linked List In-Place

Problem:
Convert a BST to a doubly-linked list in-place. Think of the left and right pointers as synonymous to the previous and next pointers in a doubly-linked list.
package main

import (
    "fmt"
)

type Node struct {
    Value int
    Left  *Node
    Right *Node
}

type LinkedList struct {
    Front *Node
    Back  *Node
}

// this is the actual algorithm that converts a BSt into a doubly linked list
// the rest of the code is just to make unit testing easier
func (l *LinkedList) ToLinkedList(node *Node) {
    if node == nil {
        return
    }
    l.ToLinkedList(node.Left)
    node.Left = l.Back
    if l.Back != nil {
        l.Back.Right = node
    } else {
        l.Front = node
    }
    l.Back = node
    l.ToLinkedList(node.Right)
}

type BST struct {
    Root *Node
}

func (b *BST) Add(value int) {
    b.Root = b.add(b.Root, value)
}

func (b *BST) add(node *Node, value int) *Node {
    if node == nil {
        return &Node{value, nil, nil}
    }
    if node.Value > value {
        node.Left = b.add(node.Left, value)
    } else if node.Value < value {
        node.Right = b.add(node.Right, value)
    }
    return node
}

func main() {
    values := []int{8, 3, 10, 1, 6, 14, 4, 7, 13}
    bst := BST{}
    for _, v := range values {
        bst.Add(v)
    }
    ll := LinkedList{}
    ll.ToLinkedList(bst.Root)
    for n := ll.Front; n != nil; n = n.Right {
        fmt.Print(n.Value, " ")
    }
    fmt.Println()
    for n := ll.Back; n != nil; n = n.Left {
        fmt.Print(n.Value, " ")
    }
    fmt.Println()
}
Output:
1 3 4 6 7 8 10 13 14 
14 13 10 8 7 6 4 3 1

Tuesday, January 7, 2014

How to Force Kill a Process in Java

In Java, there is no easy way to force a termination of a process spawned in Java. Calling Process.destroy() does not guarantee that the process will be terminated. Although Java 8 might fix this with Process.destroyForcibly(), if you still use older versions of Java, you are out of luck. Below is a not-so-portable solution to terminate a process on Linux and Windows using Java Native Runtime. You could also use JNA or JNI to invoke the OS native API.
package test;

import java.lang.reflect.Field;

import jnr.ffi.LibraryLoader;
import jnr.ffi.Pointer;
import jnr.ffi.Runtime;

public class Test {
    public static interface Kernel32 {
        boolean TerminateProcess(Pointer handle, int exitCode);
    }
    
    public static interface Posix {
        int kill(int pid, int sig);
    }
    
    public static void main(String[] args) throws Exception {
        ProcessBuilder pb = new ProcessBuilder(args[0]);
        Process p = pb.start();
        System.out.println("Sleeping for 5 seconds");
        Thread.sleep(5000);
        p.destroy();
        if (System.getProperty("os.name").toLowerCase().startsWith("win")) {
            if (p.getClass().getName().equals("java.lang.Win32Process") ||
                p.getClass().getName().equals("java.lang.ProcessImpl")) {
                Field f = p.getClass().getDeclaredField("handle");
                f.setAccessible(true);
                long handle = f.getLong(p);
                
                System.out.println("Killing process");
                Pointer ptr = Pointer.wrap(Runtime.getSystemRuntime(), handle);
                int exitCode = 0;
                Kernel32 kernel32 = LibraryLoader.create(Kernel32.class).load("Kernel32");
                kernel32.TerminateProcess(ptr, exitCode);
            }
        } else {
            if (p.getClass().getName().equals("java.lang.UNIXProcess")) {
                Field f = p.getClass().getDeclaredField("pid");
                f.setAccessible(true);
                int pid = f.getInt(p);
                
                System.out.println("Killing process");
                Posix posix = LibraryLoader.create(Posix.class).load("c");
                posix.kill(pid, 9);
            }
        }
    }
}