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

About this user

Sascha Tayefeh http://www.tayefeh.de

« Newer Snippets
Older Snippets »
Showing 1-10 of 36 total  RSS 

Pretty Print All Header and C++ files in a directory

#!/bin/sh -

echo 'Pretty Print Script v0.2 by s tayefeh (2004)'
echo 'collects all .C .cc .cpp and .h from a ./.'
echo 'and create a PRETTY_C.ps file with the C-sources'
echo 'and a PRETTY_h.ps file with the header-sources'

ls -lq *.C *.cc *.cpp \
        | awk '{printf "%s ", $8}' \
        > clist.temp

ls -lq *.h \
        | awk '{printf "%s ", $8}' \
        > hlist.temp

a2ps --prologue=color -Ec++ -o PRETTY_C.ps \
`cat clist.temp` $1 $2 $3 $4

a2ps --prologue=color -Ec++ -o PRETTY_h.ps \
`cat hlist.temp` $1 $2 $3 $4

rm hlist.temp clist.temp

Trivial AWT-only Event Handling

------------------------------------------------------------
1. Main Class
------------------------------------------------------------

class Main {

        public static void main(final String[] args) {
                MainFrameCommand cmd = new MainFrameCommand();
                MainFrameGUI gui = new MainFrameGUI(cmd);
        }

}

------------------------------------------------------------
2. MainFrameCommand Class
------------------------------------------------------------
import java.awt.*;
import java.awt.event.*;

class MainFrameCommand
implements KeyListener, MouseMotionListener, WindowListener {

        /* Key Listener */
        public void keyPressed(KeyEvent event) {}
        public void keyReleased(KeyEvent event) {}
        public void keyTyped(KeyEvent event) {}

        /* MouseMotion Listener */
        public void mouseMoved(MouseEvent event) {}
        public void mouseDragged(MouseEvent event) {}

        /* WindowListener */
        public void windowClosed(WindowEvent event) {}
        public void windowOpened(WindowEvent event) {}
        public void windowClosing(WindowEvent event) {}
        public void windowActivated(WindowEvent event) {}
        public void windowDeactivated(WindowEvent event) {}
        public void windowIconified(WindowEvent event) {}
        public void windowDeiconified(WindowEvent event) {}

}


------------------------------------------------------------
3. MainFrameGUI Class
------------------------------------------------------------

import java.awt.*;
import java.awt.event.*;

class MainFrameGUI extends Frame {
                public MainFrameGUI(MainFrameCommand cmd) {
                super("Window");
                setSize(300, 300);
                setVisible(true);


                addKeyListener(cmd);
                addWindowListener(cmd);
                addMouseMotionListener(cmd);
        }

        public void paint(Graphics g) {}
} 

Blacklist String Validator Class

Check string for forbidden stuff. The constructur needs one single string argument, that contains the URI to the blacklist.txt file. This list contains one word per line of words that must not occur in the string to validate.

<?php
   /*
   CheckContent
   (c) 2007 by S TAYEFEH

   Check string for forbidden stuff.
   The constructur needs one single string argument, 
   that contains the URI to the blacklist.txt file. 
   This list contains one word per line of words that 
   must not occur in the string to validate.

   Example use:

      require_once "CheckContent.php";
      $val = new CheckContent("pbblacklist.txt");
      if ($val->validate("blabla")) echo "ok";
      else echo "failed";

   */

   class CheckContent
   {
      public $blacklistFN; // The textfile with the list of prohibited expressions
      public $content="";  // The content to check - A single string
      private $blacklistA=array();
      private $isValid=TRUE;

      // constructor
      public function CheckContent($blacklist)
      {
	 $this->isValid=TRUE;
	 $this->blacklistFN=$blacklist;
	 $this->content="EMPTY";
      }

      // Main Method
      public function validate($content)
      {
	 $this->content=$content;
	 if(!$this->readFile()) return FALSE;

	 foreach ($this->blacklistA as $a)
	 {
	    if(preg_match('/'.$a.'/i',$content)) $this->isValid=FALSE;
	 }
	 return $this->isValid;
      }

      // Read File
      private function readFile()
      {
	 $blacklistTemp=array();
	 $blacklistS=FALSE;
	 $blacklistS=file_get_contents($this->blacklistFN);
	 if (!$blacklistS) 
	  {
	     echo "*** ERROR from CheckContent:: - Could not read blacklist file: ".$this->blacklistFN;
	     return FALSE;
	  }
	 $blacklistTemp=explode("\n",$blacklistS);
	 // Clean array
	 $this->blacklistA=array();
	 // Only lines that contain letters or digits
	 foreach ($blacklistTemp as $a) if( ereg("[a-zA-Z0-9]",$a) ) array_push($this->blacklistA,trim($a));
	 sort($this->blacklistA); // Cosmetic ;-)
	 return TRUE;
      }
   }


