use prism-tomorrow.css

This commit is contained in:
CyC2018
2018-12-19 14:09:39 +08:00
parent 0f00bcacaf
commit e9e604e6a7
1747 changed files with 100462 additions and 0 deletions

View File

@ -0,0 +1,65 @@
<h2>Comments</h2>
<pre><code>
* Line Comments
&quot; End of line comment used as line comment.
value = 1. &quot; End of line comment
DATA:
&quot;! ABAPDoc comment
value TYPE i.
</code></pre>
<h2>Strings</h2>
<pre><code>
my_string = 'Simple string'.
my_string = 'String with an escaped '' inside'.
my_string = |A string template: { nvalue } times|.
my_string = |A string template: { nvalue } times|.
my_string = |Characters \|, \{, and \} have to be escaped by \\ in literal text.|.
</code></pre>
<h2>Numbers and Operators</h2>
<pre><code>
value = 001 + 2 - 3 * 4 / 5 ** 6.
IF value &lt; 1 OR
value = 2 OR
value &gt; 3 OR
value &lt;&gt; 4 OR
value &lt;= 5 OR
value &gt;= 6.
ENDIF.
" Dynamic object assignment (with type cast check)
lo_interface ?= lo_class.
</code></pre>
<h2>Structures and Classes</h2>
<pre><code>
DATA:
BEGIN OF my_structure,
scomponent TYPE i,
END OF my_structure.
CLASS lcl_my_class DEFINITION.
PUBLIC SECTION.
METHODS my_method
RETURNING
VALUE(ret_value) TYPE i.
ENDCLASS.
CLASS lcl_my_class IMPLEMENTATION.
METHOD my_method.
ret_value = 1.
ENDMETHOD
ENDCLASS.
DATA lo_instace TYPE REF TO lcl_my_class.
CREATE OBJECT lo_instace.
my_structure-component = lo_instace->my_method( ).
</code></pre>

View File

@ -0,0 +1,133 @@
<h2>Comments</h2>
<pre><code>// Single line comment
/* Multi-line
comment */</code></pre>
<h2>Literal values</h2>
<pre><code>17
"hello"
-3
9.4
null
true
false</code></pre>
<h2>Classes</h2>
<pre><code>class A {}
class B extends A {}</code></pre>
<h2>Inline XML</h2>
<pre><code>var employees:XML =
&lt;employees>
&lt;employee ssn="123-123-1234">
&lt;name first="John" last="Doe"/>
&lt;address>
&lt;city>San Francisco&lt;/city>
&lt;state>CA&lt;/state>
&lt;zip>98765&lt;/zip>
&lt;/address>
&lt;/employee>
&lt;employee ssn="789-789-7890">
&lt;name first="Mary" last="Roe"/>
&lt;address>
&lt;city>Newton&lt;/city>
&lt;state>MA&lt;/state>
&lt;zip>01234&lt;/zip>
&lt;/address>
&lt;/employee>
&lt;/employees>;</code></pre>
<h2>Full example</h2>
<pre><code>package {
import flash.display.*;
import flash.events.*;
import flash.filters.BlurFilter;
import flash.geom.*;
import flash.ui.*;
public class ch23ex2 extends Sprite {
protected const BMP_SCALE:Number = 1/2;
protected const D:Number = 1.015;
protected const DIM_EFFECT:ColorTransform = new ColorTransform(D, D, D);
protected const B:int = 16;
protected const BLUR_EFFECT:BlurFilter = new BlurFilter(B, B, 1);
protected var RLUT:Array, GLUT:Array, BLUT:Array;
protected var sourceBmp:BitmapData;
protected var colorBmp:BitmapData;
protected var touches:Array = new Array();
protected var fingerShape:Shape = new Shape();
public function ch23ex2() {
try {
var test:Class = Multitouch;
if (Multitouch.supportsTouchEvents) {
Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT;
init();
} else {
trace("Sorry, this example requires multitouch.");
}
} catch (error:ReferenceError) {
trace("Sorry, but multitouch is not supported in this runtime.");
}
}
protected function init():void {
//create a black-and-white bitmap and a color bitmap, only show the color
sourceBmp = new BitmapData(
stage.stageWidth*BMP_SCALE, stage.stageHeight*BMP_SCALE, false, 0);
colorBmp = sourceBmp.clone();
var bitmap:Bitmap = new Bitmap(colorBmp, PixelSnapping.ALWAYS, true);
bitmap.width = stage.stageWidth; bitmap.height = stage.stageHeight;
addChild(bitmap);
//create finger shape to paste onto the bitmap under your touches
fingerShape.graphics.beginFill(0xffffff, 0.1);
fingerShape.graphics.drawEllipse(-15, -20, 30, 40);
fingerShape.graphics.endFill();
//create the palette map from a gradient
var gradient:Shape = new Shape();
var m:Matrix = new Matrix();
m.createGradientBox(256, 10);
gradient.graphics.beginGradientFill(GradientType.LINEAR,
[0x313ad8, 0x2dce4a, 0xdae234, 0x7a1c1c, 0x0f0303],
[1, 1, 1, 1, 1], [0, 0.4*256, 0.75*256, 0.9*256, 255], m);
gradient.graphics.drawRect(0, 0, 256, 10);
var gradientBmp:BitmapData = new BitmapData(256, 10, false, 0);
gradientBmp.draw(gradient);
RLUT = new Array(); GLUT = new Array(); BLUT = new Array();
for (var i:int = 0; i < 256; i++) {
var pixelColor:uint = gradientBmp.getPixel(i, 0);
//I drew the gradient backwards, so sue me
RLUT[256-i] = pixelColor & 0xff0000;
GLUT[256-i] = pixelColor & 0x00ff00;
BLUT[256-i] = pixelColor & 0x0000ff;
}
stage.addEventListener(TouchEvent.TOUCH_BEGIN, assignTouch);
stage.addEventListener(TouchEvent.TOUCH_MOVE, assignTouch);
stage.addEventListener(TouchEvent.TOUCH_END, removeTouch);
stage.addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
protected function assignTouch(event:TouchEvent):void {
touches[event.touchPointID] = event;
}
protected function removeTouch(event:TouchEvent):void {
delete touches[event.touchPointID];
}
protected function onEnterFrame(event:Event):void {
for (var key:String in touches) {
var touch:TouchEvent = touches[key] as TouchEvent;
if (touch) {
//plaster the finger image under your finger
var m:Matrix = new Matrix();
m.translate(touch.stageX*BMP_SCALE, touch.stageY*BMP_SCALE);
sourceBmp.draw(fingerShape, m, null, BlendMode.ADD);
}
}
var O:Point = new Point(0, 0);
//blur and ever-so-slightly brighten the image to make the color last
sourceBmp.applyFilter(sourceBmp, sourceBmp.rect, O, BLUR_EFFECT);
sourceBmp.colorTransform(sourceBmp.rect, DIM_EFFECT);
//we've calculated the image in grayscale brightnesses, now make it color
colorBmp.paletteMap(sourceBmp, sourceBmp.rect, O, RLUT, GLUT, BLUT, null);
}
}
}</code></pre>

View File

@ -0,0 +1,35 @@
<h2>Strings</h2>
<pre><code>"foo ""bar"" baz"
"Multi-line strings are appended with a " &
"ampersand symbole."</code></pre>
<h2>Ada83 example</h2>
<pre><code>WITH ADA.TEXT_IO;
-- Comments look like this.
PROCEDURE TEST IS
BEGIN
ADA.TEXT_IO.PUT_LINE ("Hello"); -- Comments look like this.
END TEST;</code></pre>
<h2>Ada 2012 full example</h2>
<pre><code>with Ada.Text_IO; Use Ada.Text_IO;
-- Comments look like this.
procedure Test is
procedure Bah with
Import => True, -- Shows the new aspect feature of the language.
Convention => C,
External_Name => "bah";
type Things is range 1 .. 10;
begin
Put_Line ("Hello"); -- Comments look like this.
Bah; -- Call C function.
for Index in Things'Range loop
null;
end loop;
end Test;</code></pre>

View File

@ -0,0 +1,54 @@
<h2>Comments</h2>
<pre><code># This is a comment
# &lt;VirtualHost *:80>
</code></pre>
<h2>Directives</h2>
<pre><code>&lt;Files .htaccess>
Order allow,deny
Deny from all
&lt;/Files>
</code></pre>
<h2>Variables</h2>
<pre><code>RewriteCond %{REQUEST_FILENAME}.php -f</code></pre>
<h2>Regex</h2>
<pre><code>^(.*)$
!^www\.</code></pre>
<h2>Directive flags</h2>
<pre><code>[NC]
[RC=301,L]</code></pre>
<h2>Strings</h2>
<pre><code>AuthName "Fichiers réservés"</code></pre>
<h2>Full example</h2>
<pre><code>## BASIC PASSWORD PROTECTION
AuthType basic
AuthName "prompt"
AuthUserFile /.htpasswd
AuthGroupFile /dev/null
Require valid-user
## ALLOW FROM IP OR VALID PASSWORD
Require valid-user
Allow from 192.168.1.23
Satisfy Any
## PROTECT FILES
Order Allow,Deny
Deny from all
## REQUIRE SUBDOMAIN
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^subdomain\.domain\.tld$ [NC]
RewriteRule ^/(.*)$ http://subdomain.domain.tld/$1 [L,R=301]
ErrorDocument 403 http://www.example.com/logo.gif
ErrorDocument 403 /images/you_bad_hotlinker.gif
## REDIRECT UPLOADS
RewriteCond %{REQUEST_METHOD} ^(PUT|POST)$ [NC]
RewriteRule ^(.*)$ /cgi-bin/form-upload-processor.cgi?p=$1 [L,QSA]</code></pre>

View File

@ -0,0 +1,26 @@
<h2>Comments</h2>
<pre><code>#!/usr/bin/env runapl
a←1 2 3 ⍝ this is a comment</code></pre>
<h2>Strings</h2>
<pre><code>''
'foobar'
'foo''bar''baz'</code></pre>
<h2>Numbers</h2>
<pre><code>42
3.14159
¯2
2.8e¯4
2j3
¯4.3e2J1.9e¯4</code></pre>
<h2>Primitive functions</h2>
<pre><code>a+b×c10</code></pre>
<h2>Operators</h2>
<pre><code>+/ f⍣2</code></pre>
<h2>Dfns</h2>
<pre><code>{0=:'hello' ⋄ ∇¨⍵}</code></pre>

View File

@ -0,0 +1,41 @@
<h2>Comments</h2>
<pre><code>-- Single line comment
#!/usr/bin/osascript
(* Here is
a block
comment *)</code></pre>
<h2>Strings</h2>
<pre><code>"foo \"bar\" baz"</code></pre>
<h2>Operators</h2>
<pre><code>a ≠ b
12 + 2 * 5
"DUMPtruck" is equal to "dumptruck"
"zebra" comes after "aardvark"
{ "this", "is", 2, "cool" } starts with "this"
{ "is", 2} is contained by { "this", "is", 2, "cool" }
set docRef to a reference to the first document
</code></pre>
<h2>Classes and units</h2>
<pre><code>tell application "Finder"
text 1 thru 5 of "Bring me the mouse."
set averageTemp to 63 as degrees Fahrenheit
set circleArea to (pi * 7 * 7) as square yards
</code></pre>
<h2>Known failures</h2>
<p>There are certain edge cases where Prism will fail.
There are always such cases in every regex-based syntax highlighter.
However, Prism dares to be open and honest about them.
If a failure is listed here, it doesnt mean it will never be fixed. This is more of a “known bugs” list, just with a certain type of bug.
</p>
<h3>Comments only support one level of nesting</h3>
<pre><code>(* Nested block
(* comments
(* on more than
2 levels *)
are *)
not supported *)</code></pre>

View File

@ -0,0 +1,63 @@
<h2>Strings</h2>
<pre><code>"foo \"bar\" baz"
'foo \'bar\' baz'
"Multi-line strings ending with a \
are supported too."</code></pre>
<h2>Macro statements</h2>
<pre><code>#include &lt;Bridge.h>
#define SOME_PIN 11
</code></pre>
<h2>Booleans</h2>
<pre><code>true;
false;</code></pre>
<h2>Operators</h2>
<pre><code>a < b;
c &amp;&amp; d;</code></pre>
<h2>Full example</h2>
<pre><code>#include &lt;Bridge.h>
// pin of the piezo speaker
int piezo = 8;
/**
* setups
* runs once before everyhing else
*/
void setup() {
pinMode(piezo, OUTPUT);
}
/**
* loop
* this will run forever and do what we want
*/
void loop() {
playMelody(1);
delay(1000);
}
/**
* playMelody
* will play a simple melody on piezo speaker
*/
void playMelody(int times) {
int melody[] = { 4699, 4699, 3520, 4699 };
int duration = 6;
for( int t = 0; t &lt; times; t++ ) {
for( int i = 0; i &lt; 4; i++ ) {
// pass tone to selected pin
tone(piezoPin, melody[i], 1000/duration);
// get a bit of time between the tones
delay(1000 / duration * 1.30 + 80);
// and don't forget to switch of the tone afterwards
noTone(piezoPin);
}
}
}</code></pre>

View File

@ -0,0 +1,46 @@
<h2>Comments</h2>
<pre><code>%
% Some comments
%
%</code></pre>
<h2>Keywords</h2>
<pre><code>@attribute
@data
@relation</code></pre>
<h2>Numbers</h2>
<pre><code>42
0.14</code></pre>
<h2>Strings</h2>
<pre><code>'Single \'quoted\' string'
"Double \"quoted\" string"</code></pre>
<h2>Full example</h2>
<pre><code>% 1. Title: Iris Plants Database
%
% 2. Sources:
% (a) Creator: R.A. Fisher
% (b) Donor: Michael Marshall (MARSHALL%PLU@io.arc.nasa.gov)
% (c) Date: July, 1988
%
@RELATION iris
@ATTRIBUTE sepallength NUMERIC
@ATTRIBUTE sepalwidth NUMERIC
@ATTRIBUTE petallength NUMERIC
@ATTRIBUTE petalwidth NUMERIC
@ATTRIBUTE class {Iris-setosa,Iris-versicolor,Iris-virginica}
@DATA
5.1,3.5,1.4,0.2,Iris-setosa
4.9,3.0,1.4,0.2,Iris-setosa
4.7,3.2,1.3,0.2,Iris-setosa
4.6,3.1,1.5,0.2,Iris-setosa
5.0,3.6,1.4,0.2,Iris-setosa
5.4,3.9,1.7,0.4,Iris-setosa
4.6,3.4,1.4,0.3,Iris-setosa
5.0,3.4,1.5,0.2,Iris-setosa
4.4,2.9,1.4,0.2,Iris-setosa
4.9,3.1,1.5,0.1,Iris-setosa</code></pre>

View File

@ -0,0 +1,104 @@
<h2>Comments</h2>
<pre><code>/////
Comment block
/////
// Comment line</code></pre>
<h2>Titles</h2>
<pre><code>Level 0
========
Level 1
--------
Level 2
~~~~~~~~
Level 3
^^^^^^^^
Level 4
++++++++
= Document Title (level 0) =
== Section title (level 1) ==
=== Section title (level 2) ===
==== Section title (level 3) ====
===== Section title (level 4) =====
.Notes</code></pre>
<h2>Blocks</h2>
<pre><code>++++++++++++++++++++++++++
Passthrough block
++++++++++++++++++++++++++
--------------------------
Listing block
--------------------------
..........................
Literal block
No *highlighting* _here_
..........................
**************************
Sidebar block
**************************
[quote,'http://en.wikipedia.org/wiki/Samuel_Johnson[Samuel Johnson]']
_____________________________________________________________________
Sir, a woman's preaching is like a dog's walking on his hind legs. It
is not done well; but you are surprised to find it done at all.
_____________________________________________________________________
==========================
Example block
==========================</code></pre>
<h2>Lists</h2>
<pre><code>- List item.
* List item.
** List item.
*** List item.
**** List item.
***** List item.
1. Arabic (decimal) numbered list item.
a. Lower case alpha (letter) numbered list item.
F. Upper case alpha (letter) numbered list item.
iii) Lower case roman numbered list item.
IX) Upper case roman numbered list item.
. Arabic (decimal) numbered list item.
.. Lower case alpha (letter) numbered list item.
... Lower case roman numbered list item.
.... Upper case alpha (letter) numbered list item.
..... Upper case roman numbered list item.
Dolor::
Donec eget arcu bibendum nunc consequat lobortis.
Suspendisse;;
A massa id sem aliquam auctor.
Morbi;;
Pretium nulla vel lorem.
In;;
Dictum mauris in urna.
Vivamus::: Fringilla mi eu lacus.
Donec::: Eget arcu bibendum nunc consequat lobortis.</code></pre>
<h2>Tables</h2>
<pre><code>[cols="e,m,^,>s",width="25%"]
|============================
|1 >s|2 |3 |4
^|5 2.2+^.^|6 .3+<.>m|7
^|8
|9 2+>|10
|============================</code></pre>
<h2>Inline styles</h2>
<pre><code>*Some bold text*
This is an _emphasis_
[[[walsh-muellner]]]</code></pre>
<h2>Attribute entries</h2>
<pre><code>:Author Initials: JB
{authorinitials}
:Author Initials!:</code></pre>

View File

@ -0,0 +1,39 @@
<h2>Comments</h2>
<pre><code>; This is a comment</code></pre>
<h2>Labels</h2>
<pre><code>label1: ; a label</code></pre>
<h2>Opcodes</h2>
<pre><code>
SEI
CLC
; lowercase
inx
bne label1
</code></pre>
<h2>Assembler directives</h2>
<pre><code>
.segment CODE
.word $07d3
</code></pre>
<h2>Registers</h2>
<pre><code>
ASL A ; "A"
LDA label1,x ; "x"
</code></pre>
<h2>Strings</h2>
<pre><code>
.include "header.asm"
</code></pre>
<h2>Numbers</h2>
<pre><code>
LDA #127
STA $80f0
LDY #%01011000
</code></pre>

View File

@ -0,0 +1,36 @@
<h2>Comments</h2>
<pre><code><%-- This is a comment --%>
<%-- This is a
multi-line comment --%></code></pre>
<h2>Page directives</h2>
<pre><code><%@ Page Title="Products" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="ProductList.aspx.cs" Inherits="WingtipToys.ProductList" %>
</code></pre>
<h2>Directive tag</h2>
<pre><code><%: Page.Title %>
&lt;a href="ProductDetails.aspx?productID=<%#:Item.ProductID%>">
&lt;span>
<%#:Item.ProductName%>
&lt;/span></code></pre>
<h2>Highlighted C# inside scripts</h2>
<p>This requires the C# component to be loaded.
On this page, check C# <strong>before</strong> checking ASP.NET should make
the example below work properly.</p>
<pre><code>&lt;script runat="server">
// The following variables are visible to all procedures
// within the script block.
String str;
int i;
int i2;
int DoubleIt(int inpt)
{
// The following variable is visible only within
// the DoubleIt procedure.
int factor = 2;
return inpt * factor;
}
&lt;/script></code></pre>

View File

@ -0,0 +1,68 @@
<h2>Comments</h2>
<pre><code>; This is a comment</code></pre>
<h2>Strings</h2>
<pre><code>"foo ""bar"" baz"</code></pre>
<h2>Numbers</h2>
<pre><code>123
123.456
123.456e789
0xAF</code></pre>
<h2>Full example</h2>
<pre><code>;----Open the selected favorite
f_OpenFavorite:
; Fetch the array element that corresponds to the selected menu item:
StringTrimLeft, f_path, f_path%A_ThisMenuItemPos%, 0
if f_path =
return
if f_class = #32770 ; It's a dialog.
{
if f_Edit1Pos <> ; And it has an Edit1 control.
{
; Activate the window so that if the user is middle-clicking
; outside the dialog, subsequent clicks will also work:
WinActivate ahk_id %f_window_id%
; Retrieve any filename that might already be in the field so
; that it can be restored after the switch to the new folder:
ControlGetText, f_text, Edit1, ahk_id %f_window_id%
ControlSetText, Edit1, %f_path%, ahk_id %f_window_id%
ControlSend, Edit1, {Enter}, ahk_id %f_window_id%
Sleep, 100 ; It needs extra time on some dialogs or in some cases.
ControlSetText, Edit1, %f_text%, ahk_id %f_window_id%
return
}
; else fall through to the bottom of the subroutine to take standard action.
}
else if f_class in ExploreWClass,CabinetWClass ; In Explorer, switch folders.
{
if f_Edit1Pos <> ; And it has an Edit1 control.
{
ControlSetText, Edit1, %f_path%, ahk_id %f_window_id%
; Tekl reported the following: "If I want to change to Folder L:\folder
; then the addressbar shows http://www.L:\folder.com. To solve this,
; I added a {right} before {Enter}":
ControlSend, Edit1, {Right}{Enter}, ahk_id %f_window_id%
return
}
; else fall through to the bottom of the subroutine to take standard action.
}
else if f_class = ConsoleWindowClass ; In a console window, CD to that directory
{
WinActivate, ahk_id %f_window_id% ; Because sometimes the mclick deactivates it.
SetKeyDelay, 0 ; This will be in effect only for the duration of this thread.
IfInString, f_path, : ; It contains a drive letter
{
StringLeft, f_path_drive, f_path, 1
Send %f_path_drive%:{enter}
}
Send, cd %f_path%{Enter}
return
}
; Since the above didn't return, one of the following is true:
; 1) It's an unsupported window type but f_AlwaysShowMenu is y (yes).
; 2) It's a supported type but it lacks an Edit1 control to facilitate the custom
; action, so instead do the default action below.
Run, Explorer %f_path% ; Might work on more systems without double quotes.
return</code></pre>

View File

@ -0,0 +1,52 @@
<h2>Comments</h2>
<pre><code>; Single-line comment
#comments-start
Multi-line
comment
#comments-end
#cs
Multi-line
comment
#ce
;#comments-start
foo()
;#comments-end</code></pre>
<h2>Strings</h2>
<pre><code>"foo'bar'baz"
"foo""bar""baz"
'foo"bar"baz'
'foo''bar''baz'</code></pre>
<h2>Numbers</h2>
<pre><code>2
4.566
1.5e3
0x4fff</code></pre>
<h2>Booleans</h2>
<pre><code>True
False</code></pre>
<h2>Keywords and variables</h2>
<pre><code>; Display all the numbers for 1 to 10 but skip displaying 7.
For $i = 1 To 10
If $i = 7 Then
ContinueLoop ; Skip displaying the message box when $i is equal to 7.
EndIf
MsgBox($MB_SYSTEMMODAL, "", "The value of $i is: " & $i)
Next</code></pre>
<h2>Known failures</h2>
<p>There are certain edge cases where Prism will fail.
There are always such cases in every regex-based syntax highlighter.
However, Prism dares to be open and honest about them.
If a failure is listed here, it doesnt mean it will never be fixed. This is more of a “known bugs” list, just with a certain type of bug.
</p>
<h3>Nested block comments</h3>
<pre><code>#cs
#cs
foo()
#ce
#ce</code></pre>

View File

@ -0,0 +1,49 @@
<h2>Shebang</h2>
<pre><code>#!/bin/bash</code></pre>
<h2>Comments</h2>
<pre><code># This is a comment</code></pre>
<h2>Strings</h2>
<pre><code>STRING="Hello World"
'Single and
multi-line strings are supported.'
"Single and
multi-line strings are supported."
cat &lt;&lt; EOF
Here-Documents
are also supported
EOF</code></pre>
<h2>Variables</h2>
<pre><code>echo $STRING
args=("$@")
echo ${args[0]} ${args[1]} ${args[2]}</code></pre>
<h2>Keywords</h2>
<pre><code>for (( i=0;i<$ELEMENTS;i++)); do
echo ${ARRAY[${i}]}
done
while read LINE; do
ARRAY[$count]=$LINE
((count++))
done
if [ -d $directory ]; then
echo "Directory exists"
else
echo "Directory does not exists"
fi
</code></pre>
<h2>Some well-known commands</h2>
<pre><code>crontab -l -u USER | grep -v 'YOUR JOB COMMAND or PATTERN' | crontab -u USER -
groups user1 user2|cut -d: -f2|xargs -n1|sort|uniq -d
wget -q -O - http://www.example.com/automation/remotescript.sh | bash /dev/stdin parameter1 parameter2
sudo dpkg -i vagrant_1.7.2_x86_64.deb
git pull origin master
sudo gpg --refresh-keys; sudo apt-key update; sudo rm -rf /var/lib/apt/{lists,lists.old}; sudo mkdir -p /var/lib/apt/lists/partial; sudo apt-get clean all; sudo apt-get update</code></pre>

View File

@ -0,0 +1,69 @@
<p>Note: this component focuses on first and second-generation BASICs (such as MSX BASIC, GW-BASIC, SuperBASIC, QuickBASIC, PowerBASIC...).</p>
<h2>Comments</h2>
<pre><code>! This is a comment
REM This is a remark</code></pre>
<h2>Strings</h2>
<pre><code>"This a string."
"This is a string with ""quotes"" in it."</code></pre>
<h2>Numbers</h2>
<pre><code>42
3.14159
-42
-3.14159
.5
10.
2E10
4.2E-14
-3E+2</code></pre>
<h2>Dartmouth Basic example</h2>
<pre><code>5 LET S = 0
10 MAT INPUT V
20 LET N = NUM
30 IF N = 0 THEN 99
40 FOR I = 1 TO N
45 LET S = S + V(I)
50 NEXT I
60 PRINT S/N
70 GO TO 5
99 END</code></pre>
<h2>GW-BASIC example</h2>
<pre><code>10 INPUT "What is your name: ", U$
20 PRINT "Hello "; U$
30 INPUT "How many stars do you want: ", N
40 S$ = ""
50 FOR I = 1 TO N
60 S$ = S$ + "*"
70 NEXT I
80 PRINT S$
90 INPUT "Do you want more stars? ", A$
100 IF LEN(A$) = 0 THEN GOTO 90
110 A$ = LEFT$(A$, 1)
120 IF A$ = "Y" OR A$ = "y" THEN GOTO 30
130 PRINT "Goodbye "; U$
140 END</code></pre>
<h2>QuickBASIC example</h2>
<pre><code>DECLARE SUB PrintSomeStars (StarCount!)
REM QuickBASIC example
INPUT "What is your name: ", UserName$
PRINT "Hello "; UserName$
DO
INPUT "How many stars do you want: ", NumStars
CALL PrintSomeStars(NumStars)
DO
INPUT "Do you want more stars? ", Answer$
LOOP UNTIL Answer$ <> ""
Answer$ = LEFT$(Answer$, 1)
LOOP WHILE UCASE$(Answer$) = "Y"
PRINT "Goodbye "; UserName$
SUB PrintSomeStars (StarCount)
REM This procedure uses a local variable called Stars$
Stars$ = STRING$(StarCount, "*")
PRINT Stars$
END SUB</code></pre>

View File

@ -0,0 +1,17 @@
<h2>Comments</h2>
<pre><code>::
:: Foo bar
REM This is a comment too
REM Multi-line ^
comment</code></pre>
<h2>Labels</h2>
<pre><code>:foobar
GOTO :EOF</code></pre>
<h2>Commands</h2>
<pre><code>@ECHO OFF
FOR /l %%a in (5,-1,1) do (TITLE %title% -- closing in %%as)
SET title=%~n0
if /i "%InstSize:~0,1%"=="M" set maxcnt=3
ping -n 2 -w 1 127.0.0.1</code></pre>

View File

