The first section is a (partly nonsensical) example of the HTML highlighting that has nested PHP, JavaScript and CSS support.
This page also constitutes a decent example (for EBNF and my own language).
The highlighters for C# and C++ are lacking behind. They need to be more intelligent than the others, since their naming conventions aren't as readily useful for highlighting. I will fix this upon request.
If one of the languages aren't highlighted, try pressing Ctrl+F5 to update the JavaScript to the latest version.
<!-- this is taken in part from http://www.cssdrive.com/index.php/examples/exampleitem/tableless_forms/ -->
<style type="text/css">
label {
float: left;
width: 120px;
font-weight: bold;
}
input, textarea {
width: 180px;
margin-bottom: 5px;
}
.boxes {
width: 1em;
}
#submitbutton {
margin-left: 120px;
margin-top: 5px;
width: 90px;
}
</style>
<!-- this is taken from http://www.w3schools.com/JS/JS_examples.asp (modified) -->
<script type="text/javascript">
var r = Math.random();
if (r < 0.5) {
document.write("<a href='http://www.w3schools.com'>Learn Web Development!</a>");
} else {
document.write("<a href='http://www.refsnesdata.no'>Visit Refsnes Data!</a>");
}
</script>
<!-- rest of example taken from http://www.php-scripts.com/php_diary/122299.php3 (slightly modified) -->
<form method="POST" ENCTYPE="text/plain" action="mailto:youremail@yourdomain.com">
<p>
<select name="rating" size="1">
<option value="5">5 - Excellent, Extremely Useful</option>
<option value="4">4 - Very Good, Useful</option>
<option value="3">3 - Good, I learned something</option>
<option value="2">2 - Ok, but not really that useful</option>
<option value="1">1 - Not Useful At All, Sorry</option>
</select>
<input type="submit" value="Submit">
</p>
</form>
<?php
$security_domain = "www.php-scripts.com";
$url = explode("/", $HTTP_REFERER);
if(ereg($security_domain, $url[2])) {
print("<br>Came from domain: $security_domain");
$filesplit = explode(".", $url[4]);
$filename = $filesplit[0];
if(ereg("[0-9]{6}", $filename)) {
$filename .= ".dat";
print("<p>Filename chosen for diary page is $filename");
print("<p>Thanks for rating my page: $HTTP_REFERER with a rating of: $rating");
} else {
print("<p><strong>Sorry this is not a valid diary page</strong>");
}
} else {
print("<p><strong>Sorry, you cannot run this script from this location</strong>");
}
?>
// From: http://examples.oreilly.com/jenut/
// This example is from _Java Examples in a Nutshell_. (http://www.oreilly.com)
// Copyright (c) 1997 by David Flanagan
// This example is provided WITHOUT ANY WARRANTY either expressed or implied.
// You may study, use, modify, and distribute it for non-commercial purposes.
// For any commercial use, see http://www.davidflanagan.com/javaexamples
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;
/**
* A Java applet that simulates a client-side imagemap.
* Plays a sound whenever the user clicks on one of the hyperlinks.
*/
public class Soundmap extends Applet {
protected Image image; // The image to display.
protected Vector rects; // A list of rectangles in it.
protected AudioClip sound; // A sound to play on user clicks in a rectangle.
/** Initialize the applet */
public void init() {
// Look up the name of the image, relative to a base URL, and load it.
// Note the use of three Applet methods in this one line.
image = this.getImage(this.getDocumentBase(), this.getParameter("image"));
// Lookup and parse a list of rectangular areas and the URLs they map to.
// The convenience routine getRectangleParameter() is defined below.
rects = new Vector();
ImagemapRectangle r;
for(int i = 0; (r = getRectangleParameter("rect" + i)) != null; i++)
rects.addElement(r);
// Look up a sound to play when the user clicks one of those areas.
sound = this.getAudioClip(this.getDocumentBase(),
this.getParameter("sound"));
// Specify an "event listener" object to respond to mouse button
// presses and releases. Note that this is the Java 1.1 event model.
// Note that it also uses a Java 1.1 inner class, defined below.
this.addMouseListener(new Listener());
}
/** Called when the applet is being unloaded from the system.
* We use it here to "flush" the image we no longer need. This may
* result in memory and other resources being freed more quickly. */
public void destroy() { image.flush(); }
/** To display the applet, we simply draw the image. */
public void paint(Graphics g) { g.drawImage(image, 0, 0, this); }
/** We override this method so that it doesn't clear the background
* before calling paint(). No clear is necessary, since paint() overwrites
* everything with an image. Causes less flickering this way. */
public void update(Graphics g) { paint(g); }
/** Parse a comma-separated list of rectangle coordinates and a URL.
* Used to read the imagemap rectangle definitions from applet parameters */
protected ImagemapRectangle getRectangleParameter(String name) {
int x, y, w, h;
URL url;
String value = this.getParameter(name);
if (value == null) return null;
try {
StringTokenizer st = new StringTokenizer(value, ",");
x = Integer.parseInt(st.nextToken());
y = Integer.parseInt(st.nextToken());
w = Integer.parseInt(st.nextToken());
h = Integer.parseInt(st.nextToken());
url = new URL(this.getDocumentBase(), st.nextToken());
}
catch (NoSuchElementException e) { return null; }
catch (NumberFormatException e) { return null; }
catch (MalformedURLException e) { return null; }
return new ImagemapRectangle(x, y, w, h, url);
}
/**
* An instance of this inner class is used to respond to mouse events
*/
class Listener extends MouseAdapter {
/** The rectangle that the mouse was pressed in. */
private ImagemapRectangle lastrect;
/** Called when a mouse button is pressed. */
public void mousePressed(MouseEvent e) {
// On button down, check if we're inside one of the specified rectangles.
// If so, highlight the rectangle, display a message, and play a sound.
// The utility routine findrect() is defined below.
ImagemapRectangle r = findrect(e);
if (r == null) return;
Graphics g = Applet.this.getGraphics();
g.setXORMode(Color.red);
g.drawRect(r.x, r.y, r.width, r.height); // highlight rectangle
Applet.this.showStatus("To: " + r.url); // display URL
sound.play(); // play the sound
lastrect = r; // Remember the rectangle so it can be un-highlighted.
}
/** Called when a mouse button is released. */
public void mouseReleased(MouseEvent e) {
// When the button is released, unhighlight the rectangle. If the
// mouse is still inside it, ask the browser to go to the URL.
if (lastrect != null) {
Graphics g = Applet.this.getGraphics();
g.setXORMode(Color.red);
g.drawRect(lastrect.x, lastrect.y, lastrect.width, lastrect.height);
Applet.this.showStatus(""); // Clear the message.
ImagemapRectangle r = findrect(e);
if ((r != null) && (r == lastrect)) // If still in the same rectangle
Applet.this.getAppletContext().showDocument(r.url); // Go to the URL
lastrect = null;
}
}
/** Find the rectangle we're inside. */
protected ImagemapRectangle findrect(MouseEvent e) {
int i, x = e.getX(), y = e.getY();
for(i = 0; i < rects.size(); i++) {
ImagemapRectangle r = (ImagemapRectangle) rects.elementAt(i);
if (r.contains(x, y)) return r;
}
return null;
}
}
/**
* A helper class. Just like java.awt.Rectangle, but with a URL field.
* Note the use of a nested toplevel class for neatness.
*/
static class ImagemapRectangle extends Rectangle {
URL url;
public ImagemapRectangle(int x, int y, int w, int h, URL url) {
super(x, y, w, h);
this.url = url;
}
}
}
/* Example of Scala with embedded XML and multiline strings. */
object AddressBook {
case class Person(name: String, age: Int)
/** An AddressBook takes a variable number of arguments
* which are accessed as a Sequence
*/
class AddressBook(a: Person*) {
private val people: List[Person] = a.toList
/** Serialize to XHTML. Scala supports XML literals
* which may contain Scala expressions between braces,
* which are replaced by their evaluation
*/
def toXHTML =
<table cellpadding="2" cellspacing="0">
<tr>
<th>Last Name</th>
<th>First Name</th>
</tr>
{ for (val p <- people) yield
<tr>
<td> { p.name } </td>
<td> { p.age.toString() } </td>
</tr>
}
</table>;
}
/** We introduce CSS using raw strings (between triple
* quotes). Raw strings may contain newlines and special
* characters (like \) are not interpreted.
*/
val header =
<head>
<title>
{ "My Address Book" }
</title>
<style type="text/css"> {
"""table { border-right: 1px solid #cccccc; }
th { background-color: #cccccc; }
td { border-left: 1px solid #acacac; }
td { border-bottom: 1px solid #acacac;"""}
</style>
</head>;
val people = new AddressBook(
Person("Tom", 20),
Person("Bob", 22),
Person("James", 19));
val page =
<html>
{ header }
<body>
{ people.toXHTML }
</body>
</html>;
def main(args: Array[String]) {
println(page)
}
}
{- From http://www.angelfire.com/tx4/cus/shapes/haskell.html -}
module Rectangle(Rectangle, MakeRectangle, getWidth, getHeight, setWidth, setHeight)
where
import Shape
-- declare method interfaces for rectangle subclass
class Shape a => Rectangle a where
getWidth :: a -> Int
getHeight :: a -> Int
setWidth :: a -> Int -> a
setHeight :: a -> Int -> a
-- define the methods for shape superclass
instance Shape RectangleInstance where
getX = x
getY = y
setX a newx = a {x = newx}
setY a newy = a {y = newy}
moveTo a newx newy = a {x = newx, y = newy}
rMoveTo a deltax deltay = a {x = ((getX a) + deltax), y = ((getY a) + deltay)}
draw a =
putStrLn ("Drawing a Rectangle at:(" ++ (show (getX a)) ++ "," ++ (show (getY a)) ++
"), width " ++ (show (getWidth a)) ++ ", height " ++ (show (getHeight a)))
-- define the methods for rectangle subclass
instance Rectangle RectangleInstance where
getWidth = width
getHeight = height
setWidth a newwidth = a {width = newwidth}
setHeight a newheight = a {height = newheight}
-- declare the constructor for rectangle class
data RectangleInstance = MakeRectangle {x, y, width, height :: Int}
deriving(Eq, Show)
// From: http://haxe.org/doc/js/ajax
class Test {
// change the HTML content of a DIV based on its ID
static function setContent(id,content) {
var d = js.Lib.document.getElementById(id);
if( d == null )
js.Lib.alert("Unknown element : "+id);
d.innerHTML = content;
}
// create a javascript HTML link
static function makeLink(title,code) {
return '<a href="javascript:'+code+'">'+title+'</a>';
}
// function called when the user click on the link
static function click() {
setContent("main","Congratulations !");
}
static function main() {
// set initial content
setContent("main",makeLink("click here","Test.click()"));
}
}
// From: http://www.functionx.com/cpp/examples/gcd1.htm
#include <iostream>
using namespace std;
int GCD(int a, int b)
{
int Remainder;
while( b != 0 )
{
Remainder = a % b;
a = b;
b = Remainder;
}
return a;
}
int main()
{
int x, y;
cout << "This program allows calculating the GCD\n";
cout << "Value 1: ";
cin >> x;
cout << "Value 2: ";
cin >> y;
cout << "\nThe Greatest Common Divisor of "
<< x << " and " << y << " is " << GCD(x, y) << endl;
return 0;
}
// From: http://www.java2s.com/Code/CSharp/Services-Event/Ankeypresseventexample.htm
/*
C#: The Complete Reference
by Herbert Schildt
Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/
// An keypress event example.
using System;
// Derive a custom EventArgs class that holds the key.
class KeyEventArgs : EventArgs {
public char ch;
}
// Declare a delegate for an event.
delegate void KeyHandler(object source, KeyEventArgs arg);
// Declare a key-press event class.
class KeyEvent {
public event KeyHandler KeyPress;
// This is called when a key is pressed.
public void OnKeyPress(char key) {
KeyEventArgs k = new KeyEventArgs();
if(KeyPress != null) {
k.ch = key;
KeyPress(this, k);
}
}
}
// A class that receives key-press notifications.
class ProcessKey {
public void keyhandler(object source, KeyEventArgs arg) {
Console.WriteLine("Received keystroke: " + arg.ch);
}
}
// Another class that receives key-press notifications.
class CountKeys {
public int count = 0;
public void keyhandler(object source, KeyEventArgs arg) {
count++;
}
}
# From: http://johnbokma.com/perl/google-suggest.html
# gsuggest.pl - Google suggest
#
# © Copyright, 2004-2005 By John Bokma, http://johnbokma.com/
#
# Last updated: 2005-12-06 17:56:35 -0600
use strict;
use warnings;
use URI::Escape;
use LWP::UserAgent;
unless ( @ARGV ) {
print "usage: gsuggest.pl query\n";
exit( 1 );
}
my $url = 'http://www.google.com/complete/search?js=true&qu=' .
uri_escape( join ' ' => @ARGV );
my $ua = LWP::UserAgent->new( agent => 'Mozilla/5.0' );
my $response = $ua->get( $url );
$response->is_success or
die "$url: ", $response->status_line;
my $content = $response->content;
# extract the information from the JavaScript file response
# note that the first " and the last " in the Arrays are
# excluded (if data is present)
my ( $element, $array1, $array2 ) = $content =~
/"(.+?)".+?Array\("(.+?)"\).+?Array\("(.+?)"\)/;
unless ( defined $array1 ) {
print "No results\n";
exit;
}
# split the first "array" on the item separator (the very first "
# and the very last " are already removed)
my @suggestions = split /", "/, $array1;
# remove the result(s) string from the number of results
# remove if present (no results known)
# and split the second "array"
# note that a negative limit is used to catch trailing empty
# results (caused by removing )
$array2 =~ s/ results?//g;
$array2 =~ s/ //g;
my @results = split /", "/, $array2, -1;
# make suggestion => result(s) pairs.
# note that the number of results is turned into a right justified string
my @pairs = map { [ sprintf ( "%12s", shift @results ) => $_ ] } @suggestions;
# print the pairs in suggested order
print "@$_\n" for @pairs;
# print the pairs sorted on the number of results for each suggestion,
# largest "number" first since the numbers are right justified strings.
print "\nsorted:\n";
print "@$_\n" for sort { $b->[0] cmp $a->[0] } @pairs;
# From: http://jordan.husney.com/archives/2005/12/progress_bars_w_1.php
#!/bin/env ruby18
# copyright 2005, Jordan Husney <jordan@husney.com>
# (http://jordan.husney.com/main.html)
#
# derived directly from the following source and protected under
# the GNU GENERAL PUBLIC LICENSE, Version 2, June 1991
#
# http://db.org/demo/2003/02/17/progress-bar/?view=source
#
# php+gd dynamic progress bar image script.
# copyright 2003, B. Johannessen <bob@db.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version, and provided that the above
# copyright and permission notice is included with all distributed
# copies of this or derived software.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# A copy of the GNU General Public License is available from the GNU
# website at the following URL: http://www.gnu.org/licenses/gpl.txt
require 'rubygems'
require 'gd2'
class RubyProgressbar
include GD2
IMAGE_DIR = "./images/"
IMAGE_STYLES = [ 'winxp', 'osx', 'led', 'solaris' ]
public
def initialize
@image = nil
end
def create(style, width, completed, total)
# Check arugments:
raise ArgumentError, "style '#{style}' unknown" if
not IMAGE_STYLES.include?(style)
raise ArgumentError, "width must be between 64 and 1280 pixels" if
width < 64 || width > 1280
raise ArgumentError,
"completed must be greater than 0 and less than total" if
completed < 0 || completed > total
raise ArgumentError, "total must be greater than 0" if
total < 1
# Open images according to defined style:
begin
bg = Image.import(IMAGE_DIR + style + '-bg.png')
fill = Image.import(IMAGE_DIR + style + '-fill.png')
bg_cap = Image.import(IMAGE_DIR + style + '-bg-cap.png')
fill_cap = Image.import(IMAGE_DIR + style + '-fill-cap.png')
rescue Exception => e
raise "Unable to load required images for style #{style}!"
end
# calculate the fill width:
fill_width = (((width - bg_cap.width) * completed) / total).round -
fill_cap.width
# create the new image, and copy the fragments into it:
image = Image::TrueColor.new(width, bg.height)
image.copy_from(bg, 0, 0, 0, 0, bg.w, (width - bg_cap.w))
image.copy_from(bg_cap, (width - bg_cap.w), 0, 0, 0, bg_cap.w, bg_cap.h)
image.copy_from(fill, 0, 0, 0, 0, fill_width, fill.h)
image.copy_from(fill_cap, fill_width, 0, 0, 0, fill_cap.w, fill_cap.h)
@image = image
# return success
return true
end
def destroy
@image = nil
end
def gif()
raise Exception, "image not created" if @image.nil?
return @image.gif()
end
def jpeg(compression = nil)
raise Exception, "image not created" if @image.nil?
return @image.jpeg(compression)
end
def png(compression = nil)
raise Exception, "image not created" if @image.nil?
return @image.png(compression)
end
end