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 1-10 of 16 total  RSS 

Thread Process //Pascal class

A thread class to open processes on windows and retrieve its output (input isn't supported but it's easy to add).

unit Process;

interface

uses
  SysUtils, Windows, Classes, TLHelp32;

const
  INITIALIZATION_TIMEOUT = 10000;

type
  TStringArray = array of string;
  TProcessArray = array of Cardinal;
  TExceptionEvent = procedure(Sender: TObject; Exception: Exception) of object;
  EProcessError = class(Exception);

  TProcessThread = class(TThread)
  private
    FException: Exception;
    FWatching, FStarted, FSuspended: Boolean;
    FDirectory, FPath, FCommandLine, FEnvironment: PChar;
    FData: string;
    FOnProcessTerminated, FOnDataAvailable: TNotifyEvent;
    InputRead, InputWrite, OutputRead, OutputWrite: THandle;
    FMainProcess: PROCESS_INFORMATION;
    FOnException: TExceptionEvent;
    FOnProcessStarted: TNotifyEvent;
    function GetPriority: TThreadPriority;
    procedure SetPriority(const Value: TThreadPriority);
    procedure FreeResources;
  protected
    procedure CallDataAvailable; virtual;
    procedure CallProcessTerminated; virtual;
    procedure CallProcessOpened; virtual;
    procedure CallException; virtual;
    procedure Execute; override;
  public
    constructor Create(Path, CommandLine, Directory: string; Environment: TStrings = nil; Watch: Boolean = True);
    destructor Destroy; override;

    function IsProcessAlive: Boolean;
    procedure Resume;
    procedure Suspend;
    property OnDataAvailable: TNotifyEvent read FOnDataAvailable write FOnDataAvailable;
    property OnProcessTerminated: TNotifyEvent read FOnProcessTerminated write FOnProcessTerminated;
    property OnProcessStarted: TNotifyEvent read FOnProcessStarted write FOnProcessStarted;
    property OnException: TExceptionEvent read FOnException write FOnException;
    property Data: string read FData;
    property Process: PROCESS_INFORMATION read FMainProcess;
    property Priority: TThreadPriority read GetPriority write SetPriority;

  end;

  TProcessLineThread = class;
  TOnNewLineEvent = procedure(ProcessLine:  TProcessLineThread; const Line: string) of object;
  TProcessLineThread = class(TProcessThread)
  private
    FCurrentLine: string;
    FOnNewLine: TOnNewLineEvent;
    procedure DataAvailable(Sender: TObject);
    procedure Finished(Sender: TObject);
  public
    constructor Create(Path, CommandLine, Directory: string; Environment: TStrings = nil);
    property OnNewLine: TOnNewLineEvent read FOnNewLine write FOnNewLine;
  end;

function KillProcess(const Process: Cardinal): Boolean;
function GetChildrenProcesses(const Process: Cardinal; const IncludeParent: Boolean = True): TProcessArray;

implementation

const
  Priorities: array [TThreadPriority] of Integer =
   (THREAD_PRIORITY_IDLE, THREAD_PRIORITY_LOWEST, THREAD_PRIORITY_BELOW_NORMAL,
    THREAD_PRIORITY_NORMAL, THREAD_PRIORITY_ABOVE_NORMAL,
    THREAD_PRIORITY_HIGHEST, THREAD_PRIORITY_TIME_CRITICAL);

function GetChildrenProcesses(const Process: Cardinal; const IncludeParent: Boolean): TProcessArray;
var
  Snapshot: Cardinal;
  ProcessList: PROCESSENTRY32;
  Current: Integer;
begin
  Current := 0;
  SetLength(Result, 1);
  Result[0] := Process;
  repeat
    ProcessList.dwSize := SizeOf(PROCESSENTRY32);
    Snapshot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (Snapshot = INVALID_HANDLE_VALUE) or not Process32First(Snapshot, ProcessList) then
      Continue;
    repeat
      if ProcessList.th32ParentProcessID = Result[Current] then
      begin
        SetLength(Result, Length(Result) + 1);
        Result[Length(Result) - 1] := ProcessList.th32ProcessID;
      end;
    until Process32Next(Snapshot, ProcessList) = False;
    Inc(Current);
  until Current >= Length(Result);
  if not IncludeParent then
    Result := Copy(Result, 2, Length(Result));