@ -0,0 +1,104 @@
<h2>Comments</h2>
<pre><code>// Single-line comment
/* Multi-line
comment */</code></pre>
<h2>C prologue and Bison declarations</h2>
<pre><code>%{
#include &lt;stdio.h>
#include &lt;math.h>
int yylex (void);
void yyerror (char const *);
%}
%define api.value.type {double}
%token NUM
%union { char *string; }
%%
%%</code></pre>
<h2>Grammar rules</h2>
<pre><code>%%
exp:
NUM { $$ = $1; }
| exp exp '+' { $$ = $1 + $2; }
| exp exp '-' { $$ = $1 - $2; }
| exp exp '*' { $$ = $1 * $2; }
| exp exp '/' { $$ = $1 / $2; }
| exp exp '^' { $$ = pow($1, $2); } /* Exponentiation */
| exp 'n' { $$ = -$1; } /* Unary minus */
;
$@1: %empty { a(); };
$@2: %empty { c(); };
$@3: %empty { d(); };
exp: $@1 "b" $@2 $@3 "e" { f(); };
%%</code></pre>
<h2>Full example</h2>
<pre><code>/* Mini Calculator */
/* calc.y */
%{
#include "heading.h"
int yyerror(char *s);
int yylex(void);
%}
%union{
int int_val;
string* op_val;
}
%start input
%token &lt;int_val> INTEGER_LITERAL
%type &lt;int_val> exp
%left PLUS
%left MULT
%%
input: /* empty */
| exp { cout &lt;&lt; "Result: " &lt;&lt; $1 &lt;&lt; endl; }
;
exp: INTEGER_LITERAL { $$ = $1; }
| exp PLUS exp { $$ = $1 + $3; }
| exp MULT exp { $$ = $1 * $3; }
;
%%
int yyerror(string s)
{
extern int yylineno; // defined and maintained in lex.c
extern char *yytext; // defined and maintained in lex.c
cerr &lt;&lt; "ERROR: " &lt;&lt; s &lt;&lt; " at symbol \"" &lt;&lt; yytext;
cerr &lt;&lt; "\" on line " &lt;&lt; yylineno &lt;&lt; endl;
exit(1);
}
int yyerror(char *s)
{
return yyerror(string(s));
}</code></pre>
<h2>Known failures</h2>
<p>There are certain edge cases where Prism will fail.
There are always such cases in every regex-based syntax highlighter.
However, Prism dares to be open and honest about them.
If a failure is listed here, it doesnt mean it will never be fixed. This is more of a “known bugs” list, just with a certain type of bug.
</p>
<h3>Two levels of nesting inside C section</h3>
<pre><code>{
if($1) {
if($2) {
}
}
} // <- Broken
%%
%%</code></pre>

View File

@ -0,0 +1,37 @@
<h2>Full example</h2>
<pre><code>+++++ +++ Set Cell #0 to 8
[
>++++ Add 4 to Cell #1; this will always set Cell #1 to 4
[ as the cell will be cleared by the loop
>++ Add 2 to Cell #2
>+++ Add 3 to Cell #3
>+++ Add 3 to Cell #4
>+ Add 1 to Cell #5
<<<<- Decrement the loop counter in Cell #1
] Loop till Cell #1 is zero; number of iterations is 4
>+ Add 1 to Cell #2
>+ Add 1 to Cell #3
>- Subtract 1 from Cell #4
>>+ Add 1 to Cell #6
[<] Move back to the first zero cell you find; this will
be Cell #1 which was cleared by the previous loop
<- Decrement the loop Counter in Cell #0
] Loop till Cell #0 is zero; number of iterations is 8
The result of this is:
Cell No : 0 1 2 3 4 5 6
Contents: 0 0 72 104 88 32 8
Pointer : ^
>>. Cell #2 has value 72 which is 'H'
>---. Subtract 3 from Cell #3 to get 101 which is 'e'
+++++++..+++. Likewise for 'llo' from Cell #3
>>. Cell #5 is 32 for the space
<-. Subtract 1 from Cell #4 for 87 to give a 'W'
<. Cell #3 was set to 'o' from the end of 'Hello'
+++.------.--------. Cell #3 for 'rl' and 'd'
>>+. Add 1 to Cell #5 gives us an exclamation point
>++. And finally a newline from Cell #6</code></pre>
<h2>One-line example</h2>
<pre><code>++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++.</code></pre>

View File

@ -0,0 +1,645 @@
<h2>Comments</h2>
<pre><code># Single line comment
</code></pre>
<h2>Strings</h2>
<pre><code>
"a", "b"
</code></pre>
<h2>Numbers</h2>
<pre><code>123
123.456
-123.456
</code></pre>
<h2>Misc</h2>
<pre><code>
@ifndef ourexp
@load-sigs somesigs
</code></pre>
<h2>Full example</h2>
<pre><code>
##! Scan detector ported from Bro 1.x.
##!
##! This script has evolved over many years and is quite a mess right now. We
##! have adapted it to work with Bro 2.x, but eventually Bro 2.x will
##! get its own rewritten and generalized scan detector.
@load base/frameworks/notice/main
module Scan;
export {
redef enum Notice::Type += {
## The source has scanned a number of ports.
PortScan,
## The source has scanned a number of addresses.
AddressScan,
## Apparent flooding backscatter seen from source.
BackscatterSeen,
## Summary of scanning activity.
ScanSummary,
## Summary of distinct ports per scanner.
PortScanSummary,
## Summary of distinct low ports per scanner.
LowPortScanSummary,
## Source reached :bro:id:`Scan::shut_down_thresh`
ShutdownThresh,
## Source touched privileged ports.
LowPortTrolling,
};
# Whether to consider UDP "connections" for scan detection.
# Can lead to false positives due to UDP fanout from some P2P apps.
const suppress_UDP_scan_checks = F &redef;
const activate_priv_port_check = T &redef;
const activate_landmine_check = F &redef;
const landmine_thresh_trigger = 5 &redef;
const landmine_address: set[addr] &redef;
const scan_summary_trigger = 25 &redef;
const port_summary_trigger = 20 &redef;
const lowport_summary_trigger = 10 &redef;
# Raise ShutdownThresh after this many failed attempts
const shut_down_thresh = 100 &redef;
# Which services should be analyzed when detecting scanning
# (not consulted if analyze_all_services is set).
const analyze_services: set[port] &redef;
const analyze_all_services = T &redef;
# Track address scaners only if at least these many hosts contacted.
const addr_scan_trigger = 0 &redef;
# Ignore address scanners for further scan detection after
# scanning this many hosts.
# 0 disables.
const ignore_scanners_threshold = 0 &redef;
# Report a scan of peers at each of these points.
const report_peer_scan: vector of count = {
20, 100, 1000, 10000, 50000, 100000, 250000, 500000, 1000000,
} &redef;
const report_outbound_peer_scan: vector of count = {
100, 1000, 10000,
} &redef;
# Report a scan of ports at each of these points.
const report_port_scan: vector of count = {
50, 250, 1000, 5000, 10000, 25000, 65000,
} &redef;
# Once a source has scanned this many different ports (to however many
# different remote hosts), start tracking its per-destination access.
const possible_port_scan_thresh = 20 &redef;
# Threshold for scanning privileged ports.
const priv_scan_trigger = 5 &redef;
const troll_skip_service = {
25/tcp, 21/tcp, 22/tcp, 20/tcp, 80/tcp,
} &redef;
const report_accounts_tried: vector of count = {
20, 100, 1000, 10000, 100000, 1000000,
} &redef;
const report_remote_accounts_tried: vector of count = {
100, 500,
} &redef;
# Report a successful password guessing if the source attempted
# at least this many.
const password_guessing_success_threshhold = 20 &redef;
const skip_accounts_tried: set[addr] &redef;
const addl_web = {
81/tcp, 443/tcp, 8000/tcp, 8001/tcp, 8080/tcp, }
&redef;
const skip_services = { 113/tcp, } &redef;
const skip_outbound_services = { 21/tcp, addl_web, }
&redef;
const skip_scan_sources = {
255.255.255.255, # who knows why we see these, but we do
} &redef;
const skip_scan_nets: set[subnet] = {} &redef;
# List of well known local server/ports to exclude for scanning
# purposes.
const skip_dest_server_ports: set[addr, port] = {} &redef;
# Reverse (SYN-ack) scans seen from these ports are considered
# to reflect possible SYN-flooding backscatter, and not true
# (stealth) scans.
const backscatter_ports = {
80/tcp, 8080/tcp, 53/tcp, 53/udp, 179/tcp, 6666/tcp, 6667/tcp,
} &redef;
const report_backscatter: vector of count = {
20,
} &redef;
global check_scan:
function(c: connection, established: bool, reverse: bool): bool;
# The following tables are defined here so that we can redef
# the expire timeouts.
# FIXME: should we allow redef of attributes on IDs which
# are not exported?
# How many different hosts connected to with a possible
# backscatter signature.
global distinct_backscatter_peers: table[addr] of table[addr] of count
&read_expire = 15 min;
# Expire functions that trigger summaries.
global scan_summary:
function(t: table[addr] of set[addr], orig: addr): interval;
global port_summary:
function(t: table[addr] of set[port], orig: addr): interval;
global lowport_summary:
function(t: table[addr] of set[port], orig: addr): interval;
# Indexed by scanner address, yields # distinct peers scanned.
# pre_distinct_peers tracks until addr_scan_trigger hosts first.
global pre_distinct_peers: table[addr] of set[addr]
&read_expire = 15 mins &redef;
global distinct_peers: table[addr] of set[addr]
&read_expire = 15 mins &expire_func=scan_summary &redef;
global distinct_ports: table[addr] of set[port]
&read_expire = 15 mins &expire_func=port_summary &redef;
global distinct_low_ports: table[addr] of set[port]
&read_expire = 15 mins &expire_func=lowport_summary &redef;
# Indexed by scanner address, yields a table with scanned hosts
# (and ports).
global scan_triples: table[addr] of table[addr] of set[port];
global remove_possible_source:
function(s: set[addr], idx: addr): interval;
global possible_scan_sources: set[addr]
&expire_func=remove_possible_source &read_expire = 15 mins;
# Indexed by source address, yields user name & password tried.
global accounts_tried: table[addr] of set[string, string]
&read_expire = 1 days;
global ignored_scanners: set[addr] &create_expire = 1 day &redef;
# These tables track whether a threshold has been reached.
# More precisely, the counter is the next index of threshold vector.
global shut_down_thresh_reached: table[addr] of bool &default=F;
global rb_idx: table[addr] of count
&default=1 &read_expire = 1 days &redef;
global rps_idx: table[addr] of count
&default=1 &read_expire = 1 days &redef;
global rops_idx: table[addr] of count
&default=1 &read_expire = 1 days &redef;
global rpts_idx: table[addr,addr] of count
&default=1 &read_expire = 1 days &redef;
global rat_idx: table[addr] of count
&default=1 &read_expire = 1 days &redef;
global rrat_idx: table[addr] of count
&default=1 &read_expire = 1 days &redef;
}
global thresh_check: function(v: vector of count, idx: table[addr] of count,
orig: addr, n: count): bool;
global thresh_check_2: function(v: vector of count,
idx: table[addr,addr] of count, orig: addr,
resp: addr, n: count): bool;
function scan_summary(t: table[addr] of set[addr], orig: addr): interval
{
local num_distinct_peers = orig in t ? |t[orig]| : 0;
if ( num_distinct_peers >= scan_summary_trigger )
NOTICE([$note=ScanSummary, $src=orig, $n=num_distinct_peers,
$identifier=fmt("%s", orig),
$msg=fmt("%s scanned a total of %d hosts",
orig, num_distinct_peers)]);
return 0 secs;
}
function port_summary(t: table[addr] of set[port], orig: addr): interval
{
local num_distinct_ports = orig in t ? |t[orig]| : 0;
if ( num_distinct_ports >= port_summary_trigger )
NOTICE([$note=PortScanSummary, $src=orig, $n=num_distinct_ports,
$identifier=fmt("%s", orig),
$msg=fmt("%s scanned a total of %d ports",
orig, num_distinct_ports)]);
return 0 secs;
}
function lowport_summary(t: table[addr] of set[port], orig: addr): interval
{
local num_distinct_lowports = orig in t ? |t[orig]| : 0;
if ( num_distinct_lowports >= lowport_summary_trigger )
NOTICE([$note=LowPortScanSummary, $src=orig,
$n=num_distinct_lowports,
$identifier=fmt("%s", orig),
$msg=fmt("%s scanned a total of %d low ports",
orig, num_distinct_lowports)]);
return 0 secs;
}
function clear_addr(a: addr)
{
delete distinct_peers[a];
delete distinct_ports[a];
delete distinct_low_ports[a];
delete scan_triples[a];
delete possible_scan_sources[a];
delete distinct_backscatter_peers[a];
delete pre_distinct_peers[a];
delete rb_idx[a];
delete rps_idx[a];
delete rops_idx[a];
delete rat_idx[a];
delete rrat_idx[a];
delete shut_down_thresh_reached[a];
delete ignored_scanners[a];
}
function ignore_addr(a: addr)
{
clear_addr(a);
add ignored_scanners[a];
}
function check_scan(c: connection, established: bool, reverse: bool): bool
{
local id = c$id;
local service = "ftp-data" in c$service ? 20/tcp
: (reverse ? id$orig_p : id$resp_p);
local rev_service = reverse ? id$resp_p : id$orig_p;
local orig = reverse ? id$resp_h : id$orig_h;
local resp = reverse ? id$orig_h : id$resp_h;
local outbound = Site::is_local_addr(orig);
# The following works better than using get_conn_transport_proto()
# because c might not correspond to an active connection (which
# causes the function to fail).
if ( suppress_UDP_scan_checks &&
service >= 0/udp && service <= 65535/udp )
return F;
if ( service in skip_services && ! outbound )
return F;
if ( outbound && service in skip_outbound_services )
return F;
if ( orig in skip_scan_sources )
return F;
if ( orig in skip_scan_nets )
return F;
# Don't include well known server/ports for scanning purposes.
if ( ! outbound && [resp, service] in skip_dest_server_ports )
return F;
if ( orig in ignored_scanners)
return F;
if ( ! established &&
# not established, service not expressly allowed
# not known peer set
(orig !in distinct_peers || resp !in distinct_peers[orig]) &&
# want to consider service for scan detection
(analyze_all_services || service in analyze_services) )
{
if ( reverse && rev_service in backscatter_ports &&
# reverse, non-priv backscatter port
service >= 1024/tcp )
{
if ( orig !in distinct_backscatter_peers )
{
local empty_bs_table:
table[addr] of count &default=0;
distinct_backscatter_peers[orig] =
empty_bs_table;
}
if ( ++distinct_backscatter_peers[orig][resp] <= 2 &&
# The test is <= 2 because we get two check_scan()
# calls, once on connection attempt and once on
# tear-down.
distinct_backscatter_peers[orig][resp] == 1 &&
# Looks like backscatter, and it's not scanning
# a privileged port.
thresh_check(report_backscatter, rb_idx, orig,
|distinct_backscatter_peers[orig]|)
)
{
NOTICE([$note=BackscatterSeen, $src=orig,
$p=rev_service,
$identifier=fmt("%s", orig),
$msg=fmt("backscatter seen from %s (%d hosts; %s)",
orig, |distinct_backscatter_peers[orig]|, rev_service)]);
}
if ( ignore_scanners_threshold > 0 &&
|distinct_backscatter_peers[orig]| >
ignore_scanners_threshold )
ignore_addr(orig);
}
else
{ # done with backscatter check
local ignore = F;
if ( orig !in distinct_peers && addr_scan_trigger > 0 )
{
if ( orig !in pre_distinct_peers )
pre_distinct_peers[orig] = set();
add pre_distinct_peers[orig][resp];
if ( |pre_distinct_peers[orig]| < addr_scan_trigger )
ignore = T;
}
if ( ! ignore )
{ # XXXXX
if ( orig !in distinct_peers )
distinct_peers[orig] = set() &mergeable;
if ( resp !in distinct_peers[orig] )
add distinct_peers[orig][resp];
local n = |distinct_peers[orig]|;
# Check for threshold if not outbound.
if ( ! shut_down_thresh_reached[orig] &&
n >= shut_down_thresh &&
! outbound && orig !in Site::neighbor_nets )
{
shut_down_thresh_reached[orig] = T;
local msg = fmt("shutdown threshold reached for %s", orig);
NOTICE([$note=ShutdownThresh, $src=orig,
$identifier=fmt("%s", orig),
$p=service, $msg=msg]);
}
else
{
local address_scan = F;
if ( outbound &&
# inside host scanning out?
thresh_check(report_outbound_peer_scan, rops_idx, orig, n) )
address_scan = T;
if ( ! outbound &&
thresh_check(report_peer_scan, rps_idx, orig, n) )
address_scan = T;
if ( address_scan )
NOTICE([$note=AddressScan,
$src=orig, $p=service,
$n=n,
$identifier=fmt("%s-%d", orig, n),
$msg=fmt("%s has scanned %d hosts (%s)",
orig, n, service)]);
if ( address_scan &&
ignore_scanners_threshold > 0 &&
n > ignore_scanners_threshold )
ignore_addr(orig);
}
}
} # XXXX
}
if ( established )
# Don't consider established connections for port scanning,
# it's too easy to be mislead by FTP-like applications that
# legitimately gobble their way through the port space.
return F;
# Coarse search for port-scanning candidates: those that have made
# connections (attempts) to possible_port_scan_thresh or more
# distinct ports.
if ( orig !in distinct_ports || service !in distinct_ports[orig] )
{
if ( orig !in distinct_ports )
distinct_ports[orig] = set() &mergeable;
if ( service !in distinct_ports[orig] )
add distinct_ports[orig][service];
if ( |distinct_ports[orig]| >= possible_port_scan_thresh &&
orig !in scan_triples )
{
scan_triples[orig] = table() &mergeable;
add possible_scan_sources[orig];
}
}
# Check for low ports.
if ( activate_priv_port_check && ! outbound && service < 1024/tcp &&
service !in troll_skip_service )
{
if ( orig !in distinct_low_ports ||
service !in distinct_low_ports[orig] )
{
if ( orig !in distinct_low_ports )
distinct_low_ports[orig] = set() &mergeable;
add distinct_low_ports[orig][service];
if ( |distinct_low_ports[orig]| == priv_scan_trigger &&
orig !in Site::neighbor_nets )
{
local svrc_msg = fmt("low port trolling %s %s", orig, service);
NOTICE([$note=LowPortTrolling, $src=orig,
$identifier=fmt("%s", orig),
$p=service, $msg=svrc_msg]);
}
if ( ignore_scanners_threshold > 0 &&
|distinct_low_ports[orig]| >
ignore_scanners_threshold )
ignore_addr(orig);
}
}
# For sources that have been identified as possible scan sources,
# keep track of per-host scanning.
if ( orig in possible_scan_sources )
{
if ( orig !in scan_triples )
scan_triples[orig] = table() &mergeable;
if ( resp !in scan_triples[orig] )
scan_triples[orig][resp] = set() &mergeable;
if ( service !in scan_triples[orig][resp] )
{
add scan_triples[orig][resp][service];
if ( thresh_check_2(report_port_scan, rpts_idx,
orig, resp,
|scan_triples[orig][resp]|) )
{
local m = |scan_triples[orig][resp]|;
NOTICE([$note=PortScan, $n=m, $src=orig,
$p=service,
$identifier=fmt("%s-%d", orig, n),
$msg=fmt("%s has scanned %d ports of %s",
orig, m, resp)]);
}
}
}
return T;
}
# Hook into the catch&release dropping. When an address gets restored, we reset
# the source to allow dropping it again.
event Drop::address_restored(a: addr)
{
clear_addr(a);
}
event Drop::address_cleared(a: addr)
{
clear_addr(a);
}
# When removing a possible scan source, we automatically delete its scanned
# hosts and ports. But we do not want the deletion propagated, because every
# peer calls the expire_function on its own (and thus applies the delete
# operation on its own table).
function remove_possible_source(s: set[addr], idx: addr): interval
{
suspend_state_updates();
delete scan_triples[idx];
resume_state_updates();
return 0 secs;
}
# To recognize whether a certain threshhold vector (e.g. report_peer_scans)
# has been transgressed, a global variable containing the next vector index
# (idx) must be incremented. This cumbersome mechanism is necessary because
# values naturally don't increment by one (e.g. replayed table merges).
function thresh_check(v: vector of count, idx: table[addr] of count,
orig: addr, n: count): bool
{
if ( ignore_scanners_threshold > 0 && n > ignore_scanners_threshold )
{
ignore_addr(orig);
return F;
}
if ( idx[orig] <= |v| && n >= v[idx[orig]] )
{
++idx[orig];
return T;
}
else
return F;
}
# Same as above, except the index has a different type signature.
function thresh_check_2(v: vector of count, idx: table[addr, addr] of count,
orig: addr, resp: addr, n: count): bool
{
if ( ignore_scanners_threshold > 0 && n > ignore_scanners_threshold )
{
ignore_addr(orig);
return F;
}
if ( idx[orig,resp] <= |v| && n >= v[idx[orig, resp]] )
{
++idx[orig,resp];
return T;
}
else
return F;
}
event connection_established(c: connection)
{
local is_reverse_scan = (c$orig$state == TCP_INACTIVE);
Scan::check_scan(c, T, is_reverse_scan);
}
event partial_connection(c: connection)
{
Scan::check_scan(c, T, F);
}
event connection_attempt(c: connection)
{
Scan::check_scan(c, F, c$orig$state == TCP_INACTIVE);
}
event connection_half_finished(c: connection)
{
# Half connections never were "established", so do scan-checking here.
Scan::check_scan(c, F, F);
}
event connection_rejected(c: connection)
{
local is_reverse_scan = c$orig$state == TCP_RESET;
Scan::check_scan(c, F, is_reverse_scan);
}
event connection_reset(c: connection)
{
if ( c$orig$state == TCP_INACTIVE || c$resp$state == TCP_INACTIVE )
# We never heard from one side - that looks like a scan.
Scan::check_scan(c, c$orig$size + c$resp$size > 0,
c$orig$state == TCP_INACTIVE);
}
event connection_pending(c: connection)
{
if ( c$orig$state == TCP_PARTIAL && c$resp$state == TCP_INACTIVE )
Scan::check_scan(c, F, F);
}
# Report the remaining entries in the tables.
event bro_done()
{
for ( orig in distinct_peers )
scan_summary(distinct_peers, orig);
for ( orig in distinct_ports )
port_summary(distinct_ports, orig);
for ( orig in distinct_low_ports )
lowport_summary(distinct_low_ports, orig);
}
</code></pre>

View File

@ -0,0 +1,22 @@
<h2>Strings</h2>
<pre><code>"foo \"bar\" baz"
'foo \'bar\' baz'
"Multi-line strings ending with a \
are supported too."</code></pre>
<h2>Macro statements</h2>
<pre><code># include &lt;stdio.h>
#define PG_locked 0
#define PG_error 1
</code></pre>
<h2>Full example</h2>
<pre><code>#include &lt;stdio.h>
main(int argc, char *argv[])
{
int c;
printf("Number of command line arguments passed: %d\n", argc);
for ( c = 0 ; c < argc ; c++)
printf("%d. Command line argument passed is %s\n", c+1, argv[c]);
return 0;
}</code></pre>

View File

@ -0,0 +1,28 @@
<p>The C-like component is not really a language on its own,
it is the basis of many other components. To use it directly, however,
use the class <code class="language-none">"language-clike"</code>.</p>
<h2>Comments</h2>
<pre><code>// Single line comment
/* Multi-line
comment */</code></pre>
<h2>Strings</h2>
<pre><code>"foo \"bar\" baz";
'foo \'bar\' baz';</code></pre>
<h2>Numbers</h2>
<pre><code>123
123.456
-123.456
1e-23
123.456E789
0xaf
0xAF
</code></pre>
<h2>Functions</h2>
<pre><code>foo();
Bar();
_456();
</code></pre>

View File

