SlideShare uma empresa Scribd logo
1 de 117
Baixar para ler offline
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?
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
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
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
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
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
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
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
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
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()
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!
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
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
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
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
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
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
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
Overview
Copying



protected void copyBytes(InputStream in,
                            OutputStream out)
       throws IOException {
              int b;
              while (( b = in.read()) != -1)
                out.write(b);
       }
}
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();
FilterStreams

 Filter stream classes add features to basic input or
  output streams
 Chain streams together to combine features



            PrintStream                   FileOutputStream




    DataInputStream       BufferedInputStream     FileInputStream
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();
PrintStream

 Can print a text representation of any Java type
 System.out and System.err are PrintStreams
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
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();
}
I/O with Memory

 ByteArrayInputStream,
  ByteArrayOuputStream - I/O with arrays of bytes
 StringBufferInputStream - input from a
  String
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
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
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) { }
   }
}
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();
}
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;
       }
  }
}
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
Reader: Overview
Writer: Overview
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
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
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();
    }
}
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.
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));
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.
Another way of accessing BufferedReader

 FileReader fr = new FileReader(“inFile”);
 BufferedReader br =
          new BufferedReader( fr);

 ………….
 fr.close();
 br.close();
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.
Using BufferedWriter

 FileWriter fw = new FileWriter(“outFile”);
 BufferedWriter bw =
         new BufferedWriter( fw );

 …………..
 fw.close();
 bw.close();
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()
Write to a File: which classes to use?

 Some class that takes File in constructor
 Best sounding method
 File  PrintWriter
 File  FileWriter  PrintWriter  println
Reading from a file: which classes to use?

 File  FileReader  BufferedReader  readLine()
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()
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
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();
Self Study

 Concurrent issues with thread programming
 Deadlock
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
Basic Structure

 <html>
 <head>
 <title>My First Web Page</title>
 </head>
 <body>
 Hi, How are you?
 </body>
 </html
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>
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>
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!
Demo

 http://www.w3schools.com/css/demo_default.htm
CSS Syntax

 A set of rules
 Each rule has two main parts
   selector
   one or more declarations




 Comments: /* … */
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
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>
“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)
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 …
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
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
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
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
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>
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!
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 /* .. */
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 {}
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
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
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");
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
  }
Loops

 for
 while
 break
 continue
 var person={fname:"John",lname:"Doe",age:25};
 var x;

 for (x in person)
 {
 document.write(person[x] + " ");
 }
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
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()
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
Document Object Model

 Naming hierarchy used to access individual elements of a
  HTML document
<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>
 From javascript you can get at the age input field as:
  document.myform.age.value
Validation Example

function checkform() {
  if (document.myform.age.value == "") {
     alert("You need to specify an age");
     return(false);
  } else {
     return(true);
  }
}
Validation Example

<FORM METHOD=GET ACTION=foo.cgi
 NAME=myform
 onSubmit="return(checkform())">

AGE: <INPUT TYPE=TEXT NAME=Age>
<INPUT TYPE=SUBMIT>
</FORM>
Java Vs JavaScript

       • JavaScript                • J ava
       • Interpreted (not          • Compiled on server
         compiled) by client.        before execution on
       • Object-based. Code          client.
         uses built-in,            • Object-oriented.
         extensible objects, but     Applets cons of object
         no classes or               classes with
         inheritance.                inheritance.
       • Code integrated with,     • Applets distinct from
         and embedded in,            HTML (accessed from
JAVA




         HTML.                       HTML pages)

                                                              83
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
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>
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
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
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
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
Sample PHP

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

echo or print
Comments: // or /*…*/
Other Features

 Variables
 Operators
 Control Statements
 Loop Statements
 Functions
Another Example

<?php
$today_dayofweek = date(“w”);
if ($today_dayofweek == 4){
    echo “Today is Thursday!”;
}
else{
   echo “Today is not Thursday.”;
}
?>
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>
Very Good Use

<table width=80% height=30>
<tr><td>
<div align=center> UC Riverside
Department<BR>
           <a
href=mailto:someuser@ucr.edu>someuser@ucr.
edu</a>
</div>
</td></tr></table>
</body>
</html>
Very Good Use

<?php
   // header
   include(“header.php”);
?>

Insert content here!

<?php
   // footer
   include(“footer.php”);
?>
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
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
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
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 !
The MATLAB User Interface
MATLAB

To get started, type one of these commands: helpwin,
  helpdesk, or demo

» a=5;
» b=a/2

