Saturday, November 7, 2009

Jacobi Method example

I wrote this code a while back. Apparently, this post is getting a few hits. I refined it a bit. Also wanted to make sure it was looked right.

What is the Jacobi method? It's an iterative way of solving a system of equations. Ax = b. This is learned in Numerical Analysis classes.

Generally, you decompose a matrix into its diagonal and lower and upper triangles. Such that,

A = D + L + U

x0 is the initial guess.

Now you want to solve for x. x_approx = inverse of D * (b - (L+U)x0)

Get x_approx from this formula, then plug it into x0 and do it all over again until you reach the desired error.



% Code is for matlab / octave
format long e;
A = [ 2 -1; -1 2];
b = [ 2; 1];
k = 20;
xi = [0;0]; % initial guess

%we want
%x' = Dinv(b - (L+U)x)

% just take the diagonal of A
D=[A(1,1) 0;0 A(2,2)];

Di=inv(D);

%lower and upper triangles of A
L=[0 0; -A(2,1) 0];
U=[0 -A(1, 2); 0 0];

% this part doesn't change, so calc now
C=Di*b;
% this is the main term of the algo
M=Di*(L+U);

x = [5/3; 4/3]; % solution

abs_err = [ 100 ; 100];
abs_err = abs_err - x;
i=0;

%stop until error is <= 1e-6
while abs_err(1) >= 1e-6 && abs_err(2) >= 1e-6
xi=M*xi+C
abs_err = abs(xi - x);
fprintf('i = %f abs-err = %f %f \n',i,abs_err(1),abs_err(2));
i=i+1;
end


Friday, November 6, 2009

matlab : polynomial fitting



octave-3.2.3:4> for i = 1 : 51
> x(i) = .2*(i - 1);
> end


octave-3.2.3:6> for i = 1: 51
> y(i) = 1 - x(i);
> end

octave-3.2.3:8> polyfit(x,y,4)
ans =

1.1249e-17 -2.3654e-16 1.7285e-15 -1.0000e+00 1.0000e+00

Wednesday, November 4, 2009

Java : sample applet






import java.applet.*;
import java.awt.*;

public class A extends Applet
{
private int w, h;
public void init( )
{
w = 45;
h = 50;
}

public void paint(Graphics g)
{
g.drawRect(w, h, 20, 80);
}
}


Sample J2Me Midlet for sound recording



import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.media.*;
import javax.microedition.media.control.*;

public class VoiceRecordMidlet extends MIDlet {
private Display display;

public void startApp() {
display = Display.getDisplay(this);
display.setCurrent(new VoiceRecordForm());
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
notifyDestroyed();
}
}

class VoiceRecordForm extends Form implements CommandListener {
private StringItem message;
private StringItem errormessage;
private final Command record, play;
private Player player;
private byte[] recordedAudioArray = null;
public VoiceRecordForm() {
super("Recording Audio");
message = new StringItem("", "Select Record to start recording.");
this.append(message);
errormessage = new StringItem("", "");
this.append(errormessage);
record = new Command("Record", Command.OK, 0);
this.addCommand(record);
play = new Command("Play", Command.BACK, 0);
this.addCommand(play);
this.setCommandListener(this);
}
public void commandAction(Command comm, Displayable disp) {
if (comm == record) {
Thread t = new Thread() {
public void run() {
try {
player = Manager.createPlayer("capture://audio?encoding=pcm");
player.realize();
RecordControl rc = (RecordControl) player.getControl("RecordControl");
ByteArrayOutputStream output = new ByteArrayOutputStream();
rc.setRecordStream(output);
rc.startRecord();
player.start();
message.setText("Recording...");
Thread.sleep(5000);
message.setText("Recording Done!");
rc.commit();
recordedAudioArray = output.toByteArray();
player.close();
} catch (Exception e) {
errormessage.setLabel("Error");
errormessage.setText(e.toString());
}
}
};
t.start();

}
else if (comm == play) {
try {
ByteArrayInputStream recordedInputStream = new ByteArrayInputStream(recordedAudioArray);
Player p2 = Manager.createPlayer(recordedInputStream, "audio/basic");
p2.prefetch();
p2.start();
} catch (Exception e) {
errormessage.setLabel("Error");
errormessage.setText(e.toString());
}
}
}
}

Friday, October 30, 2009

Matlab polynomial basics: roots, derivative of polynomial, evaluate polynomial



%Get roots of function

