Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 11-20 of 24 total

C++ Style Comment Stripper

// This scirpt either removes the C++ style comments or places them
// just before the line in which they occur
// for ex:
//
// int i=0, sum; //This is some comment(embedded)
//
// after conversion:
// //This is some comment(embedded)
// int i=0, sum;

# comm_stripper
#
# Description :
#
#   This scirpt either removes the C++ style comments or places them
#   just before the line in which they occur
#   for ex:
#
#       int i=0, sum;    //This is some comment(embedded)
#
#   after conversion:
#       //This is some comment(embedded)
#       int i=0, sum;

import re
import os

#comm_re = re.compile(r"(\s*)(.*)(//.*)")

comm_re = re.compile(r"(\s*)(.*?)(//.*)")
ext_re  = re.compile(r"\.(cpp|h|hpp|c|icc)$")
out_ext = ".out"

TRUE  = 1
FALSE = 0

def comm_strip(file_name, keep_comment=TRUE):
    lines = file(file_name).readlines()
    out_lines = []

    out_filename = file_name + out_ext
    fout = open(out_filename, "w")

    for line in lines:
        match = comm_re.match(line.rstrip())

        if(match):
            if keep_comment:
                #print "%s%s" % (match.group(1), match.group(3))
                out_lines.append("%s%s\n" % (match.group(1), match.group(3)))
            if match.group(2):
                #print "%s%s" % (match.group(1), match.group(2).rstrip())
                out_lines.append("%s%s\n" % (match.group(1), match.group(2).rstrip()))
        else:
            #print line.rstrip()
            out_lines.append(line)

    out_lines.append("\n\n")
    fout.writelines(out_lines)
    print "File %s => %s" % (file_name, out_filename)
    print "-"*80

print os.getcwd()
file_names = os.listdir(".")
flag=TRUE

for file_name in file_names:
    match_ext = ext_re.search(file_name)

    if match_ext :
        comm_strip(file_name, flag)

print "Done!"

Convert String-Type the C++-Way

A very useful snipped that converts strings to/from various types.

Here's the header:
#include <string>
#include <iostream>
#include <vector>
#include <sstream>
#include <iomanip>
using namespace std;

#ifndef ST_STRING
#define ST_STRING


enum CONVTYPE { STRTOINT, STRTOFLOAT, INTTOSTR, STRTODOUBLE }; 

/*
 *  Convtype converts an integer to a string and a string 
 *  string to an integer, a float, or a double. The third argument
 *  of this method determines what to do:
 *  STRTOINT, STRTOFLOAT, INTTOSTR, and STRTODOUBLE.
 *
 */
void convtype(void*, void*, const int& );  
  
#endif



The appropiate implementation:
void convtype(void* inp, void* out, const int& convtype)
{
  istringstream isbuf;
  ostringstream osbuf;

  switch(convtype)
    {
    case STRTOINT:
      isbuf.str(*(string*) inp);
      isbuf >> *((int*) out);
      break;
    case STRTOFLOAT:
      isbuf.str(*(string*) inp);
      isbuf >> *((float*) out);
      break;
    case STRTODOUBLE:
      isbuf.str(*(string*) inp);
      isbuf >> *((double*) out);
      break;
    case INTTOSTR:
      osbuf << *((int*) inp);
      *((string*)out)=osbuf.str();
      break;
    }
  return;
}

Vector Statistic Library Test

Using Intel-C++ compiler and Intel-Math Kernel Library, here is an example usage of random number generation.

 //
 // VSL test by Sascha Tayefeh 2006
 // http://www.tayefeh.de
 //
 // Vector Statistic Libraries Test 
 // You will have to use Intel icc-compiler along with its 
 // Math Kernel Library.
 // 
 // Compile with something like:
 //
 // icc  -I~/mkl_8.1/include 001.cc -L~/mkl_8.1/lib/em64t -lmkl_em64t vsl.cc -o vsl
 //
 //
 
#include <iostream>
using namespace std;
#include "mkl_cblas.h"
#include "mkl_vsl.h"
#define LENGTH 30000
int main ()
{
	int n(LENGTH); // Number of random values to be generated
	float a(60.0), s(10.9); // For a gaussian distribution parameter a and s(igma)
	float *pt(NULL); // The pointer to the array that is supposed to contain the random numbers
	int status; // Return Status of the generator algorithm

	// Allocate sufficiant memory
	pt=new float[LENGTH];
	

	// Create the VSL Stream (search the MKL/VSL-Docs for Service Routines)
	VSLStreamStatePtr stream;
		vslNewStream( &stream, VSL_BRNG_R250, 1232);
	// The random number generator routine
	status =vsRngGaussian( VSL_METHOD_SGAUSSIAN_BOXMULLER, stream, n, pt, a,s); 


	// Show us what we have done ;-)
	for (int i=0; i<LENGTH; i++)
	{
		cout  << *(pt+i) << endl;
	}
	vslDeleteStream( &stream );
	delete [] pt;
	return 0;
}

Inherided Constructors and Destructors

A little demonstration that shows how C++ acts with inherited constructors/destructors

#include <iostream>
using namespace std;

class First 
{
private:
  int i;

protected:

public:
  void getI(int &);
  void putI(const int &);
  First();
  ~First();
};

class Inh : First
{
private:
  int u;
protected:

public:
  Inh();
  ~Inh();
};

Inh::Inh()
{
  cout << "Inh Constructor" << endl;
}

Inh::~Inh()
{
  cout << "Inh Destructor" << endl;
}

void First::getI(int & o)
{
  o = i;
}

void First::putI(const int & o)
{
  i = o;
}

First::First()
{
  i = 1;
  cout << "First Constructor" << endl;
}

First::~First()
{
  cout << "First Destructor" << endl;
}

int main()
{
  int i(2),o(0);
  Inh inh;
  return;
}

Valarray vs. array matrix-calculation performance

Demonstrates the usage of valarray and measures the performance of some arithmetic operations on matriced to be compared with the same operations performed with ordinary arrays.

#include <iostream>
#include <valarray>
#include <vector>
#include <ctime>
#include <iomanip>
using namespace std;

void rndm(float& a);
void zerocheck(float& a);
double duration(vector<clock_t>::iterator start, vector<clock_t>::iterator stop);

