Tag Archives: code

Example Java Programs

Huge Sell on Popular Electronics

HelloWorld.java


public class HelloWorld {

    // method main(): ALWAYS the APPLICATION entry point
    public static void main (String[] args) {
    System.out.println ("Hello World!");
    }
}


// Print Today's Date
import java.util.*;

public class HelloDate {
    public static void main (String[] args) {
    System.out.println ("Hello, it's: ");
    System.out.println(new Date());
    }
}


//example: function call in Java
public class FunctionCall {

    public static void funct1 () {
    System.out.println ("Inside funct1");
    }

    public static void main (String[] args) {
    int val;

    System.out.println ("Inside main");

    funct1();

    System.out.println ("About to call funct2");

    val = funct2(8);

    System.out.println ("funct2 returned a value of " + val);

    System.out.println ("About to call funct2 again");

    val = funct2(-3);

    System.out.println ("funct2 returned a value of " + val);
    }

    public static int funct2 (int param) {
    System.out.println ("Inside funct2 with param " + param);
    return param * 2;
    }
}


//Array in Java
public class ArrayDemo {
    public static void main(String[] args) {
    int[] anArray;            // DECLARE an array of integers

    anArray = new int[10];    // CREATE an array of integers

    // assign a value to each array element 
    for (int i = 0; i < anArray.length; i++) {
        anArray[i] = i;
        }

    // print a value from each array element
    for (int i = 0; i < anArray.length; i++) {
        System.out.print(anArray[i] + " ");
    }
    System.out.println();
    }
}


//class usage in Java
class Point2d {
    /* The X and Y coordinates of the point--instance variables */
    private double x;
    private double y;
    private boolean debug;    // A trick to help with debugging

    public Point2d (double px, double py) { // Constructor
    x = px;
    y = py;

    debug = false;        // turn off debugging
    }

    public Point2d () {        // Default constructor
    this (0.0, 0.0);        // Invokes 2 parameter Point2D constructor
    }
    // Note that a this() invocation must be the BEGINNING of
    // statement body of constructor

    public Point2d (Point2d pt) {    // Another consructor
    x = pt.getX();
    y = pt.getY();

    // a better method would be to replace the above code with
    //    this (pt.getX(), pt.getY());
    // especially since the above code does not initialize the
    // variable debug.  This way we are reusing code that is already
    // working.
    }

    public void dprint (String s) {
    // print the debugging string only if the "debug"
    // data member is true
    if (debug)
        System.out.println("Debug: " + s);
    }

    public void setDebug (boolean b) {
    debug = b;
    }

    public void setX(double px) {
    dprint ("setX(): Changing value of X from " + x + " to " + px );
    x = px;
    }

    public double getX() {
    return x;
    }

    public void setY(double py)  {
    dprint ("setY(): Changing value of Y from " + y + " to " + py );
    y = py;
    }

    public double getY() {
    return y;
    }

    public void setXY(double px, double py) {
    setX(px);
    setY(py);
    }

    public double distanceFrom (Point2d pt) {
    double dx = Math.abs(x - pt.getX());
    double dy = Math.abs(y - pt.getY());

    // check out the use of dprint()
    dprint ("distanceFrom(): deltaX = " + dx);
    dprint ("distanceFrom(): deltaY = " + dy);

    return Math.sqrt((dx * dx) + (dy * dy));
    }

    public double distanceFromOrigin () {
    return distanceFrom (new Point2d ( ));
    }

    public String toStringForXY() {
    String str = "(" + x + ", " + y;
    return str;
    }

    public String toString() {
    String str = toStringForXY() + ")";
    return str;
    }
}



//read integer from Keyboard
import java.io.*;
import java.util.*;

public class KeyboardIntegerReader {

 public static void main (String[] args) throws java.io.IOException {
  String s1;
  String s2;
  int num = 0;

  // set up the buffered reader to read from the keyboard
  BufferedReader br = new BufferedReader (new InputStreamReader (
            System.in));

  boolean cont = true;

  while (cont)
     {
      System.out.print ("Enter an integer:");
      s1 = br.readLine();
      StringTokenizer st = new StringTokenizer (s1);
      s2 = "";

      while (cont && st.hasMoreTokens())
     {
          try 
          {
           s2 = st.nextToken();
           num = Integer.parseInt(s2);
           cont = false;
          }
          catch (NumberFormatException n)
          {
           System.out.println("The value in \"" + s2 + "\" is not an 

integer");
          }
    }
     }

  System.out.println ("You entered the integer: " + num);
 }
}


//read data from keyboard
import java.io.*;
import java.util.*;

public class KeyboardReader
{

 public static void main (String[] args) throws java.io.IOException
 {

  String s1;
  String s2;

  double num1, num2, product;

  // set up the buffered reader to read from the keyboard
  BufferedReader br = new BufferedReader (new InputStreamReader (
            System.in));

  System.out.println ("Enter a line of input");

  s1 = br.readLine();

  System.out.println ("The line has " + s1.length() + " characters");

  System.out.println ();
  System.out.println ("Breaking the line into tokens we get:");

  int numTokens = 0;
  StringTokenizer st = new StringTokenizer (s1);

  while (st.hasMoreTokens())
     {
      s2 = st.nextToken();
      numTokens++;
      System.out.println ("    Token " + numTokens + " is: " + s2);
     }
 }
}


//read from file
import java.io.*;
import java.util.*;

public class MyFileReader
{

