Ethelcofie’s How To Articles

October 6, 2008

Ethelcofie’s how to articles has Moved

Ethelcofie’s how to articles has moved to http://blog.ethelcofie.com/

I thought it would be better to have all my  stuff in one place 

Cheers 

Advertisements

September 15, 2008

Program for simulation of mutual exclusion with the use of semaphores

Program for simulation of mutual exclusion with the use of semaphores

PROBLEM DESCRIPTION

In operating systems the problem of mutual exclusion is very often encountered because of multiple processes that access, modify certain shared resources such as data structures .The operating system need to ensure that these shared data structures are not accessed and modified by multiple processes at the same time causing incorrect results for the processes involved. One of the solutions to the problem of mutual exclusion is to use semaphores which as defined by http://encyclopedia.thefreedictionary.com as a protected variable (or abstract data type) and constitutes the classic method for restricting access to shared resources (e.g. storage) in a multiprogramming environment.

Semaphores have two basic functions, P():checks if critical section is filled then blocks or allows process as appropriate() function: checks when a process leaves critical section and removes it from semaphore queue.

The semaphores are used to implement these rules: to at most one process uses the shared data structure at a time (critical section) and all processes get their turn with the shared resource

PROGRAM DESCRIPTION

This java program simulates the use mutual exclusion using semaphores. The program involves four processes named process 1,2,3,4 who are competing for critical sections A,B,C,D,E,F,G. with a semaphore A for critical section A,sem Z for B,semC for B,sem D for section E, ,sem F for section F and lastly sem G for section G .

The simulation program implements mutual exclusion by implementing these three rules:

1. At most one process may execute in the critical section a time i.e. all processes that request a critical section that is occupied are denied request and are to wait.

2. Request to enter and exit a critical section is eventually succeed: All processes that have made a request for a critical section may be denied a request initially but after a wait will get into the critical section when it is available.

3. Critical section request are prioritized on First come first served basis

HOW PROGRAM WORKS

The program simulates a random request by any number of the processes for any of critical sections and implements the management of these process request using mutual exclusion rules stated above.

The program works by creating four processes, then creating 7 semaphores along corresponding to the 7 critical sections. The implements a P function whose primary task is to check when a process makes critical section request using the counter variable whether or not the critical section is occupied if it is it blocks the process until critical section is vacant else removing process from process queue and adding it to the semaphore queue

The program also implements the V function whose primary duty is to check for a process leaving a critical section decrease counter value flagging the critical section as vacant .This is implemented after a process sends a message of leaving the process

ALGORITHM

Create Processes

Create all 7 critical sections

Create corresponding semaphores for each critical section

If for a process request for a critical section

Then

Check if semaphore counter >0

Refuse permission to enter section for process and request process to hold till critical section if available

Add process to semaphore queue

If semaphore counter =0

Then

Grant permission to enter the critical section

Remove process from semaphore queue

If process sends an acknowledgement to leave the critical section

Then

Decrease semaphore counter

DRAWING OF A SCENARIO OF THE MUTUAL EXCLUSION SIMULATION PROGRAM

DRAWING OF A SCENARIO OF THE MUTUAL EXCLUSION

DRAWING OF A SCENARIO OF THE MUTUAL EXCLUSION

SCREEN SHOT OF MUTUAL EXCLUSION INVOLVING FOUR PROCESSES AND 7 CRITICAL SECTIONS AND THEIR METAPHORS

August 31, 2008

My Motivation for choosing a Career in Information Technology

 I found a draft of my Graduate School Essay and it makes me  realise that my  reasons for starting a Bsc in Computer Science as a perlude to  career in IT still holds true today : enjoy

ETHEL DELALI COFIE
SUPPORTING STATEMENT

The computer is dumb;
I am smart and the computer is only as smart as the one who writes its logic.
These were the thoughts that crossed my mind as I sat in my first programming class along with another thought “am I sure I understand correctly what this lecturer is saying”.
I had signed up for this computer training class after my secondary school education to learn for the first time in my life about computers and how they worked and my first class had succeeded in revolutionizing the way I thought of computers.
I begun think to myself, well this computer stuff isn’t that bad after all and then mentally put it on the list of my career options I was considering at the time. After 6 months of the computer training course, I decided that a career in computing was what I wanted; I therefore applied to Valley View University to pursue a BSc course in Computer science.

