ServletTemplate.java Starting point for servlets. #Programming Code Examples #Java/J2EE/J2ME #Servlet

ServletTemplate.java Starting point for servlets. 


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

/** Servlet template.
 *  

* Taken from Core Web Programming Java 2 Edition * from Prentice Hall and Sun Microsystems Press, * . * May be freely used or adapted. */ public class ServletTemplate extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Use "request" to read incoming HTTP headers // (e.g., cookies) and query data from HTML forms. // Use "response" to specify the HTTP response status // code and headers (e.g. the content type, cookies). PrintWriter out = response.getWriter(); // Use "out" to send content to browser } }

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10240
Categories:Programming Code Examples, Java/J2EE/J2ME, Servlet
Tags:Java/J2EE/J2MEServlet
Post Data:2017-01-02 16:04:28

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Print three-dimensional valarray line-by-line #Programming Code Examples #Java/J2EE/J2ME #Valarray

/* 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 three-dimensional valarray line-by-line
template<class T>
void printValarray3D (const valarray<T>& va, int dim1, int dim2)
{
    for (int i=0; i<va.size()/(dim1*dim2); ++i) {
        for (int j=0; j<dim2; ++j) {
            for (int k=0; k<dim1; ++k) {
                cout << va[i*dim1*dim2+j*dim1+k] << ' ';
            }
            cout << 'n';
        }
        cout << 'n';
    }
    cout << endl;
}

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

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

    // print valarray
    printValarray3D (va, 3, 4);

    // we need two two-dimensional subsets of three times 3 values
    // in two 12-element arrays
    size_t lengthvalues[] = {  2, 3 };
    size_t stridevalues[] = { 12, 3 };
    valarray<size_t> length(lengthvalues,2);
    valarray<size_t> stride(stridevalues,2);

    // assign the second column of the first three rows
    // to the first column of the first three rows
    va[gslice(0,length,stride)]
        = valarray<double>(va[gslice(1,length,stride)]);

    // add and assign the third of the first three rows
    // to the first of the first three rows
    va[gslice(0,length,stride)]
        += valarray<double>(va[gslice(2,length,stride)]);

    // print valarray
    printValarray3D (va, 3, 4);
}

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

12 13 14
15 16 17
18 19 20
21 22 23


3 1 2
9 4 5
15 7 8
9 10 11

27 13 14
33 16 17
39 19 20
21 22 23



 */

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10191
Categories:Programming Code Examples, Java/J2EE/J2ME, Valarray
Tags:Java/J2EE/J2MEValarray
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Driver template to create and start a Thread object. #Programming Code Examples #Javascript #Java Threads