@ -0,0 +1,386 @@
<h2>Full example</h2>
<pre><code>
; This code is copied from https://learnxinyminutes.com/docs/clojure/
; Comments start with semicolons.
; Clojure is written in "forms", which are just
; lists of things inside parentheses, separated by whitespace.
;
; The clojure reader assumes that the first thing is a
; function or macro to call, and the rest are arguments.
; The first call in a file should be ns, to set the namespace
(ns learnclojure)
; More basic examples:
; str will create a string out of all its arguments
(str "Hello" " " "World") ; => "Hello World"
; Math is straightforward
(+ 1 1) ; => 2
(- 2 1) ; => 1
(* 1 2) ; => 2
(/ 2 1) ; => 2
; Equality is =
(= 1 1) ; => true
(= 2 1) ; => false
; You need not for logic, too
(not true) ; => false
; Nesting forms works as you expect
(+ 1 (- 3 2)) ; = 1 + (3 - 2) => 2
; Types
;;;;;;;;;;;;;
; Clojure uses Java's object types for booleans, strings and numbers.
; Use `class` to inspect them.
(class 1) ; Integer literals are java.lang.Long by default
(class 1.); Float literals are java.lang.Double
(class ""); Strings always double-quoted, and are java.lang.String
(class false) ; Booleans are java.lang.Boolean
(class nil); The "null" value is called nil
; If you want to create a literal list of data, use ' to stop it from
; being evaluated
'(+ 1 2) ; => (+ 1 2)
; (shorthand for (quote (+ 1 2)))
; You can eval a quoted list
(eval '(+ 1 2)) ; => 3
; Collections & Sequences
;;;;;;;;;;;;;;;;;;;
; Lists are linked-list data structures, while Vectors are array-backed.
; Vectors and Lists are java classes too!
(class [1 2 3]); => clojure.lang.PersistentVector
(class '(1 2 3)); => clojure.lang.PersistentList
; A list would be written as just (1 2 3), but we have to quote
; it to stop the reader thinking it's a function.
; Also, (list 1 2 3) is the same as '(1 2 3)
; "Collections" are just groups of data
; Both lists and vectors are collections:
(coll? '(1 2 3)) ; => true
(coll? [1 2 3]) ; => true
; "Sequences" (seqs) are abstract descriptions of lists of data.
; Only lists are seqs.
(seq? '(1 2 3)) ; => true
(seq? [1 2 3]) ; => false
; A seq need only provide an entry when it is accessed.
; So, seqs which can be lazy -- they can define infinite series:
(range 4) ; => (0 1 2 3)
(range) ; => (0 1 2 3 4 ...) (an infinite series)
(take 4 (range)) ; (0 1 2 3)
; Use cons to add an item to the beginning of a list or vector
(cons 4 [1 2 3]) ; => (4 1 2 3)
(cons 4 '(1 2 3)) ; => (4 1 2 3)
; Conj will add an item to a collection in the most efficient way.
; For lists, they insert at the beginning. For vectors, they insert at the end.
(conj [1 2 3] 4) ; => [1 2 3 4]
(conj '(1 2 3) 4) ; => (4 1 2 3)
; Use concat to add lists or vectors together
(concat [1 2] '(3 4)) ; => (1 2 3 4)
; Use filter, map to interact with collections
(map inc [1 2 3]) ; => (2 3 4)
(filter even? [1 2 3]) ; => (2)
; Use reduce to reduce them
(reduce + [1 2 3 4])
; = (+ (+ (+ 1 2) 3) 4)
; => 10
; Reduce can take an initial-value argument too
(reduce conj [] '(3 2 1))
; = (conj (conj (conj [] 3) 2) 1)
; => [3 2 1]
; Functions
;;;;;;;;;;;;;;;;;;;;;
; Use fn to create new functions. A function always returns
; its last statement.
(fn [] "Hello World") ; => fn
; (You need extra parens to call it)
((fn [] "Hello World")) ; => "Hello World"
; You can create a var using def
(def x 1)
x ; => 1
; Assign a function to a var
(def hello-world (fn [] "Hello World"))
(hello-world) ; => "Hello World"
; You can shorten this process by using defn
(defn hello-world [] "Hello World")
; The [] is the list of arguments for the function.
(defn hello [name]
(str "Hello " name))
(hello "Steve") ; => "Hello Steve"
; You can also use this shorthand to create functions:
(def hello2 #(str "Hello " %1))
(hello2 "Fanny") ; => "Hello Fanny"
; You can have multi-variadic functions, too
(defn hello3
([] "Hello World")
([name] (str "Hello " name)))
(hello3 "Jake") ; => "Hello Jake"
(hello3) ; => "Hello World"
; Functions can pack extra arguments up in a seq for you
(defn count-args [& args]
(str "You passed " (count args) " args: " args))
(count-args 1 2 3) ; => "You passed 3 args: (1 2 3)"
; You can mix regular and packed arguments
(defn hello-count [name & args]
(str "Hello " name ", you passed " (count args) " extra args"))
(hello-count "Finn" 1 2 3)
; => "Hello Finn, you passed 3 extra args"
; Maps
;;;;;;;;;;
; Hash maps and array maps share an interface. Hash maps have faster lookups
; but don't retain key order.
(class {:a 1 :b 2 :c 3}) ; => clojure.lang.PersistentArrayMap
(class (hash-map :a 1 :b 2 :c 3)) ; => clojure.lang.PersistentHashMap
; Arraymaps will automatically become hashmaps through most operations
; if they get big enough, so you don't need to worry.
; Maps can use any hashable type as a key, but usually keywords are best
; Keywords are like strings with some efficiency bonuses
(class :a) ; => clojure.lang.Keyword
(def stringmap {"a" 1, "b" 2, "c" 3})
stringmap ; => {"a" 1, "b" 2, "c" 3}
(def keymap {:a 1, :b 2, :c 3})
keymap ; => {:a 1, :c 3, :b 2}
; By the way, commas are always treated as whitespace and do nothing.
; Retrieve a value from a map by calling it as a function
(stringmap "a") ; => 1
(keymap :a) ; => 1
; Keywords can be used to retrieve their value from a map, too!
(:b keymap) ; => 2
; Don't try this with strings.
;("a" stringmap)
; => Exception: java.lang.String cannot be cast to clojure.lang.IFn
; Retrieving a non-present key returns nil
(stringmap "d") ; => nil
; Use assoc to add new keys to hash-maps
(def newkeymap (assoc keymap :d 4))
newkeymap ; => {:a 1, :b 2, :c 3, :d 4}
; But remember, clojure types are immutable!
keymap ; => {:a 1, :b 2, :c 3}
; Use dissoc to remove keys
(dissoc keymap :a :b) ; => {:c 3}
; Sets
;;;;;;
(class #{1 2 3}) ; => clojure.lang.PersistentHashSet
(set [1 2 3 1 2 3 3 2 1 3 2 1]) ; => #{1 2 3}
; Add a member with conj
(conj #{1 2 3} 4) ; => #{1 2 3 4}
; Remove one with disj
(disj #{1 2 3} 1) ; => #{2 3}
; Test for existence by using the set as a function:
(#{1 2 3} 1) ; => 1
(#{1 2 3} 4) ; => nil
; There are more functions in the clojure.sets namespace.
; Useful forms
;;;;;;;;;;;;;;;;;
; Logic constructs in clojure are just macros, and look like
; everything else
(if false "a" "b") ; => "b"
(if false "a") ; => nil
; Use let to create temporary bindings
(let [a 1 b 2]
(> a b)) ; => false
; Group statements together with do
(do
(print "Hello")
"World") ; => "World" (prints "Hello")
; Functions have an implicit do
(defn print-and-say-hello [name]
(print "Saying hello to " name)
(str "Hello " name))
(print-and-say-hello "Jeff") ;=> "Hello Jeff" (prints "Saying hello to Jeff")
; So does let
(let [name "Urkel"]
(print "Saying hello to " name)
(str "Hello " name)) ; => "Hello Urkel" (prints "Saying hello to Urkel")
; Use the threading macros (-> and ->>) to express transformations of
; data more clearly.
; The "Thread-first" macro (->) inserts into each form the result of
; the previous, as the first argument (second item)
(->
{:a 1 :b 2}
(assoc :c 3) ;=> (assoc {:a 1 :b 2} :c 3)
(dissoc :b)) ;=> (dissoc (assoc {:a 1 :b 2} :c 3) :b)
; This expression could be written as:
; (dissoc (assoc {:a 1 :b 2} :c 3) :b)
; and evaluates to {:a 1 :c 3}
; The double arrow does the same thing, but inserts the result of
; each line at the *end* of the form. This is useful for collection
; operations in particular:
(->>
(range 10)
(map inc) ;=> (map inc (range 10)
(filter odd?) ;=> (filter odd? (map inc (range 10))
(into [])) ;=> (into [] (filter odd? (map inc (range 10)))
; Result: [1 3 5 7 9]
; When you are in a situation where you want more freedom as where to
; put the result of previous data transformations in an
; expression, you can use the as-> macro. With it, you can assign a
; specific name to transformations' output and use it as a
; placeholder in your chained expressions:
(as-> [1 2 3] input
(map inc input);=> You can use last transform's output at the last position
(nth input 2) ;=> and at the second position, in the same expression
(conj [4 5 6] input [8 9 10])) ;=> or in the middle !
; Modules
;;;;;;;;;;;;;;;
; Use "use" to get all functions from the module
(use 'clojure.set)
; Now we can use set operations
(intersection #{1 2 3} #{2 3 4}) ; => #{2 3}
(difference #{1 2 3} #{2 3 4}) ; => #{1}
; You can choose a subset of functions to import, too
(use '[clojure.set :only [intersection]])
; Use require to import a module
(require 'clojure.string)
; Use / to call functions from a module
; Here, the module is clojure.string and the function is blank?
(clojure.string/blank? "") ; => true
; You can give a module a shorter name on import
(require '[clojure.string :as str])
(str/replace "This is a test." #"[a-o]" str/upper-case) ; => "THIs Is A tEst."
; (#"" denotes a regular expression literal)
; You can use require (and use, but don't) from a namespace using :require.
; You don't need to quote your modules if you do it this way.
(ns test
(:require
[clojure.string :as str]
[clojure.set :as set]))
; Java
;;;;;;;;;;;;;;;;;
; Java has a huge and useful standard library, so
; you'll want to learn how to get at it.
; Use import to load a java module
(import java.util.Date)
; You can import from an ns too.
(ns test
(:import java.util.Date
java.util.Calendar))
; Use the class name with a "." at the end to make a new instance
(Date.) ; <a date object>
; Use . to call methods. Or, use the ".method" shortcut
(. (Date.) getTime) ; <a timestamp>
(.getTime (Date.)) ; exactly the same thing.
; Use / to call static methods
(System/currentTimeMillis) ; <a timestamp> (system is always present)
; Use doto to make dealing with (mutable) classes more tolerable
(import java.util.Calendar)
(doto (Calendar/getInstance)
(.set 2000 1 1 0 0 0)
.getTime) ; => A Date. set to 2000-01-01 00:00:00
; STM
;;;;;;;;;;;;;;;;;
; Software Transactional Memory is the mechanism clojure uses to handle
; persistent state. There are a few constructs in clojure that use this.
; An atom is the simplest. Pass it an initial value
(def my-atom (atom {}))
; Update an atom with swap!.
; swap! takes a function and calls it with the current value of the atom
; as the first argument, and any trailing arguments as the second
(swap! my-atom assoc :a 1) ; Sets my-atom to the result of (assoc {} :a 1)
(swap! my-atom assoc :b 2) ; Sets my-atom to the result of (assoc {:a 1} :b 2)
; Use '@' to dereference the atom and get the value
my-atom ;=> Atom<#...> (Returns the Atom object)
@my-atom ; => {:a 1 :b 2}
; Here's a simple counter using an atom
(def counter (atom 0))
(defn inc-counter []
(swap! counter inc))
(inc-counter)
(inc-counter)
(inc-counter)
(inc-counter)
(inc-counter)
@counter ; => 5
; Other STM constructs are refs and agents.
; Refs: http://clojure.org/refs
; Agents: http://clojure.org/agents</code></pre>

View File

@ -0,0 +1,61 @@
<h2>Comments</h2>
<pre><code># This is a comment
### This is a
multi-line comment###</code></pre>
<h2>Strings</h2>
<pre><code>'foo \'bar\' baz'
"foo \"bar\" baz"
'Multi-line
strings are supported'
"Multi-line
strings are supported"
''' 'Block strings'
are supported too'''
""" "Block strings"
are supported too"""</code></pre>
<h2>String interpolation</h2>
<pre><code>"String #{interpolation} is supported"
'This works #{only} between double-quoted strings'</code></pre>
<h2>Object properties</h2>
<pre><code>kids =
brother:
name: "Max"
age: 11
sister:
name: "Ida"
age: 9</code></pre>
<h2>Regexps</h2>
<pre><code>/normal [r]egexp?/;
/// ^(
mul\t[i-l]ine
regexp # with embedded comment
) ///</code></pre>
<h2>Classes</h2>
<pre><code>class Animal
constructor: (@name) ->
move: (meters) ->
alert @name + " moved #{meters}m."
class Snake extends Animal
move: ->
alert "Slithering..."
super 5
class Horse extends Animal
move: ->
alert "Galloping..."
super 45
sam = new Snake "Sammy the Python"
tom = new Horse "Tommy the Palomino"
sam.move()
tom.move()</code></pre>
<h2>Inline JavaScript</h2>
<pre><code>`alert("foo")`</code></pre>

View File

@ -0,0 +1,61 @@
<h2>Strings</h2>
<pre><code>"foo \"bar\" baz"
'foo \'bar\' baz'
"Multi-line strings ending with a \
are supported too."</code></pre>
<h2>Macro statements</h2>
<pre><code># include &lt;stdio.h>
#define PG_locked 0
#define PG_error 1
</code></pre>
<h2>Booleans</h2>
<pre><code>true;
false;</code></pre>
<h2>Operators</h2>
<pre><code>a and b;
c bitand d;</code></pre>
<h2>Full example</h2>
<pre><code>/*
David Cary 2010-09-14
quick demo for wikibooks
public domain
*/
#include &lt;iostream>
#include &lt;vector>
using namespace std;
vector&lt;int> pick_vector_with_biggest_fifth_element(
vector&lt;int> left,
vector&lt;int> right
){
if( (left[5]) < (right[5]) ){
return( right );
};
// else
return( left );
}
int vector_demo(void){
cout << "vector demo" << endl;
vector&lt;int> left(7);
vector&lt;int> right(7);
left[5] = 7;
right[5] = 8;
cout << left[5] << endl;
cout << right[5] << endl;
vector&lt;int> biggest(
pick_vector_with_biggest_fifth_element( left, right )
);
cout << biggest[5] << endl;
return 0;
}
int main(void){
vector_demo();
}</code></pre>

View File

@ -0,0 +1,16 @@
<h2>Number literals with underscores and postfix</h2>
<pre><code>1_u32
123_456.789e-10_f64</code></pre>
<h2>Attributes</h2>
<pre><code>@[AlwaysInline]
def foo
1
end</code></pre>
<h2>Macro expansions</h2>
<pre><code>{% for key, value in {foo: 100, bar: 20} %}
def {{ key.id }}
{{ value }}
end
{% end %}</code></pre>

View File

@ -0,0 +1,60 @@
<h2>Comments</h2>
<pre><code>// Single line comment
/* Multi-line
comment */</code></pre>
<h2>Strings</h2>
<pre><code>"foo \"bar\" baz"
'foo \'bar\' baz'
@"Verbatim strings"
@"Luis: ""Patrick, where did you get that overnight bag?""
Patrick: ""Jean Paul Gaultier.""";
@'Luis: ''Patrick, where did you get that overnight bag?''
Patrick: ''Jean Paul Gaultier.''';
</code></pre>
<h2>Full example</h2>
<pre><code>using System.Windows.Forms;
using System.Drawing;
public static DialogResult InputBox(string title, string promptText, ref string value)
{
Form form = new Form();
Label label = new Label();
TextBox textBox = new TextBox();
Button buttonOk = new Button();
Button buttonCancel = new Button();
form.Text = title;
label.Text = promptText;
textBox.Text = value;
buttonOk.Text = "OK";
buttonCancel.Text = "Cancel";
buttonOk.DialogResult = DialogResult.OK;
buttonCancel.DialogResult = DialogResult.Cancel;
label.SetBounds(9, 20, 372, 13);
textBox.SetBounds(12, 36, 372, 20);
buttonOk.SetBounds(228, 72, 75, 23);
buttonCancel.SetBounds(309, 72, 75, 23);
label.AutoSize = true;
textBox.Anchor = textBox.Anchor | AnchorStyles.Right;
buttonOk.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
form.ClientSize = new Size(396, 107);
form.Controls.AddRange(new Control[] { label, textBox, buttonOk, buttonCancel });
form.ClientSize = new Size(Math.Max(300, label.Right + 10), form.ClientSize.Height);
form.FormBorderStyle = FormBorderStyle.FixedDialog;
form.StartPosition = FormStartPosition.CenterScreen;
form.MinimizeBox = false;
form.MaximizeBox = false;
form.AcceptButton = buttonOk;
form.CancelButton = buttonCancel;
DialogResult dialogResult = form.ShowDialog();
value = textBox.Text;
return dialogResult;
}</code></pre>

View File

@ -0,0 +1,13 @@
<h2>A complete policy</h2>
<pre><code>default-src 'none';
script-src my.cdn.com;
img-src 'self' data:;
child-src 'self' data: ms-appx-web:;
block-all-mixed-content;
report-uri https://my-reports.com/submit;
</code></pre>
<h2>An policy with unsafe source expressions</h2>
<pre><code>script-src 'self' 'unsafe-eval' 'unsafe-inline';
style-src 'unsafe-inline' 'unsafe-hashed-attributes' 'self';
</code></pre>

View File

@ -0,0 +1,34 @@
<h2>Empty rule</h2>
<pre><code>*{} * {} p {}</code></pre>
<pre><code>ul,
ol {}</code></pre>
<h2>Simple rule</h2>
<pre><code>p { color: red; }</code></pre>
<h2>Important rule</h2>
<pre><code>
p {
color: red !important;
line-height: normal!important;
}
p{position:absolute!important}
</code></pre>
<h2>@ rule</h2>
<pre><code>@media screen and (min-width: 100px) {}</code></pre>
<h2>LESS variable</h2>
<pre><code>@main-color: red;
.foo {
background: @main-color;
}</code></pre>
<h2>Comment</h2>
<pre><code>/* Simple comment here */</code></pre>
<h2>String</h2>
<pre><code>content: 'foo';</code></pre>
<h2>URL</h2>
<pre><code>content: url(foo.png);</code></pre>

View File

@ -0,0 +1,267 @@
<h2>Comments</h2>
<pre><code>// Single line comment
/* Multi-line
comment */
/+ Mutli-line
/+ nestable +/
comment +/</code></pre>
<h2>Numbers</h2>
<pre><code>0 .. 2_147_483_647
2_147_483_648 .. 9_223_372_036_854_775_807
0L .. 9_223_372_036_854_775_807L
0U .. 4_294_967_296U
4_294_967_296U .. 18_446_744_073_709_551_615U
0UL .. 18_446_744_073_709_551_615UL
0x0 .. 0x7FFF_FFFF
0x8000_0000 .. 0xFFFF_FFFF
0x1_0000_0000 .. 0x7FFF_FFFF_FFFF_FFFF
0x8000_0000_0000_0000 .. 0xFFFF_FFFF_FFFF_FFFF
0x0L .. 0x7FFF_FFFF_FFFF_FFFFL
0x8000_0000_0000_0000L .. 0xFFFF_FFFF_FFFF_FFFFL
0x0U .. 0xFFFF_FFFFU
0x1_0000_0000U .. 0xFFFF_FFFF_FFFF_FFFFU
0x0UL .. 0xFFFF_FFFF_FFFF_FFFFUL
123_456.567_8 // 123456.5678
1_2_3_4_5_6_.5_6_7_8 // 123456.5678
1_2_3_4_5_6_.5e-6_ // 123456.5e-6
0x1.FFFFFFFFFFFFFp1023 // double.max
0x1p-52 // double.epsilon
1.175494351e-38F // float.min
6.3i // idouble 6.3
6.3fi // ifloat 6.3
6.3Li // ireal 6.3
4.5 + 6.2i // complex number (phased out)</code></pre>
<h2>Strings</h2>
<pre><code>// WYSIWYG strings
r"hello"
r"c:\root\foo.exe"
r"ab\n"
`hello`
`c:\root\foo.exe`
`ab\n`
// Double-quoted strings
"hello"
"c:\\root\\foo.exe"
"ab\n"
"ab
"
// Hex strings
x"0A"
x"00 FBCD 32FD 0A"
// String postfix characters
"hello"c // string
"hello"w // wstring
"hello"d // dstring
// Delimited strings
q"(foo(xxx))"
q"[foo{]"
q"EOS
This
is a multi-line
heredoc string
EOS"
q"/foo]/"
// Token strings
q{foo}
q{/*}*/ }
q{ foo(q{hello}); }
q{ __TIME__ }
// Character literals
'a'
'\u000A'</code></pre>
<h2>Iasm registers</h2>
<pre><code>AL AH AX EAX
BL BH BX EBX
CL CH CX ECX
DL DH DX EDX
BP EBP
SP ESP
DI EDI
SI ESI
ES CS SS DS GS FS
CR0 CR2 CR3 CR4
DR0 DR1 DR2 DR3 DR6 DR7
TR3 TR4 TR5 TR6 TR7
ST
ST(0) ST(1) ST(2) ST(3) ST(4) ST(5) ST(6) ST(7)
MM0 MM1 MM2 MM3 MM4 MM5 MM6 MM7
XMM0 XMM1 XMM2 XMM3 XMM4 XMM5 XMM6 XMM7
RAX RBX RCX RDX
BPL RBP
SPL RSP
DIL RDI
SIL RSI
R8B R8W R8D R8
R9B R9W R9D R9
R10B R10W R10D R10
R11B R11W R11D R11
R12B R12W R12D R12
R13B R13W R13D R13
R14B R14W R14D R14
R15B R15W R15D R15
XMM8 XMM9 XMM10 XMM11 XMM12 XMM13 XMM14 XMM15
YMM0 YMM1 YMM2 YMM3 YMM4 YMM5 YMM6 YMM7
YMM8 YMM9 YMM10 YMM11 YMM12 YMM13 YMM14 YMM15</code></pre>
<h2>Full example</h2>
<pre><code>#!/usr/bin/dmd -run
/* sh style script syntax is supported! */
/* Hello World in D
To compile:
dmd hello.d
or to optimize:
dmd -O -inline -release hello.d
or to get generated documentation:
dmd hello.d -D
*/
import std.stdio; // References to commonly used I/O routines.
void main(char[][] args) // 'void' here means return 0 by default.
{
// Write-Formatted-Line
writefln("Hello World, " // automatic concatenation of string literals
"Reloaded");
// Strings are denoted as a dynamic array of chars 'char[]'
// auto type inference and built-in foreach
foreach(argc, argv; args)
{
// OOP is supported, of course! And automatic type inference.
auto cl = new CmdLin(argc, argv);
// 'writefln' is the improved 'printf' !!
// user-defined class properties.
writefln(cl.argnum, cl.suffix, " arg: %s", cl.argv);
// Garbage Collection or explicit memory management - your choice!!!
delete cl;
}
// Nested structs, classes and functions!
struct specs
{
// all vars. automatically initialized
int count, allocated;
}
// Note that declarations read right-to-left.
// So that 'char[][]' reads as an array of an array of chars.
specs argspecs(char[][] args)
// Optional (built-in) function contracts.
in{
assert (args.length > 0); // assert built in
}
out(result){
assert(result.count == CmdLin.total);
assert(result.allocated > 0);
}
body{
specs* s = new specs;
// no need for '->'
s.count = args.length; // The 'length' property is number of elements.
s.allocated = typeof(args).sizeof; // built-in properties for native types
foreach(argv; args)
s.allocated += argv.length * typeof(argv[0]).sizeof;
return *s;
}
// built-in string and common string operations, e.g. '~' is concatenate.
char[] argcmsg = "argc = %d";
char[] allocmsg = "allocated = %d";
writefln(argcmsg ~ ", " ~ allocmsg,
argspecs(args).count,argspecs(args).allocated);
}
/**
Stores a single command line argument.
*/
class CmdLin
{
private {
int _argc;
char[] _argv;
static uint _totalc;
}
public:
/************
Object constructor.
params:
argc = ordinal count of this argument.
argv = text of the parameter
*********/
this(int argc, char[] argv)
{
_argc = argc + 1;
_argv = argv;
_totalc++;
}
~this() /// Object destructor
{
// Doesn't actually do anything for this example.
}
int argnum() /// A property that returns arg number
{
return _argc;
}
char[] argv() /// A property that returns arg text
{
return _argv;
}
wchar[] suffix() /// A property that returns ordinal suffix
{
wchar[] suffix; // Built in Unicode strings (utf8,utf16, utf32)
switch(_argc)
{
case 1:
suffix = "st";
break;
case 2:
suffix = "nd";
break;
case 3:
suffix = "rd";
break;
default: // 'default' is mandatory with "-w" compile switch.
suffix = "th";
}
return suffix;
}
/* **************
* A property of the whole class, not just an instance.
* returns: The total number of commandline args added.
*************/
static typeof(_totalc) total()
{
return _totalc;
}
// Class invariant, things that must be true after any method is run.
invariant
{
assert(_argc > 0);
assert(_totalc >= _argc);
}
}</code></pre>
<h2>Known failures</h2>
<p>There are certain edge cases where Prism will fail.
There are always such cases in every regex-based syntax highlighter.
However, Prism dares to be open and honest about them.
If a failure is listed here, it doesnt mean it will never be fixed. This is more of a “known bugs” list, just with a certain type of bug.
</p>
<h3>Comments only support one level of nesting</h3>
<pre><code>/+ /+ /+ this does not work +/ +/ +/</code></pre>
<h3>Token strings only support one level of nesting</h3>
<pre><code>q{ q{ q{ this does not work } } }</code></pre>

View File

@ -0,0 +1,59 @@
<h2>Comments</h2>
<pre><code>// Single line comment
/// Documentation single line comment
/* Block comment
on several lines */
/** Multi-line
doc comment */</code></pre>
<h2>Annotations</h2>
<pre><code>@todo('seth', 'make this do something')
@deprecated // Metadata; makes Dart Editor warn about using activate().</code></pre>
<h2>Numbers</h2>
<pre><code>var x = 1;
var hex = 0xDEADBEEF;
var bigInt = 346534658346524376592384765923749587398457294759347029438709349347;
var y = 1.1;
var exponents = 1.42e5;
</code></pre>
<h2>Strings</h2>
<pre><code>var s1 = 'Single quotes work well for string literals.';
var s2 = "Double quotes work just as well.";
var s3 = 'It\'s easy to escape the string delimiter.';
var s4 = "It's even easier to just use the other string delimiter.";
var s1 = '''
You can create
multi-line strings like this one.
''';
var s2 = """This is also a
multi-line string.""";
var s = r"In a raw string, even \n isn't special.";</code></pre>
<h2>Full example</h2>
<pre><code>class Logger {
final String name;
bool mute = false;
// _cache is library-private, thanks to the _ in front of its name.
static final Map&lt;String, Logger> _cache = &lt;String, Logger>{};
factory Logger(String name) {
if (_cache.containsKey(name)) {
return _cache[name];
} else {
final logger = new Logger._internal(name);
_cache[name] = logger;
return logger;
}
}
Logger._internal(this.name);
void log(String msg) {
if (!mute) {
print(msg);
}
}
}</code></pre>

View File

@ -0,0 +1,33 @@
<h2>Normal Diff</h2>
<pre><code>7c7
&lt; qt: core
---
&gt; qt: core quick</code></pre>
<h2>Context Diff</h2>
<pre><code>*** qcli.yml 2014-12-16 11:43:41.000000000 +0800
--- /Users/uranusjr/Desktop/qcli.yml 2014-12-31 11:28:08.000000000 +0800
***************
*** 4,8 ****
project:
sources: "src/*.cpp"
headers: "src/*.h"
! qt: core
public_headers: "src/*.h"
--- 4,8 ----
project:
sources: "src/*.cpp"
headers: "src/*.h"
! qt: core gui
public_headers: "src/*.h"</code></pre>
<h2>Unified Diff</h2>
<pre><code>--- qcli.yml 2014-12-16 11:43:41.000000000 +0800
+++ /Users/uranusjr/Desktop/qcli.yml 2014-12-31 11:28:08.000000000 +0800
@@ -4,5 +4,5 @@
project:
sources: "src/*.cpp"
headers: "src/*.h"
- qt: core
+ qt: core gui
public_headers: "src/*.h"</code></pre>

View File

@ -0,0 +1,31 @@
<h2>Comment</h2>
<pre><code>{# This is a comment #}</code></pre>
<h2>Variable</h2>
<pre><code>{{ some_variable }}</code></pre>
<h2>Template Tag</h2>
<pre><code>{% if some_condition %}
Conditional block
{% endif %}
</code></pre>
<h2>Full Example</h2>
<pre><code>{# This a Django template example #}
{% extends "base_generic.html" %}
{% block title %}{{ section.title }}{% endblock %}
{% block content %}
&lt;h1&gt;{{ section.title }}&lt;/h1&gt;
{% for story in story_list %}
&lt;h2&gt;
&lt;a href="{{ story.get_absolute_url }}"&gt;
{{ story.headline|upper }}
&lt;/a&gt;
&lt;/h2&gt;
&lt;p&gt;{{ story.tease|truncatewords:"100" }}&lt;/p&gt;
{% endfor %}
{% endblock %}
</code></pre>

View File

@ -0,0 +1,49 @@
<h2>Comments</h2>
<pre><code># These are the comments for a dockerfile.
# I want to make sure $(variables) don't break out,
# and we shouldn't see keywords like ADD or ENTRYPOINT
</code></pre>
<h2>Full example</h2>
<pre><code># Nginx
#
# VERSION 0.0.1
FROM ubuntu
MAINTAINER Victor Vieux <victor@docker.com>
LABEL Description="This image is used to start the foobar executable" Vendor="ACME Products" Version="1.0"
RUN apt-get update && apt-get install -y inotify-tools nginx apache2 openssh-server
# Firefox over VNC
#
# VERSION 0.3
FROM ubuntu
# Install vnc, xvfb in order to create a 'fake' display and firefox
RUN apt-get update && apt-get install -y x11vnc xvfb firefox
RUN mkdir ~/.vnc
# Setup a password
RUN x11vnc -storepasswd 1234 ~/.vnc/passwd
# Autostart firefox (might not be the best way, but it does the trick)
RUN bash -c 'echo "firefox" >> /.bashrc'
EXPOSE 5900
CMD ["x11vnc", "-forever", "-usepw", "-create"]
# Multiple images example
#
# VERSION 0.1
FROM ubuntu
RUN echo foo > bar
# Will output something like ===> 907ad6c2736f
FROM ubuntu
RUN echo moo > oink
# Will output something like ===> 695d7793cbe4
# You᾿ll now have two images, 907ad6c2736f with /bar, and 695d7793cbe4 with
# /oink.
</code></pre>

View File

@ -0,0 +1,72 @@
<h2>Comments</h2>
<pre><code>-- A comment
</code></pre>
<h2>Simple string and character</h2>
<pre><code>"A simple string with %"double quotes%""
'a'
</code></pre>
<h2>Verbatim-strings</h2>
<pre><code>"[
A aligned verbatim string
]"
"{
A non-aligned verbatim string
}"
</code></pre>
<h2>Numbers</h2>
<pre><code>1_000
1_000.
1_000.e+1_000
1_000.1_000e-1_000
.1
0b1010_0001
0xAF_5B
0c75_22
</code></pre>
<h2>Class names</h2>
<pre><code>deferred class
A [G]
feature
items: G
deferred end
end
</code></pre>
<h2>Full example</h2>
<pre><code>note
description: "Represents a person."
class
PERSON
create
make, make_unknown
feature {NONE} -- Creation
make (a_name: like name)
-- Create a person with `a_name' as `name'.
do
name := a_name
ensure
name = a_name
end
make_unknown
do ensure
name = Void
end
feature -- Access
name: detachable STRING
-- Full name or Void if unknown.
end
</code></pre>

View File

@ -0,0 +1,462 @@
<h2>Comments</h2>
<pre><code># This is a comment</code></pre>
<h2>Atoms</h2>
<pre><code>:foo
:bar</code></pre>
<h2>Numbers</h2>
<pre><code>42
0b1010
0o777
0x1F
3.14159
5.2e10
100_000</code></pre>
<h2>Strings and heredoc</h2>
<pre><code>'A string with \'quotes\'!'
"A string with \"quotes\"!"
"Multi-line
strings are supported"
""" "Heredoc" strings are
also supported.
"""</code></pre>
<h2>Sigils</h2>
<pre><code>~s"""This is a sigil
using heredoc delimiters"""
~r/a [reg]exp/
~r(another|regexp)
~w[some words]s
~c&lt;a char list></code></pre>
<h2>Interpolation</h2>
<pre><code>"This is an #{:atom}"
~s/#{40+2} is the answer/</code></pre>
<h2>Function capturing</h2>
<pre><code>fun = &Math.zero?/1
(&is_function/1).(fun)
fun = &(&1 + 1)
fun.(1)
fun = &List.flatten(&1, &2)
fun.([1, [[2], 3]], [4, 5])</code></pre>
<h2>Module attributes</h2>
<pre><code>defmodule MyServer do
@vsn 2
end
defmodule Math do
@moduledoc """
Provides math-related functions.
iex> Math.sum(1, 2)
3
"""
@doc """
Calculates the sum of two numbers.
"""
def sum(a, b), do: a + b
end</code></pre>
<h2>Full example</h2>
<pre><code># Example from http://learnxinyminutes.com/docs/elixir/
# Single line comments start with a number symbol.
# There's no multi-line comment,
# but you can stack multiple comments.
# To use the elixir shell use the `iex` command.
# Compile your modules with the `elixirc` command.
# Both should be in your path if you installed elixir correctly.
## ---------------------------
## -- Basic types
## ---------------------------
# There are numbers
3 # integer
0x1F # integer
3.0 # float
# Atoms, that are literals, a constant with name. They start with `:`.
:hello # atom
# Tuples that are stored contiguously in memory.
{1,2,3} # tuple
# We can access a tuple element with the `elem` function:
elem({1, 2, 3}, 0) #=> 1
# Lists that are implemented as linked lists.
[1,2,3] # list
# We can access the head and tail of a list as follows:
[head | tail] = [1,2,3]
head #=> 1
tail #=> [2,3]
# In elixir, just like in Erlang, the `=` denotes pattern matching and
# not an assignment.
#
# This means that the left-hand side (pattern) is matched against a
# right-hand side.
#
# This is how the above example of accessing the head and tail of a list works.
# A pattern match will error when the sides don't match, in this example
# the tuples have different sizes.
# {a, b, c} = {1, 2} #=> ** (MatchError) no match of right hand side value: {1,2}
# There are also binaries
&lt;&lt;1,2,3>> # binary
# Strings and char lists
"hello" # string
'hello' # char list
# Multi-line strings
"""
I'm a multi-line
string.
"""
#=> "I'm a multi-line\nstring.\n"
# Strings are all encoded in UTF-8:
"héllò" #=> "héllò"
# Strings are really just binaries, and char lists are just lists.
&lt;&lt;?a, ?b, ?c>> #=> "abc"
[?a, ?b, ?c] #=> 'abc'
# `?a` in elixir returns the ASCII integer for the letter `a`
?a #=> 97
# To concatenate lists use `++`, for binaries use `&lt;>`
[1,2,3] ++ [4,5] #=> [1,2,3,4,5]
'hello ' ++ 'world' #=> 'hello world'
&lt;&lt;1,2,3>> &lt;> &lt;&lt;4,5>> #=> &lt;&lt;1,2,3,4,5>>
"hello " &lt;> "world" #=> "hello world"
# Ranges are represented as `start..end` (both inclusive)
1..10 #=> 1..10
lower..upper = 1..10 # Can use pattern matching on ranges as well
[lower, upper] #=> [1, 10]
## ---------------------------
## -- Operators
## ---------------------------
# Some math
1 + 1 #=> 2
10 - 5 #=> 5
5 * 2 #=> 10
10 / 2 #=> 5.0
# In elixir the operator `/` always returns a float.
# To do integer division use `div`
div(10, 2) #=> 5
# To get the division remainder use `rem`
rem(10, 3) #=> 1
# There are also boolean operators: `or`, `and` and `not`.
# These operators expect a boolean as their first argument.
true and true #=> true
false or true #=> true
# 1 and true #=> ** (ArgumentError) argument error
# Elixir also provides `||`, `&&` and `!` which accept arguments of any type.
# All values except `false` and `nil` will evaluate to true.
1 || true #=> 1
false && 1 #=> false
nil && 20 #=> nil
!true #=> false
# For comparisons we have: `==`, `!=`, `===`, `!==`, `&lt;=`, `>=`, `&lt;` and `>`
1 == 1 #=> true
1 != 1 #=> false
1 &lt; 2 #=> true
# `===` and `!==` are more strict when comparing integers and floats:
1 == 1.0 #=> true
1 === 1.0 #=> false
# We can also compare two different data types:
1 &lt; :hello #=> true
# The overall sorting order is defined below:
# number &lt; atom &lt; reference &lt; functions &lt; port &lt; pid &lt; tuple &lt; list &lt; bit string
# To quote Joe Armstrong on this: "The actual order is not important,
# but that a total ordering is well defined is important."
## ---------------------------
## -- Control Flow
## ---------------------------
# `if` expression
if false do
"This will never be seen"
else
"This will"
end
# There's also `unless`
unless true do
"This will never be seen"
else
"This will"
end
# Remember pattern matching? Many control-flow structures in elixir rely on it.
# `case` allows us to compare a value against many patterns:
case {:one, :two} do
{:four, :five} ->
"This won't match"
{:one, x} ->
"This will match and bind `x` to `:two`"
_ ->
"This will match any value"
end
# It's common to bind the value to `_` if we don't need it.
# For example, if only the head of a list matters to us:
[head | _] = [1,2,3]
head #=> 1
# For better readability we can do the following:
[head | _tail] = [:a, :b, :c]
head #=> :a
# `cond` lets us check for many conditions at the same time.
# Use `cond` instead of nesting many `if` expressions.
cond do
1 + 1 == 3 ->
"I will never be seen"
2 * 5 == 12 ->
"Me neither"
1 + 2 == 3 ->
"But I will"
end
# It is common to set the last condition equal to `true`, which will always match.
cond do
1 + 1 == 3 ->
"I will never be seen"
2 * 5 == 12 ->
"Me neither"
true ->
"But I will (this is essentially an else)"
end
# `try/catch` is used to catch values that are thrown, it also supports an
# `after` clause that is invoked whether or not a value is caught.
try do
throw(:hello)
catch
message -> "Got #{message}."
after
IO.puts("I'm the after clause.")
end
#=> I'm the after clause
# "Got :hello"
## ---------------------------
## -- Modules and Functions
## ---------------------------
# Anonymous functions (notice the dot)
square = fn(x) -> x * x end
square.(5) #=> 25
# They also accept many clauses and guards.
# Guards let you fine tune pattern matching,
# they are indicated by the `when` keyword:
f = fn
x, y when x > 0 -> x + y
x, y -> x * y
end
f.(1, 3) #=> 4
f.(-1, 3) #=> -3
# Elixir also provides many built-in functions.
# These are available in the current scope.
is_number(10) #=> true
is_list("hello") #=> false
elem({1,2,3}, 0) #=> 1
# You can group several functions into a module. Inside a module use `def`
# to define your functions.
defmodule Math do
def sum(a, b) do
a + b
end
def square(x) do
x * x
end
end
Math.sum(1, 2) #=> 3
Math.square(3) #=> 9
# To compile our simple Math module save it as `math.ex` and use `elixirc`
# in your terminal: elixirc math.ex
# Inside a module we can define functions with `def` and private functions with `defp`.
# A function defined with `def` is available to be invoked from other modules,
# a private function can only be invoked locally.
defmodule PrivateMath do
def sum(a, b) do
do_sum(a, b)
end
defp do_sum(a, b) do
a + b
end
end
PrivateMath.sum(1, 2) #=> 3
# PrivateMath.do_sum(1, 2) #=> ** (UndefinedFunctionError)
# Function declarations also support guards and multiple clauses:
defmodule Geometry do
def area({:rectangle, w, h}) do
w * h
end
def area({:circle, r}) when is_number(r) do
3.14 * r * r
end
end
Geometry.area({:rectangle, 2, 3}) #=> 6
Geometry.area({:circle, 3}) #=> 28.25999999999999801048
# Geometry.area({:circle, "not_a_number"})
#=> ** (FunctionClauseError) no function clause matching in Geometry.area/1
# Due to immutability, recursion is a big part of elixir
defmodule Recursion do
def sum_list([head | tail], acc) do
sum_list(tail, acc + head)
end
def sum_list([], acc) do
acc
end
end
Recursion.sum_list([1,2,3], 0) #=> 6
# Elixir modules support attributes, there are built-in attributes and you
# may also add custom ones.
defmodule MyMod do
@moduledoc """
This is a built-in attribute on a example module.
"""
@my_data 100 # This is a custom attribute.
IO.inspect(@my_data) #=> 100
end
## ---------------------------
## -- Structs and Exceptions
## ---------------------------
# Structs are extensions on top of maps that bring default values,
# compile-time guarantees and polymorphism into Elixir.
defmodule Person do
defstruct name: nil, age: 0, height: 0
end
joe_info = %Person{ name: "Joe", age: 30, height: 180 }
#=> %Person{age: 30, height: 180, name: "Joe"}
# Access the value of name
joe_info.name #=> "Joe"
# Update the value of age
older_joe_info = %{ joe_info | age: 31 }
#=> %Person{age: 31, height: 180, name: "Joe"}
# The `try` block with the `rescue` keyword is used to handle exceptions
try do
raise "some error"
rescue
RuntimeError -> "rescued a runtime error"
_error -> "this will rescue any error"
end
# All exceptions have a message
try do
raise "some error"
rescue
x in [RuntimeError] ->
x.message
end
## ---------------------------
## -- Concurrency
## ---------------------------
# Elixir relies on the actor model for concurrency. All we need to write
# concurrent programs in elixir are three primitives: spawning processes,
# sending messages and receiving messages.
# To start a new process we use the `spawn` function, which takes a function
# as argument.
f = fn -> 2 * 2 end #=> #Function&lt;erl_eval.20.80484245>
spawn(f) #=> #PID&lt;0.40.0>
# `spawn` returns a pid (process identifier), you can use this pid to send
# messages to the process. To do message passing we use the `send` operator.
# For all of this to be useful we need to be able to receive messages. This is
# achieved with the `receive` mechanism:
defmodule Geometry do
def area_loop do
receive do
{:rectangle, w, h} ->
IO.puts("Area = #{w * h}")
area_loop()
{:circle, r} ->
IO.puts("Area = #{3.14 * r * r}")
area_loop()
end
end
end
# Compile the module and create a process that evaluates `area_loop` in the shell
pid = spawn(fn -> Geometry.area_loop() end) #=> #PID&lt;0.40.0>
# Send a message to `pid` that will match a pattern in the receive statement
send pid, {:rectangle, 2, 3}
#=> Area = 6
# {:rectangle,2,3}
send pid, {:circle, 2}
#=> Area = 12.56000000000000049738
# {:circle,2}
# The shell is also a process, you can use `self` to get the current pid
self() #=> #PID&lt;0.27.0></code></pre>
<h2>Known failures</h2>
<p>There are certain edge cases where Prism will fail.
There are always such cases in every regex-based syntax highlighter.
However, Prism dares to be open and honest about them.
If a failure is listed here, it doesnt mean it will never be fixed. This is more of a “known bugs” list, just with a certain type of bug.
</p>
<h3>String interpolation in single-quoted strings</h3>
<pre><code>'#{:atom} &lt;- this should not be highligted'</code></pre>

View File

@ -0,0 +1,91 @@
<h2>Comments</h2>
<pre><code>-- Single line comment
{- Multi-line
comment -}</code></pre>
<h2>Strings and characters</h2>
<pre><code>'a'
'\n'
'\x03'
"foo \" bar"
"""
"multiline strings" are also
supported!
"""</code></pre>
<h2>Full example</h2>
<pre><code>module Main exposing (..)
import Html exposing (Html)
import Svg exposing (..)
import Svg.Attributes exposing (..)
import Time exposing (Time, second)
main =
Html.program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
-- MODEL
type alias Model =
Time
init : ( Model, Cmd Msg )
init =
( 0, Cmd.none )
-- UPDATE
type Msg
= Tick Time
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Tick newTime ->
( newTime, Cmd.none )
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Time.every second (\time -> Tick time)
-- VIEW
view : Model -> Html Msg
view model =
let
angle =
turns (Time.inMinutes model)
handX =
toString (50 + 40 * cos angle)
handY =
toString (50 + 40 * sin angle)
in
svg [ viewBox "0 0 100 100", width "300px" ]
[ circle [ cx "50", cy "50", r "45", fill "#0B79CE" ] []
, line [ x1 "50", y1 "50", x2 handX, y2 handY, stroke "#023963" ] []
]
</code></pre>

View File

@ -0,0 +1,22 @@
<h2>Full example</h2>
<pre><code>&lt;%# index.erb %>
&lt;h1>Listing Books&lt;/h1>
&lt;table>
&lt;tr>
&lt;th>Title&lt;/th>
&lt;th>Summary&lt;/th>
&lt;th>&lt;/th>
&lt;th>&lt;/th>
&lt;th>&lt;/th>
&lt;/tr>
&lt;% @books.each do |book| %>
&lt;tr>
&lt;td>&lt;%= book.title %>&lt;/td>
&lt;td>&lt;%= book.content %>&lt;/td>
&lt;td>&lt;%= link_to "Show", book %>&lt;/td>
&lt;td>&lt;%= link_to "Edit", edit_book_path(book) %>&lt;/td>
&lt;td>&lt;%= link_to "Remove", book, method: :delete, data: { confirm: "Are you sure?" } %>&lt;/td>
&lt;/tr>
&lt;% end %>
&lt;/table></code></pre>

View File

@ -0,0 +1,47 @@
<h2>Comments</h2>
<pre><code>% This is a comment
%% coding: utf-8</code></pre>
<h2>Strings</h2>
<pre><code>"foo \"bar\" baz"</code></pre>
<h2>Numbers</h2>
<pre><code>42.
$A.
$\n.
2#101.
16#1f.
2.3.
2.3e3.
2.3e-3.</code></pre>
<h2>Functions</h2>
<pre><code>P = spawn(m, loop, []).
io:format("I am ~p~n", [self()]).
'weird function'().
</code></pre>
<h2>Variables</h2>
<pre><code>P = {adam,24,{july,29}}.
M1 = #{name=>adam,age=>24,date=>{july,29}}.
M2 = maps:update(age,25,M1).
io:format("{~p,~p}: ~p~n", [?MODULE,?LINE,X]).</code></pre>
<h2>Operators</h2>
<pre><code>1==1.0.
1=:=1.0.
1 > a.
+1.
-1.
1+1.
4/2.
5 div 2.
5 rem 2.
2#10 band 2#01.
2#10 bor 2#01.
a + 10.
1 bsl (1 bsl 64).
not true.
true and false.
true xor false.
true or garbage.</code></pre>

View File

@ -0,0 +1,18 @@
<h2>Primitive types</h2>
<pre><code>function method(x: number, y: string, z: boolean) {}
function stringifyBasicValue(value: string | number) {}
function add(one: any, two: any): number {
return one + two;
}
const bar: number = 2;
var barVar: number = 2;
let barLet: number = 2;
let isOneOf: number | boolean | string = foo;</code></pre>
<h2>Keywords</h2>
<pre><code>type UnionAlias = 1 | 2 | 3;
opaque type ID = string;
declare opaque type PositiveNumber: number;
type Country = $Keys&lt;typeof countries>;
type RequiredProps = $Diff&lt;Props, DefaultProps>;</code></pre>

View File

@ -0,0 +1,71 @@
<h2>Comments</h2>
<pre><code>! This is a comment</code></pre>
<h2>Strings</h2>
<pre><code>"foo 'bar' baz"
'foo ''bar'' baz'
''
ITALICS_'This is in italics'
"test &
! Some "tricky comment" here
&test"</code></pre>
<h2>Numbers</h2>
<pre><code>473
+56
-101
21_2
21_SHORT
1976354279568241_8
B'01110'
B"010"
O'047'
O"642"
Z'F41A'
Z"00BC"
-12.78
+1.6E3
2.1
-16.E4_8
0.45E-4
10.93E7_QUAD
.123
3E4</code></pre>
<h2>Full example</h2>
<pre><code>MODULE MOD1
TYPE INITIALIZED_TYPE
INTEGER :: I = 1 ! Default initialization
END TYPE INITIALIZED_TYPE
SAVE :: SAVED1, SAVED2
INTEGER :: SAVED1, UNSAVED1
TYPE(INITIALIZED_TYPE) :: SAVED2, UNSAVED2
ALLOCATABLE :: SAVED1(:), SAVED2(:), UNSAVED1(:), UNSAVED2(:)
END MODULE MOD1
PROGRAM MAIN
CALL SUB1 ! The values returned by the ALLOCATED intrinsic calls
! in the PRINT statement are:
! .FALSE., .FALSE., .FALSE., and .FALSE.
! Module MOD1 is used, and its variables are allocated.
! After return from the subroutine, whether the variables
! which were not specified with the SAVE attribute
! retain their allocation status is processor dependent.
CALL SUB1 ! The values returned by the first two ALLOCATED intrinsic
! calls in the PRINT statement are:
! .TRUE., .TRUE.
! The values returned by the second two ALLOCATED
! intrinsic calls in the PRINT statement are
! processor dependent and each could be either
! .TRUE. or .FALSE.
CONTAINS
SUBROUTINE SUB1
USE MOD1 ! Brings in saved and not saved variables.
PRINT *, ALLOCATED(SAVED1), ALLOCATED(SAVED2), &
ALLOCATED(UNSAVED1), ALLOCATED(UNSAVED2)
IF (.NOT. ALLOCATED(SAVED1)) ALLOCATE(SAVED1(10))
IF (.NOT. ALLOCATED(SAVED2)) ALLOCATE(SAVED2(10))
IF (.NOT. ALLOCATED(UNSAVED1)) ALLOCATE(UNSAVED1(10))
IF (.NOT. ALLOCATED(UNSAVED2)) ALLOCATE(UNSAVED2(10))
END SUBROUTINE SUB1
END PROGRAM MAIN</code></pre>

View File

@ -0,0 +1,89 @@
<h2>Comments</h2>
<pre><code>// Single line comment
(* Multi-line
comment *)</code></pre>
<h2>Strings</h2>
<pre><code>"foo \"bar\" baz"
'foo \'bar\' baz'
@"Verbatim strings"
"""Alternate "verbatim" strings"""
</code></pre>
<h2>Numbers</h2>
<pre><code>//8 bit Int
86y
0b00000101y
//Unsigned 8 bit Int
86uy
0b00000101uy
//16 bit Int
86s
//Unsigned 16 bit Int
86us
//Int
86
86l
0b10000
0x2A6
//Unsigned Int
86u
86ul
//unativeint
0x00002D3Fun
//Long
86L
//Unsigned Long
86UL
//Float
4.14F
4.14f
4.f
4.F
0x0000000000000000lf
//Double
4.14
2.3E+32
2.3e+32
2.3e-32
2.3e32
0x0000000000000000LF
//BigInt
9999999999999999999999999999I
//Decimal
0.7833M
0.7833m
3.m
3.M
</code></pre>
<h2>Full example</h2>
<pre><code>// The declaration creates a constructor that takes two values, name and age.
type Person(name:string, age:int) =
// A Person object's age can be changed. The mutable keyword in the
// declaration makes that possible.
let mutable internalAge = age
// Declare a second constructor that takes only one argument, a name.
// This constructor calls the constructor that requires two arguments,
// sending 0 as the value for age.
new(name:string) = Person(name, 0)
// A read-only property.
member this.Name = name
// A read/write property.
member this.Age
with get() = internalAge
and set(value) = internalAge &lt;- value
// Instance methods.
// Increment the person's age.
member this.HasABirthday () = internalAge &lt;- internalAge + 1
// Check current age against some threshold.
member this.IsOfAge targetAge = internalAge &gt;= targetAge
// Display the person's name and age.
override this.ToString () =
"Name: " + name + "\n" + "Age: " + (string)internalAge
</code></pre>

View File

@ -0,0 +1,22 @@
<h2>Comments</h2>
<pre><code>; comment
(some more comments)
G28 (even in here) X0
</code></pre>
<h2>Quoted strings</h2>
<pre><code>"foo""bar"</code></pre>
<h2>Full example</h2>
<pre><code>M190 S60 ; Heat bed to 60°C
G21 ; Set units to millimeters
G28 ; Move to Origin (Homing)
G29 ; Auto Bed Leveling
G28 X0 Y0 ; Home X and Y to min endstops
M107 ; Fan off
M109 S200 ; Heat hotend to 200°C
G92 E0 ; Set current extruder position as zero
G1 F200 E15 ; Extrude 15mm filament with 200mm/min
G92 E0 ; Set current extruder position as zero
G1 F500
</code></pre>

View File

@ -0,0 +1,50 @@
<h2>Full example</h2>
<pre><code>0 HEAD
1 CHAR ASCII
1 SOUR ID_OF_CREATING_FILE
1 GEDC
2 VERS 5.5
2 FORM Lineage-Linked
1 SUBM @SUBMITTER@
0 @SUBMITTER@ SUBM
1 NAME /Submitter/
1 ADDR Submitters address
2 CONT address continued here
0 @FATHER@ INDI
1 NAME /Father/
1 SEX M
1 BIRT
2 PLAC birth place
2 DATE 1 JAN 1899
1 DEAT
2 PLAC death place
2 DATE 31 DEC 1990
1 FAMS @FAMILY@
0 @MOTHER@ INDI
1 NAME /Mother/
1 SEX F
1 BIRT
2 PLAC birth place
2 DATE 1 JAN 1899
1 DEAT
2 PLAC death place
2 DATE 31 DEC 1990
1 FAMS @FAMILY@
0 @CHILD@ INDI
1 NAME /Child/
1 BIRT
2 PLAC birth place
2 DATE 31 JUL 1950
1 DEAT
2 PLAC death place
2 DATE 29 FEB 2000
1 FAMC @FAMILY@
0 @FAMILY@ FAM
1 MARR
2 PLAC marriage place
2 DATE 1 APR 1950
1 HUSB @FATHER@
1 WIFE @MOTHER@
1 CHIL @CHILD@
0 TRLR
</code></pre>

View File

@ -0,0 +1,74 @@
<h2>Strings</h2>
<pre><code>"foo \"bar\" baz"
'foo \'bar\' baz'
"""
Some Title, Eh?
===============
Here is the first paragraph of my blog post.
Lorem ipsum dolor sit amet, consectetur adipiscing
elit.
"""
</code></pre>
<h2>Keywords</h2>
<pre><code>Feature: Some terse yet descriptive text of what is desired
In order to realize a named business value
As an explicit system actor
I want to gain some beneficial outcome which furthers the goal
Additional text...
Scenario: Some determinable business situation
Given some precondition
And some other precondition
When some action by the actor
And some other action
And yet another action
Then some testable outcome is achieved
And something else we can check happens too
Scenario: A different situation
...</code></pre>
<h2>Comments and tags</h2>
<pre><code># user.feature
@users
Feature: Sign in to the store
In order to view my orders list
As a visitor
I need to be able to log in to the store
@javascript @login
Scenario: Trying to login without credentials
Given I am on the store homepage
And I follow "Login"
When I press "Login"
Then I should be on login page
# And I should see "Invalid credentials"
</code></pre>
<h2>Tables and parameters</h2>
<pre><code>Scenario Outline: Eating
Given there are &lt;start&gt; cucumbers
When I eat &lt;eat&gt; cucumbers
Then I should have &lt;left&gt; cucumbers
Examples:
| start | eat | left |
| 12 | 5 | 7 |
| 20 | 5 | 15 |</code></pre>
<h2>Localized keywords</h2>
<pre><code>#language: fr
Fonctionnalité: Contrôle le format de la valeur saisie d'un champ d'une révision
En tant qu'expert ou analyste
Je ne dois pas pouvoir soumettre des données au mauvais format
Contexte:
Etant donné que je suis connecté avec le pseudo "p_flore" et le mot de passe "p4flore"
Et que la gamme du contrat 27156 supporte les révisions
Etant donné que le contrat ayant l'id "27156" a une révision
Et je suis sur "/contrat/27156/revision/1"
Et que j'attends quelques secondes
...</code></pre>

View File

@ -0,0 +1,39 @@
<h2>Comments</h2>
<pre><code># On branch prism-examples
# Changes to be committed:
# (use "git reset HEAD &lt;file>..." to unstage)
#
# new file: examples/prism-git.html</code></pre>
<h2>Inserted and deleted lines</h2>
<pre><code>- Some deleted line
+ Some added line</code></pre>
<h2>Diff</h2>
<pre><code>$ git diff
diff --git file.txt file.txt
index 6214953..1d54a52 100644
--- file.txt
+++ file.txt
@@ -1 +1,2 @@
-Here's my tetx file
+Here's my text file
+And this is the second line</code></pre>
<h2>Logs</h2>
<pre><code>$ git log
commit a11a14ef7e26f2ca62d4b35eac455ce636d0dc09
Author: lgiraudel
Date: Mon Feb 17 11:18:34 2014 +0100
Add of a new line
commit 87edc4ad8c71b95f6e46f736eb98b742859abd95
Author: lgiraudel
Date: Mon Feb 17 11:18:15 2014 +0100
Typo fix
commit 3102416a90c431400d2e2a14e707fb7fd6d9e06d
Author: lgiraudel
Date: Mon Feb 17 10:58:11 2014 +0100</code></pre>

View File

@ -0,0 +1,65 @@
<h2>Vertex shader example</h2>
<pre><code>attribute vec3 vertex;
attribute vec3 normal;
uniform mat4 _mvProj;
uniform mat3 _norm;
varying vec3 vColor;
varying vec3 localPos;
#pragma include "light.glsl"
// constants
vec3 materialColor = vec3(1.0,0.7,0.8);
vec3 specularColor = vec3(1.0,1.0,1.0);
void main(void) {
// compute position
gl_Position = _mvProj * vec4(vertex, 1.0);
localPos = vertex;
// compute light info
vec3 n = normalize(_norm * normal);
vec3 diffuse;
float specular;
float glowingSpecular = 50.0;
getDirectionalLight(n, _dLight, glowingSpecular, diffuse, specular);
vColor = max(diffuse,_ambient.xyz)*materialColor+specular*specularColor+_ambient;
}</code></pre>
<h2>Fragment shader example</h2>
<pre><code>#ifdef GL_ES
precision highp float;
#endif
uniform vec3 BrickColor, MortarColor;
uniform vec3 BrickSize;
uniform vec3 BrickPct;
varying vec3 vColor;
varying vec3 localPos;
void main()
{
vec3 color;
vec3 position, useBrick;
position = localPos / BrickSize.xyz;
if (fract(position.y * 0.5) > 0.5){
position.x += 0.5;
position.z += 0.5;
}
position = fract(position);
useBrick = step(position, BrickPct.xyz);
color = mix(MortarColor, BrickColor, useBrick.x * useBrick.y * useBrick.z);
color *= vColor;
gl_FragColor = vec4(color, 1.0);
}
</code></pre>

View File

@ -0,0 +1,29 @@
<h2>Comments</h2>
<pre><code>// This is a comment
/* This is a comment
on multiple lines */</code></pre>
<h2>Functions</h2>
<pre><code>variable_instance_set(_inst,_var_name,_start+_change);</code></pre>
<h2>Full example</h2>
<pre><code>if(instance_exists(_inst) || _inst==global){
if(_delay<=0){
_time+=1;
if(_time&lt;_duration){
event_user(0);
}else{
if(_inst!=global){
variable_instance_set(_inst,_var_name,_start+_change);
}else{
variable_global_set(_var_name,_start+_change);
}
instance_destroy();
}
}else{
_delay-=1;
}
}else{
instance_destroy();
}
</code></pre>

View File

@ -0,0 +1,68 @@
<h2>Comments</h2>
<pre><code>// This is a comment
/* This is a comment
on multiple lines */</code></pre>
<h2>Numbers</h2>
<pre><code>42
0600
0xBadFace
170141183460469231731687303715884105727
0.
72.40
072.40
2.71828
1.e+0
6.67428e-11
1E6
.25
.12345E+5
0i
011i
0.i
2.71828i
1.e+0i
6.67428e-11i
1E6i
.25i
.12345E+5i</code></pre>
<h2>Runes and strings</h2>
<pre><code>'\t'
'\000'
'\x07'
'\u12e4'
'\U00101234'
`abc`
`multi-line
string`
"Hello, world!"
"multi-line
string"</code></pre>
<h2>Functions</h2>
<pre><code>func(a, b int, z float64) bool { return a*b < int(z) }</code></pre>
<h2>Full example</h2>
<pre><code>package main
import "fmt"
func sum(a []int, c chan int) {
sum := 0
for _, v := range a {
sum += v
}
c <- sum // send sum to c
}
func main() {
a := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(a[:len(a)/2], c)
go sum(a[len(a)/2:], c)
x, y := <-c, <-c // receive from c
fmt.Println(x, y, x+y)
}
</code></pre>

View File

@ -0,0 +1,31 @@
<h2>Comments</h2>
<pre><code># This is a comment</code></pre>
<h2>Strings</h2>
<pre><code>""
"foo \"bar\" baz"</code></pre>
<h2>Numbers</h2>
<pre><code>0
42
3.14159
-9e-5
0.9E+7</code></pre>
<h2>Keywords</h2>
<pre><code>query withFragments {
user(id: 4) {
friends(first: 10) {
...friendFields
}
mutualFriends(first: 10) {
...friendFields
}
}
}
fragment friendFields on User {
id
name
profilePic(size: 50)
}</code></pre>

View File

@ -0,0 +1,93 @@
<h2>Comments</h2>
<pre><code>// Single line comment
/* Multi-line
comment */</code></pre>
<h2>Strings</h2>
<pre><code>"foo 'bar' baz"
'foo "bar" baz'
"""Multi-line
string"""
'''Multi-line
string'''
"String /containing/ slashes"
</code></pre>
<h2>Slashy strings (regex)</h2>
<pre><code>/.*foo.*/
/regex"containing quotes"/
$/.*"(.*)".*/(.*)/$</code></pre>
<h2>Interpolation inside GStrings and regex</h2>
<pre><code>"The answer is ${21*2}"
"The $foxtype ${foxcolor.join()} fox"
/foo${21*2}baz/
'No interpolation here : ${21*2}'</code></pre>
<h2>Full example</h2>
<pre><code>#!/usr/bin/env groovy
package model
import groovy.transform.CompileStatic
import java.util.List as MyList
trait Distributable {
void distribute(String version) {}
}
@CompileStatic
class Distribution implements Distributable {
double number = 1234.234 / 567
def otherNumber = 3 / 4
boolean archivable = condition ?: true
def ternary = a ? b : c
String name = "Guillaume"
Closure description = null
List&lt;DownloadPackage> packages = []
String regex = ~/.*foo.*/
String multi = '''
multi line string
''' + """
now with double quotes and ${gstring}
""" + $/
even with dollar slashy strings
/$
/**
* description method
* @param cl the closure
*/
void description(Closure cl) { this.description = cl }
void version(String name, Closure versionSpec) {
def closure = { println "hi" } as Runnable
MyList ml = [1, 2, [a: 1, b:2,c :3]]
for (ch in "name") {}
// single line comment
DownloadPackage pkg = new DownloadPackage(version: name)
check that: true
label:
def clone = versionSpec.rehydrate(pkg, pkg, pkg)
/*
now clone() in a multiline comment
*/
clone()
packages.add(pkg)
assert 4 / 2 == 2
}
}</code></pre>
<h2>Known failures</h2>
<p>There are certain edge cases where Prism will fail.
There are always such cases in every regex-based syntax highlighter.
However, Prism dares to be open and honest about them.
If a failure is listed here, it doesnt mean it will never be fixed. This is more of a “known bugs” list, just with a certain type of bug.
</p>
<h3>Two divisions on the same line</h3>
<pre><code>2 / 3 / 4</code></pre>

View File

@ -0,0 +1,79 @@
<h2>Comments</h2>
<pre><code>
/ This is comment
on multiple lines
/ This is a comment
but this is not
-# This is another comment
on multiple lines</code></pre>
<h2>Doctype</h2>
<pre><code>!!! XML
!!!
!!! 5</code></pre>
<h2>Tags</h2>
<pre><code>%div
%span
%span(class="widget_#{@widget.number}")
%div{:id => [@item.type, @item.number], :class => [@item.type, @item.urgency]}
%html{:xmlns => "http://www.w3.org/1999/xhtml", "xml:lang" => "en", :lang => "en"}
%html{html_attrs('fr-fr')}
%div[@user, :greeting]
%img
%pre><
foo
bar
%img
</code></pre>
<h2>Markup</h2>
<pre><code>%div
&lt;p id="blah">Blah!&lt;/p></code></pre>
<h2>Inline Ruby</h2>
<pre><code>= ['hi', 'there', 'reader!'].join " "
- foo = "hello"
= link_to_remote "Add to cart",
:url => { :action => "add", :id => product.id },
:update => { :success => "cart", :failure => "error" }
~ "Foo\n&lt;pre>Bar\nBaz&lt;/pre>"
%p
- case 2
- when 1
= "1!"
- when 2
= "2?"
- when 3
= "3."
- (42...47).each do |i|
%p= i
%p See, I can count!
</code></pre>
<h2>Filters</h2>
<pre><code>%head
:css
#content: {
background: url('img/background.jpg');
}
div {
color: #333;
}
:javascript
(function() {
var test = "Do you like Prism?";
if(confirm(test)) {
do_something_great();
}
}());
%body
</code></pre>
<p>Filters require the desired language to be loaded.
On this page, check CoffeeScript <strong>before</strong> checking Haml should make
the example below work properly.</p>
<pre><code>%script
:coffee
console.log 'This is coffee script'</code></pre>

View File

@ -0,0 +1,41 @@
<h2>Comments</h2>
<pre><code>{{! This is a comment with &lt;p>some markup&lt;/p> in it }}
{{! This is a comment }} {{ this_is_not }}</code></pre>
<h2>Variables</h2>
<pre><code>&lt;p>{{ text }}&lt;/p>
&lt;h1>{{article.title}}&lt;/h1>
{{{ triple_stash_is_supported }}}
{{articles.[10].[#comments]}}</code></pre>
<h2>Strings, numbers and booleans</h2>
<pre><code>{{{link "See more..." story.url}}}
{{ true }}
{{ custom_helper 42 href="somepage.html" false }}</code></pre>
<h2>Block helpers</h2>
<pre><code>&lt;div class="body">
{{#bold}}{{body}}{{/bold}}
&lt;/div>
{{#with story}}
&lt;div class="intro">{{{intro}}}&lt;/div>
&lt;div class="body">{{{body}}}&lt;/div>
{{/with}}
&lt;div class="{{#if test}}foo{{else}}bar{{/if}}">&lt;/div>
{{#list array}}
{{@index}}. {{title}}
{{/list}}
{{#block-with-hyphens args=yep}}
This should probably work...
{{/block-with-hyphens}}
</code></pre>
<h2>Known failures</h2>
<p>There are certain edge cases where Prism will fail.
There are always such cases in every regex-based syntax highlighter.
However, Prism dares to be open and honest about them.
If a failure is listed here, it doesnt mean it will never be fixed. This is more of a “known bugs” list, just with a certain type of bug.
</p>
<h3>Handlebars tag in the middle of an HTML tag</h3>
<pre><code>&lt;div{{#if test}} class="test"{{/if}}>&lt;/div></code></pre>

View File

@ -0,0 +1,80 @@
<h2>Comments</h2>
<pre><code>-- Single line comment
{- Multi-line
comment -}</code></pre>
<h2>Strings and characters</h2>
<pre><code>'a'
'\n'
'\^A'
'\^]'
'\NUL'
'\23'
'\o75'
'\xFE'
"Here is a backslant \\ as well as \137, \
\a numeric escape character, and \^X, a control character."</code></pre>
<h2>Numbers</h2>
<pre><code>42
123.456
123.456e-789
1e+3
0o74
0XAF</code></pre>
<h2>Full example</h2>
<pre><code>hGetLine h =
wantReadableHandle_ "Data.ByteString.hGetLine" h $
\ h_@Handle__{haByteBuffer} -> do
flushCharReadBuffer h_
buf <- readIORef haByteBuffer
if isEmptyBuffer buf
then fill h_ buf 0 []
else haveBuf h_ buf 0 []
where
fill h_@Handle__{haByteBuffer,haDevice} buf len xss =
len `seq` do
(r,buf') <- Buffered.fillReadBuffer haDevice buf
if r == 0
then do writeIORef haByteBuffer buf{ bufR=0, bufL=0 }
if len > 0
then mkBigPS len xss
else ioe_EOF
else haveBuf h_ buf' len xss
haveBuf h_@Handle__{haByteBuffer}
buf@Buffer{ bufRaw=raw, bufR=w, bufL=r }
len xss =
do
off <- findEOL r w raw
let new_len = len + off - r
xs <- mkPS raw r off
-- if eol == True, then off is the offset of the '\n'
-- otherwise off == w and the buffer is now empty.
if off /= w
then do if (w == off + 1)
then writeIORef haByteBuffer buf{ bufL=0, bufR=0 }
else writeIORef haByteBuffer buf{ bufL = off + 1 }
mkBigPS new_len (xs:xss)
else do
fill h_ buf{ bufL=0, bufR=0 } new_len (xs:xss)
-- find the end-of-line character, if there is one
findEOL r w raw
| r == w = return w
| otherwise = do
c <- readWord8Buf raw r
if c == fromIntegral (ord '\n')
then return r -- NB. not r+1: don't include the '\n'
else findEOL (r+1) w raw
mkPS :: RawBuffer Word8 -> Int -> Int -> IO ByteString
mkPS buf start end =
create len $ \p ->
withRawBuffer buf $ \pbuf -> do
copyBytes p (pbuf `plusPtr` start) len
where
len = end - start</code></pre>

View File

@ -0,0 +1,37 @@
<h2>Strings and string interpolation</h2>
<pre><code>"Foo
bar $baz"
'Foo
bar'
"${4 + 2}"</code></pre>
<h2>Regular expressions</h2>
<pre><code>~/haxe/i
~/[A-Z0-9._%-]+@[A-Z0-9.-]+.[A-Z][A-Z][A-Z]?/i
~/(dog|fox)/g</code></pre>
<h2>Conditional compilation</h2>
<pre><code>#if !debug
trace("ok");
#elseif (debug_level > 3)
trace(3);
#else
trace("debug level too low");
#end</code></pre>
<h2>Metadata</h2>
<pre><code>@author("Nicolas")
@debug
class MyClass {
@range(1, 8)
var value:Int;
@broken
@:noCompletion
static function method() { }
}</code></pre>
<h2>Reification</h2>
<pre><code>macro static function add(e:Expr) {
return macro $e + $e;
}</code></pre>

View File

@ -0,0 +1,11 @@
<h2>Pin for one year with report-uri</h2>
<pre><code>pin-sha256="EpOpN/ahUF6jhWShDUdy+NvvtaGcu5F7qM6+x2mfkh4=";
max-age=31536000;
includeSubDomains;
report-uri="https://my-reports.com/submit"
</code></pre>
<h2>Pin for a short time (considered unsafe)</h2>
<pre><code>pin-sha256="EpOpN/ahUF6jhWShDUdy+NvvtaGcu5F7qM6+x2mfkh4=";
max-age=123
</code></pre>

View File

@ -0,0 +1,8 @@
<h2>Policy with far-future max-age</h2>
<pre><code>max-age=31536000</code></pre>
<h2>Policy with near-future max-age, considered unsafe</h2>
<pre><code>max-age=123</code></pre>
<h2>Policy with extra directives</h2>
<pre><code>max-age=31536000; includeSubdomains; preload</code></pre>

View File

@ -0,0 +1,33 @@
<h2>Request header</h2>
<pre><code>GET http://localhost:9999/foo.html HTTP/1.1
Accept-Language: fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate</code></pre>
<h2>Response header</h2>
<pre><code>HTTP/1.1 200 OK
Server: GitHub.com
Date: Mon, 22 Dec 2014 18:25:30 GMT
Content-Type: text/html; charset=utf-8</code></pre>
<h2>Response body highlighted based on Content-Type</h2>
<p>This currently supports the following content types :
"application/json",
"application/xml",
"text/xml" and
"text/html".</p>
<pre><code>HTTP/1.1 200 OK
Server: GitHub.com
Date: Mon, 22 Dec 2014 18:25:30 GMT
Content-Type: text/html; charset=utf-8
Last-Modified: Sun, 21 Dec 2014 20:29:48 GMT
Transfer-Encoding: chunked
Expires: Mon, 22 Dec 2014 18:35:30 GMT
Cache-Control: max-age=600
Vary: Accept-Encoding
Content-Encoding: gzip
&lt;!DOCTYPE html>
&lt;html lang="en">
&lt;head>&lt;/head>
&lt;body>&lt;/body>
&lt;/html></code></pre>

View File

@ -0,0 +1,29 @@
<p>Note: this component focuses on IchigoJam, which uses a small subset of basic and introduces its own markers.</p>
<h2>Comments</h2>
<pre><code>' This is a comment
REM This is a remark
'NoSpaceIsOK
REMNOSPACE</code></pre>
<h2>Strings</h2>
<pre><code>"This a string."
"This is a string with ""quotes"" in it."</code></pre>
<h2>Numbers</h2>
<pre><code>42
3.14159
-42
-3.14159
.5
10.
2E10
4.2E-14
-3E+2
#496F726953756B69
`11100010</code></pre>
<h2>IchigoJam Basic example</h2>
<pre><code>A=0
FOR I=1 TO 100 : A=A+I : NEXT
PRINT A</code></pre>

View File

@ -0,0 +1,172 @@
<h2>Comments</h2>
<pre><code>#
# Foobar</code></pre>
<h2>Strings and csets</h2>
<pre><code>""
"Foo\"bar"
''
'a\'bcdefg'</code></pre>
<h2>Numbers</h2>
<pre><code>42
3.14159
5.2E+8
16rface
2r1101</code></pre>
<h2>Full example</h2>
<pre><code># Author: Robert J. Alexander
global GameObject, Tree, Learn
record Question(question, yes, no)
procedure main()
GameObject := "animal"
Tree := Question("Does it live in water", "goldfish", "canary")
Get() # Recall prior knowledge
Game() # Play a game
return
end
# Game() -- Conducts a game.
#
procedure Game()
while Confirm("Are you thinking of ", Article(GameObject), " ",
GameObject) do Ask(Tree)
write("Thanks for a great game.")
if \Learn &Confirm("Want to save knowledge learned this session")
then Save()
return
end
# Confirm() -- Handles yes/no questions and answers.
#
procedure Confirm(q[])
local answer, s
static ok
initial {
ok := table()
every ok["y" | "yes" | "yeah" | "uh huh"] := "yes"
every ok["n" | "no" | "nope" | "uh uh" ] := "no"
}
while /answer do {
every writes(!q)
write("?")
case s := read() | exit(1) of {
# Commands recognized at a yes/no prompt.
#
"save": Save()
"get": Get()
"list": List()
"dump": Output(Tree)
default: {
(answer := \ok[map(s, &ucase, &lcase)]) |
write("This is a \"yes\" or \"no\" question.")
}
}
}
return answer == "yes"
end
# Ask() -- Navigates through the barrage of questions leading to a
# guess.
#
procedure Ask(node)
local guess, question
case type(node) of {
"string": {
if not Confirm("It must be ", Article(node), " ", node, ", right") then {
Learn := "yes"
write("What were you thinking of?")
guess := read() | exit(1)
write("What question would distinguish ", Article(guess), " ",
guess, " from ", Article(node), " ", node, "?")
question := read() | exit(1)
if question[-1] == "?" then question[-1] := ""
question[1] := map(question[1], &lcase, &ucase)
if Confirm("For ", Article(guess), " ", guess, ", what would the answer be")
then return Question(question, guess, node)
else return Question(question, node, guess)
}
}
"Question": {
if Confirm(node.question) then node.yes := Ask(node.yes)
else node.no := Ask(node.no)
}
}
end
# Article() -- Come up with the appropriate indefinite article.
#
procedure Article(word)
return if any('aeiouAEIOU', word) then "an" else "a"
end
# Save() -- Store our acquired knowledge in a disk file name
# based on the GameObject.
#
procedure Save()
local f
f := open(GameObject || "s", "w")
Output(Tree, f)
close(f)
return
end
# Output() -- Recursive procedure used to output the knowledge tree.
#
procedure Output(node, f, sense)
static indent
initial indent := 0
/f := &output
/sense := " "
case type(node) of {
"string": write(f, repl(" ", indent), sense, "A: ", node)
"Question": {
write(f, repl(" ", indent), sense, "Q: ", node.question)
indent +:= 1
Output(node.yes, f, "y")
Output(node.no, f, "n")
indent -:= 1
}
}
return
end
# Get() -- Read in a knowledge base from a file.
#
procedure Get()
local f
f := open(GameObject || "s", "r") | fail
Tree := Input(f)
close(f)
return
end
# Input() -- Recursive procedure used to input the knowledge tree.
#
procedure Input(f)
local nodetype, s
read(f) ? (tab(upto(~' \t')) & =("y" | "n" | "") &
nodetype := move(1) & move(2) & s := tab(0))
return if nodetype == "Q" then Question(s, Input(f), Input(f)) else s
end
# List() -- Lists the objects in the knowledge base.
#
$define Length 78
procedure List()
local lst, line, item
lst := Show(Tree, [ ])
line := ""
every item := !sort(lst) do {
if *line + *item > Length then {
write(trim(line))
line := ""
}
line ||:= item || ", "
}
write(line[1:-2])
return
end
#
# Show() -- Recursive procedure used to navigate the knowledge tree.
#
procedure Show(node, lst)
if type(node) == "Question" then {
lst := Show(node.yes, lst)
lst := Show(node.no, lst)
}
else put(lst, node)
return lst
end</code></pre>

View File

@ -0,0 +1,171 @@
<h2>Comments</h2>
<pre><code>[This is a comment]
[This is a
multi-line comment]</code></pre>
<h2>Texts</h2>
<pre><code>"This is a string"
"This is a
multi-line string"</code></pre>
<h2>Numbers</h2>
<pre><code>42
3.14159
50kg
100m
one
three
twelve</code></pre>
<h2>Titles</h2>
<pre><code>Section 2 - Flamsteed's Balloon
Part SR1 - The Physical World Model
Table of Floors</code></pre>
<h2>Standard kinds, verbs and keywords</h2>
<pre><code>In the Treehouse is a container called the cardboard box.
The cardboard box is a closed container. The glass bottle is a transparent open container. The box is fixed in place and openable.
Check photographing:
if the noun is the camera, say "Sadly impossible." instead.</code></pre>
<h2>Text substitution</h2>
<pre><code>"[if the player is in Center Ring]A magician's booth stands in the corner, painted dark blue with glittering gold stars.[otherwise if the magician's booth is closed]A crack of light indicates the way back out to the center ring.[otherwise]The door stands open to the outside.[end if]".</code></pre>
<h2>Full example</h2>
<pre><code>"Lakeside Living"
A volume is a kind of value. 15.9 fl oz specifies a volume with parts ounces and tenths (optional, preamble optional).
A fluid container is a kind of container. A fluid container has a volume called a fluid capacity. A fluid container has a volume called current volume.
The fluid capacity of a fluid container is usually 12.0 fl oz. The current volume of a fluid container is usually 0.0 fl oz.
Liquid is a kind of value. The liquids are water, absinthe, and iced tea. A fluid container has a liquid.
Instead of examining a fluid container:
if the noun is empty,
say "You catch just a hint of [the liquid of the noun] at the bottom.";
otherwise
say "[The noun] contains [current volume of the noun in rough terms] of [liquid of the noun]."
To say (amount - a volume) in rough terms:
if the amount is less than 0.5 fl oz:
say "a swallow or two";
otherwise if tenths part of amount is greater than 3 and tenths part of amount is less than 7:
let estimate be ounces part of amount;
say "[estimate in words] or [estimate plus 1 in words] fluid ounces";
otherwise:
if tenths part of amount is greater than 6, increase amount by 1.0 fl oz;
say "about [ounces part of amount in words] fluid ounce[s]".
Before printing the name of a fluid container (called the target) while not drinking or pouring:
if the target is empty:
say "empty ";
otherwise:
do nothing.
After printing the name of a fluid container (called the target) while not examining or pouring:
unless the target is empty:
say " of [liquid of the target]";
omit contents in listing.
Instead of inserting something into a fluid container:
say "[The second noun] has too narrow a mouth to accept anything but liquids."
Definition: a fluid container is empty if the current volume of it is 0.0 fl oz. Definition: a fluid container is full if the current volume of it is the fluid capacity of it.
Understand "drink from [fluid container]" as drinking.
Instead of drinking a fluid container:
if the noun is empty:
say "There is no more [liquid of the noun] within." instead;
otherwise:
decrease the current volume of the noun by 0.2 fl oz;
if the current volume of the noun is less than 0.0 fl oz, now the current volume of the noun is 0.0 fl oz;
say "You take a sip of [the liquid of the noun][if the noun is empty], leaving [the noun] empty[end if]."
Part 2 - Filling
Understand the command "fill" as something new.
Understand "fill [fluid container] with/from [full liquid source]" as filling it with. Understand "fill [fluid container] with/from [fluid container]" as filling it with.
Understand "fill [something] with/from [something]" as filling it with.
Filling it with is an action applying to two things. Carry out filling it with: try pouring the second noun into the noun instead.
Understand "pour [fluid container] in/into/on/onto [fluid container]" as pouring it into. Understand "empty [fluid container] into [fluid container]" as pouring it into.
Understand "pour [something] in/into/on/onto [something]" as pouring it into. Understand "empty [something] into [something]" as pouring it into.
Pouring it into is an action applying to two things.
Check pouring it into:
if the noun is not a fluid container, say "You can't pour [the noun]." instead;
if the second noun is not a fluid container, say "You can't pour liquids into [the second noun]." instead;
if the noun is the second noun, say "You can hardly pour [the noun] into itself." instead;
if the liquid of the noun is not the liquid of the second noun:
if the second noun is empty, now the liquid of the second noun is the liquid of the noun;
otherwise say "Mixing [the liquid of the noun] with [the liquid of the second noun] would give unsavory results." instead;
if the noun is empty, say "No more [liquid of the noun] remains in [the noun]." instead;
if the second noun is full, say "[The second noun] cannot contain any more than it already holds." instead.
Carry out pouring it into:
let available capacity be the fluid capacity of the second noun minus the current volume of the second noun;
if the available capacity is greater than the current volume of the noun, now the available capacity is the current volume of the noun;
increase the current volume of the second noun by available capacity;
decrease the current volume of the noun by available capacity.
Report pouring it into:
say "[if the noun is empty][The noun] is now empty;[otherwise][The noun] now contains [current volume of the noun in rough terms] of [liquid of the noun]; [end if]";
say "[the second noun] contains [current volume of the second noun in rough terms] of [liquid of the second noun][if the second noun is full], and is now full[end if]."
Understand the liquid property as describing a fluid container. Understand "of" as a fluid container.
A liquid source is a kind of fluid container. A liquid source has a liquid. A liquid source is usually scenery. The fluid capacity of a liquid source is usually 3276.7 fl oz. The current volume of a liquid source is usually 3276.7 fl oz. Instead of examining a liquid source: say "[The noun] is full of [liquid of the noun]."
Carry out pouring a liquid source into something: now the current volume of the noun is 3276.7 fl oz.
After pouring a liquid source into a fluid container:
say "You fill [the second noun] up with [liquid of the noun] from [the noun]."
Instead of pouring a fluid container into a liquid source:
if the noun is empty, say "[The noun] is already empty." instead;
now the current volume of the noun is 0.0 fl oz;
say "You dump out [the noun] into [the second noun]."
Swimming is an action applying to nothing. Understand "swim" or "dive" as swimming.
Instead of swimming in the presence of a liquid source:
say "You don't feel like a dip just now."
Before inserting something into a liquid source: say "[The noun] would get lost and never be seen again." instead.
Part 3 - Scenario
The Lakeside is a room. The Lakeside swing is an enterable supporter in the Lakeside. "Here you are by the lake, enjoying a summery view."
The glass is a fluid container carried by the player. The liquid of the glass is absinthe. The current volume of the glass is 0.8 fl oz.
The pitcher is a fluid container in the Lakeside. The fluid capacity of the pitcher is 32.0 fl oz. The current volume of the pitcher is 20.0 fl oz. The liquid of the pitcher is absinthe.
The lake is a liquid source. It is in the Lakeside.
The player wears a bathing outfit. The description of the bathing outfit is "Stylishly striped in blue and white, and daringly cut to reveal almost all of your calves, and quite a bit of upper arm, as well. You had a moral struggle, purchasing it; but mercifully the lakeshore is sufficiently secluded that no one can see you in this immodest apparel."
Instead of taking off the outfit: say "What odd ideas come into your head sometimes!"
Test me with "fill glass / empty absinthe into lake / fill glass / swim / drink lake / drink / x water / x lake". </code></pre>
<h2>Known failures</h2>
<p>There are certain edge cases where Prism will fail.
There are always such cases in every regex-based syntax highlighter.
However, Prism dares to be open and honest about them.
If a failure is listed here, it doesnt mean it will never be fixed. This is more of a “known bugs” list, just with a certain type of bug.
</p>
<h3>Names starting with a number</h3>
<pre><code>The box 1A is a container</code></pre>

View File

@ -0,0 +1,10 @@
<h2>Comments</h2>
<pre><code>; This is a comment</code></pre>
<h2>Section title</h2>
<pre><code>[owner]
[database]</code></pre>
<h2>Properties</h2>
<pre><code>name=prism
file="somefile.txt"</code></pre>

View File

@ -0,0 +1,31 @@
<h2>Comments</h2>
<pre><code>//
// Foobar
#!/usr/bin/env io
/* multiline
comment
*/</code></pre>
<h2>Strings</h2>
<pre><code>"this is a \"test\".\nThis is only a test."
"""this is a "test".
This is only a test."""</code></pre>
<h2>Numbers</h2>
<pre><code>123
123.456
0.456
123e-4
123e4
123.456e-7
123.456e2
</code></pre>
<h2>Full example</h2>
<pre><code>"Hello, world!" println
A := Object clone // creates a new, empty object named "A"
factorial := method(n,
if(n == 0, return 1)
res := 1
Range 1 to(n) foreach(i, res = res * i)
)</code></pre>

View File

@ -0,0 +1,59 @@
<h2>Comments</h2>
<pre><code>NB. This is a comment</code></pre>
<h2>Strings</h2>
<pre><code>'This is a string.'
'This is a string with ''quotes'' in it.'</code></pre>
<h2>Numbers</h2>
<pre><code>2.3e2 2.3e_2 2j3
2p1 1p_1
1x2 2x1 1x_1
2e2j_2e2 2e2j2p1 2ad45 2ar0.785398
16b1f 10b23 _10b23 1e2b23 2b111.111</code></pre>
<h2>Verbs</h2>
<pre><code>%4
3%4
,b
'I';'was';'here'
3 5$'wake read lamp '</code></pre>
<h2>Adverbs</h2>
<pre><code>1 2 3 */ 4 5 6 7
'%*'(1 3;2 _1)} y</code></pre>
<h2>Conjunctions</h2>
<pre><code>10&^. 2 3 10 100 200
+`*
+:@*: +/ -:@%:</code></pre>
<h2>Examples</h2>
<pre><code>NB. The following functions E1, E2 and E3
NB. interchange two rows of a matrix,
NB. multiply a row by a constant,
NB. and add a multiple of one row to another:
E1=: <@] C. [
E2=: f`g`[}
E3=: F`g`[}
f=: {:@] * {.@] { [
F=: [: +/ (1:,{:@]) * (}:@] { [)
g=: {.@]
M=: i. 4 5
M;(M E1 1 3);(M E2 1 10);(M E3 1 3 10)</code></pre>
<pre><code>NB. Implementation of quicksort
sel=: adverb def 'u # ['
quicksort=: verb define
if. 1 >: #y do. y
else.
(quicksort y &lt;sel e),(y =sel e),quicksort y >sel e=.y{~?#y
end.
)</code></pre>
<pre><code>NB. Implementation of quicksort (tacit programming)
quicksort=: (($:@(&lt;#[), (=#[), $:@(>#[)) ({~ ?@#)) ^: (1&lt;#)</code></pre>

View File

@ -0,0 +1,65 @@
<h2>Comments</h2>
<pre><code>// Single line comment
/* Multi-line
comment */</code></pre>
<h2>Strings</h2>
<pre><code>"foo \"bar\" baz";
'foo \'bar\' baz';</code></pre>
<h2>Numbers</h2>
<pre><code>123
123.456
-123.456
.3f
1.3e9d
0xaf
0xAF
0xFF.AEP-4
</code></pre>
<h2>Full example</h2>
<pre><code>import java.util.Scanner;
public class Life {
@Override @Bind("One")
public void show(boolean[][] grid){
String s = "";
for(boolean[] row : grid){
for(boolean val : row)
if(val)
s += "*";
else
s += ".";
s += "\n";
}
System.out.println(s);
}
public static boolean[][] gen(){
boolean[][] grid = new boolean[10][10];
for(int r = 0; r < 10; r++)
for(int c = 0; c < 10; c++)
if( Math.random() > 0.7 )
grid[r][c] = true;
return grid;
}
public static void main(String[] args){
boolean[][] world = gen();
show(world);
System.out.println();
world = nextGen(world);
show(world);
Scanner s = new Scanner(System.in);
while(s.nextLine().length() == 0){
System.out.println();
world = nextGen(world);
show(world);
}
}
// [...]
}</code></pre>

View File

@ -0,0 +1,77 @@
<h2>Variable assignment</h2>
<pre><code>var foo = "bar", baz = 5;</code></pre>
<h2>Operators</h2>
<pre><code>(1 + 2 * 3)/4 >= 3 &amp;&amp; 4 &lt; 5 || 6 > 7</code></pre>
<h2>Indented code</h2>
<pre><code>if (true) {
while (true) {
doSomething();
}
}</code></pre>
<h2>Regex with slashes</h2>
<pre><code>var foo = /([^/])\/(\\?.|\[.+?])+?\/[gim]{0,3}/g;</code></pre>
<h2>Regex that ends with double slash</h2>
<pre><code>var bar = /\/\*[\w\W]*?\*\//g;</code></pre>
<h2>Single line comments &amp; regexes</h2>
<pre><code>// http://lea.verou.me
var comment = /\/\*[\w\W]*?\*\//g;</code></pre>
<h2>Link in comment</h2>
<pre><code>// http://lea.verou.me
/* http://lea.verou.me */</code></pre>
<h2>Nested strings</h2>
<pre><code>var foo = "foo", bar = "He \"said\" 'hi'!"</code></pre>
<h2>Strings inside comments</h2>
<pre><code>// "foo"
/* "foo" */</code></pre>
<h2>Strings with slashes</h2>
<pre><code>env.content + '&lt;/' + env.tag + '>'
var foo = "/" + "/";
var foo = "http://prismjs.com"; // Strings are strings and comments are comments ;)</code></pre>
<h2>Regex inside single line comment</h2>
<pre><code>// hey, /this doesnt fail!/ :D</code></pre>
<h2>Two or more division operators on the same line</h2>
<pre><code>var foo = 5 / 6 / 7;</code></pre>
<h2>A division operator on the same line as a regex</h2>
<pre><code>var foo = 1/2, bar = /a/g;
var foo = /a/, bar = 3/4;</code></pre>
<h2>ES6 features</h2>
<pre><code>// Regex "y" and "u" flags
var a = /[a-zA-Z]+/gimyu;
// for..of loops
for(let x of y) { }
// Modules: import
import { foo as bar } from "file.js"
// Template strings
`Only on ${y} one line`
`This template string ${x} is on
multiple lines.`
`40 + 2 = ${ 40 + 2 }`
`The squares of the first 3 natural integers are ${[for (x of [1,2,3]) x*x].join(', ')}`</code></pre>
<h2>Known failures</h2>
<p>There are certain edge cases where Prism will fail.
There are always such cases in every regex-based syntax highlighter.
However, Prism dares to be open and honest about them.
If a failure is listed here, it doesnt mean it will never be fixed. This is more of a “known bugs” list, just with a certain type of bug.
</p>
<h3>String interpolation containing a closing brace</h3>
<pre><code>`${ {foo:'bar'}.foo }`
`${ '}' }`</code></pre>

View File

@ -0,0 +1,63 @@
<h2>Full example</h2>
<pre><code>javax.servlet.ServletException: Something bad happened
at com.example.myproject.OpenSessionInViewFilter.doFilter(OpenSessionInViewFilter.java:60)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.example.myproject.ExceptionHandlerFilter.doFilter(ExceptionHandlerFilter.java:28)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at com.example.myproject.OutputBufferFilter.doFilter(OutputBufferFilter.java:33)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:943)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:756)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:218)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at org.mortbay.jetty.bio.SocketConnector$Connection.run(SocketConnector.java:228)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)
Caused by: com.example.myproject.MyProjectServletException
at com.example.myproject.MyServlet.doPost(MyServlet.java:169)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
at com.example.myproject.OpenSessionInViewFilter.doFilter(OpenSessionInViewFilter.java:30)
... 27 more
Suppressed: org.hibernate.exception.ConstraintViolationException: could not insert: [com.example.myproject.MyEntity]
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:64)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2329)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2822)
at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:71)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:268)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:321)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:204)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:130)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:705)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:693)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:689)
at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:344)
at $Proxy19.save(Unknown Source)
at com.example.myproject.MyEntityService.save(MyEntityService.java:59) &lt;-- relevant call (see notes below)
at com.example.myproject.MyServlet.doPost(MyServlet.java:164)
... 32 more
Caused by: java.sql.SQLException: Violation of unique constraint MY_ENTITY_UK_1: duplicate value(s) for column(s) MY_COLUMN in statement [...]
at org.hsqldb.jdbc.Util.throwError(Unknown Source)
at org.hsqldb.jdbc.jdbcPreparedStatement.executeUpdate(Unknown Source)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:105)
at org.hibernate.id.insert.AbstractSelectingDelegate.performInsert(AbstractSelectingDelegate.java:57)
... 54 more</code></pre>

View File

@ -0,0 +1,162 @@
<h2>Comments</h2>
<pre><code>// Single line comment
/* Multi-line
comment */</code></pre>
<h2>Strings</h2>
<pre><code>"foo \"bar\" baz";
'foo \'bar\' baz'</code></pre>
<h2>Numbers</h2>
<pre><code>42
42L
1.2e3
0.1E-4
0.2e+1
</code></pre>
<h2>Full example</h2>
<pre><code>include "console.iol"
type HubType: void {
.sid: undefined
.nodes[1,*] : NodeType
}
type NodeType: void {
.sid: string
.node: string
.load?: int
}
type NetType: HubType | NodeType
interface NetInterface {
OneWay: start( string ), addElement( NetType ), removeElement( NetType ), quit( void )
RequestResponse: showElements( void )( NetType ) throws SomeFault
}
type LogType: void {
.message: string
}
interface LoggerInterface {
RequestResponse: log( LogType )( void )
}
outputPort LoggerService {
Interfaces: LoggerInterface
}
embedded {
Jolie: "logger.ol" in LoggerService
}
type AuthenticationData: void {
.key:string
}
interface extender AuthInterfaceExtender {
OneWay: *(AuthenticationData)
}
service SubService
{
Interfaces: NetInterface
main
{
println@Console( "I do nothing" )()
}
}
inputPort ExtLogger {
Location: "socket://localhost:9000"
Protocol: sodep
Interfaces: LoggerInterface
Aggregates: LoggerService with AuthInterfaceExtender
}
courier ExtLogger {
[interface LoggerInterface( request )] {
if ( key == "secret" ){
forward ( request )
}
}
}
inputPort In {
Location: "socket://localhost:8000"
Protocol: http {
.debug = true;
.debug.showContent = true
}
Interfaces: NetInterface
Aggregates: SubService,
LoggerService
Redirects: A => SubService,
B => SubService
}
cset {
sid: HubType.sid NodeType.sid
}
execution{ concurrent }
define netmodule {
if( request.load == 0 || request.load < 1 &&
request.load <= 2 || request.load >= 3 &&
request.load > 4 || request.load%4 == 2
) {
scope( scopeName ) {
// inline comment
install( MyFault => println@Console( "Something \"Went\" Wrong" + ' but it\'s ok' )() );
/*
* Multi-line
* Comment
*/
install( this => cH; println@Console( "Something went wrong: " + ^load )() );
install( default => comp( scopeName ); println@Console( "Something went wrong" )() );
load -> request.( "load" );
{ ++load | load++ | --load | load-- };
throw( MyFault )
}
} else {
foreach ( node -> request.nodes ) {
with( node ){
while( .load != 100 ) {
.load++
}
}
}
}
}
main
{
start( sid );
synchronized( unneededSync ){
csets.sid = sid;
undef( sid )
};
provide
[ addElement( request ) ]{
if( request instanceof NodeType ) {
netmodule
}
}
[ removeElement() ]
[ showElements()( response ){
/*
* assemble response
*/
nullProcess
}]{
// log the request
log@LoggerService( new )();
log @ LoggerService( new )()
}
until
[ quit() ]{ exit }
}</code></pre>

View File

@ -0,0 +1,18 @@
<h2>Full example</h2>
<pre><code>var ExampleApplication = React.createClass({
render: function() {
var elapsed = Math.round(this.props.elapsed / 100);
var seconds = elapsed / 10 + (elapsed % 10 ? '' : '.0' );
var message =
'React has been successfully running for ' + seconds + ' seconds.';
return &lt;p>{message}&lt;/p>;
}
});
var start = new Date().getTime();
setInterval(function() {
React.render(
&lt;ExampleApplication elapsed={new Date().getTime() - start} />,
document.getElementById('container')
);
}, 50);</code></pre>

View File

@ -0,0 +1,29 @@
<h2>Full example</h2>
<pre><code>function mandel(z)
c = z
maxiter = 80
for n = 1:maxiter
if abs(z) > 2
return n-1
end
z = z^2 + c
end
return maxiter
end
function randmatstat(t)
n = 5
v = zeros(t)
w = zeros(t)
for i = 1:t
a = randn(n,n)
b = randn(n,n)
c = randn(n,n)
d = randn(n,n)
P = [a b c d]
Q = [a b; c d]
v[i] = trace((P.'*P)^4)
w[i] = trace((Q.'*Q)^4)
end
std(v)/mean(v), std(w)/mean(w)
end</code></pre>

View File

@ -0,0 +1,107 @@
<h2>Comments</h2>
<pre><code>c This is a comment</code></pre>
<h2>Strings, numbers and characters</h2>
<pre><code>"'this' is a string"
'and so is "this"'
U+0041 d65 x41 c these are all the letter A
</code></pre>
<h2>Prefixes and Virtual Keys</h2>
<pre><code>
c Match RAlt+E on desktops, Ctrl+Alt+E on web because L/R Alt not consistently supported in browsers.
$KeymanOnly: + [RALT K_E] > "€"
$KeymanWeb: + [CTRL ALT K_E] > "€"
</code></pre>
<h2>Example Code</h2>
<pre><code>c =====================Begin Identity Section===================================================
c
c Mnemonic input method for Amharic script on US-QWERTY
c keyboards for Keyman version 7.1, compliant with Unicode 4.1 and later.
c
store(&amp;VERSION) '9.0'
store(&amp;Name) "Amharic"
c store(&amp;MnemonicLayout) "1"
store(&amp;CapsAlwaysOff) "1"
store(&amp;Copyright) "Creative Commons Attribution 3.0"
store(&amp;Message) "This is an Amharic language mnemonic input method for Ethiopic script that requires Unicode 4.1 support."
store(&amp;WINDOWSLANGUAGES) 'x045E x045E'
store(&amp;LANGUAGE) 'x045E'
store(&amp;EthnologueCode) "amh"
store(&amp;VISUALKEYBOARD) 'gff-amh-7.kvk'
store(&amp;KMW_EMBEDCSS) 'gff-amh-7.css'
HOTKEY "^%A"
c
c =====================End Identity Section=====================================================
c =====================Begin Data Section=======================================================
c ---------------------Maps for Numbers---------------------------------------------------------
store(ArabOnes) '23456789'
store(ones) '፪፫፬፭፮፯፰፱'
store(tens) '፳፴፵፶፷፸፹፺'
store(arabNumbers) '123456789'
store(ethNumbers) '፩፪፫፬፭፮፯፰፱፲፳፴፵፶፷፸፹፺፻፼'
store(arabNumbersWithZero) '0123456789'
store(ColonOrComma) ':,'
store(ethWordspaceOrComma) '፡፣'
c ---------------------End Numbers--------------------------------------------------------------
c =====================End Data Section=========================================================
c =====================Begin Functional Section=================================================
c
store(&amp;LAYOUTFILE) 'gff-amh-7_layout.js'
store(&amp;BITMAP) 'amharic.bmp'
store(&amp;TARGETS) 'any windows'
begin Unicode > use(main)
group(main) using keys
c ---------------------Input of Numbers---------------------------------------------------------
c Special Rule for Arabic Numerals
c
c The following attempts to auto-correct the use of Ethiopic wordspace and
c Ethiopic comma within an Arabic numeral context. Ethiopic wordspace gets
c used erroneously in time formats and Ethiopic commas as an order of thousands
c delimiter. The correction context is not known until numerals appear on _both_
c sides of the punctuation.
c
any(arabNumbersWithZero) any(ethWordspaceOrComma) + any(arabNumbers) > index(arabNumbersWithZero,1) index(ColonOrComma,2) index(arabNumbers,3)
c Ethiopic Numerals
"'" + '1' > '፩'
"'" + any(ArabOnes) > index(ones,2)
c special cases for multiples of one
'፩' + '0' > '፲'
'፲' + '0' > '፻'
'፻' + '0' > '፲፻'
'፲፻' + '0' > '፼'
'፼' + '0' > '፲፼'
'፲፼' + '0' > '፻፼'
'፻፼' + '0' > '፲፻፼'
'፲፻፼' + '0' > '፼፼'
'፼፼' + '0' > context beep c do not go any higher, we could beep here
c upto the order of 100 million
any(ones) + '0' > index(tens,1)
any(tens) + '0' > index(ones,1) '፻' c Hundreds
any(ones) '፻ '+ '0' > index(tens,1) '፻' c Thousands
any(tens) '፻' + '0' > index(ones,1) '፼' c Ten Thousands
any(ones) '፼' + '0' > index(tens,1) '፼' c Hundred Thousands
any(tens) '፼' + '0' > index(ones,1) '፻፼' c Millions
any(ones) '፻፼' + '0' > index(tens,1) '፻፼' c Ten Millions
any(tens) '፻፼' + '0' > index(ones,1) '፼፼' c Hundred Millions
c enhance this later, look for something that can copy a match over
any(ethNumbers) + any(arabNumbers) > index(ethNumbers,1) index(ethNumbers,2)
c ---------------------End Input of Numbers-----------------------------------------------------
c =====================End Functional Section===================================================
</code></pre>

View File

@ -0,0 +1,134 @@
<h2>Numbers</h2>
<pre><code>123
123L
0x0F
0b00001011
123.5
123.5e10
123.5f
123.5F</code></pre>
<h2>Strings and interpolation</h2>
<pre><code>'2'
'\uFF00'
'\''
"foo $bar \"baz"
"""
foo ${40 + 2}
baz${bar()}
"""</code></pre>
<h2>Labels</h2>
<pre><code>loop@ for (i in 1..100) {
for (j in 1..100) {
if (...)
break@loop
}
}</code></pre>
<h2>Annotations</h2>
<pre><code>public class MyTest {
lateinit var subject: TestSubject
@SetUp fun setup() {
subject = TestSubject()
}
@Test fun test() {
subject.method() // dereference directly
}
}</code></pre>
<h2>Full example</h2>
<pre><code>package com.example.html
interface Element {
fun render(builder: StringBuilder, indent: String)
override fun toString(): String {
val builder = StringBuilder()
render(builder, "")
return builder.toString()
}
}
class TextElement(val text: String): Element {
override fun render(builder: StringBuilder, indent: String) {
builder.append("$indent$text\n")
}
}
abstract class Tag(val name: String): Element {
val children = arrayListOf&lt;Element>()
val attributes = hashMapOf&lt;String, String>()
protected fun initTag&lt;T: Element>(tag: T, init: T.() -> Unit): T {
tag.init()
children.add(tag)
return tag
}
override fun render(builder: StringBuilder, indent: String) {
builder.append("$indent&lt;$name${renderAttributes()}>\n")
for (c in children) {
c.render(builder, indent + " ")
}
builder.append("$indent&lt;/$name>\n")
}
private fun renderAttributes(): String? {
val builder = StringBuilder()
for (a in attributes.keySet()) {
builder.append(" $a=\"${attributes[a]}\"")
}
return builder.toString()
}
}
abstract class TagWithText(name: String): Tag(name) {
operator fun String.plus() {
children.add(TextElement(this))
}
}
class HTML(): TagWithText("html") {
fun head(init: Head.() -> Unit) = initTag(Head(), init)
fun body(init: Body.() -> Unit) = initTag(Body(), init)
}
class Head(): TagWithText("head") {
fun title(init: Title.() -> Unit) = initTag(Title(), init)
}
class Title(): TagWithText("title")
abstract class BodyTag(name: String): TagWithText(name) {
fun b(init: B.() -> Unit) = initTag(B(), init)
fun p(init: P.() -> Unit) = initTag(P(), init)
fun h1(init: H1.() -> Unit) = initTag(H1(), init)
fun a(href: String, init: A.() -> Unit) {
val a = initTag(A(), init)
a.href = href
}
}
class Body(): BodyTag("body")
class B(): BodyTag("b")
class P(): BodyTag("p")
class H1(): BodyTag("h1")
class A(): BodyTag("a") {
public var href: String
get() = attributes["href"]!!
set(value) {
attributes["href"] = value
}
}
fun html(init: HTML.() -> Unit): HTML {
val html = HTML()
html.init()
return html
}</code></pre>

View File

@ -0,0 +1,12 @@
<h2>Comments</h2>
<pre><code>% This is a comment</code></pre>
<h2>Commands</h2>
<pre><code>\begin{document}
\documentstyle[twoside,epsfig]{article}
\usepackage{epsfig,multicol}</code></pre>
<h2>Math mode</h2>
<pre><code>$\alpha$
H$_{2}$O
45$^{\circ}$C</code></pre>

View File

@ -0,0 +1,70 @@
<h2>Comments</h2>
<pre><code>// Single line comment
/* Multi-line
comment */</code></pre>
<h2>Variables</h2>
<pre><code>@nice-blue: #5B83AD;
@light-blue: @nice-blue + #111;</code></pre>
<h2>At-rules</h2>
<pre><code>@media screen and (min-width: 320px) {}</code></pre>
<h2>Mixins</h2>
<pre><code>.bordered {
border-top: dotted 1px black;
border-bottom: solid 2px black;
}
#menu a {
.bordered;
}
#header a {
color: orange;
#bundle > .button;
}</code></pre>
<h2>Mixins with parameters</h2>
<pre><code>.foo (@bg: #f5f5f5, @color: #900) {
background: @bg;
color: @color;
}
.bar {
.foo();
}
.class1 {
.mixin(@margin: 20px; @color: #33acfe);
}
.class2 {
.mixin(#efca44; @padding: 40px);
}</code></pre>
<h2>Interpolation</h2>
<pre><code>@mySelector: banner;
.@{mySelector} {
font-weight: bold;
}
@property: color;
.widget {
@{property}: #0ee;
background-@{property}: #999;
}</code></pre>
<h2>Known failures</h2>
<p>There are certain edge cases where Prism will fail.
There are always such cases in every regex-based syntax highlighter.
However, Prism dares to be open and honest about them.
If a failure is listed here, it doesnt mean it will never be fixed. This is more of a “known bugs” list, just with a certain type of bug.
</p>
<h3>At-rules looking like variables</h3>
<pre><code>@import "some file.less";</code></pre>
<h3>At-rules containing interpolation</h3>
<pre><code>@import "@{themes}/tidal-wave.less";</code></pre>
<h3>extend is not highlighted consistently</h3>
<pre><code>nav ul {
&:extend(.inline);
background: blue;
}
.a:extend(.b) {}</code></pre>

View File

@ -0,0 +1,75 @@
<h2>Comments</h2>
<pre><code>{% comment %}This is a comment{% endcomment %}</code></pre>
<h2>Control Flow</h2>
Liquid provides multiple control flow statements.
<h3>if</h3>
<pre><code>
{% if customer.name == 'kevin' %}
Hey Kevin!
{% elsif customer.name == 'anonymous' %}
Hey Anonymous!
{% else %}
Hi Stranger!
{% endif %}
</code></pre>
<h3>unless</h3>
The opposite of <code>if</code> executes a block of code only if a certain condition is not met.
<pre><code>
{% unless product.title == 'Awesome Shoes' %}
These shoes are not awesome.
{% endunless %}
</code></pre>
<h3>case</h3>
Creates a switch statement to compare a variable with different values. <code>case</code> initializes the switch statement, and <code>when</code> compares its values.
<pre><code>
{% assign handle = 'cake' %}
{% case handle %}
{% when 'cake' %}
This is a cake
{% when 'cookie' %}
This is a cookie
{% else %}
This is not a cake nor a cookie
{% endcase %}
</code></pre>
<h3>for</h3>
Repeatedly executes a block of code.
break = Causes the loop to stop iterating when it encounters the break tag.
continue = Causes the loop to skip the current iteration when it encounters the continue tag.
<pre><code>
{% for i in (1..10) %}
{% if i == 4 %}
{% break %}
{% elsif i == 6 %}
{% continue %}
{% else %}
{{ i }}
{% endif %}
{% endfor %}
</code></pre>
<h3>range</h3>
<pre><code>
{% for i in (3..5) %}
{{ i }}
{% endfor %}
{% assign num = 4 %}
{% for i in (1..num) %}
{{ i }}
{% endfor %}
</code></pre>

View File

@ -0,0 +1,46 @@
<h2>Comments</h2>
<pre><code>;; (foo bar)</code></pre>
<h2>Strings</h2>
<pre><code>(foo "bar")</code></pre>
<h3>With nested symbols</h3>
<pre><code>(foo "A string with a `symbol ")</code></pre>
<h3>With nested arguments</h3>
<pre><code>(foo "A string with an ARGUMENT ")</code></pre>
<h2>Quoted symbols</h2>
<pre><code>(foo #'bar)</code></pre>
<h2>Lisp properties</h2>
<pre><code>(foo :bar)</code></pre>
<h2>Splices</h2>
<pre><code>(foo ,bar ,@bar)</code></pre>
<h2>Keywords</h2>
<pre><code>(let foo (bar arg))</code></pre>
<h2>Declarations</h2>
<pre><code>(declare foo)</code></pre>
<h2>Booleans</h2>
<pre><code>(foo t)</code></pre>
<pre><code>(foo nil)</code></pre>
<h2>Numbers</h2>
<pre><code>(foo 1)</code></pre>
<pre><code>(foo -1.5)</code></pre>
<h2>Definitions</h2>
<pre><code>(defvar bar 23)</code></pre>
<pre><code>(defcustom bar 23)</code></pre>
<h2>Function definitions</h2>
<pre><code>(defun multiply-by-seven (number)
"Multiply NUMBER by seven."
(* 7 number))</code></pre>
<h2>Lambda expressions</h2>
<pre><code>(lambda (number) (* 7 number))</code></pre>

View File

@ -0,0 +1,84 @@
<h2>Comments</h2>
<pre><code># This is a single line comment
/* This is a
multi line comment */</code></pre>
<h2>Numbers</h2>
<pre><code>42
42km
3.754km_2
16~BadFace
36~azertyuiop0123456789</code></pre>
<h2>Strings and interpolation</h2>
<pre><code>''
''''''
""
""""""
'Foo \' bar
baz'
'''Foo \''' bar
bar'''
"Foo #bar \"
#{2 + 2}\""
"""#foobar \""" #{ if /test/ == 'test' then 3 else 4}
baz"""</code></pre>
<h2>Regex</h2>
<pre><code>/foobar/ig
//
^foo # foo
[bar]*bA?z # barbaz
//m</code></pre>
<h2>Full example</h2>
<pre><code># example from Str.ls
split = (sep, str) -->
str.split sep
join = (sep, xs) -->
xs.join sep
lines = (str) ->
return [] unless str.length
str.split '\n'
unlines = (.join '\n')
words = (str) ->
return [] unless str.length
str.split /[ ]+/
unwords = (.join ' ')
chars = (.split '')
unchars = (.join '')
reverse = (str) ->
str.split '' .reverse!.join ''
repeat = (n, str) -->
result = ''
for til n
result += str
result
capitalize = (str) ->
(str.char-at 0).to-upper-case! + str.slice 1
camelize = (.replace /[-_]+(.)?/g, (, c) -> (c ? '').to-upper-case!)
# convert camelCase to camel-case, and setJSON to set-JSON
dasherize = (str) ->
str
.replace /([^-A-Z])([A-Z]+)/g, (, lower, upper) ->
"#{lower}-#{if upper.length > 1 then upper else upper.to-lower-case!}"
.replace /^([A-Z]+)/, (, upper) ->
if upper.length > 1 then "#upper-" else upper.to-lower-case!
module.exports = {
split, join, lines, unlines, words, unwords, chars, unchars, reverse,
repeat, capitalize, camelize, dasherize,
}</code></pre>

View File

@ -0,0 +1,62 @@
<h2>Comments</h2>
<pre><code>BTW Single line comment
OBTW Multi-line
comment TLDR</code></pre>
<h2>Strings and special characters</h2>
<pre><code>"foo :"bar:" baz"
"foo:)bar:>baz"
"Interpolation :{works} too!"</code></pre>
<h2>Numbers</h2>
<pre><code>42
-42
123.456</code></pre>
<h2>Variable declaration</h2>
<pre><code>I HAS A var
var R "THREE"
var R 3</code></pre>
<h2>Types</h2>
<pre><code>MAEK some_expr A YARN
some_var IS NOW A NUMBR</code></pre>
<h2>Full example</h2>
<pre><code>OBTW Convert a number to hexadecimal. This
is returned as a string.
TLDR
HOW IZ I decimal_to_hex YR num
I HAS A i ITZ 0
I HAS A rem
I HAS A hex_num ITZ A BUKKIT
I HAS A decimal_num ITZ num
IM IN YR num_loop
rem R MOD OF decimal_num AN 16
I HAS A hex_digit
rem, WTF?
OMG 10, hex_digit R "A", GTFO
OMG 11, hex_digit R "B", GTFO
OMG 12, hex_digit R "C", GTFO
OMG 13, hex_digit R "D", GTFO
OMG 14, hex_digit R "E", GTFO
OMG 15, hex_digit R "F", GTFO
OMGWTF, hex_digit R rem
OIC
hex_num HAS A SRS i ITZ hex_digit
decimal_num R QUOSHUNT OF decimal_num AN 16
BOTH SAEM decimal_num AN 0, O RLY?
YA RLY, GTFO
NO WAI, i R SUM OF i AN 1
OIC
IM OUTTA YR num_loop
I HAS A hex_string ITZ A YARN
IM IN YR string_reverse
DIFFRINT i AN BIGGR OF i AN 0, O RLY?
YA RLY, GTFO
OIC
hex_string R SMOOSH hex_string AN hex_num'Z SRS i MKAY
i R DIFF OF i AN 1
IM OUTTA YR string_reverse
FOUND YR hex_string
IF U SAY SO</code></pre>

View File

@ -0,0 +1,89 @@
<h2>Comments</h2>
<pre><code>#!/usr/local/bin/lua
--
-- Single line comment
--[[ Multi line
comment ]]
--[====[ Multi line
comment ]====]</code></pre>
<h2>Strings</h2>
<pre><code>""
"Foo\"bar"
"Foo\
bar \z
baz"
''
'Foo\'bar'
'Foo\
bar \z
baz'
[[Multi "line"
string]]
[==[Multi [["line"]]
string]==]</code></pre>
<h2>Numbers</h2>
<pre><code>3
345
0xff
0xBEBADA
3, 3., 3.1, .3,
3e12, 3.e-41, 3.1E+1, .3e1
0x0.1E
0xA23p-4
0X1.921FB54442D18P+1</code></pre>
<h2>Full example</h2>
<pre><code>function To_Functable(t, fn)
return setmetatable(t,
{
__index = function(t, k) return fn(k) end,
__call = function(t, k) return t[k] end
})
end
-- Functable bottles of beer implementation
spell_out = {
"One", "Two", "Three", "Four", "Five",
"Six", "Seven", "Eight", "Nine", "Ten",
[0] = "No more",
[-1] = "Lots more"
}
spell_out = To_Functable(spell_out, function(i) return i end)
bottles = To_Functable({"Just one bottle of beer"},
function(i)
return spell_out(i) .. " bottles of beer"
end)
function line1(i)
return bottles(i) .. " on the wall, " .. bottles(i) .. "\n"
end
line2 = To_Functable({[0] = "Go to the store, Buy some more,\n"},
function(i)
return "Take one down and pass it around,\n"
end)
function line3(i)
return bottles(i) .. " on the wall.\n"
end
function song(n)
for i = n, 0, -1 do
io.write(line1(i), line2(i), line3(i - 1), "\n")
end
end</code></pre>
<h2>Known failures</h2>
<p>There are certain edge cases where Prism will fail.
There are always such cases in every regex-based syntax highlighter.
However, Prism dares to be open and honest about them.
If a failure is listed here, it doesnt mean it will never be fixed. This is more of a “known bugs” list, just with a certain type of bug.
</p>
<h3>Functions with a single string parameter not using parentheses are not highlighted</h3>
<pre><code>foobar"param";</code></pre>

View File

@ -0,0 +1,263 @@
<h2>Comments</h2>
<pre><code># This is a comment
include foo # This is another comment</code></pre>
<h2>Targets</h2>
<pre><code>kbd.o command.o files.o : command.h
display.o insert.o search.o files.o : buffer.h
.PHONY: clean
clean:
rm *.o temp</code></pre>
<h2>Variables</h2>
<pre><code>objects = main.o kbd.o command.o display.o \
insert.o search.o files.o utils.o
edit : $(objects)
cc -o edit $(objects)
$(objects) : defs.h
%oo: $$< $$^ $$+ $$*
foo : bar/lose
cd $(@D) && gobble $(@F) > ../$@</code></pre>
<h2>Strings</h2>
<pre><code>STR = 'A string!'
HELLO = 'hello \
world'
HELLO2 = "hello \
world"</code></pre>
<h2>Directives</h2>
<pre><code>include foo *.mk $(bar)
vpath %.c foo
override define two-lines =
foo
$(bar)
endef
ifeq ($(CC),gcc)
libs=$(libs_for_gcc)
else
libs=$(normal_libs)
endif</code></pre>
<h2>Functions</h2>
<pre><code>whoami := $(shell whoami)
host-type := $(shell arch)
y = $(subst 1,2,$(x))
dirs := a b c d
files := $(foreach dir,$(dirs),$(wildcard $(dir)/*))
reverse = $(2) $(1)
foo = $(call reverse,a,b)
$(foreach prog,$(PROGRAMS),$(eval $(call PROGRAM_template,$(prog))))</code></pre>
<h2>Complete example</h2>
<pre><code>#!/usr/bin/make -f
# Generated automatically from Makefile.in by configure.
# Un*x Makefile for GNU tar program.
# Copyright (C) 1991 Free Software Foundation, Inc.
# This program is free software; you can redistribute
# it and/or modify it under the terms of the GNU
# General Public License …
SHELL = /bin/sh
#### Start of system configuration section. ####
srcdir = .
# If you use gcc, you should either run the
# fixincludes script that comes with it or else use
# gcc with the -traditional option. Otherwise ioctl
# calls will be compiled incorrectly on some systems.
CC = gcc -O
YACC = bison -y
INSTALL = /usr/local/bin/install -c
INSTALLDATA = /usr/local/bin/install -c -m 644
# Things you might add to DEFS:
# -DSTDC_HEADERS If you have ANSI C headers and
# libraries.
# -DPOSIX If you have POSIX.1 headers and
# libraries.
# -DBSD42 If you have sys/dir.h (unless
# you use -DPOSIX), sys/file.h,
# and st_blocks in `struct stat'.
# -DUSG If you have System V/ANSI C
# string and memory functions
# and headers, sys/sysmacros.h,
# fcntl.h, getcwd, no valloc,
# and ndir.h (unless
# you use -DDIRENT).
# -DNO_MEMORY_H If USG or STDC_HEADERS but do not
# include memory.h.
# -DDIRENT If USG and you have dirent.h
# instead of ndir.h.
# -DSIGTYPE=int If your signal handlers
# return int, not void.
# -DNO_MTIO If you lack sys/mtio.h
# (magtape ioctls).
# -DNO_REMOTE If you do not have a remote shell
# or rexec.
# -DUSE_REXEC To use rexec for remote tape
# operations instead of
# forking rsh or remsh.
# -DVPRINTF_MISSING If you lack vprintf function
# (but have _doprnt).
# -DDOPRNT_MISSING If you lack _doprnt function.
# Also need to define
# -DVPRINTF_MISSING.
# -DFTIME_MISSING If you lack ftime system call.
# -DSTRSTR_MISSING If you lack strstr function.
# -DVALLOC_MISSING If you lack valloc function.
# -DMKDIR_MISSING If you lack mkdir and
# rmdir system calls.
# -DRENAME_MISSING If you lack rename system call.
# -DFTRUNCATE_MISSING If you lack ftruncate
# system call.
# -DV7 On Version 7 Unix (not
# tested in a long time).
# -DEMUL_OPEN3 If you lack a 3-argument version
# of open, and want to emulate it
# with system calls you do have.
# -DNO_OPEN3 If you lack the 3-argument open
# and want to disable the tar -k
# option instead of emulating open.
# -DXENIX If you have sys/inode.h
# and need it 94 to be included.
DEFS = -DSIGTYPE=int -DDIRENT -DSTRSTR_MISSING \
-DVPRINTF_MISSING -DBSD42
# Set this to rtapelib.o unless you defined NO_REMOTE,
# in which case make it empty.
RTAPELIB = rtapelib.o
LIBS =
DEF_AR_FILE = /dev/rmt8
DEFBLOCKING = 20
CDEBUG = -g
CFLAGS = $(CDEBUG) -I. -I$(srcdir) $(DEFS) \
-DDEF_AR_FILE=\"$(DEF_AR_FILE)\" \
-DDEFBLOCKING=$(DEFBLOCKING)
LDFLAGS = -g
prefix = /usr/local
# Prefix for each installed program,
# normally empty or `g'.
binprefix =
# The directory to install tar in.
bindir = $(prefix)/bin
# The directory to install the info files in.
infodir = $(prefix)/info
#### End of system configuration section. ####
SRCS_C = tar.c create.c extract.c buffer.c \
getoldopt.c update.c gnu.c mangle.c \
version.c list.c names.c diffarch.c \
port.c wildmat.c getopt.c getopt1.c \
regex.c
SRCS_Y = getdate.y
SRCS = $(SRCS_C) $(SRCS_Y)
OBJS = $(SRCS_C:.c=.o) $(SRCS_Y:.y=.o) $(RTAPELIB)
AUX = README COPYING ChangeLog Makefile.in \
makefile.pc configure configure.in \
tar.texinfo tar.info* texinfo.tex \
tar.h port.h open3.h getopt.h regex.h \
rmt.h rmt.c rtapelib.c alloca.c \
msd_dir.h msd_dir.c tcexparg.c \
level-0 level-1 backup-specs testpad.c
.PHONY: all
all: tar rmt tar.info
tar: $(OBJS)
$(CC) $(LDFLAGS) -o $@ $(OBJS) $(LIBS)
rmt: rmt.c
$(CC) $(CFLAGS) $(LDFLAGS) -o $@ rmt.c
tar.info: tar.texinfo
makeinfo tar.texinfo
.PHONY: install
install: all
$(INSTALL) tar $(bindir)/$(binprefix)tar
-test ! -f rmt || $(INSTALL) rmt /etc/rmt
$(INSTALLDATA) $(srcdir)/tar.info* $(infodir)
$(OBJS): tar.h port.h testpad.h
regex.o buffer.o tar.o: regex.h
# getdate.y has 8 shift/reduce conflicts.
testpad.h: testpad
./testpad
testpad: testpad.o
$(CC) -o $@ testpad.o
TAGS: $(SRCS)
etags $(SRCS)
.PHONY: clean
clean:
rm -f *.o tar rmt testpad testpad.h core
.PHONY: distclean
distclean: clean
rm -f TAGS Makefile config.status
.PHONY: realclean
realclean: distclean
rm -f tar.info*
.PHONY: shar
shar: $(SRCS) $(AUX)
shar $(SRCS) $(AUX) | compress \
> tar-`sed -e '/version_string/!d' \
-e 's/[^0-9.]*\([0-9.]*\).*/\1/' \
-e q
version.c`.shar.Z
.PHONY: dist
dist: $(SRCS) $(AUX)
echo tar-`sed \
-e '/version_string/!d' \
-e 's/[^0-9.]*\([0-9.]*\).*/\1/' \
-e q
version.c` > .fname
-rm -rf `cat .fname`
mkdir `cat .fname`
ln $(SRCS) $(AUX) `cat .fname`
tar chZf `cat .fname`.tar.Z `cat .fname`
-rm -rf `cat .fname` .fname
tar.zoo: $(SRCS) $(AUX)
-rm -rf tmp.dir
-mkdir tmp.dir
-rm tar.zoo
for X in $(SRCS) $(AUX) ; do \
echo $$X ; \
sed 's/$$/^M/' $$X \
> tmp.dir/$$X ; done
cd tmp.dir ; zoo aM ../tar.zoo *
-rm -rf tmp.dir
</code></pre>

View File

@ -0,0 +1,86 @@
<h2>Titles</h2>
<pre><code>Title 1
==
Title 2
-------
# Title 1
## Title 2
### Title 3
#### Title 4
##### Title 5
###### Title 6
</code></pre>
<h2>Bold and italic</h2>
<pre><code>*Italic*
**Bold on
multiple lines**
*Italic on
multiple lines too*
__It also works with underscores__
_It also works with underscores_
__An empty line
is not allowed__
</code></pre>
<h2>Links</h2>
<pre><code>[Prism](http://www.prismjs.com)
[Prism](http://www.prismjs.com "Prism")
[prism link]: http://www.prismjs.com (Prism)
[Prism] [prism link]
</code></pre>
<h2>Lists and quotes</h2>
<pre><code>* This is
* an unordered list
1. This is an
2. ordered list
* *List item in italic*
* **List item in bold**
* [List item as a link](http://example.com "This is an example")
> This is a quotation
>> With another quotation inside
> _italic here_, __bold there__
> And a [link](http://example.com)
</code></pre>
<h2>Code</h2>
<pre><code>Inline code between backticks `&lt;p>Paragraph&lt;/p>`
some_code(); /* Indented
with four spaces */
some_code(); /* Indented
with a tab */
</code></pre>
<h2>Raw HTML</h2>
<pre><code>> This is a quotation
> Containing &lt;strong>raw HTML&lt;/strong>
&lt;p>*Italic text inside HTML tag*&lt;/p></code></pre>
<h2>Known failures</h2>
<p>There are certain edge cases where Prism will fail.
There are always such cases in every regex-based syntax highlighter.
However, Prism dares to be open and honest about them.
If a failure is listed here, it doesnt mean it will never be fixed. This is more of a “known bugs” list, just with a certain type of bug.
</p>
<h3>Nesting of elements is not fully supported</h3>
<pre><code>_ **bold** inside italic DOESN'T work _
__ but *italic* inside bold DOES work __
[Link partially *italic* DOESN'T work](http://example.com)
_ [But link inside italic DOES work](http://example.com) _
[Link partially **bold** DOESN'T work](http://example.com)
__ [But link inside bold DOES work](http://example.com) __</code></pre>

View File

@ -0,0 +1,77 @@
<h2>Empty tag</h2>
<pre><code>&lt;p>&lt;/p></code></pre>
<h2>Tag that spans multiple lines</h2>
<pre><code>&lt;p
>hello!
&lt;/p></code></pre>
<h2>Name-attribute pair</h2>
<pre><code>&lt;p>&lt;/p></code></pre>
<h2>Name-attribute pair without quotes</h2>
<pre><code>&lt;p class=prism>&lt;/p></code></pre>
<h2>Attribute without value</h2>
<pre><code>&lt;p data-foo>&lt;/p>
&lt;p data-foo >&lt;/p>
</code></pre>
<h2>Namespaces</h2>
<pre><code>&lt;html:p foo:bar="baz" foo:weee>&lt;/html:p></code></pre>
<h2>XML prolog</h2>
<pre><code>&lt;?xml version="1.0" encoding="utf-8"?>
&lt;svg>&lt;/svg></code></pre>
<h2>DOCTYPE</h2>
<pre><code>&lt;!DOCTYPE html>
&lt;html>&lt;/html></code></pre>
<h2>CDATA section</h2>
<pre><code>&lt;ns1:description>&lt;![CDATA[
CDATA is &lt;not> magical.
]]>&lt;/ns1:description></code></pre>
<h2>Comment</h2>
<pre><code>&lt;!-- I'm a comment -->
And i'm not</code></pre>
<h2>Entities</h2>
<pre><code>&amp;amp; &amp;#x2665; &amp;#160; &amp;#x152;</code></pre>
<h2>Embedded JS and CSS</h2>
<pre><code>&lt;!DOCTYPE html>
&lt;html lang="en">
&lt;head>
&lt;meta charset="utf-8" />
&lt;title>I can haz embedded CSS and JS&lt;/title>
&lt;style>
@media print {
p { color: red !important; }
}
&lt;/style>
&lt;/head>
&lt;body>
&lt;h1>I can haz embedded CSS and JS&lt;/h1>
&lt;script>
if (true) {
console.log('foo');
}
&lt;/script>
&lt;/body>
&lt;/html></code></pre>
<h2>Invalid HTML</h2>
<pre><code>&lt;l &lt;/ul></code></pre>
<h2>Multi-line attribute values</h2>
<pre><code>&lt;p title="foo
bar
baz"></code></pre>
<h2>XML tags with non-ASCII characters</h2>
<pre><code>&lt;L&auml;ufer&gt;foo&lt;/L&auml;ufer&gt;
&lt;tag l&auml;ufer="l&auml;ufer"&gt;bar&lt;/tag&gt;
&lt;l&auml;ufer:tag&gt;baz&lt;/l&auml;ufer:tag&gt;</code></pre>

View File

@ -0,0 +1,52 @@
<h2>Strings</h2>
<pre><code>myString = 'Hello, world';
otherString = 'You''re right';</code></pre>
<h2>Comments</h2>
<pre><code>% Single line comment
%{ Multi-line
comment }%</code></pre>
<h2>Numbers</h2>
<pre><code>x = 325.499
realmax + .0001e+308
e = 1 - 3*(4/3 - 1)
b = 1e-16 + 1 - 1e-16;
x = 2 + 3i;
z =
4.7842 -1.0921i 0.8648 -1.5931i 1.2616 -2.2753i
2.6130 -0.0941i 4.8987 -2.3898i 4.3787 -3.7538i
4.4007 -7.1512i 1.3572 -5.2915i 3.6865 -0.5182i
</code></pre>
<h2>Control flow</h2>
<pre><code>if rem(a, 2) == 0
disp('a is even')
b = a/2;
end
switch dayString
case 'Monday'
disp('Start of the work week')
case 'Tuesday'
disp('Day 2')
case 'Wednesday'
disp('Day 3')
case 'Thursday'
disp('Day 4')
case 'Friday'
disp('Last day of the work week')
otherwise
disp('Weekend!')
end
n = 1;
nFactorial = 1;
while nFactorial < 1e100
n = n + 1;
nFactorial = nFactorial * n;
end</code></pre>
<h2>Functions</h2>
<pre><code>q = integral(sqr,0,1);
y = parabola(x)
mygrid = @(x,y) ndgrid((-x:x/c:x),(-y:y/c:y));
[x,y] = mygrid(pi,2*pi);</code></pre>

View File

@ -0,0 +1,137 @@
<h2>Comments</h2>
<pre><code>// This is a comment</code></pre>
<h2>Strings</h2>
<pre><code>"This is a string"
"foo \"bar\" baz"</code></pre>
<h2>Numbers</h2>
<pre><code>42
3.14159
0xA2F</code></pre>
<h2>Variables</h2>
<pre><code>$x
$floaty5000
$longDescriptiveName
$name_with_underscores
$_line
float $param;
int $counter;
string $name;
vector $position;</code></pre>
<h2>Arrays, vectors and matrices</h2>
<pre><code>string $array[3] = {"first\n", "second\n", "third\n"};
print($array[0]); // Prints "first\n"
print($array[1]); // Prints "second\n"
print($array[2]); // Prints "third\n"
vector $roger = <<3.0, 7.7, 9.1>>;
vector $more = <<4.5, 6.789, 9.12356>>;
// Assign a vector to variable $test:
vector $test = <<3.0, 7.7, 9.1>>;
$test = <<$test.x, 5.5, $test.z>>
// $test is now <<3.0, 5.5, 9.1>>
matrix $a3[3][4] = <<2.5, 4.5, 3.25, 8.05;
1.12, 1.3, 9.5, 5.2;
7.23, 6.006, 2.34, 4.67>></code></pre>
<h2>Commands</h2>
<pre><code>pickWalk -d down;
string $mySelection[] = `ls -selection`;
setAttr ($mySelection[0]+".particleRenderType") 5;
addAttr -is true -ln "spriteTwist" -at "float" -min -180 -max 180 -dv 0.0 blue_nParticleShape;</code></pre>
<h2>Full example</h2>
<pre><code>// From http://help.autodesk.com/view/MAYAUL/2015/ENU/?guid=Example_scripts_Dynamics_Time_Playback
// Alias Script File
// MODIFY THIS AT YOUR OWN RISK
//
// Creation Date: 8 May 1996
// Author: rh
//
// Description:
// Playback from frame 0 to frame &lt;n> and return the
// the playback rate in frames/sec. If a negative frame
// count is given, this indicates silent mode. In silent
// mode, no output is printed.
//
// This version is intended for use in batch tests of dynamics.
// It requests particle and rigid body positions every frame.
//
// RETURN
// Frame rate in frames/sec
//
global proc float dynTimePlayback( float $frames )
{
int $silent;
// Get the list of particle shapes.
//
string $particleObjects[] = `ls -type particle`;
int $particleCount = size( $particleObjects );
// Get the list of transforms.
// This will include rigid bodies.
//
string $transforms[] = `ls -tr`;
int $trCount = size( $transforms );
// Check for negative $frames. This indicates
// $silent mode.
//
if ($frames < 0)
{
$silent = 1;
$frames = -$frames;
}
else
{
$silent = 0;
}
// Setup the playback options.
//
playbackOptions -min 1 -max $frames -loop "once";
currentTime -edit 0;
// Playback the animation using the timerX command
// to compute the $elapsed time.
//
float $startTime, $elapsed;
$startTime = `timerX`;
// play -wait;
int $i;
for ($i = 1; $i < $frames; $i++ )
{
// Set time
//
currentTime -e $i;
int $obj;
// Request count for every particle object.
//
for ($obj = 0; $obj < $particleCount; $obj++)
{
string $cmd = "getAttr " + $particleObjects[$obj]+".count";
eval( $cmd );
}
// Request position for every transform
// (includes every rigid body).
//
for ($obj = 0; $obj < $trCount; $obj++)
{
string $cmd = "getAttr " + $transforms[$obj]+".translate";
eval ($cmd);
}
}
$elapsed = `timerX -st $startTime`;
// Compute the playback frame $rate. Print results.
//
float $rate = ($elapsed == 0 ? 0.0 : $frames / $elapsed) ;
if ( ! $silent)
{
print( "Playback time: " + $elapsed + " secs\n" );
print( "Playback $rate: " + $rate + " $frames/sec\n" );
}
return ( $rate );
} // timePlayback //</code></pre>

View File

@ -0,0 +1,45 @@
<h2>Full example</h2>
<pre><code>:: Example from http://webdocs.cs.ualberta.ca/~piotr/Mizar/Dagstuhl97/
environ
vocabulary SCM;
constructors ARYTHM, PRE_FF, NAT_1, REAL_1;
notation ARYTHM, PRE_FF, NAT_1;
requirements ARYTHM;
theorems REAL_1, PRE_FF, NAT_1, AXIOMS, CQC_THE1;
schemes NAT_1;
begin
P: for k being Nat
st for n being Nat st n < k holds Fib (n+1) n
holds Fib (k+1) k
proof let k be Nat; assume
IH: for n being Nat st n < k holds Fib (n+1) n;
per cases;
suppose k 1; then k = 0 or k = 0+1 by CQC_THE1:2;
hence Fib (k+1) k by PRE_FF:1;
suppose 1 < k; then
1+1 k by NAT_1:38; then
consider m being Nat such that
A: k = 1+1+m by NAT_1:28;
thus Fib (k+1) k proof
per cases by NAT_1:19;
suppose S1: m = 0;
Fib (0+1+1+1) = Fib(0+1) + Fib(0+1+1) by PRE_FF:1
= 1 + 1 by PRE_FF:1;
hence Fib (k+1) k by A, S1;
suppose m > 0; then
m+1 > 0+1 by REAL_1:59; then
m ≥ 1 by NAT_1:38; then
B: m+(m+1) ≥ m+1+1 by REAL_1:49;
C: k = m+1+1 by A, AXIOMS:13;
m < m+1 & m+1 < m+1+1 by REAL_1:69; then
m < k & m+1 < k by C, AXIOMS:22; then
D: Fib (m+1) m & Fib (m+1+1) m+1 by IH;
Fib (m+1+1+1) = Fib (m+1) + Fib (m+1+1) by PRE_FF:1; then
Fib (m+1+1+1) m+(m+1) by D, REAL_1:55;
hence Fib(k+1) k by C, B, AXIOMS:22;
end;
end;
for n being Nat holds Fib(n+1) n from Comp_Ind(P);</code></pre>

View File

@ -0,0 +1,74 @@
<h2>Comments</h2>
<pre><code>' This is a comment
#Rem ' This is the start of a comment block
Some comment ' We are inside the comment block
#End</code></pre>
<h2>Strings</h2>
<pre><code>"Hello World"
"~qHello World~q"
"~tIndented~n"</code></pre>
<h2>Numbers</h2>
<pre><code>0
1234
$3D0DEAD
$CAFEBABE
.0
0.0
.5
0.5
1.0
1.5
1.00001
3.14159265</code></pre>
<h2>Variable types</h2>
<pre><code>Local myVariable:Bool = True
Local myVariable? = True
Local myVariable:Int = 1024
Local myVariable% = 1024
Local myVariable:Float = 3.141516
Local myVariable# = 3.141516
Local myVariable:String = "Hello world"
Local myVariable$ = "Hello world"</code></pre>
<h2>Full example</h2>
<pre><code>Import mojo
Class MyApp Extends App
Method OnCreate()
SetUpdateRate 60
End
Method OnRender()
Local date:=GetDate()
Local months:=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]
Local day:=("0"+date[2])[-2..]
Local month:=months[date[1]-1]
Local year:=date[0]
Local hour:=("0"+date[3])[-2..]
Local min:=("0"+date[4])[-2..]
Local sec:=("0"+date[5])[-2..] + "." + ("00"+date[6])[-3..]
Local now:=hour+":"+min+":"+sec+" "+day+" "+month+" "+year
Cls
DrawText now,DeviceWidth/2,DeviceHeight/2,.5,.5
End
End
Function Main()
New MyApp
End</code></pre>

View File

@ -0,0 +1,114 @@
<h2>Keywords</h2>
<pre><code>
class C {..}
interface I {..}
foo(c: C, i: I) {
c instanceof C; // ok
c instanceof I; // ok
}
</code></pre>
<h2>Annotations</h2>
<pre><code>
// Final Methods
@Final
private tasks = new Map&lt;string,Task&gt;();
// Redefinition of Members
@Override
public async size(): int {
}
// Dependency Injection
@Binder
@Bind(Storage,StorageInMemory)
class InMemoryBinder {}
@GenerateInjector @UseBinder(InMemoryBinder)
export public class TaskManagerTest {
}
</code></pre>
<h2>Full example</h2>
<pre><code>
// A Web User Interface in HTML
// NOTE: requires full example project bundled with N4JS IDE to run.
import { TaskManager } from "TaskManager";
import {Application, Response } from "express";
import express from "express";
import { Todo } from "model";
export class WebUI {
private app: Application;
@Inject
private manager: TaskManager;
public start() {
this.app = express();
this.app.get('/', async (req, res) => {
let page = await this.renderHomePage();
res.send(page);
});
this.app.get("/clear", async (req, res) => {
await this.manager.clear();
redirect(res, '/');
});
this.app.get("/create", async (req, res) => {
let values = req.query as ~Object with {type: string, label: string};
if (values && values.type === 'Todo' && values.label && values.label.length > 0) {
await this.manager.createTodo(values.label);
}
redirect(res, '/');
});
this.app.listen(4000, '0.0.0.0', 511, function() {
console.log("HTML server listening on http://localhost:4000/");
});
}
protected async renderHomePage(): string {
let tasks = await this.manager.getTasks();
let todos = tasks.filter((task) => task instanceof Todo);
return `
&lt;html&gt;
&lt;body&gt;
Your to-do's:
&lt;ul&gt;
${
todos.length === 0 ? '&lt;li&gt;&lt;em&gt;none&lt;/em&gt;&lt;/li&gt;\n'
: todos.map((task) =>
'&lt;li&gt;' + task.label + ' &lt;small&gt;(id: ' + task.id + ')&lt;/small&gt;&lt;/li&gt;'
).join('\n')
}
&lt;/ul&gt;
&lt;hr/&gt;
&lt;form action="/create" method="get"&gt;
&lt;input type="hidden" name="type" value="Todo"&gt;
Label: &lt;input type="text" name="label"&gt;&lt;br&gt;
&lt;input type="submit" value="Create Todo"&gt;
&lt;/form&gt;
&lt;hr/&gt;
&lt;a href="/clear"&gt;[Clear All]&lt;/a&gt;
&lt;/body&gt;
&lt;/html&gt;
`;
}
}
function redirect(res: Response, url: string) {
res.header('Cache-Control', 'no-cache');
res.redirect(301, url);
}
</code></pre>

View File

@ -0,0 +1,74 @@
<h2>Comments</h2>
<pre><code>; This is a comment</code></pre>
<h2>Labels</h2>
<pre><code>label1: ; a non-local label
.local: ; this is really label1.local
..@foo: ; this is a special symbol
label2: ; another non-local label
.local: ; this is really label2.local
</code></pre>
<h2>Registers</h2>
<pre><code>st0
st1
ax
rax
zmm4</code></pre>
<h2>Strings</h2>
<pre><code>
mov eax,'abcd'
db 'hello' ; string constant
db 'h','e','l','l','o' ; equivalent character constants
dd 'ninechars' ; doubleword string constant
dd 'nine','char','s' ; becomes three doublewords
db 'ninechars',0,0,0 ; and really looks like this
db `\u263a` ; UTF-8 smiley face
db `\xe2\x98\xba` ; UTF-8 smiley face
db 0E2h, 098h, 0BAh ; UTF-8 smiley face
</code></pre>
<h2>Numbers</h2>
<pre><code>mov ax,200 ; decimal
mov ax,0200 ; still decimal
mov ax,0200d ; explicitly decimal
mov ax,0d200 ; also decimal
mov ax,0c8h ; hex
mov ax,$0c8 ; hex again: the 0 is required
mov ax,0xc8 ; hex yet again
mov ax,0hc8 ; still hex
mov ax,310q ; octal
mov ax,310o ; octal again
mov ax,0o310 ; octal yet again
mov ax,0q310 ; octal yet again
mov ax,11001000b ; binary
db -0.2 ; "Quarter precision"
dw -0.5 ; IEEE 754r/SSE5 half precision
dd 1.2 ; an easy one
dd 0x1p+2 ; 1.0x2^2 = 4.0
dq 0x1p+32 ; 1.0x2^32 = 4 294 967 296.0
dq 1.e10 ; 10 000 000 000.0
dq 1.e+10 ; synonymous with 1.e10
dq 1.e-10 ; 0.000 000 000 1
dt 3.141592653589793238462 ; pi
do 1.e+4000 ; IEEE 754r quad precision
</code></pre>
<h2>Known failures</h2>
<p>There are certain edge cases where Prism will fail.
There are always such cases in every regex-based syntax highlighter.
However, Prism dares to be open and honest about them.
If a failure is listed here, it doesnt mean it will never be fixed. This is more of a “known bugs” list, just with a certain type of bug.
</p>
<h3>Numbers with underscores</h3>
<pre><code>mov ax,1100_1000b
mov ax,1100_1000y
mov ax,0b1100_1000
mov ax,0y1100_1000
dd 1.222_222_222</code></pre>

View File

@ -0,0 +1,25 @@
<h2>Comments</h2>
<pre><code># This is a comment</code></pre>
<h2>Variables</h2>
<pre><code>fastcgi_param SERVER_NAME $server_name;</code></pre>
<h2>Server Block</h2>
<pre><code>
server { # simple reverse-proxy
listen 80;
server_name domain2.com www.domain2.com;
access_log logs/domain2.access.log main;
# serve static files
location ~ ^/(images|javascript|js|css|flash|media|static)/ {
root /var/www/virtual/big.server.com/htdocs;
expires 30d;
}
# pass requests for dynamic content to rails/turbogears/zope, et al
location / {
proxy_pass http://127.0.0.1:8080;
}
}</code></pre>

View File

@ -0,0 +1,222 @@
<h2>Comments</h2>
<pre><code># This is a comment</code></pre>
<h2>Strings</h2>
<pre><code>"This is a string."
"This is a string with \"quotes\" in it."
"""This is
a "multi-line"
string."""
""""A long string within quotes.""""
R"This is a raw string."
r"Some ""quotes"" inside a raw string."
r"""Raw strings
can also be multi-line."""
foo"This is a generalized raw string literal."
bar"""This is also
a generalized raw string literal."""</code></pre>
<h2>Characters</h2>
<pre><code>'a'
'\''
'\t'
'\15'
'\xFC'</code></pre>
<h2>Numbers</h2>
<pre><code>42
0xaf
0xf_2_c
0o07
0b1111_0000
0B0_10001110100_0000101001000111101011101111111011000101001101001001'f64
9_000'u
32.
32.1f32
32.e-5
32.2e+2
2'i16
2i16
0xfe'f32</code></pre>
<h2>Full example</h2>
<pre><code># Example from http://nim-by-example.github.io/oop_macro/
import macros
macro class*(head: expr, body: stmt): stmt {.immediate.} =
# The macro is immediate so that it doesn't
# resolve identifiers passed to it
var typeName, baseName: NimNode
if head.kind == nnkIdent:
# `head` is expression `typeName`
# echo head.treeRepr
# --------------------
# Ident !"Animal"
typeName = head
elif head.kind == nnkInfix and $head[0] == "of":
# `head` is expression `typeName of baseClass`
# echo head.treeRepr
# --------------------
# Infix
# Ident !"of"
# Ident !"Animal"
# Ident !"RootObj"
typeName = head[1]
baseName = head[2]
else:
quit "Invalid node: " & head.lispRepr
# echo treeRepr(body)
# --------------------
# StmtList
# VarSection
# IdentDefs
# Ident !"name"
# Ident !"string"
# Empty
# IdentDefs
# Ident !"age"
# Ident !"int"
# Empty
# MethodDef
# Ident !"vocalize"
# Empty
# Empty
# FormalParams
# Ident !"string"
# Empty
# Empty
# StmtList
# StrLit ...
# MethodDef
# Ident !"age_human_yrs"
# Empty
# Empty
# FormalParams
# Ident !"int"
# Empty
# Empty
# StmtList
# DotExpr
# Ident !"this"
# Ident !"age"
# create a new stmtList for the result
result = newStmtList()
# var declarations will be turned into object fields
var recList = newNimNode(nnkRecList)
# Iterate over the statements, adding `this: T`
# to the parameters of functions
for node in body.children:
case node.kind:
of nnkMethodDef, nnkProcDef:
# inject `this: T` into the arguments
let p = copyNimTree(node.params)
p.insert(1, newIdentDefs(ident"this", typeName))
node.params = p
result.add(node)
of nnkVarSection:
# variables get turned into fields of the type.
for n in node.children:
recList.add(n)
else:
result.add(node)
# The following prints out the AST structure:
#
# import macros
# dumptree:
# type X = ref object of Y
# z: int
# --------------------
# TypeSection
# TypeDef
# Ident !"X"
# Empty
# RefTy
# ObjectTy
# Empty
# OfInherit
# Ident !"Y"
# RecList
# IdentDefs
# Ident !"z"
# Ident !"int"
# Empty
result.insert(0,
if baseName == nil:
quote do:
type `typeName` = ref object of RootObj
else:
quote do:
type `typeName` = ref object of `baseName`
)
# Inspect the tree structure:
#
# echo result.treeRepr
# --------------------
# StmtList
# StmtList
# TypeSection
# TypeDef
# Ident !"Animal"
# Empty
# RefTy
# ObjectTy
# Empty
# OfInherit
# Ident !"RootObj"
# Empty <= We want to replace this
# MethodDef
# ...
result[0][0][0][2][0][2] = recList
# Lets inspect the human-readable version of the output
# echo repr(result)
# Output:
# type
# Animal = ref object of RootObj
# name: string
# age: int
#
# method vocalize(this: Animal): string =
# "..."
#
# method age_human_yrs(this: Animal): int =
# this.age
# ---
class Animal of RootObj:
var name: string
var age: int
method vocalize: string = "..."
method age_human_yrs: int = this.age # `this` is injected
class Dog of Animal:
method vocalize: string = "woof"
method age_human_yrs: int = this.age * 7
class Cat of Animal:
method vocalize: string = "meow"
# ---
var animals: seq[Animal] = @[]
animals.add(Dog(name: "Sparky", age: 10))
animals.add(Cat(name: "Mitten", age: 10))
for a in animals:
echo a.vocalize()
echo a.age_human_yrs()</code></pre>

View File

@ -0,0 +1,46 @@
<h2>Comments</h2>
<pre><code>#
# Single line comment
/* Multi-line
comment */</code></pre>
<h2>String</h2>
<pre><code>""
"foo\"bar"
"foo
bar"
''''
''foo'''bar''
''
foo
bar
''</code></pre>
<h2>String interpolation</h2>
<pre><code>"foo${42}bar"
"foo\${42}bar" # This is not interpolated
''foo${42}bar''
''foo''${42}bar'' # This is not interpolated</code></pre>
<h2>URLs and paths</h2>
<pre><code>ftp://ftp.nluug.nl/pub/gnu/hello/hello-2.1.1.tar.gz
http://example.org/foo.tar.bz2
/bin/sh
./builder.sh
~/foo.bar</code></pre>
<h2>Integers, booleans and null</h2>
<pre><code>0
42
true
false
null</code></pre>
<h2>Builtin functions</h2>
<pre><code>name = baseNameOf (toString url);
imap =
if builtins ? genList then
f: list: genList (n: f (n + 1) (elemAt list n)) (length list)</code></pre>

View File

@ -0,0 +1,18 @@
<h2>Comments</h2>
<pre><code>; Single line comment
# Single line comment
/* Multi-line
comment */</code></pre>
<h2>Strings</h2>
<pre><code>"foo \"bar\" baz"
'foo \'bar\' baz'</code></pre>
<h2>Variables</h2>
<pre><code>LicenseLangString myLicenseData ${LANG_ENGLISH} "bigtest.nsi"
LicenseData $(myLicenseData)
StrCmp $LANGUAGE ${LANG_ENGLISH} 0 +2</code></pre>
<h2>Compiler commands</h2>
<pre><code>!define VERSION "1.0.3"
!insertmacro MyFunc ""</code></pre>

View File

@ -0,0 +1,44 @@
<h2>Full example</h2>
<pre><code>#import &lt;UIKit/UIKit.h>
#import "Dependency.h"
@protocol WorldDataSource
@optional
- (NSString*)worldName;
@required
- (BOOL)allowsToLive;
@end
@interface Test : NSObject &lt;HelloDelegate, WorldDataSource> {
NSString *_greeting;
}
@property (nonatomic, readonly) NSString *greeting;
- (IBAction) show;
@end
@implementation Test
@synthesize test=_test;
+ (id) test {
return [self testWithGreeting:@"Hello, world!\nFoo bar!"];
}
+ (id) testWithGreeting:(NSString*)greeting {
return [[[self alloc] initWithGreeting:greeting] autorelease];
}
- (id) initWithGreeting:(NSString*)greeting {
if ( (self = [super init]) ) {
_greeting = [greeting retain];
}
return self;
}
- (void) dealloc {
[_greeting release];
[super dealloc];
}
@end</code></pre>

View File

@ -0,0 +1,59 @@
<h2>Comments</h2>
<pre><code>(* Simple comment *)
(* Multi-line
comment *)</code></pre>
<h2>Numbers</h2>
<pre><code>42
3.14159
42.
2.4E+2
10_452_102
0xf4 0xff_10_41
0o427
0b1100_1111_0000</code></pre>
<h2>Strings and characters</h2>
<pre><code>"Simple string."
"String with \"quotes\" in it."
'c' `c`
'\'' `\``
'\123' `\123`
'\xf4'</code></pre>
<h2>Full example</h2>
<pre><code>module Make_interval(Endpoint : Comparable) = struct
type t = | Interval of Endpoint.t * Endpoint.t
| Empty
(** [create low high] creates a new interval from [low] to
[high]. If [low > high], then the interval is empty *)
let create low high =
if Endpoint.compare low high > 0 then Empty
else Interval (low,high)
(** Returns true iff the interval is empty *)
let is_empty = function
| Empty -> true
| Interval _ -> false
(** [contains t x] returns true iff [x] is contained in the
interval [t] *)
let contains t x =
match t with
| Empty -> false
| Interval (l,h) ->
Endpoint.compare x l >= 0 && Endpoint.compare x h <= 0
(** [intersect t1 t2] returns the intersection of the two input
intervals *)
let intersect t1 t2 =
let min x y = if Endpoint.compare x y <= 0 then x else y in
let max x y = if Endpoint.compare x y >= 0 then x else y in
match t1,t2 with
| Empty, _ | _, Empty -> Empty
| Interval (l1,h1), Interval (l2,h2) ->
create (max l1 l2) (min h1 h2)
end ;;</code></pre>

View File

@ -0,0 +1,83 @@
<p>
To use this language, use the class <code class="language-none">"language-opencl"</code> for OpenCL kernel code.
Host code is automatically highlighted in <code class="language-none">"language-c"</code>
respectively <code class="language-none">"language-cpp"</code> classes.
</p>
<h2>OpenCL host code</h2>
<pre class="language-cpp"><code>// OpenCL functions, constants, etc. are also highlighted in OpenCL host code in the c or cpp language
cl::Event KernelFilterImages::runSingle(const cl::Image2D& imgSrc, SPImage2D& imgDst)
{
const size_t rows = imgSrc.getImageInfo<CL_IMAGE_HEIGHT>();
const size_t cols = imgSrc.getImageInfo<CL_IMAGE_WIDTH>();
ASSERT(rows > 0 && cols > 0, "The image object seems to be invalid, no rows/cols set");
ASSERT(imgSrc.getImageInfo<CL_IMAGE_FORMAT>().image_channel_data_type == CL_FLOAT, "Only float type images are supported");
ASSERT(imgSrc.getInfo<CL_MEM_FLAGS>() == CL_MEM_READ_ONLY || imgSrc.getInfo<CL_MEM_FLAGS>() == CL_MEM_READ_WRITE, "Can't read the input image");
imgDst = std::make_shared<cl::Image2D>(*context, CL_MEM_READ_WRITE, cl::ImageFormat(CL_R, CL_FLOAT), cols, rows);
cl::Kernel kernel(*program, "filter_single");
kernel.setArg(0, imgSrc);
kernel.setArg(1, *imgDst);
kernel.setArg(2, bufferKernel1);
kernel.setArg(3, kernel1.rows);
kernel.setArg(4, kernel1.rows / 2);
kernel.setArg(5, kernel1.cols);
kernel.setArg(6, kernel1.cols / 2);
kernel.setArg(7, border);
cl::Event eventFilter;
const cl::NDRange global(cols, rows);
queue->enqueueNDRangeKernel(kernel, cl::NullRange, global, cl::NullRange, &events, &eventFilter);
}</code></pre>
<h2>OpenCL kernel code</h2>
<pre><code>// CLK_ADDRESS_CLAMP_TO_EDGE = aaa|abcd|ddd
constant sampler_t sampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_CLAMP_TO_EDGE | CLK_FILTER_NEAREST;
typedef float type_single;
type_single filter_sum_single_3x3(read_only image2d_t imgIn,
constant float* filterKernel,
const int2 coordBase,
const int border)
{
type_single sum = (type_single)(0.0f);
const int rows = get_image_height(imgIn);
const int cols = get_image_width(imgIn);
int2 coordCurrent;
int2 coordBorder;
float color;
// Image patch is row-wise accessed
// Filter kernel is centred in the middle
#pragma unroll
for (int y = -ROWS_HALF_3x3; y <= ROWS_HALF_3x3; ++y) // Start at the top left corner of the filter
{
coordCurrent.y = coordBase.y + y;
#pragma unroll
for (int x = -COLS_HALF_3x3; x <= COLS_HALF_3x3; ++x) // And end at the bottom right corner
{
coordCurrent.x = coordBase.x + x;
coordBorder = borderCoordinate(coordCurrent, rows, cols, border);
color = read_imagef(imgIn, sampler, coordBorder).x;
const int idx = (y + ROWS_HALF_3x3) * COLS_3x3 + x + COLS_HALF_3x3;
sum += color * filterKernel[idx];
}
}
return sum;
}
kernel void filter_single_3x3(read_only image2d_t imgIn,
write_only image2d_t imgOut,
constant float* filterKernel,
const int border)
{
int2 coordBase = (int2)(get_global_id(0), get_global_id(1));
type_single sum = filter_sum_single_3x3(imgIn, filterKernel, coordBase, border);
write_imagef(imgOut, coordBase, sum);
}</code></pre>

View File

@ -0,0 +1,89 @@
<h2>Comments</h2>
<pre><code>%
% Foobar
/* Foo
bar */</code></pre>
<h2>Strings</h2>
<pre><code>""
"Foo \"bar\" baz"</code></pre>
<h2>Numbers</h2>
<pre><code>0
42
0154
0xBadFace
0B0101
3.14159
2e8
3.E~7
4.8E12
&0
&a
&\n
&\124</code></pre>
<h2>Functions and procedures</h2>
<pre><code>proc {Max X Y Z}
{Browse Z}
f(M Y)</code></pre>
<h2>Full example</h2>
<pre><code>proc {DisMember X Ys}
dis Ys = X|_ [] Yr in Ys = _|Yr {DisMember X Yr} end
end
class DataBase from BaseObject
attr d
meth init
d := {NewDictionary}
end
meth dic($) @d end
meth tell(I)
case {IsFree I.1} then
raise database(nonground(I)) end
else
Is = {Dictionary.condGet @d I.1 nil} in
{Dictionary.put @d I.1 {Append Is [I]}}
end
end
meth ask(I)
case {IsFree I} orelse {IsFree I.1} then
{DisMember I {Flatten {Dictionary.items @d}}}
else
{DisMember I {Dictionary.condGet @d I.1 nil}}
end
end
meth entries($)
{Dictionary.entries @d}
end
end
declare
proc {Dynamic ?Pred}
Pred = {New DataBase init}
end
proc {Assert P I}
{P tell(I)}
end
proc {Query P I}
{P ask(I)}
end
EdgeP = {Dynamic}
{ForAll
[edge(1 2)
edge(2 1) % Cycle
edge(2 3)
edge(3 4)
edge(2 5)
edge(5 6)
edge(4 6)
edge(6 7)
edge(6 8)
edge(1 5)
edge(5 1) % Cycle
]
proc {$ I} {Assert EdgeP I} end
}</code></pre>

View File

@ -0,0 +1,20 @@
<h2>Comments</h2>
<pre><code>\\ Single line comment
/* Multi line
comment */</code></pre>
<h2>Strings</h2>
<pre><code>""
"Foo \"bar\" baz"</code></pre>
<h2>Numbers</h2>
<pre><code>0.
42
3 . 14 15 9
5.2 E +12
.89</code></pre>
<h2>Ignored whitespaces</h2>
<pre><code>p r i n t ("hello")
if err(1/i, E, print (E))
a + = b \ / c</code></pre>

View File

@ -0,0 +1,88 @@
<h2>Comments</h2>
<pre><code>$foo[bar] # Some comment</code></pre>
<h2>Variables and functions</h2>
<pre><code>@navigation[]
$sections[^table::load[sections.cfg]]
$sections.uri</code></pre>
<h2>Literals</h2>
<pre><code>$foo(3+$bar)
^switch[$sMode]{
^case[def]{$result(true)}
}
^if(in "/news/"){}</code></pre>
<h2>Escape sequences</h2>
<pre><code>^^
^"
^;</code></pre>
<h2>Embedded in markup</h2>
<pre><code>&lt;nav>
&lt;ul>
^sections.menu{
&lt;li>
&lt;a href="$sections.uri">$sections.name&lt;/a>
&lt;/li>
}
&lt;/ul>
&lt;/nav></code></pre>
<h2>Full example</h2>
<pre><code>@CLASS
MyTable
@create[uParam]
^switch[$uParam.CLASS_NAME]{
^case[string;void]{$t[^table::create{$uParam}]}
^case[table;MyTable]{$t[^table::create[$uParam]]}
^case[DEFAULT]{^throw[MyTable;Unsupported type $uParam.CLASS_NAME]}
}
# method will return value in different calling contexts
@GET[sMode]
^switch[$sMode]{
^case[table]{$result[$t]}
^case[bool]{$result($t!=0)}
^case[def]{$result(true)}
^case[expression;double]{$result($t)}
^case[DEFAULT]{^throw[MyTable;Unsupported mode '$sMode']}
}
# method will handle access to the "columns"
@GET_DEFAULT[sName]
$result[$t.$sName]
# wrappers for all existing methods are required
@count[]
^t.count[]
@menu[jCode;sSeparator]
^t.menu{$jCode}[$sSeparator]
# new functionality
@remove[iOffset;iLimit]
$iLimit(^iLimit.int(0))
$t[^t.select(^t.offset[]<$iOffset || ^t.offset[]>=$iOffset+$iLimit)]</code></pre>
<h2>Known failures</h2>
<p>There are certain edge cases where Prism will fail.
There are always such cases in every regex-based syntax highlighter.
However, Prism dares to be open and honest about them.
If a failure is listed here, it doesnt mean it will never be fixed. This is more of a “known bugs” list, just with a certain type of bug.
</p>
<h3>Code block starting with a comment</h3>
<pre><code># Doesn't work
# Does work</code></pre>
<pre><code> # Does work when prefixed with a space</code></pre>
<h3>Comments inside expressions break literals and operators</h3>
<pre><code>^if(
$age>=4 # not too young
&& $age<=80 # and not too old
)</code></pre>

View File

@ -0,0 +1,65 @@
<h2>Comments</h2>
<pre><code>(* This is an
old style comment *)
{ This is a
Turbo Pascal comment }
// This is a Delphi comment.</code></pre>
<h2>Strings and characters</h2>
<pre><code>'This is a pascal string'
''
'a'
^G
#7
#$f4
'A tabulator character: '#9' is easy to embed'</code></pre>
<h2>Numbers</h2>
<pre><code>123
123.456
132.456e-789
132.456e+789
$7aff
&17
%11110101</code></pre>
<h2>Full example</h2>
<pre><code>Type
Str25 = String[25];
TBookRec = Record
Title, Author,
ISBN : Str25;
Price : Real;
End;
Procedure EnterNewBook(var newBook : TBookRec);
Begin
Writeln('Please enter the book details: ');
Write('Book Name: ');
Readln(newBook.Title);
Write('Author: ');
Readln(newBook.Author);
Write('ISBN: ');
Readln(newBook.ISBN);
Write('Price: ');
Readln(newBook.Price);
End;
Var
bookRecArray : Array[1..10] of TBookRec;
i : 1..10;
Begin
For i := 1 to 10 do
EnterNewBook(bookRecArray[i]);
Writeln('Thanks for entering the book details');
Write('Now choose a record to display from 1 to 10: ');
Readln(i);
Writeln('Here are the book details of record #',i,':');
Writeln;
Writeln('Title: ', bookRecArray[i].Title);
Writeln('Author: ', bookRecArray[i].Author);
Writeln('ISBN: ', bookRecArray[i].ISBN);
Writeln('Price: ', bookRecArray[i].Price);
Readln;
End.</code></pre>

View File

@ -0,0 +1,71 @@
<h2>Comments</h2>
<pre><code># Single line comment
=head1 Here There
Be Pods!
=cut</code></pre>
<h2>Strings</h2>
<pre><code>q/foo bar baz/;
q awhy not ?a;
qw(foo bar baz) q{foo bar baz}
q[foo bar baz] qq&lt;foo bar baz>
"foo bar baz" 'foo bar baz' `foo bar baz`</code></pre>
<h2>Regex</h2>
<pre><code>m/foo/ s/foo/bar/
m zfooz s zfoozbarz
qr(foo) m{foo} s(foo)(bar) s{foo}{bar}
m[foo] m&lt;foo> tr[foo][bar] s&lt;foo>&lt;bar>
/foo/i
</code></pre>
<h2>Variables</h2>
<pre><code>${^POSTMATCH}
$^V
$element_count = scalar(@whatever);
keys(%users) = 1000;
$1, $_, %!;</code></pre>
<h2>Numbers</h2>
<pre><code>12345
12345.67
.23E-10 # a very small number
3.14_15_92 # a very important number
4_294_967_296 # underscore for legibility
0xff # hex
0xdead_beef # more hex
0377 # octal (only numbers, begins with 0)
0b011011 # binary</code></pre>
<h2>Full example</h2>
<pre><code>sub read_config_file {
my ($class, $filename) = @_;
unless (defined $filename) {
my $home = File::HomeDir->my_home || '.';
$filename = File::Spec->catfile($home, '.pause');
return {} unless -e $filename and -r _;
}
my %conf;
if ( eval { require Config::Identity } ) {
%conf = Config::Identity->load($filename);
$conf{user} = delete $conf{username} unless $conf{user};
}
else { # Process .pause manually
open my $pauserc, '<', $filename
or die "can't open $filename for reading: $!";
while (<$pauserc>) {
chomp;
next unless $_ and $_ !~ /^\s*#/;
my ($k, $v) = /^\s*(\w+)\s+(.+)$/;
Carp::croak "multiple enties for $k" if $conf{$k};
$conf{$k} = $v;
}
}
return \%conf;
}</code></pre>

View File

@ -0,0 +1,67 @@
<h2>Comments</h2>
<pre><code>// Single line comment
/* Multi-line
comment */
# Shell-like comment</code></pre>
<h2>Strings</h2>
<pre><code>'foo \'bar\' baz'
"foo \"bar\" baz"
"a string # containing an hash"
$foo = &lt;&lt;&lt;FOO
Heredoc strings are supported too!
FOO;
$bar = &lt;&lt;&lt;'BAR'
And also Nowdoc strings
BAR;</code></pre>
<h2>Variables</h2>
<pre><code>$some_var = 5;
$otherVar = "Some text";
$null = null;
$false = false;</code></pre>
<h2>Functions</h2>
<pre><code>$json = json_encode($my_object);
$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);</code></pre>
<h2>Constants</h2>
<pre><code>define('MAXSIZE', 42);
echo MAXSIZE;
json_decode($json, false, 512, JSON_BIGINT_AS_STRING)</code></pre>
<h2>PHP 5.3+ support</h2>
<pre><code>namespace my\name;
$c = new \my\name\MyClass;
$arr = [1,2,3];
trait ezcReflectionReturnInfo {
function getReturnType() { /*1*/ }
function getReturnDescription() { /*2*/ }
}
function gen_one_to_three() {
for ($i = 1; $i <= 3; $i++) {
// Note that $i is preserved between yields.
yield $i;
}
}</code></pre>
<h2>PHP embedded in HTML</h2>
<pre><code>&lt;div class="&lt;?php echo $a ? 'foo' : 'bar'; ?>">
&lt;?php if($var &lt; 42) {
echo "Something";
} else {
echo "Something else";
} ?>
&lt;/div></code></pre>
<h2>String interpolation</h2>
<pre><code>$str = "This is $great!";
$foobar = "Another example: {${$foo->bar()}}";
$a = &lt;&lt;&lt;FOO
Hello $world!
FOO;
$b = &lt;&lt;&lt;"FOOBAR"
Interpolation inside Heredoc strings {$obj->values[3]->name}
FOOBAR;</code></pre>

Some files were not shown because too many files have changed in this diff Show More