Read File Linewise with Java


Here's the class

import java.io.*;

public class MyIO {
	void printFile(String fileName) {
		BufferedReader rd;
		String line;

		try {
			rd = new BufferedReader(new FileReader(fileName));
						
			while ((line =  rd.readLine()  ) != null) {
				System.out.println(line);
			}
			rd.close();
		} catch (final IOException e) {
			System.out.println("Error reading file");
		}

	}

}



All along with an example usage:

	MyIO myIO = new MyIO();
	myIO.printFile("filename.txt");

Using java.io.File object

Using java.io.File object

import java.io.*;

class Main {
	static String filename = new String("/home/sascha/temp/changes.xml");	
	
	public static void main(String[] args) {
		File fileObject;
		System.out.println("Reading File: " + filename);

		fileObject = new File(filename);
		
		System.out.println("Filename: " + fileObject.getName());
		System.out.println("Length: " + (fileObject.length()) + "bytes");
		System.out.println("Last modified timesptamp: " + fileObject.lastModified());
	}

}

Create DLL with C# (C-sharp)


HowTo create a dynamically linked library (DLL) with C# (C-sharp) and
Visual Studio 2005.

HowTo create a dynamically linked library (DLL) with C# (C-sharp) and
Visual Studio 2005.

1. Creating the DLL:

a) Create a new project -> C# Classlibrary.

b) Create your class adding or modifying
a class-file to the project and entering
something like:
		using System;
		using System.Collections.Generic;
		using System.Text;

		namespace MyClassLib
		{
		    public class ClassA
		    {
			public int PropA = 10;

			public void Multiply()
			{
			    PropA *= 2;
			}

			public void Multiply(Int32 myFactor)
			{
			    PropA *= myFactor;
			}

		    }
	  


2. Test-bind the DLL

a) Create another project WITHOUT closing or deleting the old project.
(This is done by right-clicking on the Project-Explorer and
choosing Add->New Project)

b) The new project needs to now about the DLL. The terminology is
different from that of C++. Here, we talk about "references" instead
of links. Thus, we have to add the DLL to the reference tree of the
new project in the project-explorer. Rightclick on your
new project->add reference->choose tab:Project and add.

c) To make life easier, use the namespace of your dll. Your
main code could look something like this:

	   
	   using System;
	   using System.Collections.Generic;
	   using System.Text;
	   using MyClassLib;
	   
	   namespace ConsoleApplication1
	   {
	       class Program
	       {
	           static void Main(string[] args)
	           {
	               ClassA obj = new ClassA();
	               obj.PropA = 9;
	               obj.Multiply(9);
	               Console.WriteLine(obj.PropA);
	               Console.ReadLine();
	           }
	       }
	   }
	   


Remember: The force is with you!


Most elementary Win-API "Hello, 'ere I am' code

This does nothing but opening a window for 5 seconds. No MFC, no C#, no resources, no whatsoever...

#include<windows.h> 
#include<tchar.h>

HWND NewWindow(
			   LPCTSTR str_Title,
			   int int_XPos, 
			   int int_YPos, 
			   int int_Width, 
			   int int_Height);

LRESULT CALLBACK OurWindowProcedure(
									HWND han_Wind,
									UINT uint_Message,
									WPARAM parameter1,
									LPARAM parameter2);

int WINAPI WinMain(
				   HINSTANCE hInstance,
				   HINSTANCE hPreviousInstance,
				   LPSTR lpcmdline,
				   int nCmdShow
				   )
	{
	HWND han_Window = NewWindow(_T("DirectX C++ Tutorial"),100,100,500,500);
	Sleep(5000);
	DestroyWindow(han_Window);
	return 0;
	}