b=

    2.5000

»
Other Features

 Variables
 Math and Assignment Operators
 Relational Operators
 Logical Operators
 Matrices
   first level support for matrix operations

 Selection Structures
 Repetition Structures
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
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
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
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
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
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
MATLAB Toolboxes
                                 109



 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
     …
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
       Predicate, arity 1 (male/1)

                     Terminates a clause
male(bob).
                  Argument to predicate
male(harry).
child(bob,harry).
son(X,Y):-       Indicates a rule
     male(X),child(X,Y).

                        “and”
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
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
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!
Backtracking

   How are questions resolved?
?- son(X,harry).

  Recall the rule:
son(X,Y):-
     male(X),child(X,Y).
Backtracking

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

male(X)         child(X,Y)

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


X=bob
Y=harry            child(bob,harry)?
                                       yes - succeeds
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
Self Study

 LISP

Mais conteúdo relacionado

Mais procurados

Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)arvind pandey
 
Lambda: A Peek Under The Hood - Brian Goetz
Lambda: A Peek Under The Hood - Brian GoetzLambda: A Peek Under The Hood - Brian Goetz
Lambda: A Peek Under The Hood - Brian GoetzJAX London
 
Java programming basics
Java programming basicsJava programming basics
Java programming basicsHamid Ghorbani
 
Java bytecode and classes
Java bytecode and classesJava bytecode and classes
Java bytecode and classesyoavwix
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in JavaAllan Huang
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7Deniz Oguz
 
Playing with Java Classes and Bytecode
Playing with Java Classes and BytecodePlaying with Java Classes and Bytecode
Playing with Java Classes and BytecodeYoav Avrahami
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8Heartin Jacob
 
Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchMatteo Battaglio
 
Method Handles in Java
Method Handles in JavaMethod Handles in Java
Method Handles in Javahendersk
 
Clojure - An Introduction for Java Programmers
Clojure - An Introduction for Java ProgrammersClojure - An Introduction for Java Programmers
Clojure - An Introduction for Java Programmerselliando dias
 

Mais procurados (20)

Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Lambda: A Peek Under The Hood - Brian Goetz
Lambda: A Peek Under The Hood - Brian GoetzLambda: A Peek Under The Hood - Brian Goetz
Lambda: A Peek Under The Hood - Brian Goetz
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
Java bytecode and classes
Java bytecode and classesJava bytecode and classes
Java bytecode and classes
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in Java
 
Invoke dynamics
Invoke dynamicsInvoke dynamics
Invoke dynamics
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7
 
Playing with Java Classes and Bytecode
Playing with Java Classes and BytecodePlaying with Java Classes and Bytecode
Playing with Java Classes and Bytecode
 
Working With Concurrency In Java 8
Working With Concurrency In Java 8Working With Concurrency In Java 8
Working With Concurrency In Java 8
 
02 basic java programming and operators
02 basic java programming and operators02 basic java programming and operators
02 basic java programming and operators
 
JAVA BYTE CODE
JAVA BYTE CODEJAVA BYTE CODE
JAVA BYTE CODE
 
Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central Dispatch
 
Method Handles in Java
Method Handles in JavaMethod Handles in Java
Method Handles in Java
 
Clojure - An Introduction for Java Programmers
Clojure - An Introduction for Java ProgrammersClojure - An Introduction for Java Programmers
Clojure - An Introduction for Java Programmers
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdf
 
JAVA BASICS
JAVA BASICSJAVA BASICS
JAVA BASICS
 
Core java
Core javaCore java
Core java
 
Java Basics
Java BasicsJava Basics
Java Basics
 

Semelhante a Ppl for students unit 4 and 5

Semelhante a Ppl for students unit 4 and 5 (20)

concurrency
concurrencyconcurrency
concurrency
 
Here comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdfHere comes the Loom - Ya!vaConf.pdf
Here comes the Loom - Ya!vaConf.pdf
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
 
Basic java part_ii
Basic java part_iiBasic java part_ii
Basic java part_ii
 
Lecture10
Lecture10Lecture10
Lecture10
 
Java sockets
Java socketsJava sockets
Java sockets
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
.NET Multithreading/Multitasking
.NET Multithreading/Multitasking.NET Multithreading/Multitasking
.NET Multithreading/Multitasking
 
MultiThreading in Python
MultiThreading in PythonMultiThreading in Python
MultiThreading in Python
 
Java I/O
Java I/OJava I/O
Java I/O
 
Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01Introto netthreads-090906214344-phpapp01
Introto netthreads-090906214344-phpapp01
 
