Apache
LoadModule rewrite_module modules/mod_rewrite.so
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php [NC,L]
ExpiresActive On
ExpiresByType application/x-javascript "access plus 1 days"
Order Deny, Allow
Allow from All
<Location /maps/>
RewriteMap map txt:map.txt
RewriteMap lower int:tolower
RewriteCond %{REQUEST_URI} ^/([^/.]+)\.html$ [NC]
RewriteCond ${map:${lower:%1}|NOT_FOUND} !NOT_FOUND
RewriteRule .? /index.php?q=${map:${lower:%1}} [NC,L]
</Location>
HTML
<!DOCTYPE html>
<title>Title</title>
<style>body {width: 500px;}</style>
<script type="application/javascript">
function $init() {return true;}
</script>
<body>
<p checked class="title" id='title'>Title</p>
</body>
Bash
#!/bin/bash
ACCEPTED_HOSTS="/root/.hag_accepted.conf"
BE_VERBOSE=false
if [ "$UID" -ne 0 ]
then
echo "Superuser rights required"
exit 2
fi
genApacheConf(){
echo -e "# Host ${HOME_DIR}$1/$2 :"
}
echo '"quoted"' | tr -d \" > text.txt
CoffeeScript
grade = (student, period=(if b? then 7 else 6)) ->
if student.excellentWork
"A+"
else if student.okayStuff
if student.triedHard then "B" else "B-"
else
"C"
class Animal extends Being
constructor: (@name) ->
move: (meters) ->
alert @name + " moved #{meters}m."
C
#include<stdio.h>
#include<stdio.h>
void main()
{
FILE *fp1, *fp2;
char ch;
int pos;
if ((fp1 = fopen("File_1.txt", "r")) == NULL)
{
printf("\nFile cannot be opened.");
return;
}
else
{
printf("\nFile opened for copy...\n ");
}
fp2 = fopen("File_2.txt", "w");
fseek(fp1, 0L, SEEK_END);
pos = ftell(fp1);
fseek(fp1, 0L, SEEK_SET);
while (pos--)
{
ch = fgetc(fp1);
fputc(ch, fp2);
}
fcloseall();
}
C++
#include <iostream>
int main(int argc, char *argv[]) {
for (auto i = 0; i < 0xFFFF; i++)
cout << "Hello, World!" << endl;
char c = '\n';
unordered_map <string, vector<string> > m;
m["key"] = "\\\\";
return -2e3 + 12l;
}
C#
using System.IO.Compression;
#pragma warning disable 414, 3021
namespace MyApplication
{
[Obsolete("...")]
class Program : IInterface
{
public static List<int> JustDoIt(int count)
{
Span<int> numbers = stackalloc int[length];
Console.WriteLine($"Hello {Name}!");
return new List<int>(new int[] { 1, 2, 3 })
}
}
}
CSS
@font-face {
font-family: Chunkfive; src: url('Chunkfive.otf');
}
body, .usertext {
color: #F0F0F0; background: #600;
font-family: Chunkfive, sans;
--heading-1: 30px/32px Helvetica, sans-serif;
}
@import url(print.css);
@media print {
a[href^=http]::after {
content: attr(href)
}
}
Markdown
# hello world
you can write text [with links](http://example.com) inline or [link references][1].
* one _thing_ has *em*phasis
* two __things__ are **bold**
[1]: http://example.com
---
hello world
===========
<this_is inline="xml"></this_is>
> markdown is so cool
so are code segments
1. one thing (yeah!)
2. two thing `i can write code`, and `more` wipee!
Diff
@@ -1,8 +1,7 @@
hljs.LANGUAGES.ini =
{
case_insensitive: true,
- defaultMode:
- {
+ defaultMode: {
contains: ['comment', 'title', 'setting'],
illegal: '[^\\s]'
},
*** 1,3 ****
--- 1,9 ----
+ This is an important
+ notice! It should
+ therefore be located at
+ the beginning of this
+ document!
! compress the size of the
! changes.
It is important to spell
Ruby
class Greeter
def initialize(name)
@name = name.capitalize
end
def salute
puts "Hello #{@name}!"
end
end
g = Greeter.new("world")
g.salute
Go
package main
import "fmt"
func main() {
ch := make(chan float64)
ch <- 1.0e10
x, ok := <- ch
defer fmt.Println(`exitting now\`)
go println(len("hello world!"))
return
}
HTTP
POST /task?id=1 HTTP/1.1
Host: example.org
Content-Type: application/json; charset=utf-8
Content-Length: 137
{
"status": "ok",
"extended": true,
"results": [
{"value": 0, "type": "int64"},
{"value": 1.0e+3, "type": "decimal"}
]
}
TOML, INI
[package]
name = "some_name"
authors = ["Author"]
description = "This is \
a description"
[[lib]]
name = ${NAME}
default = True
auto = no
counter = 1_000
Java
package l2f.gameserver.model;
public abstract strictfp class L2Char extends L2Object {
public static final Short ERROR = 0x0001;
public void moveTo(int x, int y, int z) {
_ai = null;
log("Should not be called");
if (1 > 5) {
return;
}
}
}
JavaScript
function $initHighlight(block, cls) {
try {
if (cls.search(/\bno\-highlight\b/) != -1)
return process(block, true, 0x0F) +
` class="${cls}"`;
} catch (e) {
}
for (var i = 0 / 2; i < classes.length; i++) {
if (checkCondition(classes[i]) === undefined)
console.log('undefined');
}
return (
<div>
<web-component>{block}</web-component>
</div>
)
}
export $initHighlight;
JSON
[
{
"title": "apples",
"count": [12000, 20000],
"description": {"text": "...", "sensitive": false}
},
{
"title": "oranges",
"count": [17500, null],
"description": {"text": "...", "sensitive": false}
}
]
Kotlin
import kotlin.lang.test
interface A {
fun x()
}
fun xxx(): Int {
return 888
}
public fun main(args: Array<String>) {
}
Less
@import "fruits";
@rhythm: 1.5em;
@media screen and (min-resolution: 2dppx) {
body {font-size: 125%}
}
section > .foo + #bar:hover [href*="less"] {
margin: @rhythm 0 0 @rhythm;
padding: calc(5% + 20px);
background: #f00ba7 url(http://placehold.alpha-centauri/42.png) no-repeat;
background-image: linear-gradient(-135deg, wheat, fuchsia) !important ;
background-blend-mode: multiply;
}
@font-face {
font-family: 'Omega';
src: url('../fonts/omega-webfont.woff?v=2.0.2');
}
.icon-baz::before {
display: inline-block;
font-family: "Omega", Alpha, sans-serif;
content: "\f085";
color: rgba(98, 76 , 231, .75);
}
Lisp
(defun approxeq (x y)
"(approxeq x y) true if value of x is within 0.001% of value of y"
(let ((precision 0.00001)
(denom x))
(diffratio 0)
(cond
((not (numberp x)) (eq x y))
((not (numberp y)) nil)
((= x y) t)
(t (block
(setf denom (if (= 0 x) y) x)
(setf diffratio (abs (/ (- x y) denom)))
(if (< diffratio precision) t nil)
)))))
Lua
local signal_mt = {
__index = {
register = table.insert
}
}
function signal_mt.__index:emit(... )
for _, slot in ipairs(self) do
slot(self, ...)
end
end
local function create_signal()
return setmetatable({}, signal_mt)
end
local signal = create_signal()
signal:register(function(signal, ...)
print(...)
end)
signal:emit('Answer to Life, the Universe, and Everything:', 42)
[==[ Nested
[=[ multi-line
[[ string
]] ]=] ]==]
Makefile
BUILDDIR = _build
EXTRAS ?= $(BUILDDIR)/extras
.PHONY: main clean
main:
@echo "Building main facility..."
build_main $(BUILDDIR)
clean:
rm -rf $(BUILDDIR)/*
Perl
sub load
{
my $flds = $c->db_load($id,@_) || do {
Carp::carp "Can`t load (class: $c, id: $id): '$!'"; return undef
};
my $o = $c->_perl_new();
$id12 = $id / 24 / 3600;
$o->{'ID'} = $id12 + 123;
my $p = $o->props;
my $vt;
$string =~ m/^sought_text$/;
$items = split //, 'abc';
$string //= "bar";
for my $key (keys %$p)
{
if(${$vt.'::property'}) {
$o->{$key . '_real'} = $flds->{$key};
tie $o->{$key}, 'CMSBuilder::Property', $o, $key;
}
}
$o->save if delete $o->{'_save_after_load'};
my $g = glob("/usr/bin/*");
return $o;
}
__DATA__
<!DOCTYPE html>
<html>
<head><title><%= title %></title></head>
<body><%= content %></body>
</html>
__END__
Nginx
user www www;
worker_processes 2;
pid /var/run/nginx.pid;
error_log /var/log/nginx.error_log debug | info | notice | warn | error | crit;
events {
connections 2000;
use kqueue | rtsig | epoll | /dev/poll | select | poll;
}
http {
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $bytes_sent '
'"$http_referer" "$http_user_agent" '
'"$gzip_ratio"';
send_timeout 3m;
client_header_buffer_size 1k;
gzip on;
gzip_min_length 1100;
server {
server_name one.example.com www.one.example.com;
access_log /var/log/nginx.access_log main;
rewrite (.*) /index.php?page=$1 break;
location / {
proxy_pass http://127.0.0.1/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
charset koi8-r;
}
location /api/ {
fastcgi_pass 127.0.0.1:9000;
}
location ~* \.(jpg|jpeg|gif)$ {
root /spool/www;
}
}
}
Objective-C
#import <UIKit/UIKit.h>
#import "Dependency.h"
@protocol WorldDataSource
@optional
- (NSString*)worldName;
@required
- (BOOL)allowsToLive;
@end
@property (nonatomic, readonly) NSString *title;
- (IBAction) show;
@end
PHP
require_once 'Zend/Uri/Http.php';
namespace Location\Web;
interface Factory
{
static function _factory();
}
abstract class URI extends BaseURI implements Factory
{
abstract function test();
public static $st1 = 1;
const ME = "Yo";
var $list = NULL;
private $var;
static public function _factory($stats = array(), $uri = 'http')
{
echo __METHOD__;
$uri = explode(':', $uri, 0b10);
$schemeSpecific = isset($uri[1]) ? $uri[1] : '';
$desc = 'Multi
line description';
if (!ctype_alnum($scheme)) {
throw new Zend_Uri_Exception('Illegal scheme');
}
$this->var = 0 - self::$st;
$this->list = list(Array("1"=> 2, 2=>self::ME, 3 => \Location\Web\URI::class));
return [
'uri' => $uri,
'value' => null,
];
}
}
echo URI::ME . URI::$st1;
PHP Template
<html>
</html>
<body>
<?php
echo "Hello, world!";
?>
</body>
.properties
key1 = value1
key2 : value2
key3 value3
key\ spaces multiline\
value4
empty_key
\:\= = value5
Python
@requires_authorization(roles=["ADMIN"])
def somefunc(param1='', param2=0):
r'''A docstring'''
if param1 > param2:
print 'Gre\'ater'
return (param2 - param1 + 1 + 0b10l) or None
class SomeClass:
pass
>>> message = '''interpreter
... prompt'''
Python REPL
>>> v = "foo = 42"
>>> v
"foo = 42"
>>> print(v)
foo = 42
>>> print(repr(v).rstrip('"'))
"foo = 42
>>> print(repr(v).lstrip('"'))
foo = 42"
>>> """
... abc
... """
>>> def test():
... pass
R
require(stats)
centre <- function(x, type) {
switch(type,
mean = mean(x),
median = median(x),
trimmed = mean(x, trim = .1))
}
x <- rcauchy(10)
centre(x, "mean")
library(ggplot2)
models <- tibble::tribble(
~model_name, ~ formula,
"length-width", Sepal.Length ~ Petal.Width + Petal.Length,
"interaction", Sepal.Length ~ Petal.Width * Petal.Length
)
iris %>%
nest_by(Species) %>%
left_join(models, by = character()) %>%
rowwise(Species, model_name) %>%
mutate(model = list(lm(formula, data = data))) %>%
summarise(broom::glance(model))
Rust
#[derive(Debug)]
pub enum State {
Start,
Transient,
Closed,
}
impl From<&'a str> for State {
fn from(s: &'a str) -> Self {
match s {
"start" => State::Start,
"closed" => State::Closed,
_ => unreachable!(),
}
}
}
Scala
package futures
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.util.{Failure, Success}
object MultipleFutures extends App {
val startTime = currentTime
val aaplFuture = getStockPrice("AAPL")
val amznFuture = getStockPrice("AMZN")
val googFuture = getStockPrice("GOOG")
val result: Future[(Double, Double, Double)] = for {
aapl <- aaplFuture
amzn <- amznFuture
goog <- googFuture
} yield (aapl, amzn, goog)
result.onComplete {
case Success(x) => {
val totalTime = deltaTime(startTime)
println(s"In Success case, time delta: ${totalTime}")
println(s"The stock prices are: $x")
}
case Failure(e) => e.printStackTrace
}
sleep(5000)
def sleep(time: Long): Unit = Thread.sleep(time)
def getStockPrice(stockSymbol: String): Future[Double] = Future {
val r = scala.util.Random
val randomSleepTime = r.nextInt(3000)
println(s"For $stockSymbol, sleep time is $randomSleepTime")
val randomPrice = r.nextDouble * 1000
sleep(randomSleepTime)
randomPrice
}
def currentTime = System.currentTimeMillis()
def deltaTime(t0: Long) = currentTime - t0
}
SCSS
@import "compass/reset";
$colorGreen: #008000;
$colorGreenDark: darken($colorGreen, 10);
@mixin container {
max-width: 980px;
}
@mixin button($color:green) {
@if ($color == green) {
background-color: #008000;
}
@else if ($color == red) {
background-color: #B22222;
}
}
button {
@include button(red);
}
div,
.navbar,
#header,
input[type="input"] {
font-family: "Helvetica Neue", Arial, sans-serif;
width: auto;
margin: 0 auto;
display: block;
}
.row-12 > [class*="spans"] {
border-left: 1px solid #B5C583;
}
ul {
width: 100%;
padding: {
left: 5px; right: 5px;
}
li {
float: left; margin-right: 10px;
.home {
background: url('http://placehold.it/20') scroll no-repeat 0 0;
}
}
}
.banner {
@extend .container;
}
a {
color: $colorGreen;
&:hover { color: $colorGreenDark; }
&:visited { color: #c458cb; }
}
@for $i from 1 through 5 {
.span#{$i} {
width: 20px*$i;
}
}
@mixin mobile {
@media screen and (max-width : 600px) {
@content;
}
}
Shell session
$ echo $EDITOR
vim
$ git checkout master
Switched to branch 'master'
Your branch is up-to-date with 'origin/master'.
$ git push
Everything up-to-date
$ echo 'All
> done!'
All
done!
$ echo $EDITOR
vim
$ git checkout master
Switched to branch 'master'
Your branch is up-to-date with 'origin/master'.
$ git push
Everything up-to-date
$ echo 'All
> done!'
All
done!
SQL
CREATE TABLE "topic" (
"id" serial NOT NULL PRIMARY KEY,
"forum_id" integer NOT NULL,
"subject" varchar(255) NOT NULL
);
ALTER TABLE "topic"
ADD CONSTRAINT forum_id FOREIGN KEY ("forum_id")
REFERENCES "forum" ("id");
insert into "topic" ("forum_id", "subject")
values (2, 'D''artagnian');
Swift
import Foundation
@objc class Person: Entity {
var name: String!
var age: Int!
init(name: String, age: Int) {
}
func description(offset: Int = 0) -> String {
return "\(name) is \(age + offset) years old"
}
}
YAML
---
string_1: "Bar"
string_2: 'bar'
string_3: bar
inline_keys_ignored: sompath/name/file.jpg
keywords_in_yaml:
- true
- false
- TRUE
- FALSE
- 21
- 21.0
- !!str 123
"quoted_key": &foobar
bar: foo
foo:
"foo": bar
reference: *foobar
multiline_1: |
Multiline
String
multiline_2: >
Multiline
String
multiline_3: "
Multiline string
"
ansible_variables: "foo {{variable}}"
array_nested:
- a
- b: 1
c: 2
- b
- comment
TypeScript
class MyClass {
public static myValue: string;
constructor(init: string) {
this.myValue = init;
}
}
import fs = require("fs");
module MyModule {
export interface MyInterface extends Other {
myProperty: any;
}
}
declare magicNumber number;
myArray.forEach(() => { });
VisualBasic .NET
Imports System
Imports System.IO
#Const DEBUG = True
Namespace Highlighter.Test
Public Class Program
Protected Shared hello As Integer = 3
Private Const ABC As Boolean = False
#Region "Code"
<STAThread()> _
Public Shared Sub Main(ByVal args() As String, ParamArray arr As Object) Handles Form1.Click
On Error Resume Next
If ABC Then
While ABC : Console.WriteLine() : End While
For i As Long = 0 To 1000 Step 123
Try
System.Windows.Forms.MessageBox.Show(CInt("1").ToString())
Catch ex As Exception
Dim exp = CType(ex, IOException)
REM ORZ
Return
End Try
Next
Else
Dim l As New System.Collections.List<String>()
SyncLock l
If TypeOf l Is Decimal And l IsNot Nothing Then
RemoveHandler button1.Paint, delegate
End If
Dim d = New System.Threading.Thread(AddressOf ThreadProc)
Dim a = New Action(Sub(x, y) x + y)
Static u = From x As String In l Select x.Substring(2, 4) Where x.Length > 0
End SyncLock
Do : Laugh() : Loop Until hello = 4
End If
End Sub
#End Region
End Class
End Namespace