octave-3.2.3:13> A = [1 -3 3 -1]
A =

1 -3 3 -1

octave-3.2.3:14> roots(A)
ans =

1.00001 + 0.00000i
1.00000 + 0.00001i
1.00000 - 0.00001i

%get derivative of polynomial

octave-3.2.3:18> A
A =

1 -2 1

octave-3.2.3:19> polyder(A)
ans =

2 -2


%evaluate polynomial using matrix notation

polyval(A,1)
ans = 0
octave-3.2.3:21> polyval(A,2)
ans = 1

Sunday, October 11, 2009

matlab : example program to find extreme points of lp problem



format compact;
A=[2 1 1 1 0 0; 1 -2 1 0 1 0; 1 1 0 0 0 1];

b = [ 10; 8; 3];
c= [-1 1 1 0 0 0];

n = 3;
m = 3;

i = 1;
while i <= n+1
j = i+1;
while j < n+m
k=j+1;
while k <=n+m
B=[A(:,[i j k]) b];
B=rref(B);
temp = [ 0 ; 0 ; 0; 0; 0; 0];
x = B(:,[n+1]);
fprintf(1,'***Is feasible __ ***');
fprintf(1,'i=%d,j=%d,k=%d \n',i,j,k);
temp(i) = x(1);
temp(j) = x(2);
temp(k) = x(3);
temp
c*temp
B=0;
x=0;
k=k+1;

end
j=j+1;
end
i=i+1;
end

matlab basics : matrix norms, condition number




A =

1 0 -2
2 2 2
2 2 4

>> norm(A)

ans =

6.0225

%infinity norm

>> norm(A,'inf')

ans =

8


%condition numbers
>> cond(A)

ans =

19.5212

>> cond(A,'inf')

ans =

36

>> norm(A)*norm(inv(A))

ans =

19.5212

>> norm(A,'inf')*norm(inv(A),'inf')

ans =

36


matlab basics : matrix num elements, row/column operations, lu decomposition




%num of matrix elements
numel(A)

%example of row/col operations for complete pivoting

B =

1 0 -2 1
2 2 2 0
2 2 4 0

%swop rows 1 and 3
>> B([1 3],:) = B([3 1],:)


B =

2 2 4 0
2 2 2 0
1 0 -2 1

%swop columns 1 and 3
>> B( :,[1 3]) = B(:,[3 1])

B =

4 2 2 0
2 2 2 0
-2 0 1 1

% it is now z y x

>> B(2,:) = (-1/2)*B(1,:) + B(2,:)

B =

4 2 2 0
0 1 1 0
-2 0 1 1

>> B(3,:) = (1/2)*B(1,:) + B(3,:)

B =

4 2 2 0
0 1 1 0
0 1 2 1


>> B([2 3],:) = B([3 2],:)

B =

4 2 2 0
0 1 2 1
0 1 1 0

>> B( :,[2 3]) = B(:,[3 2])

B =

4 2 2 0
0 2 1 1
0 1 1 0

%it is now z x y

>> B(3,:) = (-1/2) * B(2,:) + B(3,:)

B =

4.0000 2.0000 2.0000 0
0 2.0000 1.0000 1.0000
0 0 0.5000 -0.5000

>> rref(B)

ans =

1 0 0 0
0 1 0 1
0 0 1 -1

%x = 1
%y = -1
%z = 0



%lu decomposition

[L,U]=lu(some_matrix)

Saturday, October 10, 2009

matlab : sample Gauss Elimination


A = [ 2 1 -1 8; -3 -1 2 -11; -2 1 2 -3]

m = 3
n = 4

i = 1

adds=0 %just counting the additions
mults=0 % just counting the multiplications

while i < m
j = i+1
while j <= m
temp = -(A(j,i)/A(i,i))
k = i
while k <= n
A(j,k) = A(j,k) + A(i,k)*temp
adds=adds+1
mults=mults+1
k=k+1
end
j=j+1
end
i=i+1
end
A

matlab : sample cholesky program


A = [2 4 2; 4 11 4; 2 4 6]

j = 1
n = 3

while j <= n
k = 1
while k < j
i = j
while i <= n
A(i,j) = A(i,j) - A(i,k)*A(j,k)
i=i+1
end
k = k+1
end
A(j,j) = (A(j,j)).^(1/2)
k = j+1
while k <= n
A(k,j) = (A(k,j))/(A(j,j))
k = k+1
end
j = j+1
end
A