Intro To .Net Threads
Intro To .Net ThreadsIntro To .Net Threads
Intro To .Net Threads
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Basic of Javaio
Basic of JavaioBasic of Javaio
Basic of Javaio
 
Thread 1
Thread 1Thread 1
Thread 1
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
15. text files
15. text files15. text files
15. text files
 
Generators & Decorators.pptx
Generators & Decorators.pptxGenerators & Decorators.pptx
Generators & Decorators.pptx
 

Mais de Akshay Nagpurkar (20)

4.osi model
4.osi model4.osi model
4.osi model
 
L6 mecse ncc
L6 mecse nccL6 mecse ncc
L6 mecse ncc
 
Tcp ip
Tcp ipTcp ip
Tcp ip
 
1 ip address
1 ip address1 ip address
1 ip address
 
1.network topology
1.network topology1.network topology
1.network topology
 
1.lan man wan
1.lan man wan1.lan man wan
1.lan man wan
 
Dcunit4 transmission media
Dcunit4 transmission mediaDcunit4 transmission media
Dcunit4 transmission media
 
Ppl for students unit 4 and 5
Ppl for students unit 4 and 5Ppl for students unit 4 and 5
Ppl for students unit 4 and 5
 
Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3
 
234 rb trees2x2
234 rb trees2x2234 rb trees2x2
234 rb trees2x2
 
Ppl home assignment_unit4
Ppl home assignment_unit4Ppl home assignment_unit4
Ppl home assignment_unit4
 
Ppl home assignment_unit5
Ppl home assignment_unit5Ppl home assignment_unit5
Ppl home assignment_unit5
 
3 multiplexing-wdm
3 multiplexing-wdm3 multiplexing-wdm
3 multiplexing-wdm
 
2 multiplexing
2 multiplexing2 multiplexing
2 multiplexing
 
1 multiplexing
1 multiplexing1 multiplexing
1 multiplexing
 
Pcm pulse codemodulation-2
Pcm pulse codemodulation-2Pcm pulse codemodulation-2
Pcm pulse codemodulation-2
 
Modulation techniq of modem
Modulation techniq of modemModulation techniq of modem
Modulation techniq of modem
 
Ppl home assignment_unit3
Ppl home assignment_unit3Ppl home assignment_unit3
Ppl home assignment_unit3
 
Ppl home assignment_unit2
Ppl home assignment_unit2Ppl home assignment_unit2
Ppl home assignment_unit2
 
Ppl home assignment_unit1
Ppl home assignment_unit1Ppl home assignment_unit1
Ppl home assignment_unit1
 

Último

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 

