Ppl for students unit 4 and 5

117
Packages Let us say you want to use Random class java.util.Random rand = new java.util.Random() import java.util.Random; import java.util.*; package mypackage; must appear as first non-comment in the file naming a library of classes convention use all lower case letters “package” and “import” statements work hand-in-hand “jar” file How does compiler finds the classes?

description

 

Transcript of Ppl for students unit 4 and 5

Page 1: Ppl for students unit 4 and 5

Packages

Let us say you want to use Random class java.util.Random rand = new java.util.Random()

import java.util.Random;

import java.util.*;

package mypackage; must appear as first non-comment in the file

naming a library of classes

convention – use all lower case letters

“package” and “import” statements work hand-in-hand

“jar” file

How does compiler finds the classes?

Page 2: Ppl for students unit 4 and 5

Multithreading

What is concurrency? Browser loading a page – improve throughput Responsive user interface Serial execution vs parallel execution

Each independent subtask is called a “thread” contrast with a process a quick look under the covers – CPU sharing

Process – self contained running program with its own address space

Multitasking OS Thread – single sequential flow of control within a

process True concurrency – multi processor machine

Page 3: Ppl for students unit 4 and 5

Multithreading

Stepping into an entirely new world

requires paradigm shift

Enables you to create scalable programs

Allows elegant design – like responding to events

How do you create a Thread?

inherit from java.lang.Thread

override run() to define the sub task that you want to be executed in parallel

Let us see it in action

Page 4: Ppl for students unit 4 and 5

Points to Note

Thread name – constructor

getName()

toString()

start() can be called from anywhere

unless this is called, thread will never be started

run()

Order of execution Different output every time we run this code

thread scheduling mechanism is not deterministic

Page 5: Ppl for students unit 4 and 5

Controlling Thread execution

yield() indicating to the CPU that you have done enough and some

other thread might as well have the CPU

not guaranteed

rarely used

sleep() cease execution for given number of milliseconds

at least that much

more – depends on when its turn comes next

less – InterruptedException – somebody called interrupt() on this thread

order is still undeterministic

Page 6: Ppl for students unit 4 and 5

Controlling Thread Execution

join()

one thread may call join() on another thread to wait for the second thread to complete before proceeding

calling thread is suspended until target thread finishes

Let us see this in action!

Blocking call

Can also be called with a timeout – join(1000)

Call to join() may be aborted by callling interrupt() on the calling thread – hence a try catch clause is required here as well

Page 7: Ppl for students unit 4 and 5

Priority

Tells the scheduler how important this thread is

If there are a number of threads blocked and waiting to be run, the scheduler will lean towards the one with highest priority first Is it possible that lower priority threads are never run?

No. Just that they are run less often

setPriority()

JDK has 10 priority levels – but what matters is the support by OS

Best to use Thread.MAX_PRIORITY, NORM_PRIORITY and MIN_PRIORITY

Page 8: Ppl for students unit 4 and 5

Daemon Thread

To provide some general service in the background as long as the program is running but is as such not part of the essence of the program

When all of the non-daemon threads are complete, the program is terminated daemon threads don’t prevent the program from ending

setDaemon(true) must be called before start()

A non-daemon thread runs main()

isDaemon()

Any thread created by a daemon thread is also by default daemon

Page 9: Ppl for students unit 4 and 5

Coding Alternatives

What if you already need to inherit from some other class?

implements Runnable So you need to have a run() method defined

Create thread by using new Thread(runnable) and then call start() on the newly created Thread object

getName() is no longer available! Thread.currentThread().getName()

Let us see this in action!

Task and an object capable of running that task

Page 10: Ppl for students unit 4 and 5

Lifecycle

A thread can be in any one of the four states New

Thread object created, but haven’t been started yet cannot run

Runnable Can be run when the CPU is available for it next May or may not be running at the moment Neither dead nor blocked

Dead normal termination of run() method

Blocked could be run, but something prevents it from running scheduler will skip over it and give time to next thread sleep(), waiting for some I/O to complete, trying to call a synchronized

method on another object and that object’s lock is not available wait()

Page 11: Ppl for students unit 4 and 5

Issues with concurrency

Two threads trying to use the same shared resource at the same time

two people trying to park car at the same slot

two people trying to go through a door

See to believe!

Page 12: Ppl for students unit 4 and 5

Solution?