matlab basics : inverse matrices, transpose

matlab basics : inverse matrices, transpose



>> B = [ 2 0 ; 3 1]

B =

2 0
3 1

>> inv(B)

ans =

0.5000 0
-1.5000 1.0000


transpose

>> B = [2 0; 3 1]

B =

2 0
3 1

>> B'

ans =

2 3
0 1

Tuesday, October 6, 2009

matlab basics : matrices

% 3 by 3 matrix

A = [ 2 1 1
1 -2 1
1 1 0]

A =

2 1 1
1 -2 1
1 1 0

% column vector

b = [10; 8; 3]

b =

10
8
3

% matrix multiplication

A * [1; 0; 0]

ans =

2
1
1


% index operations

A(1:3)

ans =

2 1 1

>> A(1:4)

ans =

2 1 1 1


% adding 3 columns to the A matrix and assigning result to B
B = [A(1:3) 1 0 0; A(4:6) 0 1 0; A(7:9) 0 0 1]

B =

2 1 1 1 0 0
1 -2 1 0 1 0
1 1 0 0 0 1



% the rref function for solving a linear system

rref(A)

Saturday, October 3, 2009

matlab basics : scripts, functions, precision

running scripts
===============

matlab -r myscript


creating and using a function
=============================

g = inline('9*(s.^6) + 6*(s.^5) - 11*(s.^4) - 4*(s.^3) - 5*(s.^2) + 12*s - 4')

g(1)

precision display
=================

format long e %15 digits with exponent

Saturday, September 5, 2009

Removing unwanted characters from a text file with grep

# This worked pretty good when I was getting strange characters from uploading a google text file to my linux box
#I couldn't import into mysql
#So I did this:

cat $1 | grep -o "[a-zA-Z,;()0-9_ ][a-zA-Z,;()0-9_ *@'.]*" > output.sql

#this command greps for only letters,commas, numbers, underscores, parenthesis, semicolons, astericks, and at signs.

Thursday, September 3, 2009

Cut out unwanted pieces of a lastname with vbscript



lastname = "DE' CA-R LO III"

'separate lastname by spaces into an array
a = split(lastname," ")
new_lastname = a(0)

for i = 0 to ubound(a) -1 ' add each chunk of the last name to the final string
'the last piece of the last name is not added if it is less than 4 characters (such as III, II, I, etc)
if i + 1 = ubound(a) and len(a(i+1)) > 3 then
new_lastname = new_lastname + a(i+1)
elseif i + 1< ubound(a) then
new_lastname = new_lastname + a(i+1)
end if
next

new_lastname = Replace(new_lastname,"-","") 'take out hyphens
new_lastname = Replace(new_lastname,"'","") 'take out punctuations

wscript.echo new_lastname

Monday, August 31, 2009

Linux mail basics

# Start interactive mail
mail

# Print current message
p

# Delete current message
d

#Exit mail program
q

Friday, August 28, 2009

Leopard user template

sudo mv /System/Library/User\ Template/English.lproj /System/Library/User\ Template/English.lproj.old

This will give you copy of the original called "English.lproj.old" in the same folder. Then you may copy your new template file by executing:

sudo cp -R /Users/new-user-short-name /System/Library/User\ Template/English.lproj