/** Taken from Core Web Programming from 
 *  Prentice Hall and Sun Microsystems Press,
  *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class DriverClass extends SomeClass {
  ...
  public void startAThread() {
    // Create a Thread object.
    ThreadClass thread = new ThreadClass();
    // Start it in a separate process.
    thread.start();
    ...
  }
}

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10183
Categories:Programming Code Examples, Javascript, Java Threads
Tags:JavascriptJava Threads
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

JavaScript Code #Programming Code Examples #Javascript #JavaScript

                var browser=navigator.appName;
                var b_version=navigator.appVersion;


<a href="http://www.justetc.net" target="_blank">
<img border="0" alt="hello" src="b_pink.gif" id="b1" width="26" height="26" onmouseover="mouseOver()" onmouseout="mouseOut()" />


Place the following code under script tag/in a javascript file function mouseOver() { document.getElementById("b1").src ="b_blue.gif"; } function mouseOut() { document.getElementById("b1").src ="b_pink.gif"; }

<map name="planetmap">

<area shape ="rect" coords ="0,0,82,126"
onMouseOver="writeText('You are over the target area')"
href ="target.htm" target ="_blank" alt="target" />
var t1=setTimeout("document.getElementById('id1').value='2 seconds!'",2000);
var t2=setTimeout("document.getElementById('id1').value='4 seconds!'",4000);
var t3=setTimeout("document.getElementById('id1').value='6 seconds!'",6000);
Direct Instance: 

pObj=new Object();
pObj.firstname="John";
pObj.lastname="Doe";
pObj.age=50;
pObj.eyecolor="blue";

document.write(pObj.firstname + " is " + pObj.age + " years 

function car(brand,make,model)
{
this.brand=brand;
this.make=make;
this.model=model;
}
var myCar=new car("Honda","2009","Accord");
document.write(myCar.brand +  myCar.make + myCar.model );
try
{
}
catch(err)
{
}

Under script tag/javascript file:

onerror=handleErr;
var alertTxt = "" 

function handleErr(msg, url, l)
{
   alertTxt = "Error Information:.nn";
   alertTxt += msg + "n";
   alertTxt += url + "n";
   alertTxt += l + "nn";
   alertTxt += "Click OK to continue.nn";
   alert(alertTxt);
   return true;
}


var x;
var myFriends= new Array();
myFriends[0] = "Shafiq";
myFriends[1] = "Rafiq";
myFriends[2] = "Abba";
myFriends[3] = "Amma";

for (x in myFriends)
{
   document.write(myFriends[x] + "
"); }
var d = new Date();
theDay=d.getDay();
switch (theDay)
{
case 5:
  document.write("Friday");
  break;
case 6:
  document.write("Saturday");
  break;
case 0:
  document.write("Sunday");
  break;
}
   var pattern = new RegExp("e","g");
   do
   {
     result=pattern .exec("This is the line where the regular expression will be searched on");
     document.write(result);
   }
   while (result!=null) 

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10182
Categories:Programming Code Examples, Javascript, JavaScript
Tags:JavascriptJavaScript
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Javascript : Miscellaneous Code #Programming Code Examples #Javascript #JavaScript

                var browser=navigator.appName;
                var b_version=navigator.appVersion;

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10180
Categories:Programming Code Examples, Javascript, JavaScript
Tags:JavascriptJavaScript
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

GetElementsByName an example: Checkbox #Programming Code Examples #Javascript #JavaScript

<html>

	<head>
		<script type="text/javascript">
			function getElements()
			  {
			  var x=document.getElementsByName("myInput[]");
			  alert(x.length);
			  alert(x[0].value);
			  alert(x[1].value);
			  alert(x[2].value);


			  }
		</script>
</head>

<body>
	<input name="myInput[]" type="checkbox" size="20" value='10'/>10 
<input name="myInput[]" type="checkbox" size="20" value='20' />20
<input name="myInput[]" type="checkbox" size="20" value='30' />30
<br /> <input type="button" onclick="getElements()" value="How many elements named 'myInput'?" /> </body> </html>

Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10179
Categories:Programming Code Examples, Javascript, JavaScript
Tags:JavascriptJavaScript
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

JavaScript Form Validation: Validate a Form Collecting Credit Card Information #Programming Code Examples #Javascript #JavaScript


	function validateCollectPaymentInformationForm()
	{
		var method, name, number, expiry, errMsg
		
		errMsg = "";
		
		method = document.getElementById('paymentMethod');
		name =   document.getElementById('txtCCName');
		number = document.getElementById('txtCCNumber');
        
		if (method.value == "" || method.value == "0" || method.value == null){
			
			errMsg = "Please select a payment method n";
			
			
		}
		
		if (name.value == "" || name.value == null){
			
			errMsg = errMsg + 'Please write down your name  n';
			
			
		}
		
		if (number.value == "" || number.value == null){
			
			errMsg = errMsg + 'Please provide credit card number  n';
				
		}else if (number.value.length  0 ){
			alert(errMsg);
			method.focus();
			return false;			
		}else{		
			return true;
		}		
		return false;	
	}


	function validateCollectPaymentInformationForm()
	{
		var method, name, number, expiry, errMsg
		
		
		
		method = document.getElementById('paymentMethod');
		name =   document.getElementById('txtCCName');
		number = document.getElementById('txtCCNumber');
        
		if (method.value == "" || method.value == "0" || method.value == null){
			alert('Please select a payment method');
			method.focus();
			return false;
			
		}
		
		if (name.value == "" || name.value == null){
			alert('Please write down your name');			
			name.focus();
			return false;
			
		}
		
		if (number.value == "" || number.value == null){
			alert('Please provide credit card number');			
			number.focus();
			return false;			
		}else if (number.value.length < 16 ){
			alert('Invalid card number');			
			number.focus();
			return false;	
		}
		
		
			
		return true;
	}



Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10176
Categories:Programming Code Examples, Javascript, JavaScript
Tags:JavascriptJavaScript
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

Ajax Basic Operations #Programming Code Examples #NULL


Get a handle to XMLHttpRequest object

 function getAjaxObject(){

    var ajaxObject = false;

    if (window.XMLHttpRequest){

         ajaxObject = new XMLHttpRequest();

    }else if (window.ActiveXObject) {
      try{
        ajaxObject = new ActiveXObject("Msxml2.XMLHTTP");

      }catch(e){
         try{
          ajaxObject = new ActiveXObject("Microsoft.XMLHTTP");

         }catch(e){
           ajaxObject = false;

         }

      }
    }
    return ajaxObject; 

  }



use of onreadystatechange

if (ajaxObject){
//takeAction - reference to a function
   ajaxObject.onreadystatechange = takeAction; 
}



Sample code:

 var ajaxObject = getAjaxObject();

 if (ajaxObject ){
    ajaxObject.onreadystatechange = takeAction; 

    ajaxObject.open("POST","file.jsp", true);

    ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    ajaxObject.send("id=500&name=keith&age=18");

 }



function takeAction(ajaxObject){
  if (ajaxObject.readyState == 4) {

     //do something with the response
  }
 }


function takeAction(ajaxObject){

  if (ajaxObject.readyState == 4) {

     if (ajaxObject.status == 200 || ajaxObject.status == 304){ //response was sent succesfully 

          //do something with the response
     }
  }
 }



function takeAction(ajaxObject){
  if (ajaxObject.readyState == 4) {

     if (ajaxObject.status == 200 || 
ajaxObject.status == 304){ 
//response was sent succesfully 

          //do something with the response
          alert(ajaxObject.responseText);

     }
  }
 }






function getAjaxObject(){
    var ajaxObject = false;
    if (window.XMLHttpRequest){

         ajaxObject = new XMLHttpRequest();
    }else if (window.ActiveXObject) {

      try{
        ajaxObject = new ActiveXObject("Msxml2.XMLHTTP");

      }catch(e){
         try{
          ajaxObject = new ActiveXObject("Microsoft.XMLHTTP");

         }catch(e){
           ajaxObject = false;
         }

      }
    }
    return ajaxObject; 
  }

  function entryPoint(){

    var ajaxObject = getAjaxObject();

     if (ajaxObject ){
    ajaxObject.onreadystatechange = function(){

      takeAction(ajaxObject); 
    };
    ajaxObject.open("POST","file.jsp", true);

    ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    ajaxObject.send("id=500&name=keith&age=18");

 }
 }
 function takeAction(ajaxObject){
  if (ajaxObject.readyState == 4) {

     if (ajaxObject.status == 200 || ajaxObject.status == 304){
 //response was sent succesfully 

          //do something with the response
          alert(ajaxObject.responseText);

          var testDiv = document.getElementById("test");

          testDiv.innerText = ajaxObject.responseText; 

     }
  }
 }



Processing Response Data:

var data = ajaxObject.responseXML;

data.getElementsByTagName("name")

data.getElementsByTagName("name")[0]

data.getElementsByTagName("name")[0].firstChild

data.getElementsByTagName("name")[0].firstChild.nodeValue


JSON Example:

{"person":{ "name":"Keith Tang", "school":"uofm" } } 

var data = eval('('+ ajaxObject.responseText +')');
var name = data.person.name;
var school = data.person.school; 



if (ajaxObject.status == 200 || ajaxObject.status == 304){ 
//response was sent succesfully 
          //do something with the response

          alert(ajaxObject.responseText);
          var testDiv = document.getElementById("test");

          testDiv.innerHTML = ajaxObject.responseText; 

     }




Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10177
Categories:Programming Code Examples, NULL
Tags:NULL
Post Data:2017-01-02 16:04:23

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

UriRetriever.java Accepts a host, port, and file from the command line and retrieves the implied URL from the HTTP server by issuing a GET request. Uses the following classes: #Programming Code Examples #NULL #Network Programming

UriRetriever.java  Accepts a host, port, and file from the command line and retrieves the implied URL from the HTTP server by issuing a GET request. Uses the following classes:


import java.net.*;
import java.io.*;

/** Retrieve a URL given the host, port, and file as three
 *  separate command-line arguments. A later class
 *  (UrlRetriever) supports a single URL instead.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class UriRetriever extends NetworkClient {
  private String uri;

  public static void main(String[] args) {
    UriRetriever uriClient
      = new UriRetriever(args[0], Integer.parseInt(args[1]),
                         args[2]);
    uriClient.connect();
  }

  public UriRetriever(String host, int port, String uri) {
    super(host, port);
    this.uri = uri;
  }

  /** Send one GET line, then read the results one line at a
   *  time, printing each to standard output.
   */

  // It is safe to use blocking IO (readLine), since
  // HTTP servers close connection when done, resulting
  // in a null value for readLine.

  protected void handleConnection(Socket uriSocket)
      throws IOException {
    PrintWriter out = SocketUtil.getWriter(uriSocket);
    BufferedReader in = SocketUtil.getReader(uriSocket);
    out.println("GET " + uri + " HTTP/1.0rn");
    String line;
    while ((line = in.readLine()) != null) {
      System.out.println("> " + line);
    }
  }
}


