Practical Web Programming

Monday, August 04, 2008

PHP: How to Display Errors Without Tweaking the Configuration File

Displaying errors in your PHP applications by tweaking the configuration file is sometimes troublesome, especially for most beginners. Luckily, you don't have to get your hand dirty to deal with it.

After installing MAMP (Mac, Apache, MySQL, PHP) in my MacBook, I had a hard time debugging my PHP codes as MAMP's default configuration do not allow showing of error.

In production environment, showing errors is a big mistake you can commit as your website is more vulnerable to hack attacks. But in development environment such as localhost, showing errors save you a lot of time in debugging.

Here's what I did.


ini_set('display_errors', 1);
error_reporting(E_ALL);


Put this two lines of codes in your index file and you'll see all the errors in your PHP codes will show off, if there are any (minus the links, of course).

Thursday, July 31, 2008

Ebook: Database Normalization Explained

If you're a programmer, aside from your favorite EDI and PL, database is one of your everyday companion. Almost all program these days uses a form of database, be it a flat file or RDBMS.

Being a good programmer, it's not enough that you only know the DML and DDL statements. You should also know and master the art of Database Normalization. Database normalization techniques is essential in order to achieve a high performance database design for your programs. If your database design doesn't conform to at least the Third Normal Form, you will have a hard time getting the data you want and it will be harder to achieve a high performance and scalable application.

Finally, there's an e-book that could give you the right knowledge about Database Normalization. This e-book shows you that normalization is a far too easy approach, and it is richly documented with graphical Entity Relationship and Server Diagram examples.

This knowledge-packed e-book is a great resource for DBAs and programmers.

Click here to get a copy of the Database Normalization Ebook.

Friday, February 29, 2008

PHP: How to Get the Current Server Date and Time

Adding date and time to your website gives it an impression of being fresh and updated regularly. In PHP, getting the current server date and time is a no brainer using the getdate() function.

To add date and time, see the PHP script below.

<html>
<head>
<title>DATE and TIME</title>
</head>

<body>
<?php
$date_array = getdate();
print "Server Date : $date_array[month] $date_array[mday], $date_array[year].<BR>";
print "Server Time : $date_array[hours]:$date_array[minutes]:$date_array[seconds]<BR>";
?>
</body>
</html>

Wednesday, February 27, 2008

Types of Looping Construct in Visual Basic

A loop is a sequence of instructions that is continually repeated until a certain condition is reached. It is a fundamental programming idea that is commonly used in writing programs. Without looping in a programming language, hundreds to thousands of repeated computer instructions would be time consuming, if not impossible to perform.

Here are the four types of looping construct in Visual Basic.

For Loop example
Private Sub ForLoop()
Dim intX As Integer

'-->INCREMENTING
For intX = 0 To 10
MsgBox "For Loop #" & intX, vbInformation, _
"Visual Basic Looping"
Next

'-->DECREMENTING
For intX = 10 To 0 Step -1
MsgBox "For Loop Step -1 #" & intX, vbInformation, _
"Visual Basic Looping"
Next
End Sub


Do While Loop example
Private Sub DoWhileLoop()
Dim intX As Integer

intX = 0
Do While intX < 10
MsgBox "Do While Loop #" & intX, vbInformation, _
"Visual Basic Looping"
intX = intX + 1
Loop
End Sub


While Wend Loop example
Private Sub WhileWendLoop()
Dim intX As Integer

intX = 0
While intX < 10
MsgBox "While Wend Loop #" & intX, vbInformation, _
"Visual Basic Looping"
intX = intX + 1
Wend
End Sub


Do Loop Example
Private Sub DoLoop()
Dim intX As Integer

intX = 0
Do
MsgBox "Do Loop #" & intX, vbInformation, _
"Visual Basic Looping"
intX = intX + 1
Loop While intX < 10
End Sub

Tuesday, February 26, 2008

PHP: How To Redirect To Another Website

Redirecting to another website in PHP is very simple and straightforward. Just by using the PHP header function and the the URL where to you want to redirect as a parameter, you can accomplish this task.

Here's the example below.
<html>

<header>
<title>PHP Redirection</title>
</header>

<body>

<?php
$url= "http://www.joelbadinas.com/";

/* Redirect browser */
header("Location: $url");

/* Make sure that code below does not
get executed when we redirect. */
exit;
?>

</body>

</html>


To use this script, just copy and paste it to your favorite PHP/HTML text editor, save it with a .php extension and put it in you web server. When you run it, you will be redirected to this blog.

Enjoy, and comments are welcome. (^_^)

Monday, February 25, 2008

How to Get The RGB of a Color Value in Visual Basic

This functions will returns the red, blue and green value of a color value.


'-->RETURNS THE RED COLOR VALUE
Private Function Red(ByVal Color As Long) As Integer
Red = Color Mod &H100
End Function

'-->RETURNS THE GREEN COLOR VALUE
Private Function Green(ByVal Color As Long) As Integer
Green = (Color \ &H100) Mod &H100
End Function

'-->RETURNS THE BLUE COLOR VALUE
Private Function Blue(ByVal Color As Long) As Integer
Blue = (Color \ &H10000) Mod &H100
End Function


Here's how to use this functions (see the image above for the result):

Private Sub Command1_Click()
MsgBox "Red: " & Red(Me.BackColor) & "," & vbNewLine & _
"Blue: " & Blue(Me.BackColor) & "," & vbNewLine & _
"Green: " & Green(Me.BackColor), _
vbInformation, "Form RGB Color"
End Sub

Thursday, February 21, 2008

How to Full Format Date in Visual Basic

This function shows how to full format date in Visual Basic 6.

Here's how to call the function: MsgBox FullFormatDate("02/24/1978")
The result will be: Friday, 24th Mar 1978

Public Function FullFormatDate(ByVal strDate As String) As String
Dim strDay As String