int main()
{
  int i(0);
  int p(0);
  float k(5.3235),l(9.212);
  int size(4000000);

  vector<clock_t> vstart;
  vector<clock_t> vstop;
  vector<clock_t>::iterator istartclock;
  vector<clock_t>::iterator istopclock;
  vector<float> vfloat(size);
  vector<float>::iterator ifloat;
  valarray<float> valfloat(size);

  cout << "Filling float array with " << size << " random elements" << endl;
  cout << "(each element needs " << sizeof(float) << " bytes of memory, so " \
       << "we need to make use of " << size*sizeof(float)/1000000<< "MBytes.)"<< endl;

  // ======================= ORDINARY OPERATIONS =======================
  // fill array

  vstart.push_back(clock());
  //  vfloat.resize(size);
  ifloat=vfloat.begin();
  for_each(vfloat.begin(),vfloat.end(),rndm);
  vstop.push_back(clock());

  cout << "****** Phase 1: Math. operations on ordinary array" << endl;  

  // Add k to each element
  cout << "*** Adding " << k << " to each element " ;
  cout << "(10th element was: " << *(ifloat+10) ;
  vstart.push_back(clock());
  for (i=0; i<vfloat.size(); i++) { *(ifloat+i)+=k; }
  vstop.push_back(clock());
  cout << " now is: " << *(ifloat+10) << ")" << endl;


  // Multiply each element with k
  cout << "*** Multiplying each element with " << k ;
  cout << " (10th element was: " << *(ifloat+10) ;
  vstart.push_back(clock());
  for (i=0; i<vfloat.size(); i++) { *(ifloat+i)*=k; }
  vstop.push_back(clock());
  cout << " now is: " << *(ifloat+10) << ")"<< endl;

  // Divide each element by k
  cout << "*** Dividing each element by " << l ;
  cout << " (10th element was: " << *(ifloat+10) ;
  vstart.push_back(clock());
  for (i=0; i<vfloat.size(); i++) { *(ifloat+i)/=l; }
  vstop.push_back(clock());
  cout << " now is: " << *(ifloat+10) << ")" << endl;

  // Cos of each
  cout << "*** Calculate cos for each element "  ;
  cout << " (10th element was: " << *(ifloat+10) ;
  vstart.push_back(clock());
  for (i=0; i<vfloat.size(); i++) { *(ifloat+i)= cosf(*(ifloat+i)); }
  vstop.push_back(clock());
  cout << " now is: " << *(ifloat+10) << ")" << endl;

  for_each(vfloat.begin(),vfloat.end(),zerocheck);

  // Expand each element by itself
  cout << "*** Calculate element ^ element "  ;
  cout << " (10th element was: " << *(ifloat+10) ;
  vstart.push_back(clock());
  for (i=0; i<vfloat.size(); i++) { *(ifloat+i)= pow(*(ifloat+i),*(ifloat+i)); }
  vstop.push_back(clock());
  cout << " now is: " << *(ifloat+10) << ")" << endl;

  // log
  cout << "*** Calculate log of each element "  ;
  cout << " (10th element was: " << *(ifloat+10) ;
  vstart.push_back(clock());
  for (i=0; i<vfloat.size(); i++) { *(ifloat+i)= log(*(ifloat+i)); }
  vstop.push_back(clock());
  cout << " now is: " << *(ifloat+10) << ")" << endl;


  // Summary
  istartclock=vstart.begin(); istopclock=vstop.begin();
  cout << "****** Clock ticks for operations: " << endl;
  cout << right << fixed << setw(13) << duration(istartclock++,istopclock++) << " (random fill)" << endl;
  cout << right << fixed << setw(13) << duration(istartclock++,istopclock++) << " (add.)" << endl;
  cout << right << fixed << setw(13) << duration(istartclock++,istopclock++) << " (mult.)" << endl;
  cout << right << fixed << setw(13) << duration(istartclock++,istopclock++) << " (div.)" << endl;
  cout << right << fixed << setw(13) << duration(istartclock++,istopclock++) << " (cos)" << endl;
  cout << right << fixed << setw(13) << duration(istartclock++,istopclock++) << " (pow)" << endl;
  cout << right << fixed << setw(13) << duration(istartclock,istopclock) << " (log)" << endl;
  cout << right << fixed << setw(13) << *(vstop.rbegin())-*(vstart.begin()) << " (total) " << endl;


  p=vstart.size();
  // ======================= VALARRAY OPERATIONS =======================
  // fill valarray

  cout << "****** Phase 2: Math. operations on valarray" << endl;  
  vstart.push_back(clock());
  for (i=0;i<size;i++)
    {
      rndm(valfloat[i]);
    }
  vstop.push_back(clock());


  // Add k to each element
  cout << "*** Adding " << k << " to each element " ;
  cout << "(10th element was: " << valfloat[10] ;
  vstart.push_back(clock());
  valfloat+=k;
  vstop.push_back(clock());
  cout << " now is: " << valfloat[10] << ")" << endl;

  // Multiply
  cout << "*** Multiplying each element with " << k ;
  cout << "(10th element was: " << valfloat[10] ;
  vstart.push_back(clock());
  valfloat*=k;
  vstop.push_back(clock());
  cout << " now is: " << valfloat[10] << ")" << endl;

  // Divide
  cout << "*** Dividing each element by " << l ;
  cout << "(10th element was: " << valfloat[10] ;
  vstart.push_back(clock());
  valfloat/=l;
  vstop.push_back(clock());
  cout << " now is: " << valfloat[10] << ")" << endl;

  // Cosinus
  cout << "*** Calculate cos for each element "  ;
  cout << "(10th element was: " << valfloat[10] ;
  vstart.push_back(clock());
  valfloat=cos(valfloat);
  vstop.push_back(clock());
  cout << " now is: " << valfloat[10] << ")" << endl;


  for (i=0;i<size;i++)
    {
      zerocheck(valfloat[i]);
    }

  // Expand each element by itself
  cout << "*** Calculate element ^ element "  ;
  cout << "(10th element was: " << valfloat[10] ;
  vstart.push_back(clock());
  valfloat=pow(valfloat,valfloat);
  vstop.push_back(clock());
  cout << " now is: " << valfloat[10] << ")" << endl;

  // log
  cout << "*** Calculate log of each element "  ;
  cout << "(10th element was: " << valfloat[10] ;
  vstart.push_back(clock());
  valfloat=log(valfloat);
  vstop.push_back(clock());
  cout << " now is: " << valfloat[10] << ")" << endl;

  // Summary

  cout << "****** Clock ticks for operations: " << endl;
  istartclock=vstart.begin(); istopclock=vstop.begin();
  
  istartclock+=p; istopclock+=p;
  
  cout << right << fixed << setw(13) << duration(istartclock++,istopclock++)  << " (random fill)" << endl;
  cout << right << fixed << setw(13) << duration(istartclock++,istopclock++)  << " (add.)" << endl;
  cout << right << fixed << setw(13) << duration(istartclock++,istopclock++)  << " (mult.)" << endl;
  cout << right << fixed << setw(13) << duration(istartclock++,istopclock++)  << " (div.)" << endl;
  cout << right << fixed << setw(13) << duration(istartclock++,istopclock++)  << " (cos)" << endl;
  cout << right << fixed << setw(13) << duration(istartclock++,istopclock++)  << " (pow)" << endl;
  cout << right << fixed << setw(13) << duration(istartclock,istopclock)      << " (log)" << endl;
  cout << right << fixed << setw(13) << *(vstop.rbegin())-*(vstart.begin()+p) << " (total) " << endl;



}

