Posts Tagged ‘c’

Create keyboard shortcut for console application with hidden form (c#)

April 18th, 2014

Here is good example from stackoverflow:。 It works like a charm!

Here I paste the code for your convenience (I don’t own the copyright).
The helper class for hotkey registry

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

  public class HotKeyManager
    public static event EventHandler HotKeyPressed;

    public static int RegisterHotKey(Keys key, KeyModifiers modifiers)
      int id = System.Threading.Interlocked.Increment(ref _id);
      RegisterHotKey(_wnd.Handle, id, (uint)modifiers, (uint)key);
      return id;

    public static bool UnregisterHotKey(int id)
      return UnregisterHotKey(_wnd.Handle, id);

    protected static void OnHotKeyPressed(HotKeyEventArgs e)
      if (HotKeyManager.HotKeyPressed != null)
        HotKeyManager.HotKeyPressed(null, e);

    private static MessageWindow _wnd = new MessageWindow();

    private class MessageWindow : Form
      protected override void WndProc(ref Message m)
        if (m.Msg == WM_HOTKEY)
          HotKeyEventArgs e = new HotKeyEventArgs(m.LParam);

        base.WndProc(ref m);

      private const int WM_HOTKEY = 0x312;

    private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

    private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

    private static int _id = 0;

  public class HotKeyEventArgs : EventArgs
    public readonly Keys Key;
    public readonly KeyModifiers Modifiers;

    public HotKeyEventArgs(Keys key, KeyModifiers modifiers)
      this.Key = key;
      this.Modifiers = modifiers;

    public HotKeyEventArgs(IntPtr hotKeyParam)
      uint param = (uint)hotKeyParam.ToInt64();
      Key = (Keys)((param & 0xffff0000) >> 16);
      Modifiers = (KeyModifiers)(param & 0x0000ffff);

  public enum KeyModifiers
    Alt = 1,
    Control = 2,
    Shift = 4,
    Windows = 8,
    NoRepeat = 0x4000

Example of using the helper class

using System;
using System.Windows.Forms;

namespace ConsoleHotKey
  class Program
    static void Main(string[] args)
      HotKeyManager.RegisterHotKey(Keys.A, KeyModifiers.Alt);
      HotKeyManager.HotKeyPressed += new EventHandler(HotKeyManager_HotKeyPressed);

    static void HotKeyManager_HotKeyPressed(object sender, HotKeyEventArgs e)
      Console.WriteLine("Hit me!");

install igraph (C) on Linux(ubuntu) and use it in Eclipse

November 30th, 2011

Build and install igraph.

      download the source code package;
      unpack it into a directory, eg. igraph-0.5.4 (I’ll use IGRAPH_DIR instead below)
      enter the directory: user> cd IGRAPH_DIR
          user> make
          user> sudo make install This will install the igraph libary files into /usr/local/lib

Add igraph libraries to the shared libraries search path

If you haven’t include /usr/local/lib into your shared libraries search path as defined in /etc/, add it. Otherwise, you will see an error like this: error while loading shared libraries: cannot open shared object file: No such file or directory.

And DON’T forget to reload the config:user> sudo ldconfig

Use igraph in Eclipse

      Go to Project -> Properties-> C/C++ Build -> Settings
      Go to GCC C++ Compiler -> Directories, add /usr/loccal/include/igraph.
      Go to GCC C++ Linker -> Libraries, add “igraph” to Libraries (-l) and add “/usr/loca/lib” to Library search path (-L).

An example of Boost Betweenness Centrality

November 28th, 2011

Here is an example of using Boost to calculate Betweenness Centrality for a graph. The example is original from:

But now the page is down, so I cache it here:


 * In the included example, the max centrality of the graph is 14. So specifying
 * the required input argument 14 gives the "first" decomposition of the graph.
 * That is, removal of one edge (with the maximal edge centrality). Specifying a value
 * greater than 14 yields no decomposition.
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graphviz.hpp>
// For clustering
#include <boost/graph/bc_clustering.hpp>
#include <boost/graph/iteration_macros.hpp>
// Graph edge properties (bundled properties)
struct EdgeProperties
  int weight;
typedef boost::adjacency_list< boost::setS, boost::vecS, boost::undirectedS, boost::no_property, EdgeProperties > Graph;
typedef Graph::vertex_descriptor Vertex;
typedef Graph::edge_descriptor Edge;
void WriteGraph(const Graph& g, const std::string& filename);
int main(int argc, char** argv)
  // Verify arguments
  if( argc != 2 )
    std::cerr << "USAGE: " << argv[0] << " <Max centrality>" << std::endl;
    return -1;
  // Convert the input argument to a double
  std::stringstream ss;
  ss << argv[1];
  double max_centrality;
  ss >> max_centrality;
  // Create a star graph
  Graph g;
  // Central vertex
  Vertex centerVertex = boost::add_vertex(g);
  // Surrounding vertices
  Vertex v;
  v = boost::add_vertex(g);
  boost::add_edge(centerVertex, v, g);
  v = boost::add_vertex(g);
  boost::add_edge(centerVertex, v, g);
  v = boost::add_vertex(g);
  boost::add_edge(centerVertex, v, g);
  v = boost::add_vertex(g);
  boost::add_edge(centerVertex, v, g);
  v = boost::add_vertex(g);
  boost::add_edge(centerVertex, v, g);
  v = boost::add_vertex(g);
  boost::add_edge(centerVertex, v, g);
  v = boost::add_vertex(g);
  boost::add_edge(centerVertex, v, g);
  // Attach an additional vertex to one of the star arm vertices
  Vertex x = boost::add_vertex(g);
  boost::add_edge(v, x, g);
  // std::map used for convenient initialization
  typedef std::map<Edge, int> StdEdgeIndexMap;
  StdEdgeIndexMap my_e_index;
  // associative property map needed for iterator property map-wrapper
  typedef boost::associative_property_map< StdEdgeIndexMap > EdgeIndexMap;
  EdgeIndexMap e_index(my_e_index);
  // We use setS as edge-container -> no automatic indices
  // -> Create and set it explicitly
  int i = 0;
  BGL_FORALL_EDGES(edge, g, Graph)
    my_e_index.insert(std::pair< Edge, int >( edge, i));
  // Define EdgeCentralityMap
  std::vector< double > e_centrality_vec(boost::num_edges(g), 0.0);
  // Create the external property map
  boost::iterator_property_map< std::vector< double >::iterator, EdgeIndexMap >
          e_centrality_map(e_centrality_vec.begin(), e_index);
  // Define VertexCentralityMap
  typedef boost::property_map< Graph, boost::vertex_index_t>::type VertexIndexMap;
  VertexIndexMap v_index = get(boost::vertex_index, g);
  std::vector< double > v_centrality_vec(boost::num_vertices(g), 0.0);
  // Create the external property map
  boost::iterator_property_map< std::vector< double >::iterator, VertexIndexMap >
          v_centrality_map(v_centrality_vec.begin(), v_index);
  std::cout << "Before" << std::endl;
  BGL_FORALL_EDGES(edge, g, Graph)
    std::cout << edge << ": " << e_centrality_map[edge] << std::endl;
  // Write to graphviz -> illustrate the graph via 'neato -Tps >'
  WriteGraph(g, "");
  // Calculate the vertex and edge centralites
  // Can be used to get an initial impression about the edge centrality values for the graph
  //brandes_betweenness_centrality( g, v_centrality_map, e_centrality_map );
  // Define the done-object:
  // 'false' means here that no normalization is performed, so edge centrality-values can become big
  // If set to 'true', values will range between 0 and 1 but will be more difficult to use for this
  // illustrative example.
  boost::bc_clustering_threshold< double > terminate(max_centrality, g, false);
  // Do the clustering
  // Does also calculate the brandes_betweenness_centrality and stores it in e_centrality_map
  betweenness_centrality_clustering( g, terminate, e_centrality_map );
  // Print the results
  std::cout << "\nAfter" << std::endl;
  BGL_FORALL_EDGES(edge, g, Graph)
    std::cout << edge << ": " <<e_centrality_map[edge] << std::endl;
  // Write to graphviz -> illustrate the graph via 'neato -Tps >'
  WriteGraph(g, "");
  return 0;
void WriteGraph(const Graph& g, const std::string& filename)
  std::ofstream graphStream;;
  boost::write_graphviz(graphStream, g );

CPP (C++) time

October 21st, 2011

There are may ways to estimate how long a program (or a part of the program) elapsed.

Use clock()

clock() is a standard function defined in . Here is the usage:

#include <ctime>

int main() {
  clock_t start, end;
  start = clock();
  // do sth...
  end = clock();

  double elapsedSeconds = (end - start) / CLOCKS_PER_SEC;

Use gettimeofday()

clock() is a linux function defined in . Here is the usage: #include <sys/time.h> int main() { timeval start, end; gettimeofday(&start, 0); // the second parameter is the timezone. // do sth... gettimeofday(&end, 0); double elapsedSeconds = (end.tv_sec - start.tv_sec + 1e-6*(end.tv_usec - start.tv_usec)); }

solve the problem of no output in console on windows eclipse with MinGW

October 14th, 2011

If you are experiencing the problem of no output in console on windows eclipse with MinGW, here is the solution.

And actually the solution the is very simple, you only have to add a PATH variable to your MinGW bin directory in the run configuration.

Here are the steps:

From menu: Run -> Run Configuration…, open the run configuration window, and add the PATH variable to your MinGW bin directory (as shown in the picture below).

Differences between new/delete and malloc/free in C and CPP

October 4th, 2011

There is a very good post about this:

Here I’ll just list some of the differences concisely:

  • new & delete will call the object’s default constructor & destructor respectively; while malloc & free will not. This is also why dynamically array will call it’s element’s default constuctor. See
  • malloc returns a void*, so it’s result always needs cast. Such as: FooCls* t = (FooCls*) malloc(sizeof FooCls);
  • when using new to create an array, delete[] is needed. And never delete[] a single object, it's even worse.
  • realloc only exists with malloc/free pair. It's handy when resize an object to the same or less size.
  • new & delete are based on malloc & free. Malloc additionally allocate a header storing the size allocated, so free() knows the size to free. new[] not only keeps the malloc header, but also has an extra header storing the size of the array/vector, so delete[] knows how many objects are in the array/vector, and thus knows how many times to call the destructor.
    details of new[] & delete[] can be found at: Mismatching scalar and vector new and delete

mysqlpp connection timeout problem

October 3rd, 2011

If you have a application having long time connection with mysql using mysqlpp. You may at first think of using Connection::connected() to determine whether the connection is still valid. But actually this doesn’t work if the connection gets timeout.

After checking the reference, I found out Connection::ping() would be a good way to determine timeout.

Here is a piece of test code:

#include <iostream>
#include <string>
#include <mysql++.h>

using namespace std;

int main() {
	string db_schema("DB_SCHEMA");
	string db_host("DB_HOST");
	string db_user("DB_USER");
	string db_pass("DB_PASS");
	string qry_str("SELECT MAX(user_id) FROM users");

	mysqlpp::Connection cn;
	cn.connect(db_schema.c_str(), db_host.c_str(), db_user.c_str(), db_pass.c_str());
	mysqlpp::Query qry = cn.query(qry_str);
	mysqlpp::StoreQueryResult res =;
	cout << "frist query result: " << res[0][0] << endl;

	string tmp;
	cout << "Wait for a period of time to let the connection timeout, and then input whatever a string to continue: " << endl;
	cin >> tmp;

	cout << "ping result: " << << endl;
	cout << "connected: " << cn.connected() << endl;
		cn.connect(db_schema.c_str(), db_host.c_str(), db_user.c_str(), db_pass.c_str());
	mysqlpp::Query qry2 = cn.query(qry_str);
	res =;
	cout << "second query result: " << res[0][0] << endl;

	return 0;	

But of course, I’m still new to mysqlpp. There may be a better way to do this. Please comment below if you have a better way.

NOTE: Here is how to change mysql connection idle timeout.

UPDATE: Just found another way to handle the timeout problem: use Connection::set_option(new mysqlpp::ReconnectOption(true));. This is much more elegant.
Here is a piece of sample code:

mysqlpp::Connection cn;
cn.set_option(new mysqlpp::ReconnectOption(true));
cn.connect(db_schema.c_str(), db_host.c_str(), db_user.c_str(), db_pass.c_str());

System V message queue example (msgget, msgctl, msgsnd, msgrcv)

September 21st, 2011

Found a very good example of message queue showing how to use msgget, msgctl, msgsnd, and msgrcv at Here I list the code with tiny fix and some of my comments.

The linux man page of msgsnd & msgrcv can be found here:


extern int errno;       // error NO.
#define MSGPERM 0600    // msg queue permission
#define MSGTXTLEN 128   // msg text length

int msgqid, rc;
int done;

struct msg_buf {
  long mtype;
  char mtext[MSGTXTLEN];
} msg;

int main(int argc,char **argv)
  // create a message queue. If here you get a invalid msgid and use it in msgsnd() or msgrcg(), an Invalid Argument error will be returned.
  if (msgqid < 0) {
    printf("failed to create message queue with msgqid = %d\n", msgqid);
    return 1;
  printf("message queue %d created\n",msgqid);
  // message to send
  msg.mtype = 1; // set the type of message
  sprintf (msg.mtext, "%s\n", "a text msg..."); /* setting the right time format by means of ctime() */

  // send the message to queue
  rc = msgsnd(msgqid, &msg, sizeof(msg.mtext), 0); // the last param can be: 0, IPC_NOWAIT, MSG_NOERROR, or IPC_NOWAIT|MSG_NOERROR.
  if (rc < 0) {
    perror( strerror(errno) );
    printf("msgsnd failed, rc = %d\n", rc);
    return 1;

  // read the message from queue
  rc = msgrcv(msgqid, &msg, sizeof(msg.mtext), 0, 0); 
  if (rc < 0) {
    perror( strerror(errno) );
    printf("msgrcv failed, rc=%d\n", rc);
    return 1;
  printf("received msg: %s\n", msg.mtext);

  // remove the queue
  if (rc < 0) {
    perror( strerror(errno) );
    printf("msgctl (return queue) failed, rc=%d\n", rc);
    return 1;
  printf("message queue %d is gone\n",msgqid);

  return 0;

————– Update 14/Dec/2011 ——————
A note about the struct msg_buf. From: “The Linux Programmer’s Guide”

The ability to assign a given message a type, essentially gives you the capability to multiplex messages on a single queue. For instance, client processes could be assigned a magic number, which could be used as the message type for messages sent from a server process. The server itself could use some other number, which clients could use to send messages to it. In another scenario, an application could mark error messages as having a message type of 1, request messages could be type 2, etc. The possibilities are endless.

On another note, do not be misled by the almost too-descriptive name assigned to the message data element (mtext). This field is not restricted to holding only arrays of characters, but any data, in any form. The field itself is actually completely arbitrary, since this structure gets redefined by the application programmer. Consider this redefinition:

struct my_msgbuf {
long mtype; /* Message type */
long request_id; /* Request identifier */
struct client info; /* Client information structure */

Here we see the message type, as before, but the remainder of the structure has been replaced by two other elements, one of which is another structure! This is the beauty of message queues. The kernel makes no translations of data whatsoever. Any information can be sent.

problem of returning *this in C++

July 5th, 2011

I have a small class, in one of whose methods I want to return the instance itself so I can continue to use the instance and thus save inputting. However, “return *this” seems not working as waht I expected. The class is like this:


* UndirectedGraph.h


#include <utility>
#include <set>

using namespace std;

namespace wp {

class UndirectedGraph {
UndirectedGraph(size_t n);
virtual ~UndirectedGraph();

addEdge(size_t node1, size_t node2);

size_t len;
set *nbs;





* UndirectedGraph.cpp
#include <utility>
#include <set>
#include <iostream>
#include "UndirectedGraph.h"

using namespace std;

namespace wp {

UndirectedGraph::UndirectedGraph(size_t n) : len(n) {
std::cout << "constructor with len: " << this->len << std::endl;
for(size_t node = 0; node != n; ++node) {
nbs = new set[this->len];

UndirectedGraph::~UndirectedGraph() {
delete[] nbs;
std::cout << "destructor finished" << std::endl;

UndirectedGraph::addEdge(size_t node1, size_t node2) {
if(node1 >= this->len || node2 >= this->len)
throw 1;
if(node1 == node2)
throw 2;
return *this;




And in the main() function:

int main() {
UndirectedGraph g(7);
g.addEdge(0, 1).addEdge(0, 2)
.addEdge(1, 3).addEdge(1, 5);

What am I missing?

————– EDIT ————-
The solution to the problem is to return *this as a reference to itself, as below:
UndirectedGraph & addEdge(size_t node1, size_t node2);

set up CppUnit Eclipse plugin (ECUT) for C++ on Ubuntu

September 24th, 2010

Here I will show how to use CppUnit to do Unit Testing for C++ within Eclipse with the plugin ECUT.

NB: the OS here is Ubuntu 10.4. As for other OS, you have to figure out how to install CppUnit by yourself, and change the build path accordingly in configuration.

* First, install CppUnit. On Ubuntu, we can install from the repository:

sudo apt-get install libcppunit-1.12-1 libcppunit-dev

* Get the ECUT plugin from and install it in Eclipse with the software installer in the Help menu.

* Configur the connector in Eclipse in Window -> Preferences -> C/C++ -> ECUT -> Configure (Add “Library location: /usr/lib/libcppunit.a” and “Include location: /usr/include/cppunit”).

Now the configuration is done. Now let’s see a sample project. I’ll use the official ECUT Demo:

* Create a empty C++ project in Eclipse called: EcutTest.

* Create 2 source folders within the project: src & test. src will be place for application application source files, while test is for test cases.

* Copy the 3 source files from EcutDemo_M3/src into the project src folder.

* Build a Debug version, and run it. This is just to test whether the project works. You will find the output: “result: 13″ if it build the project right.

Now it’s the time to connect CppTest with the project.

* Right click on the project name “EcutTest”, and choose ECUT -> Apply Connector. Select the one and only Connect “CppUnit Connector”, and “Create build configurations” as well.
– Note: ignore the warning in the image below, because I have applied the connect before.
– If you need a configuration: Library location is: “/usr/lib/libcppunit.a” and Include location is: “/usr/include/cppunit”.

* Create a Test case. Right click on module1.c -> New -> ECUT Test Case. Note: ignore the error message in the image below, because I have already created the Test Case.

* edit the automatically created source file test/module1Test.cpp a little bit to correct the Include Path.

change the source:

#include “module1.c”


#include “../src/module1.c”

* Create a run configuration to run the Test Case: Run -> Run Configurations -> Right click on ECUT -> New:

ECUT Test Case Run Configuration

* Run the test by clicking on Run as shown in the above image. Both of the 2 test cases should fail, because in the test method body, they return false directly.

* OK, now everything is done. It’s the time to do some real work. Change the function module1Test::testadd as bleow:

void module1Test::testadd() {
CPPUNIT_ASSERT(24 == add(12, 12));

And run the Test again, you will find 1 case is passed, and 1 case fails.

Details of assertions can be found here: