### Start HTTP Service Source: https://github.com/tommylemon/apiauto/blob/master/README.md Navigate to the 'js' directory and start the HTTP service. If packages are missing, install them using 'npm i xxx'. ```sh cd js node server.js ``` -------------------------------- ### Puppet Module Example Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/puppet/index.html This snippet demonstrates a basic Puppet module for installing and configuring AutoMySQLBackup. It includes class parameters, validation of paths, and resource declarations for files and directories. ```puppet # == Class: automysqlbackup # # Puppet module to install AutoMySQLBackup for periodic MySQL backups. # # class { # 'automysqlbackup': # backup_dir => '/mnt/backups', # } class automysqlbackup ( $bin_dir = $automysqlbackup::params::bin_dir, $etc_dir = $automysqlbackup::params::etc_dir, $backup_dir = $automysysqlbackup::params::backup_dir, $install_multicore = undef, $config = {}, $config_defaults = {}, ) inherits automysqlbackup::params { # Ensure valid paths are assigned validate_absolute_path($bin_dir) validate_absolute_path($etc_dir) validate_absolute_path($backup_dir) # Create a subdirectory in /etc for config files file { $etc_dir: ensure => directory, owner => 'root', group => 'root', mode => '0750', } # Create an example backup file, useful for reference file { "${etc_dir}/automysqlbackup.conf.example": ensure => file, owner => 'root', group => 'root', mode => '0660', source => 'puppet:///modules/automysqlbackup/automysqlbackup.conf', } # Add files from the developer file { "${etc_dir}/AMB_README": ensure => file, source => 'puppet:///modules/automysqlbackup/AMB_README', } file { "${etc_dir}/AMB_LICENSE": ensure => file, source => 'puppet:///modules/automysqlbackup/AMB_LICENSE', } # Install the actual binary file file { "${bin_dir}/automysqlbackup": ensure => file, owner => 'root', group => 'root', mode => '0755', source => 'puppet:///modules/automysqlbackup/automysqlbackup', } # Create the base backup directory file { $backup_dir: ensure => directory, owner => 'root', group => 'root', mode => '0755', } # If you'd like to keep your config in hiera and pass it to this class if !empty($config) { create_resources('automysqlbackup::backup', $config, $config_defaults) } # If using RedHat family, must have the RPMforge repo's enabled if $install_multicore { package { ['pigz', 'pbzip2']: ensure => installed } } } ``` -------------------------------- ### Stylus Syntax Example Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/stylus/index.html Demonstrates basic Stylus syntax including variables, mixins, and nested selectors. ```stylus /* Stylus mode */ #id .class article font-family: Arial, sans-serif #id, .class, article { font-family: Arial, sans-serif; } // Variables font-size-base = 16px line-height-base = 1.5 font-family-base = "Helvetica Neue", Helvetica, Arial, sans-serif text-color = lighten(#000, 20%) body { font: 400 16px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif; color: #333; } // Variables link-color = darken(#428bca, 6.5%) link-hover-color = darken(link-color, 15%) link-decoration = none link-hover-decoration = false // Mixin tab-focus() { outline: thin dotted; outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px; } a { color: link-color if link-decoration { text-decoration: link-decoration } &:hover, &:focus { color: link-hover-color } &:focus { if link-hover-decoration { text-decoration: link-hover-decoration } tab-focus() } } a:hover, a:focus { color: #2f6ea7; } a:focus { outline: thin dotted; outline: 5px auto -webkit-focus-ring-color; outline-offset: -2px; } ``` -------------------------------- ### Install Node.js and Koa Source: https://github.com/tommylemon/apiauto/blob/master/README.md Install Node.js version 7 and the Koa package. Ensure Node.js is installed from nodejs.org. ```sh nvm install 7 npm i koa ``` -------------------------------- ### Basic CodeMirror Initialization Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/diff/index.html A minimal example of initializing CodeMirror from a textarea element. This serves as a basic setup for using CodeMirror in a web page. ```javascript var editor = CodeMirror.fromTextArea(document.getElementById("code"), {}); ``` -------------------------------- ### Dockerfile Syntax Highlighting Example Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/dockerfile/index.html This is a sample Dockerfile demonstrating various instructions and syntax elements. It is used for syntax highlighting by the Dockerfile mode. ```dockerfile # Install Ghost blogging platform and run development environment # # VERSION 1.0.0 FROM ubuntu:12.10 MAINTAINER Amer Grgic "amer@livebyt.es" WORKDIR /data/ghost # Install dependencies for nginx installation RUN apt-get update RUN apt-get install -y python g++ make software-properties-common --force-yes RUN add-apt-repository ppa:chris-lea/node.js RUN apt-get update # Install unzip RUN apt-get install -y unzip # Install curl RUN apt-get install -y curl # Install nodejs & npm RUN apt-get install -y rlwrap RUN apt-get install -y nodejs # Download Ghost v0.4.1 RUN curl -L https://ghost.org/zip/ghost-latest.zip -o /tmp/ghost.zip # Unzip Ghost zip to /data/ghost RUN unzip -uo /tmp/ghost.zip -d /data/ghost # Add custom config js to /data/ghost ADD ./config.example.js /data/ghost/config.js # Install Ghost with NPM RUN cd /data/ghost/ && npm install --production # Expose port 2368 EXPOSE 2368 # Run Ghost CMD ["npm","start"] ``` -------------------------------- ### Objective-C Example with Comments and C Arrays Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/clike/index.html Shows Objective-C syntax including multi-line comments, import statements, class implementations, and C-style character arrays. This example is relevant for Objective-C development. ```objectivec /* This is a longer comment That spans two lines */ #import @implementation YourAppDelegate // This is a one-line comment - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ char myString[] = "This is a C character array"; int test = 5; return YES; } ``` -------------------------------- ### XQuery Syntax Example Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/xquery/index.html Demonstrates basic XQuery syntax including version declaration, comments, let bindings, XML construction, and function calls. ```xquery xquery version "1.0-ml"; (: this is : a "comment" :) let $let := "test"function() $var {function()} {$var} let $joe:=1 return element element { attribute attribute { 1 }, element test { 'a' }, attribute foo { "bar" }, fn:doc()[ foo/@bar eq $let ], //x } (: a more 'evil' test :) (: Modified Blakeley example (: with nested comment :) ... :) ``` -------------------------------- ### Install Missing Packages Source: https://github.com/tommylemon/apiauto/blob/master/README.md If the HTTP service reports missing packages, install them using npm. ```sh npm i xxx ``` -------------------------------- ### Hxml Mode Example Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/haxe/index.html Shows Hxml syntax highlighting, commonly used for compiler arguments and project configuration. ```hxml -cp test -js path/to/file.js #-remap nme:flash --next -D source-map-content -cmd 'test' -lib lime ``` -------------------------------- ### Asterisk Dialplan Configuration Example Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/asterisk/index.html This snippet shows a typical Asterisk extensions.conf file structure, including general settings, context definitions, and example extensions for various call scenarios like local calls, voicemail, and external demos. ```asterisk ; extensions.conf - the Asterisk dial plan ; [general] ; ; If static is set to no, or omitted, then the pbx_config will rewrite ; this file when extensions are modified. Remember that all comments ; made in the file will be lost when that happens. static=yes #include "/etc/asterisk/additional_general.conf" [iaxprovider] switch => IAX2/user:[key]@myserver/mycontext [dynamic] #exec /usr/bin/dynamic-peers.pl [trunkint] ; ; International long distance through trunk ; exten => _9011.,1,Macro(dundi-e164,${EXTEN:4}) exten => _9011.,n,Dial(${GLOBAL(TRUNK)}/${FILTER(0-9,${EXTEN:${GLOBAL(TRUNKMSD)}})}) [local] ; ; Master context for local, toll-free, and iaxtel calls only ; ignorepat => 9 include => default [demo] include => stdexten ; ; We start with what to do when a call first comes in. ; exten => s,1,Wait(1) ; Wait a second, just for fun same => n,Answer ; Answer the line same => n,Set(TIMEOUT(digit)=5) ; Set Digit Timeout to 5 seconds same => n,Set(TIMEOUT(response)=10) ; Set Response Timeout to 10 seconds same => n(restart),BackGround(demo-congrats) ; Play a congratulatory message same => n(instruct),BackGround(demo-instruct) ; Play some instructions same => n,WaitExten ; Wait for an extension to be dialed. exten => 2,1,BackGround(demo-moreinfo) ; Give some more information. exten => 2,n,Goto(s,instruct) exten => 3,1,Set(LANGUAGE()=fr) ; Set language to french exten => 3,n,Goto(s,restart) ; Start with the congratulations exten => 1000,1,Goto(default,s,1) ; ; ; We also create an example user, 1234, who is on the console and has ; voicemail, etc. ; exten => 1234,1,Playback(transfer,skip) ; "Please hold while..." ; (but skip if channel is not up) exten => 1234,n,Gosub(${EXTEN},stdexten(${GLOBAL(CONSOLE)})) exten => 1234,n,Goto(default,s,1) ; exited Voicemail exten => 1235,1,Voicemail(1234,u) ; Right to voicemail exten => 1236,1,Dial(Console/dsp) ; Ring forever exten => 1236,n,Voicemail(1234,b) ; Unless busy ; ; # for when they're done with the demo ; exten => #,1,Playback(demo-thanks) ; "Thanks for trying the demo" exten => #,n,Hangup ; Hang them up. ; ; A timeout and "invalid extension rule" ; exten => t,1,Goto(#,1) ; If they take too long, give up exten => i,1,Playback(invalid) ; "That's not valid, try again" ; ; Create an extension, 500, for dialing the ; Asterisk demo. ; exten => 500,1,Playback(demo-abouttotry); Let them know what's going on exten => 500,n,Dial(IAX2/guest@pbx.digium.com/s@default) ; Call the Asterisk demo exten => 500,n,Playback(demo-nogo) ; Couldn't connect to the demo site exten => 500,n,Goto(s,6) ; Return to the start over message. ; ; Create an extension, 600, for evaluating echo latency. ; exten => 600,1,Playback(demo-echotest) ; Let them know what's going on exten => 600,n,Echo ; Do the echo test exten => 600,n,Playback(demo-echodone) ; Let them know it's over exten => 600,n,Goto(s,6) ; Start over ; ; You can use the Macro Page to intercom a individual user exten => 76245,1,Macro(page,SIP/Grandstream1) ; or if your peernames are the same as extensions exten => _7XXX,1,Macro(page,SIP/${EXTEN}) ; ; ; System Wide Page at extension 7999 exten => 7999,1,Set(TIMEOUT(absolute)=60) exten => 7999,2,Page(Local/Grandstream1@page&Local/Xlite1@page&Local/1234@page/n) ; Give voicemail at extension 8500 ; exten => 8500,1,VoicemailMain exten => 8500,n,Goto(s,6) ``` -------------------------------- ### Haxe Mode Example Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/haxe/index.html Demonstrates Haxe syntax highlighting with various language features like classes, functions, enums, and conditional compilation. ```haxe import one.two.Three; @attr("test") class Foo extends Three { public function new() { noFoo = 12; } public static inline function doFoo(obj:{k:Int, l:Float}):Int { for(i in 0...10) { obj.k++; trace(i); var var1 = new Array(); if(var1.length > 1) throw "Error"; } // The following line should not be colored, the variable is scoped out var1; /* Multi line * Comment test */ return obj.k; } private function bar():Void { #if flash var t1:String = "1.21"; #end try { doFoo({k:3, l:1.2}); } catch (e : String) { trace(e); } var t2:Float = cast(3.2); var t3:haxe.Timer = new haxe.Timer(); var t4 = {k:Std.int(t2), l:Std.parseFloat(t1)}; var t5 = ~/123+.*$/i; doFoo(t4); untyped t1 = 4; bob = new Foo } public var okFoo(default, never):Float; var noFoo(getFoo, null):Int; function getFoo():Int { return noFoo; } public var three:Int; } enum Color { red; green; blue; grey( v : Int ); rgb (r:Int,g:Int,b:Int); } ``` -------------------------------- ### Verilog/SystemVerilog Syntax Examples Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/verilog/index.html Illustrates various Verilog and SystemVerilog constructs including literals, macro definitions, module definitions, class definitions, and built-in system tasks. ```verilog // Literals 1'b0 1'bx 1'bz 16'hDC78 'hdeadbeef 'b0011xxzz 1234 32'd5678 3.4e6 -128.7 // Macro definition `define BUS_WIDTH = 8; // Module definition module block( input clk, input rst_n, input [`BUS_WIDTH-1:0] data_in, output [`BUS_WIDTH-1:0] data_out ); always @(posedge clk or negedge rst_n) begin if (~rst_n) begin data_out <= 8'b0; end else begin data_out <= data_in; end if (~rst_n) data_out <= 8'b0; else data_out <= data_in; if (~rst_n) begin data_out <= 8'b0; end else begin data_out <= data_in; end end endmodule // Class definition class test; /** * Sum two integers */ function int sum(int a, int b); int result = a + b; string msg = $sformatf("%d + %d = %d", a, b, result); $display(msg); return result; endfunction task delay(int num_cycles); repeat(num_cycles) #1; endtask endclass ``` -------------------------------- ### LESS Mode Example Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/css/less.html Demonstrates the basic structure and syntax of LESS, including media queries, pseudo-classes, nested rules, and variable usage. This snippet showcases various LESS features for styling. ```less @media screen and (device-aspect-ratio: 16/9) { … } @media screen and (device-aspect-ratio: 1280/720) { … } @media screen and (device-aspect-ratio: 2560/1440) { … } html:lang(fr-be) tr:nth-child(2n+1) /* represents every odd row of an HTML table */ img:nth-of-type(2n+1) { float: right; } img:nth-of-type(2n) { float: left; } body > h2:not(:first-of-type):not(:last-of-type) html|*:not(:link):not(:visited) *|*:not(:hover) p::first-line { text-transform: uppercase } @namespace foo url(http://www.example.com); foo|h1 { color: blue } /* first rule */ span[hello="Ocean"][goodbye="Land"] E[foo]{ padding:65px; } input[type="search"]::-webkit-search-decoration, input[type="search"]::-webkit-search-cancel-button { -webkit-appearance: none; /* Inner-padding issues in Chrome OSX, Safari 5 */ } button::-moz-focus-inner, input::-moz-focus-inner { /* Inner padding and border oddities in FF3/4 */ padding: 0; border: 0; } .btn { /* reset here as of 2.0.3 due to Recess property order */ border-color: #ccc; border-color: rgba(0,0,0,.1) rgba(0,0,0,.1) rgba(0,0,0,.25); } fieldset span button, fieldset span input[type="file"] { font-size:12px; font-family:Arial, Helvetica, sans-serif; } .rounded-corners (@radius: 5px) { border-radius: @radius; -webkit-border-radius: @radius; -moz-border-radius: @radius; } @import url("something.css"); @light-blue: hsl(190, 50%, 65%); #menu { position: absolute; width: 100%; z-index: 3; clear: both; display: block; background-color: @blue; height: 42px; border-top: 2px solid lighten(@alpha-blue, 20%); border-bottom: 2px solid darken(@alpha-blue, 25%); .box-shadow(0, 1px, 8px, 0.6); -moz-box-shadow: 0 0 0 #000; /* Because firefox sucks. */ &.docked { background-color: hsla(210, 60%, 40%, 0.4); } &:hover { background-color: @blue; } #dropdown { margin: 0 0 0 117px; padding: 0; padding-top: 5px; display: none; width: 190px; border-top: 2px solid @medium; color: @highlight; border: 2px solid darken(@medium, 25%); border-left-color: darken(@medium, 15%); border-right-color: darken(@medium, 15%); border-top-width: 0; background-color: darken(@medium, 10%); ul { padding: 0px; } li { font-size: 14px; display: block; text-align: left; padding: 0; border: 0; a { display: block; padding: 0px 15px; text-decoration: none; color: white; &:hover { background-color: darken(@medium, 15%); text-decoration: none; } } } .border-radius(5px, bottom); .box-shadow(0, 6px, 8px, 0.5); } } ``` -------------------------------- ### SCSS Example Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/css/scss.html This snippet demonstrates a typical SCSS structure including variables, nested rules, mixins, and imports. It's useful for understanding SCSS syntax. ```scss /* Some example SCSS */ @import "compass/css3"; $variable: #333; $blue: #3bbfce; $margin: 16px; .content-navigation { #nested { background-color: black; } border-color: $blue; color: darken($blue, 9%); } .border { padding: $margin / 2; margin: $margin / 2; border-color: $blue; } @mixin table-base { th { text-align: center; font-weight: bold; } td, th {padding: 2px} } table.hl { margin: 2em 0; td.ln { text-align: right; } } li { font: { family: serif; weight: bold; size: 1.2em; } } @mixin left($dist) { float: left; margin-left: $dist; } #data { @include left(10px); @include table-base; } .source { @include flow-into(target); border: 10px solid green; margin: 20px; width: 200px; } .new-container { @include flow-from(target); border: 10px solid red; margin: 20px; width: 200px; } body { margin: 0; padding: 3em 6em; font-family: tahoma, arial, sans-serif; color: #000; } @mixin yellow() { background: yellow; } .big { font-size: 14px; } .nested { @include border-radius(3px); @extend .big; p { background: whitesmoke; a { color: red; } } } #navigation a { font-weight: bold; text-decoration: none !important; } h1 { font-size: 2.5em; } h2 { font-size: 1.7em; } h1:before, h2:before { content: "::"; } code { font-family: courier, monospace; font-size: 80%; color: #418A8A; } ``` -------------------------------- ### Python 3 Example Code Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/python/index.html A sample Python code snippet demonstrating class definition, decorators, and methods. ```python import os from package import ParentClass @nonsenseDecorator def doesNothing(): pass class ExampleClass(ParentClass): @staticmethod def example(inputStr): a = list(inputStr) a.reverse() return ''.join(a) def __init__(self, mixin = 'Hello'): self.mixin = mixin ``` -------------------------------- ### Scala Example with Recursion and List Processing Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/clike/index.html Presents a Scala example demonstrating functional programming concepts, including recursive functions for list filtering and processing. This snippet is suitable for learning Scala's approach to data manipulation. ```scala object FilterTest extends App { def filter(xs: List[Int], threshold: Int) = { def process(ys: List[Int]): List[Int] = if (ys.isEmpty) ys else if (ys.head < threshold) ys.head :: process(ys.tail) else process(ys.tail) process(xs) } println(filter(List(1, 9, 2, 8, 3, 7, 4), 5)) } ``` -------------------------------- ### Sass Syntax Example Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/sass/index.html Illustrates common Sass syntax, including variable definitions, global attributes, and scoped styles. Useful for understanding Sass structure. ```sass // Variable Definitions $page-width: 800px $sidebar-width: 200px $primary-color: #eeeeee // Global Attributes body { font: family: sans-serif size: 30em weight: bold } // Scoped Styles #contents { width: $page-width } #sidebar { float: right width: $sidebar-width } #main { width: $page-width - $sidebar-width background: $primary-color } h2 { color: blue } #footer { height: 200px } ``` -------------------------------- ### Grid Table Example in reST Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/rst/index.html Illustrates the syntax for creating grid tables in reStructuredText, which requires manual drawing of cell borders. ```rst +------------------------+------------+----------+----------+ | Header row, column 1 | Header 2 | Header 3 | Header 4 | | (header rows optional) | | | | +========================+============+==========+==========+ | body row 1, column 1 | column 2 | column 3 | column 4 | +------------------------+------------+----------+----------+ | body row 2 | ... | ... | | +------------------------+------------+----------+----------+ ``` -------------------------------- ### Simple Table Example in reST Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/rst/index.html Demonstrates the simpler syntax for creating simple tables in reStructuredText. Note the limitations on row count and multi-line cells in the first column. ```rst ===== ===== ======= A B A and B ===== ===== ======= False False False True False False False True False True True True ===== ===== ======= ``` -------------------------------- ### Section Header Example in reST Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/rst/index.html Illustrates creating a section header in reStructuredText using an underline (and optional overline) of punctuation characters. ```rst ================= This is a heading ================= ``` -------------------------------- ### XQuery to JSON Transformation Examples Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/xquery/index.html Illustrates various XQuery to JSON transformations, including handling of text, quotes, backslashes, nested elements, arrays, and type casting. ```xquery <e/> becomes {"e":null} ``` ```xquery <e>text</e> becomes {"e":"text"} ``` ```xquery <e>quote " escaping</e> becomes {"e":"quote \" escaping"} ``` ```xquery <e>backslash \ escaping</e> becomes {"e":"backslash \\ escaping"} ``` ```xquery <e><a>text1</a><b>text2</b></e> becomes {"e":{"a":"text1","b":"text2"}} ``` ```xquery <e><a>text1</a><a>text2</a></e> becomes {"e":{"a":["text1","text2"]}} ``` ```xquery <e><a array="true">text1</a></e> becomes {"e":{"a":["text1"]}} ``` ```xquery <e><a type="boolean">false</a></e> becomes {"e":{"a":false}} ``` ```xquery <e><a type="number">123.5</a></e> becomes {"e":{"a":123.5}} ``` ```xquery <e quote="true"><div attrib="value"/></e> becomes {"e":"<div attrib=\"value\"/>"} ``` -------------------------------- ### C++ Example with Templates and Raw Strings Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/clike/index.html Illustrates C++ features including namespaces, enums, unicode strings, raw string literals, class templates, inheritance, and member functions. This snippet is useful for understanding modern C++ syntax. ```cpp #include #include "mystuff/util.h" namespace { enum Enum { VAL1, VAL2, VAL3 }; char32_t unicode_string = U"\U0010FFFF"; string raw_string = R"delim(anything you want)delim"; int Helper(const MyType& param) { return 0; } } // namespace class ForwardDec; template class Class : public BaseClass { const MyType member_; public: const MyType& Method() const { return member_; } void Method2(MyType* value); } template void Class::Method2(MyType* value) { std::out << 1 >> method(); value->Method3(member_); member_ = value; } ``` -------------------------------- ### mIRC NickNames Hash Table Initialization and Persistence Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/mirc/index.html Initializes the NickNames hash table on script start and saves/loads it to/from a file for persistence. ```mirc On *:Start: {\n if (!$hget(NickNames)) {\n hmake NickNames 10\n }\n if ($isfile(NickNames.hsh)) {\n hload NickNames NickNames.hsh\n }\n}\nOn *:Exit: {\n if ($hget(NickNames)) {\n hsave NickNames NickNames.hsh\n }\n}\nOn *:Disconnect: {\n if ($hget(NickNames)) {\n hsave NickNames NickNames.hsh\n }\n}\nOn *:Unload: {\n hfree NickNames\n} ``` -------------------------------- ### Groovy Coin Changer Demo Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/groovy/index.html An example of the coin changer algorithm implemented in Groovy, showcasing enum usage and functional programming concepts. ```groovy /* Coin changer demo code from http://groovy.codehaus.org */ enum UsCoin { quarter(25), dime(10), nickel(5), penny(1) UsCoin(v) { value = v } final value } enum OzzieCoin { fifty(50), twenty(20), ten(10), five(5) OzzieCoin(v) { value = v } final value } def plural(word, count) { if (count == 1) return word word[-1] == 'y' ? word[0..-2] + "ies" : word + "s" } def change(currency, amount) { currency.values().inject([]){ list, coin -> int count = amount / coin.value amount = amount % coin.value list += "$count ${plural(coin.toString(), count)}" } } ``` -------------------------------- ### Java Example with Generics and Enums Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/clike/index.html Demonstrates Java syntax including generic types, interfaces, enums, static final members, inner classes, and method overrides. This snippet is useful for understanding Java class definitions. ```java import com.demo.util.MyType; import com.demo.util.MyInterface; public enum Enum { VAL1, VAL2, VAL3 } public class Class implements MyInterface { public static final MyType member; private class InnerClass { public int zero() { return 0; } } @Override public MyType method() { return member; } public void method2(MyType value) { method(); value.method3(); member = value; } } ``` -------------------------------- ### mIRC Nick Tracker Setup Aliases Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/mirc/index.html Defines configuration aliases for the mIRC Nick Tracker script, such as display settings and the maximum number of nicknames to store. ```mirc ;AKA Nick Tracker by Ford_Lawnmower irc.GeekShed.net #Script-Help ;***********************************************************************; ;**Start Setup ;Change JoinDisplay, below, for On Join AKA Display. On = 1 - Off = 0 alias -l JoinDisplay { return 1 }\n ;Change MaxNicks, below, to the number of nicknames you want to store for each hostmask. I wouldn't go over 400 with this ;/ alias -l MaxNicks { return 20 }\n ;Change AKALogo, below, To the text you want displayed before each AKA result. alias -l AKALogo { return 06 05A06K07A 06 } ``` -------------------------------- ### XQuery Function Declarations Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/xquery/index.html Shows examples of declaring private functions in XQuery, including functions named 'declare', 'private', 'function', and 'local'. ```xquery declare private function local:declare() {()}; declare private function local:private() {()}; declare private function local:function() {()}; declare private function local:local() {()}; ``` -------------------------------- ### Initialize and Run VB.NET Editor Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/vb/index.html JavaScript functions to initialize the CodeMirror editor with VB.NET syntax highlighting and to run the defined tests. This setup is typically used for development and testing purposes. ```javascript function initText(editor) { var content = 'Class rocket\nPrivate quality as Double\nPublic Sub launch() as String\nif quality > 0.8\nlaunch = "Successful"\nElse\nlaunch = "Failed"\nEnd If\nEnd sub\nEnd class\n'; editor.setValue(content); for (var i =0; i< editor.lineCount(); i++) editor.indentLine(i); } function init() { editor = CodeMirror.fromTextArea(document.getElementById("solution"), { lineNumbers: true, mode: "text/x-vb", readOnly: false }); runTest(); } function runTest() { document.getElementById('testresult').innerHTML = testAll(); initText(editor); } document.body.onload = init; ``` -------------------------------- ### Explicit Markup Block Example in reST Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/rst/index.html Shows the basic structure of an explicit markup block in reStructuredText, which starts with '.. ' and is used for directives, footnotes, and comments. ```rst .. _directives: Directives ---------- A directive (:duref:`ref `) is a generic block of explicit markup. ``` -------------------------------- ### JSON-LD Example Data Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/javascript/json-ld.html An example of JSON-LD data structure used for representing information about the Empire State Building. ```json { "@context": { "name": "http://schema.org/name", "description": "http://schema.org/description", "image": { "@id": "http://schema.org/image", "@type": "@id" }, "geo": "http://schema.org/geo", "latitude": { "@id": "http://schema.org/latitude", "@type": "xsd:float" }, "longitude": { "@id": "http://schema.org/longitude", "@type": "xsd:float" }, "xsd": "http://www.w3.org/2001/XMLSchema#" }, "name": "The Empire State Building", "description": "The Empire State Building is a 102-story landmark in New York City.", "image": "http://www.civil.usherbrooke.ca/cours/gci215a/empire-state-building.jpg", "geo": { "latitude": "40.75", "longitude": "73.98" } } ``` -------------------------------- ### Kotlin Server Implementation Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/kotlin/index.html A basic Kotlin server implementation using Netty, demonstrating Netty's bootstrap and channel handling for an HTTP server. ```kotlin package org.wasabi.http import java.util.concurrent.Executors import java.net.InetSocketAddress import org.wasabi.app.AppConfiguration import io.netty.bootstrap.ServerBootstrap import io.netty.channel.nio.NioEventLoopGroup import io.netty.channel.socket.nio.NioServerSocketChannel import org.wasabi.app.AppServer public class HttpServer(private val appServer: AppServer) { val bootstrap: ServerBootstrap val primaryGroup: NioEventLoopGroup val workerGroup: NioEventLoopGroup { // Define worker groups primaryGroup = NioEventLoopGroup() workerGroup = NioEventLoopGroup() // Initialize bootstrap of server bootstrap = ServerBootstrap() bootstrap.group(primaryGroup, workerGroup) bootstrap.channel(javaClass()) bootstrap.childHandler(NettyPipelineInitializer(appServer)) } public fun start(wait: Boolean = true) { val channel = bootstrap.bind(appServer.configuration.port)?.sync()?.channel() if (wait) { channel?.closeFuture()?.sync() } } public fun stop() { // Shutdown all event loops primaryGroup.shutdownGracefully() workerGroup.shutdownGracefully() // Wait till all threads are terminated primaryGroup.terminationFuture().sync() workerGroup.terminationFuture().sync() } } ``` -------------------------------- ### Cython Example Code Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/python/index.html A Cython function for calculating pairwise distances between rows of a NumPy array. ```cython import numpy as np cimport cython from libc.math cimport sqrt @cython.boundscheck(False) @cython.wraparound(False) def pairwise_cython(double[:, ::1] X): cdef int M = X.shape[0] cdef int N = X.shape[1] cdef double tmp, d cdef double[:, ::1] D = np.empty((M, M), dtype=np.float64) for i in range(M): for j in range(M): d = 0.0 for k in range(N): tmp = X[i, k] - X[j, k] d += tmp * tmp D[i, j] = sqrt(d) return np.asarray(D) ``` -------------------------------- ### C Demo Code with ZMQ Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/clike/index.html Demonstrates C code utilizing the ZeroMQ library for inter-process communication, including thread management and socket operations. This snippet showcases complex C structures and function definitions. ```c /* C demo code */ #include #include #include #include #include #include #include typedef struct { void* arg_socket; zmq_msg_t* arg_msg; char* arg_string; unsigned long arg_len; int arg_int, arg_command; int signal_fd; int pad; void* context; sem_t sem; } acl_zmq_context; #define p(X) (context->arg_##X) void* zmq_thread(void* context_pointer) { acl_zmq_context* context = (acl_zmq_context*)context_pointer; char ok = 'K', err = 'X'; int res; while (1) { while ((res = sem_wait(&context->sem)) == EINTR); if (res) {write(context->signal_fd, &err, 1); goto cleanup;} switch(p(command)) { case 0: goto cleanup; case 1: p(socket) = zmq_socket(context->context, p(int)); break; case 2: p(int) = zmq_close(p(socket)); break; case 3: p(int) = zmq_bind(p(socket), p(string)); break; case 4: p(int) = zmq_connect(p(socket), p(string)); break; case 5: p(int) = zmq_getsockopt(p(socket), p(int), (void*)p(string), &p(len)); break; case 6: p(int) = zmq_setsockopt(p(socket), p(int), (void*)p(string), p(len)); break; case 7: p(int) = zmq_send(p(socket), p(msg), p(int)); break; case 8: p(int) = zmq_recv(p(socket), p(msg), p(int)); break; case 9: p(int) = zmq_poll(p(socket), p(int), p(len)); break; } p(command) = errno; write(context->signal_fd, &ok, 1); } cleanup: close(context->signal_fd); free(context_pointer); return 0; } void* zmq_thread_init(void* zmq_context, int signal_fd) { acl_zmq_context* context = malloc(sizeof(acl_zmq_context)); pthread_t thread; context->context = zmq_context; context->signal_fd = signal_fd; sem_init(&context->sem, 1, 0); pthread_create(&thread, 0, &zmq_thread, context); pthread_detach(thread); return context; } ``` -------------------------------- ### Initialize CodeMirror for Sass Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/sass/index.html Demonstrates how to initialize a CodeMirror editor instance from a textarea element, enabling features like line numbers and bracket matching for Sass code. ```javascript var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers : true, matchBrackets : true }); ``` -------------------------------- ### Initialize SLIM Mode in CodeMirror Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/slim/index.html Use this code to initialize CodeMirror with the SLIM mode. Ensure the target textarea exists and the desired theme is loaded. ```javascript var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, theme: "ambiance", mode: "application/x-slim" }); $(".CodeMirror").resizable({ resize: function() { editor.setSize($(this).width(), $(this).height()); //editor.refresh(); } }); ``` -------------------------------- ### Initialize Verilog CodeMirror Editor Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/verilog/index.html Initializes a CodeMirror editor instance for Verilog/SystemVerilog mode using a textarea element. Includes options for line numbers, bracket matching, and custom indentation keywords. ```javascript var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, matchBrackets: true, mode: { name: "verilog", noIndentKeywords: ["package"] } }); ``` -------------------------------- ### Initialize Haxe CodeMirror Editor Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/haxe/index.html Initializes a CodeMirror editor instance for Haxe code. ```javascript var editor = CodeMirror.fromTextArea(document.getElementById("code-haxe"), { mode: "haxe", lineNumbers: true, indentUnit: 4, indentWithTabs: true }); ``` -------------------------------- ### Initialize CodeMirror with Markdown Mode Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/markdown/index.html Use this JavaScript to enable Markdown highlighting and specific key behaviors in a CodeMirror instance. It requires an HTML element with the ID 'code'. ```javascript var editor = CodeMirror.fromTextArea(document.getElementById("code"), { mode: 'markdown', lineNumbers: true, theme: "default", extraKeys: {"Enter": "newlineAndIndentContinueMarkdownList"} }); ``` -------------------------------- ### XQuery with Try-Catch and Type Casting Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/xquery/index.html Illustrates XQuery syntax for try-catch blocks, type casting, and conditional logic within XML construction. ```xquery let $let := let $let := "let" return element element { attribute attribute { try { xdmp:version() } catch($e) { xdmp:log($e) } }, attribute fn:doc { "bar" castable as xs:string }, element text { text { "text" } }, fn:doc()[ child::eq/(@bar | attribute::attribute) eq $let ], //fn:doc } ``` -------------------------------- ### Customizing Line Number Display in CodeMirror Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/diff/index.html Modifies the display of line numbers in the CodeMirror gutter to use a `firstLineNumber` option, allowing for custom starting numbers. This is useful for paginated views or specific diffing scenarios. ```javascript else html.push("
" + (options.lineNumbers ? i + options.firstLineNumber : "\u00a0") + "
"); ``` -------------------------------- ### R Lists and Element Access Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/r/index.html Demonstrates how to create a list in R and access its individual elements using the '$' operator. ```r # FIRST LEARN ABOUT LISTS -- X = list(height=5.4, weight=54) print("Use default printing --") print(X) print("Accessing individual elements --") cat("Your height is ", X$height, " and your weight is ", X$weight, "\n") ``` -------------------------------- ### Initialize CodeMirror with Groovy Mode Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/groovy/index.html This snippet shows how to initialize a CodeMirror editor instance from a textarea element, enabling line numbers, bracket matching, and setting the mode to Groovy. ```javascript var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, matchBrackets: true, mode: "text/x-groovy" }); ``` -------------------------------- ### Groovy Script File Matching Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/groovy/index.html This snippet demonstrates how to find and process all .groovy files within a specified directory using Groovy's file matching capabilities. ```groovy //Pattern for groovy script def p = ~/.*\.groovy/ new File( 'd:\\scripts' ).eachFileMatch(p) { f -> // imports list def imports = [] f.eachLine { // condition to detect an import instruction ln -> if ( ln =~ '^import .*' ) { imports << "${ln - 'import '}" } } // print them if ( ! imports.empty ) { println f imports.each { println " $it" } } } ``` -------------------------------- ### Initialize CodeMirror with Diff Mode Options Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/diff/index.html Initializes a CodeMirror editor from a textarea, enabling line numbers, auto-matching brackets, and a custom gutter click handler. This is useful for setting up an editor to display diffs or code with interactive gutter elements. ```javascript var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, autoMatchBrackets: true, onGutterClick: function(x){console.log(x);} }); ``` -------------------------------- ### Initialize TiddlyWiki Mode in CodeMirror Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/tiddlywiki/index.html This snippet shows how to initialize CodeMirror with the TiddlyWiki mode. It targets a textarea element with the ID 'code' and enables line numbers and bracket matching. ```javascript var editor = CodeMirror.fromTextArea(document.getElementById("code"), { mode: 'tiddlywiki', lineNumbers: true, matchBrackets: true }); ``` -------------------------------- ### Initialize Hxml CodeMirror Editor Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/haxe/index.html Initializes a CodeMirror editor instance for Hxml code. ```javascript editor = CodeMirror.fromTextArea(document.getElementById("code-hxml"), { mode: "hxml", lineNumbers: true, indentUnit: 4, indentWithTabs: true }); ``` -------------------------------- ### Initialize CodeMirror Editor Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/xquery/index.html Initializes a CodeMirror editor instance from a textarea element. Configures line numbers, bracket matching, and a dark theme. ```javascript var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, matchBrackets: true, theme: "xq-dark" }); ``` -------------------------------- ### Initialize CodeMirror for Dockerfile Mode Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/dockerfile/index.html This JavaScript code initializes a CodeMirror editor instance for a textarea element with the ID 'code', enabling line numbers and setting the mode to 'dockerfile'. ```javascript var editor = CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, mode: "dockerfile" }); ``` -------------------------------- ### R Function Definition and Usage Source: https://github.com/tommylemon/apiauto/blob/master/md/lib/codemirror/mode/r/index.html Shows how to define a simple R function that returns a value and how to call it. ```r # FUNCTIONS -- square <- function(x) { return(x*x) } cat("The square of 3 is ", square(3), "\n") ```