strDay = Format(strDate, "DD")
Select Case strDay
Case 1, 21, 31
strDay = Format(strDay, "#0") & "st"
Case 2, 22
strDay = Format(strDay, "#0") & "nd"
Case 3, 23
strDay = Format(strDay, "#0") & "rd"
Case Else
strDay = Format(strDay, "#0") & "th"
End Select

FullFormatDate = Format(strDate, "DDDD, ") & strDay & _
Format(strDate, " MMM YYYY")
End Function

Monday, February 11, 2008

Get Free Hosting Services at Tribuhost

Tribuhost is a website that offers free hosting services. At present, it is hosting two of my websites, Free Funny Jokes Collections and Online Recipe Collections, and so far, I am contented with there services. The support is fast and very helpful. Here's what Tribuhost offers:

- 250 MB disk space
- 6 GB Monthly transfer
- 5 MySQL databases
- 5 Add-on domains
- 5 Sub domains
- Vista Panel
- Automatic installer (29 scripts)
- Php 5
- FTP account
- File manager (browser upload)
- Web mail
- POP email accounts
- and more...

When you sign-up, you get a sub domain (ex: you.tribuhost.com) and you can create your website immediately. Also, a 468x60 banner ad is placed at the bottom of your website to cover the free hosting services - which I think is too little compared to the good service you get.

Sunday, February 10, 2008

Yahoo to Reject Microsoft's Plans to Buy the Internet Giant


Yesterday, reports came out the Yahoo plans to reject Microsoft's plans to buy the internet giant Yahoo.

Last February 1, Microsoft announced that it made an unsolicited offer to buy Yahoo for $44.6 billion, both in terms of cash and stocks. This is Microsoft's move to counter Google's an unstoppable superior status in the web.

The $44.6 billion bid, according to Yahoo's board, is way too low compared to it's current value.

Count the Forms Loaded in a Visual Basic Project

Sometimes you want to count the forms loaded in your Visual Basic project during runtime.


This simple and ready to use function will return the number of forms loaded in a project.

Public Function FormCount() As Long
Dim frmForm As Form
For Each frmForm In Forms
FormCount = FormCount + 1
Next
End Function


To use, just call the function like this.

MsgBox "# of forms loaded: " & FormCount

Saturday, February 09, 2008

My JoelBadinas.com Domain Is Not Working at the Moment

If you guys are wondering why joelbadinas.com is not working at the moment, it's because I am having issues with my registrar. For the meantime, this blog can be access via kabalweg.blogspot.com.

I'm already working to get my previous domain to work, unfortunately, it may take days before it will be back to normal. So please bear with me for the meantime.

Thursday, February 07, 2008

How to Flash a Minimized Form in the Taskbar Using API in Visual Basic

Here's a simple function to to flash a minimized form in the taskbar. It uses the FlashWindow API function and is written in Visual Basic

'-->API DECLARATION
Public Declare Function FlashWindow Lib "user32" (ByVal hWnd As Long, _
ByVal bInvert As Long) As Long

'-->THIS SUB WILL FLASH THE MINIMIZED FORM IN THE TASKBAR
Public Sub FlashForm(lngHandle As Long, _
Optional intCount As Integer = 1)
Dim intX As Integer

For intX = 0 To intCount
Call FlashWindow(lngHandle, True)
Next
End Sub

Wednesday, February 06, 2008

Free Online Recipes

Get free recipes at Free Online Recipes. This site features hundreds of free and practical yet mouth-watering recipes for homemakers, hobbyists and food enthusiasts or anybody who likes to cook. You can choose from several different recipe categories.

If you are a homemaker who don't know what dish to cook next for you family, a kitchen hobbyist who want to serve unique meals everyday, or just someone who would like to experiment something in the kitchen, this site is for you.

Drag PictureBox at Runtime in Visual Basic

The source codes below shows how you can drag a picturebox at runtime. To test this, copy and paste code to the declaration section of a form with a picturebox on it.

Private dblX As Double, dblY As Double
Private bolMove As Boolean

Private Sub cmdClose_Click()
Unload Me
End Sub

Private Sub Picture1_MouseDown(Button As Integer, _
Shift As Integer, _
X As Single, Y As Single)
If Button = 1 And Not bolMove Then
bolMove = True
dblX = X
dblY = Y
End If
End Sub

Private Sub Picture1_MouseMove(Button As Integer, _
Shift As Integer, _
X As Single, Y As Single)
Dim tmpy As Integer
Dim tmpx As Integer

If bolMove Then
If dblY > Y Then 'scroll up
tmpy = (dblY - Y) '* 100
Me.Picture1.Top = Me.Picture1.Top - tmpy
Else 'scroll down
tmpy = (Y - dblY) '* 100
Me.Picture1.Top = Me.Picture1.Top + tmpy
End If
If dblX > X Then 'scroll right
tmpx = (dblX - X) '* 100
Me.Picture1.Left = Me.Picture1.Left - tmpx
Else 'scroll left
tmpx = (X - dblX) '* 100
Me.Picture1.Left = Me.Picture1.Left + tmpx
End If
End If
End Sub

Private Sub Picture1_MouseUp(Button As Integer, _
Shift As Integer, _
X As Single, Y As Single)
bolMove = False
End Sub

Tuesday, February 05, 2008

Oracle PL/SQL Basics: A Simple Tutorial on Oracle PL/SQL

1. Using SQL-Plus

SQL-Plus is a query command line utility which has some powerful formatting capabilities.

Basic SQL-Plus Command
;                     Command line terminator
/ Execute the current batch of commands
SET SERVEROUTPUT ON Allow messages from PL-SQL to be displayed
SHOW ERRORS Show errors from last batch
EDIT Run editor, and load buffer
CLEAR BUFFER Clear buffer commands
& Prompt for value
@ Run commands in @filename


Prompt for process id, and kill
alter system kill session 'Victim';


Run commands in tables.sql
@tables.sql;


2. Creating a stored procedure

Below is a simple stored procedure which deletes an invoice.
Note:
- variable declaration placement
- the syntax for comments is /* --- */, or --
- ALL select statements must have an into statement for the result set. Oracle stored procedures must use "out" variables to return results to client programs.
- the declaration of INV_ID1 uses the column def as a prototype

CREATE OR REPLACE PROCEDURE PROC_DELETE_INVOICE(USERID1 VARCHAR2,
INV_ID1 INVOICE.INV_ID%TYPE) AS INV_COUNT NUMBER;
BEGIN
INV_COUNT := 0;
/* check if invoice exists */
SELECT COUNT(*) INTO INV_COUNT
FROM INVOICE WHERE INV_ID = INV_ID1;
IF INV_COUNT > 0 THEN
DELETE FROM INVOICE WHERE INV_ID = INV_ID1;
COMMIT;
END IF;
END;


3. Displaying output

All SELECT statements in PL-SQL must have an INTO clause; therefore another method is needed to display output to the console.

DBMS_OUTPUT.PUT_LINE('TEST OUTPUT');
salary := 24000;
dbms_output.put_line(salary);


4. Output variables

Output variables are used to return data to another procedure, or to an external application which has invoked the stored procedure.

Sample procedure header using output variables
TYPE INV_ARRAY IS TABLE OF NUMBER(8) INDEX BY BINARY_INTEGER;

CREATE OR REPLACE PROCEDURE PROC_GET_INV_NOS(
USERID1 IN VARCHAR2,
INV_IDS OUT INV_ARRAY)
AS . . .


5. Arrays and structures

Arrays and structures are implemented thought the use of "tables" and
"records" in PL-SQL.

Example of a simple record type
TYPE INVOICE_REC_TYPE IS RECORD(INV_ID   INVOICE.INV_ID%TYPE,
INV_DT INVOICE.INV_DT%TYPE);


Array declaration
TYPE NAME_TABLE_TYPE IS TABLE OF VARCHAR2(20) 
INDEX BY BINARY_INTEGER;
NAME_TABLE NAME_TABLE_TYPE;


Array subscripting
I := I + 1;
NAME_TABLE(I) := 'JSMITH';


6. Conditionals

Sample formats of conditional branching are given below:

IF statement
IF 'condition' THEN 'statement' ;


IF .. END IF statement
IF 'condition' THEN
'statements' ;
END IF;


IF .. ELSIF .. END IF statement
IF 'condition' THEN
'statements';
ELSIF 'condition' THEN
'statements';
END IF;


Sample statement, note the pipes for concatenation
IF (COUNT1 = 0) AND (COUNT2 > 0) THEN
RETMSG := 'Security attributes have not been assigned,
' || 'you are restricted.';
ELSE
RETMSG := 'You are OK';
END IF;


7. Looping

