text:
package main

// 2fa = two factor authentication service
// Author: Bernhard Hecker

import (
	"bytes"
	"crypto/rsa"
	"crypto/sha256"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"math/rand"
	"net/http"
	"os"
	"os/signal"
	"strconv"
	"strings"
	"time"

	"github.com/dgrijalva/jwt-go"     //JWT Implementation
	"github.com/gin-gonic/gin"        //REST Framework
	"github.com/go-redis/redis"       //redis cache client
	"github.com/nyaruka/phonenumbers" //newer rewrite of lobphonenumber
	"gopkg.in/yaml.v2"                //YAML Parser for external configuration
)

const (
	capletters  = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	smalletters = "abcdefghijklmnopqrstuvwxyz"
	nums        = "0123456789"
	symbols     = "!@#$%^&*()-_=+,.?/:;{}[]`~"
	cryptokey   = "2@KwsyuX6f5&ZJAoFZkt6gZMEC!lYK!u" //AES Crypto Key
	//privKeyPath = "app.rsa"                          // RSA Private Key file for JWT Token verification
	//pubKeyPath  = "app.rsa.pub"                      //Rsa Public Key file for JWT Token signing
)

//Conf stores config parameters
type Conf struct {
	Rhost              string        `yaml:"rhost"` //redis host
	Rpass              string        `yaml:"rpass"` //redis password
	Suser              string        `yaml:"suser"` //SMS User
	Spass              string        `yaml:"spass"` //SMS Password
	DefaultTokenLength int           `yaml:"detaulttokenlength"`
	DefaulTokentExpiry time.Duration `yaml:"defaultokentexpiry"`
	MaxTokenLength     int           `yaml:"maxtokenlength"`
	Messageprefix      string        `yaml:"messageprefix"`
	Messagesuffix      string        `yaml:"messagesuffix"`
	HTTPPort           string        `yaml:"httpport"`
	PrivKeyPath        string        `yaml:"privKeyPath"`
	PubKeyPath         string        `yaml:"pubKeyPath"`
}

//Result ist the final Token, that we'll store in a jwt
type Result struct { //this is how the token looks like
	Token  string `json:"token"`
	Expiry string `json:"expiry"`
}

type Postjwt struct { //this is the JSON object we need if we have to validate a pin that gets posted
	JToken string `json:"jwt"`
	Pin    string `json:"pin"`
}

//Jobid is the ID we get back from the SMS Provider
type Jobid struct { //retarus SMS jobid
	JobId string
}

// Recipients structs for SMS4A API - a little complicated because it allows several messages in a call and several recipients per message
type Recipients struct {
	Dst string `json:"dst"`
}

type Messages struct {
	Text        string       `json:"text"`
	Rrecipients []Recipients `json:"recipients"`
}
type SMS4amsg struct {
	Mmessages []Messages `json:"messages"`
}

type Postmsg struct {
	Length  string `json:"length" binding:"required"`
	Expiry  string `json:"exp" binding:"required"`
	Destnum string `json:"destnum" binding:"required"`
	Type    string `json:"type" binding:"required"`
	Msg     string `json:"msg" binding:"required"`
}

//JWTToken will be filled with a JWT Token...
type JWTToken struct {
	Token string `json:"token"`
}

var (
	VerifyKey   *rsa.PublicKey
	VerifyBytes []byte
	SignKey     *rsa.PrivateKey
	RClient     redis.Client
	Cfg         Conf
)

func main() {

	/* usage:
	 curl -H "Content-Type: application/json" -X POST -d '{"type":"numbers","exp":"5m","destnum":"017615528046","msg":" Prefix !TOKEN! suffix","length":"8"}' http://172.20.19.122:8181/api/v1/tokens

	 supported types: string, lstring, ustring, numbers, symbol
	 exp: expiry in time.Duration
	 length: token length
	msg: message !TOKEN! will be replaced by token

	*/

	log.Println(time.Now(), "2fa started")
	readconfig()

	//this waits fpr ctrl-c to interrupt the program
	c := make(chan os.Signal)
	signal.Notify(c, os.Interrupt)

	go func() {
		select {
		case sig := <-c:
			fmt.Printf("Got %s signal. Aborting...\n", sig)
			os.Exit(1)
		}
	}()

	//several things need to be initialized here...
	RClient = initcache()            //Redis.Client
	rand.Seed(time.Now().UnixNano()) //make random a little more random
	initKeys()                       // Initialize RAS Keys

	router := gin.Default()

	router.LoadHTMLFiles("HTMLPage1.html")
	router.GET("/", usage)

	v1 := router.Group("/api/v1")
	{

		v1.GET("/check", checktoken) //validate token
		v1.POST("/tokens", tokens)   //create token
		//v1.GET("/jwt", checkjwttoken)  //validate jwt token
		v1.POST("/pjwt", postcheckjwt) // check jwt token (posted)
	}

	router.Run(":" + Cfg.HTTPPort)
}

//tokens generates a random token
func tokens(c *gin.Context) {
	var Message Postmsg //this is the json we get posted
	err := c.BindJSON(&Message)
	if err != nil {
		log.Println(time.Now(), err)
		c.JSON(500, "MSG Error")
		return
	}
	var job Jobid
	job = sendmessage(Message)
	c.JSON(200, job)

}

//postcheckjwt validates a token, that has been posted
// we need the jwt and the user input here
func postcheckjwt(c *gin.Context) {
	var Message Postjwt // this is the json we get posted
	err := c.BindJSON(&Message)
	if err != nil {
		log.Println(time.Now(), err)
		c.JSON(500, "MSG Error")
		return
	}

	pinhash := hash(Message.Pin) //this is the SHA 265 hash value of the transmitted pin
	jtoken := Message.JToken

	checkedpin := checkjwttoken(jtoken)

	fmt.Println("claims: ", checkedpin.Claims)
	fmt.Println("pinhash: ", pinhash)

	//TODO collect field values and hand over to validate jwt, validate expiry time and validate pin hash vs jwt hash - then return ok or bad...

}

//usage displays a html page as simple documentation for the api
func usage(c *gin.Context) {

	c.HTML(http.StatusOK, "HTMLPage1.html", nil)

}

//reads config File
func readconfig() {

	confFile, err := ioutil.ReadFile("2fa.cfg")
	errlog(err)

	err = yaml.Unmarshal(confFile, &Cfg)
	errlog(err)
}

func sendmessage(Message Postmsg) Jobid { // Sends a Text message via retarus SMS for Applications REST API V1

	//SMS4A Credentials
	url := "https://sms4a.retarus.com/rest/v1/"
	rUser := Cfg.Suser
	rPwd := Cfg.Spass

	//generating token:
	pin := makepin(Message)
	jtoken := makejwttoken(pin)
	fmt.Println("Jwttoken: ", jtoken)
	// stoken, err := json.Marshal(&token)
	// errlog(err)

	//jtoken := jwt.EncodeSegment(stoken)
	//fmt.Println("Jtoken: ", jtoken)
	/* ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims(stoken))
	fmt.Println ("kompletter JWT Token: ", ttoken) */

	//Query Parameter and Number Handling
	destnum := Message.Destnum
	//destnum, _ := dest.GetQuery("dest")                    //destination number
	destnumvalid, err := phonenumbers.Parse(destnum, "DE") //validate phone number
	errlog(err)

	i := phonenumbers.GetNumberType(destnumvalid)
	if i != phonenumbers.MOBILE && i != phonenumbers.FIXED_LINE_OR_MOBILE { //either mobile or somewhat unknown
		log.Println(time.Now(), "Not Mobile Number: ", destnumvalid)
		//Message.IndentedJSON(500, "Not mobile number")
		var r Jobid
		r.JobId = "Not mobile Number"
		return r //here we should either have a valid mobile number or leave the show...
	}

	// Building SMS Message
	msgstring := Message.Msg

	if msgstring == "" {
		msgstring = Cfg.Messageprefix + "!TOKEN!" + Cfg.Messagesuffix
	}

	msgs := strings.Split(msgstring, "!TOKEN!")
	msgstring = msgs[0] + pin.Token + " " + msgs[1]
	fmt.Println("Message: ", msgstring)

	arecipient := []Recipients{{destnum}}
	amessages := []Messages{{msgstring, arecipient}}
	asms := SMS4amsg{amessages}

	//http post message
	// first we build the request
	jsonStr, errs := json.Marshal(asms)
	errlog(errs)

	req, err := http.NewRequest("POST", url+"jobs", bytes.NewBuffer(jsonStr))
	errlog(err)

	req.SetBasicAuth(rUser, rPwd) //we're precise and set all neccessary headers, just in case
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("charset", "utf-8")
	defer req.Body.Close()

	client := &http.Client{}

	resp, err := client.Do(req)
	errlog(err)

	//http response...
	body, err := ioutil.ReadAll(resp.Body)
	errlog(err)

	bd := string(body[:])
	log.Println(time.Now(), "JobID: ", bd)
	log.Println(time.Now(), "Body: ", body)

	var bdj Jobid

	errr := json.Unmarshal(body, &bdj)
	errlog(errr)
	//fmt.Println(" BDJ.Jobid: ", bdj.JobId)

	storetoken(pin, bdj.JobId, RClient)
	return bdj
	//dest.IndentedJSON(200, bdj)

}

func makepin(Message Postmsg) Result { //generates pin and expiry TS

	qlen := Message.Length // Token length
	qtype := Message.Type  // Token type
	qexp := Message.Expiry // TTL

	//defaults
	dqtype := smalletters
	dlength := Cfg.DefaultTokenLength // Config Parameter default length
	dexp := Cfg.DefaulTokentExpiry    // config default time to live

	qex, err := time.ParseDuration(qexp)
	errlog(err)

	if qex == 0 {
		qex = time.Duration(dexp) * time.Minute // set default
	}

	var LetterBytes string // building the letter soup, we pick the token content from

	switch qtype {
	case "string":
		LetterBytes = capletters + smalletters
	case "lstring":
		LetterBytes = smalletters
	case "ustring":
		LetterBytes = capletters
	case "numbers":
		LetterBytes = nums
	case "symbol":
		LetterBytes = symbols + smalletters + capletters
	default:
		LetterBytes = dqtype // if something goes wrong, we just generate a token instead of throwing an error
		log.Println(time.Now(), "Incorrect type query parameter: ", qtype)
	}

	tokenlength, err := strconv.Atoi(qlen)
	errlog(err)

	if tokenlength > Cfg.MaxTokenLength { //max 25
		tokenlength = Cfg.MaxTokenLength
	}

	if tokenlength < 1 { // just in case: set to default
		tokenlength = dlength
	}

	b := make([]byte, tokenlength)
	for i := range b {
		b[i] = LetterBytes[rand.Intn(len(LetterBytes))]
	}

	qexstring := fmt.Sprintf("%s", qex) // time to live as string...
	//tokstring := string(b[:])
	//tokhash := hash(tokstring) // Building an SHA256 Hash

	var ergebnis Result
	ergebnis = Result{string(b[:]), qexstring}

	return ergebnis

}

func initcache() redis.Client { //Initializes cache connection

	client := redis.NewClient(&redis.Options{
		Addr:     Cfg.Rhost,
		Password: Cfg.Rpass,
		DB:       0, // use default DB
	})

	log.Println(time.Now(), "redis connection established")

	Client := *client

	return Client

}

func storetoken(token Result, key string, RClient redis.Client) { //stores token and key in redis

	expiryduration, _ := time.ParseDuration(token.Expiry)
	err := RClient.Set(key, hash(token.Token), expiryduration).Err()
	errlog(err)

}