HWND NewWindow(
			   LPCTSTR str_Title,
			   int int_XPos, 
			   int int_YPos, 
			   int int_Width, 
			   int int_Height)
	{

	WNDCLASSEX wnd_Structure;

	wnd_Structure.cbSize = sizeof(WNDCLASSEX);
	wnd_Structure.style = CS_HREDRAW | CS_VREDRAW;
	wnd_Structure.lpfnWndProc = OurWindowProcedure;
	wnd_Structure.cbClsExtra = 0;
	wnd_Structure.cbWndExtra = 0;
	wnd_Structure.hInstance = GetModuleHandle(NULL);
	wnd_Structure.hIcon = NULL;
	wnd_Structure.hCursor = NULL;
	wnd_Structure.hbrBackground = GetSysColorBrush(COLOR_BTNFACE);
	wnd_Structure.lpszMenuName = NULL;
	wnd_Structure.lpszClassName = _T("WindowClassName");
	wnd_Structure.hIconSm = LoadIcon(NULL,IDI_APPLICATION);

	RegisterClassEx(&wnd_Structure);

	return CreateWindowEx(
		WS_EX_CONTROLPARENT, 
		_T("WindowClassName"), 
		str_Title, WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_VISIBLE,
		int_XPos, 
		int_YPos, 
		int_Width, 
		int_Height, 
		NULL, 
		NULL, 
		GetModuleHandle(NULL),
		NULL);
	}

LRESULT CALLBACK OurWindowProcedure(HWND han_Wind,UINT uint_Message,WPARAM parameter1,LPARAM parameter2)
	{
	return DefWindowProc(han_Wind,uint_Message,parameter1,parameter2);
	}


logmem.sh


continuously prints active memory from /proc/meminfo
if fileentries exceed MAXENTRIES, then file is bzipped

#!/bin/sh
# logmem.sh
# 2007 by Sascha Tayefeh
# continuously prints active memory from /proc/meminfo
# if fileentries exceed MAXENTRIES, then file is bzipped
# created for SUSE 10.2 
# some adaptions may be needed for use with other linuxes
#
# usage (OPTIONS ORDER IS CRUTIAL!!!):
# nohup /usr/bin/nice -n 19 logmem.sh [logfile.log] [maximum entries per logfile ] [logging interval in seconds]  &
#
# example:
# nohup /usr/bin/nice -n 19 logmem.sh mem.log 1747626 10  &
# nohup /usr/bin/nice -n 19 ~/src/sh/logmem.sh /tmp/mem.log 1747626 1 >& /tmp/logmem.sh.log &
# 
# to merge archived files do something like this:
#
# bunzip2 *.bz2
# rm -f mem.merged.log 
# find . -name "mem*" -exec cat {} >> mem.merged.log \;
#
# to CUT by TIME:
# cut -c9-29 mem.log
#


# Maximum number of entries per logfile
# When exeeded, file will be archived 

pathToBzip="/usr/bin/bzip2"

currentdir=`pwd`
unamestring=`uname -a`
hostname=$HOST
pid=`ps -d | grep logmem | awk '{print $1}'`


echo "********************"
echo logmem.sh 2007 by ST
echo "********************"
echo "unamestring: $unamestring"
echo "host: $hostname"
echo "user: $USER"
echo "date: `date`"
echo "logmem.sh PID: $pid"