I was the unofficial Class President during my years in the university given that I was always the one who would organize and rally the class to complete tasks.
To further illustrate; The course work for the Expert system course included developing six expert system modules individually using the Knowledge Wright development platform from about a hundred pages of system requirement documents. I rallied the class and we decided that different groups of students would analyze and develop one system each, and make a presentation to the class for approval and onward dissemination, cutting down the effort and time needed to develop the system individually and enabling all of us to get much needed sleep.

In the University I took a semester’s course in distributed systems but I really developed interest in the subject area after taking an internet based applications course. Learning about object oriented client based systems,J2EE,Corba,Ole/ActiveX ,the concept of autonomous computers working together but seeming as one coherent system and the connectivity offered by the internet I realized there was limitless possibilities in this subject area.
I became fascinated for instance by the idea of developing a system connecting a company’s geographically dispersed sites as well as thousands of sales representatives which would effectively manage sales ,billing ,stock control ,delivery and order tracking all in real time .
This fascination led me to develop for my final year project a java based Client Server system for electoral data collation and statistic generation. This software is part of the few projects selected to be showcased in Valley View University’s annual press exhibition to be held in March 2006.

During my years in the university I endeavoured to acquire knowledge not only in the classroom but also in industry:
My first year summer break was spent as an intern in Softtribe one of West Africa foremost software houses. There I worked developing modules in C++ and Java for their major systems being developed at the time.

The second year summer break saw me studying French because I believe that to be successful you need to be internationally competitive.
During my third year summer break I became an intern at INIIT a computing research and development firm. After that summer I stayed on and worked part-time through to my final year and then after Graduation went on to work with them fulltime.
At INIIT, I initially worked on web applications using PHP and JavaScript, and then moved to system analysis and design.

I am presently the project leader involved in developing a Client Server System which will be accesses via the intranet using Visual basic and SqlServer and I also represented my organisation in an ICT, telecommunication and media convergence conference in Cotonou –Benin (West-Africa) in February 2006. This conference was organized by the Panos Institute West Africa ( CIPACO project), in collaboration with the Haute Autorité de l’Audiovisuel et de la Communication (HAAC) of Benin, the African Communication Regulation Authorities Network (ACRAN) and the West African Telecommunications Regulators Association (WATRA).
I was also part of the writing of the Cotonou Appeal on the Regulation of Convergence the document adopted at the conference.

I aim not only to develop more systems with a bias towards distributed systems and gradually move into the management of my own multinational computing firm and this has influenced my choice to study for an MSc in Distributed Systems Integration at De Montfort University.
This is because after a critical look at the course modules being offered I realised that there is the right blend of technical, management and e-business modules to give me the relevant skills, up-to-date tools and knowledge not only to be technologically savvy but also for management also because as stated in the prospectus the course was designed in conjunction with industry.

Ps : I didn’t end up going to De Montfort though they offered me a place ,
I went to Brighton University because they offered me a scholarship and they were by the sea
I do have my Msc in Distributed Systems now and everyday i happily work on a variety distributed Systems  be it a financial sysytem or a booking system

August 27, 2008

How to Write to create a Lightbox Effect with Div’s and Javacript

Filed under: Development Articles — ethelcofie @ 1:03 pm
Tags: , ,

How to Write to create a Lightbox Effect with Div’s and Javacript

The tutorial shows a the light box effect and the use of iframes (changing the src target of the iframe)
A quick and easy snipper of code with minimal hassle

1.The Html Code

