Sunday, December 30, 2007

JAVA: Printmyself Class

import java.io.*;
import java.lang.*;
public class Printmyself  {
  public static void main(String[] args) {
 try
    {
String fileName = "Printmyself.java";
                 FileReader fileRdr = new FileReader(fileName);
                 BufferedReader bfrRdr = new BufferedReader(fileRdr);
                 String line = " ";
                 while(bfrRdr.readLine() != null) {
                 line = bfrRdr.readLine();
                 System.out.println(line);}
   }
  catch (IOException ioe) { System.out.println(ioe); }
  }
}


>javac Printmyself.java
>java Printmyself

Wednesday, December 26, 2007

PHP: For Loops

print "<table>";
for ($y=1; $y<= 12 ; $y++) {
print "<tr>\n";
 for ($x=1; $x<= 12 ; $x++) {
  if ($x==$y) {print "<td bgcolor=red>\n";}
  else {print "<td>\n";}   
  print ($x * $y);
  print "</td>\n";
       }
print "</tr>\n";
       }
print "</table>";
1 2 3 4 5 6 7 8 9 10 11 12
2 4 6 8 10 12 14 16 18 20 22 24
3 6 9 12 15 18 21 24 27 30 33 36
4 8 12 16 20 24 28 32 36 40 44 48
5 10 15 20 25 30 35 40 45 50 55 60
6 12 18 24 30 36 42 48 54 60 66 72
7 14 21 28 35 42 49 56 63 70 77 84
8 16 24 32 40 48 56 64 72 80 88 96
9 18 27 36 45 54 63 72 81 90 99 108
10 20 30 40 50 60 70 80 90 100 110 120
11 22 33 44 55 66 77 88 99 110 121 132
12 24 36 48 60 72 84 96 108 120 132 144

Lesson: Quantity of "For Loops" = "Amount of Dimensions".

Almost same program on command line:

<?php
for ($y=1$y<= 12 $y++) {
echo 
"\n";
    for (
$x=1$x<= 12 $x++) {
        echo 
"\t";            
        echo (
$x $y);
                   }
echo 
"\n";
             }
?>
Just copy that into a file named numbers.php, and run it by this command:
php ./numbers.php

JAVA: Cellular Automata

import java.awt.*;

//John Conway's Game of Life
//altered from barry tolnas applet
public class CA1 {
        public static void main(String[] args) { 
 int width =100;
 int height=100;

   int[][] CA1 = new int[width][]; //Array to hold the cell states
   int[][] CA2 = new int[width][]; //Array to hold new states temporarily

 for (int col=0; col<width; col++) {
     CA1[col] = new int[height];
     CA2[col] = new int[height];
 }

 //Initialize a box of cells
 final int boxwidth = 100;
 final int cx = width/2;  //center in the x direction
 final int cy = height/2; //center in the y direction

 for (int y=0; y<boxwidth/2; y++) {
     for(int x=0; x<boxwidth/2; x++) {
  int initialState=(int)(2*Math.random()); //Get a random 1 or 0
  CA1[cx-x][cy-y]=initialState;  //These four lines create
  CA1[cx+x][cy-y]=initialState;  // a symmetrical pattern of
  CA1[cx+x][cy+y]=initialState;  // cells by placing four 
  CA1[cx-x][cy+y]=initialState;  // copies of each in the 
     }                                  // right places.
 }


 int sum;
 while (true) {  // infinite loop

     //Update all cells
     for(int y=1; y<height-1; y++) { //loop down window drawing rows
  for(int x=1; x<width-1; x++) { //loop over each cell in row

      //Draw the state of the current cell
      if (CA1[x][y]==0) ;
      else    ;
      //g.drawLine(x,y,x,y);

      //Figure out next state
      sum=0;

      sum += CA1[x-1][y];
      sum += CA1[x-1][y+1];
      sum += CA1[x][y+1];
      sum += CA1[x+1][y+1];
      sum += CA1[x+1][y];
      sum += CA1[x+1][y-1];
      sum += CA1[x][y-1];
      sum += CA1[x-1][y-1];

      if (CA1[x][y]==0 && sum==3) { CA2[x][y] = 1; // cell is born
    System.out.println("oh; joy; a child is");
    System.out.println("born");
                           continue; } 

      if (CA1[x][y]==1 && sum<2)  { CA2[x][y] = 0; //die of loneliness
    System.out.println("oh; so so sad;");
    System.out.println("that one died of loneliness");
    System.out.println("**\n***\n****\n*****\n******\n");
   continue; } 

      if (CA1[x][y]==1 && sum>=4) { CA2[x][y] = 0; // die of overpopulation
    System.out.println("oh; sad; death by");
    System.out.println("over population");
    System.out.println("**\n***\n****\n*****\n******\n");
   continue; }

      CA2[x][y] = CA1[x][y];
    System.out.println("oh, i am");
    System.out.println("staying alive and doing ok");
    System.out.println("**\n***\n****\n*****\n******\n");

  }

     }

     //Copy the new states in CA2 back into CA1 for the next iteration.
     for (int y=1; y<height-1; y++) {
  for (int x=1; x<width-1; x++) CA1[x][y]=CA2[x][y];
     }
 }


    }
}

  1. Copy the souce code above into a file called CA.java
  2. javac CA.java
  3. java CA1