NetworkClient.java  Starting point for a network client to communicate with a remote computer

import java.net.*;
import java.io.*;

/** A starting point for network clients. You'll need to
 *  override handleConnection, but in many cases connect can
 *  remain unchanged. It uses SocketUtil to simplify the
 *  creation of the PrintWriter and BufferedReader.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class NetworkClient {
  protected String host;
  protected int port;

  /** Register host and port. The connection won't
   *  actually be established until you call
   *  connect.
   */

  public NetworkClient(String host, int port) {
    this.host = host;
    this.port = port;
  }

  /** Establishes the connection, then passes the socket
   *  to handleConnection.
   */

  public void connect() {
    try {
      Socket client = new Socket(host, port);
      handleConnection(client);
    } catch(UnknownHostException uhe) {
      System.out.println("Unknown host: " + host);
      uhe.printStackTrace();
    } catch(IOException ioe) {
      System.out.println("IOException: " + ioe);
      ioe.printStackTrace();
    }
  }

  /** This is the method you will override when
   *  making a network client for your task.
   *  The default version sends a single line
   *  ("Generic Network Client") to the server,
   *  reads one line of response, prints it, then exits.
   */

  protected void handleConnection(Socket client)
    throws IOException {
    PrintWriter out = SocketUtil.getWriter(client);
    BufferedReader in = SocketUtil.getReader(client);
    out.println("Generic Network Client");
    System.out.println
      ("Generic Network Client:n" +
       "Made connection to " + host +
       " and got '" + in.readLine() + "' in response");
    client.close();
  }

  /** The hostname of the server we're contacting. */

  public String getHost() {
    return(host);
  }

  /** The port connection will be made on. */

  public int getPort() {
    return(port);
  }
}