Último (20)

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Ppl for students unit 4 and 5

  • 1. 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?
  • 2. 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
  • 3. 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
  • 4. 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
  • 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
  • 6. 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
  • 7. 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
  • 8. 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
  • 9. 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
  • 10. 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()
  • 11. 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!
  • 12. 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
  • 13. 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
  • 14. 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
  • 15. 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
  • 16. 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
  • 17. 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
  • 18. 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
  • 20. Copying protected void copyBytes(InputStream in, OutputStream out) throws IOException { int b; while (( b = in.read()) != -1) out.write(b); } }
  • 21. 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();
  • 22. FilterStreams  Filter stream classes add features to basic input or output streams  Chain streams together to combine features PrintStream FileOutputStream DataInputStream BufferedInputStream FileInputStream
  • 23. 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();
  • 24. PrintStream  Can print a text representation of any Java type  System.out and System.err are PrintStreams
  • 25. 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
  • 26. 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(); }
  • 27. I/O with Memory  ByteArrayInputStream, ByteArrayOuputStream - I/O with arrays of bytes  StringBufferInputStream - input from a String
  • 28. 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
  • 29. 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
  • 30. 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) { } } }
  • 31. 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(); }
  • 32. 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; } } }
  • 33. 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
  • 36. 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
  • 37. 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
  • 38. 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(); } }
  • 39. 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.
  • 40. 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));
  • 41. 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.
  • 42. Another way of accessing BufferedReader  FileReader fr = new FileReader(“inFile”);  BufferedReader br =  new BufferedReader( fr);  ………….  fr.close();  br.close();
  • 43. 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.
  • 44. Using BufferedWriter  FileWriter fw = new FileWriter(“outFile”);  BufferedWriter bw =  new BufferedWriter( fw );  …………..  fw.close();  bw.close();
  • 45. 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()
  • 46.
  • 47. Write to a File: which classes to use?  Some class that takes File in constructor  Best sounding method  File  PrintWriter  File  FileWriter  PrintWriter  println
  • 48. Reading from a file: which classes to use?  File  FileReader  BufferedReader  readLine()
  • 49. 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()
  • 50. 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
  • 51. 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();
  • 52. Self Study  Concurrent issues with thread programming  Deadlock
  • 53. 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
  • 54. Basic Structure  <html>  <head>  <title>My First Web Page</title>  </head>  <body>  Hi, How are you?  </body>  </html
  • 55. 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>
  • 56. 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>
  • 57. 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!
  • 59. CSS Syntax  A set of rules  Each rule has two main parts  selector  one or more declarations  Comments: /* … */
  • 60. 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
  • 61. 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>
  • 62. “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)
  • 63. 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 …
  • 64. 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
  • 65. 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
  • 66. 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
  • 67. 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
  • 68. 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>
  • 69. 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!
  • 70. 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 /* .. */
  • 71. 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 {}
  • 72. 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
  • 73. 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
  • 74. 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");
  • 75. 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 }
  • 76. Loops  for  while  break  continue  var person={fname:"John",lname:"Doe",age:25}; var x; for (x in person) { document.write(person[x] + " "); }
  • 77. 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
  • 78. 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()
  • 79. 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
  • 80. Document Object Model  Naming hierarchy used to access individual elements of a HTML document <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>  From javascript you can get at the age input field as: document.myform.age.value
  • 81. Validation Example function checkform() { if (document.myform.age.value == "") { alert("You need to specify an age"); return(false); } else { return(true); } }
  • 82. Validation Example <FORM METHOD=GET ACTION=foo.cgi NAME=myform onSubmit="return(checkform())"> AGE: <INPUT TYPE=TEXT NAME=Age> <INPUT TYPE=SUBMIT> </FORM>
  • 83. Java Vs JavaScript • JavaScript • J ava • Interpreted (not • Compiled on server compiled) by client. before execution on • Object-based. Code client. uses built-in, • Object-oriented. extensible objects, but Applets cons of object no classes or classes with inheritance. inheritance. • Code integrated with, • Applets distinct from and embedded in, HTML (accessed from JAVA HTML. HTML pages) 83
  • 84. 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
  • 85. 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>
  • 86. 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
  • 87. 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
  • 88. 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
  • 89. 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
  • 90. Sample PHP <html> <body> <?php echo "Hello World"; ?> </body> </html> echo or print Comments: // or /*…*/
  • 91. Other Features  Variables  Operators  Control Statements  Loop Statements  Functions
  • 92. Another Example <?php $today_dayofweek = date(“w”); if ($today_dayofweek == 4){ echo “Today is Thursday!”; } else{ echo “Today is not Thursday.”; } ?>
  • 93. 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>
  • 94. Very Good Use <table width=80% height=30> <tr><td> <div align=center> UC Riverside Department<BR> <a href=mailto:someuser@ucr.edu>someuser@ucr. edu</a> </div> </td></tr></table> </body> </html>
  • 95. Very Good Use <?php // header include(“header.php”); ?> Insert content here! <?php // footer include(“footer.php”); ?>
  • 96. 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
  • 97. 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
  • 98. 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
  • 99. 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 !
  • 100. The MATLAB User Interface
  • 101. MATLAB To get started, type one of these commands: helpwin, helpdesk, or demo » a=5; » b=a/2 b= 2.5000 »
  • 102. Other Features  Variables  Math and Assignment Operators  Relational Operators  Logical Operators  Matrices  first level support for matrix operations  Selection Structures  Repetition Structures
  • 103. 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
  • 104. 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
  • 105. 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
  • 106. 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
  • 107. 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
  • 108. 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
  • 109. MATLAB Toolboxes 109  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  …
  • 110. 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 Predicate, arity 1 (male/1) Terminates a clause male(bob). Argument to predicate male(harry). child(bob,harry). son(X,Y):- Indicates a rule male(X),child(X,Y). “and”
  • 111. 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
  • 112. 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
  • 113. 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!
  • 114. Backtracking How are questions resolved? ?- son(X,harry). Recall the rule: son(X,Y):- male(X),child(X,Y).
  • 115. Backtracking Y is bound to the atom “harry” by the question. male(X) child(X,Y) X=harry child(harry,harry)? Y=harry no X=bob Y=harry child(bob,harry)? yes - succeeds
  • 116. 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