 public static void main (String[] args) throws java.io.IOException
 {

  String s1;
  String s2;

  // set up the buffered reader to read from the keyboard
  BufferedReader br = new BufferedReader (new FileReader 

("MyFileReader.txt"));

  s1 = br.readLine();

  System.out.println ("The line is " + s1);
  System.out.println ("The line has " + s1.length() + " characters");

  System.out.println ();
  System.out.println ("Breaking the line into tokens we get:");

  int numTokens = 0;
  StringTokenizer st = new StringTokenizer (s1);

  while (st.hasMoreTokens())
     {
      s2 = st.nextToken();
      numTokens++;
      System.out.println ("    Token " + numTokens + " is: " + s2);
     }
 }
}


//exception handling in Java

public class HelloWorldException {
    public static void main (String[] args) throws Exception {
        System.out.println("Bienvenitos!");
        throw new Exception("Generic Exception");
    }
}



//exception handling


import java.io.*;
import java.util.*;

/** Causes a compilation error due to an unhandled Exception
 */
public class KeyboardReaderError {

  public static void main (String[] args) { // throws java.io.IOException

    String s1;
    String s2;

    double num1, num2, product;

    // set up the buffered reader to read from the keyboard
    BufferedReader br = new BufferedReader (new InputStreamReader 

(System.in));

    System.out.println ("Enter a line of input");
    
    /* Following line triggers the error.  Error will show the type of
       unhandled exception and where the call occurs */
    s1 = br.readLine();

    System.out.println ("The line has " + s1.length() + " characters");

    System.out.println ();
    System.out.println ("Breaking the line into tokens we get:");

    int numTokens = 0;
    StringTokenizer st = new StringTokenizer (s1);

    while (st.hasMoreTokens()) {
    s2 = st.nextToken();
    numTokens++;
    System.out.println ("    Token " + numTokens + " is: " + s2);
    }
  }
}

//encounters an error

import java.io.*;

// This program shows a stack track that occurs when java
// encounters a terminal error when running a program.

public class DivBy0
{

 public static void funct1 ()
 {
  System.out.println ("Inside funct1()");

  funct2();
 }

 public static void main (String[] args)
 {
  int val;

  System.out.println ("Inside main()");

  funct1();

 }

 public static void funct2 ()
 {
  System.out.println ("Inside funct2()");
  int i, j, k;

  i = 10;
  j = 0;

  k = i/j;
 }

}


FruitCreation.java: Creates a simple table named fruits in either an Oracle or a Sybase database.

Huge Sell on Popular Electronics

FruitCreation.java Creates a simple table named fruits in either an Oracle or a Sybase database.

package cwp;

import java.sql.*;

/** Creates a simple table named "fruits" in either
 *  an Oracle or a Sybase database.
 *  

 */

public class FruitCreation {
  public static void main(String[] args) {
    if (args.length < 5) {
      printUsage();
      return;
    }
    String vendorName = args[4];
    int vendor = DriverUtilities.getVendor(vendorName);
    if (vendor == DriverUtilities.UNKNOWN) {
      printUsage();
      return;
    }
    String driver = DriverUtilities.getDriver(vendor);
    String host = args[0];
    String dbName = args[1];
    String url =
      DriverUtilities.makeURL(host, dbName, vendor);
    String username = args[2];
    String password = args[3];
    String format =
      "(quarter int, " +
      "apples int, applesales float, " +
      "oranges int, orangesales float, " +
      "topseller varchar(16))";
    String[] rows =
    { "(1, 32248, 3547.28, 18459, 3138.03, 'Maria')",
      "(2, 35009, 3850.99, 18722, 3182.74, 'Bob')",
      "(3, 39393, 4333.23, 18999, 3229.83, 'Joe')",
      "(4, 42001, 4620.11, 19333, 3286.61, 'Maria')" };
    Connection connection = 
      DatabaseUtilities.createTable(driver, url,
                                    username, password,
                                    "fruits", format, rows,
                                    false);
    // Test to verify table was created properly. Reuse
    // old connection for efficiency.
    DatabaseUtilities.printTable(connection, "fruits",
                                 11, true);
  }

  private static void printUsage() {
     System.out.println("Usage: FruitCreation host dbName " +
                        "username password oracle|sybase.");
  }
}



	

Example illustrating inheritance and abstract classes

Huge Sell on Popular Electronics

illustrating inheritance এবং abstract classes এর উদাহরণ

  • Shape.java সব, বদ্ধ খোলা, বাঁকা, এবং সোজা পার্শ্বে ধারবিশিষ্ট আকার এর জন্য প্যারেন্ট ক্লাস (সারাংশ)।
  • Curve.java একটি (সারাংশ) বাঁকা আকার (খোলা বা বন্ধ)
  • StraightEdgedShape.java সরাসরি ধার সম্বলিত একটি আকৃতি (খোলা বা বন্ধ)।
  • Measurable.java পরিমাপযোগ্য এলাকায় ইন্টারফেস ডিফাইনিং ক্লাস
  • Circle.java একটি বৃত্ত যা আকার প্রসারিত করে এবং পরিমাপ প্রয়োগ করে।
  • MeasureUtil.java পরিমাপযোগ্য স্থানের উপর কাজ করে।
  • Polygon.java সরাসরি ধার সম্বলিত একটি বদ্ধ আকৃতি; StraightEdgedShape প্রসারিত করে এবং পরিমাপ প্রয়োগ করে।
  • Rectangle.java একটি আয়তক্ষেত্র যা পরিমাপযোগ্য ইন্টারফেস ধারণ করে; বহুভুজে প্রসারিত করে।
  • MeasureTest.java উদাহরণ এর জন্য ড্রাইভার

Shape.java


/** The parent class for all closed, open, curved, and 
 *  straight-edged shapes.
 *

public abstract class Shape {
  protected int x, y;

  public int getX() {
    return(x);
  }

  public void setX(int x) {
    this.x = x;
  }

  public int getY() {
    return(y);
  }

  public void setY(int y) {
    this.y = y;
  }
}


 

Curve.java

একটি (সারাংশ) বাঁকা আকার (খোলা বা বন্ধ) Curve.java An (abstract) curved Shape (open or closed)


/** A curved shape (open or closed). Subclasses will include
 *  arcs and circles.
 *
public abstract class Curve extends Shape {}

 

StraightEdgedShape.java

সরাসরি ধার সম্বলিত একটি আকৃতি (খোলা বা বন্ধ) । A Shape with straight edges (open or closed).


/** A Shape with straight edges (open or closed). Subclasses
 *  will include Line, LineSegment, LinkedLineSegments,
 *  and Polygon.
 *

public abstract class StraightEdgedShape extends Shape {}

 

Measurable.java

পরিমাপযোগ্য এলাকায় ইন্টারফেস ডিফাইনিং ক্লাস Interface defining classes with measurable areas


/** Used in classes with measurable areas. 
 *
 **************

public interface Measurable {
  double getArea();
}

 

 

Circle.java

একটি বৃত্ত যা আকার প্রসারিত করে এবং পরিমাপ প্রয়োগ করে  ।  A circle that extends Shape and implements Measurable.


/** A circle. Since you can calculate the area of
 *  circles, class implements the Measurable interface.
 *

public class Circle extends Curve implements Measurable {
  private double radius;

  public Circle(int x, int y, double radius) {
    setX(x);
    setY(y);
    setRadius(radius);
  }

  public double getRadius() {
    return(radius);
  }

  public void setRadius(double radius) {
    this.radius = radius;
  }

  /** Required for Measurable interface. */