func checktoken(req *gin.Context) {

	token, _ := req.GetQuery("token")
	hval := hash(token)
	//fmt.Println(hval)

	key, _ := req.GetQuery("id")

	val, err := RClient.Get(key).Result()
	errlog(err)
	fmt.Println(key, val)

	if val == string(hval[:]) {
		req.IndentedJSON(200, "true")
	} else {
		req.IndentedJSON(200, "false")
	}

}

func hash(key string) []byte {
	h := sha256.New()
	h.Write([]byte(key))
	return h.Sum(nil)
}

func errlog(err error) {
	if err != nil {
		log.Println(time.Now(), err)
	}
}

func initKeys() { //Initialize RSA Keys
	SignBytes, err := ioutil.ReadFile(Cfg.PrivKeyPath)
	errlog(err)

	SignKey, err = jwt.ParseRSAPrivateKeyFromPEM(SignBytes)
	errlog(err)

	VerifyBytes, err := ioutil.ReadFile(Cfg.PubKeyPath)
	errlog(err)

	VerifyKey, err = jwt.ParseRSAPublicKeyFromPEM(VerifyBytes)
	errlog(err)
}

func makejwttoken(c Result) string { //generates a jwt Token

	jt := jwt.New(jwt.SigningMethodRS256)
	jtclaims := make(jwt.MapClaims)

	//calculating the expiry TS
	expduration, err := time.ParseDuration(c.Expiry)
	errlog(err)
	pinexpires := time.Now().Add(expduration)
	//fmt.Println("Expires at: ", pinexpires)

	pinhash := hash(c.Token)
	pinstr := fmt.Sprintf("%x", pinhash)
	fmt.Println("Pin String: ", pinstr)

	jtclaims["expiry"] = pinexpires
	jtclaims["token"] = pinstr

	jt.Claims = jtclaims

	jtString, err := jt.SignedString(SignKey)
	errlog(err)

	response := JWTToken{jtString}
	return response.Token

}

func checkjwttoken(mytoken string) *jwt.Token { //validates a JWT token

	token, err := jwt.Parse(mytoken, func(token *jwt.Token) (interface{}, error) {
		// Don't forget to validate the alg is what you expect:
		if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return VerifyKey, nil
	})

	fmt.Println("Valid: ", token.Valid)
	fmt.Println("Claims: ", token.Claims)
	fmt.Println("Signature: ", token.Signature)
	fmt.Println("Header: ", token.Header)
	fmt.Println("Method: ", token.Method)
	fmt.Println("Token: ", mytoken)
	fmt.Println("err: ", err)

	return token

}

//EOF


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.willkara</groupId>
    <artifactId>zeteo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>
    <name>Zeteo Directory Informant</name>
    <description>A library to list information and statistics about a directory and the files contained within.</description>
    <dependencies>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>org</groupId>
            <artifactId>jaudiotagger</artifactId>
            <version>2.0.3</version>
        </dependency>
        <dependency>
            <groupId>commons-cli</groupId>
            <artifactId>commons-cli</artifactId>
            <version>1.2</version>
            <type>jar</type>
        </dependency>
        <dependency>
            <groupId>net.sf.opencsv</groupId>
            <artifactId>opencsv</artifactId>
            <version>2.3</version>
            <type>jar</type>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>com.willkara.zeteo.Zeteo</mainClass>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>com.willkara.zeteo.Zeteo </mainClass>
                        </manifest>
                    </archive>
                    <descriptorRefs>
                        <descriptorRef>jar-with-dependencies</descriptorRef>
                    </descriptorRefs>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>

    <meta charset="utf-8">
    <title>CodeMirror: Markdown mode</title>
    <link rel="stylesheet" href="../../lib/codemirror.css">

    <link rel="stylesheet" href="../../doc/docs.css">

CodeMirror: Markdown mode

<form><textarea id="code" name="code">
Markdown: Basics
================

<ul id="ProjectSubmenu">
    <li><a href="/projects/markdown/" title="Markdown Project Page">Main</a></li>
    <li><a class="selected" title="Markdown Basics">Basics</a></li>
    <li><a href="/projects/markdown/syntax" title="Markdown Syntax Documentation">Syntax</a></li>
    <li><a href="/projects/markdown/license" title="Pricing and License Information">License</a></li>
    <li><a href="/projects/markdown/dingus" title="Online Markdown Web Form">Dingus</a></li>
</ul>

Getting the Gist of Markdown's Formatting Syntax
------------------------------------------------

This page offers a brief overview of what it's like to use Markdown.
The [syntax page] [s] provides complete, detailed documentation for
every feature, but Markdown should be very easy to pick up simply by
looking at a few examples of it in action. The examples on this page
are written in a before/after style, showing example syntax and the
HTML output produced by Markdown.

It's also helpful to simply try Markdown out; the [Dingus] [d] is a
web application that allows you type your own Markdown-formatted text
and translate it to XHTML.

**Note:** This document is itself written using Markdown; you
can [see the source for it by adding '.text' to the URL] [src].

  [s]: /projects/markdown/syntax  "Markdown Syntax"
  [d]: /projects/markdown/dingus  "Markdown Dingus"
  [src]: /projects/markdown/basics.text

## Paragraphs, Headers, Blockquotes ##

A paragraph is simply one or more consecutive lines of text, separated
by one or more blank lines. (A blank line is any line that looks like
a blank line -- a line containing nothing but spaces or tabs is
considered blank.) Normal paragraphs should not be indented with
spaces or tabs.

Markdown offers two styles of headers: *Setext* and *atx*.
Setext-style headers for `<h1>` and `<h2>` are created by
"underlining" with equal signs (`=`) and hyphens (`-`), respectively.
To create an atx-style header, you put 1-6 hash marks (`#`) at the
beginning of the line -- the number of hashes equals the resulting
HTML header level.

Blockquotes are indicated using email-style '`>`' angle brackets.

Markdown:

    A First Level Header
    ====================

    A Second Level Header
    ---------------------

    Now is the time for all good men to come to
    the aid of their country. This is just a
    regular paragraph.

    The quick brown fox jumped over the lazy
    dog's back.

    ### Header 3

    > This is a blockquote.
    >
    > This is the second paragraph in the blockquote.
    >
    > ## This is an H2 in a blockquote

Output:

    <h1>A First Level Header</h1>

    <h2>A Second Level Header</h2>

    <p>Now is the time for all good men to come to
    the aid of their country. This is just a
    regular paragraph.</p>

    <p>The quick brown fox jumped over the lazy
    dog's back.</p>

    <h3>Header 3</h3>

    <blockquote>
        <p>This is a blockquote.</p>

        <p>This is the second paragraph in the blockquote.</p>

        <h2>This is an H2 in a blockquote</h2>
    </blockquote>

### Phrase Emphasis ###

Markdown uses asterisks and underscores to indicate spans of emphasis.

Markdown:

    Some of these words *are emphasized*.
    Some of these words _are emphasized also_.

    Use two asterisks for **strong emphasis**.
    Or, if you prefer, __use two underscores instead__.

Output:

    <p>Some of these words <em>are emphasized</em>.
    Some of these words <em>are emphasized also</em>.</p>

    <p>Use two asterisks for <strong>strong emphasis</strong>.
    Or, if you prefer, <strong>use two underscores instead</strong>.</p>

## Lists ##

Unordered (bulleted) lists use asterisks, pluses, and hyphens (`*`,
`+`, and `-`) as list markers. These three markers are
interchangable; this:

    *   Candy.
    *   Gum.
    *   Booze.

this:

    +   Candy.
    +   Gum.
    +   Booze.

and this:

    -   Candy.
    -   Gum.
    -   Booze.

all produce the same output:

    <ul>
    <li>Candy.</li>
    <li>Gum.</li>
    <li>Booze.</li>
    </ul>

Ordered (numbered) lists use regular numbers, followed by periods, as
list markers:

    1.  Red
    2.  Green
    3.  Blue

Output:

    <ol>
    <li>Red</li>
    <li>Green</li>
    <li>Blue</li>
    </ol>

If you put blank lines between items, you'll get `<p>` tags for the
list item text. You can create multi-paragraph list items by indenting
the paragraphs by 4 spaces or 1 tab:

    *   A list item.

        With multiple paragraphs.

    *   Another item in the list.

Output:

    <ul>
    <li><p>A list item.</p>
    <p>With multiple paragraphs.</p></li>
    <li><p>Another item in the list.</p></li>
    </ul>

### Links ###

Markdown supports two styles for creating links: *inline* and
*reference*. With both styles, you use square brackets to delimit the
text you want to turn into a link.

Inline-style links use parentheses immediately after the link text.
For example:

    This is an [example link](http://example.com/).

Output:

    <p>This is an <a href="http://example.com/">
    example link</a>.</p>

Optionally, you may include a title attribute in the parentheses:

    This is an [example link](http://example.com/ "With a Title").

Output:

    <p>This is an <a href="http://example.com/" title="With a Title">
    example link</a>.</p>

Reference-style links allow you to refer to your links by names, which
you define elsewhere in your document:

    I get 10 times more traffic from [Google][1] than from
    [Yahoo][2] or [MSN][3].

    [1]: http://google.com/        "Google"
    [2]: http://search.yahoo.com/  "Yahoo Search"
    [3]: http://search.msn.com/    "MSN Search"

Output:

    <p>I get 10 times more traffic from <a href="http://google.com/"
    title="Google">Google</a> than from <a href="http://search.yahoo.com/"
    title="Yahoo Search">Yahoo</a> or <a href="http://search.msn.com/"
    title="MSN Search">MSN</a>.</p>

The title attribute is optional. Link names may contain letters,
numbers and spaces, but are *not* case sensitive:

    I start my morning with a cup of coffee and
    [The New York Times][NY Times].

    [ny times]: http://www.nytimes.com/

Output:

    <p>I start my morning with a cup of coffee and
    <a href="http://www.nytimes.com/">The New York Times</a>.</p>

### Images ###

Image syntax is very much like link syntax.

Inline (titles are optional):

    ![alt text](/path/to/img.jpg "Title")

Reference-style:

    ![alt text][id]

    [id]: /path/to/img.jpg "Title"

Both of the above examples produce the same output:

    <img src="/path/to/img.jpg" alt="alt text" title="Title" />

### Code ###

In a regular paragraph, you can create code span by wrapping text in
backtick quotes. Any ampersands (`&`) and angle brackets (`<` or
`>`) will automatically be translated into HTML entities. This makes
it easy to use Markdown to write about HTML example code:

    I strongly recommend against using any `<blink>` tags.

    I wish SmartyPants used named entities like `&mdash;`
    instead of decimal-encoded entites like `&#8212;`.

Output:

    <p>I strongly recommend against using any
    <code>&lt;blink&gt;</code> tags.</p>

    <p>I wish SmartyPants used named entities like
    <code>&amp;mdash;</code> instead of decimal-encoded
    entites like <code>&amp;#8212;</code>.</p>

To specify an entire block of pre-formatted code, indent every line of
the block by 4 spaces or 1 tab. Just like with code spans, `&`, `<`,
and `>` characters will be escaped automatically.

Markdown:

    If you want your page to validate under XHTML 1.0 Strict,
    you've got to put paragraph tags in your blockquotes:

        <blockquote>
            <p>For example.</p>
        </blockquote>

Output:

    <p>If you want your page to validate under XHTML 1.0 Strict,
    you've got to put paragraph tags in your blockquotes:</p>

    <pre><code>&lt;blockquote&gt;
        &lt;p&gt;For example.&lt;/p&gt;
    &lt;/blockquote&gt;
    </code></pre>
</textarea></form>

Optionally depends on the XML mode for properly highlighted inline XML blocks.

MIME types defined: text/x-markdown.

Parsing/Highlighting Tests: normal,  verbose.


text:
#include <stdio.h>
#include <stdlib.h>
#include "utest.h"
#include "test_utils.h"
#include "ttree.h"

struct item {
    int key;
};

static int __cmpfunc(void *key1, void *key2)
{
    return (*(int *)key1 - *(int *)key2);
}

static struct item *alloc_item(int val)
{
    struct item *item;

    item = malloc(sizeof(*item));
    if (!item) {
        utest_error("Failed to allocate %zd bytes!", sizeof(*item));
    }

    item->key = val;
    return item;
}

#define CHECK_ITEM(item, exp)                                           \
    do {                                                                \
        if (!item) {                                                    \
            UTEST_FAILED("Failed to lookup item by key %d. But given key" \
                         " was inserted into the tree!", exp);          \
        }                                                               \
        if ((item)->key != exp) {                                       \
            UTEST_FAILED("ttree_lookup returned unexpected item with key " \
                         "%d. But key I wanted to find was %d!",        \
                         (item)->key, exp);                             \
        }                                                               \
    } while (0)

/*
 * ut_lookup is simple test function that should validate all possible
 * lookup cases. Saying "all possible cases" I mean that given function
 * should generate 100% coverage of ttree_lookup code.
 */
UTEST_FUNCTION(ut_lookup, args)
{
    Ttree tree;
    TtreeNode *tnode;
    int num_keys, num_items, ret, i;
    struct balance_info binfo;
    struct item *item;

    num_keys = utest_get_arg(args, 0, INT);
    num_items = utest_get_arg(args, 1, INT);
    UTEST_ASSERT(num_items >= 1);

    ret = ttree_init(&tree, num_keys, true, __cmpfunc, struct item, key);
    UTEST_ASSERT(ret >= 0);
    for (i = 0; i < (num_items / 2); i++) {
        item = alloc_item(i);
        UTEST_ASSERT(ttree_insert(&tree, item) == 0);
        item = alloc_item(num_items - i - 1);
        UTEST_ASSERT(ttree_insert(&tree, item) == 0);
    }

    check_tree_balance(&tree, &binfo);
    if (binfo.balance != TREE_BALANCED) {
        UTEST_FAILED("Tree is unbalanced on a node %p BFC = %d, %s\n",
                     binfo.tnode, binfo.tnode->bfc,
                     balance_name(binfo.balance));
    }

    /*
     * Just an example of how to browse the tree keys
     * in a sorted order: from the smallest one to the greatest one.
     * The following cycle runs from the smallest key to the greatest
     * one and checks that an item by given key can be successfully found.
     */
    tnode = ttree_node_leftmost(tree.root);
    while (tnode) {
        tnode_for_each_index(tnode, i) {
            ret = *(int *)tnode_key(tnode, i);
            item = (struct item *)ttree_lookup(&tree, &ret, NULL);
            CHECK_ITEM(item, ret);
        }

        tnode = tnode->successor;
    }

    /*
     * Here we run from the largest item to the smallest one
     * checking that ttree_lookup finds each item we ask.
     */
    for (i = num_keys - 1; i >= 0; i--) {
        item = (struct item *)ttree_lookup(&tree, &i, NULL);
        CHECK_ITEM(item, i);
    }

    UTEST_PASSED();
}

DEFINE_UTESTS_LIST(tests) = {
    {
        "UT_LOOKUP",
        "Simple lookup test with sanity check",
        ut_lookup,
        UTEST_ARGS_LIST {
            { "keys", UT_ARG_INT, "Number of keys per T*-tree node" },
            { "total_items", UT_ARG_INT, "Number of items in a tree" },
            UTEST_ARGS_LIST_END,
        },
    },
    UTESTS_LIST_END,
};

int main(int argc, char *argv[])
{
    utest_main(tests, argc, argv);
    return 0;
}


text:
package org.apache.poi.hssf.record;

/**
 * Title:        Header Record

 * Description:  Specifies a header for a sheet

 * REFERENCE:  PG 321 Microsoft Excel 97 Developer's Kit (ISBN: 1-57231-498-2)

 * @author Andrew C. Oliver (acoliver at apache dot org)
 * @author Shawn Laubach (slaubach at apache dot org) Modified 3/14/02
 * @author Jason Height (jheight at chariot dot net dot au)
 */
public final class HeaderRecord extends HeaderFooterBase implements Cloneable {
	public final static short sid = 0x0014;

	public HeaderRecord(String text) {
		super(text);
	}

	public HeaderRecord(RecordInputStream in) {
		super(in);
	}

	public String toString() {
		StringBuffer buffer = new StringBuffer();

		buffer.append("[HEADER]\n");
		buffer.append("    .header = ").append(getText()).append("\n");
		buffer.append("[/HEADER]\n");
		return buffer.toString();
	}

	public short getSid() {
		return sid;
	}

	@Override
	public HeaderRecord clone() {
		return new HeaderRecord(getText());
	}
}


text:
/*
-----------------------------------
TOC
-----------------------------------

Bootstrap Overrides:......Changes to base-Bootstrap CSS

Template Globals:.........Styles for specific responsive templates

Page Globals:.............Styling of HTML and BODY

Site Elements:............Re-usable site elements

Structure:................Site structural components

Section Specific:.........Styles for Home and all Sub Pages

Page/Element Specific:....Page, element or flow Specific CSS

Responsive:...............Specific styles for Desktop, Tablet and Mobile

Additive CSS:.............Additive/override CSS

Lightbox..................3rd Party Lightbox CSS

Downsize..................Reduce font size for sections

*/

/* ------------------------------------
Structure
------------------------------------ */

/* ---- Header ---- */

  /* Header: Global Navbars */
  .navbar-header { padding-right: 9px; padding-left: 5px; margin-right: -15px; margin-left: -15px; background: #fff; }

  .navbar-brand { height:44px; padding:0px; }
  .navbar-brand .mw_logo { width:157px; height:32px; margin:6px 0px 0px 5px; }
  .navbar-brand .mlc_logo { width:245px; height:32px; margin:6px 0px 0px 5px; }

  .navbar-toggle { padding:0px; margin-top:2px; margin-right:4px; margin-bottom:2px; border:none; }
  .navbar-toggle { margin-right: 0; } /* Fix for 3 icons*/

  .navbar-default .navbar-toggle:hover,
  .navbar-default .navbar-toggle:focus { background-color: #fff; border-radius: 0; }

  .navbar-toggle .icon-cog,
  .navbar-toggle .icon-contactus-menu,
  .navbar-toggle .icon-menu { font-size: 44px; color: #428bca; line-height: 0.86 !important; display: block !important; }
  .navbar-toggle .icon-cog:hover,
  .navbar-toggle .icon-contactus-menu:hover,
  .navbar-toggle .icon-menu:hover { color: #428bca; }

  .navbar-collapse li { font-size:14px; line-height: 1.00; }

  .navbar-nav { margin-top: 0; margin-bottom: 0; }

  .navbar-default #topnav { margin-top: 0; border-top: 1px solid #e6e6e6; }

  .navbar-default #topnav.navbar-nav > li > a { padding: 11px 15px; font-weight: normal; }
  .navbar-default #topnav.navbar-nav > li > a,
  .navbar-default #topnav.navbar-nav > li > a:focus,
  .navbar-default #topnav.navbar-nav > li > a:visited { color: #333; }
  .navbar-default #topnav.navbar-nav > li > a:hover { color: #333; background: #e6ebef; }

  .navbar-default #topnav.navbar-nav > li.active > a,
  .navbar-default #topnav.navbar-nav > li.active > a:hover { border-radius: 0; color: #333; background: #e6ebef; }

  .navbar-default .navbar-nav > .open > a,
  .navbar-default .navbar-nav > .open > a:hover,
  .navbar-default .navbar-nav > .open > a:focus { color: #333; background: #e6ebef; }

  .navbar-default .navbar-nav > .open .dropdown-menu { padding: 0; border-top: 1px solid #e6e6e6; }
  .navbar-default .navbar-nav > .open .dropdown-menu > li > a { padding: 11px 15px 11px 25px; color: #333; }
  .navbar-default .navbar-nav > .open .dropdown-menu > li > a:hover,
  .navbar-default .navbar-nav > .open .dropdown-menu > li > a:focus { color: #333; background: #e6ebef; }

  #topnav_collapse { max-height: none; margin-right: -15px; margin-left: -15px; background: #fff; border-top: none; }
  #topnav_collapse li + li { border-top: 1px solid #e6e6e6; }

  /* Header: Mobile Subnav */
  #mobile_subnav { background: #2f7eb2; }

  #mobile_subnav .navbar-collapse { max-height: none; border-top: 1px solid #fff; border-top: 1px solid rgba(255,255,255,0.5); }
  #mobile_subnav .navbar-collapse .subnav { margin-bottom: 0; }
  #mobile_subnav .navbar-collapse .subnav > li { color: #fff; }
  #mobile_subnav .navbar-collapse .subnav > li + li { border-top: 1px solid #fff; border-top: 1px solid rgba(255,255,255,0.5); }
  #mobile_subnav .navbar-collapse .subnav > li .caret { margin: 0 0 0 5px; }
  #mobile_subnav .navbar-collapse .subnav > li > a { padding: 11px 18px 11px 8px; }

  #mobile_subnav .navbar-collapse .subnav > li > a { color: #fff; }
  #mobile_subnav .navbar-collapse .subnav > li > a:hover,
  #mobile_subnav .navbar-collapse .subnav > li > a:focus,
  #mobile_subnav .navbar-collapse .subnav > li > a:active { background: #235e85; background: rgba(0,0,0,0.2); color: #fff; }

  #mobile_subnav .navbar-collapse .open > a,
  #mobile_subnav .navbar-collapse .open > a:hover,
  #mobile_subnav .navbar-collapse .open > a:focus,
  #mobile_subnav .navbar-collapse .open > a:active { background: #235e85; background: rgba(0,0,0,0.2); color: #fff; }

  #mobile_subnav .navbar-collapse .dropdown-menu { padding-top: 0; padding-bottom: 0; border-top: 1px solid #fff; border-top: 1px solid rgba(255,255,255,0.5); background: #2f7eb2; }
  #mobile_subnav .navbar-collapse .dropdown-menu > li > a { padding: 11px 18px; white-space: normal;  }

  #mobile_subnav .navbar-collapse .dropdown-menu > li > a { color: #fff; }
  #mobile_subnav .navbar-collapse .dropdown-menu > li > a:hover,
  #mobile_subnav .navbar-collapse .dropdown-menu > li > a:focus,
  #mobile_subnav .navbar-collapse .dropdown-menu > li > a:active { background: #235e85; background: rgba(0,0,0,0.2); color: #fff; }

  #mobile_subnav .navbar-collapse .dropdown-menu > .active > a,
  #mobile_subnav .navbar-collapse .dropdown-menu > .active > a:hover,
  #mobile_subnav .navbar-collapse .dropdown-menu > .active > a:focus { background: #235e85; background: rgba(0,0,0,0.2); color: #fff; }

/* ---- Section Header ----  */
.section_header_content { padding-right: 19px; }
.has_horizontal_local_nav#section_header_title:after { width: 0; height: auto; border-right: 1px solid #fff; border-right: 1px solid rgba(255,255,255,0.25); bottom: 0; content: ""; position: absolute; right: 0; top: 0; }

  /* Section Header: Search */
	.section_header .navbar-toggle { margin-top: 2px; float: right; position: absolute; right: 5px; }

    /* Section Header: Without Search Box */
    .section_header .col-xs-12 > .section_header_content { padding-right: 40px; }
    .section_header .col-xs-12 > .section_header_content .navbar-toggle { right: 19px; }

  /* Affix */

    /* Account for Affixed Header --- padding-top : calc(Height of Affixed Banner + Top Padding on Element) */
    .sticky_header_container.affix + .full_banner_container { padding-top: calc(52px + 0px); }
    .sticky_header_container.affix + .body_lead_container { padding-top: calc(52px + 30px); }
    .sticky_header_container.affix + .cta_container_mobile { padding-top: calc(52px + 20px); }
    .sticky_header_container.affix + .content_container { padding-top: calc(52px + 20px); }

    .sticky_header_container.affix.includes_subnav + .full_banner_container { padding-top: calc(52px + 0px); }
    .sticky_header_container.affix.includes_subnav + .body_lead_container {padding-top: calc(52px + 30px); }
    .sticky_header_container.affix.includes_subnav + .content_container { padding-top: calc(52px + 20px); }

/* ---- CTA ---- */

  /* CTA: CTA Box */
  .cta_box { padding: 0; background-color: transparent; box-shadow: none; }
  .cta_box ul>li { margin-bottom: 5px; }

  .cta_item a { padding: 8px 40px; border-radius: 3px; display: block; font-size: 16px; line-height: 1.00; }
  .cta_item a:hover { text-decoration:none; }

    /* CTA Box: Button Types */
    .cta_item_general a,
    .cta_item_general a:visited { border-color: #e6e6e6; background: #e6e6e6; color:#005fce; }
    .cta_item_general a:active,
    .cta_item_general a:focus,
    .cta_item_general a:hover { border-color: #d8d8d8; background: #d8d8d8; color:#005fce; }

    .cta_item_primary a,
    .cta_item_primary a:visited { border-color: #808080; background: #808080; color: #fff; }
    .cta_item_primary a:active,
    .cta_item_primary a:focus,
    .cta_item_primary a:hover { border-color: #999; background: #999; color: #fff; }

    .cta_item_secondary a,
    .cta_item_secondary a:visited { border-color: #004b87; background: #004b87; color: #fff; }
    .cta_item_secondary a:active,
    .cta_item_secondary a:focus,
    .cta_item_secondary a:hover { border-color: #2f7abf; background: #2f7abf; color: #fff; }

    .cta_item_tertiary a,
    .cta_item_tertiary a:visited { border-color: #48a23f; background: #48a23f; color: #fff; }
    .cta_item_tertiary a:active,
    .cta_item_tertiary a:focus,
    .cta_item_tertiary a:hover { border-color: #5fd362; background: #5fd362; color: #fff; }

    .cta_item_quaternary a,
    .cta_item_quaternary a:visited { border-color: #f2a900; background: #f2a900; color: #fff; }
    .cta_item_quaternary a:active,
    .cta_item_quaternary a:focus,
    .cta_item_quaternary a:hover { border-color: #f1b51c; background: #f1b51c; color: #fff; }

    .cta_item_quinary a,
    .cta_item_quinary a:visited { border-color: #00a9e0; background: #00a9e0; color: #fff; }
    .cta_item_quinary a:active,
    .cta_item_quinary a:focus,
    .cta_item_quinary a:hover { border-color: #0184b2; background: #0184b2; color: #fff; }

    .cta_item_senary a,
    .cta_item_senary a:visited { border-color: #b7312c; background: #b7312c; color: #fff; }
    .cta_item_senary a:active,
    .cta_item_senary a:focus,
    .cta_item_senary a:hover { border-color: #68b9d6; background: #68b9d6; color: #fff; }

    .cta_item_septenary a,
    .cta_item_septenary a:visited { border-color: #d78825; background: #d78825; color: #fff; }
    .cta_item_septenary a:active,
    .cta_item_septenary a:focus,
    .cta_item_septenary a:hover { border-color: #038064; background: #038064; color: #fff; }

    .cta_item_emphasize a,
    .cta_item_emphasize a:visited { border-color: #cb6015; background: #cb6015; color: #fff; }
    .cta_item_emphasize a:active,
    .cta_item_emphasize a:focus,
    .cta_item_emphasize a:hover { border-color: #ee6f32; background: #ee6f32; color: #fff; }

    /* CTA Box: Inline */
    .cta_box ul.list-inline > li { margin-bottom: 5px; display: block; }
    .cta_box ul.list-inline > li:last-child { margin-bottom: 0; }

/* ---- Content ---- */

  /* ---- Search Results ---- */

    /* Search Results: Facets */
    #mobile_pagefacets { padding: 20px; }

/* ------------------------------------
$ To Be Code Reviewed
------------------------------------ */
/*
 All CSS changes/addtions/edits MUST be code reviewed before they can accepted as part of the site6 standards.

 Please add any working code below, and be sure to add you initials in the comments for your section.

 Once your work is complete, coordinate a code review with Ryan Johnson.  Code reviews should be scheduled before the end of Feature Freeze.
*/


text:
#ifndef AOM_DSP_ANS_H_
#define AOM_DSP_ANS_H_
// Constants, types and utilities for Asymmetric Numeral Systems
// http://arxiv.org/abs/1311.2540v2

#include <assert.h>
#include "./aom_config.h"
#include "aom/aom_integer.h"
#include "aom_dsp/prob.h"

#ifdef __cplusplus
extern "C" {
#endif  // __cplusplus

// Use windowed ANS, size is passed in at initialization
#define ANS_MAX_SYMBOLS 1
#define ANS_REVERSE 1

typedef uint8_t AnsP8;
#define ANS_P8_PRECISION 256u
#define ANS_P8_SHIFT 8
#define RANS_PROB_BITS 15
#define RANS_PRECISION (1u << RANS_PROB_BITS)

// L_BASE is the ANS base state. L_BASE % PRECISION must be 0.
#define L_BASE (1u << 17)
#define IO_BASE 256
// Range I = { L_BASE, L_BASE + 1, ..., L_BASE * IO_BASE - 1 }

#ifdef __cplusplus
}  // extern "C"
#endif  // __cplusplus
#endif  // AOM_DSP_ANS_H_


text:
module SidebarHelper

  def my_tasks_count
    current_user.tasks.for_circle(current_circle).volunteered.not_completed.count
  end

  def open_tasks_count
    current_circle.tasks.unassigned.not_completed.select { |t| can?(:read, t) }.count
  end

  def all_supplies_count
    current_circle.supplies.not_completed.select { |s| can?(:read, s) }.count
  end

  def projects_count
    current_circle.projects.open.select { |project| can?(:read, project) }.count
  end

  def admin_actions_counter
    pending_admin_actions_count
  end

  def working_group_counter(working_group)
    # FIXME DRY up scopes by making methods on task, creating finder mutations/objects, etc.
    working_group.tasks.not_completed.not_in_project.count + working_group.supplies.not_completed.not_in_project.count
  end

  def current_users_working_groups
    working_groups_per_user(:include?)
  end

  def other_users_working_groups
    working_groups_per_user(:exclude?)
  end

  def sidebar_link(name, path, opts={})
    opts[:text] = name
    opts[:path] = path
    opts[:css_selector] = "sidebar-item"
    opts[:css_selector] += " selected" if current_page?(path)
    opts[:css_selector] += " #{opts[:link_class]}" if opts[:link_class].present?
    opts[:icon_id]      ||= nil
    opts[:badge_text]   ||= nil
    opts[:after_icon]   ||= nil
    opts[:id]           ||= nil
    render partial: 'layouts/internal/sidebar_item', locals: opts
  end

  def visible_projects?
    # performance: don't load & loop through all projects if user is admin
    if (can?(:manage, current_circle) && current_circle.projects.present?)
      true
    else
      current_circle.projects.any? { |project| can?(:read, project) }
    end
  end

  private

  def working_groups_per_user(check_method)
    current_circle.working_groups.active.asc_order.select do |wg|
      current_user.working_groups.map(&:id).send(check_method, wg.id)
    end
  end

end


text:
package de.darwinspl.preferences.resource.dwprofile.ui;

import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EcoreUtil;

public class DwprofileDefaultHoverTextProvider implements de.darwinspl.preferences.resource.dwprofile.IDwprofileHoverTextProvider {

	public String getHoverText(EObject container, EObject referencedObject) {
		return getHoverText(referencedObject);
	}

	public String getHoverText(EObject object) {
		if (object == null) {
			return null;
		}
		EClass eClass = object.eClass();
		String label = "" + eClass.getName() + "";
		String documentation = EcoreUtil.getDocumentation(eClass);
		String documentationHTML = documentation == null ? "" : " (" + documentation +")";
		label += documentationHTML;
		for (EAttribute attribute : eClass.getEAllAttributes()) {
			Object value = null;
			try {
				value = object.eGet(attribute);
			} catch (Exception e) {
				// Exception in eGet, do nothing
			}
			if (value != null && value.toString() != null && !value.toString().equals("[]")) {
				label += "
" + attribute.getName() + ": " + object.eGet(attribute).toString();
			}
		}
		return label;
	}

}


text:
package com.shop.web.api;

import com.shop.service.dataservice.currency.CurrencyService;
import com.shop.service.dto.currency.CurrencySimpleDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created by zhirayrg on 3/9/2017.
 */
@RestController
@RequestMapping(value = "/api")
public class CurrencyController {

    @Autowired
    private CurrencyService currencyService;

    @GetMapping(value = "/currencies")
    public List<CurrencySimpleDto> getCurrencies() {

        List<CurrencySimpleDto> currencies = currencyService.getAll();
        return currencies;
    }
}


text:
package com.mmall.concurrency;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@Slf4j
public class TestController {

    @RequestMapping("/test")
    @ResponseBody
    public String test() {
        return "test";
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;

namespace QuantConnect.Securities.Future
{
    /// <summary>
    /// Calculate the date of a futures expiry given an expiry month and year
    /// </summary>
    public class FuturesExpiryFunctions
    {
        /// <summary>
        /// Method to retrieve the Function for a specific future symbol
        /// </summary>
        public static Func<DateTime, DateTime> FuturesExpiryFunction(string symbol)
        {
            if (FuturesExpiryDictionary.ContainsKey(symbol.ToUpper()))
            {
                return FuturesExpiryDictionary[symbol.ToUpper()];
            }

            // If function for expiry cannot be found pass the date through
            return (date) => date;
        }

        /// <summary>
        /// Dictionary of the Functions that calculates the expiry for a given year and month.
        /// It does not matter what the day and time of day are passed into the Functions.
        /// The Functions is responsible for calculating the day and time of day given a year and month
        /// </summary>
        public static Dictionary<string, Func<DateTime, DateTime>> FuturesExpiryDictionary = new Dictionary<string, Func<DateTime, DateTime>>()
        {
            // Metals
            // Gold (GC): http://www.cmegroup.com/trading/metals/precious/gold_contract_specifications.html
            {Futures.Metals.Gold, (time =>
                    // Trading terminates on the third last business day of the delivery month.
                    FuturesExpiryUtilityFunctions.NthLastBusinessDay(time,3)
                )
            },
            // Silver (SI): http://www.cmegroup.com/trading/metals/precious/silver_contract_specifications.html
            {Futures.Metals.Silver, (time =>
                    // Trading terminates on the third last business day of the delivery month.
                    FuturesExpiryUtilityFunctions.NthLastBusinessDay(time,3)
                )
            },
            // Platinum (PL): http://www.cmegroup.com/trading/metals/precious/platinum_contract_specifications.html
            {Futures.Metals.Platinum, (time =>
                    // Trading terminates on the third last business day of the delivery month.
                    FuturesExpiryUtilityFunctions.NthLastBusinessDay(time,3)
                )
            },
            // Palladium (PA): http://www.cmegroup.com/trading/metals/precious/palladium_contract_specifications.html
            {Futures.Metals.Palladium, (time =>
                    // Trading terminates on the third last business day of the delivery month.
                    FuturesExpiryUtilityFunctions.NthLastBusinessDay(time,3)
                )
            },
            // Indices
            // SP500EMini (ES): http://www.cmegroup.com/trading/equity-index/us-index/e-mini-sandp500_contract_specifications.html
            {Futures.Indices.SP500EMini, (time =>
                {
                    // Trading can occur up to 9:30 a.m. Eastern Time (ET) on the 3rd Friday of the contract month
                    var thirdFriday = FuturesExpiryUtilityFunctions.ThirdFriday(time);
                    return thirdFriday.Add(new TimeSpan(13,30,0));
                })
            },
            // NASDAQ100EMini (NQ): http://www.cmegroup.com/trading/equity-index/us-index/e-mini-nasdaq-100_contract_specifications.html
            {Futures.Indices.NASDAQ100EMini, (time =>
                {
                    // Trading can occur up to 9:30 a.m. Eastern Time (ET) on the 3rd Friday of the contract month
                    var thirdFriday = FuturesExpiryUtilityFunctions.ThirdFriday(time);
                    return thirdFriday.Add(new TimeSpan(13,30,0));
                })
            },
            // Dow30EMini (YM): http://www.cmegroup.com/trading/equity-index/us-index/e-mini-dow_contract_specifications.html
            {Futures.Indices.Dow30EMini, (time =>
                {
                    // Trading can occur up to 9:30 a.m. Eastern Time (ET) on the 3rd Friday of the contract month
                    var thirdFriday = FuturesExpiryUtilityFunctions.ThirdFriday(time);
                    return thirdFriday.Add(new TimeSpan(13,30,0));
                })
            },
            // Russell2000EMini (RTY): https://www.cmegroup.com/trading/equity-index/us-index/e-mini-russell-2000_contract_specifications.html
            {Futures.Indices.Russell2000EMini, (time =>
                {
                    // Trading can occur up to 9:30 a.m. Eastern Time (ET) on the 3rd Friday of the contract month
                    var thirdFriday = FuturesExpiryUtilityFunctions.ThirdFriday(time);
                    return thirdFriday.Add(new TimeSpan (13,30,0));
                })
            },
            // Nikkei225Dollar (NKD): https://www.cmegroup.com/trading/equity-index/international-index/nikkei-225-dollar_contract_specifications.html
            {Futures.Indices.Nikkei225Dollar, (time =>
                {
                    // Trading terminates at 5:00 p.m. Eastern Time (ET) on Business Day prior to 2nd Friday of the contract month.
                    var secondFriday = FuturesExpiryUtilityFunctions.SecondFriday(time);
                    var priorBusinessDay = secondFriday.AddDays(-1);
                    while (!FuturesExpiryUtilityFunctions.NotHoliday(priorBusinessDay))
                    {
                        priorBusinessDay = priorBusinessDay.AddDays(-1);
                    }
                    return priorBusinessDay.Add(TimeSpan.FromHours(21));
                })
            },
            // CBOE Volatility Index Futures (VIX): https://cfe.cboe.com/cfe-products/vx-cboe-volatility-index-vix-futures/contract-specifications
            {Futures.Indices.VIX, (time =>
                {
                    // Trading can occur up to 9:00 a.m. Eastern Time (ET) on the "Wednesday that is 30 days prior to
                    // the third Friday of the calendar month immediately following the month in which the contract expires".
                    var nextThirdFriday = FuturesExpiryUtilityFunctions.ThirdFriday(time.AddMonths(1));
                    var expiryDate = nextThirdFriday.AddDays(-30);
                    // If the next third Friday or the Wednesday are holidays, then it is moved to the previous day.
                    if (USHoliday.Dates.Contains(expiryDate) || USHoliday.Dates.Contains(nextThirdFriday))
                    {
                        expiryDate = expiryDate.AddDays(-1);
                    }
                    // Trading hours for expiring VX futures contracts end at 8:00 a.m. Chicago time on the final settlement date.
                    return expiryDate.Add(new TimeSpan(13, 0, 0));
                })
            },
            // Grains And OilSeeds Group
            // Wheat (ZW): http://www.cmegroup.com/trading/agricultural/grain-and-oilseed/wheat_contract_specifications.html
            {Futures.Grains.Wheat, (time =>
                {
                    // The business day prior to the 15th calendar day of the contract month.
                    var fifteenth = new DateTime(time.Year,time.Month,15);
                    return FuturesExpiryUtilityFunctions.AddBusinessDays(fifteenth,-1);
                })
            },
            // Corn (ZC): http://www.cmegroup.com/trading/agricultural/grain-and-oilseed/corn_contract_specifications.html
            {Futures.Grains.Corn, (time =>
                {
                    // The business day prior to the 15th calendar day of the contract month.
                    var fifteenth = new DateTime(time.Year,time.Month,15);
                    return FuturesExpiryUtilityFunctions.AddBusinessDays(fifteenth,-1);
                })
            },
            // Soybeans (ZS): http://www.cmegroup.com/trading/agricultural/grain-and-oilseed/soybean_contract_specifications.html
            {Futures.Grains.Soybeans, (time =>
                {
                    // The business day prior to the 15th calendar day of the contract month.
                    var fifteenth = new DateTime(time.Year,time.Month,15);
                    return FuturesExpiryUtilityFunctions.AddBusinessDays(fifteenth,-1);
                })
            },
            // SoybeanMeal (ZM): http://www.cmegroup.com/trading/agricultural/grain-and-oilseed/soybean-meal_contract_specifications.html
            {Futures.Grains.SoybeanMeal, (time =>
                {
                    // The business day prior to the 15th calendar day of the contract month.
                    var fifteenth = new DateTime(time.Year,time.Month,15);
                    return FuturesExpiryUtilityFunctions.AddBusinessDays(fifteenth,-1);
                })
            },
            // SoybeanOil (ZL): http://www.cmegroup.com/trading/agricultural/grain-and-oilseed/soybean-oil_contract_specifications.html
            {Futures.Grains.SoybeanOil, (time =>
                {
                    // The business day prior to the 15th calendar day of the contract month.
                    var fifteenth = new DateTime(time.Year,time.Month,15);
                    return FuturesExpiryUtilityFunctions.AddBusinessDays(fifteenth,-1);
                })
            },
            // Oats (ZO): http://www.cmegroup.com/trading/agricultural/grain-and-oilseed/oats_contract_specifications.html
            {Futures.Grains.Oats, (time =>
                {
                    // The business day prior to the 15th calendar day of the contract month.
                    var fifteenth = new DateTime(time.Year,time.Month,15);
                    return FuturesExpiryUtilityFunctions.AddBusinessDays(fifteenth,-1);
                })
            },

            // Currencies group
            // U.S. Dollar Index Futures is not found on cmegroup will discuss and update
            //  GBP (6B): http://www.cmegroup.com/trading/fx/g10/british-pound_contract_specifications.html
            {Futures.Currencies.GBP, (time =>
                {
                    // 9:16 a.m. Central Time (CT) on the second business day immediately preceding the third Wednesday of the contract month (usually Monday).
                    var thirdWednesday = FuturesExpiryUtilityFunctions.ThirdWednesday(time);
                    var secondBusinessDayPrecedingThirdWednesday = FuturesExpiryUtilityFunctions.AddBusinessDays(thirdWednesday,-2);
                    return secondBusinessDayPrecedingThirdWednesday.Add(new TimeSpan(14,16,0));
                })
            },
            // CAD (6C): http://www.cmegroup.com/trading/fx/g10/canadian-dollar_contract_specifications.html
            {Futures.Currencies.CAD, (time =>
                {
                    // 9:16 a.m. Central Time (CT) on the business day immediately preceding the third Wednesday of the contract month (usually Tuesday).
                    var thirdWednesday = FuturesExpiryUtilityFunctions.ThirdWednesday(time);
                    var businessDayPrecedingThridWednesday = FuturesExpiryUtilityFunctions.AddBusinessDays(thirdWednesday,-1);
                    return businessDayPrecedingThridWednesday.Add(new TimeSpan(14,16,0));
                })
            },
            // JPY (6J): http://www.cmegroup.com/trading/fx/g10/japanese-yen_contract_specifications.html
            {Futures.Currencies.JPY, (time =>
                {
                    // 9:16 a.m. Central Time (CT) on the second business day immediately preceding the third Wednesday of the contract month (usually Monday).
                    var thirdWednesday = FuturesExpiryUtilityFunctions.ThirdWednesday(time);
                    var secondBusinessDayPrecedingThirdWednesday = FuturesExpiryUtilityFunctions.AddBusinessDays(thirdWednesday,-2);
                    return secondBusinessDayPrecedingThirdWednesday.Add(new TimeSpan(14,16,0));
                })
            },
            // CHF (6S): http://www.cmegroup.com/trading/fx/g10/swiss-franc_contract_specifications.html
            {Futures.Currencies.CHF, (time =>
                {
                    // 9:16 a.m. Central Time (CT) on the second business day immediately preceding the third Wednesday of the contract month (usually Monday).
                    var thirdWednesday = FuturesExpiryUtilityFunctions.ThirdWednesday(time);
                    var secondBusinessDayPrecedingThirdWednesday = FuturesExpiryUtilityFunctions.AddBusinessDays(thirdWednesday,-2);
                    return secondBusinessDayPrecedingThirdWednesday.Add(new TimeSpan(14,16,0));
                })
            },
            // EUR (6E): http://www.cmegroup.com/trading/fx/g10/euro-fx_contract_specifications.html
            {Futures.Currencies.EUR, (time =>
                {
                    // 9:16 a.m. Central Time (CT) on the second business day immediately preceding the third Wednesday of the contract month (usually Monday).
                    var thirdWednesday = FuturesExpiryUtilityFunctions.ThirdWednesday(time);
                    var secondBusinessDayPrecedingThirdWednesday = FuturesExpiryUtilityFunctions.AddBusinessDays(thirdWednesday,-2);
                    return secondBusinessDayPrecedingThirdWednesday.Add(new TimeSpan(14,16,0));
                })
            },
            // AUD (6A): http://www.cmegroup.com/trading/fx/g10/australian-dollar_contract_specifications.html
            {Futures.Currencies.AUD, (time =>
                {
                    // 9:16 a.m. Central Time (CT) on the second business day immediately preceding the third Wednesday of the contract month (usually Monday).
                    var thirdWednesday = FuturesExpiryUtilityFunctions.ThirdWednesday(time);
                    var secondBusinessDayPrecedingThirdWednesday = FuturesExpiryUtilityFunctions.AddBusinessDays(thirdWednesday,-2);
                    return secondBusinessDayPrecedingThirdWednesday.Add(new TimeSpan(14,16,0));
                })
            },
            // NZD (6N): http://www.cmegroup.com/trading/fx/g10/new-zealand-dollar_contract_specifications.html
            {Futures.Currencies.NZD, (time =>
                {
                    // 9:16 a.m. Central Time (CT) on the second business day immediately preceding the third Wednesday of the contract month (usually Monday).
                    var thirdWednesday = FuturesExpiryUtilityFunctions.ThirdWednesday(time);
                    var secondBusinessDayPrecedingThirdWednesday = FuturesExpiryUtilityFunctions.AddBusinessDays(thirdWednesday,-2);
                    return secondBusinessDayPrecedingThirdWednesday.Add(new TimeSpan(14,16,0));
                })
            },
            // RUB (6R): https://www.cmegroup.com/trading/fx/emerging-market/russian-ruble_contract_specifications.html
            {Futures.Currencies.RUB, (time =>
                {
                    // 11:00 a.m. Mosccow time on the fifteenth day of the month, or, if not a business day, on the next business day for the Moscow interbank foreign exchange market.
                    var fifteenth = new DateTime(time.Year, time.Month, 15);

                    while (!FuturesExpiryUtilityFunctions.NotHoliday(fifteenth))
                    {
                        fifteenth = FuturesExpiryUtilityFunctions.AddBusinessDays(fifteenth, 1);
                    }
                    return fifteenth.Add(new TimeSpan(08,0,0));
                })
            },
            // BRL (6L): https://www.cmegroup.com/trading/fx/emerging-market/brazilian-real_contract_specifications.html
            {Futures.Currencies.BRL, (time =>
                {
                    // On the last business day of the month, at 9:15 a.m. CT, immediately preceding the contract month, on which the Central Bank of Brazil is scheduled to publish its final end-of-month (EOM), "Commercial exchange rate for Brazilian reais per U.S. dollar for cash delivery" (PTAX rate).
                    var lastPrecedingBusinessDay = FuturesExpiryUtilityFunctions.AddBusinessDays(time, -1);
                    var symbolHolidays = MarketHoursDatabase.FromDataFolder().GetEntry("usa", Futures.Currencies.BRL, SecurityType.Future)
                        .ExchangeHours
                        .Holidays;

                    while (symbolHolidays.Contains(lastPrecedingBusinessDay))
                    {
                        lastPrecedingBusinessDay = FuturesExpiryUtilityFunctions.AddBusinessDays(lastPrecedingBusinessDay, -1);
                    }

                    return lastPrecedingBusinessDay.Add(new TimeSpan(14,15,0));
                })
            },
            // MXN (6M): https://www.cmegroup.com/trading/fx/emerging-market/mexican-peso_contract_specifications.html
            {Futures.Currencies.MXN, (time =>
                {
                    // 9:16 a.m. Central Time (CT) on the second business day immediately preceding the third Wednesday of the contract month (usually Monday).
                    var thirdWednesday = FuturesExpiryUtilityFunctions.ThirdWednesday(time);
                    var secondBusinessDayPrecedingThirdWednesday = FuturesExpiryUtilityFunctions.AddBusinessDays(thirdWednesday,-2);

                    var symbolHolidays = MarketHoursDatabase.FromDataFolder().GetEntry("usa", Futures.Currencies.MXN, SecurityType.Future)
                        .ExchangeHours
                        .Holidays;

                    // Columbus Day as per SIFMA holiday schedule
                    if (symbolHolidays.Contains(secondBusinessDayPrecedingThirdWednesday))
                    {
                        secondBusinessDayPrecedingThirdWednesday = FuturesExpiryUtilityFunctions.AddBusinessDays(secondBusinessDayPrecedingThirdWednesday, -1);
                    }
                    return secondBusinessDayPrecedingThirdWednesday.Add(new TimeSpan(14,16,0));
                })
            },
            // ZAR (6Z): https://www.cmegroup.com/trading/fx/emerging-market/south-african-rand_contract_specifications.html
            {Futures.Currencies.ZAR, (time =>
                {
                    // 9:16 a.m. Central Time (CT) on the second business day immediately preceding the third Wednesday of the contract month (usually Monday)
                    var thirdWednesday = FuturesExpiryUtilityFunctions.ThirdWednesday(time);
                    var secondBusinessDayPrecedingThirdWednesday = FuturesExpiryUtilityFunctions.AddBusinessDays(thirdWednesday, -2);

                    var symbolHolidays = MarketHoursDatabase.FromDataFolder().GetEntry("usa", Futures.Currencies.ZAR, SecurityType.Future)
                        .ExchangeHours
                        .Holidays;

                    while (symbolHolidays.Contains(secondBusinessDayPrecedingThirdWednesday))
                    {
                        secondBusinessDayPrecedingThirdWednesday = FuturesExpiryUtilityFunctions.AddBusinessDays(secondBusinessDayPrecedingThirdWednesday, -1);
                    }
                    return secondBusinessDayPrecedingThirdWednesday.Add(new TimeSpan(14,16,0));
                })
            },
            // AUD/CAD (ACD): https://www.cmegroup.com/trading/fx/g10/australian-dollar-canadian-dollar_contract_specifications.html
            {Futures.Currencies.AUDCAD, (time =>
                {
                    // 9:16 a.m. Central Time (CT) on the second business day immediately preceding the third Wednesday of the contract month (usually Monday)
                    var thirdWednesday = FuturesExpiryUtilityFunctions.ThirdWednesday(time);
                    var secondBusinessDayPrecedingThirdWednesday = FuturesExpiryUtilityFunctions.AddBusinessDays(thirdWednesday, -2);

                    var holidays = MarketHoursDatabase.FromDataFolder()
                        .GetEntry("usa", Futures.Currencies.AUDCAD, SecurityType.Future)
                        .ExchangeHours
                        .Holidays;

                    while (holidays.Contains(secondBusinessDayPrecedingThirdWednesday))
                    {
                        secondBusinessDayPrecedingThirdWednesday =  FuturesExpiryUtilityFunctions.AddBusinessDays(secondBusinessDayPrecedingThirdWednesday, -1);
                    }

                    return secondBusinessDayPrecedingThirdWednesday.Add(new TimeSpan(14,16,0));
                })
            },
            // Financials group
            // Y30TreasuryBond (ZB): http://www.cmegroup.com/trading/interest-rates/us-treasury/30-year-us-treasury-bond_contract_specifications.html
            {Futures.Financials.Y30TreasuryBond, (time =>
                {
                    //  Seventh business day preceding the last business day of the delivery month. Trading in expiring contracts closes at 12:01 p.m. on the last trading day.
                    var lastBusinessDay = FuturesExpiryUtilityFunctions.NthLastBusinessDay(time, 1);
                    var seventhBusinessDayPrecedingLastBusinessDay = FuturesExpiryUtilityFunctions.AddBusinessDays(lastBusinessDay,-7);
                    return seventhBusinessDayPrecedingLastBusinessDay.Add(new TimeSpan(12,01,0));
                })
            },
            // Y10TreasuryNote (ZN): http://www.cmegroup.com/trading/interest-rates/us-treasury/10-year-us-treasury-note_contract_specifications.html
            {Futures.Financials.Y10TreasuryNote, (time =>
                {
                    //  Seventh business day preceding the last business day of the delivery month. Trading in expiring contracts closes at 12:01 p.m. on the last trading day.
                    var lastBusinessDay = FuturesExpiryUtilityFunctions.NthLastBusinessDay(time, 1);
                    var seventhBusinessDayPrecedingLastBusinessDay = FuturesExpiryUtilityFunctions.AddBusinessDays(lastBusinessDay,-7);
                    return seventhBusinessDayPrecedingLastBusinessDay.Add(new TimeSpan(12,01,0));
                })
            },
            // Y5TreasuryNote (ZF): http://www.cmegroup.com/trading/interest-rates/us-treasury/5-year-us-treasury-note_contract_specifications.html
            {Futures.Financials.Y5TreasuryNote, (time =>
                {
                    // Last business day of the calendar month. Trading in expiring contracts closes at 12:01 p.m. on the last trading day.
                    var lastBusinessDay = FuturesExpiryUtilityFunctions.NthLastBusinessDay(time, 1);
                    return lastBusinessDay.Add(new TimeSpan(12,01,0));
                })
            },
            // Y2TreasuryNote (ZT): http://www.cmegroup.com/trading/interest-rates/us-treasury/2-year-us-treasury-note_contract_specifications.html
            {Futures.Financials.Y2TreasuryNote, (time =>
                {
                    // Last business day of the calendar month. Trading in expiring contracts closes at 12:01 p.m. on the last trading day.
                    var lastBusinessDay = FuturesExpiryUtilityFunctions.NthLastBusinessDay(time, 1);
                    return lastBusinessDay.Add(new TimeSpan(12,01,0));
                })
            },
            // EuroDollar Futures : TODO London bank calendar

            // Energies group
            //Propane Non LDH Mont Belvieu (1S): https://www.cmegroup.com/trading/energy/petrochemicals/propane-non-ldh-mt-belvieu-opis-balmo-swap_contract_specifications.html
            {Futures.Energies.PropaneNonLDHMontBelvieu, (time =>
                {
                    // Trading shall cease on the last business day of the contract month (no time specified)
                    return FuturesExpiryUtilityFunctions.NthLastBusinessDay(time, 1);
                })
            },
            // Argus Propane Far East Index BALMO (22): https://www.cmegroup.com/trading/energy/petrochemicals/argus-propane-far-east-index-balmo-swap-futures_contract_specifications.html
            {Futures.Energies.ArgusPropaneFarEastIndexBALMO, (time =>
                {
                    // Trading shall cease on the last business day of the contract month. Business days are based on the Singapore Public Holiday calendar.
                    // TODO: Might need singapore calendar
                    return FuturesExpiryUtilityFunctions.NthLastBusinessDay(time, 1);
                })
            },
            // Mini European 3.5% Fuel Oil Barges FOB Rdam (Platts) (A0D): https://www.cmegroup.com/trading/energy/refined-products/mini-european-35pct-fuel-oil-platts-barges-fob-rdam-swap-futures_contract_specifications.html
            {Futures.Energies.MiniEuropeanThreePointPercentFiveFuelOilBargesPlatts, (time =>
                {
                    // Trading shall cease on the last business day of the contract month.
                    var lastBusinessDay = FuturesExpiryUtilityFunctions.NthLastBusinessDay(time, 1);
                    var holidays = MarketHoursDatabase.FromDataFolder()
                        .GetEntry("usa", Futures.Energies.MiniEuropeanThreePointPercentFiveFuelOilBargesPlatts, SecurityType.Future)
                        .ExchangeHours
                        .Holidays;

                    while (holidays.Contains(lastBusinessDay))
                    {
                        lastBusinessDay = FuturesExpiryUtilityFunctions.AddBusinessDays(lastBusinessDay, -1);
                    }

                    return lastBusinessDay;
                })
            },
            // Mini Singapore Fuel Oil 180 cst (Platts) (A0F): https://www.cmegroup.com/trading/energy/refined-products/mini-singapore-fuel-oil-180-cst-platts-swap-futures_contract_specifications.html
            {Futures.Energies.MiniSingaporeFuelOil180CstPlatts, (time =>
                {
                    // Trading shall cease on the last business day of the contract month.
                    // Special case exists where the last trade occurs on US holiday, but not an exchange holiday (markets closed)
                    // In order to fix that case, we will start from the last day of the month and go backwards checking if it's a weekday and a holiday
                    var lastDay = new DateTime(time.Year, time.Month, DateTime.DaysInMonth(time.Year, time.Month));
                    var holidays = MarketHoursDatabase.FromDataFolder()
                        .GetEntry("usa", Futures.Energies.MiniSingaporeFuelOil180CstPlatts, SecurityType.Future)
                        .ExchangeHours
                        .Holidays;

                    while (holidays.Contains(lastDay) || !lastDay.IsCommonBusinessDay())
                    {
                        lastDay = lastDay.AddDays(-1);
                    }

                    return lastDay;
                })
            },
            // Gulf Coast ULSD (Platts) Up-Down BALMO Futures (A1L): https://www.cmegroup.com/trading/energy/refined-products/ulsd-up-down-balmo-calendar-swap-futures_contract_specifications.html
            {Futures.Energies.GulfCoastULSDPlattsUpDownBALMO, (time =>
                {
                    // Trading shall cease on the last business day of the contract month.
                    return FuturesExpiryUtilityFunctions.NthLastBusinessDay(time, 1);
                })
            },
            // Gulf Coast Jet (Platts) Up-Down BALMO Futures (A1M): https://www.cmegroup.com/trading/energy/refined-products/jet-fuel-up-down-balmo-calendar-swap_contract_specifications.html
            {Futures.Energies.GulfCoastJetPlattsUpDownBALMO, (time =>
                {
                    // Trading shall cease on the last business day of the contract month.
                    return FuturesExpiryUtilityFunctions.NthLastBusinessDay(time, 1);
                })
            },
            // Propane Non-LDH Mont Belvieu (OPIS) Futures (A1R): https://www.cmegroup.com/trading/energy/petrochemicals/propane-non-ldh-mt-belvieu-opis-swap_contract_specifications.html
            {Futures.Energies.PropaneNonLDHMontBelvieuOPIS, (time =>
                {
                    // Trading shall cease on the last business day of the contract month.
                    return FuturesExpiryUtilityFunctions.NthLastBusinessDay(time, 1);
                })
            },
            // European Propane CIF ARA (Argus) BALMO Futures (A32): https://www.cmegroup.com/trading/energy/petrochemicals/european-propane-cif-ara-argus-balmo-swap-futures_contract_specifications.html
            {Futures.Energies.EuropeanPropaneCIFARAArgusBALMO, (time =>
                {
                    // Trading shall cease on the last business day of the contract month.
                    return FuturesExpiryUtilityFunctions.NthLastBusinessDay(time, 1);
                })
            },
            // Premium Unleaded Gasoline 10 ppm FOB MED (Platts) Futures (A3G): https://www.cmegroup.com/trading/energy/refined-products/premium-unleaded-10-ppm-platts-fob-med-swap_contract_specifications.html
            {Futures.Energies.PremiumUnleadedGasoline10ppmFOBMEDPlatts, (time =>
                {
                    var lastBusinessDay = FuturesExpiryUtilityFunctions.NthLastBusinessDay(time, 1);
                    var holidays = MarketHoursDatabase.FromDataFolder()
                        .GetEntry("usa", Futures.Energies.PremiumUnleadedGasoline10ppmFOBMEDPlatts, SecurityType.Future)
                        .ExchangeHours
                        .Holidays;

                    while (holidays.Contains(lastBusinessDay))
                    {
                        lastBusinessDay = FuturesExpiryUtilityFunctions.AddBusinessDays(lastBusinessDay, -1);
                    }

                    return lastBusinessDay;
                })
            },
            // Argus Propane Far East Index Futures (A7E):
            {Futures.Energies.ArgusPropaneFarEastIndex, (time =>
                {
                    // Trading shall cease on the last business day of the contract month.
                    return FuturesExpiryUtilityFunctions.NthLastBusinessDay(time, 1);
                })
            },
            // Gasoline Euro-bob Oxy NWE Barges (Argus) Crack Spread BALMO Futures (A7I): https://www.cmegroup.com/trading/energy/refined-products/gasoline-euro-bob-oxy-new-barges-crack-spread-balmo-swap-futures_contract_specifications.html
            {Futures.Energies.GasolineEurobobOxyNWEBargesArgusCrackSpreadBALMO, (time =>
                {
                    // Trading ceases on the last business day of the contract month.
                    return FuturesExpiryUtilityFunctions.NthLastBusinessDay(time, 1);
                })
            },
            // Mont Belvieu Natural Gasoline (OPIS) Futures (A7Q): https://www.cmegroup.com/trading/energy/petrochemicals/mont-belvieu-natural-gasoline-5-decimal-opis-swap_contract_specifications.html
            {Futures.Energies.MontBelvieuNaturalGasolineOPIS, (time =>
                {
                    // Trading shall cease on the last business day of the contract month
                    return FuturesExpiryUtilityFunctions.NthLastBusinessDay(time, 1);
                })
            },
            // Mont Belvieu Normal Butane (OPIS) BALMO Futures (A8J): https://www.cmegroup.com/trading/energy/petrochemicals/mont-belvieu-normal-butane-opis-balmo-swap_contract_specifications.html
            {Futures.Energies.MontBelvieuNormalButaneOPISBALMO, (time =>
                {
                    // Trading terminates on the last business day of the contract month.
                    return FuturesExpiryUtilityFunctions.NthLastBusinessDay(time, 1);
                })
            },
            // Conway Propane (OPIS) Futures (A8K): https://www.cmegroup.com/trading/energy/petrochemicals/conway-propane-opis-swap_contract_specifications.html
            {Futures.Energies.ConwayPropaneOPIS, (time =>
                {
                    // Trading shall cease on the last business day of the contract month.
                    return FuturesExpiryUtilityFunctions.NthLastBusinessDay(time, 1);
                })
            },
            // Mont Belvieu LDH Propane (OPIS) BALMO Futures (A8O): https://www.cmegroup.com/trading/energy/petrochemicals/mont-belvieu-ldh-propane-opis-balmo-swap-futures_contract_specifications.html
            {Futures.Energies.MontBelvieuLDHPropaneOPISBALMO, (time =>
                {
                    // Trading shall cease on the last business day of the contract month.
                    return FuturesExpiryUtilityFunctions.NthLastBusinessDay(time, 1);
                })
            },
            // Argus Propane Far East Index vs. European Propane CIF ARA (Argus) Futures (A91): https://www.cmegroup.com/trading/energy/petrochemicals/argus-propane-far-east-index-vs-european-propane-cif-ara-argus-swap-futures_contract_specifications.html
            {Futures.Energies.ArgusPropaneFarEastIndexVsEuropeanPropaneCIFARAArgus, (time =>
                {
                    // Trading shall cease on the last business day of the contract month.
                    var lastBusinessDay = FuturesExpiryUtilityFunctions.NthLastBusinessDay(time, 1);
                    var holidays = MarketHoursDatabase.FromDataFolder()
                        .GetEntry("usa", Futures.Energies.ArgusPropaneFarEastIndexVsEuropeanPropaneCIFARAArgus, SecurityType.Future)
                        .ExchangeHours
                        .Holidays;

                    while (holidays.Contains(lastBusinessDay))
                    {
                        lastBusinessDay = FuturesExpiryUtilityFunctions.AddBusinessDays(lastBusinessDay, -1);
                    }

                    return lastBusinessDay;
                })
            },
            // Argus Propane (Saudi Aramco) Futures (A9N): https://www.cmegroup.com/trading/energy/petrochemicals/argus-propane-saudi-aramco-swap-futures_contract_specifications.html
            {Futures.Energies.ArgusPropaneSaudiAramco, (time =>
                {
                    // Trading shall terminate on the last business day of the month prior to the contract month.
                    // Business days are based on the Singapore Public Holiday Calendar.
                    // Special case in 2021 where last traded date falls on US Holiday, but not exchange holiday
                    var previousMonth = time.AddMonths(-1);
                    var lastDay = new DateTime(previousMonth.Year, previousMonth.Month, DateTime.DaysInMonth(previousMonth.Year, previousMonth.Month));
                    var holidays = MarketHoursDatabase.FromDataFolder()
                        .GetEntry("usa", Futures.Energies.ArgusPropaneSaudiAramco, SecurityType.Future)
                        .ExchangeHours
                        .Holidays;

                    while (!lastDay.IsCommonBusinessDay() || holidays.Contains(lastDay))
                    {
                        lastDay = lastDay.AddDays(-1);
                    }

                    return lastDay;
                })
            },
            // Group Three ULSD (Platts) vs. NY Harbor ULSD Futures (AA6): https://www.cmegroup.com/trading/energy/refined-products/group-three-ultra-low-sulfur-diesel-ulsd-platts-vs-heating-oil-spread-swap_contract_specifications.html
            {Futures.Energies.GroupThreeULSDPlattsVsNYHarborULSD, (time =>
                {
                    // Trading shall cease on the last business day of the contract month.
                    return FuturesExpiryUtilityFunctions.NthLastBusinessDay(time, 1);
                })
            },
            // Group Three Sub-octane Gasoline (Platts) vs. RBOB Futures (AA8): https://www.cmegroup.com/trading/energy/refined-products/group-three-unleaded-gasoline-platts-vs-rbob-spread-swap_contract_specifications.html
            {Futures.Energies.GroupThreeSuboctaneGasolinePlattsVsRBOB, (time =>
                {
                    // Trading shall cease on the last business day of the contract month
                    return FuturesExpiryUtilityFunctions.NthLastBusinessDay(time, 1);
                })
            },
            // Singapore Fuel Oil 180 cst (Platts) BALMO Futures (ABS): https://www.cmegroup.com/trading/energy/refined-products/singapore-180cst-fuel-oil-balmo-swap_contract_specifications.html
            {Futures.Energies.SingaporeFuelOil180cstPlattsBALMO, (time =>
                {
                    // Trading shall cease on the last business day of the contract month.
                    return FuturesExpiryUtilityFunctions.NthLastBusinessDay(time, 1);
                })
            },
            // Singapore Fuel Oil 380 cst (Platts) BALMO Futures (ABT): https://www.cmegroup.com/trading/energy/refined-products/singapore-380cst-fuel-oil-balmo-swap_contract_specifications.html
            {Futures.Energies.SingaporeFuelOil380cstPlattsBALMO, (time =>
                {
                    // Trading shall cease on the last business day of the contract month.
                    return FuturesExpiryUtilityFunctions.NthLastBusinessDay(time, 1);
                })
            },
            // Mont Belvieu Ethane (OPIS) Futures (AC0): https://www.cmegroup.com/trading/energy/petrochemicals/mont-belvieu-ethane-opis-5-decimals-swap_contract_specifications.html
            {Futures.Energies.MontBelvieuEthaneOPIS, (time =>
                {
                    // Trading shall cease on the last business day of the contract month.
                    return FuturesExpiryUtilityFunctions.NthLastBusinessDay(time, 1);
                })
            },
            // Mont Belvieu Normal Butane (OPIS) Futures (AD0): https://www.cmegroup.com/trading/energy/petrochemicals/mont-belvieu-normal-butane-5-decimals-swap_contract_specifications.html
            {Futures.Energies.MontBelvieuNormalButaneOPIS, (time =>
                {
                    // Trading shall cease on the last business day of the contract month.
                    return FuturesExpiryUtilityFunctions.NthLastBusinessDay(time, 1);
                })
            },
            // Brent Crude Oil vs. Dubai Crude Oil (Platts) Futures (ADB): https://www.cmegroup.com/trading/energy/crude-oil/brent-dubai-swap-futures_contract_specifications.html
            {Futures.Energies.BrentCrudeOilVsDubaiCrudeOilPlatts, (time =>
                {
                    // Trading shall cease on the last London and Singapore business day of the contract month.
                    var lastBusinessDay = FuturesExpiryUtilityFunctions.NthLastBusinessDay(time, 1);
                    var holidays = MarketHoursDatabase.FromDataFolder()
                        .GetEntry("usa", Futures.Energies.BrentCrudeOilVsDubaiCrudeOilPlatts, SecurityType.Future)
                        .ExchangeHours
                        .Holidays;

                    while (holidays.Contains(lastBusinessDay))
                    {
                        lastBusinessDay = FuturesExpiryUtilityFunctions.AddBusinessDays(lastBusinessDay, -1);
                    }

                    return lastBusinessDay;
                })
            },
            // Argus LLS vs. WTI (Argus) Trade Month Futures (AE5): https://www.cmegroup.com/trading/energy/crude-oil/argus-lls-vs-wti-argus-trade-month-swap-futures_contract_specifications.html
            {Futures.Energies.ArgusLLSvsWTIArgusTradeMonth, (time =>
                {
                    // Trading shall cease at the close of trading on the last business day that falls on or before the 25th calendar day of the month prior to the contract month. If the 25th calendar day is a weekend or holiday, trading shall cease on the first business day prior to the 25th calendar day.
                    var previousMonth = time.AddMonths(-1);
                    var twentyFifthDay = new DateTime(previousMonth.Year, previousMonth.Month, 25);
                    var holidays = MarketHoursDatabase.FromDataFolder()
                        .GetEntry("usa", Futures.Energies.ArgusLLSvsWTIArgusTradeMonth, SecurityType.Future)
                        .ExchangeHours
                        .Holidays;

                    while (!twentyFifthDay.IsCommonBusinessDay() || holidays.Contains(twentyFifthDay))
                    {
                        twentyFifthDay = FuturesExpiryUtilityFunctions.AddBusinessDays(twentyFifthDay, -1);
                    }

                    return twentyFifthDay;
                })
            },
            // CrudeOilWTI (CL): http://www.cmegroup.com/trading/energy/crude-oil/light-sweet-crude_contract_specifications.html
            {Futures.Energies.CrudeOilWTI, (time =>
                {
                    // Trading in the current delivery month shall cease on the third business day prior to the twenty-fifth calendar day of the month preceding the delivery month. If the twenty-fifth calendar day of the month is a non-business day, trading shall cease on the third business day prior to the last business day preceding the twenty-fifth calendar day. In the event that the official Exchange holiday schedule changes subsequent to the listing of a Crude Oil futures, the originally listed expiration date shall remain in effect.In the event that the originally listed expiration day is declared a holiday, expiration will move to the business day immediately prior.
                    var twentyFifth = new DateTime(time.Year,time.Month,25);
                    twentyFifth = twentyFifth.AddMonths(-1);
                    if(FuturesExpiryUtilityFunctions.NotHoliday(twentyFifth))
                    {
                        return FuturesExpiryUtilityFunctions.AddBusinessDays(twentyFifth,-3);
                    }
                    else
                    {
                        var lastBuisnessDay = FuturesExpiryUtilityFunctions.AddBusinessDays(twentyFifth,-1);
                        return FuturesExpiryUtilityFunctions.AddBusinessDays(lastBuisnessDay,-3);
                    }
                })
            },
            // HeatingOil (HO): http://www.cmegroup.com/trading/energy/refined-products/heating-oil_contract_specifications.html
            {Futures.Energies.HeatingOil, (time =>
                {
                    // Trading in a current month shall cease on the last business day of the month preceding the delivery month.
                    var precedingMonth = time.AddMonths(-1);
                    return FuturesExpiryUtilityFunctions.NthLastBusinessDay(precedingMonth, 1);
                })
            },
            // Gasoline (RB): http://www.cmegroup.com/trading/energy/refined-products/rbob-gasoline_contract_specifications.html
            {Futures.Energies.Gasoline, (time =>
                {
                    // Trading in a current delivery month shall cease on the last business day of the month preceding the delivery month.
                    var precedingMonth = time.AddMonths(-1);
                    return FuturesExpiryUtilityFunctions.NthLastBusinessDay(precedingMonth, 1);
                })
            },
            // Natural Gas (NG) : http://www.cmegroup.com/trading/energy/natural-gas/natural-gas_contract_specifications.html
            {Futures.Energies.NaturalGas, (time =>
                {
                    //Trading of any delivery month shall cease three (3) business days prior to the first day of the delivery month. In the event that the official Exchange holiday schedule changes subsequent to the listing of a Natural Gas futures, the originally listed expiration date shall remain in effect.In the event that the originally listed expiration day is declared a holiday, expiration will move to the business day immediately prior.
                    var firstDay = new DateTime(time.Year,time.Month,1);
                    return FuturesExpiryUtilityFunctions.AddBusinessDays(firstDay,-3);
                })
            },

            // Meats group
            // LiveCattle (LE): http://www.cmegroup.com/trading/agricultural/livestock/live-cattle_contract_specifications.html
            {Futures.Meats.LiveCattle, (time =>
                {
                    //Last business day of the contract month, 12:00 p.m.
                    var lastBusinessDay = FuturesExpiryUtilityFunctions.NthLastBusinessDay(time, 1);
                    return lastBusinessDay.Add(new TimeSpan(12,0,0));
                })
            },
            // LeanHogs (HE): http://www.cmegroup.com/trading/agricultural/livestock/lean-hogs_contract_specifications.html
            {Futures.Meats.LeanHogs, (time =>
                {
                    // 10th business day of the contract month, 12:00 p.m.
                    var lastday = new DateTime(time.Year,time.Month,1);
                    lastday = lastday.AddDays(-1);
                    var tenthday = FuturesExpiryUtilityFunctions.AddBusinessDays(lastday,10);
                    return tenthday.Add(new TimeSpan(12,0,0));
                })
            },
            // FeederCattle (GF): http://www.cmegroup.com/trading/agricultural/livestock/feeder-cattle_contract_specifications.html
            {Futures.Meats.FeederCattle, (time =>
                {
                    /* Trading shall terminate on the last Thursday of the contract month, except:
                     * 1. The November contract shall terminate on the Thursday
                     * prior to Thanksgiving Day, unless a holiday falls on
                     * that Thursday or on any of the four weekdays prior to
                     * that Thursday, in which case trading shall terminate on
                     * the first prior Thursday that is not a holiday and is
                     * not so preceded by a holiday. Weekdays shall be defined
                     * as Monday, Tuesday, Wednesday, Thursday and Friday.
                     * 2. Any contract month in which a holiday falls on the last
                     * Thursday of the month or on any of the four weekdays
                     * prior to that Thursday shall terminate on the first
                     * prior Thursday that is not a holiday and is not so
                     * preceded by a holiday.*/
                    var daysInMonth = DateTime.DaysInMonth(time.Year, time.Month);
                    // Checking condition 1
                    if(time.Month == 11)
                    {
                        var priorThursday = (from day in Enumerable.Range(1, daysInMonth)
                                  where new DateTime(time.Year, time.Month, day).DayOfWeek == DayOfWeek.Thursday
                                  select new DateTime(time.Year, time.Month, day)).Reverse().ElementAt(1);
                        while (!FuturesExpiryUtilityFunctions.NotHoliday(priorThursday) || !FuturesExpiryUtilityFunctions.NotPrecededByHoliday(priorThursday))
                        {
                            priorThursday = priorThursday.AddDays(-7);
                        }
                        return priorThursday;
                    }
                    // Checking Condition 2
                    var lastThursday = (from day in Enumerable.Range(1, daysInMonth)
                                  where new DateTime(time.Year, time.Month, day).DayOfWeek == DayOfWeek.Thursday
                                  select new DateTime(time.Year, time.Month, day)).Reverse().ElementAt(0);
                    while (!FuturesExpiryUtilityFunctions.NotHoliday(lastThursday) || !FuturesExpiryUtilityFunctions.NotPrecededByHoliday(lastThursday))
                    {
                        lastThursday = lastThursday.AddDays(-7);
                    }
                    return lastThursday;
                })
            },
            // Sugar #11 CME (YO): https://www.cmegroup.com/trading/agricultural/softs/sugar-no11_contract_specifications.html
            {Futures.Softs.Sugar11CME, (time =>
                {
                    // Trading terminates on the day immediately preceding the first notice day of the corresponding trading month of Sugar No. 11 futures at ICE Futures U.S.
                    var precedingMonth = time.AddMonths(-1);
                    return FuturesExpiryUtilityFunctions.NthLastBusinessDay(precedingMonth, 1);
                })
            }
        };
    }
}


text:
class Template {
  constructor() {

  }
  default(command){ // This is the default command that is ran when you do your bot prefix and your plugin prefix example   !ping
    var self = this;
    self.disnode.bot.
  }
  commandTest(command){
    var self = this;
    self.disnode.bot.SendMessage(command.msg.channel, "Working Command!: " );
  }
}
module.exports = Template;


text:
js css extension for relative properties

###How to use
to make a div element with height of 40% from window and width of 80% from element with id 'someElement':

```html
<div csse-style="height: window|40%;width: #someElement > .someClass|80%;"></div>
```

The syntax is similar to css. {propertyName} : {selector|window|screen} | {percentage};

And in the document ready event call
```javascript
csse.bootstrap()
```


text:
package org.gearvrf;

import org.gearvrf.utility.Log;
import org.joml.Vector4f;

import java.util.LinkedList;

/**
 * Example:
 * <pre>
 * root = new GVRSceneObject(..);
 *
 * sphereHighDensity = new GVRSceneObject(..);
 * sphereMediumDensity = new GVRSceneObject(..);
 * sphereLowDensity = new GVRSceneObject(..);
 *
 * GVRLODGroup lodGroup = new GVRLODGroup(gvrContext);
 * lodGroup.addRange(0, sphereHighDensity);
 * lodGroup.addRange(5, sphereMediumDensity);
 * lodGroup.addRange(9, sphereLowDensity);
 * root.attachComponent(lodGroup);
 * </pre>
 */
public final class GVRLODGroup extends GVRBehavior {
    static private long TYPE_LODGROUP = newComponentType(GVRLODGroup.class);

    public GVRLODGroup(GVRContext gvrContext) {
        super(gvrContext, 0);
        mType = getComponentType();
    }

    static public long getComponentType() {
        return TYPE_LODGROUP;
    }

    private final Vector4f mCenter = new Vector4f();
    private final Vector4f mVector = new Vector4f();
    private final LinkedList<Object[]> mRanges = new LinkedList<>();

    /**
     * Add a range to this LOD group. Specify the scene object that should be displayed in this
     * range. Add the LOG group as a component to the parent scene object. The scene objects
     * associated with each range will automatically be added as children to the parent.
     * @param range show the scene object if the camera distance is greater than this value
     * @param sceneObject scene object that should be rendered when in this range
     * @throws IllegalArgumentException if range is negative or sceneObject null
     */
    public synchronized void addRange(final float range, final GVRSceneObject sceneObject)
    {
        if (null == sceneObject) {
            throw new IllegalArgumentException("sceneObject must be specified!");
        }
        if (range < 0) {
            throw new IllegalArgumentException("range cannot be negative");
        }

        final int size = mRanges.size();
        final float rangePow2 = range*range;
        final Object[] newElement = new Object[] {rangePow2, sceneObject};

        for (int i = 0; i < size; ++i) {
            final Object[] el = mRanges.get(i);
            final Float r = (Float)el[0];
            if (r > rangePow2) {
                mRanges.add(i, newElement);
                break;
            }
        }

        if (mRanges.size() == size) {
            mRanges.add(newElement);
        }

        final GVRSceneObject owner = getOwnerObject();
        if (null != owner) {
            owner.addChildObject(sceneObject);
        }
    }

    /**
     * Do not call directly.
     * @deprecated
     */
    public void onDrawFrame(float frameTime) {
        final GVRSceneObject owner = getOwnerObject();
        if (owner == null) {
            return;
        }

        final int size = mRanges.size();
        final GVRTransform t = getGVRContext().getMainScene().getMainCameraRig().getCenterCamera().getTransform();

        for (final Object[] range : mRanges) {
            ((GVRSceneObject)range[1]).setEnable(false);
        }

        for (int i = size - 1; i >= 0; --i) {
            final Object[] range = mRanges.get(i);
            final GVRSceneObject child = (GVRSceneObject) range[1];
            if (child.getParent() != owner) {
                Log.w(TAG, "the scene object for distance greater than " + range[0] + " is not a child of the owner; skipping it");
                continue;
            }

            final float[] values = child.getBoundingVolumeRawValues();
            mCenter.set(values[0], values[1], values[2], 1.0f);
            mVector.set(t.getPositionX(), t.getPositionY(), t.getPositionZ(), 1.0f);

            mVector.sub(mCenter);
            mVector.negate();

            float distance = mVector.dot(mVector);

            if (distance >= (Float) range[0]) {
                child.setEnable(true);
                break;
            }
        }
    }

    @Override
    public synchronized void onAttach(GVRSceneObject newOwner) {
        super.onAttach(newOwner);

        for (final Object[] el : mRanges) {
            newOwner.addChildObject((GVRSceneObject)el[1]);
        }
    }

    @Override
    public synchronized void onDetach(GVRSceneObject oldOwner) {
        super.onDetach(oldOwner);

        for (final Object[] el : mRanges) {
            oldOwner.removeChildObject((GVRSceneObject)el[1]);
        }
    }

    private static final String TAG = "GVRLODGroup";
}