Some way to put a lock when somebody is accessing a shared resource

Java has built-in support for locks, called monitor

synchronized keyword

method

block

Page 13: Ppl for students unit 4 and 5

Inter-Thread communication

Collision among threads

Cooperation among threads

Handshaking between threads wait() and notify()

sleep() does not release the lock

wait() releases the lock execution is suspended, lock is released

You can come out of wait() due to notify()

notifyAll()

timeout

Page 14: Ppl for students unit 4 and 5

Inter Thread Communication

You can call these methods only from within a synchronized method or block Otherwise IllegalMonitorStateException

“busy wait” is not good for CPU testing a condition in an infinite loop and breaking out when

appropriate

Synchronizing activities between threads

Consumer has to wait for the Producer to produce

Consumer calls wait() after aquiring its lock

Producer calls notify() on that consumer object after acquiring that guy’s lock

Page 15: Ppl for students unit 4 and 5

Idiom for wait()

while (conditionIsNotMet)

wait();

Java provides one more level of support for inter-thread communication

Java I/O

PipedWriter

PipedReader

Issue of deadlock

Page 16: Ppl for students unit 4 and 5

Java I/O

Different sources and sinks console, memory, file, network

Different approach sequential, random access, buffered, binary, character, by lines, by

words

java < 1.0 only byte oriented library

java > 1.0 also char oriented library

java 1.4 “new” io, performance and functionality improvements

Java I/O heavily depends upon wrapping or chaining

java.io: about 50 classes, 10 interfaces, 15 exceptions

Page 17: Ppl for students unit 4 and 5

Streams

Streams – for sequential reading/writing

Input vs Output

Character vs Byte

CharacterStreams

ByteStreams

Data Sink vs processing

Memory vs File vs Console vs Network

Page 18: Ppl for students unit 4 and 5

InputStream: different sources

FileInputStream

ByteArrayInputStream

StringBufferInputStream

PipedInputStream

SequenceInputStream

FilterInputStream (base class for decorator)

DataInputStream (allows to read different types of primitive data and Strings)

Modifies the way InputStream behaves internally

BufferedInputStream

LineNumberInputStream

PushbackInputStream

Page 19: Ppl for students unit 4 and 5

Overview

Page 20: Ppl for students unit 4 and 5

Copying

protected void copyBytes(InputStream in,

OutputStream out)

throws IOException {

int b;

while (( b = in.read()) != -1)

out.write(b);

}

}

Page 21: Ppl for students unit 4 and 5

FileStreams

Open files for reading or writing

Cannot append - use RandomAccessFile instead

String from, to;

FileInputStream in = new FileInputStream(from);

FileOutputStream out = new FileOutputStream(to);

copyBytes(in, out);

out.close();

Page 22: Ppl for students unit 4 and 5

FilterStreams

Filter stream classes add features to basic input or output streams

Chain streams together to combine features

PrintStream FileOutputStream

FileInputStream BufferedInputStream DataInputStream

Page 23: Ppl for students unit 4 and 5

BufferedStreams

By default, most streams are not buffered

Wrap a stream in a BufferedInputStream or BufferedOutputStream to improve performance

FileInputStream in = new FileInputStream(from);

FileOutputStream out = new FileOutputStream(to);

BufferedInputStream bin =

new BufferedInputStream(in, bufferSize);

BufferedOutputStream bout =

new BufferedOutputStream(out, bufferSize);

copyBytes(bin, bout);

in.close(); bin.close();

out.close(); bout.close();

Page 24: Ppl for students unit 4 and 5

PrintStream

Can print a text representation of any Java type

System.out and System.err are PrintStreams

Page 25: Ppl for students unit 4 and 5

DataStreams

Provide for input and output of java primitive types(int, float, etc) and Strings

Output format is independent of local machine architecture(endian-ness)

UTF format provides fir efficient storage of Unicode strings

DataInput can read in a line as a String

Page 26: Ppl for students unit 4 and 5

Typing a File

private void typeFile(String filename, PrintStream out)

throws IOException {

FileInputStream fin = new FileInputStream(filename);

DataInputStream din = new DataInputStream(fin):

String line;

while ((line = din.readLine()) != null)

out.println(line);

fin.close();

}

Page 27: Ppl for students unit 4 and 5

I/O with Memory

ByteArrayInputStream, ByteArrayOuputStream - I/O with arrays of bytes