Tuesday, December 25, 2007

PHP Generate Line Number Anchor Links

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<h3>Generate Line Number Anchor Links</h3>
<?php
$base="/home/lance/inc/public_html";
if ($HTTP_GET_VARS['file']!="") {
$the_file=$HTTP_GET_VARS['file'];
$lines = file($the_file);
// Loop through our array, show HTML source as HTML source; and line numbers too.
foreach ($lines as $line_num => $line) {
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}
highlight_file($base.$PHP_SELF);
}
if ($HTTP_GET_VARS['file']=="") {
echo "<hr>\n";
$lines=file($base.$PHP_SELF);
echo "<table border=1><tr><td>\n";
foreach ($lines as $line_num => $line) {
echo "<a name=".$line_num."><a href=\"#".$line_num."\">".$line_num."</a><br>\n";
}
echo "</td><td>\n";
foreach ($lines as $line_num => $line) {
echo htmlspecialchars($line)."<br />\n";
}
echo "</td></tr></table>";
}
?>

PHP CLI image size calculator

<source_code>
#!/usr/bin/php
<?php
fwrite(STDOUT, "Please enter the URL directory 
path of the files: \n");
$host_dir = fgets(STDIN);
fwrite(STDOUT, "Please enter the sizing number:\n");
$sizeimg = fgets(STDIN);
$list_of_files = array();
exec(ls, &$list_of_files);
foreach ($list_of_files as $image) {
$size = getimagesize($image);
$width = $size[0]; // Index 0
$height = $size[1]; // Index 1
$type = $size[2]; // Index 2
$nwidth=$width*${sizeimg};
$nheight=$height*${sizeimg};
echo "\n<a href=\"".${host_dir}.${image}."\">
     <img src=\"".${host_dir}.${image}."\" 
     width=\"".$nwidth."\"
     height=\"".$nheight."\" ></img>\n";
echo "</a><br /><br />";
}
echo "\n";
?>
</source_code>

Bash: Check if file exists

<source_code>
#!/bin/bash
FILENAME=$1
if [ -f $FILENAME ]; then
echo "Size is $(ls -lh $FILENAME | awk '{ print $5 }')"
echo "Type is $(file $FILENAME | cut -d":" -f2 -)"
echo "Inode number is $(ls -i $FILENAME | cut -d" " -f1 -)"
echo "$(df -h $FILENAME | grep -v Mounted | awk '{ print \
"On",$1", \
which is mounted as the",$6,"partition."}')"
else
 echo "File does not exist."
fi
</source_code>

PHPBB -How to edit the banner section of the page

If you are using phpbb and want to edit the banner or footer sections of the index.php webpage, the file in which you enter your own HTML is:
.../templates/subSilver/index_body.tpl

PHP: Showing the Remote Address

<source_code>
<form name="thisform" method="POST" action="http://ws.arin.net/cgi-bin/whois.pl">
<input type="text" Name="queryinput" size="15" maxsize="15" value="<?php echo ${REMOTE_ADDR}; ?>">
<input type="submit" value="<--this is your external IP">
</form>
</source_code>

Simple Clickthru PHP

MySQL Create Table Statement:

CREATE TABLE `count_stuff` (
  `ip_number` varchar(16) NOT NULL default '',
  `time` datetime NOT NULL default '0000-00-00 00:00:00',
  `referer` varchar(128) NOT NULL default '',
  `target_file` varchar(128) NOT NULL default ''
) TYPE=MyISAM;
(redirect1.php) The redirect page that enters the clickthru info into database:
<html>
<head>
<meta http-equiv="REFRESH" content="0; 
URL=http://www.example.com/PRODUCTS.php">
</head>
</html>
<?php
$target_file
="Manual_Download";
$dbh=mysql_connect ("localhost"
                    
"db_username"
            
"password"
            or die 
            (
'I cannot connect to the database because: '
            
mysql_error());
mysql_select_db ("count_clicks");
$sql "INSERT INTO 
        `count_stuff` 
    ( `ip_number` ,
    `time` ,
    `referer`, 
    `target_file` ) "
;
$sql.= " VALUES ( '".$REMOTE_ADDR."',
         now() ,
     '"
.$_SERVER['HTTP_REFERER']."',
     '"
.$target_file."' );";
mysql_query($sql);
?>

This PHP will show how many have accessed the PRODUCT.pdf:
<?php
$dbh
=mysql_connect ("localhost"
                   
"db_user"
           
"password"
or die (
'I cannot connect to the database because: ' 
mysql_error());
mysql_select_db ("count_clicks");
$sql="SELECT COUNT(  `target_file` ) 
FROM  `count_stuff` 
WHERE  `target_file`='Manual_Download'"
;
$results=mysql_query($sql);
while(
$row mysql_fetch_row($results)) {
echo 
"This many people downloaded the manual:".$row[0];
}
?>

PHP : General Redirect with One Variable

<source_code>
<?php
$redirect="http://www.example.com";
echo "<html>\n<head>\n<meta http-equiv=\"REFRESH\"\n content=\"0;\n
URL=".$redirect."\">\n</head>\n</html>";
?>
</source_code>

Monday, December 24, 2007

Bash iteration over list with command line argument


<source_code>
#!/bin/bash
LIST="
Anyone
Everyone
Someone
"
for item in ${LIST}
do
echo ${1} ${item} 
done
exit 0;
</source_code>

>./listing.sh hello
hello Anyone
hello Everyone
hello Someone

SED: The simplest example

>echo I am older | sed -e 's/old/new/g'
I am newer

SED: Converting carat symbols to HTML special characters

Goal: Show HTML and PHP code, rather than have it interpreted by the web browser.

Using a GNU or Unix command line, myWebpage.html is a regular fully working HTML web page, here is the command:

sed -e 's/\</\&#60;/g' -e 's/\>/\&#62;/g' myWebpage.html > newWebpage.html

Bash Program To Convert Tags to Special Characters
#!/usr/bin/env bash
echo  "lancemiller777@gmail.com"
echo "Argument 1 is file with html tags"
echo "sed -e 's/\</\&#60;/g' -e 's/\>/\&#62;/g' \${1}"
sed -e 's/\</\&#60;/g' -e 's/\>/\&#62;/g' ${1}

PHP Database that shows web page access


<source_code>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>show IP numbers</TITLE>
</HEAD>
<body
background=""
bgcolor="#000000"
text="#33FF33"
link="#33FF33"
alink="#33FF33"
vlink="#33FF33">
<?php
$this_url="http://www.yourdomainname.org";
$database="put-your-database-name-here";
$user="put-your-database-user-name-here";
$password="put-your-database-user-password-here";
$host="localhost"; 
$dbh=mysql_connect (${host},${user},${password}) or die ('I cannot connect to the database because: ' . 
mysql_error());
mysql_select_db ($database);
echo "<h3>Database of Visitors</h3>";
echo "MySQL is currently: ";
echo date("l dS of F Y h:i:s A");
echo "<br>";
$sql = 'SELECT * ';
$sql .= " FROM `ip_visit` ORDER by `time` DESC LIMIT 40 ";
$results = mysql_query( ${sql});
$error=mysql_error();
echo "{$error}";

while($row = mysql_fetch_row($results)) {
echo "<hr>";
if ($REMOTE_ADDR==$row[0]) {echo "this ip is yours:<br>";}
whonumber($row[0]);
echo " time of access:  ".$row[1]."<br>webpage: ";
linker($row[2],$row[2]);
echo "<hr><br>";
} 

function insert_showaccess($this_url, $REMOTE_ADDR , $PHP_SELF) {
$sql = "INSERT INTO `ip_visit` ( `ip_number` , `time` , `webpage` ) ";
$sql.= " VALUES ( '".$REMOTE_ADDR."', now() , '".$this_url.$PHP_SELF."' );";
mysql_query($sql);
}

function whonumber($ip_num) {
echo "<form name=\"thisform\" method=\"POST\" action=\"http://ws.arin.net/cgi-bin/whois.pl\">
<input type=\"text\" Name=\"queryinput\"";
echo " value=\"".$ip_num."\"";
echo " size=\"20\"><input type=\"submit\" value=go></form>";
}

function makevisitortable($database) {
mysql_select_db ($database);
 $sql = 'CREATE TABLE `ip_visit` ( `ip_number` varchar( 16 ) NOT NULL default \'\','
        . ' `time` datetime NOT NULL default \'0000-00-00 00:00:00\','
        . ' `webpage` varchar( 128 ) NOT NULL default \'\','
        . ' `nmap` tinytext NOT NULL ) TYPE = MYISAM ';
mysql_query($sql);
}

function linker($url,$link) {
echo "<a href=\"$url\">$link</a>";
}

if ($HTTP_GET_VARS['create_db_table']==yes) {
makevisitortable($database);
}

insert_showaccess($this_url, $REMOTE_ADDR , $PHP_SELF);
?>

</body>
</html>
<?php
die();
?>
</source_code>

Telnet Into All in IP Range


<source_code>
#!/bin/bash
host=0;
IP=10.0.2;
scheme=telnet;
while [ $host -lt 255 ]
do
${scheme} ${IP}.${host};
let "host = host+1";
done
</source_code>

PHP File Upload : Boilerplate Basic Code

This is the most minimal code needed to upload files with a PHP script.

< source_code>

$uploaddir = '/home/lance/www/uploads/';
$http_post_uploaded_file = $_FILES['uploadedfile']['name']; 
$uploadfile = ${uploaddir}.${http_post_uploaded_file};
move_uploaded_file($_FILES['uploadedfile']['tmp_name'],
                   ${uploadfile}); 
$upload_url="/uploads/".${http_post_uploaded_file};
if ($_FILES['uploadedfile']['name']!="") {
echo "<href=\"".${upload_url}."\">here is what you uploaded</a>\n";   }

</source_code>

Sunday, December 23, 2007

Bash Command Line: Email all mac addresses



< source_code>
#!/bin/bash
sendmac()
{
sendmail someone@example.org
$1
$2
$3
$4
$5
$6
}
ifconfig | grep ether | sendmac;
</source_code>

Another way to get the mac address into portable format is this:
ifconfig | grep ether > ~/Desktop/MACaddress.txt; \
echo "this is my mac addresses" >> ~/Desktop/MACaddress.txt;

Perl: Tiny Spreadsheet


< source_code>
#!/usr/bin/perl
system ('clear');
print DATA;
while(  ) {
$sum+=$_;
print $_;
}
print "--------\n";
print "$sum  TOTAL\n";
__END__
12.00  mini-saigon 12/21/2002 
18.80  groceries   12/21/2002
18.86  groceries   12/22/2002
15.00  pho bac     12/24/2002
6.00   pike market 12/26/2002
34.73  groceries   12/27/2002
</source_code>
> ./tiny_perl_spreadsheet.pl
12.00 mini-saigon 12/21/2002 
18.80 groceries 12/21/2002
18.86 groceries 12/22/2002
15.00 pho bac 12/24/2002
6.00 pike market 12/26/2002
34.73 groceries 12/27/2002
--------
105.39 TOTAL

Recursive Bash Program


< source_code>
#!/bin/bash
LIMIT=$1
if [ $2 ]
then
CELL=$2
else
CELL=[] 
fi 
#******************
print_horizontal_line()
{
ME=0
while [ $ME -lt $LIMIT ] 
do
echo -n $CELL 
let "ME= ME+1"
done
}
#******************

#******************
print_vertical_line()
{
ME2=0
while [ $ME2 -lt $LIMIT ] 
do
print_horizontal_line  
echo     
let "ME2= ME2+1"
done
}
#******************
print_vertical_line;
let "LIMIT= LIMIT/2"
if [ $LIMIT -le 0 ]
then
exit
else
$0 $LIMIT $CELL
fi
exit
</source_code>

This short program to the above serves to demonstrate some basic bash programming syntax and a (very) basic use of recursion. If the program is run on the command line as:

lancemiller$ recursive_bash 4
[][][][]
[][][][]
[][][][]
[][][][]
[][]
[][]
[]
In shell programming the arguments are numbered
$0  $1   $2   $3   $4 ....etc 
recursive_bash 4
 ^             ^
 |             |
$0             $1

The recursive_bash program is going to take $1 (numeral 4 in this example) and perform some math and print a certain amount of characters as a result. First $1 is assigned to the variable LIMIT. Math and print statements occur using $LIMIT. $CELL is the character that will be printed. Argument $2 is optional. Example:

lancemiller$ recursive_bash 4 cat
catcatcatcat                   ^
catcatcatcat                   |
catcatcatcat              arg $2   
catcatcatcat
catcat
catcat
cat

$LIMIT is divided by 2.-> let "LIMIT= LIMIT/2" Then the recursive moment comes in recursive_bash at the line that says: 
$0 $LIMIT $CELL
$0 is the program itself(recursive_bash). It is called over and over till
let "LIMIT= LIMIT/2" results in zero. When $LIMIT is equal or less than zero the program exits.