end;

function KillProcess(const Process: Cardinal): Boolean;
var
  Handle: Cardinal;
  List: TProcessArray;
  I: Integer;
begin
  Result := True;
  List := GetChildrenProcesses(Process);
  for I := Length(List) - 1 downto 0 do
    if Result then
    begin
      Handle := OpenProcess(PROCESS_TERMINATE, false, List[I]);
      Result := (Handle <> 0) and TerminateProcess(Handle, 0) and CloseHandle(Handle);
    end;
end;

{ TProcessThread }

procedure TProcessThread.CallDataAvailable;
begin
  if Assigned(FOnDataAvailable) then
    FOnDataAvailable(Self);
end;

procedure TProcessThread.Resume;
var
  SuspendCount: Integer;
begin
  if FStarted then
  begin
    FStarted := True;
    SuspendCount := ResumeThread(FMainProcess.hThread);
    CheckThreadError(SuspendCount >= 0);
    if SuspendCount = 1 then
      FSuspended := False;
  end;
  inherited Resume;
end;

function TProcessThread.GetPriority: TThreadPriority;
begin
  if FStarted then
  begin
    CheckThreadError(GetThreadPriority(FMainProcess.hThread) <> THREAD_PRIORITY_ERROR_RETURN);
  end;
  Result := inherited Priority;
end;

function TProcessThread.IsProcessAlive: Boolean;
var
  Status: Cardinal;
begin
  GetExitCodeProcess(FMainProcess.hProcess, Status);
  Result := Status = STILL_ACTIVE;
end;

procedure TProcessThread.SetPriority(const Value: TThreadPriority);
begin
  if FStarted then
    CheckThreadError(SetThreadPriority(FMainProcess.hThread, Priorities[Value]));
  inherited Priority := Value;
end;

procedure TProcessThread.Suspend;
var
  OldSuspend: Boolean;
begin
  if FStarted then
  begin
    OldSuspend := FSuspended;
    try
      FSuspended := True;
      CheckThreadError(Integer(SuspendThread(FMainProcess.hThread)) >= 0);
    except
      FSuspended := OldSuspend;
      raise;
    end;
  end;
  inherited Suspend;
end;


procedure TProcessThread.CallException;
begin
  if Assigned(FOnException) then
    FOnException(Self, FException);
end;

procedure TProcessThread.CallProcessOpened;
begin
  if Assigned(FOnProcessStarted) then
    FOnProcessStarted(Self);
end;

procedure TProcessThread.CallProcessTerminated;
begin
  if Assigned(FOnProcessTerminated) then
    FOnProcessTerminated(Self);
end;

constructor TProcessThread.Create(Path, CommandLine, Directory: string; Environment: TStrings; Watch: Boolean);
var
  Len, I: Integer;
begin
  inherited Create(True);

  if (Length(CommandLine) > 0) and (Length(Path) > 0) then
    CommandLine := ' ' + CommandLine;

  if Length(Path) > 0 then
  begin
    GetMem(FPath, Length(Path) + 1);
    StrCopy(FPath, PChar(Path));
  end;
  if Length(CommandLine) > 0 then
  begin
    GetMem(FCommandLine, Length(CommandLine) + 1);
    StrCopy(FCommandLine, PChar(CommandLine));
  end;

  if Length(Directory) > 0 then
  begin
    GetMem(FDirectory, Length(Directory) + 1);
    StrCopy(FDirectory, PChar(Directory));
  end;

  FWatching := Watch;

  if Assigned(Environment) then
  begin
    GetMem(FEnvironment, 1);
    Len := 1;
    for I := 0 to Environment.Count - 1 do
    begin
      Inc(Len, Length(Environment[I]) + 1);
      ReallocMem(FEnvironment, Len);
      SetEnvironmentVariable(PChar(Environment.Names[I]), PChar(Environment.ValueFromIndex[I]));
      StrCopy(FEnvironment + Len - Length(Environment[I]) - 2, PChar(Environment[I]));
    end;
    (FEnvironment + Len - 1)^ := #0;
    FreeMem(FEnvironment);
    FEnvironment := nil;
  end;