StringBufferInputStream - input from a

String

Page 28: Ppl for students unit 4 and 5

Other Streams

LineNumberInputStream - keeps track of line

numbers

PushbackInputStream - allows pushing back one

character

SequenceInputStream - concatenates two or

more input streams

PipedInputStream, PipedOutputStream - for

communication between threads

Page 29: Ppl for students unit 4 and 5

File

Abstract representation of file and directory path names

Isn’t used to actually read/write data

It is used to work at a higher level

Page 30: Ppl for students unit 4 and 5

Creating a File

import java.io.*; class Writer1 { public static void main(String [] args) { try { // warning: exceptions possible boolean newFile = false; File file = new File // it's only an object ("fileWrite1.txt"); System.out.println(file.exists()); // look for a real file newFile = file.createNewFile(); // maybe create a file! System.out.println(newFile); // already there? System.out.println(file.exists()); // look again } catch(IOException e) { } } }

Page 31: Ppl for students unit 4 and 5

Appending to a File

static void appendStringToFile(String s, String fName)

throws IOException {

RandomAccessFile f =

new RandomAccessFile(fName, “rw”);

f.seek(f.length()); // move to end of file

f.writeBytes(s); //Appends to the end of the file….

f.close();

}

Page 32: Ppl for students unit 4 and 5

Renaming a File

class RenameCommand implements Command {

public int execute (Shell s, String[] args) {

File f1 = new File(args[1]);

File f2 = new File(args[2]);

if(f1.renameTo(f2))

return OK;

else

s.err.println(“rename failed”);

return -1;

}

}

}

Page 33: Ppl for students unit 4 and 5

Readers and Writers

Stream byte oriented

Reader/Writer unicode compliant char oriented

Adapter classes like

InputStreamReader: converts IS to Reader

OutputStreamWriter: converts OutputStream to Writer

Page 34: Ppl for students unit 4 and 5

Reader: Overview

Page 35: Ppl for students unit 4 and 5

Writer: Overview

Page 36: Ppl for students unit 4 and 5

FileReader

Convenience class for reading character files. read() single character whole stream of characters fixed number of characters

Usually wrapped by higher level objects like BufferedReader improved performance convenient methods

The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream

Page 37: Ppl for students unit 4 and 5

FileWriter

Convenience class for writing character files.

write()

write character(s) or Strings to file

Usually wrapped by high level Writer objects like BufferedWriter or PrintWriter

The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream

Page 38: Ppl for students unit 4 and 5

Using FileReader and FileWriter

import java.io.*; public class Copy { public static void main(String[] args) throws IOException { File inputFile = new File(”Source.txt"); File outputFile = new File(”Target.txt"); FileReader in = new FileReader(inputFile); FileWriter out = new FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close();` out.close(); } }

Page 39: Ppl for students unit 4 and 5

BufferedReader

To make lower level classes more efficient and easier to use

use of buffer

readLine()

Read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.

The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

Page 40: Ppl for students unit 4 and 5

Note

As of JDK 1.1, the preferred way to read lines of text is via the BufferedReader.readLine() method.

Programs that use the DataInputStream class to read lines can be converted to use the BufferedReader class by replacing code of the form

DataInputStream d =

new DataInputStream(in);

with

BufferedReader d

= new BufferedReader(new InputStreamReader(in));

Page 41: Ppl for students unit 4 and 5

BufferedReader

Reads the next line of text from this data input stream. This method successively reads bytes from the underlying input stream until it reaches the end of a line of text.

This method blocks until a newline character is read, a carriage return and the byte following it are read (to see if it is a newline), the end of the stream is detected, or an exception is thrown.

Page 42: Ppl for students unit 4 and 5

Another way of accessing BufferedReader

FileReader fr = new FileReader(“inFile”);

BufferedReader br =

new BufferedReader( fr);

………….

fr.close();

br.close();

Page 43: Ppl for students unit 4 and 5

BufferedWriter

Makes lower level classes more efficient and easier to use

newLine() method

Write text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

The buffer size may be specified, or the default size may be accepted. The default is large enough for most purposes.

Page 44: Ppl for students unit 4 and 5

Using BufferedWriter

FileWriter fw = new FileWriter(“outFile”);

BufferedWriter bw =

new BufferedWriter( fw );

…………..

fw.close();

bw.close();

Page 45: Ppl for students unit 4 and 5

PrintWriter

Enhanced significantly in java 5

You can build a PrintWriter with a File or a String

Can use in places where you previously needed a Writer wrapped with FileWrite and/or BufferedWriter

New methods make it very flexible and powerful

format()

printf()

append()

Page 46: Ppl for students unit 4 and 5
Page 47: Ppl for students unit 4 and 5

Write to a File: which classes to use?

Some class that takes File in constructor

Best sounding method

File PrintWriter

File FileWriter PrintWriter println

Page 48: Ppl for students unit 4 and 5

Reading from a file: which classes to use?

File FileReader BufferedReader readLine()

Page 49: Ppl for students unit 4 and 5

Typical Cases

Reading input by lines

File name FileReader BufferedReader readLine()

Reading standard input

System.in InputStreamReader BufferedReader readLine()

Alternative:

Scanner s = new Scanner(System.in);

s.nextLine()

Page 50: Ppl for students unit 4 and 5

Serializing Objects

How to Write to an ObjectOutputStream

Writing objects to a stream is a straight-forward process. For example, the following gets the current time in milliseconds by constructing a Date object and then serializes that object:

FileOutputStream out = new FileOutputStream("theTime");

ObjectOutputStream s = new ObjectOutputStream(out);

s.writeObject("Today");

s.writeObject(new Date());

s.flush();

Your class must implement Serializable

Page 51: Ppl for students unit 4 and 5

De-serializing objects

How to Read from an ObjectOutputStream

Once you've written objects and primitive data types to a stream, you'll likely want to read them out again and reconstruct the objects.

FileInputStream in = new FileInputStream("theTime");

ObjectInputStream s = new ObjectInputStream(in);

String today = (String)s.readObject();

Date date = (Date)s.readObject();

Page 52: Ppl for students unit 4 and 5

Self Study

Concurrent issues with thread programming

Deadlock

Page 53: Ppl for students unit 4 and 5

HTML

Hyper text Markup Language

Not a programming language

Does not act on external data

Both the data and markup tags are part of the same document

Mark Up Tags

special instructions for specific display

case in-sensitive

Page 54: Ppl for students unit 4 and 5

Basic Structure

<html>

<head>

<title>My First Web Page</title>

</head>

<body>

Hi, How are you?

</body>

</html

Page 55: Ppl for students unit 4 and 5

Some useful tags

<br>

<p>

<blockquote/>

<center/>

<!-- ….. -->

Heading levels <h1> … <h6>

<B>, <I>, <U>, <SMALL>, <BIG>

<UL> <LI> <LI> </UL>

<OL> <LI> <LI> </OL>

<HR>

Page 56: Ppl for students unit 4 and 5

More

Hyperlinks

< a href=“index.html> Home Page </a>

Images

<img src=“mailbox.jpg”>

width, height, border attributes

Tables

<table></table>

<tr></tr>

<td></td>

Page 57: Ppl for students unit 4 and 5

CSS

Original intent of HTMl was not to define the format of the content but to define the content itself

Later tags like font etc. got added Became a nightmare

Separating design and content Cascading Style Sheets Styles define HOW to display HTML elements Created by Hakon Wium Lie of MIT in 1994 Has become the W3C standard for controlling visual

presentation of web pages HTML 4.0 onwards – style in a separate CSS file Separates design elements from structural logic Lets see it in action!

Page 58: Ppl for students unit 4 and 5

Demo

http://www.w3schools.com/css/demo_default.htm

Page 59: Ppl for students unit 4 and 5

CSS Syntax

A set of rules

Each rule has two main parts selector

one or more declarations

Comments: /* … */

Page 60: Ppl for students unit 4 and 5

Two Additional Selectors

id

if you want to apply style to a single, unique element

uses the id attribute of the HTML element, and is defined with a "#“

Lets see it in action

class

to specify style for a group of elements

allows you to set a particular style for many HTML elements with the same class

uses the HTML class attribute, and is defined with a ".“

Lets see it in action

Page 61: Ppl for students unit 4 and 5

Three Ways to Insert a CSS

External Style Sheet <head>

<link rel="stylesheet" type="text/css" href="mystyle.css" /> </head>

Internal Style Sheet <head>

<style type="text/css"> hr {color:sienna;} p {margin-left:20px;} body {background-image:url("images/back40.gif");} </style> </head>

Inline Style Sheet <p style="color:sienna;margin-left:20px">This is a paragraph.</p>

Page 62: Ppl for students unit 4 and 5

“Cascading”

What style will be used when there is more than one style specified for an HTML element?

all the styles will "cascade" into a new "virtual" style sheet by the following rules, where number four has the highest priority

1. Browser default

2. External style sheet

3. Internal style sheet (in the head section)

4. Inline style (inside an HTML element)

Page 63: Ppl for students unit 4 and 5

Useful Properties

background

background-color, image, repeat

text

color, text-align, text-transform, text-indent

font

font-family, font-style, font-size

links, lists, tables …

Page 64: Ppl for students unit 4 and 5

Advantages of CSS

Faster downloads

Better site maintenance

Reduced bandwidth costs one style sheet called and cached

Higher search engine rankings cleaner code

greater density of indexable content

Not all CSS properties may be supported by all browsers

Page 65: Ppl for students unit 4 and 5

JavaScript

THE scripting language of the web

Used in billions of Web pages to add functionality, validate forms, communicate with the server, and much more

Let us first see a demo

Page 66: Ppl for students unit 4 and 5

What is JavaScript

was designed to add interactivity to HTML pages

lightweight programming language

usually embedded directly into HTML pages

interpreted language (means that scripts execute without preliminary compilation)

implementation of ECMAScript language standard

JavScript has NOTHING TO DO with Java

Page 67: Ppl for students unit 4 and 5

What can JavaScript do?

gives HTML designers a programming tool

can react to events

page finished loading, user clicked on an element

can read and write HTML elements

change content of a HTML element

can be used to validate data

can be used to detect the visitor's browser

and hence show browser specific stuff

can be used to create cookies

Page 68: Ppl for students unit 4 and 5

JavaScript and HTML

HTML <script> tag is used to insert a JavaScript into an HTML page – either in body or in head

Example of writing HTML

Example of changing HTML

Hiding JavaScript <html>

<body> <script type="text/javascript"> <!-- document.getElementById("demo").innerHTML=Date(); //--> </script> </body> </html>

Page 69: Ppl for students unit 4 and 5

Functions and Events

JavaScripts in an HTML page will be executed when the page loads

This is not always what we want

Sometimes we want to execute a JavaScript when an event occurs, such as when a user clicks a button

When this is the case we can put the script inside a function

Events are normally used in combination with functions (like calling a function when an event occurs)

Example!

Page 70: Ppl for students unit 4 and 5

External JavaScript

JavaScript can also be placed in external files cane be used on several different web pages

File extension .js

External script cannot contain the <script></script> tags!

To use an external script, point to the .js file in the "src" attribute of the <script> tag <script type="text/javascript" src="xxx.js"></script>

Comments: // or /* .. */

Page 71: Ppl for students unit 4 and 5

About JavaScript Syntax

JavaScript is a sequence of statements to be executed by the browser

Case sensitive

; at the end of each statement is optional

<script type="text/javascript"> document.write("<h1>This is a heading</h1>"); document.write("<p>This is a paragraph.</p>"); document.write("<p>This is another paragraph.</p>"); </script>

statements can be grouped in blocks {}

Page 72: Ppl for students unit 4 and 5

Variables

Variable names are case sensitive (y and Y are two different variables)

Variable names must begin with a letter, the $ character, or the underscore character

var x; var x=5; var name=“Vishal”; If you redeclare a JavaScript variable, it will not lose its

value local (inside and function) and global variables Assigning Values to Undeclared JavaScript Variables makes them implicitly global

Page 73: Ppl for students unit 4 and 5

Operators

Arithmetic +, -, *, /, %, ++, --

Assignment =, += etc.

+ is also used for concatenation

If you add a number and a string, the result will be a string!

Comparison Operators

Logical Operators

If .. Else statement

Switch statement

Page 74: Ppl for students unit 4 and 5

GUI

JavaScript has three kind of popup boxes Alert box user will have to click “OK” to proceed alert("sometext");

Confirm box user will have to click either "OK" or "Cancel" to proceed If the user clicks "OK", the box returns true. If the user clicks "Cancel",

the box returns false confirm("sometext");

Prompt box user will have to click either "OK" or "Cancel" to proceed after entering

an input value If the user clicks "OK" the box returns the input value. If the user clicks

"Cancel" the box returns null prompt("sometext","defaultvalue");

Page 75: Ppl for students unit 4 and 5

Functions

A function will be executed by an event or by a call to the function

to assure that a function is read/loaded by the browser before it is called, it could be wise to put functions in the <head> section

function functionname(var1,var2,...,varX) { some code }

Page 76: Ppl for students unit 4 and 5

Loops

for

while

break

continue

var person={fname:"John",lname:"Doe",age:25}; var x; for (x in person) { document.write(person[x] + " "); }

Page 77: Ppl for students unit 4 and 5

Events

Every element on a web page has certain events which can trigger a JavaScript

A mouse click

A web page or an image loading

Mousing over a hot spot on the web page

Selecting an input field in an HTML form

Submitting an HTML form

A keystroke

onLoad, onUnload, onSubmit, onMouseOver

Page 78: Ppl for students unit 4 and 5

Objects

JavaScript is Object based programming language

Allows you to define your own objects and make your own variable types

Object is just a special kind of data. An object has properties and methods

Objects have attributes and methods.

Many pre-defined objects and object types.

Using objects follows the syntax of C++/Java objectname.attributename

objectname.methodname()

Page 79: Ppl for students unit 4 and 5

Pre-defined Objects

document

attributes of current document like title, URL, forms, images etc.

write()

navigator

contains information about the browser

screen

contains info about visitor’s screen

window

represents an open window in the browser

Page 80: Ppl for students unit 4 and 5

Document Object Model

Naming hierarchy used to access individual elements of a HTML document

From javascript you can get at the age input field as: document.myform.age.value

<FORM ID=myform ACTION=…

Please Enter Your Age:

<INPUT TYPE=TEXT ID=age NAME=age><BR>

And your weight:

<INPUT TYPE=TEXT ID=weight NAME=weight><BR>

</FORM>

Page 81: Ppl for students unit 4 and 5

Validation Example

function checkform() {

if (document.myform.age.value == "") {

alert("You need to specify an age");

return(false);

} else {

return(true);

}

}

Page 82: Ppl for students unit 4 and 5

Validation Example

<FORM METHOD=GET ACTION=foo.cgi

NAME=myform

onSubmit="return(checkform())">

AGE: <INPUT TYPE=TEXT NAME=Age>

<INPUT TYPE=SUBMIT>

</FORM>

Page 83: Ppl for students unit 4 and 5

JA

VA

83

Java Vs JavaScript

• JavaScript

• Interpreted (not

compiled) by client.

• Object-based. Code

uses built-in,

extensible objects, but

no classes or

inheritance.

• Code integrated with,

and embedded in,

HTML.

• J ava

• Compiled on server

before execution on

client.

• Object-oriented.

Applets cons of object

classes with

inheritance.

• Applets distinct from

HTML (accessed from

HTML pages)

Page 84: Ppl for students unit 4 and 5

PHP

Powerful tool for making dynamic and interactive web pages

Counterpart of MS ASP

Server-side scripting language

PHP stands for PHP: Hypertext Preprocessor

PHP scripts are executed on the server

PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic ODBC, etc.)

PHP is an open source software

PHP is free to download and use

Page 85: Ppl for students unit 4 and 5

Why is PHP used?

1. Easy to Use Code is embedded into HTML. The PHP code is enclosed in special start and end tags

that allow you to jump into and out of "PHP mode".

<html>

<head>

<title>Example</title>

</head>

<body>

<?php

echo "Hi, I'm a PHP script!";

?>

</body>

</html>

Page 86: Ppl for students unit 4 and 5

Why is PHP used?

1. Cross Platform Runs on almost any Web server on several operating systems.

One of the strongest features is the wide range of supported databases

Web Servers: Apache, Microsoft IIS, Caudium, Netscape Enterprise

Server

Operating Systems: UNIX (HP-UX,OpenBSD,Solaris,Linux), Mac

OSX, Windows NT/98/2000/XP/2003

Supported Databases: Adabas D, dBase,Empress, FilePro (read-

only), Hyperwave,IBM DB2, Informix, Ingres, InterBase, FrontBase,

mSQL, Direct MS-SQL, MySQL, ODBC, Oracle (OCI7 and OCI8),

Ovrimos, PostgreSQL, SQLite, Solid, Sybase, Velocis,Unix dbm

Page 87: Ppl for students unit 4 and 5

Why is PHP used?

1. Cost Benefits PHP is free. Open source code means that the entire PHP community will contribute

towards bug fixes. There are several add-on technologies (libraries) for PHP that are

also free.

PHP

Software Free

Platform

Free (Linux)

Development Tools Free

PHP Coder, jEdit

Page 88: Ppl for students unit 4 and 5

More about PHP

PHP files can contain text, HTML tags and scripts PHP files are returned to the browser as plain HTML PHP files have a file extension of ".php", ".php3", or

".phtml" PHP runs on different platforms (Windows, Linux, Unix,

etc.) PHP is compatible with almost all servers used today

(Apache, IIS, etc.) PHP is FREE to download from the official PHP

resource: www.php.net PHP is easy to learn and runs efficiently on the server

side

Page 89: Ppl for students unit 4 and 5

How Does It Work?

The PHP script is executed on the server, and the plain HTML result is sent back to the browser

A PHP script always starts with <?php and ends with ?>. A PHP script can be placed anywhere in the document.

<? .. ?>

A PHP file normally contains HTML tags, and some PHP scripting code.

Each code line in PHP must end with a semicolon

Page 90: Ppl for students unit 4 and 5

Sample PHP

<html>

<body> <?php echo "Hello World"; ?>

</body>

</html>

echo or print

Comments: // or /*…*/

Page 91: Ppl for students unit 4 and 5

Other Features

Variables

Operators

Control Statements

Loop Statements

Functions

Page 92: Ppl for students unit 4 and 5

Another Example

<?php $today_dayofweek = date(“w”);

if ($today_dayofweek == 4){ echo “Today is Thursday!”; } else{ echo “Today is not Thursday.”; }

?>

Page 93: Ppl for students unit 4 and 5

Very Good Use

<html><head>

<title>UCR Webmaster Support Group</title> <link rel="stylesheet" type="text/css" href=“mycssfile.css">

</head> <body>

<table width=80% height=30>

<tr><td> <div align=center> Page Title </div> </td></tr></table>

Page 94: Ppl for students unit 4 and 5

Very Good Use

<table width=80% height=30> <tr><td> <div align=center> UC Riverside Department<BR> <a href=mailto:[email protected]>[email protected]</a> </div> </td></tr></table> </body> </html>

Page 95: Ppl for students unit 4 and 5

Very Good Use

<?php // header include(“header.php”); ?> Insert content here! <?php // footer include(“footer.php”); ?>

Page 96: Ppl for students unit 4 and 5

Additional Resources

• PHP Manual http://docs.php.net/

• PHP Tutorial http://academ.hvcc.edu/~kantopet/php/index.php

• PHP Coder http://www.phpide.de/ • JEdit http://www.jedit.org/

• PHP's creator offers his thoughts on the PHP phenomenon, what has

shaped and motivated the language, and where the PHP movement is heading http://www.oracle.com/technology/pub/articles/php_experts/rasmus_php.html

• Hotscripts – A large number of PHP scripts can be found at: http://hotscripts.com/PHP/Scripts_and_Programs/index.html

Page 97: Ppl for students unit 4 and 5

MATLAB

MATLAB is a program for doing numerical computation. It was originally designed for solving linear algebra type problems using matrices. It’s name is derived from MATrix LABoratory

Plotting functions ..

Image Processing Basics ..

Robotics Applications ..

GUI Design and Programming

Page 98: Ppl for students unit 4 and 5

MATLAB

The MATLAB environment is command oriented somewhat like UNIX. A prompt appears on the screen and a MATLAB statement can be entered. When the <ENTER> key is pressed, the statement is executed, and another prompt appears.

If a statement is terminated with a semicolon ( ; ), no results will be displayed. Otherwise results will appear before the next prompt

Page 99: Ppl for students unit 4 and 5

MATLAB

MATLAB has since been expanded and now has built-in functions for solving problems requiring data analysis, signal processing, optimization, and several other types of scientific computations. It also contains functions for 2-D and 3-D graphics and animation

Everything in MATLAB is a matrix !

Page 100: Ppl for students unit 4 and 5

The MATLAB User Interface

Page 101: Ppl for students unit 4 and 5

MATLAB

To get started, type one of these commands: helpwin,

helpdesk, or demo

» a=5;

» b=a/2

b =

2.5000

»

Page 102: Ppl for students unit 4 and 5

Other Features

Variables

Math and Assignment Operators

Relational Operators

Logical Operators

Matrices

first level support for matrix operations

Selection Structures

Repetition Structures

Page 103: Ppl for students unit 4 and 5

MATLAB Matrices

MATLAB treats all variables as matrices. For our purposes a matrix can be thought of as an array, in fact, that is how it is stored.

Vectors are special forms of matrices and contain only one row OR one column.

Scalars are matrices with only one row AND one column

Page 104: Ppl for students unit 4 and 5

MATLAB Matrices

A matrix can be created in MATLAB as follows (note the commas AND semicolons):

» matrix = [1 , 2 , 3 ; 4 , 5 ,6 ; 7 , 8 , 9]

matrix =

1 2 3

4 5 6

7 8 9

Page 105: Ppl for students unit 4 and 5

Use of M-File

There are two kinds of M-files:

Scripts, which do not accept input arguments or return output arguments. They operate on data in the workspace.

Functions, which can accept input

arguments and return output arguments. Internal variables are local to the function.

Click to create

a new M-File

Page 106: Ppl for students unit 4 and 5

M-File as script file

Save file as filename.m

Type what you want to

do, eg. Create matrices

If you include “;” at the

end of each statement,

result will not be shown

immediately

Run the file by typing the filename in the command window

Page 107: Ppl for students unit 4 and 5

Some Useful MATLAB commands

who List known variables

whos List known variables plus their size

help >> help sqrt Help on using sqrt

lookfor >> lookfor sqrt Search for

keyword sqrt in m-files

what >> what a: List MATLAB files in a:

clear Clear all variables from work space

clear x y Clear variables x and y from work space

clc Clear the command window

Page 108: Ppl for students unit 4 and 5

Some Useful MATLAB commands

what List all m-files in current directory

dir List all files in current directory

ls Same as dir

type test Display test.m in command window

delete test Delete test.m

cd a: Change directory to a:

chdir a: Same as cd

pwd Show current directory

which test Display directory path to ‘closest’ test.m

Page 109: Ppl for students unit 4 and 5

109 109

MATLAB Toolboxes

MATLAB has a number of add-on software modules, called toolbox , that perform more specialized computations. Signal Processing Image Processing Communications System Identification Wavelet Filter Design Control System Fuzzy Logic Robust Control µ-Analysis and Synthesis LMI Control Model Predictive Control …

Page 110: Ppl for students unit 4 and 5

PROLOG

Logic based language

With a few simple rules, information can be analyzed .pl files contain lists of clauses

Clauses can be either facts or rules

male(bob).

male(harry).

child(bob,harry).

son(X,Y):-

male(X),child(X,Y).

Predicate, arity 1 (male/1)

Terminates a clause

Indicates a rule

“and”

Argument to predicate

Page 111: Ppl for students unit 4 and 5

Rules

Rules combine facts to increase knowledge of the system

son(X,Y):-

male(X),child(X,Y).

X is a son of Y if X is male and X is a child of Y

Page 112: Ppl for students unit 4 and 5

Questions

Ask the Prolog virtual machine questions

Composed at the ?- prompt

Returns values of bound variables and yes or no

?- son(bob, harry).

yes

?- king(bob, france).

no

Page 113: Ppl for students unit 4 and 5

Questions

Can bind answers to questions to variables

Who is bob the son of? (X=harry)

?- son(bob, X).

Who is male? (X=bob, harry)

?- male(X).

Is bob the son of someone? (yes)

?- son(bob, _).

No variables bound in this case!

Page 114: Ppl for students unit 4 and 5

Backtracking

How are questions resolved?

?- son(X,harry).

Recall the rule:

son(X,Y):-

male(X),child(X,Y).

Page 115: Ppl for students unit 4 and 5

Backtracking

Y is bound to the atom “harry” by the question.

male(X) child(X,Y)

X=harry Y=harry

child(harry,harry)?

child(bob,harry)? X=bob Y=harry

no

yes - succeeds

Page 116: Ppl for students unit 4 and 5

Applications

Intelligent systems Complicated knowledge databases Natural language processing Logic data analysis

Strengths:

Strong ties to formal logic

Many algorithms become trivially simple to implement

Weaknesses:

Complicated syntax

Difficult to understand programs at first sight

Page 117: Ppl for students unit 4 and 5

Self Study

LISP