void rndm(float& a)
{
  a=rand()%1000000;
  a/=(1000);
}

void zerocheck(float& a)
{
  if (a<0) { a*=-1; } 
}

double duration(
	      vector<clock_t>::iterator start, 
	      vector<clock_t>::iterator stop
	      )
{
  return difftime(*stop,*start) ;
}

Xlib - mouseClick

// Simula il click del mouse

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <unistd.h>

#include <X11/Xlib.h>
#include <X11/Xutil.h>

void mouseClick(int button)
{
	Display *display = XOpenDisplay(NULL);

	XEvent event;
	
	if(display == NULL)
	{
		fprintf(stderr, "Errore nell'apertura del Display !!!\n");
		exit(EXIT_FAILURE);
	}
	
	memset(&event, 0x00, sizeof(event));
	
	event.type = ButtonPress;
	event.xbutton.button = button;
	event.xbutton.same_screen = True;
	
	XQueryPointer(display, RootWindow(display, DefaultScreen(display)), &event.xbutton.root, &event.xbutton.window, &event.xbutton.x_root, &event.xbutton.y_root, &event.xbutton.x, &event.xbutton.y, &event.xbutton.state);
	
	event.xbutton.subwindow = event.xbutton.window;
	
	while(event.xbutton.subwindow)
	{
		event.xbutton.window = event.xbutton.subwindow;
		
		XQueryPointer(display, event.xbutton.window, &event.xbutton.root, &event.xbutton.subwindow, &event.xbutton.x_root, &event.xbutton.y_root, &event.xbutton.x, &event.xbutton.y, &event.xbutton.state);
	}
	
	if(XSendEvent(display, PointerWindow, True, 0xfff, &event) == 0) fprintf(stderr, "Errore nell'invio dell'evento !!!\n");
	
	XFlush(display);
	
	usleep(100000);
	
	event.type = ButtonRelease;
	event.xbutton.state = 0x100;
	
	if(XSendEvent(display, PointerWindow, True, 0xfff, &event) == 0) fprintf(stderr, "Errore nell'invio dell'evento !!!\n");
	
	XFlush(display);
	
	XCloseDisplay(display);
}


// gcc source.c -L /usr/X11R6/lib -lX11

C++ - Hello World

/*
 * 
 * Semplice esempio di Hello World !!!
 */

#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
	cout << "Hello World !!!" << endl; // endl equivale ad un \n
	
	return 0;
}

CPP SMTP Client

An SMTP client in CPP, apparently for a Linux machine. It was found in my old source code folder and so may not be fully working.


#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>

#define HELO "HELO\n"
#define DATA "DATA\n"
#define QUIT "QUIT\n"

FILE *fin;
int sock;
struct sockaddr_in server;
struct hostent *hp, *gethostbyname();
char buf[BUFSIZ+1];
int len;
char *host_id;
char *from_id;
char *to_id;
char *file_id;
char wkstr[100];

/*=====Send a string to the socket=====*/

send_socket(char *s)
{
	write(sock,s,strlen(s));
	write(1,s,strlen(s));
}