  public double getArea() {
    return(Math.PI * radius * radius);
  }
}

 

MeasureUtil.java

পরিমাপযোগ্য স্থানের উপর কাজ করে  ।  Operates on Measurable instances


/** Some operations on Measurable instances. 
 *

public class MeasureUtil {
  public static double maxArea(Measurable m1,
                               Measurable m2) {
    return(Math.max(m1.getArea(), m2.getArea()));
  }

  public static double totalArea(Measurable[] mArray) {
    double total = 0;
    for(int i=0; i

 

Some simple utilities for building Oracle and Sybase JDBC connections

Huge Sell on Popular Electronics

এই সাধারণ উদ্দেশ্যে তৈরিকৃত কোড নয় - এটা আমাদের লোকাল সেটআপ এর ক্ষেত্রে প্রযোজ্য।


 

 

package cwp;

/** Some simple utilities for building Oracle and Sybase
 *  JDBC connections. This is not general-purpose
 *  code -- it is specific to my local setup.
 */

public class DriverUtilities {
  public static final int ORACLE = 1;
  public static final int SYBASE = 2;
  public static final int UNKNOWN = -1;

  /** Build a URL in the format needed by the
   *  Oracle and Sybase drivers I am using.
   */
  
  public static String makeURL(String host, String dbName,
                               int vendor) {
    if (vendor == ORACLE) {
      return("jdbc:oracle:thin:@" + host + ":1521:" + dbName);
    } else if (vendor == SYBASE) {
      return("jdbc:sybase:Tds:" + host  + ":1521" +
             "?SERVICENAME=" + dbName);
    } else {
      return(null);
    }
  }

  /** Get the fully qualified name of a driver. */
  
  public static String getDriver(int vendor) {
    if (vendor == ORACLE) {
      return("oracle.jdbc.driver.OracleDriver");
    } else if (vendor == SYBASE) {
      return("com.sybase.jdbc.SybDriver");
    } else {
      return(null);
    }
  }

  /** Map name to int value. */

  public static int getVendor(String vendorName) {
    if (vendorName.equalsIgnoreCase("oracle")) {
      return(ORACLE);
    } else if (vendorName.equalsIgnoreCase("sybase")) {
      return(SYBASE);
    } else {
      return(UNKNOWN);
    }
  }
}

FruitTest.java: A class that connects to either an Oracle or a Sybase database and prints out the values of predetermined columns in the “fruits” table.

Huge Sell on Popular Electronics

# FruitTest.java  A class that connects to either an Oracle or a Sybase database and prints 
  out the values of predetermined columns in the "fruits" table. 

package cwp;

import java.sql.*;

/** A JDBC example that connects to either an Oracle or
 *  a Sybase database and prints out the values of
 *  predetermined columns in the "fruits" table.
 *  


 */

public class FruitTest {

  /** Reads the hostname, database name, username, password,
   *  and vendor identifier from the command line. It
   *  uses the vendor identifier to determine which
   *  driver to load and how to format the URL. The
   *  driver, URL, username, host, and password are then
   *  passed to the showFruitTable method.
   */
  
  public static void main(String[] args) {
    if (args.length < 5) {
      printUsage();
      return;
    }
    String vendorName = args[4];
    int vendor = DriverUtilities.getVendor(vendorName);
    if (vendor == DriverUtilities.UNKNOWN) {
      printUsage();
      return;
    }
    String driver = DriverUtilities.getDriver(vendor);
    String host = args[0];
    String dbName = args[1];
    String url = DriverUtilities.makeURL(host, dbName, vendor);
    String username = args[2];
    String password = args[3];
    showFruitTable(driver, url, username, password);
  }

  /** Get the table and print all the values. */
  