if [ $# -lt 3 ];
then
   echo
   echo "******** ERROR: Too few arguments ********"
   echo "******** I need to have EXACTLY 3 arguments !!! ***********"
   echo
   echo  "usage (OPTIONS ORDER IS CRUTIAL!!!):"
   echo  "nohup /usr/bin/nice -n 19 logmem.sh [logfile.log] [maximum entries per logfile ] [logging interval in seconds]  &"
   echo 
   echo  "example:"
   echo  "nohup /usr/bin/nice -n 19 logmem.sh mem.log 1747626 10  &"
   echo 'nohup /usr/bin/nice -n 19 ~/src/sh/logmem.sh /tmp/mem.log 1747626 1 >& /tmp/logmem.sh.log &'

   echo 
   exit
else
   let interval=$3
   let MAXENTRIES=$2
   logfile=$1
fi

rm -f $logfile
echo "logfile: $logfile"
echo "loginterval: $interval"
echo "syntax of logfile: [timestamp] [active mem] [active swap]"
echo
echo "to merge archived files do something like this:"
echo 
echo " bunzip2 *.bz2"
echo " rm -f mem.merged.log "
echo " find . -name 'mem*' -exec cat {} >> mem.merged.log \;"
echo 
echo "logging started until aborted by KILL or something..."
echo 

let count=0

# enter endless loop
while [ 0 ];
do
   # get properties
   let mem=`grep "Active" /proc/meminfo | awk '{print $2}'`
   let swapTot=`grep "SwapTotal" /proc/meminfo | awk '{print $2}'`
   let swapFree=`grep "SwapFree" /proc/meminfo | awk '{print $2}'`
   let swapUsed=$swapTot-$swapFree
   datestr=`date +'%Y%m%d %H%M%S'`

   # log top file
   echo "$datestr $mem $swapUsed " >> $logfile

   # Achive file?
   if [ $count -ge $MAXENTRIES ];
   then
      let count=0
      $pathToBzip  -f -q -9 $logfile
      mv "$logfile.bz2" "$logfile.$datestr.bz2"
   fi

   # fall asleep
   sleep $interval

   let count=$count+1
done



Count the appearence of certain chars

Count the appearence of certain chars using regular expression query and
using perl's string-operator

#!/usr/bin/perl
# Count the appearence of certain chars using regular expression query
#


$string="MNVDPFSPHSSDSFAQAASPARKPPRGGRRIWSGTREVIAYGMPASVWRDLYYWALKVSWPVFFASLAALFVVNNTLFALLYQLGDAPIANQSPPGFVGAFFFSVETLATVGYGDMHPQTVYAHAIATLEIFVGMSGIALSTGLVFARFARPRAKIMFARHAIVRPFNGRMTLMVRAANARQNVIAEARAKMRLMRREHSSEGYSLMKIHDLKLVRNEHPIFLLGWNMMHVIDESSPLFGETPESLAEGRAMLLVMIEGSDETTAQVMQARHAWEHDDIRWHHRYVDLMSDVDGMTHIDYTRFNDTEPVEPPGAAPDAQAFAAKPGEGDARPV";

$neg = ($string =~ tr/[DE]//);
$pos = ($string =~ tr/[RK]//);
$his = ($string =~ tr/[H]//);
$total = $pos+$his-$neg;
$totalNoHis = $pos-$neg;

print "NEG = $neg ; POS = $pos ; HIS = $his; TOT = $total (without HIS = $totalNoHis)\n";

SocketJpeg

<?
/*
 socketJpeg.php
 2007 by Sascha Tayefeh

 This script
 1. Opens a socket to a server
 2. Sends a GET-request
 3. Reads the header
 4. Sends a jpeg-header to your browser
 5. Sends the jpeg to your server

*/

$server="www.ilenvo.de";
$pic ="/kunden/sascha/pb/blog/1170195444-viper.jpg";

$fp = fsockopen($server, 80, $errno, $errstr, 30);
if (!$fp) {
   echo "$errstr ($errno)<br />\n";
} else {
   $out = "GET $pic HTTP/1.1\r\n";
   $out .= "Host: $server\r\n";
   $out .= "Connection: Close\r\n\r\n";

   fwrite($fp, $out);
   $img="";
   $fill=0;
   while (!feof($fp)) {
      /*

      $buffer = fgets($fp, 1024);
      echo strlen($buffer)." - ".$buffer;
      echo "<br>";
      */

      /* Comment this for printing the header */
      if($fill==0) 
      { 
	 $buffer = fgets($fp, 1024);
	 if (strlen($buffer)==2) $fill=1;
      } else if($fill==1)
      {
	 $img.=fgets($fp, 1096); 
      }
      /**/
   }
   fclose($fp);

   $len=strlen($img);
   header('Content-type: image/jpeg');
   header("Content-Length: $len");
   echo $img;

}


?>

« Newer Snippets
Older Snippets »
Showing 1-10 of 36 total  RSS