Introduction to the demo
Each snippet below is highlighted with some randomly generated settings. The settings are shown below the file names. One of the aim of the demo is to show that different themes can be shown in the same page.
6502asm.6502asm
Theme: dark, Line numbers: true
MainKernel
nop
ldy #PLAYAREAHEIGHT ;+2 72
KernelLoopOuter ; 72
SLEEP 4 ;+4 76
KernelLoopInner ; 76
sta HMOVE ;+3 3
lda #MAID_HEIGHT
dcp MaidLineCounter2
bcs DoDraw2
lda #0
.byte $2C
DoDraw2
lda (HeroGfx1Ptra),Y
sta GRP0 ;+18 21
lda ElevRAM,X
sta PF1 ;+7 28
lda #0
sta PF2 ;+5 33
lda ElevRAM+[NUM_RAMBANDS*3],X
sta PF1 ;+7 40
BackFromNoSpritesKernelMain
lda StairCaseTable,Y
sta HMBL ;+7 47
beq NoSpritesKernelMain ;+2 49
lda #MAID_HEIGHT ;+2 51
cpy HeroTop0
bpl SwitchDraw1 ;+5 56
dcp MaidLineCounter2 ;+5 61
lda (HeroGfx0Ptra),Y
sta GRP1 ; VDEL
lda (HeroColorPtra),Y
sta HMOVE ;+16 1
sta COLUP1 ;+3 4
BackFromSwitchDraw1
lda GameFlags3
eor BackgroundColorTable-1,Y
sta COLUBK ;+10 14
;--can't use SwitchDraw for P1 since P0 is VDELed - have to
; use DoDraw, which draws *something* every line.
; lda #MAID_HEIGHT
; dcp MaidLineCounter2
bcc NoDraw1
lda (HeroGfx1Ptrb),Y
sta GRP0 ;+10 24 too late? No.
lda #<[3.14 * 100]
sta pi
sta PF1 ;+5 29 too late? Maybe.
BackFromNoDraw1
lda ElevRAM+NUM_RAMBANDS,X
sta PF2 ;+7 36
sta.w HMCLR
lda ElevRAM+[NUM_RAMBANDS*2],X
cpy HeroTop0
sta PF2 ;+14 50
bpl WaitDraw3
lda (HeroGfx0Ptrb),Y
sta.w GRP1 ; VDEL
BackFromSwitchDraw3 ;+11 61
; nop
dey
tya
cmp ElevBandHeight,X
bne KernelLoopOuter ;+11 (72)
dex
bpl KernelLoopInner ;+5 76
; 75
sta HMOVE ;+3 2
cpy #0
bne NotDoneWithPlayAreaKernels ;+5 7
; 6
beq DoneWithPlayAreaKernels ;+3 9 branch always
actionscript.as
Theme: light, Line numbers: true
// Copyright: Hiroshi Ichikawa <http://gimite.net/en/>
// License: New BSD License
// Reference: http://dev.w3.org/html5/websockets/
// Reference: http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76
package {
import com.adobe.net.proxies.RFC2817Socket;
import com.gsolo.encryption.MD5;
import com.hurlant.crypto.tls.TLSConfig;
import com.hurlant.crypto.tls.TLSEngine;
import com.hurlant.crypto.tls.TLSSecurityParameters;
import com.hurlant.crypto.tls.TLSSocket;
import flash.display.*;
import flash.events.*;
import flash.external.*;
import flash.net.*;
import flash.system.*;
import flash.utils.*;
import mx.controls.*;
import mx.core.*;
import mx.events.*;
import mx.utils.*;
public class WebSocket extends EventDispatcher {
private static var CONNECTING:int = 0;
private static var OPEN:int = 1;
private static var CLOSING:int = 2;
private static var CLOSED:int = 3;
private var id:int;
private var rawSocket:Socket;
private var tlsSocket:TLSSocket;
private var tlsConfig:TLSConfig;
private var socket:Socket;
private var url:String;
private var scheme:String;
private var host:String;
private var port:uint;
private var path:String;
private var origin:String;
private var protocol:String;
private var buffer:ByteArray = new ByteArray();
private var headerState:int = 0;
private var readyState:int = CONNECTING;
private var cookie:String;
private var headers:String;
private var noiseChars:Array;
private var expectedDigest:String;
private var logger:IWebSocketLogger;
public function WebSocket(
id:int, url:String, protocol:String, origin:String,
proxyHost:String, proxyPort:int,
cookie:String, headers:String,
logger:IWebSocketLogger) {
this.logger = logger;
this.id = id;
initNoiseChars();
this.url = url;
var m:Array = url.match(/^(\w+):\/\/([^\/:]+)(:(\d+))?(\/.*)?(\?.*)?$/);
if (!m) fatal("SYNTAX_ERR: invalid url: " + url);
this.scheme = m[1];
this.host = m[2];
this.port = parseInt(m[4] || "80");
this.path = (m[5] || "/") + (m[6] || "");
this.origin = origin;
this.protocol = protocol;
this.cookie = cookie;
// if present and not the empty string, headers MUST end with \r\n
// headers should be zero or more complete lines, for example
// "Header1: xxx\r\nHeader2: yyyy\r\n"
this.headers = headers;
if (proxyHost != null && proxyPort != 0){
if (scheme == "wss") {
fatal("wss with proxy is not supported");
}
var proxySocket:RFC2817Socket = new RFC2817Socket();
proxySocket.setProxyInfo(proxyHost, proxyPort);
proxySocket.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData);
rawSocket = socket = proxySocket;
} else {
rawSocket = new Socket();
if (scheme == "wss") {
tlsConfig= new TLSConfig(TLSEngine.CLIENT,
null, null, null, null, null,
TLSSecurityParameters.PROTOCOL_VERSION);
tlsConfig.trustAllCertificates = true;
tlsConfig.ignoreCommonNameMismatch = true;
tlsSocket = new TLSSocket();
tlsSocket.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData);
socket = tlsSocket;
} else {
rawSocket.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData);
socket = rawSocket;
}
}
rawSocket.addEventListener(Event.CLOSE, onSocketClose);
rawSocket.addEventListener(Event.CONNECT, onSocketConnect);
rawSocket.addEventListener(IOErrorEvent.IO_ERROR, onSocketIoError);
rawSocket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSocketSecurityError);
rawSocket.connect(host, port);
}
/**
* @return This WebSocket's ID.
*/
public function getId():int {
return this.id;
}
/**
* @return this WebSocket's readyState.
*/
public function getReadyState():int {
return this.readyState;
}
public function send(encData:String):int {
var data:String = decodeURIComponent(encData);
if (readyState == OPEN) {
socket.writeByte(0x00);
socket.writeUTFBytes(data);
socket.writeByte(0xff);
socket.flush();
logger.log("sent: " + data);
return -1;
} else if (readyState == CLOSING || readyState == CLOSED) {
var bytes:ByteArray = new ByteArray();
bytes.writeUTFBytes(data);
return bytes.length; // not sure whether it should include \x00 and \xff
} else {
fatal("invalid state");
return 0;
}
}
public function close(isError:Boolean = false):void {
logger.log("close");
try {
if (readyState == OPEN && !isError) {
socket.writeByte(0xff);
socket.writeByte(0x00);
socket.flush();
}
socket.close();
} catch (ex:Error) { }
readyState = CLOSED;
this.dispatchEvent(new WebSocketEvent(isError ? "error" : "close"));
}
private function onSocketConnect(event:Event):void {
logger.log("connected");
if (scheme == "wss") {
logger.log("starting SSL/TLS");
tlsSocket.startTLS(rawSocket, host, tlsConfig);
}
var hostValue:String = host + (port == 80 ? "" : ":" + port);
var key1:String = generateKey();
var key2:String = generateKey();
var key3:String = generateKey3();
expectedDigest = getSecurityDigest(key1, key2, key3);
var opt:String = "";
if (protocol) opt += "Sec-WebSocket-Protocol: " + protocol + "\r\n";
// if caller passes additional headers they must end with "\r\n"
if (headers) opt += headers;
var req:String = StringUtil.substitute(
"GET {0} HTTP/1.1\r\n" +
"Upgrade: WebSocket\r\n" +
"Connection: Upgrade\r\n" +
"Host: {1}\r\n" +
"Origin: {2}\r\n" +
"Cookie: {3}\r\n" +
"Sec-WebSocket-Key1: {4}\r\n" +
"Sec-WebSocket-Key2: {5}\r\n" +
"{6}" +
"\r\n",
path, hostValue, origin, cookie, key1, key2, opt);
logger.log("request header:\n" + req);
socket.writeUTFBytes(req);
logger.log("sent key3: " + key3);
writeBytes(key3);
socket.flush();
}
private function onSocketClose(event:Event):void {
logger.log("closed");
readyState = CLOSED;
this.dispatchEvent(new WebSocketEvent("close"));
}
private function onSocketIoError(event:IOErrorEvent):void {
var message:String;
if (readyState == CONNECTING) {
message = "cannot connect to Web Socket server at " + url + " (IoError)";
} else {
message = "error communicating with Web Socket server at " + url + " (IoError)";
}
onError(message);
}
private function onSocketSecurityError(event:SecurityErrorEvent):void {
var message:String;
if (readyState == CONNECTING) {
message =
"cannot connect to Web Socket server at " + url + " (SecurityError)\n" +
"make sure the server is running and Flash socket policy file is correctly placed";
} else {
message = "error communicating with Web Socket server at " + url + " (SecurityError)";
}
onError(message);
}
private function onError(message:String):void {
if (readyState == CLOSED) return;
logger.error(message);
close(readyState != CONNECTING);
}
private function onSocketData(event:ProgressEvent):void {
var pos:int = buffer.length;
socket.readBytes(buffer, pos);
for (; pos < buffer.length; ++pos) {
if (headerState < 4) {
// try to find "\r\n\r\n"
if ((headerState == 0 || headerState == 2) && buffer[pos] == 0x0d) {
++headerState;
} else if ((headerState == 1 || headerState == 3) && buffer[pos] == 0x0a) {
++headerState;
} else {
headerState = 0;
}
if (headerState == 4) {
var headerStr:String = readUTFBytes(buffer, 0, pos + 1);
logger.log("response header:\n" + headerStr);
if (!validateHeader(headerStr)) return;
removeBufferBefore(pos + 1);
pos = -1;
}
} else if (headerState == 4) {
if (pos == 15) {
var replyDigest:String = readBytes(buffer, 0, 16);
logger.log("reply digest: " + replyDigest);
if (replyDigest != expectedDigest) {
onError("digest doesn't match: " + replyDigest + " != " + expectedDigest);
return;
}
headerState = 5;
removeBufferBefore(pos + 1);
pos = -1;
readyState = OPEN;
this.dispatchEvent(new WebSocketEvent("open"));
}
} else {
if (buffer[pos] == 0xff && pos > 0) {
if (buffer[0] != 0x00) {
onError("data must start with \\x00");
return;
}
var data:String = readUTFBytes(buffer, 1, pos - 1);
logger.log("received: " + data);
this.dispatchEvent(new WebSocketEvent("message", encodeURIComponent(data)));
removeBufferBefore(pos + 1);
pos = -1;
} else if (pos == 1 && buffer[0] == 0xff && buffer[1] == 0x00) { // closing
logger.log("received closing packet");
removeBufferBefore(pos + 1);
pos = -1;
close();
}
}
}
}
private function validateHeader(headerStr:String):Boolean {
var lines:Array = headerStr.split(/\r\n/);
if (!lines[0].match(/^HTTP\/1.1 101 /)) {
onError("bad response: " + lines[0]);
return false;
}
var header:Object = {};
var lowerHeader:Object = {};
for (var i:int = 1; i < lines.length; ++i) {
if (lines[i].length == 0) continue;
var m:Array = lines[i].match(/^(\S+): (.*)$/);
if (!m) {
onError("failed to parse response header line: " + lines[i]);
return false;
}
header[m[1].toLowerCase()] = m[2];
lowerHeader[m[1].toLowerCase()] = m[2].toLowerCase();
}
if (lowerHeader["upgrade"] != "websocket") {
onError("invalid Upgrade: " + header["Upgrade"]);
return false;
}
if (lowerHeader["connection"] != "upgrade") {
onError("invalid Connection: " + header["Connection"]);
return false;
}
if (!lowerHeader["sec-websocket-origin"]) {
if (lowerHeader["websocket-origin"]) {
onError(
"The WebSocket server speaks old WebSocket protocol, " +
"which is not supported by web-socket-js. " +
"It requires WebSocket protocol 76 or later. " +
"Try newer version of the server if available.");
} else {
onError("header Sec-WebSocket-Origin is missing");
}
return false;
}
var resOrigin:String = lowerHeader["sec-websocket-origin"];
if (resOrigin != origin) {
onError("origin doesn't match: '" + resOrigin + "' != '" + origin + "'");
return false;
}
if (protocol && header["sec-websocket-protocol"] != protocol) {
onError("protocol doesn't match: '" +
header["websocket-protocol"] + "' != '" + protocol + "'");
return false;
}
return true;
}
private function removeBufferBefore(pos:int):void {
if (pos == 0) return;
var nextBuffer:ByteArray = new ByteArray();
buffer.position = pos;
buffer.readBytes(nextBuffer);
buffer = nextBuffer;
}
private function initNoiseChars():void {
noiseChars = new Array();
for (var i:int = 0x21; i <= 0x2f; ++i) {
noiseChars.push(String.fromCharCode(i));
}
for (var j:int = 0x3a; j <= 0x7a; ++j) {
noiseChars.push(String.fromCharCode(j));
}
}
private function generateKey():String {
var spaces:uint = randomInt(1, 12);
var max:uint = uint.MAX_VALUE / spaces;
var number:uint = randomInt(0, max);
var key:String = (number * spaces).toString();
var noises:int = randomInt(1, 12);
var pos:int;
for (var i:int = 0; i < noises; ++i) {
var char:String = noiseChars[randomInt(0, noiseChars.length - 1)];
pos = randomInt(0, key.length);
key = key.substr(0, pos) + char + key.substr(pos);
}
for (var j:int = 0; j < spaces; ++j) {
pos = randomInt(1, key.length - 1);
key = key.substr(0, pos) + " " + key.substr(pos);
}
return key;
}
private function generateKey3():String {
var key3:String = "";
for (var i:int = 0; i < 8; ++i) {
key3 += String.fromCharCode(randomInt(0, 255));
}
return key3;
}
private function getSecurityDigest(key1:String, key2:String, key3:String):String {
var bytes1:String = keyToBytes(key1);
var bytes2:String = keyToBytes(key2);
return MD5.rstr_md5(bytes1 + bytes2 + key3);
}
private function keyToBytes(key:String):String {
var keyNum:uint = parseInt(key.replace(/[^\d]/g, ""));
var spaces:uint = 0;
for (var i:int = 0; i < key.length; ++i) {
if (key.charAt(i) == " ") ++spaces;
}
var resultNum:uint = keyNum / spaces;
var bytes:String = "";
for (var j:int = 3; j >= 0; --j) {
bytes += String.fromCharCode((resultNum >> (j * 8)) & 0xff);
}
return bytes;
}
// Writes byte sequence to socket.
// bytes is String in special format where bytes[i] is i-th byte, not i-th character.
private function writeBytes(bytes:String):void {
for (var i:int = 0; i < bytes.length; ++i) {
socket.writeByte(bytes.charCodeAt(i));
}
}
// Reads specified number of bytes from buffer, and returns it as special format String
// where bytes[i] is i-th byte (not i-th character).
private function readBytes(buffer:ByteArray, start:int, numBytes:int):String {
buffer.position = start;
var bytes:String = "";
for (var i:int = 0; i < numBytes; ++i) {
// & 0xff is to make \x80-\xff positive number.
bytes += String.fromCharCode(buffer.readByte() & 0xff);
}
return bytes;
}
private function readUTFBytes(buffer:ByteArray, start:int, numBytes:int):String {
buffer.position = start;
var data:String = "";
for(var i:int = start; i < start + numBytes; ++i) {
// Workaround of a bug of ByteArray#readUTFBytes() that bytes after "\x00" is discarded.
if (buffer[i] == 0x00) {
data += buffer.readUTFBytes(i - buffer.position) + "\x00";
buffer.position = i + 1;
}
}
data += buffer.readUTFBytes(start + numBytes - buffer.position);
return data;
}
private function randomInt(min:uint, max:uint):uint {
return min + Math.floor(Math.random() * (Number(max) - min + 1));
}
private function fatal(message:String):void {
logger.error(message);
throw message;
}
// for debug
private function dumpBytes(bytes:String):void {
var output:String = "";
for (var i:int = 0; i < bytes.length; ++i) {
output += bytes.charCodeAt(i).toString() + ", ";
}
logger.log(output);
}
}
}
//other tests
class Foo implements IInterface1, IInterface2, IInterface3 {}
bash.sh
Theme: light, Line numbers: true
#!/bin/bash
echo "Starting the script, yo"
#this is a comment
DIR=/var/log
cd $DIR
my_function () {
rm -rf "$1"
return 0
}
for planet in Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune Pluto
do
echo $planet # Each planet on a separate line.
done
my_function $DIR
if [ $# -ne 2 ]
then
echo "Usage: `basename $0` search_string filename"
exit 65
fi
while [ "$var1" != "end" ] # while test "$var1" != "end"
do
echo "Input variable #1 (end to exit) "
read var1 # Not 'read $var1' (why?).
echo "variable #1 = $var1" # Need quotes because of "#" . . .
# If input is 'end', echoes it here.
# Does not test for termination condition until top of loop.
echo
done
count=1
let "count += 1"
case "$Keypress" in
[[:lower:]] ) echo "Lowercase letter";;
[[:upper:]] ) echo "Uppercase letter";;
[0-9] ) echo "Digit";;
* ) echo "Punctuation, whitespace, or other";;
esac
echo $?
echo `echo running a command`
exit 0 #exit
batch1.bat
Theme: light, Line numbers: false
REM http://en.wikipedia.org/wiki/Batch_file#Advanced_batch_example_-_conditional_shutdown
@echo off
color 3
title Conditional Shutdown
set /p name=enter a name:
:start
cls
echo Hi, %name%
echo.
echo 1.Shutdown
echo 2.Quit
:invalid_choice
set /p choice=enter your choice 1,2:
if %choice%==1 goto shutdown
if %choice%==2 exit
echo invalid choice: %choice%
goto invalid_choice
:shutdown
cls
set /p sec=enter the number of seconds that you wish the computer to shutdown in:
set /p message=enter the shutdown message you wish to display:
shutdown -s -f -t %sec% -c "%message%"
echo shutdown initiated at %time%
set /p cancel=type cancel to stop shutdown
if %cancel%==cancel shutdown -a
if %cancel%==cancel goto start
:: http://en.wikipedia.org/wiki/Batch_file#Text_output_with_stripped_CR.2FLF
set foo=Line 1
echo y | set /p tmp="%foo%"
echo Line 2
echo Line 3
REM http://en.wikipedia.org/wiki/Batch_file#Sleep_.2F_Scripted_Delay
for /f "tokens=1-3 delims=:.," %%a in ("%time%") do set /a h=%%a, m=1%%b%%100, s=1%%c%%100, end=(h*60+m)*60+s+%1
:wait
for /f "tokens=1-3 delims=:.," %%a in ("%time%") do set /a h=%%a, m=1%%b%%100, s=1%%c%%100, current=(h*60+m)*60+s
if %current% lss %end% goto wait
batch2.bat
Theme: light, Line numbers: true
brainfuck.bf
Theme: dark, Line numbers: false
[ http://bf.doleczek.pl ]
wypisuje kody wpisanych znaków
++++ ++++ [>+++++++>++++<<-]>++>>>+
[,.<<<.>.>>[>>+>+<<<-]>>>[<<<+>>>-]<<+>[<->[>++++++++++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]
++++++++[<++++++>-]>[<<+>>-]>[<<+>>-]<<]>]<[->>++++++++[<++++++>-]]<[.[-]<]+++++ +++++ +++.[-]<]
cpp.cpp
Theme: gitbook, Line numbers: true
#include <iostream>
using namespace std;
float Perimeter(float l, float w) {
double p;
p = 2 * (l + w);
return p;
}
//http://hg.mozilla.org/tracemonkey/file/dc6ce44bedd4/chrome/src/nsChromeRegistry.cpp
void
nsChromeRegistry::LogMessageWithContext(nsIURI* aURL, PRUint32 aLineNumber, PRUint32 flags,
const char* aMsg, ...)
{
nsresult rv;
nsCOMPtr<nsIConsoleService> console
(do_GetService(NS_CONSOLESERVICE_CONTRACTID));
nsCOMPtr<nsIScriptError> error
(do_CreateInstance(NS_SCRIPTERROR_CONTRACTID));
if (!console || !error)
return;
va_list args;
va_start(args, aMsg);
char* formatted = PR_vsmprintf(aMsg, args);
va_end(args);
if (!formatted)
return;
nsCString spec;
if (aURL)
aURL->GetSpec(spec);
rv = error->Init(NS_ConvertUTF8toUTF16(formatted).get(),
NS_ConvertUTF8toUTF16(spec).get(),
nsnull,
aLineNumber, 0, flags, "chrome registration");
PR_smprintf_free(formatted);
if (NS_FAILED(rv))
return;
console->LogMessage(error);
}
int regexStuff() {
std::regex phoneRegex(R"(\d{3}-\d{4})");
std::string input = "Jenny: 867-5309";
auto cur = input.begin(), end = input.end();
std::smatch phoneMatch;
while (std::regex_search(cur, end, phoneMatch, phoneRegex) {
std::cout << "I got it: " << phoneMatch.str() << std::endl;
cur = phoneMatch[0].second;
}
}
class IntList {
public:
IntList();
void AddToEnd(int k);
void Print(ostream &output) const;
private:
static const int SIZE = 10;
int *Items;
int numItems;
int arraySize;
};
class CRectangle {
int width, height;
public:
int area() {
lolPointer * myPointer = (pointerCast*)cast;
lolPointer2** anotherPointer;
other myPointer = (regularCast)cast;
padd = (ReferenceCast*)&d;
int result = firstIdent1 * secondIdent1;
result = (firstIdent2 * secondIdent2);
result = firstIdent3 & secondIdent3;
result = (firstIdent4 & secondIdent4);
}
void convert(CSquare a);
};
class CSquare {
private:
int side;
public:
void set_side(int a) {
side = a;
}
friend class CRectangle;
};
void CRectangle::convert(CSquare a) {
width = a.side;
height = a.side;
}
template <typename T>
inline T const& max(T const& a, T const& b) {
// if a < b then use b else use a
return a < b ? b : a;
}
template <class T, int N>
void mysequence<T, N>::setmember(int x, T value) {
memblock[x] = value;
}
template <class MyTemplateClass, int N>
T mysequence<T, N>::getmember(int x) {
return memblock[x];
}
csharp1.cs
Theme: gitbook, Line numbers: true
extern alias GridV1;
using System;
using UsingAlias = My.Namespace.UsingThisClass;
namespace My.Namespace {
[NotAnAttribute.FullyQualifiedAttribute]
public abstract class ValueHandlerFactoryBase<T1, T2, in TClass1> : MarshalByRefObject, IValueHandlerFactory, IAmAnInterface
where TClass1Constraint : IAmATypeConstraint
where T2 : T1
{
[Obsolete] private Skank foo;
public const Stripper bar = "foo";
protected static readonly DirtyWhore baz = 0xffffff;
#if NET_20
private ArrayList list = new ArrayList();
#endif
[AnAttribute(typeof(Exception), Message = "foo"]
protected internal class InternalClass<TClass2, out TClass3> : ICloneable where TClass2Constraint : class, IAfterClassConstraint, ISecondConstraint {
void Iterate(ICollection<object> foos) {
foreach (var foo in foos) {
if (foo is MyNamespace.TypeAfterIs) {
this.SomeMethod(ref foo, out foo);
}
var chars = new[] { 'c', '\'', '\\' };
}
}
}
#region verify that casts are properly colored
partial void Meh(AnotherArrayOfSomething[] somethings) {
IDisposable foo = (IDisposable)foo as ICloneable;
foo.Dispose();
((IDisposable)this).Dispose();
var lame = typeof(IDisposable);
if (notACast) methodCall();
}
#endregion
/**
* Gets or sets the value of an integer
* and such. This is a useful comment.
*/
public new Object PropertyAccessor {
get {
var get = foo > 0 ? new Integer[initialArrayLength] : new Integer[0];
return new List<object> {
get
};
}
private set {
var set = value;
value = value;
value == value ? DoSomething() : DoSomethingElse();
this.value = set ?? value;
}
}
public string AutomaticProperty {
get; private set;
}
private static Func<Object, char> GetFunction(Object o, Character c, Integer[] integers) {
if (!Object.ReferenceEquals(o, c)) {
throw new ArgumentException();
}
return value => (char)value.GetHashCode();
}
/// <summary>
/// Tests the coloring of generic method definitions and
/// and <c cref="Foo">generic parameters</c>
/// </summary>
///
/// <param name="foos">Collection of <see cref="Foo" /></param>
[FirstAttribute]
[Pure(typeof(IDisposable[])), OutOfThisWorld, ThirdAttribute]
[OutOfThisWorld(AttributeNamedParameter = "foo")]
[Another]
Action<IDisposable> DoOtherStuff(IEnumerable<Foo> fooEnumerable, string[] strings) {
Action<Func<IDisposable, SecondGeneric>> action = () => disposable => new Foo();
//neither foo below should be a named ident
return foo < 1 || foo > 2;
}
public IEnumerable<TReturnValue> GenericMethod<TMethod>(GenericCollection1<TParameter> shouldNotBeNamed, GenericCollection2<TGenericTest4> somethingElse) {
container.GenericMethodInvocation<GenericMethodDefinition>();
var options = OptionParser.Parse<Contract>(args);
expression.ArrayAccess[0].Name; //ArrayAccess should not be a named ident
}
//method without an access modifier: "Action" should be a named ident
Action DoStuff() {
Fully1.Qualified1.FullyQualifiedClass1 fqc = new Fully2.Qualified2.FullyQualifiedClass2();
}
protected override sealed TNotNamed NumbersTest<T>(ref Foo foo, out Bar @class, params ArrayOfSomething[] somethings) where T : event, IDisposable, IFoo {
//let's test out numbers
int i = 0;
double d = 1.5;
float f = (1.7f + 1.2d) * (12 % 5);
decimal dec = 1.2d;
int hex = 0x1a; //ooh! hex!
return default(TAlsoNotNamed);
}
public virtual IValueHandler Create(string resourceName, string criterionFieldName) {
//1) check for resource-specific value handler
VerifyStuff((int)resourceName);
/* multi
line comment
*/
var s = "this is \"a\" string";
s = @"this is ""another""
multi line
string";
switch (Foo.Bar) {
case "foo":
if (2 |= Foo["foo"]) {
throw new InvalidOperationException(string.Format("fail"));
}
break;
case "bar":
goto default;
case Empty:
return "foo";
default:
yield return new TanningBooth();
}
}
}
}
csharp2.cs
Theme: gitbook, Line numbers: false
UndefinedTokenFix<Foo> undefinedTokenFix = new List<Foo>();
csharp3.cs
Theme: gitbook, Line numbers: true
css.css
Theme: gitbook, Line numbers: true
@import "/my/style/sheet.css";
@import url(/my/style/sheet.css) screen "Print style\"s";
html div.myClass {
width: 100%;
min-height: 100%;
opacity: 0.0;
background: transparent url(foo.png) no-repeat;
background-color: #000000;
color: white;
font-family: "Courier New", 'Arialola\'s', sans-serif;
}
body > .warning {
color: #FF0000;
background-image: url(warning.png); /* ".png" should not be colored as a class */
border: 2px solid none;
border-image: url(warning.png);
border-radius: url(warning.png);
border-top: 1px dotted #FFFFFF;
border-top-color: magenta;
filter: progid:DXImageTransform.Microsoft.Alpha(opacity = 50);
filter: alpha(opacity=50);
opacity: 0.5;
}
#wrapper div[lang~="en"]:first-child::before {
text-decoration: underline overline;
padding-left: 12px;
width: 50%;
position: fixed;
display: inline-block;
}
a:fake-pseudo-class {
transform: rotate(5deg);
-moz-background-inline-policy: -moz-initial;
-o-device-pixel-ratio: meh;
-webkit-background-origin: lolwut;
-ms-accelerator: snoo-snoo !important;
zoom: 1; /* IE crap */
vertical-align: middle;
}
/* new clearfix */
.clearfix:after {
visibility: hidden;
display: block;
font-size: 0;
content: " ";
clear: both;
height: 0;
}
* html .clearfix { zoom: 1; } /* IE6 */
*:first-child+shouldBeNamed .shouldBeNamed { zoom: 1; } /* IE7 */
pseudotest1:before, pseudotest2:after {
/* stuff goes here */
}
/* do not mix up id selectors and hex color */
#abc {
color: #12345678;
background-color: #def;
}
diff.diff
Theme: gitbook, Line numbers: true
Index: path/to/file.cpp
===================================================================
--- /path/to/original ''timestamp''
+++ /path/to/new ''timestamp''
@@ -1,3 +1,9 @@
+This is an important
+notice! It should
+therefore be located at
+the beginning of this
+document!
+
This part of the
document has stayed the
same from version to
@@ -5,16 +11,10 @@
be shown if it doesn't
change. Otherwise, that
would not be helping to
-compress the size of the
-changes.
-
-This paragraph contains
-text that is outdated.
-It will be deleted in the
-near future.
+compress anything.
It is important to spell
-check this dokument. On
+check this document. On
the other hand, a
misspelled word isn't
the end of the world.
@@ -22,3 +22,7 @@
this paragraph needs to
be changed. Things can
be added after it.
+
+This paragraph contains
+important new additions
+to this document.
*** /path/to/original ''timestamp''
--- /path/to/new ''timestamp''
***************
*** 1,3 ****
--- 1,9 ----
+ This is an important
+ notice! It should
+ therefore be located at
+ the beginning of this
+ document!
+
This part of the
document has stayed the
same from version to
***************
*** 5,20 ****
be shown if it doesn't
change. Otherwise, that
would not be helping to
! compress the size of the
! changes.
!
! This paragraph contains
! text that is outdated.
! It will be deleted in the
! near future.
It is important to spell
! check this dokument. On
the other hand, a
misspelled word isn't
the end of the world.
--- 11,20 ----
be shown if it doesn't
change. Otherwise, that
would not be helping to
! compress anything.
It is important to spell
! check this document. On
the other hand, a
misspelled word isn't
the end of the world.
***************
*** 22,24 ****
--- 22,28 ----
this paragraph needs to
be changed. Things can
be added after it.
+
+ This paragraph contains
+ important new additions
+ to this document.
\ No newline at end of file
erlang1.erl
Theme: gitbook, Line numbers: false
-module(talk2).
-compile(export_all).
start() ->
OtherNode = clean(io:get_line('What node? ')),
FullNode = string:concat(OtherNode, "@localhost"),
io:format("talking to: ~s~n", [FullNode]),
register(receiver, spawn(?MODULE, receiver, [])),
register(sender, spawn(?MODULE, sender, [list_to_atom(FullNode)])),
get_input().
get_input() ->
Message = clean(io:get_line('Talk: ')),
case string:equal("exit!", Message) of
true ->
receiver ! done,
sender ! done;
false ->
talk(Message),
get_input()
end.
talk(Message) ->
sender ! {send, Message}.
sender(OtherNode) ->
receive
{send, Message} ->
rpc:call(OtherNode, talk2, send_message, [Message]),
sender(OtherNode);
done ->
void
end.
% Add extra spaces after send_message to test the highlighter.
send_message (Message) ->
receiver ! {message, Message}.
% Remove the space between () and -> to test the highlighter.
receiver()->
receive
{message, Message} ->
io:format("~s~n", [Message]),
receiver();
done ->
void
end.
clean(Data) ->
string:strip(Data, both, $\n).
erlang2.erl
Theme: gitbook, Line numbers: true
var parser = new Butterfly.Parser().loadDefaultStrategies(), timeout, current;
$("#markup").keydown(function(e) {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
timeout = setTimeout(render, 200);
});
function render() {
var text = $("#markup").val();
if (text === current) {
return;
}
current = text;
var $html = $("#html").removeClass("error").empty();
var startTime = new Date().getTime();
try {
var html = parser.parseAndReturn(text);
$html.html(html);
} catch (e) {
$html.addClass("error").html("<p/>").text(e.toString());
}
parser.analyzer.flush();
$("#elapsed-time").empty().text((new Date().getTime() - startTime) + "ms");
Sunlight.highlightAll();
}
render();
haskell.hs
Theme: light, Line numbers: true
-----------------------------------------------------------------------------
-- |
-- Module : Text.PrettyPrint.HughesPJ
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : provisional
-- Portability : portable
--
-- John Hughes's and Simon Peyton Jones's Pretty Printer Combinators
--
-- Based on /The Design of a Pretty-printing Library/
-- in Advanced Functional Programming,
-- Johan Jeuring and Erik Meijer (eds), LNCS 925
-- <http://www.cs.chalmers.se/~rjmh/Papers/pretty.ps>
--
-- Heavily modified by Simon Peyton Jones, Dec 96
--
-----------------------------------------------------------------------------
{-
Version 3.0 28 May 1997
* Cured massive performance bug. If you write
foldl <> empty (map (text.show) [1..10000])
you get quadratic behaviour with V2.0. Why? For just the same
reason as you get quadratic behaviour with left-associated (++)
chains.
This is really bad news. One thing a pretty-printer abstraction
should certainly guarantee is insensivity to associativity. It
matters: suddenly GHC's compilation times went up by a factor of
100 when I switched to the new pretty printer.
I fixed it with a bit of a hack (because I wanted to get GHC back
on the road). I added two new constructors to the Doc type, Above
and Beside:
<> = Beside
$$ = Above
Then, where I need to get to a "TextBeside" or "NilAbove" form I
"force" the Doc to squeeze out these suspended calls to Beside and
Above; but in so doing I re-associate. It's quite simple, but I'm
not satisfied that I've done the best possible job. I'll send you
the code if you are interested.
* Added new exports:
punctuate, hang
int, integer, float, double, rational,
lparen, rparen, lbrack, rbrack, lbrace, rbrace,
* fullRender's type signature has changed. Rather than producing a
string it now takes an extra couple of arguments that tells it how
to glue fragments of output together:
fullRender :: Mode
-> Int -- Line length
-> Float -- Ribbons per line
-> (TextDetails -> a -> a) -- What to do with text
-> a -- What to do at the end
-> Doc
-> a -- Result
The "fragments" are encapsulated in the TextDetails data type:
data TextDetails = Chr Char
| Str String
| PStr FAST_STRING
The Chr and Str constructors are obvious enough. The PStr
constructor has a packed string (FAST_STRING) inside it. It's
generated by using the new "ptext" export.
An advantage of this new setup is that you can get the renderer to
do output directly (by passing in a function of type (TextDetails
-> IO () -> IO ()), rather than producing a string that you then
print.
Version 2.0 24 April 1997
* Made empty into a left unit for <> as well as a right unit;
it is also now true that
nest k empty = empty
which wasn't true before.
* Fixed an obscure bug in sep that occassionally gave very weird behaviour
* Added $+$
* Corrected and tidied up the laws and invariants
======================================================================
Relative to John's original paper, there are the following new features:
1. There's an empty document, "empty". It's a left and right unit for
both <> and $$, and anywhere in the argument list for
sep, hcat, hsep, vcat, fcat etc.
It is Really Useful in practice.
2. There is a paragraph-fill combinator, fsep, that's much like sep,
only it keeps fitting things on one line until it can't fit any more.
3. Some random useful extra combinators are provided.
<+> puts its arguments beside each other with a space between them,
unless either argument is empty in which case it returns the other
hcat is a list version of <>
hsep is a list version of <+>
vcat is a list version of $$
sep (separate) is either like hsep or like vcat, depending on what fits
cat behaves like sep, but it uses <> for horizontal conposition
fcat behaves like fsep, but it uses <> for horizontal conposition
These new ones do the obvious things:
char, semi, comma, colon, space,
parens, brackets, braces,
quotes, doubleQuotes
4. The "above" combinator, $$, now overlaps its two arguments if the
last line of the top argument stops before the first line of the
second begins.
For example: text "hi" $$ nest 5 (text "there")
lays out as
hi there
rather than
hi
there
There are two places this is really useful
a) When making labelled blocks, like this:
Left -> code for left
Right -> code for right
LongLongLongLabel ->
code for longlonglonglabel
The block is on the same line as the label if the label is
short, but on the next line otherwise.
b) When laying out lists like this:
[ first
, second
, third
]
which some people like. But if the list fits on one line
you want [first, second, third]. You can't do this with
John's original combinators, but it's quite easy with the
new $$.
The combinator $+$ gives the original "never-overlap" behaviour.
5. Several different renderers are provided:
* a standard one
* one that uses cut-marks to avoid deeply-nested documents
simply piling up in the right-hand margin
* one that ignores indentation (fewer chars output; good for machines)
* one that ignores indentation and newlines (ditto, only more so)
6. Numerous implementation tidy-ups
Use of unboxed data types to speed up the implementation
-}
module Text.PrettyPrint.HughesPJ (
-- * The document type
Doc, -- Abstract
-- * Constructing documents
-- ** Converting values into documents
char, text, ptext,
int, integer, float, double, rational,
-- ** Simple derived documents
semi, comma, colon, space, equals,
lparen, rparen, lbrack, rbrack, lbrace, rbrace,
-- ** Wrapping documents in delimiters
parens, brackets, braces, quotes, doubleQuotes,
-- ** Combining documents
empty,
(<>), (<+>), hcat, hsep,
($$), ($+$), vcat,
sep, cat,
fsep, fcat,
nest,
hang, punctuate,
-- * Predicates on documents
isEmpty,
-- * Rendering documents
-- ** Default rendering
render,
-- ** Rendering with a particular style
Style(..),
style,
renderStyle,
-- ** General rendering
fullRender,
Mode(..), TextDetails(..),
) where
import Prelude
infixl 6 <>
infixl 6 <+>
infixl 5 $$, $+$
-- ---------------------------------------------------------------------------
-- The interface
-- The primitive Doc values
isEmpty :: Doc -> Bool; -- ^ Returns 'True' if the document is empty
-- | The empty document, with no height and no width.
-- 'empty' is the identity for '<>', '<+>', '$$' and '$+$', and anywhere
-- in the argument list for 'sep', 'hcat', 'hsep', 'vcat', 'fcat' etc.
empty :: Doc
semi :: Doc; -- ^ A ';' character
comma :: Doc; -- ^ A ',' character
colon :: Doc; -- ^ A ':' character
space :: Doc; -- ^ A space character
equals :: Doc; -- ^ A '=' character
lparen :: Doc; -- ^ A '(' character
rparen :: Doc; -- ^ A ')' character
lbrack :: Doc; -- ^ A '[' character
rbrack :: Doc; -- ^ A ']' character
lbrace :: Doc; -- ^ A '{' character
rbrace :: Doc; -- ^ A '}' character
-- | A document of height and width 1, containing a literal character.
char :: Char -> Doc
-- | A document of height 1 containing a literal string.
-- 'text' satisfies the following laws:
--
-- * @'text' s '<>' 'text' t = 'text' (s'++'t)@
--
-- * @'text' \"\" '<>' x = x@, if @x@ non-empty
--
-- The side condition on the last law is necessary because @'text' \"\"@
-- has height 1, while 'empty' has no height.
text :: String -> Doc
-- | An obsolete function, now identical to 'text'.
ptext :: String -> Doc
int :: Int -> Doc; -- ^ @int n = text (show n)@
integer :: Integer -> Doc; -- ^ @integer n = text (show n)@
float :: Float -> Doc; -- ^ @float n = text (show n)@
double :: Double -> Doc; -- ^ @double n = text (show n)@
rational :: Rational -> Doc; -- ^ @rational n = text (show n)@
parens :: Doc -> Doc; -- ^ Wrap document in @(...)@
brackets :: Doc -> Doc; -- ^ Wrap document in @[...]@
braces :: Doc -> Doc; -- ^ Wrap document in @{...}@
quotes :: Doc -> Doc; -- ^ Wrap document in @\'...\'@
doubleQuotes :: Doc -> Doc; -- ^ Wrap document in @\"...\"@
-- Combining @Doc@ values
-- | Beside.
-- '<>' is associative, with identity 'empty'.
(<>) :: Doc -> Doc -> Doc
-- | Beside, separated by space, unless one of the arguments is 'empty'.
-- '<+>' is associative, with identity 'empty'.
(<+>) :: Doc -> Doc -> Doc
-- | Above, except that if the last line of the first argument stops
-- at least one position before the first line of the second begins,
-- these two lines are overlapped. For example:
--
-- > text "hi" $$ nest 5 (text "there")
--
-- lays out as
--
-- > hi there
--
-- rather than
--
-- > hi
-- > there
--
-- '$$' is associative, with identity 'empty', and also satisfies
--
-- * @(x '$$' y) '<>' z = x '$$' (y '<>' z)@, if @y@ non-empty.
--
($$) :: Doc -> Doc -> Doc
-- | Above, with no overlapping.
-- '$+$' is associative, with identity 'empty'.
($+$) :: Doc -> Doc -> Doc
hcat :: [Doc] -> Doc; -- ^List version of '<>'.
hsep :: [Doc] -> Doc; -- ^List version of '<+>'.
vcat :: [Doc] -> Doc; -- ^List version of '$$'.
cat :: [Doc] -> Doc; -- ^ Either 'hcat' or 'vcat'.
sep :: [Doc] -> Doc; -- ^ Either 'hsep' or 'vcat'.
fcat :: [Doc] -> Doc; -- ^ \"Paragraph fill\" version of 'cat'.
fsep :: [Doc] -> Doc; -- ^ \"Paragraph fill\" version of 'sep'.
-- | Nest (or indent) a document by a given number of positions
-- (which may also be negative). 'nest' satisfies the laws:
--
-- * @'nest' 0 x = x@
--
-- * @'nest' k ('nest' k' x) = 'nest' (k+k') x@
--
-- * @'nest' k (x '<>' y) = 'nest' k z '<>' 'nest' k y@
--
-- * @'nest' k (x '$$' y) = 'nest' k x '$$' 'nest' k y@
--
-- * @'nest' k 'empty' = 'empty'@
--
-- * @x '<>' 'nest' k y = x '<>' y@, if @x@ non-empty
--
-- The side condition on the last law is needed because
-- 'empty' is a left identity for '<>'.
nest :: Int -> Doc -> Doc
-- GHC-specific ones.
-- | @hang d1 n d2 = sep [d1, nest n d2]@
hang :: Doc -> Int -> Doc -> Doc
-- | @punctuate p [d1, ... dn] = [d1 \<> p, d2 \<> p, ... dn-1 \<> p, dn]@
punctuate :: Doc -> [Doc] -> [Doc]
-- Displaying @Doc@ values.
instance Show Doc where
showsPrec prec doc cont = showDoc doc cont
-- | Renders the document as a string using the default 'style'.
render :: Doc -> String
-- | The general rendering interface.
fullRender :: Mode -- ^Rendering mode
-> Int -- ^Line length
-> Float -- ^Ribbons per line
-> (TextDetails -> a -> a) -- ^What to do with text
-> a -- ^What to do at the end
-> Doc -- ^The document
-> a -- ^Result
-- | Render the document as a string using a specified style.
renderStyle :: Style -> Doc -> String
-- | A rendering style.
data Style
= Style { mode :: Mode -- ^ The rendering mode
, lineLength :: Int -- ^ Length of line, in chars
, ribbonsPerLine :: Float -- ^ Ratio of ribbon length to line length
}
-- | The default style (@mode=PageMode, lineLength=100, ribbonsPerLine=1.5@).
style :: Style
style = Style { lineLength = 100, ribbonsPerLine = 1.5, mode = PageMode }
-- | Rendering mode.
data Mode = PageMode -- ^Normal
| ZigZagMode -- ^With zig-zag cuts
| LeftMode -- ^No indentation, infinitely long lines
| OneLineMode -- ^All on one line
-- ---------------------------------------------------------------------------
-- The Doc calculus
-- The Doc combinators satisfy the following laws:
{-
Laws for $$
~~~~~~~~~~~
<a1> (x $$ y) $$ z = x $$ (y $$ z)
<a2> empty $$ x = x
<a3> x $$ empty = x
...ditto $+$...
Laws for <>
~~~~~~~~~~~
<b1> (x <> y) <> z = x <> (y <> z)
<b2> empty <> x = empty
<b3> x <> empty = x
...ditto <+>...
Laws for text
~~~~~~~~~~~~~
<t1> text s <> text t = text (s++t)
<t2> text "" <> x = x, if x non-empty
Laws for nest
~~~~~~~~~~~~~
<n1> nest 0 x = x
<n2> nest k (nest k' x) = nest (k+k') x
<n3> nest k (x <> y) = nest k z <> nest k y
<n4> nest k (x $$ y) = nest k x $$ nest k y
<n5> nest k empty = empty
<n6> x <> nest k y = x <> y, if x non-empty
** Note the side condition on <n6>! It is this that
** makes it OK for empty to be a left unit for <>.
Miscellaneous
~~~~~~~~~~~~~
<m1> (text s <> x) $$ y = text s <> ((text "" <> x)) $$
nest (-length s) y)
<m2> (x $$ y) <> z = x $$ (y <> z)
if y non-empty
Laws for list versions
~~~~~~~~~~~~~~~~~~~~~~
<l1> sep (ps++[empty]++qs) = sep (ps ++ qs)
...ditto hsep, hcat, vcat, fill...
<l2> nest k (sep ps) = sep (map (nest k) ps)
...ditto hsep, hcat, vcat, fill...
Laws for oneLiner
~~~~~~~~~~~~~~~~~
<o1> oneLiner (nest k p) = nest k (oneLiner p)
<o2> oneLiner (x <> y) = oneLiner x <> oneLiner y
You might think that the following verion of <m1> would
be neater:
<3 NO> (text s <> x) $$ y = text s <> ((empty <> x)) $$
nest (-length s) y)
But it doesn't work, for if x=empty, we would have
text s $$ y = text s <> (empty $$ nest (-length s) y)
= text s <> nest (-length s) y
-}
-- ---------------------------------------------------------------------------
-- Simple derived definitions
semi = char ';'
colon = char ':'
comma = char ','
space = char ' '
equals = char '='
lparen = char '('
rparen = char ')'
lbrack = char '['
rbrack = char ']'
lbrace = char '{'
rbrace = char '}'
int n = text (show n)
integer n = text (show n)
float n = text (show n)
double n = text (show n)
rational n = text (show n)
-- SIGBJORN wrote instead:
-- rational n = text (show (fromRationalX n))
quotes p = char '\'' <> p <> char '\''
doubleQuotes p = char '"' <> p <> char '"'
parens p = char '(' <> p <> char ')'
brackets p = char '[' <> p <> char ']'
braces p = char '{' <> p <> char '}'
hcat = foldr (<>) empty
hsep = foldr (<+>) empty
vcat = foldr ($$) empty
hang d1 n d2 = sep [d1, nest n d2]
punctuate p [] = []
punctuate p (d:ds) = go d ds
where
go d [] = [d]
go d (e:es) = (d <> p) : go e es
-- ---------------------------------------------------------------------------
-- The Doc data type
-- A Doc represents a *set* of layouts. A Doc with
-- no occurrences of Union or NoDoc represents just one layout.
-- | The abstract type of documents.
-- The 'Show' instance is equivalent to using 'render'.
data Doc
= Empty -- empty
| NilAbove Doc -- text "" $$ x
| TextBeside TextDetails !Int Doc -- text s <> x
| Nest !Int Doc -- nest k x
| Union Doc Doc -- ul `union` ur
| NoDoc -- The empty set of documents
| Beside Doc Bool Doc -- True <=> space between
| Above Doc Bool Doc -- True <=> never overlap
type RDoc = Doc -- RDoc is a "reduced Doc", guaranteed not to have a top-level Above or Beside
reduceDoc :: Doc -> RDoc
reduceDoc (Beside p g q) = beside p g (reduceDoc q)
reduceDoc (Above p g q) = above p g (reduceDoc q)
reduceDoc p = p
data TextDetails = Chr Char
| Str String
| PStr String
space_text = Chr ' '
nl_text = Chr '\n'
{-
Here are the invariants:
* The argument of NilAbove is never Empty. Therefore
a NilAbove occupies at least two lines.
* The arugment of @TextBeside@ is never @Nest@.
* The layouts of the two arguments of @Union@ both flatten to the same
string.
* The arguments of @Union@ are either @TextBeside@, or @NilAbove@.
* The right argument of a union cannot be equivalent to the empty set
(@NoDoc@). If the left argument of a union is equivalent to the
empty set (@NoDoc@), then the @NoDoc@ appears in the first line.
* An empty document is always represented by @Empty@. It can't be
hidden inside a @Nest@, or a @Union@ of two @Empty@s.
* The first line of every layout in the left argument of @Union@ is
longer than the first line of any layout in the right argument.
(1) ensures that the left argument has a first line. In view of
(3), this invariant means that the right argument must have at
least two lines.
-}
-- Arg of a NilAbove is always an RDoc
nilAbove_ p = NilAbove p
-- Arg of a TextBeside is always an RDoc
textBeside_ s sl p = TextBeside s sl p
-- Arg of Nest is always an RDoc
nest_ k p = Nest k p
-- Args of union are always RDocs
union_ p q = Union p q
-- Notice the difference between
-- * NoDoc (no documents)
-- * Empty (one empty document; no height and no width)
-- * text "" (a document containing the empty string;
-- one line high, but has no width)
-- ---------------------------------------------------------------------------
-- @empty@, @text@, @nest@, @union@
empty = Empty
isEmpty Empty = True
isEmpty _ = False
char c = textBeside_ (Chr c) 1 Empty
text s = case length s of {sl -> textBeside_ (Str s) sl Empty}
ptext s = case length s of {sl -> textBeside_ (PStr s) sl Empty}
nest k p = mkNest k (reduceDoc p) -- Externally callable version
-- mkNest checks for Nest's invariant that it doesn't have an Empty inside it
mkNest k _ | k `seq` False = undefined
mkNest k (Nest k1 p) = mkNest (k + k1) p
mkNest k NoDoc = NoDoc
mkNest k Empty = Empty
mkNest 0 p = p -- Worth a try!
mkNest k p = nest_ k p
-- mkUnion checks for an empty document
mkUnion Empty q = Empty
mkUnion p q = p `union_` q
-- ---------------------------------------------------------------------------
-- Vertical composition @$$@
above_ :: Doc -> Bool -> Doc -> Doc
above_ p _ Empty = p
above_ Empty _ q = q
above_ p g q = Above p g q
p $$ q = above_ p False q
p $+$ q = above_ p True q
above :: Doc -> Bool -> RDoc -> RDoc
above (Above p g1 q1) g2 q2 = above p g1 (above q1 g2 q2)
above p@(Beside _ _ _) g q = aboveNest (reduceDoc p) g 0 (reduceDoc q)
above p g q = aboveNest p g 0 (reduceDoc q)
aboveNest :: RDoc -> Bool -> Int -> RDoc -> RDoc
-- Specfication: aboveNest p g k q = p $g$ (nest k q)
aboveNest _ _ k _ | k `seq` False = undefined
aboveNest NoDoc g k q = NoDoc
aboveNest (p1 `Union` p2) g k q = aboveNest p1 g k q `union_`
aboveNest p2 g k q
aboveNest Empty g k q = mkNest k q
aboveNest (Nest k1 p) g k q = nest_ k1 (aboveNest p g (k - k1) q)
-- p can't be Empty, so no need for mkNest
aboveNest (NilAbove p) g k q = nilAbove_ (aboveNest p g k q)
aboveNest (TextBeside s sl p) g k q = k1 `seq` textBeside_ s sl rest
where
k1 = k - sl
rest = case p of
Empty -> nilAboveNest g k1 q
other -> aboveNest p g k1 q
nilAboveNest :: Bool -> Int -> RDoc -> RDoc
-- Specification: text s <> nilaboveNest g k q
-- = text s <> (text "" $g$ nest k q)
nilAboveNest _ k _ | k `seq` False = undefined
nilAboveNest g k Empty = Empty -- Here's why the "text s <>" is in the spec!
nilAboveNest g k (Nest k1 q) = nilAboveNest g (k + k1) q
nilAboveNest g k q | (not g) && (k > 0) -- No newline if no overlap
= textBeside_ (Str (spaces k)) k q
| otherwise -- Put them really above
= nilAbove_ (mkNest k q)
-- ---------------------------------------------------------------------------
-- Horizontal composition @<>@
beside_ :: Doc -> Bool -> Doc -> Doc
beside_ p _ Empty = p
beside_ Empty _ q = q
beside_ p g q = Beside p g q
p <> q = beside_ p False q
p <+> q = beside_ p True q
beside :: Doc -> Bool -> RDoc -> RDoc
-- Specification: beside g p q = p <g> q
beside NoDoc g q = NoDoc
beside (p1 `Union` p2) g q = (beside p1 g q) `union_` (beside p2 g q)
beside Empty g q = q
beside (Nest k p) g q = nest_ k (beside p g q) -- p non-empty
beside p@(Beside p1 g1 q1) g2 q2
{- (A `op1` B) `op2` C == A `op1` (B `op2` C) iff op1 == op2
[ && (op1 == <> || op1 == <+>) ] -}
| g1 == g2 = beside p1 g1 (beside q1 g2 q2)
| otherwise = beside (reduceDoc p) g2 q2
beside p@(Above _ _ _) g q = beside (reduceDoc p) g q
beside (NilAbove p) g q = nilAbove_ (beside p g q)
beside (TextBeside s sl p) g q = textBeside_ s sl rest
where
rest = case p of
Empty -> nilBeside g q
other -> beside p g q
nilBeside :: Bool -> RDoc -> RDoc
-- Specification: text "" <> nilBeside g p
-- = text "" <g> p
nilBeside g Empty = Empty -- Hence the text "" in the spec
nilBeside g (Nest _ p) = nilBeside g p
nilBeside g p | g = textBeside_ space_text 1 p
| otherwise = p
-- ---------------------------------------------------------------------------
-- Separate, @sep@, Hughes version
-- Specification: sep ps = oneLiner (hsep ps)
-- `union`
-- vcat ps
sep = sepX True -- Separate with spaces
cat = sepX False -- Don't
sepX x [] = empty
sepX x (p:ps) = sep1 x (reduceDoc p) 0 ps
-- Specification: sep1 g k ys = sep (x : map (nest k) ys)
-- = oneLiner (x <g> nest k (hsep ys))
-- `union` x $$ nest k (vcat ys)
sep1 :: Bool -> RDoc -> Int -> [Doc] -> RDoc
sep1 g _ k ys | k `seq` False = undefined
sep1 g NoDoc k ys = NoDoc
sep1 g (p `Union` q) k ys = sep1 g p k ys
`union_`
(aboveNest q False k (reduceDoc (vcat ys)))
sep1 g Empty k ys = mkNest k (sepX g ys)
sep1 g (Nest n p) k ys = nest_ n (sep1 g p (k - n) ys)
sep1 g (NilAbove p) k ys = nilAbove_ (aboveNest p False k (reduceDoc (vcat ys)))
sep1 g (TextBeside s sl p) k ys = textBeside_ s sl (sepNB g p (k - sl) ys)
-- Specification: sepNB p k ys = sep1 (text "" <> p) k ys
-- Called when we have already found some text in the first item
-- We have to eat up nests
sepNB g (Nest _ p) k ys = sepNB g p k ys
sepNB g Empty k ys = oneLiner (nilBeside g (reduceDoc rest))
`mkUnion`
nilAboveNest False k (reduceDoc (vcat ys))
where
rest | g = hsep ys
| otherwise = hcat ys
sepNB g p k ys = sep1 g p k ys
-- ---------------------------------------------------------------------------
-- @fill@
fsep = fill True
fcat = fill False
-- Specification:
-- fill [] = empty
-- fill [p] = p
-- fill (p1:p2:ps) = oneLiner p1 <#> nest (length p1)
-- (fill (oneLiner p2 : ps))
-- `union`
-- p1 $$ fill ps
fill g [] = empty
fill g (p:ps) = fill1 g (reduceDoc p) 0 ps
fill1 :: Bool -> RDoc -> Int -> [Doc] -> Doc
fill1 g _ k ys | k `seq` False = undefined
fill1 g NoDoc k ys = NoDoc
fill1 g (p `Union` q) k ys = fill1 g p k ys
`union_`
(aboveNest q False k (fill g ys))
fill1 g Empty k ys = mkNest k (fill g ys)
fill1 g (Nest n p) k ys = nest_ n (fill1 g p (k - n) ys)
fill1 g (NilAbove p) k ys = nilAbove_ (aboveNest p False k (fill g ys))
fill1 g (TextBeside s sl p) k ys = textBeside_ s sl (fillNB g p (k - sl) ys)
fillNB g _ k ys | k `seq` False = undefined
fillNB g (Nest _ p) k ys = fillNB g p k ys
fillNB g Empty k [] = Empty
fillNB g Empty k (y:ys) = nilBeside g (fill1 g (oneLiner (reduceDoc y)) k1 ys)
`mkUnion`
nilAboveNest False k (fill g (y:ys))
where
k1 | g = k - 1
| otherwise = k
fillNB g p k ys = fill1 g p k ys
-- ---------------------------------------------------------------------------
-- Selecting the best layout
best :: Mode
-> Int -- Line length
-> Int -- Ribbon length
-> RDoc
-> RDoc -- No unions in here!
best OneLineMode w r p
= get p
where
get Empty = Empty
get NoDoc = NoDoc
get (NilAbove p) = nilAbove_ (get p)
get (TextBeside s sl p) = textBeside_ s sl (get p)
get (Nest k p) = get p -- Elide nest
get (p `Union` q) = first (get p) (get q)
best mode w r p
= get w p
where
get :: Int -- (Remaining) width of line
-> Doc -> Doc
get w _ | w==0 && False = undefined
get w Empty = Empty
get w NoDoc = NoDoc
get w (NilAbove p) = nilAbove_ (get w p)
get w (TextBeside s sl p) = textBeside_ s sl (get1 w sl p)
get w (Nest k p) = nest_ k (get (w - k) p)
get w (p `Union` q) = nicest w r (get w p) (get w q)
get1 :: Int -- (Remaining) width of line
-> Int -- Amount of first line already eaten up
-> Doc -- This is an argument to TextBeside => eat Nests
-> Doc -- No unions in here!
get1 w _ _ | w==0 && False = undefined
get1 w sl Empty = Empty
get1 w sl NoDoc = NoDoc
get1 w sl (NilAbove p) = nilAbove_ (get (w - sl) p)
get1 w sl (TextBeside t tl p) = textBeside_ t tl (get1 w (sl + tl) p)
get1 w sl (Nest k p) = get1 w sl p
get1 w sl (p `Union` q) = nicest1 w r sl (get1 w sl p)
(get1 w sl q)
nicest w r p q = nicest1 w r 0 p q
nicest1 w r sl p q | fits ((w `minn` r) - sl) p = p
| otherwise = q
fits :: Int -- Space available
-> Doc
-> Bool -- True if *first line* of Doc fits in space available
fits n p | n < 0 = False
fits n NoDoc = False
fits n Empty = True
fits n (NilAbove _) = True
fits n (TextBeside _ sl p) = fits (n - sl) p
minn x y | x < y = x
| otherwise = y
-- @first@ and @nonEmptySet@ are similar to @nicest@ and @fits@, only simpler.
-- @first@ returns its first argument if it is non-empty, otherwise its second.
first p q | nonEmptySet p = p
| otherwise = q
nonEmptySet NoDoc = False
nonEmptySet (p `Union` q) = True
nonEmptySet Empty = True
nonEmptySet (NilAbove p) = True -- NoDoc always in first line
nonEmptySet (TextBeside _ _ p) = nonEmptySet p
nonEmptySet (Nest _ p) = nonEmptySet p
-- @oneLiner@ returns the one-line members of the given set of @Doc@s.
oneLiner :: Doc -> Doc
oneLiner NoDoc = NoDoc
oneLiner Empty = Empty
oneLiner (NilAbove p) = NoDoc
oneLiner (TextBeside s sl p) = textBeside_ s sl (oneLiner p)
oneLiner (Nest k p) = nest_ k (oneLiner p)
oneLiner (p `Union` q) = oneLiner p
-- ---------------------------------------------------------------------------
-- Displaying the best layout
renderStyle style doc
= fullRender (mode style)
(lineLength style)
(ribbonsPerLine style)
string_txt
""
doc
render doc = showDoc doc ""
showDoc doc rest = fullRender PageMode 100 1.5 string_txt rest doc
string_txt (Chr c) s = c:s
string_txt (Str s1) s2 = s1 ++ s2
string_txt (PStr s1) s2 = s1 ++ s2
fullRender OneLineMode _ _ txt end doc = easy_display space_text txt end (reduceDoc doc)
fullRender LeftMode _ _ txt end doc = easy_display nl_text txt end (reduceDoc doc)
fullRender mode line_length ribbons_per_line txt end doc
= display mode line_length ribbon_length txt end best_doc
where
best_doc = best mode hacked_line_length ribbon_length (reduceDoc doc)
hacked_line_length, ribbon_length :: Int
ribbon_length = round (fromIntegral line_length / ribbons_per_line)
hacked_line_length = case mode of { ZigZagMode -> maxBound; other -> line_length }
display mode page_width ribbon_width txt end doc
= case page_width - ribbon_width of { gap_width ->
case gap_width `quot` 2 of { shift ->
let
lay k _ | k `seq` False = undefined
lay k (Nest k1 p) = lay (k + k1) p
lay k Empty = end
lay k (NilAbove p) = nl_text `txt` lay k p
lay k (TextBeside s sl p)
= case mode of
ZigZagMode | k >= gap_width
-> nl_text `txt` (
Str (multi_ch shift '/') `txt` (
nl_text `txt` (
lay1 (k - shift) s sl p)))
| k < 0
-> nl_text `txt` (
Str (multi_ch shift '\\') `txt` (
nl_text `txt` (
lay1 (k + shift) s sl p )))
other -> lay1 k s sl p
lay1 k _ sl _ | k+sl `seq` False = undefined
lay1 k s sl p = Str (indent k) `txt` (s `txt` lay2 (k + sl) p)
lay2 k _ | k `seq` False = undefined
lay2 k (NilAbove p) = nl_text `txt` lay k p
lay2 k (TextBeside s sl p) = s `txt` (lay2 (k + sl) p)
lay2 k (Nest _ p) = lay2 k p
lay2 k Empty = end
in
lay 0 doc
}}
cant_fail = error "easy_display: NoDoc"
easy_display nl_text txt end doc
= lay doc cant_fail
where
lay NoDoc no_doc = no_doc
lay (Union p q) no_doc = {- lay p -} (lay q cant_fail) -- Second arg can't be NoDoc
lay (Nest k p) no_doc = lay p no_doc
lay Empty no_doc = end
lay (NilAbove p) no_doc = nl_text `txt` lay p cant_fail -- NoDoc always on first line
lay (TextBeside s sl p) no_doc = s `txt` lay p no_doc
-- OLD version: we shouldn't rely on tabs being 8 columns apart in the output.
-- indent n | n >= 8 = '\t' : indent (n - 8)
-- | otherwise = spaces n
indent n = spaces n
multi_ch 0 ch = ""
multi_ch n ch = ch : multi_ch (n - 1) ch
-- (spaces n) generates a list of n spaces
--
-- It should never be called with 'n' < 0, but that can happen for reasons I don't understand
-- Here's a test case:
-- ncat x y = nest 4 $ cat [ x, y ]
-- d1 = foldl1 ncat $ take 50 $ repeat $ char 'a'
-- d2 = parens $ sep [ d1, text "+" , d1 ]
-- main = print d2
-- I don't feel motivated enough to find the Real Bug, so meanwhile we just test for n<=0
spaces n | n <= 0 = ""
| otherwise = ' ' : spaces (n - 1)
{- Comments from Johannes Waldmann about what the problem might be:
In the example above, d2 and d1 are deeply nested, but `text "+"' is not,
so the layout function tries to "out-dent" it.
when I look at the Doc values that are generated, there are lots of
Nest constructors with negative arguments. see this sample output of
d1 (obtained with hugs, :s -u)
tBeside (TextDetails_Chr 'a') 1 Doc_Empty) (Doc_NilAbove (Doc_Nest
(-241) (Doc_TextBeside (TextDetails_Chr 'a') 1 Doc_Empty)))))
(Doc_NilAbove (Doc_Nest (-236) (Doc_TextBeside (TextDetails_Chr 'a') 1
(Doc_NilAbove (Doc_Nest (-5) (Doc_TextBeside (TextDetails_Chr 'a') 1
Doc_Empty)))))))) (Doc_NilAbove (Doc_Nest (-231) (Doc_TextBeside
(TextDetails_Chr 'a') 1 (Doc_NilAbove (Doc_Nest (-5) (Doc_TextBeside
(TextDetails_Chr 'a') 1 (Doc_NilAbove (Doc_Nest (-5) (Doc_TextBeside
(TextDetails_Chr 'a') 1 Doc_Empty))))))))))) (Doc_NilAbove (Doc_Nest
-}
httpd.httpdconf
Theme: light, Line numbers: false
ServerType standalone
ServerRoot "/var/www"
Timeout 300
#LockFile logs/accept.lock
MaxClients 150
Listen 8080
Listen 12.34.56.78:80
RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} ^Mozilla
RewriteRule ^/$ /homepage.max.html [L]
RewriteLog "/usr/local/var/apache/logs/rewrite.log"
RewriteMap examplemap txt:/path/to/file/map.txt
RewriteRule ^/ex/(.*) ${examplemap:$1}
RewriteRule ^$ RewriteRule
#1.3 legacy style
<IfDefine SSL>
Listen 80
Listen 443
</IfDefine>
<IfModule SSL>
Listen 80
Listen 443
</IfModule>
<Directory />
Options FollowSymLinks
AllowOverride None
Order Deny,Allow
Deny from all
</Directory>
<Directory "/var/www/htdocs">
AllowOverride None
Order allow,deny
Allow from all
</Directory>
<Directory /home/*/public_html>
AllowOverride FileInfo AuthConfig Limit Options Indexes
Options MultiViews SymLinksIfOwnerMatch IncludesNoExec
<Limit GET POST OPTIONS PROPFIND>
Order allow,deny
Allow from all
</Limit>
<Limit PUT DELETE PATCH PROPPATCH MKCOL COPY MOVE LOCK UNLOCK>
Order deny,allow
Deny from all
</Limit>
</Directory>
<Files .htaccess>
Order allow,deny
Deny from all
</Files>
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip
AddIconByType (TXT,/icons/text.gif) text/*
AddIconByType (IMG,/icons/image2.gif) image/*
AddIconByType (SND,/icons/sound2.gif) audio/*
AddIconByType (VID,/icons/movie.gif) video/*
AddIcon /icons/binary.gif .bin .exe
NameVirtualHost *:80
<VirtualHost *:80>
ServerName www.domain.tld
ServerAlias domain.tld *.domain.tld
DocumentRoot /www/domain
</VirtualHost>
invalid-lang.txt
Theme: light, Line numbers: false
foo
java.java
Theme: gitbook, Line numbers: true
package com.sunlightjs.awesome;
import java.text.*;
import java.io.BufferedStreamReader;
import java.lang.annotation.*;
import java.lang.StackTraceElement;
public class MyClass extends ExtendedClass implements Interfacable1, Interfacable2, Interfacable3 {
private int foo;
public MyClass(int parameter1) {
super();
this.foo = (CastingTest1)foo;
this.foo = ((CastingTest2)this).doStuff();
if (notACast) methodCall();
if (this.foo instanceof java.lang.CharSequence) {
throw new Exception();
}
}
/**
* How about an inner class?
*/
private class InnerEvenIterator {
//start stepping through the array from the beginning
private int next = 0;
public boolean hasNext() {
//check if a current element is the last in the array
return (next <= SIZE - 1);
}
public int getNext() {
//record a value of an even index of the array
int retValue = arrayOfInts[next];
//get the next even element
next += 2;
return retValue;
}
}
private void anonymousInnerClassTest() throws CheckedException1, CheckedException2, CheckedException3 {
new Thread(new Runnable() {
public void run() {
try {
while (true) {
sleep(1000); System.out.print(".");
}
}
catch(InterruptedException ex) {}
}
}).start();
//http://www.roseindia.net/javatutorials/anonymous_innerclassestutorial.shtml
Vector myVector = new Vector(3) {{
add("Heinz"); add("John"); add("Anton");
}};
}
/*
multi line
comment
*/
protected abstract void abstractMethod(Kissable lips, char c, ArrayParameter[] arrayParameter);
/**
* Stolen mostly from http://download.oracle.com/javase/tutorial/java/generics/bounded.html
* because I haven't written Java since I was an idiot in college
*/
@Documented @AnnotationWithArguments(name = "this \"is\" a string\\")
@Override public static <T extends GenericExtended & GenericImplemented<? super T>> T genericMethod(GenericParam<? extends T> genericParam) {
//wait, so Java seriously uses the ampersand for interfaces in generics?
MyCustomMap1<char, AnotherGeneric> map = new MyCustomMap2<FirstGeneric, SecondGeneric>();
fully1.qualified1.ClassName1 fqc = new fully2.qualified2.ClassName2();
int length = 2;
ArrayTest1[] arrayOStuff = length > 0 ? new ArrayTest2[length] : new ArrayTest3[12];
return true ? false : null;
}
}
//enum test: http://download.oracle.com/javase/1.5.0/docs/guide/language/enums.html
public enum Planet {
MERCURY (3.303e+23, 2.4397e6),
VENUS (4.869e+24, 6.0518e6),
EARTH (5.976e+24, 6.37814e6),
MARS (6.421e+23, 3.3972e6),
JUPITER (1.9e+27, 7.1492e7),
SATURN (5.688e+26, 6.0268e7),
URANUS (8.686e+25, 2.5559e7),
NEPTUNE (1.024e+26, 2.4746e7),
PLUTO (1.27e+22, 1.137e6);
private final double mass; // in kilograms
private final double radius; // in meters
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
public double mass() { return mass; }
public double radius() { return radius; }
// universal gravitational constant (m3 kg-1 s-2)
public static final double G = 6.67300E-11;
public double surfaceGravity() {
return G * mass / (radius * radius);
}
public double surfaceWeight(double otherMass) {
return otherMass * surfaceGravity();
}
}
javascript.js
Theme: light, Line numbers: false
(function($, window), undefined){
if ($ === undefined) {
throw 'missing jQuery\'s dependency';
}
function $$(id) {
var element = document.getElementById(id);
for (var property in element) {
document.write(property + ": " + element[property].toString());
}
}
function foo(bar) {
window.alert("oh noes!!");
var abstract = encodeURIComponent(parseFloat("abstract is a reserved word"));
var elements = document.getElementsByTagName("foo");
for (var i = 0; i < elements.length; i++) {
if (element[i].name !== 'foo\'s') {
return false;
} else {
return true;
}
}
var req;
try {
req = new XMLHttpRequest();
} catch (e) {
try {
req = new XDomainRequest();
} catch (e) {
try {
req = new ActiveXObject("MSXML2.HTTP");
} catch (e) {
if (e instanceof Object) {
throw e;
}
}
}
} finally {
if (req !== null) {
req.open("http://google.com/");
req.send();
}
}
if (req === null) {
throw new Error("FAIL");
}
return bar == 0.5;
}
var stringify = function(string) {
return JSON !== undefined ? JSON.stringify.call(null, string) : new String(string);
};
switch (foo("he\\\"ad").length) {
case 1:
//fall through
case 0x2:
break;
case 1e3:
default:
/*
* default implementation
* of something
*/
if (isNaN(10) || this === NaN) {
doSomething(Infinity, new Boolean(true));
}
doSomething(/\w[^A-Z0-9]$/g, 5 / 3);
break;
}
//regex literal parsing
/foo/.test("foo"); //should be a regex
/\//.test("/"); //should be a regex
/\\/.test("foo"); //should be a regex
var foo = /foo/.test("foo"); //should be a regex
var foo = /f\/oo/.test("foo"); //should be a regex
if (/foo/.test("foo")) { } //should be a regex
var x = 4 / 5; /foo/.test("foo") { } //should be a regex
4 = /foo/ //should be a regex
if (!/foo/.test("foo")) {} //should be a regex
if (!/foo/.test("foo") || /foo/.test("foo") && /foo/.test("foo")) {} //all should be a regex
4 + /regexafteroperator/ //should be a regex
/regexatstartofline/ //should be a regex
/[/]/.test('/'); //should be a regex
/[\/]/.test('/'); //should be a regex
/[\]]/.test('/'); //should be a regex
/[\[]/.test('/'); //should be a regex
/\[/.test('/'); //should be a regex
/\]/.test('/'); //should be a regex
/foo/gim.test("foo") //should be a regex with modifiers
/foo/asdfasdf //should be a regex with non-existent modifiers
var foo = (4 + 5) / 2; //should not be a regex
var arr = [/regexafterbracket/, /regexaftercomma/, 4/5];
function(regex) { /regexafterbrace/.text(regex); }
func(/regexafterparen/); /regexaftersemicolon/;
//.test("foo"); //should not be a regex
4 /identafterdivision1/ //should not be a regex
var foo = 5/identafterdivision2; //should not be a regex
var foo = 5 /identafterdivision3; //should not be a regex
if /regexafterkeyword/ //should not be a regex
var jsonLiteral = {
regex: /regexaftercolon/
};
}(jQuery, window));
lisp.lisp
Theme: dark, Line numbers: true
;;; Count and collect names and ages.
(loop for name in '(fred sue alice joe june)
as age in '(22 26 19 20 10)
append (list name age) into name-and-age-list
count name into name-count
sum age into total-age
finally
(return (values (round total-age name-count)
name-and-age-list)))
; special form and constant
(setq x (+ 3 2 1) y (cons x nil))
; type
(series 'b 'c) => #Z(b c b c b c ...)
(scan (list 'a 'b 'c)) => #Z(a b c)
; declaration specifier
(defun simple-collect-sum (numbers)
(declare (optimizable-series-function 1))
(collect-fn 'number #'(lambda () 0) #'+ numbers))
; global variables
(let ((*print-right-margin* 25) (*print-lines* 3))
(pprint '(progn (setq a 1 b 2 c 3 d 4))))
#2A((0 1 5) (foo #4r4056 (hot dog)))
; user-defined variable
(setf *temp* (function *))
; keyword arguments
(write foo
:pretty t
:right-margin 60
:case :downcase)
;;; cl-typesetting copyright 2003-2004 Marc Battyani see license.txt for the details
;;; You can reach me at marc.battyani@fractalconcept.com or marc@battyani.net
;;; The homepage of cl-typesetting is here: http://www.fractalconcept.com/asp/html/cl-typesetting.html
(in-package #:typeset)
;;; This is a module to typeset Common Lisp code with some syntax coloring
;;; The syntax coloring is too simple to be 100% accurate:
;;; Improvements welcomed!
(defparameter *pp-font-size* 9)
(defparameter *pp-default-decoration* '("courier" (0.0 0.0 0.0)))
(defparameter *pp-keyword-decoration* '("courier" (0.8 0.0 0.0)))
(defparameter *pp-common-lisp-decoration* '("courier" (0.0 0.0 0.4)))
(defparameter *pp-string-decoration* '("courier" (0.0 0.5 0.0)))
(defparameter *pp-comment-decoration* '("courier" (0.2 0.2 0.6)))
(defparameter *pp-symbol-decoration-table* (make-hash-table))
(defparameter *exceptions* '())
(defun add-symbol-decoration (symbol decoration)
(setf (gethash symbol *pp-symbol-decoration-table*) decoration))
;(loop for (symbol . decoration) in '((defvar "courier-bold" (0.0 0.0 0.5))
; (defun "courier-bold" (0.0 0.2 0.5))
; (defmethod "courier-bold" (0.0 0.2 0.5)))
; do (add-symbol-decoration symbol decoration))
(loop for symbol being the external-symbols of 'common-lisp
when (eql (search "DEF" (symbol-name symbol)) 0)
do (add-symbol-decoration symbol '("courier-bold" (0.0 0.2 0.5))))
(defun split-comment (line)
(let ((comment-pos (position #\; line)))
(if comment-pos
(values (subseq line 0 comment-pos)(subseq line comment-pos))
line)))
(defun clean-line (line)
(setf line (copy-seq line))
(map-into line #'(lambda (char)
(if (find char "()'`# ")
#\Space
char))
line))
(defun process-lisp-line (line)
(multiple-value-bind (code comment)(split-comment line)
(let* ((cleaned-line (clean-line code))
(cl-package (find-package 'common-lisp))
(decorations '())
(start 0)
(trimmed 0)
(length (length cleaned-line)))
(iter
(setf trimmed (position #\Space cleaned-line :start start :test #'char/=))
(while (and trimmed (< trimmed length)))
(for (values obj end) = (ignore-errors
(read-from-string
cleaned-line nil nil
:start trimmed :preserve-whitespace t)))
(unless (numberp end)
(setf end (position #\Space cleaned-line :start trimmed :test #'char=)))
(while (and (numberp end) (< end length)))
(cond ((keywordp obj)
(push (list* trimmed end *pp-keyword-decoration*) decorations))
((stringp obj)
(push (list* trimmed end *pp-string-decoration*) decorations))
((gethash obj *pp-symbol-decoration-table*)
(push (list* trimmed end (gethash obj *pp-symbol-decoration-table*)) decorations))
((and (symbolp obj)
(or (eq (symbol-package obj) cl-package)
(member (symbol-name obj)
'("FOR" "THEN" "WHILE" "COLLECT" "IN" "WITH" "FINALLY")
:test #'string=))
(not (member (symbol-name obj) *exceptions* :test #'string=)))
(push (list* trimmed end *pp-common-lisp-decoration*) decorations)))
(setf start end))
(setf start 0)
(loop for (start-tok end-tok font-name color) in (nreverse decorations) do
(when (/= start start-tok)
(with-text-compilation
(verbatim (subseq line start start-tok))))
(with-text-compilation
(with-style (:font font-name :font-size *pp-font-size* :color color)
(verbatim (subseq line start-tok end-tok))))
(setf start end-tok))
(with-text-compilation
(when (< start length)
(verbatim (subseq code start)))
(with-style (:font (first *pp-comment-decoration*)
:font-size *pp-font-size*
:color (second *pp-comment-decoration*))
(verbatim comment)
(when (zerop length) (verbatim " ")) :eol)))))
(defmethod process-lisp-code ((s stream))
(with-text-compilation
(paragraph (:h-align :left :top-margin 10
:left-margin 5 :right-margin 5
:font "courier" :font-size *pp-font-size*)
(loop for line = (read-line s nil)
while line
do (with-text-compilation
(process-lisp-line line))))))
(defmethod process-lisp-code ((lisp-file pathname))
(with-open-file (s lisp-file :direction :input)
(process-lisp-code s)))
(defmethod process-lisp-code ((lisp-string string))
(with-input-from-string (s lisp-string)
(process-lisp-code s)))
(defmethod process-lisp-code ((sexpr t))
(process-lisp-code
(with-output-to-string (s)
(pprint sexpr s))))
(defun pprint-lisp-file (lisp-code pdf-file &optional title *exceptions*)
(with-document ()
(let* ((margins '(30 50 30 50))
(print-stamp (multiple-value-bind (second minute hour date month year)
(get-decoded-time)
(declare (ignore second))
(format nil "Printed on ~4D-~2,'0D-~2,'0D ~2,'0D:~2,'0D"
year month date hour minute)))
(header (compile-text ()
(paragraph (:h-align :center
:font "Helvetica-BoldOblique" :font-size 12)
(put-string (cond
(title title)
((pathnamep lisp-code)(namestring lisp-code))
(t "Lisp Source Code"))))
(vspace 1)
(hrule :dy 0.5)))
(footer (lambda (pdf:*page*)
(compile-text (:font "Helvetica" :font-size 10)
(hrule :dy 1/2)
(hbox (:align :center :adjustable-p t)
(verbatim print-stamp)
:hfill
(verbatim
(format nil "Page ~d" pdf:*page-number*))))))
(content (compile-text () (process-lisp-code lisp-code))))
(draw-pages content :margins margins :header header :footer footer)
(when pdf:*page* (finalize-page pdf:*page*))
(pdf:write-document pdf-file))))
lua.lua
Theme: gitbook, Line numbers: true
--strings
a = 'alo\n123"'
a = "alo\n123\""
a = '\97lo\10\04923"'
a = [[alo
123"]]
a = [==[
alo
123"]==]
--[[
multi
line
comment]]
local BUFSIZE = 2^13 -- 8K
local f = io.input(arg[1]) -- open input file
local cc, lc, wc = 0, 0, 0 -- char, line, and word counts
while true do
local lines, rest = f:read(BUFSIZE, "*line")
if not lines then break end
if rest then lines = lines .. rest .. '\n' end
cc = cc + string.len(lines)
-- count words in the chunk
local _,t = string.gsub(lines, "%S+", "")
wc = wc + t
-- count newlines in the chunk
_,t = string.gsub(lines, "\n", "\n")
lc = lc + t
end
print(lc, wc, cc)
-- print the first non-empty line
repeat
line = os.read()
until line ~= ""
print(line)
function sortbygrade(names, grades)
table.sort(names, function(n1, n2)
return grades[n1] > grades[n2] -- compare the grades
end)
end
-- Markov Chain Program in Lua
function allwords()
local line = io.read() -- current line
local pos = 1 -- current position in the line
return function () -- iterator function
while line do -- repeat while there are lines
local s, e = string.find(line, "%w+", pos)
if s then -- found a word?
pos = e + 1 -- update next position
return string.sub(line, s, e) -- return the word
else
line = io.read() -- word not found; try next line
pos = 1 -- restart from first position
end
end
return nil -- no more lines: end of traversal
end
end
function prefix(w1, w2)
return w1 .. ' ' .. w2
end
local statetab
function insert (index, value)
if not statetab[index] then
statetab[index] = {n=0}
end
table.insert(statetab[index], value)
end
local N = 2
local MAXGEN = 10000
local NOWORD = "\n"
-- build table
statetab = {}
local w1, w2 = NOWORD, NOWORD
for w in allwords() do
insert(prefix(w1, w2), w)
w1 = w2; w2 = w;
end
insert(prefix(w1, w2), NOWORD)
-- generate text
w1 = NOWORD; w2 = NOWORD -- reinitialize
for i=1,MAXGEN do
local list = statetab[prefix(w1, w2)]
-- choose a random item from list
local r = math.random(table.getn(list))
local nextword = list[r]
if nextword == NOWORD then return end
io.write(nextword, " ")
w1 = w2; w2 = nextword
end
mysql.sql
Theme: light, Line numbers: false
--comment 1
select * from db.my_table where myTable.id > 10;
/* multi
line comment */
select "escaped\\\"";
select 'escaped\\\'';
#comment 2
SELECT
f.foo `foo`,
f.bar,
f.name AS `foo.name`,
b.baz
FROM foo f
INNER JOIN bar b
ON b.id = f.bar_id
LEFT OUTER JOIN baz
ON baz.id = f.foo
AND baz.id IS NOT NULL
GROUP BY f.name
HAVING COUNT(f.name) < 10
WHERE LENGTH(f.foo) < 5
AND LEFT(f.foo) = 'f'
START TRANSACTION;
SELECT @A:=SUM(salary) FROM table1 WHERE type=1;
UPDATE table2 SET summary=@A WHERE type=1;
COMMIT;
DELIMITER $$
BEGIN
DECLARE foo = 'bar';
END $$
DELIMITER ;
nginx.nginxconf
Theme: dark, Line numbers: true
#nginx test
http {
error_page 502 503 504 /50x.html;
gzip on;
gzip_static on;
gzip_disable "MSIE [1-6]\.";
expires 24h;
index index.html;
<!--# echo var="name" default="no" -->
geo $geo { # the variable created is $geo
default 0;
127.0.0.1/32 2;
192.168.1.0/24 1;
10.1.0.0/16 1;
}
map $uri $new {
default http://www.domain.com/home/;
/aa http://aa.domain.com/;
/bb http://bb.domain.com/;
/john http://my.domain.com/users/john/;
}
split-clients '${remote-addr}AAA' $variant {
0.5% .one;
2.0% .two;
- "";
}
upstream backend {
server backend1.example.com weight=5;
server backend2.example.com:8080;
server unix:/tmp/backend3;
}
location / {
error_page 404 = @fallback;
proxy_set_header X-Real-IP $remote_addr;
rewrite ^ /prefix/$secure_link break;
}
location @fallback {
proxy_pass http://backend;
proxy_cache_path /data/nginx/cache/three levels=1:1:2 keys_zone=three:1000m;
}
server {
listen [fe80::1];
listen 127.0.0.1 default accept_filter=dataready backlog=1024;
server_name example.com *.example.com www.example.*;
root /var/www;
}
server {
listen *:8000;
listen localhost:8000;
listen 443;
ssl on;
ssl_certificate /usr/local/nginx/conf/cert.pem;
ssl_certificate_key /usr/local/nginx/conf/cert.key;
server_name server_name www.example.com ~^(www\.)?(?P<domain>.+)$;
root /sites/$domain;
if ($slow) {
set $limit_rate 4k;
}
location ^~ /images/ {
# matches any query beginning with /images/ and halts searching,
# so regular expressions will not be checked.
}
location = / {
# matches the query / only.
}
location ~* \.(gif|jpg|jpeg)$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME /home/www/scripts/php$fastcgi_script_name;
}
location /video {
aio on;
directio 512;
output_buffers 1 128k;
types {
text/html html;
image/gif gif;
image/jpeg jpg;
}
default_type text/html;
echo "foo";
echo_after_body "after the body";
}
location ~ ^/download/(.*)$ {
alias /home/website/files/$1;
internal;
limit_except GET {
allow 192.168.1.0/32;
deny all;
}
}
}
}
mail {
imap_capabilities NAMESPACE SORT QUOTA;
listen 127.0.0.1:8000;
server {
server_name example.com www.example.com;
}
}
objective-c1.mm
Theme: gitbook, Line numbers: true
//
// GCPagedScrollView.m
// GCLibrary
//
// Created by Guillaume Campagna on 10-11-10.
// Copyright (c) 2010 LittleKiwi. All rights reserved.
//
#import "GCPagedScrollView.h"
#import <QuartzCore/CATransaction.h>
NSString * const GCPagedScrollViewContentOffsetKey = @"contentOffset";
const CGFloat GCPagedScrollViewPageControlHeight = 36.0;
@interface GCPagedScrollView ()
@property (nonatomic, readonly) NSMutableArray* views;
@property (nonatomic, readonly) UIPageControl* pageControl;
- (void) updateViewPositionAndPageControl;
- (void) changePage:(UIPageControl*) aPageControl;
@end
@implementation GCPagedScrollView
@synthesize views;
@synthesize pageControl;
#pragma mark -
#pragma mark Subclass
- (id)initWithFrame:(CGRect)frame {
if ((self = [super :frame])) {
self.pagingEnabled = YES;
self.showsVerticalScrollIndicator = NO;
self.showsHorizontalScrollIndicator = NO;
self.scrollsToTop = NO;
//Place page control
CGRect frame = CGRectMake(self.contentOffset.x, 0, self.frame.size.width, GCPagedScrollViewPageControlHeight);
UIPageControl* aPageControl = [[UIPageControl ] :frame];
[aPageControl :self :@selector(changePage:) :UIControlEventValueChanged];
aPageControl.defersCurrentPageDisplay = YES;
aPageControl.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin);
[self :aPageControl];
pageControl = aPageControl;
}
return self;
}
- (void) setPagingEnabled:(BOOL) pagingEnabled {
if (pagingEnabled) [super :pagingEnabled];
else {
[NSException :@"Disabling pagingEnabled" :@"Paging enabled should not be disabled in GCPagedScrollView"];
}
}
#pragma mark -
#pragma mark Add/Remove content
- (void) addContentSubview:(UIView *)view {
[self :view :[self.views ]];
}
- (void) addContentSubview:(UIView *)view atIndex:(NSUInteger)index {
[self :view :index];
[self.views :view :index];
[self ];
self.contentOffset = CGPointMake(0, - self.scrollIndicatorInsets.top);
}
- (void) removeContentSubview:(UIView *)view {
[view ];
[self.views :view];
[self ];
}
- (void)removeContentSubviewAtIndex:(NSUInteger)index {
[self :[self.views :index]];
}
- (void) removeAllContentSubview {
for (UIView* view in self.views) {
[view ];
}
[self.views ];
[self ];
}
#pragma mark -
#pragma mark Layout
- (void) updateViewPositionAndPageControl {
NSUInteger index = 0;
for (UIView* view in self.views) {
view.center = CGPointMake(self.frame.size.width * index + self.frame.size.width / 2,
(self.frame.size.height - GCPagedScrollViewPageControlHeight) / 2);
index ++;
}
UIEdgeInsets inset = self.scrollIndicatorInsets;
CGFloat heightInset = inset.top + inset.bottom;
self.contentSize = CGSizeMake(self.frame.size.width * [self.views ], self.frame.size.height - heightInset);
self.pageControl.numberOfPages = self.views.count;
}
- (void) layoutSubviews {
[super ];
//Avoid that the pageControl move
[CATransaction ];
[CATransaction :(id)kCFBooleanTrue :kCATransactionDisableActions];
CGRect frame = self.pageControl.frame;
frame.origin.x = self.contentOffset.x;
frame.origin.y = self.frame.size.height - GCPagedScrollViewPageControlHeight - self.scrollIndicatorInsets.bottom - self.scrollIndicatorInsets.top;
frame.size.width = self.frame.size.width;
self.pageControl.frame = frame;
[CATransaction ];
}
#pragma mark -
#pragma mark Getters/Setters
- (void) setFrame:(CGRect) newFrame {
[super :newFrame];
[self ];
}
- (void) changePage:(UIPageControl*) aPageControl {
[self :aPageControl.currentPage :YES];
}
- (void) setContentOffset:(CGPoint) new {
new.y = -self.scrollIndicatorInsets.top;
[super :new];
self.pageControl.currentPage = self.page; //Update the page number
}
- (NSMutableArray*) views {
if (views == nil) {
views = [[NSMutableArray ] :1];
}
return views;
}
- (NSUInteger) page {
return (self.contentOffset.x + self.frame.size.width / 2) / self.frame.size.width;
}
- (void) setPage:(NSUInteger)page {
[self :page :NO];
}
- (void) setPage:(NSUInteger)page animated:(BOOL) animated {
[self :CGPointMake(page * self.frame.size.width, - self.scrollIndicatorInsets.top) :animated];
}
#pragma mark -
#pragma mark Dealloc
- (void)dealloc {
[views ];
[pageControl ];
[super ];
}
@end
objective-c2.mm
Theme: gitbook, Line numbers: false
- (void)popToViewControllerOfType:(Class)lollersk8
animated:(BOOL)animated
perl.pl
Theme: light, Line numbers: true
#!/usr/bin/perl
use strict;
use warnings;
use IO::Handle;
use feature ":5.10";
print "Hello \"world\\\"";
print 'Hello \'world\\\'s best';
print 42;
my $animal = "camel";
my $content = '';
open my $fh, "<", "foo" or die $!;
{
local $/;
$content = <$fh>;
}
close $fh;
sub handler { # 1st argument is signal name
my($sig) = @_;
print "Caught a SIG$sig--shutting down\n";
close(LOG);
exit(0);
}
$SIG{'INT'} = \&referenceOrSomethingIGuess;
local $SIG{__WARN__} = sub { die $_[0] };
eval $proggie;
my @mixed = ("camel", 42, 101.23);
print $mixed[$#mixed]; #how do perl programmers remember all this stuff?
@animals[1..$#animals]
my %fruit_color = (
apple => "red",
banana => "yellow",
);
my @fruits = keys %fruit_colors;
my @colors = values %fruit_colors;
given($foo) {
when (undef) {
say '$foo is undefined';
}
when ("foo") {
say '$foo is the string "foo"';
}
when ([1,3,5,7,9]) {
say '$foo is an odd digit';
continue; # Fall through
}
when ($_ < 100) {
say '$foo is numerically less than 100';
}
when (\&complicated_check) {
say 'a complicated check for $foo is true';
}
default {
die q(I don't know what to do (with) $foo);
}
}
if (1) {
#do stuff
} elsif (0) {
#do other stuff
} else {
until (1) {
foreach my $key (keys %hash) {
print "The value of $key is $hash{$key}\n";
}
}
}
#regex literal mayhem
while (<>) {
if (?^$?) {
# blank line between header and body
}
} continue {
reset if eof; # clear ?? status for next file
}
$re = qr/$pattern/;
$string =~ /foo${re}bar/;
$string =~ //;
$string =~ ??;
$string =~ /$re/;
$count = ($paragraph =~ s/Mister\b/Mr./g);
$ARGV[1] =~ tr/A-Z/a-z/; # canonicalize to lower case
tr [\200-\377]
[\000-\177];
y/i/hate/perl; #seriously
$cnt = tr/0-9//; # count the digits in $_
#remove C-like comments I can't believe I got this pile of sewage to parse correctly
$program =~ s {
/\* # Match the opening delimiter.
.*? # Match a minimal number of characters.
\*/ # Match the closing delimiter.
} []gsx;
#friggin' heredocs...
print <<HEREDOC;
Default heredoc body
HEREDOC
print <<"QUOTEDHEREDOC";
Quoted heredoc body
QUOTEDHEREDOC
print <<`BACKQUOTEDHEREDOC`;
echo back quoted heredoc body
BACKQUOTEDHEREDOC
print <<'SINGLEQUOTEDHEREDOC';
single quoted heredoc body
SINGLEQUOTEDHEREDOC
print <<"stacked1", <<"stacked2";
stacked heredoc #1
stacked1
stacked heredoc #2
stacked2
($quote = <<'FINIS') =~ s/^\s+//gm;
The Road goes ever on and on,
down from the door where it began.
FINIS
#doc comments
=pod
=head1 Heading Text
=cut this should not be parsed
sub { say "yay!"; }
php1.php
Theme: gitbook, Line numbers: false
<?php
namespace My\Namespace;
use UseThisClass;
use AlsoUseThis, AndUseThis;
use My\Favorite\UseMePlease;
use Other\Namespace\UseMe, Other\Namespace\NoUseMe;
interface Kissable extends Countable {
function kiss(array $foo = null);
}
abstract class HenryKissable extends ExtendedClass implements ImplementedInterface1, ImplementedInterface2, ImplementedInterface3 {
const KISS = 'kiss';
private $myPrivateVar;
public $publicVar;
#Perl-style comments are stupid
public function __construct($foo, Iterator $bar = null, array $kiss = array()) {
parent::__construct();
$this->myPrivateVar = $foo;
$this->publicVar = $bar ?: new self();
foreach ($kiss as $key => $value) {
//unset stuff
unset($this[$key]);
if ($value instanceof \My\Namespace\InstanceOfClassName1):
$value = $value instanceof InstanceOfClassName2;
endif;
$this[$key] = is_int($value) ? (int)$value : (string)$value;
}
}
protected final function invokeStatic() {
StaticClass::invoke("this is a \"string\"");
static::doSomething();
switch (KISS) {
case 5:
case 0x1a:
if (KISS === 'foo') {
return null;
} elseif (KISS === 'bar') {
return false;
} else {
return true;
}
case 1e3:
break;
default:
throw new OutOfBoundsException();
}
}
function noModifier() {
$fqc = new Fully1\Qualified1\FullyQualifiedClassName1();
$fqc = new \Fully2\Qualified2\FullyQualifiedClassName2();
$notFullyQualified = new NotFullyQualified();
$closure = function($foo, array $bar) use (Fully3\Qualified3\ClassName3 $fqc) {
return $fqc;
};
}
public abstract function(TypeHinted $var);
/**
* This does something
*/
private static function doSomething() {
$emptyheredoc = <<<EMPTYHEREDOC
EMPTYHEREDOC;
$emptynowdoc = <<<'EMPTYNOWDOC'
EMPTYNOWDOC;
$heredoc = "this one is my \"favorite\"";
$heredoc .= <<<LOL
oh 'look'
a heredoc!
LOL;
$nowdoc = <<<'LULZ'
oh look
a nowdoc!
LULZ;
}
}
?>
<?
//short tags
?>
<?= 'lol' ?>
php2.php
Theme: gitbook, Line numbers: true
plaintext.txt
Theme: light, Line numbers: true
powershell.ps1
Theme: light, Line numbers: true
$strComputer = Read-Host "Printer Report - Enter Computer Name"
$OS = Get-WmiObject -Class win32_OperatingSystem -namespace "root\CIMV2" `
-ComputerName $strComputer
# if statement to run code for Windows XP and Windows 2003 Server.
if (($OS.Version -eq "5.1.2600") -or ($OS.Version -eq "5.2.3790"))
{
write-host "Computer Name: " $strComputer
#nested if statement
if ($OS.Version -eq "5.1.2600") {write-host "OS Version: Windows XP"}
elseif ($OS.Version -eq "5.2.3790") {write-host "OS Version: Windows 2003"}
$colPrinters = Get-WmiObject -Class win32_Printer -namespace "root\CIMV2" `
-computerName $strComputer
foreach ($objPrinter in $colPrinters) {
write-host "Name: " $objPrinter.Name
write-host "Description: " $objPrinter.Description
write-host
}
}
# if statement to run code for Windows 2000 Server
elseif ($OS.Version -eq "5.0.2195")
{
write-host "Computer Name: " $strComputer
write-host "OS Version: Windows 2000 Server"
$colPrinters = Get-WmiObject -Class win32_PrintJob -namespace "root\CIMV2" `
-computername $strComputer
foreach ($objPrinter in $colPrinters) {
write-host "Name: " $objPrinter.Name
write-host "Description: " $objPrinter.Description
write-host
}
}
# if OS not identified
else {write-host "The OS for: $strComputer is not supported."}
write-host "-END OF REPORT-"
#prints all powershell keywords
[type]::gettype("System.Management.Automation.KeywordTokenReader")|`
%{$_.InvokeMember("_keywordTokens", "NonPublic,Static,GetField", $null, $_,@())}
#http://weblogs.asp.net/steveschofield/archive/2007/01/25/basic-powershell-examples-couple-useful-commands.aspx
$request = [Fully.Qualified.WebRequest]::Create("http://www.iislogs.com/testlink.aspx")
$response = $request.GetResponse()
$requestStream = $response.GetResponseStream()
$readStream = new-object System.IO.StreamReader $requestStream
new-variable db
$db = $readStream.ReadToEnd()
$readStream.Close()
$response.Close()
python.py
Theme: gitbook, Line numbers: false
#normal strings
print 'Hello, world!'
print "Hello, world!"
#looooooooooooooong strings
print """Hello, world!"""
print '''Hello, world!'''
#raw strings
print r"hello"
print r'hello'
print R"hello"
print R'hello'
print r'''hello'''
print R'''hello'''
print r"""hello"""
print R"""hello"""
#binary strings
print br"hello"
print br'hello'
print bR"hello"
print bR'hello'
print Br"hello"
print Br'hello'
print BR"hello"
print BR'hello'
print br"""hello"""
print br'''hello'''
print bR"""hello"""
print bR'''hello'''
print Br"""hello"""
print Br'''hello'''
print BR"""hello"""
print BR'''hello'''
#fibonacci tuple assignment
parents, babies = (1, 1)
while babies < 100:
print 'This generation has %d babies' % babies
parents, babies = (babies, parents + babies)
#import, regex
import re
for test_string in ['555-1212', 'ILL-EGAL']:
if re.match(r'^\d{3}-\d{4}$', test_string):
print test_string, 'is a valid US local phone number'
else:
print test_string, 'rejected'
#!/usr/bin/env python
# This program adds up integers in the command line
import sys
try:
total = sum(int(arg) for arg in sys.argv[1:])
print 'sum =', total
except ValueError:
print 'Please supply integer arguments'
class BankAccount(object):
def __init__(self, initial_balance=0):
self.balance = initial_balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
self.balance -= amount
def overdrawn(self):
return self.balance < 0
my_account = BankAccount(15)
my_account.withdraw(5)
print my_account.balance
#8-Queens
BOARD_SIZE = 8
class BailOut(Exception):
pass
def validate(queens):
left = right = col = queens[-1]
for r in reversed(queens[:-1]):
left, right = left-1, right+1
if r in (left, col, right):
raise BailOut
def add_queen(queens):
for i in range(BOARD_SIZE):
test_queens = queens + [i]
try:
validate(test_queens)
if len(test_queens) == BOARD_SIZE:
return test_queens
else:
return add_queen(test_queens)
except BailOut:
pass
raise BailOut
queens = add_queen([])
print queens
print "\n".join(". "*q + "Q " + ". "*(BOARD_SIZE-q-1) for q in queens)
variableName = 4**5
complexNumber = 4j += 1
constants = (None, True, False, NotImplemented, __debug__, Ellipsis)
ellipsis = ...
import unittest
def median(pool):
copy = sorted(pool)
size = len(copy)
if size % 2 == 1:
return copy[(size - 1) / 2]
else:
return (copy[size/2 - 1] + copy[size/2]) / 2
class TestMedian(unittest.TestCase):
def testMedian(self):
self.failUnlessEqual(median([2, 9, 9, 7, 9, 2, 4, 5, 8]), 7)
if __name__ == '__main__':
unittest.main()
ruby.rb
Theme: dark, Line numbers: true
#!/usr/bin/ruby
#single line comment
puts 'Hello world!'
puts "Hello world!"
=begin This is a "comment" that begins with
=begin and apparently doesn't end until
you get to a line that starts with =end
=end this is also ignored by the interpreter
def factorial(n)
if n == 0
1
else
n * factorial(n-1)
end
end
`ls -l`
foo %= not(a && b)
print defined? foo || foo.eql?(10) || foo.equal?(10.0)
"stringToChomp1".chomp!()
"stringToChomp2".chomp()
foo = %q(raw string 1)
foo = %Q[raw string 2]
foo = %{raw string 3}
foo = %!raw string\\\! 4!
#regex stuff
print /regextest1/ =~ 'regextest'
print /regextest2/i =~ 'regextest'
print 5 /regextest3/i #not a regex
print %r[regextest4]xm =~ 'regextest' #dear god why does ruby have so many different syntaxes for the same thing?
print %r|regextest5| =~ 'regextest'
print /\/\\/ #escape test
StaticVariableAccess::Bar
case $age
when 0 .. 2
"baby"
when 3 .. 6
"little child"
when 7 .. 12
"child"
when 12 .. 18
# Note: 12 already matched by "child"
"youth"
else
"adult"
end
[1,2,3].each do |i| print i*2, "\n" end
begin
do_something
rescue
recover
ensure
must_to_do
end
BEGIN {
#oh god, the colons!
not_true = false
foo = false ? :symbol1 :not_a_symbol1
foo = false ? (true ? :symbol2 : :symbol3) :not_a_symbol2
}
END {
#do stuff
}
class Person
attr_reader :name, :age
def initialize(name, age)
@name, @age = name, age
end
def <=>(person) # Comparison operator for sorting
@age <=> person.age
end
def to_s
"#@name (#@age)"
end
end
class ParseError < ExtendedException
def initialize input, line, pos
super "Could not parse '#{input}' at line #{line}, position #{pos}"
end
end
raise IdentBeforeNew.new("Foo", 3, 9)
#friggin' heredocs...
#http://ruby-doc.org/docs/ruby-doc-bundle/Manual/man-1.4/syntax.html#here_doc
print <<HEREDOC
Default heredoc body
HEREDOC
print <<"QUOTEDHEREDOC";
Quoted heredoc body
QUOTEDHEREDOC
print <<`BACKQUOTEDHEREDOC`
echo back quoted heredoc body
BACKQUOTEDHEREDOC
print <<'SINGLEQUOTEDHEREDOC'
single quoted heredoc body
SINGLEQUOTEDHEREDOC
print <<"stacked1", <<"stacked2"
stacked heredoc #1
stacked1
stacked heredoc #2
stacked2
if need_define_foo
eval <<-INDENTED # delimiters can be indented
def foo
print "foo\n"
end
INDENTED
end
print <<-'THERE'
This is single quoted.
The above used #{a + 1}
THERE
File::open("grocery-list", "w") do |f|
f << <<GROCERY_LIST
Grocery list
------------
1. Salad mix.
2. Strawberries.*
3. Cereal.
4. Milk.*
* Organic
GROCERY_LIST
end
#<< operator should not be interpreted as heredoc
self << a[0]
def foo(s)
puts s
end
foo <<afterIdent
lol
afterIdent
foo = <<1_a2
lol
1_a2
print "we're still good"
scala.scala
Theme: gitbook, Line numbers: true
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>Name</th> <th>Age</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) } } object callccInterpreter { type Answer = Value; /** * A continuation monad. */ case class M[A](in: (A => Answer) => Answer) { def bind[B](k: A => M[B]) = M[B](c => in (a => k(a) in c)) def map[B](f: A => B): M[B] = bind(x => unitM(f(x))) def flatMap[B](f: A => M[B]): M[B] = bind(f) } def unitM[A](a: A) = M[A](c => c(a)) def id[A] = (x: A) => x def showM(m: M[Value]): String = (m in id).toString() def callCC[A](h: (A => M[A]) => M[A]) = M[A](c => h(a => M[A](d => c(a))) in c) type Name = String trait Term case class Var(x: Name) extends Term case class Con(n: int) extends Term case class Add(l: Term, r: Term) extends Term case class Lam(x: Name, body: Term) extends Term case class App(fun: Term, arg: Term) extends Term case class Ccc(x: Name, t: Term) extends Term trait Value case object Wrong extends Value { override def toString() = "wrong" } case class Num(n: Int) extends Value { override def toString() = n.toString() } case class Fun(f: Value => M[Value]) extends Value { override def toString() = "<function>" } type Environment = List[Pair[Name, Value]]; def lookup(x: Name, e: Environment): M[Value] = e match { case List() => unitM(Wrong) case Pair(y, b) :: e1 => if (x == y) unitM(b) else lookup(x, e1) } def add(a: Value, b: Value): M[Value] = Pair(a, b) match { case Pair(Num(m), Num(n)) => unitM(Num(m + n)) case _ => unitM(Wrong) } def apply(a: Value, b: Value): M[Value] = a match { case Fun(k) => k(b) case _ => unitM(Wrong) } def interp(t: Term, e: Environment): M[Value] = t match { case Var(x) => lookup(x, e) case Con(n) => unitM(Num(n)) case Add(l, r) => for (val a <- interp(l, e); val b <- interp(r, e); val c <- add(a, b)) yield c case Lam(x, t) => unitM(Fun(a => interp(t, Pair(x, a) :: e))) case App(f, t) => for (val a <- interp(f, e); val b <- interp(t, e); val c <- apply(a, b)) yield c case Ccc(x, t) => callCC(k => interp(t, Pair(x, Fun(k)) :: e)) } def test(t: Term): String = showM(interp(t, List())) val term0 = App(Lam("x", Add(Var("x"), Var("x"))), Add(Con(10), Con(11))) val term1 = App(Con(1), Con(2)) val term2 = Add(Con(1), Ccc("k", Add(Con(2), App(Var("k"), Con(4))))) def main(args: Array[String]) { println(test(term0)) println(test(term1)) println(test(term2)) } } // Contributed by Daniel Gronau import scala.annotation._ trait Func[T] { val zero: T def inc(t: T): T def dec(t: T): T def in: T def out(t: T): Unit } object ByteFunc extends Func[Byte] { override val zero: Byte = 0 override def inc(t: Byte) = ((t + 1) & 0xFF).toByte override def dec(t: Byte) = ((t - 1) & 0xFF).toByte override def in: Byte = readByte override def out(t: Byte) { print(t.toChar) } } case class Tape[T](left: List[T], cell: T, right: List[T])(implicit func: Func[T]) { private def headOf(list:List[T]) = if (list.isEmpty) func.zero else list.head private def tailOf(list:List[T]) = if (list.isEmpty) Nil else list.tail def isZero = cell == func.zero def execute(ch: Char) = (ch: @switch) match { case '+' => copy(cell = func.inc(cell)) case '-' => copy(cell = func.dec(cell)) case '<' => Tape(tailOf(left), headOf(left), cell :: right) case '>' => Tape(cell :: left, headOf(right), tailOf(right)) case '.' => func.out(cell); this case ',' => copy(cell = func.in) case '[' | ']' => this case _ => error("Unexpected token: " + ch) } } object Tape { def empty[T](func: Func[T]) = Tape(Nil, func.zero, Nil)(func) } class Brainfuck[T](func:Func[T]) { def execute(p: String) { val prog = p.replaceAll("[^\\+\\-\\[\\]\\.\\,\\>\\<]", "") @tailrec def braceMatcher(pos: Int, stack: List[Int], o2c: Map[Int, Int]): Map[Int,Int] = if(pos == prog.length) o2c else (prog(pos): @switch) match { case '[' => braceMatcher(pos + 1, pos :: stack, o2c) case ']' => braceMatcher(pos + 1, stack.tail, o2c + (stack.head -> pos)) case _ => braceMatcher(pos + 1, stack, o2c) } val open2close = braceMatcher(0, Nil, Map()) val close2open = open2close.map(_.swap) @tailrec def ex(pos:Int, tape:Tape[T]): Unit = if(pos < prog.length) ex((prog(pos): @switch) match { case '[' if tape.isZero => open2close(pos) case ']' if ! tape.isZero => close2open(pos) case _ => pos + 1 }, tape.execute(prog(pos))) println("---running---") ex(0, Tape.empty(func)) println("\n---done---") } } /* Run with: val bf = new Brainfuck(ByteFunc) bf.execute(""">+++++++++[<++++++++>-]<.>+++++++[<++ ++>-]<+.+++++++..+++.[-]>++++++++[<++++>-] <.#>+++++++++++[<+++++>-]<.>++++++++[<++ +>-]<.+++.------.--------.[-]>++++++++[<++++> -]<+.[-]++++++++++.""") */ //symbol literals and chars val aSymbol = 'aSymbol val notASymbol = ' ' val aChar = 'a' val aChar = '\u0041' val rawString = """123"""
tsql.tsql
Theme: light, Line numbers: false
--comment 1
select * from db.my_table where myTable.id > 10
select @@IDENTITY
/* multi
line comment */
select "escaped\\\"";
select 'escaped\\\'';
SELECT TOP 1000
f.foo [foo],
f.bar,
f.name [foo.name],
b.baz,
@@ROWCOUNT
FROM foo f
INNER JOIN bar b
ON b.id = f.bar_id
LEFT OUTER JOIN baz
ON baz.id = f.foo
AND baz.id IS NOT NULL
GROUP BY f.name
HAVING COUNT(f.name) < 10
WHERE LEN(f.foo) < 5
AND LEFT(f.foo) = 'f'
vb1.vb
Theme: gitbook, Line numbers: false
Imports System.Runtime.InteropServices
'comment
''' <summary>
''' How about an XML doc comment?
''' This class does <c cref="Foo">something</c>
''' </summary>
'''
''' <param name="foos">Collection of <see cref="Foo" /></param>
<Attribute1("DEBUG"), Attribute2("TEST1")>
<System.Runtime.InteropServices.DllImport("user32.dll")>
Public Class thisClass(Of t As {GenericConstraint1, GenericConstraint2, Class, New})
' Insert code that defines class members.
End Class
Public Class Dictionary(Of entryType, keyType As IComparable)
Public Sub add(<[In](), ICanHazAttribute()>ByVal e As entryType, ByVal k As keyType)
Dim dk As keyType
'array initialization and char literals
Dim testChars As Char() = New Char(2) {"%"c, "&"c, "@"c}
'casting stuff
f = CType(CType(castVar1, OohNestedCast), CastToThisType)
f = DirectCast(castVar2, NoCastToThisType)
f = CType(castVar3, CastToArray())
Dim objAsConvertible As IConvertible = TryCast(castVar4, TryToCastToThisType)
MsgBox(GetType(GetTypeTest).ToString())
If k.CompareTo(dk) = 0 Then
End If
End Sub
Public Function find(ByVal k As keyType) As entryType
End Function
End Class
Public Class ThisClass
Inherits BaseClass
Implements IInterface1, IInterface2, IInterface3
Sub New(ByVal SomeValue As Integer)
' Call MyBase.New if this is a derived class.
MyBase.New()
MsgBox("ThisClass is initializing with Sub New.")
' Place initialization statements here.
ThisPropertyValue = SomeValue
End Sub
Private ThisPropertyValue As Integer
Property ThisProperty() As Integer
Get
CheckIfDisposed()
ThisProperty = ThisPropertyValue
End Get
Set(ByVal Value As Integer)
CheckIfDisposed()
ThisPropertyValue = Value
End Set
End Property
Private disposed As Boolean = False
Public Sub CheckIfDisposed()
If Me.disposed AndAlso True Then
Throw New ObjectDisposedException(Me.GetType().ToString, _
"This object has been disposed.")
End If
End Sub
End Class
Delegate Function MathOperator(
ByVal x As Double,
ByVal y As Double
) As Double
Function AddNumbers(
ByVal x As Double,
ByVal y As Double
) As Double
Return x + y
End Function
Function SubtractNumbers(
ByVal x As Double,
ByVal y As Double
) As Double
Return x - y
End Function
Sub DelegateTest(
ByVal x As Double,
ByVal op As MathOperator,
ByVal y As Double
)
Dim ret As Double
ret = op.Invoke(x, y) ' Call the method.
MsgBox(ret)
End Sub
Protected Sub Test()
DelegateTest(5, AddressOf AddNumbers, 3)
DelegateTest(9, AddressOf SubtractNumbers, 3)
End Sub
Public Interface thisInterface
Property thisProp(ByVal thisStr As String) As Char
Function thisFunc(ByVal thisInt As Integer) As Integer
End Interface
Public Structure employee
Public firstName As String
Public middleName As String
Const maximum As Long = 459
Friend Sub calculateBonus(ByVal rate As Single)
bonus = salary * CDbl(rate)
End Sub
' Property member to return employee's eligibility.
Friend ReadOnly Property eligible() As Boolean
Get
Return level >= 25
End Get
End Property
' Event member, raised when business phone number has changed.
Public Event changedWorkPhone(ByVal newPhone As Long)
End Structure
Public Module thisModule
Sub Main()
Dim [True] As String = InputBox("What is your name?")
MsgBox("User name is" & [True])
End Sub
' Insert variable, property, procedure, and event declarations.
End Module
Public Enum InterfaceColors
MistyRose = &HE1E4FF
SlateGray = &H908070
DodgerBlue = &HFF901E
DeepSkyBlue = &HFFBF00
SpringGreen = &H7FFF00
ForestGreen = &H228B22
Goldenrod = &H20A5DA
Firebrick = &H2222B2
End Enum
vb2.vb
Theme: gitbook, Line numbers: true
Public Module thisModule
Const i1_OK = 12_34_5%
Const i2_OK = &ha_BC_d23_8&
Const i3_OK = &O42_7i
Const i4_OK = &B01_1_0l
Const i5_OK = +123S
Const i6_OK = -123UI
Const i7_OK = +123uL
Const i8_OK = -123us
Const i9_OK = 2398
Const i1_ERROR = _123 ' This should be an identifier.
Const i2_ERROR = 123_ ' _ is an invalid identifier (still highlighted)
Const f1_OK = 1F
Const f2_OK = 2.0E3R
Const f3_OK = .3E+8D
Const f4_OK = 4E-9
Const f5_OK = 5___2.3_1_3e-4_6_4!
Const f6_OK = 6.2#
Const f7_OK = 7@
End Module
vssolution.sln
Theme: dark, Line numbers: false
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "Project1", "Project1.vbproj", "{8CDD8387-B905-44A8-B5D5-07BB50E05BEA}"
EndProject
Global
GlobalSection(SolutionNotes) = postSolution
Name1 = Note2
Issue1 = N
Text1 = This is a shared note.
Name2 = Note3
Issue2 = N
Text2 = This is also a shared note. The second of two shared notes.
NumNotes = 2
EndGlobalSection
GlobalSection(SolutionConfiguration) = preSolution
ConfigName.0 = Debug
ConfigName.1 = Release
EndGlobalSection
GlobalSection(ProjectDependencies) = postSolution
EndGlobalSection
GlobalSection(ProjectConfiguration) = postSolution
{8CDD8387-B905-44A8-B5D5-07BB50E05BEA}.Debug.ActiveCfg = Debug|.NET
{8CDD8387-B905-44A8-B5D5-07BB50E05BEA}.Debug.Build.0 = Debug|.NET
{8CDD8387-B905-44A8-B5D5-07BB50E05BEA}.Release.ActiveCfg = Release|.NET
{8CDD8387-B905-44A8-B5D5-07BB50E05BEA}.Release.Build.0 = Release|.NET
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
EndGlobalSection
GlobalSection(ExtensibilityAddIns) = postSolution
EndGlobalSection
EndGlobal
xml-multilang.xml
Theme: dark, Line numbers: true
<!doctype html> <html> <head> <script type="text/javascript" src="/sunlight.js"></script> <style></style> <style type="text/css"> @font-face { font-family: Custom; src: url(/fonts/custom.ttf); } body { background-color: black; font-family: "Courier New"; width: 100%; min-height: 200px; } .attention { color: red; border: 2px solid #000000; } </style> <script type="text/javascript"> window.onload = function() { try { var xhr = new XMLHttpRequest(); xhr.open("GET", "/ajax.php", true); xhr.onreadystatechange = function(e) { if (xhr.readyState === 4 && xhr.status === 200) { document.getElementById("foo").innerHTML = xhr.responseText; } }; xhr.send(null); } catch (e) {} }; </script> </head> <body> <p> Let's try some PHP: Hello <?= $_GET['username'] ?>! Long tags work, too: <?php echo 'Hello world'; foreach (range(1, 10) as $i) { print_r($i); //prints $i lol } ?> </p> <p> Now let's try some C#: </p> <%-- server side comment --%> <% if (User.IsInRole("admin")) { %> You can see this <% } else { %> You are no admin fool! <% } %> <%= "Short tag ftw" %> </body> </html>
xml.xml
Theme: light, Line numbers: false
<?xml version="1.0" ?>
<config xmlns:foo="http://example.com">
<!-- sections -->
<section name="foo">Content of the section</section>
<section name="bar">Content of the section&beforeopentag;</section>
<section foo:id="12" name="foo">Content of the "section" & stuff</section>
<System.Net />
<!-- cdata -->
<![CDATA[I can put whatever I want here HAHAHA!
<tags> that shouldn't be tags</tags>
<?xml lol! ?>]]>
<_self-closing />
<section>
<nested lulz="asdf">
And again…
<again>nested content</again>
</nested>
</section>
</config>