WHILE (I <>/* put command here */
I = I + 1;
END LOOP;


8. Packages

A package is a construct which bounds related procedures and functions together. Variables declared in the declaration section of a package can be shared among the procedures/functions in the body of the package.

Package
CREATE OR REPLACE PACKAGE INVPACK IS
/* function */
FUNCTION COUNTINV(SALESREP IN VARCHAR2) RETURN INTEGER;
/* procedure */
PROCEDURE PURGEINV(INV_ID IN INTEGER);
END INVPACK;


Package body
CREATE OR REPLACE PACKAGE BODY INVPACK IS
COUNT1 NUMBER;

/* function */
FUNCTION COUNTINV(SALESREP IN VARCHAR2) RETURN INTEGER IS
BEGIN
SELECT COUNT(*) INTO COUNT1
FROM INVOICE
WHERE SALES_REP_ID = SALESREP;

RETURN COUNT1;
END COUNTINV;

/* procedure */
PROCEDURE PURGEINV(INV_ID1 IN INTEGER) IS
BEGIN
DELETE FROM INVOICE WHERE INV_ID = INV_ID1;
END PURGEINV;
END INVPACK;


9. Cursors

Sample #1: This example depicts dbase-style row processing.
PROCEDURE PROC_SCAN_INVOICES(EXPIRE_DT IN DATE) IS
CURSOR INVOICE_CUR IS SELECT INV_ID, INV_DT FROM INVOICE;

TYPE INVOICE_REC_TYPE IS RECORD(INV_ID INVOICE.INV_ID%TYPE,
INV_DT INVOICE.INV_DT%TYPE);

INVOICE_REC INVOICE_REC_TYPE;
BEGIN
FOR INVOICE_REC1 IN INVOICE_CUR LOOP
IF INVOICE_REC.INV_DT <> EXPIRE_DT THEN
DELETE FROM INVOICE WHERE INV_ID = INV_REC.INV_ID;
DBMS_OUTPUT.PUT_LINE('INVOICE DELETETED:');
DBMS_OUTPUT.PUT_LINE(INV_REC.INV_ID);
END IF;
END LOOP;
END PROC_SCAN_INVOICES;


Sample #2: This example is a more traditional "fetch" approach.
PROCEDURE UPDATE_LOAD_CENTER_WORK_ORDER(
REC_NO IN MASTERTABLE.RECORDNUMBER%TYPE,
LCID IN MASTERTABLE.LC_NUMBER%TYPE,
WO_NO IN MASTERTABLE.WO_NUMBER%TYPE,
TRS_NO IN MASTERTABLE.TRS_NUMBER%TYPE) IS

CURSOR CURMAXID IS
SELECT MAX(RECORDNUMBER) + 1 FROM AMFM.GIS_LCWOMASTER;
NEXTRECNO MASTERTABLE.RECORDNUMBER%TYPE;

BEGIN
IF REC_NO = 0 THEN
OPEN CURMAXID;
FETCH CURMAXID
INTO NEXTRECNO;
CLOSE CURMAXID;
IF NEXTRECNO IS NULL THEN
NEXTRECNO := 1;
END IF;

INSERT INTO AMFM.GIS_LCWOMASTER A
(RECORDNUMBER, LC_NUMBER, WO_NUMBER, TRS_NUMBER, DATE_ENCODED)
VALUES
(NEXTRECNO, LCID, WO_NO, TRS_NO, SYSDATE);
ELSE
UPDATE AMFM.GIS_LCWOMASTER
SET LC_NUMBER = LCID, WO_NUMBER = WO_NO, TRS_NUMBER = TRS_NO
WHERE RECORDNUMBER = REC_NO;
END IF;
END UPDATE_LOAD_CENTER_WORK_ORDER;


Sample #3: This example returns a cursor. Note: Execute this two sample separately.
/* package declaration */
CREATE OR REPLACE PACKAGE load_center_pkg IS
TYPE refCursor IS REF CURSOR;

PROCEDURE get_all_transformers(pCursor OUT refCursor);
END load_center_pkg;

/* package body declaration */
CREATE OR REPLACE PACKAGE BODY load_center_pkg IS
PROCEDURE GET_ALL_TRANSFORMERS(PCURSOR OUT REFCURSOR) IS
BEGIN
OPEN PCURSOR FOR
SELECT A.XFORMER_ID,
A.PRIVATE_OWN,
A.PHASE, A.BRAND
FROM TRANSFORMER_MAST A;
END GET_ALL_TRANSFORMERS;
END load_center_pkg;


10. Exception Handling

The following block could appear at the end of a stored procedure:

EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('End of data !!);
WHEN OTHERS THEN
BEGIN
DBMS_OUTPUT.PUT_LINE('OTHER CONDITION OCCURRED !');
END;

Sunday, February 03, 2008

Gauss - Jordan Reduction Source Codes in C/C++

This program will process the matrix entered by the user to Reduced-Row Echelon Form. This method is known as Gauss-Jordan Reduction. I made this as a Midterm Project in Numerical Analysis.

NOTE: This is a complete and running C/C++ program.

#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <ctype.h>
#include <conio.h>
#include <string.h>
#define PAUSE 10000

/*++++++++++++++ FUNCTION DECLARATION ++++++++++++++++++++++++*/
void Main_Screen();
void Dimension();
void Enter_To_The_Matrix();
void About_The_Matrix();
void The_Programmer();
void Help_Topics();
void ProcessMatrix(float Matrix[10][10],int row,int col);
void SwapRow(float Matrix[10][10],int R1,int R2,int col);
void MultiplyRow(float Matrix[10][10],int R1,int R2,int col);
void MultiplyAddRow(float Matrix[10][10],int R1,int R2,int col);
void centerY(char *text,int y,int fore,int back);
void centerX(char text[],int x1,int y1,int fore,int back);
void box1(int x1,int y1,int x2,int y2,int fore);
void wall1(int x1,int y1,int x2,int y2,int fore,int back);
void shadow(int x1,int y1,int x2,int y2,int fore,int back);

/*++++++++++++++ GLOBAL VARIABLES ++++++++++++++++++++++++++++*/
char ans, buffer[10], rowBuf[10], colBuf[10];
int x, y, z, X, Y, Z, check1,check2;
float matrix[10][10], InputBuf, row, col, num;

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

/*########### S T A R T of M A I N #########################*/
void main()
{
while(1 == 1)
{
Main_Screen();
ans=0;
while(ans!='1' && ans!='2' && ans!='3')
{
ans = getch();
}
switch(ans)
{
case 49: Dimension(); break;
case 50: About_The_Matrix(); break;
case 51: exit(0);
}
}
}

void Dimension()
{
shadow(20,10,66,20,8,0); wall1(18,9,64,19,3,3);
box1(18,10,63,17,8); box1(28,12,52,16,8);
centerY(" I n s i d e t h ‚ M … t r i x ",10,15,4);
centerY("Dimension",12,0,3);
while(1 == 1)
{
centerY(" x ",14,14,1);
gotoxy(37,14); gets(rowBuf); row = atof(rowBuf);
gotoxy(43,14); gets(colBuf); col = atof(colBuf);
gotoxy(44,14);
if(row > 0 && row < 6 && col > 1 && col < 7 )
{
break;
}
}
Enter_To_The_Matrix();
}

void Enter_To_The_Matrix()
{
char label[]="ABCDE";
ans=0;
while(ans != 'N')
{
shadow(10,4,76,24,8,0); wall1(8,3,74,23,7,7); box1(8,4,73,21,8);
box1(10,10,47,20,9); box1(48,6,71,20,1);
centerY(" I n s i d e t h ‚ M … t i x ",4,10,4);
centerX("Gauss-Jordan Reduction", 60,6,14,1);
centerX("Enter elements :", 19,9,0,7);
for(x=0 ; x<row ; x++)
{
for(y=0,z=0 ; y<col ; y++,z=z+6)
{
if(y < col-1)
{
textattr(14+(4<<4));
gotoxy(12+z,11); cprintf(" %c ",label[y]);
}
while(1 == 1)
{
centerX(" ",30,9,14,1);
gotoxy(29,9); gets(buffer);
InputBuf = atof(buffer);
if(InputBuf < 100 && InputBuf > -100)
{
break;
}
}
if(y == col-1)
{
label[y] = ' ';
}
matrix[x][y] = InputBuf; textattr(0+(7<<4));
gotoxy(12+z,13+x); cprintf("%.0f%c",matrix[x][y],label[y]);
}
}
ProcessMatrix(matrix,row,col);
centerX("Again? (Y/N)", 15,22,1,7);
ans=0;
while(ans != 'Y' && ans != 'N' && ans != 27)
{
ans = toupper(getch());
}
if(ans == 'N')
{
return;
}
if(ans == 'Y')
{
Dimension();
}
if(ans == 27)
{
return;
}
}
}

void ProcessMatrix(float Matrix[10][10],int row,int col)
{
char label[]="ABCDE";
X=0;Y=0;Z=1;
while(X<row)
{
for(x=X;x<row;x++)
{
if(Matrix[x][Y] == 1)
{
SwapRow(Matrix,x,Y,col);
}
}
if(Matrix[X][Y] == 0)
{
for(x=X;x<row-1;x++)
{
if(Matrix[x][Y] != 0)
{
SwapRow(Matrix,x,Y,col);
}
}
}
MultiplyRow(Matrix,X,Y,col);
for(y=Z;y<row;y++)
{
MultiplyAddRow(Matrix,y,Y,col);
}
X++;Y++;Z++;
}
for(Z=1;Z<6;Z++)
{
X=0;Y=Z;
while(X<row)
{
MultiplyAddRow(Matrix,X,Y,col);
X++;Y++;
}
}
for(y=0;y<col-1;y++)
{
check1=0;
if(y==col-2)
{
for(x=0;x<col;x++)
{
if(Matrix[row-1][x]==0)
{
check1++;
}
}
}
check2=0;
if(check1==col && row<col)
{
check2=1;
centerX("Ä> Has infinitely many solution!",29,19,4,7);
}
if(col>=row+2)
{
check2=1;
centerX("Ä> No possible solution! ",29,19,4,7);
}
}
for(y=0,z=0;y<col-1;y++,z=z+2)
{
textattr(15+(4<<4));
gotoxy(50,9+z); cprintf(" %c ",label[y]);
textattr(8+(7<<4));
gotoxy(54,9+z); cprintf("=");
if(check2==0)
{
textattr(0+(7<<4));
gotoxy(56,9+z); cprintf(" %.1f ",Matrix[y][col-1]);
}
}
for(x=0;x<row;x++)
{
for(y=0,z=0;y<col;y++,z=z+6)
{
textattr(0+(7<<4));
gotoxy(12+z,13+x); cprintf(" ");
gotoxy(12+z,13+x); cprintf("%.1f",Matrix[x][y]);
}
}
}

void SwapRow(float Matrix[10][10],int R1,int R2,int col)
{
float buffer[10];
for(x = 0; x < col; x++)
{
buffer[x] = Matrix[R1][x];
Matrix[R1][x] = Matrix[R2][x];
matrix[R2][x] = buffer[x];
}
}

void MultiplyRow(float Matrix[10][10],int R1,int R2,int col)
{
if(Matrix[R1][R2] == 0)
{
return;
}
num = (1 / Matrix[R1][R2]);

for(x = 0; x < col; x++)
{
Matrix[R1][x] = Matrix[R1][x] * num;
}
}

void MultiplyAddRow(float Matrix[10][10],int R1,int R2,int col)
{
float buffer[10];
num = Matrix[R1][R2];
if(num!=0)
{
num = num*(-1);
}
for(x = 0; x < col; x++)
{
buffer[x] = Matrix[R2][x];
buffer[x] = buffer[x] * num;
Matrix[R1][x] = Matrix[R1][x] + buffer[x];
}
}

void About_The_Matrix()
{
while(1 == 1)
{
shadow(14,6,72,20,8,0); wall1(12,5,70,19,3,3);
box1(12,6,69,18,8); shadow(18,9,68,18,8,0); wall1(16,8,66,17,4,4);
centerY(" A B O U T t h ‚ M … t r i x ",6,15,4);
centerX(" 1 ", 30,10,14,9);
centerX(" 2 ", 51,10,14,9);
centerX(" 3 ", 40,13,14,9);
centerX("The Programmers", 30,11,15,4);
centerX("Help Topics", 51,11,15,4);
centerX("Return To Main Menu", 40,14,15,4);
ans=0;
while(ans != '1' && ans != '2' && ans != '3'&& ans != 27)
{
ans = toupper(getch());
}
switch(ans)
{
case 49: The_Programmer(); break;
case 50: Help_Topics(); break;
case 51: return;
case 27: return;
}
}
}

void The_Programmer()
{
while(1 == 1)
{
shadow(10,4,76,24,8,0); wall1(8,3,74,23,7,7); box1(8,4,73,21,8);
centerY(" T h e P r o g r a m m e r s ",4,10,4);
centerY("Joel Badinas",8,0,7);
centerY("Michelle Claridad",9,0,7);
centerY("Dan Virgel Ratilla",10,0,7);
centerY("Frederick Jhun Layno",11,0,7);
centerY("ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ ",13,6,7);
centerY("The programmers are 3rd year students of",15,0,7);
centerY("the University of Southeastern Philippines taking up",16,0,7);
centerY("Bachelor of Science in Computer Science.",17,0,7);
centerX("<Esc> to cancel", 16,22,1,7);
while(ans != 27)
{
ans = getch();
}
if(ans == 27)
{
return;
}
}
}

void Help_Topics()
{
while(1 == 1)
{
shadow(10,4,76,24,8,0); wall1(8,3,74,23,7,7); box1(8,4,73,21,8);
centerY(" H e l p T o p i c s ",4,10,4);
centerX("This program will process the matrix entered by the user ",41,8,0,7);
centerX("to Reduced-Row Echelon Form(R.R.E.F.). This method is ",41,9,0,7);
centerX("known as Gauss-Jordan Reduction. The program will display ",41,10,0,7);
centerX("the result of the operation or the value corresponding the",41,11,0,7);
centerX("letter. ",41,12,0,7);

centerX("Please be guided that the dimension of the matrix the ",41,14,0,7);
centerX("program will accept must have a minimum of '1 x 2' and ",41,15,0,7);
centerX("a maximum of '5 x 6'. Also, the value of each element ",41,16,0,7);
centerX("should not be greater than '100'. ",41,17,0,7);

centerX("<Esc> to cancel", 16,22,1,7);
while(ans != 27)
{
ans = getch();
}
if(ans == 27)
{
return;
}
}
}

void Main_Screen()
{
textattr(1+(1<<4));
clrscr(); box1(1,1,80,24,7);
centerY("th‚ M…trix",2,10,1);
centerY(" Copyright(c) 2002 ",3,14,1);
centerY(" A Midterm Project in Numerical Analysis ",4,15,1);
centerY(" Submitted on February 2002 ",5,15,1);
textattr(13+(1<<4));
gotoxy(12,9); cprintf(" Û Û Üß ");
gotoxy(12,10); cprintf(" ÜÜÛÜ ÛÜÜÜ ÜÜÜÜ ");
gotoxy(12,11); cprintf(" Û Û Û ÛÜÜÛ ");
gotoxy(12,12); cprintf(" ÛÛ ÛÛ Û ÛÜÜÜ ");
gotoxy(12,13); cprintf("ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ¿");
textattr(10+(1<<4));
gotoxy(29,8); cprintf(" ÛÛÛÜ ÜÛÛÛ Ü ÛÛ ");
gotoxy(29,9); cprintf(" ÛÛÛÛÛ ÛÛÛÛÛ ß ßßÛÛßß ");
gotoxy(29,10); cprintf(" ÛÛÛ Û Û ÛÛÛ ßßßßÜ ÛÛ Û Üßß Ü ÛÜ ÜÛ ");
gotoxy(29,11); cprintf(" ÛÛÛ ÛÛÛ ÛÛÛ ÜßßßÛ ÛÛ Ûß Û ßÛÜÜÛß ");
gotoxy(29,12); cprintf(" ÛÛÛ ß ÛÛÛ Þ Û ÛÛ Û Û ÛÛ ");
gotoxy(29,13); cprintf(" ÛÛÛ ÛÛÛ ßÜÜßÛ ÛÛ Û Û ÜÛßßÛÜ ");
gotoxy(28,14); cprintf("ÀÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄßßÄÄÄÄßßÄ ");
textattr(12+(1<<4));
gotoxy(57,8); cprintf(" Ü ");
gotoxy(57,9); cprintf("ßÜß");
centerY(" G A U S S - J O R D A N R E D U C T I O N ",15,4,2);
wall1(5,17,77,24,7,1);
wall1(10,18,30,22,4,4); wall1(32,18,50,22,4,4); wall1(52,18,72,22,4,4);
shadow(12,19,32,23,8,0); shadow(34,19,52,23,8,0); shadow(54,19,74,23,8,0);
centerX(" 1 ", 20,19,14,9);
centerX(" 2 ", 41,19,14,9);
centerX(" 3 ", 62,19,14,9);
centerX(" E N T E R ", 20,20,15,4);
centerX(" A B O U T ", 41,20,15,4);
centerX(" Q U I T ", 62,20,15,4);
centerX("Type number to select", 12,25,14,1);
centerX("D rkm…n", 76,25,3,1);
}

/*################ E N D ##################################*/




/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
void centerX(char text[],int x1,int y1,int fore,int back)
{
int x;
textattr(fore+(back<<4));
x = (x1 - ((x1-x1)/2)) - (strlen(text)/2);
gotoxy(x,y1); cprintf("%s",text);
}
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
void centerY(char *text,int y,int fore,int back)
{
textattr(fore+(back<<4));
gotoxy(40-strlen(text)/2,y);cprintf("%s",text);
}
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
void box1(int x1,int y1,int x2,int y2,int fore)
{
int i; textcolor(fore);
for(i=x1;i<x2;i++) {
gotoxy(i,y1);cprintf("Ä");
gotoxy(i,y2);cprintf("Ä"); }
for(i=y1;i<y2;i++) {
gotoxy(x1,i);cprintf("³");
gotoxy(x2,i);cprintf("³"); }
gotoxy(x1,y1);cprintf("Ú");
gotoxy(x2,y1);cprintf("¿");
gotoxy(x1,y2);cprintf("À");
gotoxy(x2,y2);cprintf("Ù");
}
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
void wall1(int x1,int y1,int x2,int y2,int fore,int back)
{
int i,j;
for(j = y1; j < y2; j++) {
for(i = x1;i < x2; i++) {
gotoxy(i,j); textattr(fore+(back<<4)); cprintf("°");} }
}
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
void shadow(int x1,int y1,int x2,int y2,int fore,int back)
{
int i,j;
for(j = y1; j < y2; j++) {
for(i = x1;i < x2; i++) {
if(i+2 >= x2 || j+1 >= y2) {
gotoxy(i,j); textattr(fore+(back<<4)); cprintf("°"); } } }
}
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/


/*+++++++++++++ E X C E S S +++++++++++++++++++++++++++++++*/
/*X=0;Y=1;
while(X<row)
{
MultiplyAddRow(Matrix,X,Y,col);
X++;Y++;
}
X=0;Y=2;
while(X<row)
{
MultiplyAddRow(Matrix,X,Y,col);
X++;Y++;
}

X=0;Y=3;
while(X<row)
{
MultiplyAddRow(Matrix,X,Y,col);
X++;Y++;
}*/
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

Thursday, January 31, 2008

How to Get the File Information Using API in Visual Basic

This function takes a passed filename as an argument and returns the description of that file. For example, if you pass the filename "c:\windows\sys.com" to the function, it will return the string "MS-DOS Application". If the file doesn'texist, it will return a blank type information.

NOTE: To see the result, copy and paste the code below in the
declaration section of a form.

'Constants declaration
Const SHGFI_DISPLAYNAME = &H200
Const SHGFI_TYPENAME = &H400
Const MAX_PATH = 260
Private Type SHFILEINFO
hIcon As Long ' out: icon
iIcon As Long ' out: icon index
dwAttributes As Long ' out: SFGAO_ flags
szDisplayName As String * MAX_PATH ' out: display name (or path)
szTypeName As String * 80 ' out: type name
End Type

'API declaration
Private Declare Function SHGetFileInfo Lib "shell32.dll" Alias _
"SHGetFileInfoA" (ByVal pszPath As String, _
ByVal dwFileAttributes As Long, _
psfi As SHFILEINFO, ByVal cbFileInfo As Long, _
ByVal uFlags As Long) As Long

'Gets the information of the file passed to it
Private Function GetFileInfo(strFileName) As SHFILEINFO
Dim lngRetVal As Long
Dim fileInfo As SHFILEINFO

lngRetVal = SHGetFileInfo(strFileName, 0, fileInfo, Len(fileInfo), _
SHGFI_DISPLAYNAME Or SHGFI_TYPENAME)
GetFileInfo = fileInfo
End Function

'This fucntion is used to strip al the unnecessary chr$(0)'s
Private Function StripTerminator(sInput As String) As String
Dim ZeroPos As Integer
'Search the position of the first chr$(0)
ZeroPos = InStr(1, sInput, vbNullChar)
If ZeroPos > 0 Then
StripTerminator = Left$(sInput, ZeroPos - 1)
Else
StripTerminator = sInput
End If
End Function

Private Sub Form_Load()
Dim fileInfo As SHFILEINFO

fileInfo = GetFileInfo("c:\autoexec.bat")
MsgBox "Displayname: " & StripTerminator(fileInfo.szDisplayName) & _
vbNewLine & _
"Typename: " & StripTerminator(fileInfo.szTypeName)
End Sub

Tuesday, January 29, 2008

Cut, Copy, Paste and Delete Using the Clipboard Object Source Codes in Visual Basic

Are you having difficulty in doing Cut, Copy, Paste and Delete of texts routines in Visual Basic? Well, settle down now.

This source codes shows the CUT, COPY, PASTE and DELETE routines using the Clipboard object. This source codes assumes that you have four commandbutton controls (EditCut, EditCopy, EditPaste and EditDelete) in your Visual Basic project

Private Sub EditCut_Click()
'Clear the contents of the Clipboard.
Clipboard.Clear
'Copy selected text to Clipboard.
Clipboard.SetText Screen.ActiveControl.SelText
'Delete selected text.
Screen.ActiveControl.SelText = ""
End Sub

Private Sub EditCopy_Click()
'Clear the contents of the Clipboard.
Clipboard.Clear
'Copy selected text to Clipboard.
Clipboard.SetText Screen.ActiveControl.SelText
End Sub

Private Sub EditPaste_Click()
'Place text from Clipboard into active control.
Screen.ActiveControl.SelText = Clipboard.GetText()
End Sub

Private Sub EditDelete_Click()
'Delete selected text.
Screen.ActiveControl.SelText = ""
End Sub

Monday, January 28, 2008

How to Handle Control Arrays with Index Holes in Between in Visual Basic

Here's simple tutorial on how you can handle control arrays with index holes in between.

Control array is one of the best feature of Visual Basic. However, this can cause runtime errors if you are not careful, especially if they have missing elements or index in between.

To handle control arrays with sequence index, you can use this method.

Dim intX as integer
For intX = Text1.LBound to Text1.UBound
MsgBox Text1(intX).Text
Next


However, if they have holes in between them (Ex: Text1(0), Text1(1), Text1(3), Text1(4)), the above method spits an error. To avoid that situation, treat the array like a collection as below.

Dim txt as TextBox
For Each txt In Text1
MsgBox txt.Text
Next txt


That's it. Tamed control arrays. (^_^)

Sunday, January 27, 2008

Oracle DDL Basics: A Simple Tutorial on Oracle Data Definition Language

Here's a simple tutorial on Oracle Data Definition Language. I always make this handy at the office as I sometimes forget some of the basis of the Oracle DDL.

1. Data Type.

Type                Storage     Range/Length
----------------- ---------- --------------
NUMBER 16 40 digit floating point
FLOAT 16 40 digit floating point
SMALLINT 16 40 digit floating point
NUMBER(a,b) varies a digits, b precision
FLOAT(a,b) varies a digits, b precision
DECIMAL 16 40 digit
INTEGER 16 40 digits
INTEGER(a) varies a digits
CHAR(a) a a=(1-255)
VARCHAR(a) varies 1 - 255
VARCHAR2(a) varies 1 - 2000
DATE 8 1/1/4217BC - 12/31/4712AD
LONG varies 0 - 2 GB
LONG RAW varies 0 - 2 GB
LONG VARCHAR varies 0 - 2 GB
BLOB varies 0 - 4 GB
CLOB varies 0 - 4 GB
NCLOB varies 0 - 4 GB
BFILE ?? ??
ROWID 8 n/a


* Long datatypes are discouraged in Oracle 8.
Note that are long and blob datatypes are incompatible.

2. Creating a Table.

PCTFREE = Amount of space to leave in block during insert operations. Allows room for records to grow within the same area.
PCUSED = The threshold at which the block is placed back on the free block list.
INITIAL/NEXT = The initial disk allocated, and the next extent size.
LOGGING = Indicates whether operations are written to the redo logs.

CREATE TABLE EMPLOYEE (
EMP_ID NUMBER(8),
LNAME VARCHAR2(30),
FNAME VARCHAR2(15),
HIRE_DT DATE,
SALARY NUMBER(8,2) )

PCTFREE 20
PCTUSED 50
STORAGE (INITIAL 200K NEXT 200K PCTINCREASE 0 MAXEXTENTS 50 )
TABLESPACE ts01 LOGGING;


3. Creating indexes

CREATE UNIQUE INDEX EMP_IDX ON EMPLOYEE (EMP_ID);


/* index create - table has sorted data */
CREATE UNIQUE INDEX IDX_INVOICE_ITEMS   ON INVOICE_ITEMS
(INVOICE_ID,YEAR,FREQ_CODE,FREQ_NUMBER,FIELD_NUMBER,RECORD_SEQ)
TABLESPACE TS_07
NOLOGGING
NOSORT;


/* create index - constraint */
ALTER TABLE  INVOICE_FORMAT
ADD CONSTRAINT PK_INVOICE_FORMAT PRIMARY KEY(INVOICE_ID)
USING INDEX TABLESPACE PROD_IDX_01;


/* Get index information */
SELECT A.COLUMN_NAME,
A.COLUMN_POSITION,
A.INDEX_NAME,
B.UNIQUENESS
FROM USER_IND_COLUMNS A,
USER_INDEXES B
WHERE A.INDEX_NAME = B.INDEX_NAME AND
A.TABLE_NAME = 'IDX_INVOICE_ITEMS'
ORDER BY A.INDEX_NAME, A.COLUMN_POSITION;


/* create bitmap index - table is fairly static, and has less than 1000 distinct values in the indexed column */
CREATE BITMAP INDEX BIX_INVOICE_ARCHIVE
ON INVOICE_ARCHIVE (SALES_ID)
TABLESPACE PROD_IDX_01;


4. Creating constraints

/* primary key constraint */
ALTER TABLE EMPLOYEE (
CONSTRAINT EMP_PK
PRIMARY KEY (EMP_ID));


ALTER TABLE  REPORT_FORMAT
ADD CONSTRAINT PK_REPORT_FORMAT PRIMARY KEY(REPORT_ID)
USING INDEX TABLESPACE PROD_IDX_01;


/* foreign key constraint */
ALTER TABLE EMPLOYEE ADD (
CONSTRAINT EMP_LOC_ASSIGN_FK
FOREIGN KEY (EMP_ID,
LOC_CD)
REFERENCES LOC_REGISTRY (
EMP_ID,
LOC_CD));


5. Creating and using a sequence.

/* create a sequence for employee ids */
CREATE SEQUENCE EMP_ID_SEQ
INCREMENT BY 1
NOMINVALUE
NOMAXVALUE
NOCYCLE
CACHE 20
NOORDER ;


/ * use the next emp id, and increment the sequence */
INSERT INTO EMPLOYEE(EMP_ID, LNAME, FNAME)
VALUES (EMP_ID_SEQ.NEXTVAL, 'SMITH', 'JIM');


/* get the current value of the sequence */
INSERT INTO EMPLOYEE(EMP_ID, LNAME, FNAME)
VALUES (EMP_ID_SEQ.CURRVAL, 'SMITH', 'JIM');


6. Creating triggers.

The example below illustrates versioning of the EMP_RESUME table, which contains a blob field.

CREATE OR REPLACE TRIGGER EMP_RES_INS_TR
AFTER INSERT ON EMP_RES
FOR EACH ROW
DECLARE
VER1 NUMBER ;
EBLOB BLOB ;
VBLOB BLOB ;
BEGIN
EBLOB := EMPTY_BLOB();

SELECT (COUNT(*) + 1) INTO VER1
FROM VEMP_RES
WHERE EMP_ID =:NEW.EMP_ID ;

VBLOB := :NEW.RESUME ;

INSERT INTO VEMP_RES
( EMP_ID, DOC_URL,
A_USERID, D_MODIFIED, VER_NO, RESUME)
VALUES (
:NEW.EMP_ID, :NEW.DOC_URL,
USER, SYSDATE, VER1, EBLOB ) ;

SELECT RESUME
INTO EBLOB
FROM VEMP_RES
WHERE EMP_ID =:NEW.EMP_ID AND
VER_NO = VER1
FOR UPDATE ;

UPDATE VEMP_RES
SET RESUME = VBLOB
WHERE EMP_ID =:NEW.EMP_ID AND
VER_NO = VER1 ;
END;



7. Renaming a table.

RENAME EMPLOYEE TO MANAGER;


8. Synonyms and Database Links.

/* Synonym Creation */
GRANT SELECT ON USER5.COMPANY TO USER6 ;
CREATE SYNONYM USER6.COMPANY5 FOR USER5.COMPANY;


/* Database Link */
CREATE DATABASE LINK ARCHIVE_DATA CONNECT TO
USER5 IDENTIFIED BY TIGER USING 'SERVER5';


/* user within this system can now reference tables using ARCHIVE_DATA.tablename */

9. Changing a column's type or name.

/*Change Type*/
ALTER TABLE CORPORATION MODIFY (COMPANY_NM VARCHAR2(100));


ALTER TABLE employee MODIFY(last_name varchar2(40));


/*Change Name*/
ALTER TABLE EMPLOYEE RENAME COLUMN LAST_NAME TO LNAME;


10. Moving a table.

ALTER TABLE COMPANY MOVE
STORAGE (
INITIAL 200K
NEXT 200K
PCTINCREASE 0
MAXEXTENTS 50 )
TABLESPACE TS_01;


11. Partitioned Tables.

Table partitioning is the best feature ever added to the Oracle RDBMS.
Chunks of data can be appended, replaced, or purged very easily when
using table partitioning. When you have more than 20 million rows in a
non-static table, partitioning is recommended. We found that bitmap
indexes work better than standard indexes on partitioned tables.

/*Add a partition*/
ALTER TABLE PHONE_DATA ADD PARTITION
p2004JUL VALUES (200407) TABLESPACE TS01 ;


/*Populate a partition, replaces existing data, if it exists*/
ALTER TABLE PHONE_DATA EXCHANGE PARTITION
p2004JUL WITH TABLE TMP_SWITCH_DATA ;


/*Move a partition*/
ALTER TABLE PHONE_DATA MOVE PARTITION 
P2004JUL TABLESPACE TS01 NOLOGGING;


/*Truncate a partition*/
ALTER TABLE PHONE_DATA TRUNCATE PARTITION;


/*Drop a partition*/
ALTER TABLE PHONE_DATA DROP PARTITION p2004JUL 
update global indexes;


/*Get partition information*/
SET PAGESIZE 0
SET LINESIZE 120
SELECT TABLE_NAME, PARTITION_NAME, BLOCKS, TABLESPACE_NAME
FROM USER_TAB_PARTITIONS
ORDER BY TABLE_NAME, PARTITION_NAME;


/*Create a local partition index*/
CREATE BITMAP INDEX BIX_PHONE_DATA ON PHONE_DATA
(PERIOD_KEY)
TABLESPACE TS02
LOCAL;


/*Rebuild*/
ALTER TABLE PHONE_DATA MODIFY PARTITION
p2004JUL REBUILD UNUSABLE LOCAL INDEXES;

Recent Post