SocketUtil.java  Provides utilities for wrapping a BufferedReader  and PrintWriter around the Socket's input and output streams, respectively. 

import java.net.*;
import java.io.*;

/** A shorthand way to create BufferedReaders and
 *  PrintWriters associated with a Socket.
 *
 *  Taken from Core Web Programming from
 *  Prentice Hall and Sun Microsystems Press,
 *  .
 *  © 2001 Marty Hall and Larry Brown;
 *  may be freely used or adapted.
 */

public class SocketUtil {
  /** Make a BufferedReader to get incoming data. */

  public static BufferedReader getReader(Socket s)
      throws IOException {
    return(new BufferedReader(
       new InputStreamReader(s.getInputStream())));
  }

  /** Make a PrintWriter to send outgoing data.
   *  This PrintWriter will automatically flush stream
   *  when println is called.
   */

  public static PrintWriter getWriter(Socket s)
      throws IOException {
    // Second argument of true means autoflush.
    return(new PrintWriter(s.getOutputStream(), true));
  }
}



Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10230
Categories:Programming Code Examples, NULL, Network Programming
Tags:NULLNetwork Programming
Post Data:2017-01-02 16:04:28

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada

C++ Syntax: in brief #Programming #C++

This will make sense only if you want to refresh your memory on C++ syntax. 

cout << "Enter two integers:" << endl;           // output to screen
cin >> n >> m;    
// Note: Using endl prints out a newline and flushes the output buffer.

cout << "number of digits in char: " << numeric_limits::digits << 'n';


if (n > m) {                    // if n is bigger than m, swap them
    int temp = n;                 // declare temp and initialize it
    n = m;                        // assign value of m to n
    m = temp;                     // assign value of temp to m
}


long iii = i;          // implicit conversion from int to long
iii = long(i);         // explicit conversion from int to long  


for (double d = 1.1; d <= 9.9; d += 0.2) sum += sin(d);


using namespace std; 

#include  

int main() {

  using namespace std;
}


const int mxdigits = 999500;


int* p = &n;
int m = 200;
*p = m;


double* tryd = new double (x);

unsigned int jj = ii;


cout.width(2);
cout << i;


struct point2d {
  char nm;
  float x;
  float y;
};

point2d pt2 = { 'A', 3.14, -38 };


union val {
  int i;
  double d;
  char c;
};



double* tmv = new double[n];


int n = atoi(argv[1]);  // first integer is assigned to n


int* local = new int;
*local = 555;


namespace Vec {
  const int maxsize = 100000;             // a const number        
  double onenorm(double*, int);           // L 1 norm  
}

double Vec::onenorm(double* v, int size) { 
}



std::cout <<"Approx root near 7.7 by newton method is: " << root << 'n';