<html>
<head>Light Box Effect </head>
<body>
<!–image that onclick triggers the light box effect –>
<img src=”Box.jpg” name=”Box Image” onclick=’LightEffect(“http://www.flickr.com/&#8221;)’/>

<!–Div which will show light box effect –>
<div id=’light’ class=’white_content’ style=”>
<a href=’javascript:void(0)’ onclick=’CloseFrame();’>Close</a> <!–Close button –>
<iframe id=’pictureframe’ src=” width=’800′ height=’800′> </iframe></div>”; <!–iframe –>
</div>
<!–div the causes fade shadow ovwe web page –>
<div id=’fade’ class=’black_overlay’>
</div>
</body>
</html>

2.Then the Javascript function that display lightbox effect .

function LightEffect(source)
{
// new url retrieved
var url =source;

// new iframe url set
parent.document.getElementById(“pictureframe”).src=url;

// make lightframe div visible
document.getElementById(“light”).style.display=’block’;

//fadeout web page
document.getElementById(“fade”).style.display=’block’;
}

3.Then the function that closes the lighbox

function CloseFrame()
{
// iframe url removed
parent.document.getElementById(“pictureframe”).src=”;

//make lightframe div not visible
document.getElementById(“light”).style.display=’none’;

//remove fade from web page
document.getElementById(“fade”).style.display=’none’;
}

4. The CSS section (to be out in seperate css document or within the html in the head section )

.black_overlay{

display: none;
position: absolute;

top: 0%;

left: 0%;

background-color: black;

z-index:1001;

-moz-opacity: 0.8;
width: 100%;

height: 100%;

opacity:.80;

filter: alpha(opacity=80);

}

.white_content {

display: none;

position: absolute;

top: 25%;

left: 25%;

border: 16px solid orange;

background-color: white;

z-index:1002;

overflow: auto;
width: 800px;

height: 800px;

padding: 16px;

}

5.Complete Code

<html>
<head>
<title>Light Box Effect </title >
<style type=”text/css”>

.black_overlay{

display: none;
position: absolute;

top: 0%;

left: 0%;

background-color: black;

z-index:1001;

-moz-opacity: 0.8;
width: 100%;

height: 100%;

opacity:.80;

filter: alpha(opacity=80);

}

.white_content {

display: none;

position: absolute;

top: 25%;

left: 25%;

border: 16px solid orange;

background-color: white;

z-index:1002;

overflow: auto;
width: 800px;

height: 800px;

padding: 16px;

}

</style>

</head>
<body>
<!–javascript –>
<script type=”text/javascript”>
function LightEffect(source)
{

var url =source;
parent.document.getElementById(“pictureframe”).src=url;
document.getElementById(“light”).style.display=’block’;
document.getElementById(“fade”).style.display=’block’;
}

function CloseFrame()
{
parent.document.getElementById(“pictureframe”).src=”;
document.getElementById(“light”).style.display=’none’;
document.getElementById(“fade”).style.display=’none’;
}
</script>

<!–image that onclick triggers the light box effect –>
<img src=”Box.jpg” name=”Box Image” onclick=’LightEffect(“http://www.flickr.com/&#8221;)’/>

<!–Div which will show light box effect –>
<div id=’light’ class=’white_content’ style=”>
<a href=’javascript:void(0)’ onclick=’CloseFrame();’>Close</a> <!–Close button –>
<iframe id=’pictureframe’ src=” width=’800′ height=’800′> </iframe></div>”; <!–iframe –>
</div>
<!–div the causes fade shadow ovwe web page –>
<div id=’fade’ class=’black_overlay’>
</div>
</body>
</html>

Hope this tutorial was helpful

July 29, 2008

How to Write a Process Order Stored Procedure in T-SQL

Filed under: Development Articles — ethelcofie @ 2:02 pm
Tags: , ,

PERSISTANT STORED MODULE CHOSEN: PROCESS ORDER

This Persistent stored module Process Processes Orders by reading the oldest unfulfilled Order and Flags it status as Fulfilled when there is enough stock to fulfil other or leaves to Unfulfilled or Awaiting Stock otherwise.

Database Structure

Stock control database

Stock control database

5.1 Pseudocode

START

Get oldest Unfufilled Order data

Get the catalogue data for that Order

For Each Catalogue Item

If Catalogue Item type is Stock

Then

if Catlogue Item available stock> Catalogue Order Quantity

Then

Set Order Status =Fufilled

Else

Set Order Status=Awaiting Stock

STOP

Else if Catalogue Item type is Non-Stock

Create supplier Order

If Error in then return transaction to former state

STOP

5.2 Actual code

CREATE PROCEDURE [dbo].[ProcessOrder]

— Add the parameters for the stored procedure here

AS

BEGIN

— SET NOCOUNT ON added to prevent extra result sets from

— interfering with SELECT statements.

SET NOCOUNT ON;

declare @catId varchar(max)

declare @count int –count

declare @iRow int –showing number of rows

declare @itemtype varchar(50)

declare @available_stock int

declare @orderqty int

declare @Orderid varchar(max)

declare @checkAwaiting int

— Insert statements for procedure here

DECLARE @tbl TABLE(

RowID INT IDENTITY(1, 1),

CatlID VARCHAR(Max),

Qty INT,

OrderID VARCHAR(MAX))

INSERT @tbl

SELECT Catl_id,Quantity,Order_id from dbo.VwUnfufilledOrders where VwUnfufilledOrders.Order_date=(Select min(VwUnfufilledOrders.Order_date)

from dbo.VwUnfufilledOrders)

SET @count = @@ROWCOUNT

SET @iRow = 1

set @checkAwaiting=0

Select @count

Begin transaction— start transcation

–call function for availability

—start loop to check for availabilty of every catlogue item

WHILE @iRow <= @count

begin

Select @catId=CatlID,@orderqty=Qty,@Orderid=OrderID from @tbl where RowID=@iRow

select @itemtype=Item_Type, @available_stock=Available_stock from dbo.Catlogue_Item where Catl_id=@catId

if (@itemtype=‘Stock’)

begin

print ‘Order id is’+@Orderid+‘with number of rows=’+ convert(varchar,@count) +‘it is a stock item’

if(@available_stock>@orderqty)

begin

print ‘Oder id is’+@Orderid+‘ /with Qty=’+ convert(varchar(50),@orderqty) +‘and available stock=’+convert(varchar(50),@available_stock)

Update dbo.CustOrder set Status=‘Fufilled’ where Order_id=@Orderid

If @@error <> 0

goto ERR_HANDLER

end

else

begin

Update dbo.CustOrder set Status=‘UnFufilled’ where Order_id=@Orderid

print ‘Qty not enough’

set @checkAwaiting=1

goto ERR_HANDLER

— stock insufficient so Order status remains unfufilled

–call stock replenish function

end

end

if (@itemtype=‘NonStock’)

begin

— create supplier order

print ‘Its a supplier direct order’

end

SET @iRow = @iRow + 1

end

Commit Transaction

Return 0

ERR_HANDLER:

Select ‘Unexpected error occurred!’

Rollback transaction

if ( @checkAwaiting=1)Update dbo.CustOrder set Status=‘AwaitingStock’ where Order_id=@Orderid— to be removed

Return 1

END

May 19, 2008

Flickr API: How to perform Authentication using PHP

Filed under: Development Articles — ethelcofie @ 1:32 pm
Tags: ,

I presented this at Brighton BArCamp3 download power point

//1.Create a login link

$secret_key=’secret key’;

$params = array(
‘api_key’=> ‘api_key’,
‘perms’ => ‘write’);

$encoded_param = array();

//1.a Encode and organize authentication parameters

foreach($params as $key => $value)
{
$encoded_params[] = urlencode($key).’=’.urlencode($value);
}

//1b Create the api signature :an md5 of the parameters in alphabetic order


$apisig=md5($secret_key.’api_key’.$params[‘api_key’].’perms’.$params[‘perms’]);

//1.c append api signature to url

$url =”http://flickr.com/services/auth/?”.

implode(‘&’,$encoded_params).”&api_sig=”.$apisig;

header(‘Location:’.$url); –>This will then redirect back to your call back url and include a frob value

//2.Get and use frob to retrive authentication token

//2.a Get frob from url

if ($_REQUEST[‘frob’])
{
//using php_serial paramater serial to retrieve the format in serialized data structure
$frobparams = array(
‘api_key’=> ‘api_key’,
‘frob’ => ‘frob’ ,
‘method’ => ‘flickr.auth.getToken’,
‘format’ => ‘php_serial’);

$encoded_param = array();

foreach($frobparams as $key => $value)
{
$encoded_params[] = urlencode($key).’=’.urlencode($value);
}
$url = “http://api.flickr.com/services/rest/?”.implode(‘&’, $encoded_params);

//2.bCreate the api signature :an md5 of the parameters in alphabetic order

$apisigfrob=md5(

$secret_key.

‘api_key’. $frobparams [‘api_key’].

‘format’.$frobparams [‘format’].

‘frob’.$frobparam[‘frob’].

‘method’.$frobparams[‘method’]);

//2.c Construct url to auth.getToken

$url=$url.”&api_sig=”.$apisigfrob;

// 2.d Get url response/contents
$rsp = file_get_contents($url);

$rsp_obj = unserialize($rsp);

$details=$rsp_obj;

//2.e Glean Auth Token from $details

if($details[stat]==’ok’)
{
echo $details[‘auth’][‘token’][‘_content’];
}
else
{

//dispaly error message if there is a problem
echo $details [message] ;

}

}

Just getting started: The Authentication Token can then be ussed as part of the parameter for a method call

Blog at WordPress.com.