end;

destructor TProcessThread.Destroy;
begin
  FreeMem(FPath);
  FreeMem(FCommandLine);
  FreeMem(FDirectory);
  FreeResources;
  if Assigned(FEnvironment) then
    FreeMem(FEnvironment);
  inherited;
end;

procedure TProcessThread.Execute;
const
  MAX_BUFFER = 512 * 1024;
var
  MaxBytes, Available, BytesRead: Cardinal;
  Buffer: array[0..MAX_BUFFER] of Char;

  function Read: Boolean;
  begin
    Result := True;
    FillChar(Buffer, MAX_BUFFER, #0);
    PeekNamedPipe(OutputRead, @Buffer, MAX_BUFFER, @BytesRead, @Available, nil);

    if BytesRead < MAX_BUFFER then
    begin
      MaxBytes := BytesRead;
    end
    else
      MaxBytes := MAX_BUFFER;

    if MaxBytes > 0 then
      if ReadFile(OutputRead, Buffer, MaxBytes, BytesRead, nil) then
      begin
        if BytesRead > 0 then
        begin
          FData := StrPas(Buffer);
          Synchronize(CallDataAvailable);
        end;
      end
      else
        Result := False;
  end;

var
  Startup: STARTUPINFO;
  SecurityDescriptor: SECURITY_DESCRIPTOR;
  SecurityAttributes: SECURITY_ATTRIBUTES;
begin
  try
    ZeroMemory(@Startup, SizeOf(STARTUPINFO));
    Startup.cb := SizeOf(STARTUPINFO);
    ZeroMemory(@SecurityDescriptor, SizeOf(SECURITY_DESCRIPTOR));
    ZeroMemory(@SecurityAttributes, SizeOf(SECURITY_ATTRIBUTES));
    InputRead := 0;
    InputWrite := 0;
    OutputRead := 0;
    OutputWrite := 0;

    if Win32Platform = VER_PLATFORM_WIN32_NT then
    begin
      InitializeSecurityDescriptor(@SecurityDescriptor, SECURITY_DESCRIPTOR_REVISION);
      SetSecurityDescriptorDacl(@SecurityDescriptor, True, nil, False);
      SecurityAttributes.lpSecurityDescriptor := @SecurityDescriptor;
    end
    else
      SecurityAttributes.lpSecurityDescriptor := nil;
    SecurityAttributes.nLength := SizeOf(SECURITY_ATTRIBUTES);
    SecurityAttributes.bInheritHandle := True;
    if not CreatePipe(OutputRead, OutputWrite, @SecurityAttributes, 0)
    or not CreatePipe(InputRead, InputWrite, @SecurityAttributes, 0) then
      raise EProcessError.Create('Error while opening pipes');

    SetHandleInformation(OutputRead, HANDLE_FLAG_INHERIT, 0);
    SetHandleInformation(InputWrite, HANDLE_FLAG_INHERIT, 0);

    GetStartupInfo(Startup);
    Startup.dwFlags := STARTF_USESHOWWINDOW OR STARTF_USESTDHANDLES;

    Startup.hStdOutput := OutputWrite;
    Startup.hStdError := OutputWrite;
    Startup.hStdInput := InputRead;

    FlushFileBuffers(OutputWrite);
    FlushFileBuffers(OutputRead);
    FlushFileBuffers(InputRead);
    FlushFileBuffers(InputWrite);

    Startup.wShowWindow := SW_HIDE;

    if not CreateProcess(FPath, FCommandLine, nil, nil, True, CREATE_NEW_CONSOLE OR NORMAL_PRIORITY_CLASS, FEnvironment, FDirectory, Startup, FMainProcess) then
      raise EProcessError.Create('Error while starting Process: ' + SysErrorMessage(GetLastError) + ':' + FPath + ':' + FCommandLine + ':' + FDirectory);
    WaitForInputIdle(FMainProcess.hProcess, INITIALIZATION_TIMEOUT);
    FStarted := True;
    SetPriority(GetPriority);
    Synchronize(CallProcessOpened);
    
    if not FWatching then
      Exit;

    repeat
      if not Read then
        Break;
    until not IsProcessAlive or Terminated;
    Read;

    if not IsProcessAlive then
      Synchronize(CallProcessTerminated);
      
  except
    on E: Exception do
    begin
      FException := E;
      Synchronize(CallException);
    end;
  end;
end;

procedure TProcessThread.FreeResources;
begin
  KillProcess(FMainProcess.dwProcessId);

  if OutputRead <> 0 then
  begin
    CloseHandle(OutputRead);
    OutputRead := 0;
  end;
  if OutputWrite <> 0 then
  begin
    CloseHandle(OutputWrite);
    OutputWrite := 0;
  end;
  if InputWrite <> 0 then
  begin
    CloseHandle(InputWrite);
    InputWrite := 0;
  end;
  if InputRead <> 0 then
  begin
    CloseHandle(InputRead);
    InputRead := 0;
  end;
end;

{  TProcessLineThread }

constructor  TProcessLineThread.Create(Path, CommandLine, Directory: string; Environment: TStrings);
begin
  inherited Create(Path, CommandLine, Directory, Environment);
  OnDataAvailable := DataAvailable;
  OnTerminate := Finished;
end;

procedure  TProcessLineThread.DataAvailable(Sender: TObject);
var
  I, L: Integer;
begin
  I := 0;
  L := Length(Data);
  while I < L do
  begin
    Inc(I);
    if Data[I] in [#13, #10] then
    begin
      if (I < L) and (Data[I+1] in [#13, #10]) then
        Inc(I);
      if Assigned(FOnNewLine) then
        FOnNewLine(Self, FCurrentLine);
      FCurrentLine := '';
    end
    else
      FCurrentLine := FCurrentLine + Data[I];
  end;
end;

procedure  TProcessLineThread.Finished(Sender: TObject);
begin
  if (FCurrentLine <> '') and Assigned(FOnNewLine) then
    FOnNewLine(Self, FCurrentLine);
end;

end.

VMWare Fusion disk resize

// resize wmvare fusion disk image

cd /Users/vvlad/Documents/Virtual Machines.localized/Windows XP Professional.vmwarevm
/Applications/VMware\ Fusion.app/Contents/MacOS/diskTool -X 5Gb Windows\ XP\ Professional.vmdk 


// then you need run some windows part manager - to resize partition to use newly available disk space

Twitter and Jaiku from the command line

The following instructions make it easy to post to Twitter and Jaiku from the command line. The instructions were copied from the article "Ubuntu Unleashed: Howto Twitter From the Command Line in Ubuntu!" [ubuntu-unleashed.com] and modified to post via Rorbuilder's ProjectX API.

sudo apt-get install curl

sudo gedit /usr/bin/jaitwit

Now Paste this in gEdit and simply replace "YourUsername" with your username and "YourPassword" with your twitter passwd, then replace the Jaiku variables (YourUsername, YourPassword, YourCity, YourAccessKey) and ctrl-s to save, then alt-F4 to exit!
curl http://rorbuilder.info/api/projectx.cgi?xml_project=%3Cproject%20name=%22micro_blog%22%3E%3Cmethods%3E%3Cmethod%20name=%22post2jaiku%22%3E%3Cparams%3E%3Cparam%20var=%22user%22%20val=%22YourUsername%22/%3E%3Cparam%20var=%22msg%22%20val=%22`echo $@|tr ' ' '+'`%22/%3E%3Cparam%20var=%22location%22%20val=%22YourCity%22/%3E%3Cparam%20var=%22apikey%22%20val=%22YourAccessKey%22/%3E%3C/params%3E%3C/method%3E%3Cmethod%20name=%22post2twitter%22%3E%3Cparams%3E%3Cparam%20var=%22user%22%20val=%22YourUsername%22/%3E%3Cparam%20var=%22msg%22%20val=%22`echo $@|tr ' ' '+'`%22/%3E%3Cparam%20var=%22password%22%20val=%22YourPassword%22/%3E%3C/params%3E%3C/method%3E%3C/methods%3E%3C/project%3E -o /dev/null
echo Message Sent!

Then chmod for exec privileges:
chmod +x /usr/bin/jaitwit

Then from the CLI type jaitwit followed by your message.
jaitwit "message here without the quotes"

Simple way to check command line arguments in a C program

A simple way to check command line arguments.

Author: Joana Matos Fonseca da Trindade
Date: 2008.02.25

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

/* minimum required number of parameters */
#define MIN_REQUIRED 2

/* display usage */
int help() {
   printf("Usage: myprogram [-s <arg0>] [-n <arg1>] [-true]\n");
   printf("\t-s: a string a\n");
   printf("\t-n: a number\n");
   printf("\t-true: a single parameter\n");

   return 1;
}

/* main */
int main(int argc, char *argv[]) {
   if (argc < MIN_REQUIRED) {
      return help();
   }
   int i;

   /* iterate over all arguments */
   for (i = 1; i < (argc - 1); i++) {
       if (strcmp("-s", argv[i]) == 0) {
          /* do something with it */ 
          printf("string = %s\n", argv[++i]);
          continue;
       }
       if (strcmp("-n", argv[i]) == 0) {
          /* do something with it. for example, convert it to an integer */
          printf("number = %i\n", atoi(argv[++i]));
          continue;
       }
       if (strcmp("-true", argv[i]) == 0) {
          printf("true activated\n");
          continue;
       }
       return help();
   }
   return 0;
}

ARGV Parser

This function parse ARGV and return a string.
See exemples for more informations :

// Go : http://blackh.badfile.net/wordz/

Function :

  def options(param)
  
	i = 0
		ARGV.each  { |valeur|
		
    		if (valeur == '-' + param.to_s)
				return ARGV[i+1]
			elseif (valeur != '-' + param.to_s)
				return false
			end
		i += 1
		}
		
   end


Usage :

// cmd> ruby test.rb -o foo

	out =  self.options('o')

	if (out != false and out.empty? == false)
                   puts out # print -> foo
	end

Using Ruby to delete a file directory

In this example the file we want to delete is a non-empty directory called sample.
  require 'fileutils' 

  FileUtils.rm_r 'sample'

Install vmware tools on ubuntu

Install vmware tools tar file on ubuntu from http://www.howtogeek.com/howto/ubuntu/install-vmware-tools-on-ubuntu-edgy-eft/
The first thing that is important is that you will need to know is
that you have to install the compilation utilities, which aren't
installed by default. Run these commands to get you started:

sudo apt-get install build-essential
sudo apt-get install linux-headers-`uname -r`


Now you'll want to navigate to the VM \ Install VMware Tools menu:

cp /cdrom/*.gz /tmp/
cd /tmp
tar xvzf VM*.gz
cd vmware*
sudo ./vmware-install.pl

Parsing simple command line arguments in java, using the the Commons CLI library.

// Skeleton to read in two command line arguments, one mandatory, one optional

package snippets;

import org.apache.commons.cli.*;

/* 
 * Stub program that reads command line arguments
 */
public class CommandLineProgram {

	private static Options options = null; // Command line options
	
	private static final String PROPERTIES_LOCATION_OPTION = "f";
	private static final String OUTPUT_FILE_OPTION = "o";
	private static final String DEFAULT_OUTPUT_FILE = "out.feed";
	
	private CommandLine cmd = null; // Command Line arguments
	
	private String outputFile = DEFAULT_OUTPUT_FILE;
	
	static{
		options = new Options();
		options.addOption(PROPERTIES_LOCATION_OPTION, true, 
				"Data file location");
		options.addOption(OUTPUT_FILE_OPTION, false, "Output file. " + DEFAULT_OUTPUT_FILE + " by default ");
		
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		CommandLineProgram cliProg = new CommandLineProgram();
		cliProg.loadArgs(args);
	}
	
	/**
	 * Validate and set command line arguments.
	 * Exit after printing usage if anything is astray
	 * @param args String[] args as featured in public static void main()
	 */
	private void loadArgs(String[] args){
		CommandLineParser parser = new PosixParser();
		try {
			cmd = parser.parse(options, args);
		} catch (ParseException e) {
			System.err.println("Error parsing arguments");
			e.printStackTrace();
			System.exit(1);
		}
		
		// Check for mandatory args
		
		if (! cmd.hasOption(PROPERTIES_LOCATION_OPTION)){
			HelpFormatter formatter = new HelpFormatter();
			formatter.printHelp("java -jar this_jar.jar", options);
			System.exit(1);
		}
		
		// Look for optional args.
		
		if (cmd.hasOption(OUTPUT_FILE_OPTION)){
			outputFile = cmd.getOptionValue(OUTPUT_FILE_OPTION);
			
		}
	}
}

Linux - command ls without color

// Elimina tutti i caratteri speciali che portano il colore

ls --color=never

yubnub.py

#!/usr/bin/env python

__author__="Andrew Pennebaker (andrew.pennebaker@gmail.com)"
__date__="9 Dec 2006 - 10 Dec 2006"
__copyright__="Copyright 2006 Andrew Pennebaker"
__license__="GPL"
__version__="0.0.1"
__credits__="Based on Yubnub for Windows (http://www.opbarnes.com/blog/Programming/OPB/Utilities/yubnub.html)"
__URL__="http://snippets.dzone.com/posts/show/3120"

from html2txt import html2txt

import webbrowser
from urllib import urlopen
import re

import sys
from getopt import getopt

PARSER="http://yubnub.org/parser/parse?command="

BROWSER_MODE="BROWSER"
PLAIN_MODE="PLAIN"

def space2plus(s):
	return "+".join(s.split())

def yubnub(command=""):
	global PARSER

	return PARSER+space2plus(command)

def yubnubBrowser(command):
	return webbrowser.open(yubnub(command))

def cleanHTML(html):
	h=html2txt()
	h.feed(html)
	h.close()

	return h.output()

def yubnubPlain(command, clean=True):
	command=yubnub(command)

	try:
		url=urlopen(command)
		lines=url.readlines()
		url.close()

		lines="".join(lines)

		if clean:
			return cleanHTML(lines)

		return lines

	except IOError, e:
		return "Error connecting to "+command

def usage():
	print "Usage: "+sys.argv[0]+" [options] <command>"
	print "-b --browser"
	print "\n--plain (default)"
	print "\t-c --clean (default)"
	print "\t-d --dirty"
	print "\n--parser <parser> (experimental)"
	print "\n-h --help"

	sys.exit()

def main():
	global PARSER

	global BROWSER_MODE
	global PLAIN_MODE

	mode=PLAIN_MODE
	parser=PARSER
	clean=True

	systemArgs=sys.argv[1:]
	optlist, args=[], []
	try:
		optlist, args=getopt(systemArgs, "bhcd", ["browser", "plain", "clean", "dirty", "parser=", "help"])
	except:
		usage()

	for option, value in optlist:
		if option=="-h" or option=="--help":
			usage()

		elif option=="-b" or option=="--browser":
			mode=BROWSER_MODE
		elif option=="--plain":
			mode=PLAIN_MODE
		elif option=="-c" or option=="--clean":
			clean=True
		elif option=="-d" or option=="--dirty":
			clean=False
		elif option=="--parser":
			parser=value

	command=" ".join(args)

	if mode==BROWSER_MODE:
		yubnubBrowser(command)
	elif mode==PLAIN_MODE:
		for line in yubnubPlain(command, clean):
			sys.stdout.write(line)
		print ""

if __name__=="__main__":
	main()