If you prefer to remove (delete) the original try the command without the /* at the end: sudo rm -r /System/Library/User\ Template/English.lproj

Get mac address from xml and generate computer names for each mac

Parsing xml is pretty easy using grep. The benefit of sed/grep is that they are right there -- if you have cygwin, Linux or Mac.

Here is an example format:



<macs>

<string>00-00-00-00-00-01</string>
<string>00-00-00-00-00-02</string>
</macs>


This will parse the xml file formatted like above and generate a computer name for each mac address. A good application of sed/grep/bash. If you are installing a lot of new computers and need to associate new names with mac addresses, this is a good start.


grep All\ Computers.plist | sed -e 's/<\/*string>//g' | while read line; do ((i++)); echo "pc-$i $line"; done > macs.txt

Friday, August 21, 2009

Set the default printer from the registry

rem Using reg.exe you can set the default printer

@echo off

rem Here we are doing a split of the hostname on the hypen, so room1-01, becomes room1

for /F "tokens=1 delims=-" %%a in ('hostname') do set name=%%a


if %name% == room1 ( reg add "hkcu\software\microsoft\windows nt\currentversion\windows" /t REG_SZ /d "ROOM1PRINTER,winspool,NE04:" /v "Device" /f
)

Thursday, August 20, 2009

Installing a folder tree of fonts on XP

rem XP doesn't let you select a folder to install fonts from; it will not recurse to find fonts within a folder unless they are all under one folder

rem This command will go through all folders in the current directory and copy the files to all_fonts

rem The /y for copy will force an overwrite if a duplicate file shows up

for /F "tokens=1 delims=," %a in ('dir /s /b') do copy /y "%a" all_fonts

Tuesday, August 4, 2009

mysql -- attaching to a host

#This is a way checking your connection to a mysql db server

mysql --user=username -h hostname -p

Thursday, July 9, 2009

GPG Error with APT

Get a gpg error when apt-get update

The time is incorrect; do this:

apt-get install ntpdate
ntpdate pool.ntp.org

then again:-

apt-get update

Wednesday, June 24, 2009

Replacing folders on a network with psexec and xcopy

rem We can run a process remotely with psexec
rem
rem cmd /C allows us to run a process in a cmd window and it automatically terminates

for /l %a in (1,1,50) do psexec \\station-%a cmd /C "move c:\path\to\folder c:\path\to\backup"

rem Now lets replace that folder with a new one using xcopy
rem
rem We use our local copy of the folder c:\path\to\folder and copy it to each station
rem
rem /S /E /H /I switches for xcopy ensure that we get hidden files, sub directories, and empty directories. /I assumes that the destination is a folder.

for /l %a in (1,1,50) do start cmd /k "xcopy /S /E /H /I c:\path\to\folder \\station-%a\c$\path\to\folder"

Wednesday, June 17, 2009

Get mac serial no from terminal

system_profiler SPHardwareDataType | grep "Serial Number" | sed 's/Serial Number://'

Tuesday, June 16, 2009

Php basics : error handling, tests, array functs, classes, and scope

Checking if a file exists

if (file_exists($some_file)){
...
}

Basic Error Handling

function($var) or exit("some error");


Printing an array


print_r();


Creating a class

class SomeClass{

private some_var;

public function SomeClass(){}

public function new_fun($r){
print_r($r);
echo $this->some_var;

}

}


Defining an array

$my_array = array('elem1','elem2');

Adding an array element

array_push($array,$elem)


Checking if a key exists

array_key_exists("some_name",$r)


Using a global var in a function

global $global_var;

JQuery basics : working with divs and text boxes, and checking for null elements

Adding text to a div's innerHTML

$("div#some_div").append(s);


Getting text from a div

var text = $("div#some_div" ).html();


Getting/Setting value from text box

var text = $("#some_textbox").val();
$("#some_textbox").val("bla");


Checking if document element is null

if (!$("#some_elem").length){
...

}

Monday, June 15, 2009

Get the distance between two latitude/longitude points in km (example)

Here is a python script to convert lat/lng point to meters. It expects the points to be entered in as decimal degrees. It outputs the distance in km.

For example:

python distlatlng.py 36.12 -86.67 33.94 -118.40
the distance in km is 2887.25995061



#uses the haversine formula
# based on code from http://www.movable-type.co.uk/scripts/latlong.html
import math, sys

def main(*args):
if len(args) < 5:
print args[0]," lng1 lat1 lng2 lat2 (finds distance between two lat/lng pairs)"
return
lat1 = float(args[1])
lng1 = float(args[2])
lat2 = float(args[3])
lng2 = float(args[4])
radius = 6372.8 # earth's mean radium in km
dlat = math.radians(lat2-lat1)
dlng = math.radians(lng2-lng1)
a = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(dlng/2)*math.sin(dlng/2)
c = 2*math.atan2(math.sqrt(a),math.sqrt(1-a))
dist = radius*c
print "the distance in km is " , dist


if __name__ == "__main__":
main(*sys.argv)


Python basics : math functions, main funct

Math functions
#Unfortunately, you need to import math, but python has a nice library of math functions



import math
math.pow(2,3)
math.cos(math.pi/2) #<-- radians!
math.pi
math.sqrt(4)



Main function

#Making a main function in Python is a little tricky. Here is an example:



def main(*args):
if len(args) < 4:
return

print "main : args[0] ", args[0], " args[1]", args[1]
print "(main) : args[1] ", args[2]
print "(main) : args[3] ", args[3]

if __name__ == "__main__":


Sunday, June 14, 2009

Mysql -- get table engine type

Get table engine type

You have to go to the mysql system database 1st

This allows you to see which type of table engine you're using

Common types:

myisam: doesn't support the features listed below for innodb
innodb (default) : supports r-trees (good for spatial extensions), enforces foreign keys, and supports transactions


select table_name, engine from tables where table_schema = "vsn";

Friday, June 12, 2009

Silent install of msp patch

msiexec /p mspfile.msp /qn

Thursday, June 11, 2009

Checking versions if Office 2004 is at 11.5.5 and Acrobat is at 9.1.2

This is a trick to check version of some software on a group of computers


Here we're checking that Office 2004 11.5.5 update is installed


for ((i=1;i < 21;i++)); do if [[ $i -lt 10 ]]; then echo "station $i" ; ssh station-0${i}.local " ls -l /Applications/Microsoft\ Office\ 2004/Updater\ Logs/11.5.5\ Update\ Log.txt "; else ssh station-${i}.local " ls -l /Applications/Microsoft\ Office\ 2004/Updater\ Logs/11.5.5\ Update\ Log.txt "; fi; done

Here we're checking that Acrobat reader and acrobat are at 9.1.2


for ((i=1;i < 21;i++)); do if [[ $i -lt 10 ]]; then echo "station $i" ; ssh station-0${i}.local "system_profiler SPSoftwareDataType SPApplicationsDataType | grep '9.1.2' "; else ssh station-${i}.local " system_profiler SPSoftwareDataType SPApplicationsDataType | grep '9.1.2' "; fi; done

Wednesday, June 10, 2009

How to set up Jogre for the web

Set up jdk, apache tomcat, and hsqldb
==============================

apt-get install sun-java6-jdk
apt-get install tomcat5.5 tomcat5.5-wepapps tomcat5.5-admin
apt-get install hsqldb-server

Set up jogre
=========

wget http://voxel.dl.sourceforge.net/sourceforge/jogre/jogre_beta_0.3_bin.zip
cd /opt
unzip ~/jogre_beta_0.3.bin.zip
adduser jogre
chown -R jogre:jogre jogre
su jogre
cd
echo "export CLASSPATH=$CLASSPATH:/usr/share/java/hsqldb.jar:." >> .profile
source .profile
java org.hsqldb.Server &
cd /opt/jogre/server
chmod a+x *.sh


Configuration
==========

./server.sh &

#I prefer the gui; it's easier to just change the db settings with this tool
./administrator.sh &
#Login with admin, admin
#Change the database from xml to hsqldb
#The path to the db is jdbc:hsqldb:hsql://localhost/jogre_hsqldb

#restart the jogre server
killall server.sh
./server.sh &


#With apache tomcat admin (http://localhost:8180/admin), add jogreweb.war

Tuesday, June 9, 2009

How to start another X session

You already have X running and want to run another one.

1. Login into another virtual console
2. Open the terminal
3. startx -- :1

Monday, June 8, 2009

Tricks with the Echo command in XP

rem generate list with echo
for /l %a in (1,1,9) do echo "station-0%a"

rem Generate a file with echo to a room of computers
for /l %a in (1,1,50) do echo "station-%a" > \\station-%a\c$\myfile.txt

Printing from the command line in XP

rem Print from command line


notepad /p textfile.txt

Sunday, June 7, 2009

Java - convert byte array to String



int len = (int)c.getLength();

if (len > 0) {
int actual = 0;
int bytesread = 0 ;
byte[] data = new byte[len];
while ((bytesread != len) && (actual != -1)) {
actual = is.read(data, bytesread, len - bytesread);
bytesread += actual;

}

//assuming utf-8 encoding
String test = new String(data,0,data.length,"UTF8");
System.out.println(test);


Java - how to make an anonymous thread

Creating an anonymous thread is pretty easy. If you want to make a thread that performs a simple operation anonymous threads can be convenient.

Java threads perform their task in the run() function, which is initiated with the start method.

Here is an example:



Thread t = new Thread( new Runnable(){
public void run(){
System.out.println(" do some work");


}
});

t.start();

Saturday, June 6, 2009

SVN commands

Creating a new repository for SVN

svnadmin create /path/to/svn/newrepository


Importing

svn --username user import http://svnsite.com/path/to/svn/newrepository -m "initial import"

#note about importing
#create a local folder called newrepository and put whatever code you want to import into newrepository
#run svn from newrepository


Permission denied when importing

# Do this on the server's svn directory

sudo chown -R www-data:www-data svn

Hello world Midlet


import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;


public class LoginScreen extends MIDlet {

public LoginScreen() {
// TODO Auto-generated constructor stub
}

protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub

}

protected void pauseApp() {
// TODO Auto-generated method stub

}

protected void startApp() throws MIDletStateChangeException {
// TODO Auto-generated method stub

Form f = new Form("Login Form");
Display d = Display.getDisplay(this);
d.setCurrent(f);

f.append("Hello");

}

}

Flash tricks - global vars, functions, timers

Creating global var-
_global.myvar

Creating a timer-
var starttime = getTimer();
var atime=0;

while (atime < _global.timestop+starttime){

atime = getTimer();

if (_global.conn_state == true){
break;
}
}

Creating a function-
function populateJoin(){

gamelist.data = _global.currentmsg.split(_global.SEP);
gamelist.labels = _global.currentmsg.split(_global.SEP);


}

Photoshop Tricks - alpha channels and actions

Creating an alpha channel (ps cs2)-
magic lasso outside of the object
inverse select
go to channels
click save selection as channel
Now you can save with the alpha channel


Creating an action (ps cs2)-
Click the actions tab
Click new actions and click record
Do what you want to record and press stop

Automatically start action (ps cs2)-
go to file ->scripts
click scripts events manager
check the enable events to run scripts/actions
associate your action with an event

Java Me Notes

Links

Main site

http://java.sun.com/javame/index.jsp

Download

http://java.sun.com/products/sjwtoolkit/download.html

Eclipse plugin

http://download.eclipse.org/dsdp/mtj/updates/0.9/stable/

Need to use eclipse to export jad and jar for the project (which is in deploy)


Conventions

startApp() --> like main

import javax.microedition.lcdui.*; //required to use display

Display // interface with phone screen

Form //set up the screen then attach it to display

myform.append("some text"); //a label

Friday, June 5, 2009

Setting up hsqldb

hsqldb is a java based database server

Install it:

apt-get install hsqldb-server

Create the server.properties and sqltool.rc files in your home folder (sample files should be where hsqldb was installed)

The main jar file is /usr/share/java/hsqldb.jar, which should be in your CLASSPATH when working with hsqldb

Place a link in /usr/share/tomcat5.5/common/lib if you want to use it with tomcat 5.5.

There is a swing utility to test and manage the databases.

Starting the server:

java -cp /path/to/hsqldb.jar org.hsqldb.Server


Database URL:

jdbc:hsqldb:hsql://localhost/mydb

See list of mac file servers on network

This is quick way to get a list of appletalk machines on your network when you only have access to the terminal.

atlookup

Set remote desktop from command line

reg add "\\computer\hklm\system\currentcontrolset\control\terminal server" /v "fDenyTSConnections" /d 0 /t REG_DWORD /f

0 is off and 1 is on

Wednesday, June 3, 2009

Generate a command window for each iteration of a loop

rem This is good for those commands that take a lot of time.
rem Each iteration generates a new cmd window

for /l %a in (1,1,10) do start cmd /k psexec \\computer-%a time-consuming.exe

Force a live update from command line

This will perform a silent live update of Symantec Antivirus 10.2

"c:\Program Files\Symantec AntiVirus\VPDN_LU.exe" /fUpdate /s

Adding a printer with vbscript from a network share

rem Add the connection
cscript prnmngr.vbs -ac -p \\server\printer_share


rem Set it as a default
cscript prnmngr.vbs -t -p "\\server\printer name"

rem If you don't know the name
cscript prnmngr.vbs -l

Keeping track of station numbers with a text file

rem Usually I keep track of the configurations associated with a station by its mac
rem Without the macs, one can keep track of what configuration to use by using a counter
rem
rem This works well with a network or a flash drive


for /f %%a in ('type \\server\share\count.txt') do SET temp=%%a
rem echo %temp%
SET /A temp+=1
echo %temp% > \\server\share\count.txt

rem The counts of count.txt is simply a number and can be used in a script

Adding an extension to a bunch of files

#I made a bunch of text files for Windows, but XP cannot open them without an extension
#This was a quick fix

find . -type f -exec mv {} {}.txt \;

Tuesday, June 2, 2009

Installing Apache Tomcat 5.5

#make sure you add unstable entries to sources.list
apt-get install sun-java6-jdk

apt-get install tomcat5.5
apt-get install tomcat5.5-admin
apt-get install tomcat5.5-webapps

$CATALINA_HOME/webapps/ROOT/index.jsp
/usr/share/tomcat5.5-webapps/ROOT/index.jsp



#it will be listening on port 8180

Debian package manager

#useful Debian/Ubuntu package commands

apt-get install package
apt-get remove package
apt-get update #good for updating your database after editing sources.list
apt-cache search search_string

dpkg --list
dpkg --install program.deb
dpkg --remove program




#Sometimes you have to add this to /etc/apt/sources.list
# etch is a version of Debian, replace with your version

deb http://security.debian.org/ etch/updates main contrib
deb-src http://security.debian.org/ etch/updates main contrib

deb http://ftp.debian.org/debian/ etch main
deb-src http://ftp.debian.org/debian/ etch main

#these are good for install outside packages like java

deb http://ftp.debian.org/debian/ unstable non-free
deb-src http://ftp.debian.org/debian/ unstable non-free

Power configuration from command line with xp

powercfg /setactive "always on"

powercfg /query

net time commands

net time (time from domain server)

net time /querysntp

net time /set \\another_pc

net time /setsntp:time.apple.com

Monday, June 1, 2009

Change a computer name with vbscript

Scripting the changing of computer names in windows is straight-forward with a vbscript.

You can change a computer via the registry, so this is the approach used here.

Set the computer name you want in the sNewName variable.



sNewName = "new_pc_name"

Set oShell = CreateObject ("WSCript.shell")



sCCS = "HKLM\SYSTEM\CurrentControlSet\"

sTcpipParamsRegPath = sCCS & "Services\Tcpip\Parameters\"

sCompNameRegPath = sCCS & "Control\ComputerName\"



With oShell

.RegDelete sTcpipParamsRegPath & "Hostname"

.RegDelete sTcpipParamsRegPath & "NV Hostname"



.RegWrite sCompNameRegPath & "ComputerName\ComputerName", sNewName

.RegWrite sCompNameRegPath & "ActiveComputerName\ComputerName", sNewName

.RegWrite sTcpipParamsRegPath & "Hostname", sNewName

.RegWrite sTcpipParamsRegPath & "NV Hostname", sNewName

End With ' oShell

VBScript tricks : no logo, filesystem, control blocks, argument


'When running from the console, here is how to hide the logo

cscript //Nologo myscript.vbs

'How to reference an argument
WScript.Arguments.Item(0)


'Here is how to read a file

set f = fso.opentextfile(source, 1,false)



if fso.fileexists(source) then



while not f.atendofstream



inputline = f.readline



msgbox inputline

wend

end if

Inserting a blank line with sed

#I found this to be a bit tricky

sed -e '/pattern/i\
\ # <-- this is the key
' input_file > output_file

Saturday, May 30, 2009

awk example using arrays, the split() function, and regex

#record format

Request: 10
As Of: 05/27/2009 1:34:58 pm
Irrevelant Data ...
Summary: Virus on PC.
Description: Virus on PC.

Request: 11
As Of: 05/27/2009 1:34:58 pm
Irrevelant Data...
Summary: room1 several computers in a row are freezing up and student...
Description: room1 several computers in a row are freezing up and students have to reboot.


awk -v pat1="room1" -v pat2="freezing|crash" 'BEGIN { RS=""; FS="Summary"; i=0; j=0; k=0 } {\
i=i+1; \
field1=$1; \
split(field1,sub_fields,":"); \
request=sub_fields[1]; \
the_date=sub_fields[4]; \
if ($2 ~ pat1){ \
k=k+1; \
if ($2 ~ pat2){ \
j=1+j; \
print "***Record***", request, the_date; print " ---Start Data---", $2; } } \
} END { print "Processed, ", i, ",num of lab matches,", k,", records num of keywords matches: ,", j }' requests


#Output

***Record*** Request 05/27/2009 1
---Start Data--- : room1 several computers in a row are freezing up and student...
Description: room1 several computers in a row are freezing up and students have to reboot.
Processed, 2 ,num of lab matches, 1 , records num of keywords matches: , 1

Friday, May 29, 2009

Removing carriage returns with sed

sed -e s/$'\r'/\ /g input_file # remove carriage returns

sed -e 's/\n/ /g' input_file # remove newlines

Insert text before a pattern with sed

cat some_file | sed '/pattern/i\
text to insert
' > output_file

Remove empty lines with vi

In ex mode:

:1,$s/^$//

Sometimes you need to do this too:

:1,$s/^\n//


May be able to do this:

:1,$s/^[\n$]//

Show special characters in vi

:set list

# see control chars (tabstops, control characters, etc)

Example of processing multiline records with awk

Processing multiline records is tricky. It is easier to use blank lines as record separators.


#example records
ink1 4.99
red

ink2 5.99
yellow

awk ' BEGIN { RS=""; FS=" "} { r1=$1; r2=$2; r3=$3; print "***Record***" r1 " " r2 " " r3 }' inks

#What it prints out
***Record***ink1 4.99
red
***Record***ink2 5.99
yellow

Thursday, May 28, 2009

Creating a mysql user and granting privileges

//standard way of creating a user

CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';


//Creating a user and granting privileges:

GRANT ALL PRIVILEGES ON table.* TO 'user'@'localhost' identified by 'password'

//Show privileges for a user:

show grants for 'user'@'localhost'

Install Windows nic driver on Linux

#Download ndiswrapper

make #this will install the kernel module (after compiling)
modprobe ndiswrapper
ndiswrapper -i driver.inf
ndiswrapper -m #generate modprobe alias for ndiswrapper
#restart


#Check installed drivers:

ndiswrapper -l

Showing a decimal expansion with bc

#3 digits after the decimal place
echo "scale=3; 41.0 / 939.0" | bc

Wednesday, May 27, 2009

awk script to generate count of each program

#csv of format:
#the_program, any_data, any_data, ....
#
#this script counts number of repetitions of a program



cat program-list.csv | awk -F',' '/[a-zA-Z0-9]+/{print $1}' | sort | uniq -c

Tuesday, May 26, 2009

Create a dojo dialog widget

Create Messagebox / popup for Java

//Assuming that the current object is a JFrame:

JOptionPane.showMessageDialog(this, "Some Message");

Monday, May 25, 2009

Php declare a constant

define("CONSTANT", "Hello world.");
echo CONSTANT; // outputs "Hello world."

Monday, April 20, 2009

For loop of death

This is a way to somewhat defend yourself when a process keeps on respawning itself and won't go away. This happens quite a bit when XP gets infiltrated by malware.




for /l %a in (1,1,1000000) do taskkill /im malware.exe /f

Universal scripted uninstall (XP)

Given the displayname value, this vbscript will go and find it in the registry and uninstall the corresponding program.

This is where it searches:

hklm\software\microsoft\windows\currentversion\uninstall



' arg 1 - displayname


if (wscript.arguments.count > 0 ) then

set shell = wscript.createobject("wscript.shell")
strcmd = "reg query hklm\software\microsoft\windows\currentversion\uninstall /s"

set oexec = shell.exec(strcmd)

temp = 0
parent = ""

do while not oexec.stdout.atendofstream

strline = oexec.stdout.readline


if len(strline) > 0 then
a=split(strline,vbtab)
if mid(trim(a(0)),1,4) = "HKEY" then
b = split(trim(a(0)),"\")
parent = b(ubound(b))
temp = 1
end if
alen = ubound(a) + 1
if alen >= 3 then
if trim(a(0)) = "DisplayName" and trim(a(2)) = wscript.arguments(0) and temp = 1 then
wscript.echo "msiexec /x " & parent & " /qn"
temp = 0
shell.exec("msiexec /x " & parent & " /qn")
exit do
end if

end if
end if
loop




end if

Sunday, April 19, 2009

Solution to generating markers along a route at a regular interval

I found this neat javascript extension for the google map api. Here is the link:

http://econym.org.uk/gmap/epoly.htm

You specify the distance and give it a polyline and it returns an array of points along the route.



map.setCenter(new GLatLng(42.351505,-71.094455), 15);
var directionsPanel = document.getElementById("directions_div");
var directions = new GDirections(map, directionsPanel);
var address = "from: trenton, nj to: philadelphia, pa";

directions.load(new_address);
if (directions == null){
alert("Error: directions object is null");
return;
}

var pl = directions.getPolyline();

if (pl == null){
alert("Error: polyline object is null");
return;
}

var points = pl.GetPointsAtDistance(1609.344);

if (points == null){
return;
}

for (var i=0; i
map.addOverlay(new GMarker(points[i]));
}