/*=====Read a string from the socket=====*/

read_socket()
{
	len = read(sock,buf,BUFSIZ);
	write(1,buf,len);
}

/*=====MAIN=====*/
int main(int argc, char* argv[])
{

if(argc != 5)
{
 printf("USAGE: %s <host> <from> <to> <filename>\n\n", argv[0]);
 exit(1);
}

host_id=argv[1];
from_id=argv[2];
to_id=argv[3];
file_id=argv[4];

/*=====Create Socket=====*/
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock==-1)
{
 perror("opening stream socket");
 exit(1);
}

/*=====Verify host=====*/
server.sin_family = AF_INET;
hp = gethostbyname(host_id);
if (hp==(struct hostent *) 0)
{
 fprintf(stderr, "%s: unknown host\n", host_id);
 exit(2);
}

/*=====Connect to port 25 on remote host=====*/
printf ("hostent %s\n", hp->h_addr_list[0]);
memcpy((char *) &server.sin_addr, (char *) hp->h_addr, hp->h_length);

server.sin_port=htons(25); /* SMTP PORT */

if (connect(sock, (struct sockaddr *) &server, sizeof server)==-1)
{
 perror("connecting stream socket");
 exit(1);
}

/*=====Write some data then read some =====*/

read_socket(); /* SMTP Server logon string */

send_socket(HELO); /* introduce ourselves */
read_socket(); /*Read reply */

send_socket("MAIL from: "); /* Mail from us */
send_socket(from_id);
send_socket("\n");
read_socket(); /* Sender OK */

send_socket("RCPT To: "); /*Mail to*/
send_socket(to_id);
send_socket("\n");
read_socket(); /*Recipient OK*/

send_socket(DATA);/*body to follow*/
read_socket(); /*ok to send */

fin=fopen(file_id, "r"); /* open file */
while(1)
{
 if(fgets(wkstr, 100, fin)==NULL) break; /* exit on EOF */
 send_socket(wkstr);
}
fclose(fin); /* close file */

send_socket(fin); /*send file*/
send_socket(".\n");

read_socket(); /* OK*/
send_socket(QUIT); /* quit */
read_socket(); /* log off */

/*=====Close socket and finish=====*/
close(sock);
exit(0);
}


CPP Web Crawler

Another program I found in my old source code directory. This looks like another web crawler designed to run in Windows.

// http.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream.h>
#include <winsock2.h>
#include <stdio.h>


#define MAX_LENGTH 4096


void main()
      {
          int s_len;
          int skt_Smtp;
          int success;
		  int i;
          struct sockaddr_in st_Sockaddr;
		  char                 recv_Buf[MAX_LENGTH];
          char send_Buf[MAX_LENGTH];

          //Initialize Sockets
          WSADATA wsa;
          WSAStartup(MAKEWORD(2, 0), &wsa);


          skt_Smtp = socket(AF_INET,SOCK_STREAM,0);
          if (skt_Smtp < 0)
          {
              cout<< "Error Creating Socket"<<endl;
              return;
          }
         else
         {
              st_Sockaddr.sin_family = AF_INET;
              st_Sockaddr.sin_port = htons(80);

             //Get the IP address and initialize the structure
             st_Sockaddr.sin_addr.s_addr = inet_addr("143.53.238.9");

             success = connect(skt_Smtp,(struct sockaddr *) &st_Sockaddr,sizeof(st_Sockaddr));

             //do stuff
             strcpy(send_Buf,"GET /internal/index.php HTTP/1.1\r\nHost: www.brad.ac.uk\r\n\r\n");

             s_len = send(skt_Smtp,send_Buf,strlen(send_Buf),0);
	do
	{
		i = recv(skt_Smtp, recv_Buf, MAX_LENGTH, 0);
		if(i < 0)
		{
			printf("recv() returned %d, errno=%d\n", i, errno);
			break;
		}
		if(i > MAX_LENGTH)
			i = MAX_LENGTH;
		printf("%-*.*s", i, i, recv_Buf);
	}
	while(i != 0);


         WSACleanup();
}
}

write STL container to output stream

//write all elements without any delimiter
copy (coll.begin(), coll.end(), ostream_iterator(cout));

reff : josutis, pg. 278

//with boost
for_each(coll