  public static void showFruitTable(String driver,
                                    String url,
                                    String username,
                                    String password) {
    try {
      // Load database driver if not already loaded
      Class.forName(driver);
      // Establish network connection to database
      Connection connection =
        DriverManager.getConnection(url, username, password);
      // Look up info about the database as a whole.
      DatabaseMetaData dbMetaData = connection.getMetaData();
      String productName =
        dbMetaData.getDatabaseProductName();
      System.out.println("Database: " + productName);
      String productVersion =
        dbMetaData.getDatabaseProductVersion();
      System.out.println("Version: " + productVersion + "\n");
      System.out.println("Comparing Apples and Oranges\n" +
                         "============================");
      Statement statement = connection.createStatement();
      String query = "SELECT * FROM fruits";
      // Send query to database and store results
      ResultSet resultSet = statement.executeQuery(query);
      // Look up information about a particular table
      ResultSetMetaData resultsMetaData =
        resultSet.getMetaData();
      int columnCount = resultsMetaData.getColumnCount();
      // Column index starts at 1 (ala SQL) not 0 (ala Java).
      for(int i=1; i

J2SE : LinkedList and Iterators in Java

Huge Sell on Popular Electronics

/*
 * LinkedList.java
 *
 * Created on January 10, 2008, 8:51 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package linkedlist;

import java.util.List;
import java.util.LinkedList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Collections;
import java.util.Random;

/**
 *
 * @author Sayed
 */
public class LinkedListTest {
    
    /** Creates a new instance of LinkedList */
    public LinkedListTest() {
    }
    
    /**
     *Example operations using linked lists
     */
    
    public void linkedListOperation(){
        
        final int MAX = 10;
        int counter = 0;

        //create two linked lists
        List listA = new LinkedList();
        List listB = new LinkedList();

        //store data in the linked list A
        for (int i = 0; i < MAX; i++) {
            System.out.println("  - Storing Integer(" + i + ")");
            listA.add(new Integer(i));
        }
       
        //print data from the linked list using iterator 
        Iterator it = listA.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }

        //print data from the linked list using listIterator. 
        counter = 0;
        ListIterator liIt = listA.listIterator();
        while (liIt.hasNext()) {
            System.out.println("Element [" + counter + "] = " + liIt.next());
            System.out.println("  - hasPrevious    = " + liIt.hasPrevious());
            System.out.println("  - hasNext        = " + liIt.hasNext());
            System.out.println("  - previousIndex  = " + liIt.previousIndex());
            System.out.println("  - nextIndex      = " + liIt.nextIndex());
            System.out.println();
            counter++;
        }


        //retrieve data from the linked list using index
        for (int j=0; j < listA.size(); j++) {
            System.out.println("[" + j + "] - " + listA.get(j));
        }

        //find the location of an element
        int locationIndex = listA.indexOf("5");
        System.out.println("Index location of the String \"5\" is: " + locationIndex);  

        //find the first and the last location of an element
        System.out.println("First occurance search for String \"5\".  Index =  " + 
        listA.indexOf("5"));
        System.out.println("Last Index search for String \"5\".       Index =  " + 
        listA.lastIndexOf("5"));

        //create a sublist from the list 
        List listSub = listA.subList(10, listA.size());
        System.out.println("New Sub-List from index 10 to " + listA.size() + ": " + 
        listSub);

        //sort the sub-list
        System.out.println("Original List   : " + listSub);
        Collections.sort(listSub);
        System.out.println("New Sorted List : " + listSub);
        System.out.println();

        //reverse the new sub-list
        System.out.println("Original List     : " + listSub);
        Collections.reverse(listSub);
        System.out.println("New Reversed List : " + listSub);
        System.out.println();

        //check to see if the lists are empty
        System.out.println("Is List A empty?   " + listA.isEmpty());
        System.out.println("Is List B empty?   " + listB.isEmpty());
        System.out.println("Is Sub-List empty? " + listSub.isEmpty());
        
        //compare two lists
        System.out.println("A=B? " + listA.equals(listB));        
        System.out.println();

        //Shuffle the elements around in some Random order for List A
        Collections.shuffle(listA, new Random());

        //convert a list into an array
        Object[] objArray = listA.toArray();
        for (int j=0; j < objArray.length; j++) {
            System.out.println("Array Element [" + j + "] = " + objArray[j]);
        }

        //clear listA
        System.out.println("List A   (before) : " + listA);        
        System.out.println();
        listA.clear();
        System.out.println("List A   (after)  : " + listA);        
        System.out.println();
        
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        LinkedListTest listExample = new LinkedListTest();
        listExample.linkedListOperation();
    }
    
}

Use sorting criterion in sort function

Huge Sell on Popular Electronics

/* The following code example is taken from the book
 * "The C++ Standard Library - A Tutorial and Reference"
 * by Nicolai M. Josuttis, Addison-Wesley, 1999
 *
 * (C) Copyright Nicolai M. Josuttis 1999.
 * Permission to copy, use, modify, sell and distribute this software
 * is granted provided this copyright notice appears in all copies.
 * This software is provided "as is" without express or implied
 * warranty, and with no claim as to its suitability for any purpose.
 */

#include <iostream>
#include <vector>
#include <deque>
#include <list>
#include <set>
#include <map>
#include <string>
#include <algorithm>
#include <iterator>
#include <functional>
#include <numeric>

/* PRINT_ELEMENTS()
 * - prints optional C-string optcstr followed by
 * - all elements of the collection coll
 * - separated by spaces
 */
template <class T>
inline void PRINT_ELEMENTS (const T& coll, const char* optcstr="")
{
    typename T::const_iterator pos;

    std::cout << optcstr;
    for (pos=coll.begin(); pos!=coll.end(); ++pos) {
        std::cout << *pos << ' ';
    }
    std::cout << std::endl;
}

/* INSERT_ELEMENTS (collection, first, last)
 * - fill values from first to last into the collection
 * - NOTE: NO half-open range
 */
template <class T>
inline void INSERT_ELEMENTS (T& coll, int first, int last)
{
    for (int i=first; i<=last; ++i) {
        coll.insert(coll.end(),i);
    }
}

using namespace std;

void printCollection (const list<int>& l)
{
    PRINT_ELEMENTS(l);
}

bool lessForCollection (const list<int>& l1, const list<int>& l2)
{
    return lexicographical_compare
                (l1.begin(), l1.end(),   // first range
                 l2.begin(), l2.end());  // second range
}

int main()
{
    list<int> c1, c2, c3, c4;

    // fill all collections with the same starting values
    INSERT_ELEMENTS(c1,1,5);
    c4 = c3 = c2 = c1;

    // and now some differences
    c1.push_back(7);
    c3.push_back(2);
    c3.push_back(0);
    c4.push_back(2);

    // create collection of collections
    vector<list<int> > cc;

    cc.push_back(c1);
    cc.push_back(c2);
    cc.push_back(c3);
    cc.push_back(c4);
    cc.push_back(c3);
    cc.push_back(c1);
    cc.push_back(c4);
    cc.push_back(c2);

    // print all collections
    for_each (cc.begin(), cc.end(),
              printCollection);
    cout << endl;

    // sort collection lexicographically
    sort (cc.begin(), cc.end(),    // range
          lessForCollection);      // sorting criterion

    // print all collections again
    for_each (cc.begin(), cc.end(),
              printCollection);
}
/*
1 2 3 4 5 7
1 2 3 4 5
1 2 3 4 5 2 0
1 2 3 4 5 2
1 2 3 4 5 2 0
1 2 3 4 5 7
1 2 3 4 5 2
1 2 3 4 5

1 2 3 4 5
1 2 3 4 5
1 2 3 4 5 2
1 2 3 4 5 2
1 2 3 4 5 2 0
1 2 3 4 5 2 0
1 2 3 4 5 7
1 2 3 4 5 7

 */

C++ code : Read file content

Huge Sell on Popular Electronics

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
  ifstream in("test", ios::in | ios::binary);

  if(!in) {
    cout << "Cannot open input file.\n";
    return 1;
  }

  double num;
  char str[80];

  in.read((char *) &num, sizeof(double));
  in.read(str, 14);
  str[14] = '\0'; // null terminate str

  cout << num << ' ' << str;

  in.close();

  return 0;
}

Sort objects stored in deque

Huge Sell on Popular Electronics

/* The following code example is taken from the book
 * "The C++ Standard Library - A Tutorial and Reference"
 * by Nicolai M. Josuttis, Addison-Wesley, 1999
 *
 * (C) Copyright Nicolai M. Josuttis 1999.
 * Permission to copy, use, modify, sell and distribute this software
 * is granted provided this copyright notice appears in all copies.
 * This software is provided "as is" without express or implied
 * warranty, and with no claim as to its suitability for any purpose.
 */
#include <iostream>
#include <string>
#include <deque>
#include <set>
#include <algorithm>
using namespace std;


/* class Person
 */
class Person {
  private:
    string fn;    // first name
    string ln;    // last name
  public:
    Person() {
    }
    Person(const string& f, const string& n)
     : fn(f), ln(n) {
    }
    string firstname() const;
    string lastname() const;
    // ...
};

inline string Person::firstname() const {
    return fn;
}

inline string Person::lastname() const {
    return ln;
}

ostream& operator<< (ostream& s, const Person& p)
{
    s << "[" << p.firstname() << " " << p.lastname() << "]";
    return s;
}


/* binary function predicate:
 * - returns whether a person is less than another person
 */
bool personSortCriterion (const Person& p1, const Person& p2)
{
    /* a person is less than another person
     * - if the last name is less
     * - if the last name is equal and the first name is less
     */
    return p1.lastname()<p2.lastname() ||
           (p1.lastname()==p2.lastname() &&
            p1.firstname()<p2.firstname());
}

int main()
{
    // create some persons
    Person p1("nicolai","josuttis");
    Person p2("ulli","josuttis");
    Person p3("anica","josuttis");
    Person p4("lucas","josuttis");
    Person p5("lucas","otto");
    Person p6("lucas","arm");
    Person p7("anica","holle");

    // insert person into collection coll
    deque<Person> coll;
    coll.push_back(p1);
    coll.push_back(p2);
    coll.push_back(p3);
    coll.push_back(p4);
    coll.push_back(p5);
    coll.push_back(p6);
    coll.push_back(p7);

    // print elements
    cout << "deque before sort():" << endl;
    deque<Person>::iterator pos;
    for (pos = coll.begin(); pos != coll.end(); ++pos) {
        cout << *pos << endl;
    }

    // sort elements
    sort(coll.begin(),coll.end(),    // range
         personSortCriterion);       // sort criterion

    // print elements
    cout << "deque after sort():" << endl;
    for (pos = coll.begin(); pos != coll.end(); ++pos) {
        cout << *pos << endl;
    }
}

/*
deque before sort():
[nicolai josuttis]
[ulli josuttis]
[anica josuttis]
[lucas josuttis]
[lucas otto]
[lucas arm]
[anica holle]
deque after sort():
[lucas arm]
[anica holle]
[anica josuttis]
[lucas josuttis]
[nicolai josuttis]
[ulli josuttis]
[lucas otto]

 */

Expressions.jsp Page that demonstrates JSP expressions. Uses the JSP-Styles style sheet.

Huge Sell on Popular Electronics

Expressions.jsp  Page that demonstrates JSP expressions. Uses the JSP-Styles  style sheet. 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- 
Example of JSP Expressions. 
   
Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted.
-->
<HTML>
<HEAD>
<TITLE>JSP Expressions</TITLE>
<META NAME="keywords"
      CONTENT="JSP,expressions,JavaServer,Pages,servlets">
<META NAME="description"
      CONTENT="A quick example of JSP expressions.">
<LINK REL=STYLESHEET
      HREF="JSP-Styles.css"
      TYPE="text/css">
</HEAD>

<BODY>
<H2>JSP Expressions</H2>
<UL>
  <LI>Current time: <%= new java.util.Date() %>
  <LI>Your hostname: <%= request.getRemoteHost() %>
  <LI>Your session ID: <%= session.getId() %>
  <LI>The <CODE>testParam</CODE> form parameter:
      <%= request.getParameter("testParam") %>
</UL>
</BODY>
</HTML>

A simple C++ Program code

Huge Sell on Popular Electronics

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
  ifstream in("test", ios::in | ios::binary);

  if(!in) {
    cout << "Cannot open input file.\n";
    return 1;
  }

  double num;
  char str[80];

  in.read((char *) &num, sizeof(double));
  in.read(str, 14);
  str[14] = '\0'; // null terminate str

  cout << num << ' ' << str;

  in.close();

  return 0;
}

valarray with double value inside

Huge Sell on Popular Electronics

/* The following code example is taken from the book
 * "The C++ Standard Library - A Tutorial and Reference"
 * by Nicolai M. Josuttis, Addison-Wesley, 1999
 *
 * (C) Copyright Nicolai M. Josuttis 1999.
 * Permission to copy, use, modify, sell and distribute this software
 * is granted provided this copyright notice appears in all copies.
 * This software is provided "as is" without express or implied
 * warranty, and with no claim as to its suitability for any purpose.
 */
#include <iostream>
#include <valarray>
using namespace std;

// print valarray line-by-line
template<class T>
void printValarray (const valarray<T>& va, int num)
{
    for (int i=0; i<va.size()/num; ++i) {
        for (int j=0; j<num; ++j) {
            cout << va[i*num+j] << ' ';
        }
        cout << endl;
    }
    cout << endl;
}

int main()
{
    /* valarray with 12 elements
     * - four rows
     * - three columns
     */
    valarray<double> va(12);

    // fill valarray with values
    for (int i=0; i<12; i++) {
        va[i] = i;
    }

    printValarray (va, 3);

    // assign 77 to all values that are less than 5
    va[va<5.0] = 77.0;

    // add 100 to all values that are greater than 5 and less than 9
    va[va>5.0 && va<9.0] = valarray<double>(va[va>5.0 && va<9.0]) + 100.0;

    printValarray (va, 3);
}

/*
0 1 2
3 4 5
6 7 8
9 10 11

77 77 77
77 77 5
106 107 108
9 10 11


 */

এইচটিএমএল রঙ (HTML Color codes chart)

Huge Sell on Popular Electronics

এইচটিএমএল রঙ (HTML Color Names)

স্বর্ণা আখতার

 

স্বর্ণা আখতারআমরা জানি একেকটি কালার হলো লাল, নীল এবং সবুজ এর সমন্বিত রূপ। সাধারনত, ১৪০ টি কালার আছে যেগুলো সব ওয়েব ব্রাউজারেই সাপোর্ট করে। এই ১৪০ টি নাম এইচ টি এম এল ৫ এবং সিএসএস ৫ এ উল্লেখ আছে। যার মধ্যে ১৭ টি এসেছে এইচ টি এম এল থেকে এবং ১২৭ টি এসেছে সিএসএস থেকে। নিচে সেইসব ১৪০ টি কালারের নাম এবং তাদের হেক্সাডেসিমেল কোড দেয়া হল।

 

Color Name HEX Color Shades Mix
AliceBlue #F0F8FF Shades Mix
AntiqueWhite #FAEBD7 Shades Mix
Aqua #00FFFF Shades Mix
Aquamarine #7FFFD4 Shades Mix
Azure #F0FFFF Shades Mix
Beige #F5F5DC Shades Mix
Bisque #FFE4C4 Shades Mix
Black #000000 Shades Mix
BlanchedAlmond #FFEBCD Shades Mix
Blue #0000FF Shades Mix
BlueViolet #8A2BE2 Shades Mix
Brown #A52A2A Shades Mix
BurlyWood #DEB887 Shades Mix
CadetBlue #5F9EA0 Shades Mix
Chartreuse #7FFF00 Shades Mix
Chocolate #D2691E Shades Mix
Coral #FF7F50 Shades Mix
CornflowerBlue #6495ED Shades Mix
Cornsilk #FFF8DC Shades Mix
Crimson #DC143C Shades Mix
Cyan #00FFFF Shades Mix
DarkBlue #00008B Shades Mix
DarkCyan #008B8B Shades Mix
DarkGoldenRod #B8860B Shades Mix
DarkGray #A9A9A9 Shades Mix
DarkGreen #006400 Shades Mix
DarkKhaki #BDB76B Shades Mix
DarkMagenta #8B008B Shades Mix
DarkOliveGreen #556B2F Shades Mix
DarkOrange #FF8C00 Shades Mix
DarkOrchid #9932CC Shades Mix
DarkRed #8B0000 Shades Mix
DarkSalmon #E9967A Shades Mix
DarkSeaGreen #8FBC8F Shades Mix
DarkSlateBlue #483D8B Shades Mix
DarkSlateGray #2F4F4F Shades Mix
DarkTurquoise #00CED1 Shades Mix
DarkViolet #9400D3 Shades Mix
DeepPink #FF1493 Shades Mix
DeepSkyBlue #00BFFF Shades Mix
DimGray #696969 Shades Mix
DodgerBlue #1E90FF Shades Mix
FireBrick #B22222 Shades Mix
FloralWhite #FFFAF0 Shades Mix
ForestGreen #228B22 Shades Mix
Fuchsia #FF00FF Shades Mix
Gainsboro #DCDCDC Shades Mix
GhostWhite #F8F8FF Shades Mix
Gold #FFD700 Shades Mix
GoldenRod #DAA520 Shades Mix
Gray #808080 Shades Mix
Green #008000 Shades Mix
GreenYellow #ADFF2F Shades Mix
HoneyDew #F0FFF0 Shades Mix
HotPink #FF69B4 Shades Mix
IndianRed #CD5C5C Shades Mix
Indigo #4B0082 Shades Mix
Ivory #FFFFF0 Shades Mix
Khaki #F0E68C Shades Mix
Lavender #E6E6FA Shades Mix
LavenderBlush #FFF0F5 Shades Mix
LawnGreen #7CFC00 Shades Mix
LemonChiffon #FFFACD Shades Mix
LightBlue #ADD8E6 Shades Mix
LightCoral #F08080 Shades Mix
LightCyan #E0FFFF Shades Mix
LightGoldenRodYellow #FAFAD2 Shades Mix
LightGray #D3D3D3 Shades Mix
LightGreen #90EE90 Shades Mix
LightPink #FFB6C1 Shades Mix
LightSalmon #FFA07A Shades Mix
LightSeaGreen #20B2AA Shades Mix
LightSkyBlue #87CEFA Shades Mix
LightSlateGray #778899 Shades Mix
LightSteelBlue #B0C4DE Shades Mix
LightYellow #FFFFE0 Shades Mix
Lime #00FF00 Shades Mix
LimeGreen #32CD32 Shades Mix
Linen #FAF0E6 Shades Mix
Magenta #FF00FF Shades Mix
Maroon #800000 Shades Mix
MediumAquaMarine #66CDAA Shades Mix
MediumBlue #0000CD Shades Mix
MediumOrchid #BA55D3 Shades Mix
MediumPurple #9370DB Shades Mix
MediumSeaGreen #3CB371 Shades Mix
MediumSlateBlue #7B68EE Shades Mix
MediumSpringGreen #00FA9A Shades Mix
MediumTurquoise #48D1CC Shades Mix
MediumVioletRed #C71585 Shades Mix
MidnightBlue #191970 Shades Mix
MintCream #F5FFFA Shades Mix
MistyRose #FFE4E1 Shades Mix
Moccasin #FFE4B5 Shades Mix
NavajoWhite #FFDEAD Shades Mix
Navy #000080 Shades Mix
OldLace #FDF5E6 Shades Mix
Olive #808000 Shades Mix
OliveDrab #6B8E23 Shades Mix
Orange #FFA500 Shades Mix
OrangeRed #FF4500 Shades Mix
Orchid #DA70D6 Shades Mix
PaleGoldenRod #EEE8AA Shades Mix
PaleGreen #98FB98 Shades Mix
PaleTurquoise #AFEEEE Shades Mix
PaleVioletRed #DB7093 Shades Mix
PapayaWhip #FFEFD5 Shades Mix
PeachPuff #FFDAB9 Shades Mix
Peru #CD853F Shades Mix
Pink #FFC0CB Shades Mix
Plum #DDA0DD Shades Mix
PowderBlue #B0E0E6 Shades Mix
Purple #800080 Shades Mix
RebeccaPurple #663399 Shades Mix
Red #FF0000 Shades Mix
RosyBrown #BC8F8F Shades Mix
RoyalBlue #4169E1 Shades Mix
SaddleBrown #8B4513 Shades Mix
Salmon #FA8072 Shades Mix
SandyBrown #F4A460 Shades Mix
SeaGreen #2E8B57 Shades Mix
SeaShell #FFF5EE Shades Mix
Sienna #A0522D Shades Mix
Silver #C0C0C0 Shades Mix
SkyBlue #87CEEB Shades Mix
SlateBlue #6A5ACD Shades Mix
SlateGray #708090 Shades Mix
Snow #FFFAFA Shades Mix
SpringGreen #00FF7F Shades Mix
SteelBlue #4682B4 Shades Mix
Tan #D2B48C Shades Mix
Teal #008080 Shades Mix
Thistle #D8BFD8 Shades Mix
Tomato #FF6347 Shades Mix
Turquoise #40E0D0 Shades Mix
Violet #EE82EE Shades Mix
Wheat #F5DEB3 Shades Mix
White #FFFFFF Shades Mix
WhiteSmoke #F5F5F5 Shades Mix
Yellow #FFFF00 Shades Mix
YellowGreen #9ACD32 Shades Mix

এইচটিএমএল কম্পিউটার কোডের উপাদান (HTML Computer Code Elements)

Huge Sell on Popular Electronics

HTML Computer Code Elements

AbuJubair Mahin

Computer Code

var person = {
     firstName:"John",
     lastName:"Doe",
     age:50,
     eyeColor:"blue"
}

এইচটি এম এল কম্পিউটার কোডের উপাদান (HTML Computer Code Elements)

সাধারণত, এইচটিএমএল পরিবর্তনশীল letter size, এবং পরিবর্তনশীল letter spacing ব্যবহার করে।

কম্পিউটার কোড এর উদাহরণ প্রদর্শনের সময় এটি ঘটা আশানুরূপ নয় ।

সকল <kbd>, <samp>, and <code> উপাদানগুলো স্থায়ী letter size এবং spacing সাপোর্ট করে ।

 

HTML Keyboard Formatting

এইচটিএমএল <kbd> উপাদান কীবোর্ড ইনপুট কে সংজ্ঞায়িত করে:

উদাহরনঃ


<p>To open a file, select:</p>

<p><kbd>File | Open...</kbd></p>


 

ফলাফলঃ


To open a file, select:

File | Open...


 

HTML Sample Formatting

এইচটিএমএল <samp> উপাদান কম্পিউটার আউটপুট কে সংজ্ঞায়িত করে:

উদাহরনঃ


<samp>
demo.example.com login: Apr 12 09:10:17
Linux 2.6.10-grsec+gg3+e+fhs6b+nfs+gr0501+++p3+c4a+gr2b-reslog-v6.189
</samp>


 

ফলাফলঃ


demo.example.com login: Apr 12 09:10:17
Linux 2.6.10-grsec+gg3+e+fhs6b+nfs+gr0501+++p3+c4a+gr2b-reslog-v6.189


 

HTML Code Formatting

এইচটিএমএল <code> উপাদান প্রোগ্রামিং কোড কে সংজ্ঞায়িত করে:

উদাহরনঃ


<code>
var person = { firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}
</code>


 

ফলাফলঃ


var person = { firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}


 

<code> উপাদান অতিরিক্ত হোয়াইটস্পেস এবং লাইন ব্রেক সংরক্ষণ করে না:

উদাহরনঃ


<p>Coding Example:</p>

<code>
var person = {
    firstName:"John",
    lastName:"Doe",
    age:50,
    eyeColor:"blue"
}
</code>

 


 

ফলাফলঃ


Coding Example:


var person = {
firstName:"John",
lastName:"Doe",
age:50,
eyeColor:"blue"
}


 

এই সমস্যা সমাধানের জন্য, কোডগুলোকে <pre> এলিমেন্টে এর ভিতরে রাখতে হবে:

উদাহরনঃ


<p>Coding Example:</p>

<code>
<pre>
var person = {
    firstName:"John",
    lastName:"Doe",
    age:50,
    eyeColor:"blue"
}
</pre>
</code>

 

ফলাফলঃ


Coding Example:

var person = {
    firstName:"John",
    lastName:"Doe",
    age:50,
    eyeColor:"blue"
}

 

HTML Variable Formatting

এইচটিএমএল <var> উপাদান গাণিতিক ভেরিয়েবলকে সংজ্ঞায়িত করে:

উদাহরনঃ


<p>Einstein wrote:</p>

<p><var>E = m c<sup>2</sup></var></p>


 

ফলাফলঃ


Einstein wrote:

E = m c2


 

এইচটিএমএল Computer Code এলিমেন্টস

Tag বিবরণ
<code> প্রোগ্রামিং কোড কে সংজ্ঞায়িত করে
<kbd> কীবোর্ড ইনপুট কে সংজ্ঞায়িত করে
<samp> কম্পিউটার আউটপুট কে সংজ্ঞায়িত করে
<var> গাণিতিক ভেরিয়েবল কে সংজ্ঞায়িত করে
<pre> পূর্ববিন্যাসিত টেক্সট কে সংজ্ঞায়িত করে

 

এইচটিএমএল এর মৌলিক বিষয় (HTML Basic Example)

Huge Sell on Popular Electronics

এইচ টি এম এল এর সাধারন বিষয়াবলী

স্বর্ণা আখতার

 

(টিউটোরিয়াল টি পড়ার আগে অবশ্যই আপনাকে এইচ টি এম এল ট্যাগ এর ব্যবহার সম্পর্কে জানতে হবে। পরবর্তী অধ্যায় এ ট্যাগ সম্পর্কে আলোচনা করা হয়েছে।)

 

এইচ টি এম এল ডকুমেন্ট

সকল এইচ টি এম এল ডকুমেন্ট অবশ্যই ডকুমেন্ট এর টাইপ ঘোষণা এর মাধ্যমে শুরু করতে হয়। যেমন, <DOCTYPE html>

এইচ টি এম এল এর শুরু হয় <html> ট্যাগ দিয়ে এবং শেষ হয় </html> এর মাধ্যমে।

<body> এবং </body> এর মধ্যে প্রদর্শিত টেক্সট এইচ টি এম এল ডকুমেন্ট এর বিষয়বস্তু হিসাবে গণ্য হয়।

উদাহরনের সাহায্যে নিচে দেখানো হল


<!DOCTYPE html>
<html>
<body>

<h1>My First Heading</h1>

<p>My first paragraph.</p>

</body>
</html>


 

 

ফলাফল


My First Heading

My first paragraph.


 

 

এইচ টি এম এল এর শিরোনাম

এইচ টি এম এল এর শিরোনাম গুলো <h1> এবং <h6> ট্যাগ দ্বারা নির্ধারণ করা হয়।

যেমন,


<h1>This is a heading</h1>
<h2>This is a heading</h2>
<h3>This is a heading</h3>


 

 

ফলাফল


This is a heading

This is a heading

This is a heading


 

এইচ টি এম এল প্যারাগ্রাফ

এইচ টি এম এল প্যারাগ্রাফগুলোকে <p> ট্যাগে দ্বারা নির্ধারণ করা হয়।

যেমন,


<p>This is a paragraph.</p>
<p>This is another paragraph.</p>


 

 

ফলাফল


This is a paragraph.

This is another paragraph.


 

এইচ টি এম এল লিঙ্ক

এইচ টি এম এল এর লিঙ্কগুলো <a> ট্যাগের মাধ্যমে লিখা হয়।

যেমন,


<a href="http://bangla.salearningschool.com">This is a link</a>


 

 

ফলাফল


This is a link


 

এখানে, লিঙ্ক এড্রেস গুলো কি রকম হবে তা নির্ভর করে “href” attribute এর উপর। আর অ্যাট্রিবিউট গুলো এইচ টি এম এল এর উপাদানগুলো সম্পর্কে বিস্তারিত বিবরণ প্রদান করে।

এইচ টি এম এল ইমেজ

এইচ টি এম এল ইমেজগুলোকে <img> ট্যাগের মাধ্যমে লিখা হয়। আর এখানে src, alt, height এবং width গুলো অ্যাট্রিবিউট হিসাবে ব্যবহার করা হয়।

উদাহরনের মাধ্যমে দেখানো হল,


<img src="http://bangla.salearningschool.com/wp-content/uploads/2015/04/bangla.salearning.png" alt="http://bangla.salearningschool.com" width="660" height="150">


 

 

ফলাফল


http://bangla.salearningschool.com


A simple applet that uses the ClickListener class

Huge Sell on Popular Electronics

ClickReporter.java A simple applet that uses the ClickListener class to handle mouse events.
***************
import java.applet.Applet;
import java.awt.*;

/** Prints a message saying where the user clicks.
 *  Uses an external listener.
 *  


 ******
public class ClickReporter extends Applet {
  public void init() {
    setBackground(Color.yellow);
    addMouseListener(new ClickListener());
  }
}