---
std::srand(time(0));                  // seed the random number generator
for (int i = 0; i< n; i++) dp[i]  = std::rand()%1000;
std::sort(dp, dp+n);      
---

double d = - 12345.678987654321;
cout.setf(ios_base::scientific, ios_base::floatfield);   // scientific format
cout.setf(ios_base::uppercase);
cout.width(25);
cout.precision(15);
cout.setf(ios_base::left, ios_base::adjustfield);        // adjust to left
cout << d << "n";
--------
double sum(int num, ...);
va_list argPtr;
va_start(argPtr, num);  // initialize argPrt. num is the last known argument

double sum = 0;

for( ; num; num--) {
   sum += va_arg(argPtr, double);   // argument of type double is returned
}

va_end(argPtr);          // deallocate stack pointed to by argPtr
return sum;

--
struct point2d {
  double x;
  double y;
  friend double norm(point2d p) {                   // a friend
    return sqrt(p.x*p.x + p.y*p.y);                 // distance to origin
  }
};
----
class triangle {
  point2d* vertices;
public:
  triangle(point2d, point2d, point2d);         // constructor  
  ~triangle() {      
   }                                           // destructor
  double area() const;                         // a function member 
};
----
class triple {                                  // a triple of numbers
  float* data;
public:
  triple(float a, float b, float c);            // constructor 
  ~triple() { }                                 // destructor, also defined here        
  friend triple add(const triple&, const triple&);      // add is a friend
};
inline triple::triple(const triple& t) {
  data = new float [3];
  for (int i = 0; i < 3; i++) data[i] = t.data[i];
}
-----
operator overloading
class Cmpx {      // class for complex numbers
private:
  double re;      // real part of a complex number
  double im;      // imaginal part of a complex number
public:
  Cmpx(double x = 0, double y = 0) { re =x; im =y; }  // constructor
  Cmpx& operator+=(Cmpx);                          // operator +=, eg z1 +=  z2
  Cmpx& operator-=(Cmpx);                          // operator -=, eg z1 -=  z2
  Cmpx& operator++();                              // prefix,  z1 = ++z
  Cmpx operator++(int);                            // postfix, z1 =  z++


  friend Cmpx operator*(Cmpx, Cmpx);                   // binary *, z = z1 * z2
  friend std::ostream& operator<<(std::ostream&, Cmpx);      // operator <<
  friend std::istream& operator>>(std::istream&, Cmpx&);     // operator >> 
};
----------------
template class Vcr {       
  int lenth;                       // number of entries in vector
  T* vr;                           // entries of the vector
public: 
  Vcr(int, T*);                    // constructor
  Vcr(const Vcr&);                 // copy constructor
  ~Vcr(){ delete[] vr; }           // destructor
 
};

// partial specialization
template class Vcr< complex > {       
  int lenth;                       // number of entries in vector
  complex* vr;                    // entries of the vector
public: 
  Vcr(int, complex*);              // constructor
  Vcr(const Vcr&);                 // copy constructor
  ~Vcr(){ delete[] vr; }           // destructor  
};


// complete specialization
template<>
class Vcr< complex > {       
  int lenth;                       // number of entries in vector
  complex* vr;             // entries of the vector
public: 
  Vcr(int, complex*);      // constructor
  Vcr(const Vcr&);                 // copy constructor
  ~Vcr(){ delete[] vr; }           // destructor
  
};
----------
complex aa = complex(3, 5);
---
 list nodes;                         // a list of integers for nodes

  nodes.push_front(10);              // add 10 at the beginning
  nodes.push_back(5);                // add 5 at the end
  nodes.pop_back();                  // remove last element
  nodes.remove(10);                  // remove element 10

for (list::iterator j = nodes.begin(); j != nodes.end(); j++) 
    cout << *j << "  ";              // *j is the element at position j

nodes.sort(); 
nodes.unique();
nodes.reverse();
nodes.insert(i, 2);                // insert before element that i refers to
  nodes.insert(i, 5, 7);             // insert 5 copies of 7
  nodes.erase(i);
ft.merge(sd);               // ft has the merged list, sd will be empty

list::iterator ii = find(ft.begin(), ft.end(), 5.5); 
  sd.splice(sd.begin(), ft, ii);     

----
VECTOR

std::vector vi(10);
for (int i = 0; i < 10; i++) vi[i] = (i-5)*i;
std::sort(vi.begin(),vi.end());
std::unique(vi.begin(),vi.end());

From: http://sitestree.com/?p=3525
Categories:Programming, C++
Tags:
Post Data:2016-07-07 16:00:12

Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada