text:
<?php

/**
 * This file is part of the Nextras community extensions of Nette Framework
 *
 * @license    New BSD License
 * @link       https://github.com/nextras/migrations
 */

namespace Nextras\Migrations\Engine;

use DateTime;
use Nextras\Migrations\Entities\File;
use Nextras\Migrations\Entities\Group;
use Nextras\Migrations\Entities\Migration;
use Nextras\Migrations\Exception;
use Nextras\Migrations\ExecutionException;
use Nextras\Migrations\IDriver;
use Nextras\Migrations\IExtensionHandler;
use Nextras\Migrations\IPrinter;
use Nextras\Migrations\LogicException;

class Runner
{
	/** @const modes */
	const MODE_CONTINUE = 'continue';
	const MODE_RESET = 'reset';
	const MODE_INIT = 'init';

	/** @var IPrinter */
	private $printer;

	/** @var array (extension => IExtensionHandler) */
	private $extensionsHandlers = array();

	/** @var Group[] */
	private $groups = array();

	/** @var IDriver */
	private $driver;

	/** @var Finder */
	private $finder;

	/** @var OrderResolver */
	private $orderResolver;

	public function __construct(IDriver $driver, IPrinter $printer)
	{
		$this->driver = $driver;
		$this->printer = $printer;
		$this->finder = new Finder;
		$this->orderResolver = new OrderResolver;
	}

	public function addGroup(Group $group)
	{
		$this->groups[] = $group;
		return $this;
	}

	/**
	 * @param  string            $extension
	 * @param  IExtensionHandler $handler
	 * @return self
	 */
	public function addExtensionHandler($extension, IExtensionHandler $handler)
	{
		if (isset($this->extensionsHandlers[$extension])) {
			throw new LogicException("Extension '$extension' has already been defined.");
		}

		$this->extensionsHandlers[$extension] = $handler;
		return $this;
	}

	/**
	 * @param  string $mode self::MODE_CONTINUE|self::MODE_RESET|self::MODE_INIT
	 * @return void
	 */
	public function run($mode = self::MODE_CONTINUE)
	{
		if ($mode === self::MODE_INIT) {
			$this->printer->printSource($this->driver->getInitTableSource() . "\n");
			$files = $this->finder->find($this->groups, array_keys($this->extensionsHandlers));
			$files = $this->orderResolver->resolve(array(), $this->groups, $files, self::MODE_RESET);
			$this->printer->printSource($this->driver->getInitMigrationsSource($files));
			return;
		}

		try {

			$this->driver->setupConnection();
			$this->driver->lock();

			$this->printer->printIntro($mode);
			if ($mode === self::MODE_RESET) {
				$this->driver->emptyDatabase();
			}

			$this->driver->createTable();
			$migrations = $this->driver->getAllMigrations();
			$files = $this->finder->find($this->groups, array_keys($this->extensionsHandlers));
			$toExecute = $this->orderResolver->resolve($migrations, $this->groups, $files, $mode);
			$this->printer->printToExecute($toExecute);

			foreach ($toExecute as $file) {
				$time = microtime(TRUE);
				$queriesCount = $this->execute($file);
				$this->printer->printExecute($file, $queriesCount, microtime(TRUE) - $time);
			}

			$this->driver->unlock();
			$this->printer->printDone();

		} catch (Exception $e) {
			$this->driver->unlock();
			$this->printer->printError($e);
		}
	}

	/**
	 * @param  string $name
	 * @return IExtensionHandler
	 */
	public function getExtension($name)
	{
		if (!isset($this->extensionsHandlers[$name])) {
			throw new LogicException("Extension '$name' not found.");
		}
		return $this->extensionsHandlers[$name];
	}

	/**
	 * @param  File $file
	 * @return int  number of executed queries
	 */
	protected function execute(File $file)
	{
		$this->driver->beginTransaction();

		$migration = new Migration;
		$migration->group = $file->group->name;
		$migration->filename = $file->name;
		$migration->checksum = $file->checksum;
		$migration->executedAt = new DateTime('now');

		$this->driver->insertMigration($migration);

		try {
			$queriesCount = $this->getExtension($file->extension)->execute($file);
		} catch (\Exception $e) {
			$this->driver->rollbackTransaction();
			throw new ExecutionException(sprintf('Executing migration "%s" has failed.', $file->path), NULL, $e);
		}

		$this->driver->markMigrationAsReady($migration);
		$this->driver->commitTransaction();

		return $queriesCount;
	}

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

	<title>Custom styles</title>

		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<link rel="stylesheet" type="text/css" href="../../../codebase/dhtmlx.css"/>

Add row

Remove Selected Row

				<input type="button" name="some_name" value="update" onclick="myDataProcessor.sendData();">

redpajama_set_name: RedPajamaGithub


text:
package main

import "fmt"
import "reflect"

func main() {
  var i float64 = 3+4.5
  fmt.Println("type of i is", reflect.TypeOf(i))
  fmt.Println("value of i is", i)
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Urocystis bomareae Dietel & Neger

### Remarks
null


text:
\def\lang{eng} % -*- texinfo -*- for Texinfo V.3.1
\input texinfo
@setfilename yahtmle
@settitle Yet Another html-mode for Emacs
@direntry
* yahtml-e: (yahtmle).  Yet Another html-mode for Emacs (English).
@end direntry

@iftex
@c @syncodeindex fn cp
@c Last modified Fri May 11 15:42:22 2012 on firestorm
@syncodeindex vr cp
@end iftex

@titlepage
@sp 10
@center
@subtitle Yet Another html-mode for emacs
@title // yahtml //
%@subtitle // yahtml //
@author @copyright{} 1994-2012 by    HIROSE, Yuuji [yuuji@@yatex.org]
@end titlepage

@node Top, Intro, (dir), (dir)
@comment  node-name,  next,  previous,  up

@menu
* Intro::                       Introduction
* Installation::                Installing yahtml
* Command Invocation::          Using External Commands
* Completion::                  Input with Completion
* Jump::                        Moving the Cursor
* Changing and Deleting::       Changing and Deleting
* CSS Support::                 Style Sheet Support
* Customizations::              List of Customize Variables
* Copying::                     Copyright
* Concept Index::               Index
@end menu

@node Intro, Installation, Top, Top
@comment  node-name,  next,  previous,  up
@chapter Introduction
@cindex Demacs
@cindex Mule
@cindex LaTeX
@cindex yahtml

yahtml is a package to support creating HTML documents on Emacsens.  Easy
input of elements (tags) by completion, syntax checking with programs like
weblint, and invoking the appropriate browser or image viewer depending on
the cursor position is its main features.

(This Info is still incomplete)

@node Installation, Command Invocation, Intro, Top
@comment  node-name,  next,  previous,  up
@chapter Installing yahtml
@menu
* Setting up yahtml::
* Setting environments for weblint browsers and image viewers::
* Setting environment variables for WWW pages::
@end menu

@node Setting up yahtml, Setting environments for weblint browsers and image viewers, Installation, Installation
@comment  node-name,  next,  previous,  up
@section Setting up yahtml

Add the following to @file{~/.emacs}

@lisp
(setq auto-mode-alist
      (cons (cons "\\.html$" 'yahtml-mode) auto-mode-alist))
(autoload 'yahtml-mode "yahtml" "Yet Another HTML mode" t)
@end lisp

Next, add to load-path the directory with the yahtml files
(@file{yahtml.el}, @file{yatexlib.el}, @file{yatexprc.el}).  For example,
if you put them in @file{~/src/emacs/yahtml},

@lisp
(setq load-path (cons (expand-file-name "~/src/emacs/yahtml") load-path))
@end lisp

@noindent
is what you add.

By this, yahtml will be automatically loaded when editing files with .html
extensions.  "yahtml" will be displayed on the mode line if no errors
occurred.

@node Setting environments for weblint browsers and image viewers, Setting environment variables for WWW pages, Setting up yahtml, Installation
@comment  node-name,  next,  previous,  up
@section Setting environments for weblint, browsers, and image viewers

Check the variables for invoking external commands and modify as needed.
Defaults are in parenthesis.

@table @code
@item yahtml-www-browser
        @dots{} browser command name (netscape)
@item yahtml-image-viewer
        @dots{} image viewer command name (xv)
@item yahtml-lint-program
        @dots{} syntax check programs command name (jweblint)
@item yahtml-kanji-code
        @dots{} kanji code for HTML files
@end table

@node Setting environment variables for WWW pages,  , Setting environments for weblint browsers and image viewers, Installation
@comment  node-name,  next,  previous,  up
@section Setting environment variables for WWW pages

Variables regarding path names for files that will be your home page.
@table @code
@item yahtml-path-url-alist
        @dots{} list of matching path name on file system and URLs
@item yahtml-directory-index
        @dots{} index file displayed when none is given in URL.  Usually
        @file{index.html} on NCSA type httpd and @file{Welcome.html} on
        CERN types.
@end table

Examples for  @code{yahtml-path-url-alist}.  If @file{/home/yuuji/http/}
is @code{http://localhost/~yuuji} at home and @file{/usr/home/yuuji/www/}
is @code{http://www.keio.ac.jp/~yuuji/} at work, then

@lisp
(setq yahtml-path-url-alist
      '(("/home/yuuji/http" . "http://localhost/~yuuji")
        ("/usr/home/yuuji/www" . "http://www.keio.ac.jp/~yuuji")))
@end lisp

Any number of additions can be made to this list.

@node Command Invocation, Completion, Installation, Top
@comment  node-name,  next,  previous,  up
@chapter Invoking external commands

For easy use of commands that are handy when editing HTML files.
@table @kbd
@item [prefix] t j
        @dots{} Invoke HTML syntax checker (jweblint)
@item [prefix] t p
        @dots{} Display current page in browser
@item [prefix] t r
        @dots{} Reload current page if browser is already running
@end table

@node Completion, Jump, Command Invocation, Top
@comment  node-name,  next,  previous,  up
@chapter Completion Input

Completion input of HTML elements is done through the same key strokes as
YaTeX's begin-type completion, section-type completion, large-type
completion, maketitle-type completion, and accent completion.
Corresponding elements in this order is; elements that span multiple
lines, empty elements such as img, tags that start and end in a
single line, elements with no attributes or contents, and special or
symbol entities.

@table @kbd
@item [prefix] b (YaTeX begin-type completion)
@dots{}
@example

@end example

@noindent
Completion for elements that the start tag and the end tag span multiple
lines. Mostly block-level elements.

@item [prefix] s (YateX section-type completion)
@dots{}
@example

@end example

@noindent
Completion for elements that do not have end tags and require only
attributes.  Possible completions are, , <input>.

@item [prefix] l (YaTeX large-type completion)
@dots{}

@example
<big> $B!A(B </big>
@end example

@noindent
Similar to begin-type completion but used for elements that start and end
on a single line.

@item [prefix] m (YaTeX maketitle-type completion)
@dots{} Completion for elements without attributes or contents.  Possible
completion is

@item [prefix] a (YaTeX accent completion)
@dots{} Used to enter special or symbol entities.  By default completion
for < (<), > (>), & (&), " ("), ' ('), blank ( )
is possible.
@end table

@node Jump, Changing and Deleting, Completion, Top
@comment  node-name,  next,  previous,  up
@chapter Cursor Movement
By using

@table @kbd
@item [prefix] g
        @dots{} move to corresponding object
@end table

@noindent
the cursor will go to the corresponding object according to the context.
Recognized contexts are

@itemize @bullet
@item @code{<TAG>} <--> @code{</TAG>}
@item @code{} -> invoke viewer
@item @code{} -> move cursor to linked target
@item @code{<applet code="program">} -> open Java source
@c @item @code{\include(\input)} $B"*(B $BBP1~$9$k%U%!%$%k(B
@end itemize

@node Changing and Deleting, CSS Support, Jump, Top
@comment  node-name,  next,  previous,  up
@chapter Changing and Deleting

@menu
* Changing tags in pairs::
* Changing entities::
* URLencoding of strings within region::
* td-enclosure/tr-enclosure::
@end menu

@node Changing tags in pairs, Changing entities, Changing and Deleting, Changing and Deleting
@comment  node-name,  next,  previous,  up
@section Changing tags in pairs
By using

@table @kbd
@item [prefix] c
        @dots{} change tags in matching pairs
@end table

@noindent
the content can be changed according to the context of the HTML document
where the cursor is located.

@itemize @bullet
@item @code{<TAG>}$B!A(B@code{</TAG>}
@dots{} change @code{TAG} element name
@item attributes such as @code{}
@dots{} change attributes
@end itemize

@node Changing entities, URLencoding of strings within region, Changing tags in pairs, Changing and Deleting
@comment  node-name,  next,  previous,  up
@section Changing entities
Special characters such as < or > must be written as < and >.  Easy
conversion of these characters can be done when importing text from non
HTML files.

@table @kbd
@item [prefix] ;
        @dots{} convert char to special entity in marked region
@item [prefix] :
        @dots{} convert special entity to original char in marked region
        (reverse of [prefix] ;)
@end table

@node URLencoding of strings within region, td-enclosure/tr-enclosure, Changing entities, Changing and Deleting
@comment  node-name,  next,  previous,  up
@section URLencoding of strings within region

@table @kbd
@item [prefix] #
	@dots{} encode chars that needs to be URLencoded within region
@end table

@node  td-enclosure/tr-enclosure,  , URLencoding of strings within region, Changing and Deleting
@comment  node-name,  next,  previous,  up
@section td-enclosure/tr-enclosure
If you wan to convert series of field into ...	 repetitions for
table element, td-enclosure or tr-enclosure is convenient.

@table @kbd
 @item [prefix] @}
	@dots{} Enclose each field in a region into ...	's.
 @item [prefix] ]
	@dots{} Enclose each line in a region into
...
's, with
        every line converted to ...	 repetition.
@end table
They presume white space as field separator by default.
To change this, enter other delimiting character for a query.
You can convert CSV, for example, into table by specifying
comma(,) as a delimiter.

If you want to enclose fields with th, call with
universal-argument (@kbd{C-u}).  Enter `th' to enclose fields
with ...	.  The special answer `thd' means that
enclose the only first column with th, and the rest with td.

@node CSS Support, Customizations, Changing and Deleting, Top
@comment  node-name,  next,  previous,  up
@chapter CSS(Style Sheets) Support

@menu
* CSS-class completion::
* Reread CSS definition::
@end menu

@node CSS-class completion, Reread CSS definition, CSS Support, CSS Support
@comment  node-name,  next,  previous,  up
@section CSS class-name completion
You can input a class name in your CSS definition with completion.
If you have CSS defined as below;

@display
 h1.foo, h2.foo @{ background-color: 0xffffff; @}
 h1.bar, h2.bar @{ font-size: 120%; @}
@end display

when you input h1(or h2) tag with completing-read by [prefix] b or
[prefix] l, yahtml prompts you to input class name with completion from
the words which are effective to h1 or h2.  And if you defined
global class like this;

@display
 .caution @{ font-size: 120%; background-color: 0xc00000;@}
@end display

when you input any tags via completing-read, yahtml prompts you to input
class name.  If this is bothering, typing @kbd{C-j} instead of
@kbd{RET} (or @kbd{C-m}) cancels the next prompt to class name completion.

@node Reread CSS definition,  , CSS-class completion, CSS Support
@comment  node-name,  next,  previous,  up
@section Re-reading CSS definition
If you add some class to your CSS file and you want yahtml to load
new definitions, type @kbd{M-x yahtml-mode RET} to make yahtml do.

@node Customizations, Copying, CSS Support, Top
@comment  node-name,  next,  previous,  up
@chapter Customizations
@cindex Customize
@cindex Key Assign

Variables that modify yahtml's behavior.

@menu
* All customizable variables::  List of customizable variables
* Hook variables::              hook variables
@end menu

@node All customizable variables, Hook variables, Customizations, Customizations
@comment  node-name,  next,  previous,  up
@section List of customizable variables.  Defaults in parenthesis

@defvar yahtml-prefix
Prefix key for yahtml-mode.  (@kbd{\C-c})
@end defvar

@defvar yahtml-image-viewer
Command to view image files refered by img. (xv)
@end defvar

@defvar yahtml-www-browser
Browser to view external pages with @kbd{[prefix]g}. (netscape)
@end defvar

@defvar yahtml-kanji-code
Default kanji code. 1=sjis, 2=jis, 3=euc, 4=utf-8 (2)
If
@quotation
 AddType "text/html; charset=xxx" .html
@end quotation
is written in .htaccess, this will override yahtml-kanji-code.
@end defvar

@defvar yahtml-fill-column
Columns to auto-fill (72)
@end defvar

@defvar yahtml-fill-prefix
fill-prefix specific to yahtml-mode. (@code{nil})
@end defvar

@defvar yahtml-path-url-alist
Matching list of URL and full path name on OS's file system.
@end defvar

@defvar yahtml-directory-index
Default index filed opened when accessing a server without a filename,
usually index.html. (@code{"index.html"})
@end defvar

@defvar yahtml-lint-program
HTML syntax check program. (@code{"jweblint"})
@end defvar

@defvar yahtml-hate-too-deep-indentation
setq to t when indentations for nested enumerate elements are too deep.
(@code{nil})
@end defvar

@defvar yahtml-always-/p
setq to t if you always want @code{
} after @code{
}. @code{nil}
@end defvar

@defvar yahtml-p-prefered-env-regexp
Elements that @code{
} will be automatically inserted.
(@code{"^\\(body\\|dl\\|blockquote\\)"})
@end defvar

@defvar yahtml-template-file
File to automatically insert when editing a new HTML file.
@file{"~/http/template.html"}
@end defvar

@defvar yahtml-prefer-upcases
Use uppercase for tags. @code{nil}
@end defvar

@defvar yahtml-prefer-upcase-attributes
Use uppercase for attributes. @code{nil}
@end defvar

@defvar yahtml-server-type
setq to 'apache if using a Apache server, and will refer ./.htaccess.
@code{'apache}
@end defvar

@defvar yahtml-apache-access-file
When @code{yahtml-server-type} is @code{'apache}, define name of access
restriction file. @file{".htaccess"}
@end defvar

@defvar yahtml-shell-command-option
Options needed to invoke shell commands.
@end defvar

@defvar yahtml-translate-hyphens-when-comment-region
Whether to change hyphens to @code{-} when commenting out region.
(@code{t})
@end defvar

@defvar yahtml-entity-reference-chars-alist
alist of characters that needs to be written by Entity Reference.  Enter
as @code{'(?char . "EntityReference")}.  By default, @code{<}, @code{>},
@code{&}, @code{'}, is set.  Add as needed.  Do not include @code{&} at
beginning and @code{;} at end of cdr portion of @code{"EntityReference"}.
@end defvar

@defvar yahtml-faithful-to-htmllint
When using htmllint to check syntax, it will complain about excess spaces.
setq to @code{t} to avoid this.
@end defvar

@defvar yahtml-use-css
Use style-sheet support or not (@code{t})
@end defvar

@defvar yahtml-image-inspection-bytes
Number of bytes to inspect the image for geometry information (@code{10000})
@end defvar

@defvar yahtml:img-default-alt-format
format of img entity's ALT attributes.
%x: width, %y: height, %s: size in bytes, %c: first comment string,
%f: filename (@code{"%xx%y(%sbytes)"})
@end defvar

@defvar yahtml-escape-chars
When, completing href-s, Escape reserved characters to URL-encoding or not.
Nil for never, t for everytime, and 'ask for inquiring
at each reserved chars. (@code{'ask})
@end defvar

@defvar yahtml-use-font-lock
Use font-lock to fontify buffer or not
(@code{(featurep 'font-lock)})
@end defvar

@defvar yahtml-use-hilit19
Use hilit19 to highlight buffer or not
(@code{(featurep 'hilit19)})
@end defvar

@defvar yahtml-indentation-boundary
Boundary regexp for indentation calculation.
(@code{"^\\s *<h[1-3]>"})
@end defvar

@node Hook variables,  , All customizable variables, Customizations
@comment  node-name,  next,  previous,  up
@section hook variables

@node Copying, Concept Index, Customizations, Top
@comment  node-name,  next,  previous,  up
@chapter Copying

This program is distributed as freesoftware.  The author will take no
responsibility to any damages due to the usage of this software
whatsoever.  There are no restrictions to its redistribution, just use
common sense.  Mail me your thoughts on this program and I will be more
than willing to help.

Complaints, requests, bug reports and comments are welcome.  Make contacts
to yuuji@@yatex.org$B!!(B(as of December 2000)

If you like this program and use it on a regular basis, please join the
mailing list "fj Wild Bird Society".  Procedures can be found in the "etc"
section of @file{docs/htmlqa.eng} in this package.

@flushright
HIROSE, Yuuji
@end flushright

@node    Concept Index,  , Copying, Top
@comment node-name, next, previous, up
@unnumbered Index
@printindex cp

@contents

@bye

@c Local Variables:
@c fill-column: 74
@c fill-prefix: nil
@c End:

Tag table:

End tag table


text:
package mof

import (
	"fmt"
	"strings"
	"unicode"
)

// item represents a token or text string returned from the scanner.
type item struct {
	typ itemType // The type of this item.
	pos pos      // The starting position, in bytes, of this item in the input string.
	val string   // The value of this item.
}

func (i item) String() string {
	switch {
	case i.typ == itemEOF:
		return "EOF"
	case i.typ == itemError:
		return i.val
	case len(i.val) > 10:
		return fmt.Sprintf("%.10q...", i.val)
	}
	return fmt.Sprintf("%q", i.val)
}

// itemType identifies the type of lex items.
type itemType int

const (
	itemError itemType = iota // error occurred; value is text of error
	itemEOF
	itemWord
	itemLeftBrace    // '{'
	itemRightBrace   // '}'
	itemLeftBracket  // '['
	itemRightBracket // ']'
	itemEq           // '='
	itemString
	itemNumber
	itemSemi // ';'
	itemComma
	itemChar
)

const eof = -1

// stateFn represents the state of the scanner as a function that returns the next state.
type stateFn func(*lexer) stateFn

// lexer holds the state of the scanner.
type lexer struct {
	input   []rune    // the string being scanned
	state   stateFn   // the next lexing function to enter
	pos     pos       // current position in the input
	start   pos       // start position of this item
	lastPos pos       // position of most recent item returned by nextItem
	items   chan item // channel of scanned items
}

// next returns the next rune in the input.
func (l *lexer) next() rune {
	if int(l.pos) >= len(l.input) {
		return eof
	}
	r := l.input[l.pos]
	l.pos++
	return r
}

// peek returns but does not consume the next rune in the input.
func (l *lexer) peek() rune {
	r := l.next()
	l.backup()
	return r
}

// backup steps back one rune. Can only be called once per call of next.
func (l *lexer) backup() {
	l.pos--
}

// emit passes an item back to the client.
func (l *lexer) emit(t itemType) {
	l.items <- item{t, l.start, string(l.input[l.start:l.pos])}
	l.start = l.pos
}

// accept consumes the next rune if it's from the valid set.
func (l *lexer) accept(valid string) bool {
	if strings.IndexRune(valid, l.next()) >= 0 {
		return true
	}
	l.backup()
	return false
}

// acceptRun consumes a run of runes from the valid set.
func (l *lexer) acceptRun(valid string) {
	for strings.IndexRune(valid, l.next()) >= 0 {
	}
	l.backup()
}

// ignore skips over the pending input before this point.
func (l *lexer) ignore() {
	l.start = l.pos
}

// lineNumber reports which line we're on, based on the position of
// the previous item returned by nextItem. Doing it this way
// means we don't have to worry about peek double counting.
func (l *lexer) lineNumber() int {
	return 1 + strings.Count(string(l.input[:l.lastPos]), "\n")
}

// errorf returns an error token and terminates the scan by passing
// back a nil pointer that will be the next state, terminating l.nextItem.
func (l *lexer) errorf(format string, args ...interface{}) stateFn {
	l.items <- item{itemError, l.start, fmt.Sprintf(format, args...)}
	return nil
}

// nextItem returns the next item from the input.
func (l *lexer) nextItem() item {
	item := <-l.items
	l.lastPos = item.pos
	return item
}

// lex creates a new scanner for the input string.
func lex(input []rune) *lexer {
	l := &lexer{
		input: input,
		items: make(chan item),
	}
	go l.run()
	return l
}

// run runs the state machine for the lexer.
func (l *lexer) run() {
	for l.state = lexItem; l.state != nil; {
		l.state = l.state(l)
	}
}

// state functions

func lexItem(l *lexer) stateFn {
Loop:
	for {
		switch r := l.next(); {
		case r == '{':
			l.emit(itemLeftBrace)
		case r == '}':
			l.emit(itemRightBrace)
		case r == '[':
			l.emit(itemLeftBracket)
		case r == ']':
			l.emit(itemRightBracket)
		case r == '=':
			l.emit(itemEq)
		case r == ';':
			l.emit(itemSemi)
		case r == ',':
			l.emit(itemComma)
		case isNumber(r):
			l.backup()
			return lexNumber
		case r == '"':
			return lexString
		case isSpace(r):
			l.ignore()
		case isWord(r):
			l.backup()
			return lexWord
		case r == eof:
			l.emit(itemEOF)
			break Loop
		default:
			l.emit(itemChar)
		}
	}
	return nil
}

// lexNumber scans a number: decimal, octal, hex, float, or imaginary. This
// isn't a perfect number scanner - for instance it accepts "." and "0x0.2"
// and "089" - but when it's wrong the input is invalid and the parser (via
// strconv) will notice.
func lexNumber(l *lexer) stateFn {
	if !l.scanNumber() {
		return l.errorf("bad number syntax: %q", l.input[l.start:l.pos])
	}
	l.emit(itemNumber)
	return lexItem
}

func (l *lexer) scanNumber() bool {
	// Is it hex?
	digits := "0123456789"
	if l.accept("0") && l.accept("xX") {
		digits = "0123456789abcdefABCDEF"
	}
	l.acceptRun(digits)
	if l.accept(".") {
		l.acceptRun(digits)
	}
	if l.accept("eE") {
		l.accept("+-")
		l.acceptRun("0123456789")
	}
	return true
}

func lexWord(l *lexer) stateFn {
	first := true
	for {
		r := l.next()
		switch {
		case isWord(r):
			// absorb
		case unicode.IsNumber(r) && !first:
			// absorb
		default:
			l.backup()
			l.emit(itemWord)
			return lexItem
		}
		first = false
	}
}

func lexString(l *lexer) stateFn {
	var prev rune
	for {
		c := l.next()
		switch {
		case c == '"' && prev != '\\':
			l.emit(itemString)
			return lexItem
		case c == eof:
			return l.errorf("unterminated string")
		case prev == '\\' && c == '\\':
			prev = 0
		default:
			prev = c
		}
	}
}

// isSpace reports whether r is a space character.
func isSpace(r rune) bool {
	return unicode.IsSpace(r)
}

func isNumber(r rune) bool {
	return unicode.IsDigit(r)
}

func isWord(r rune) bool {
	return unicode.IsLetter(r) || r == '_'
}


text:
package org.uberfire.client.views.pfly.notifications;

import java.util.ArrayList;
import java.util.List;
import javax.enterprise.context.Dependent;

import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import org.uberfire.client.workbench.widgets.animations.LinearFadeOutAnimation;
import org.uberfire.client.workbench.widgets.notifications.NotificationManager;
import org.uberfire.client.workbench.widgets.notifications.NotificationManager.NotificationPopupHandle;
import org.uberfire.commons.validation.PortablePreconditions;
import org.uberfire.workbench.events.NotificationEvent;

@Dependent
public class NotificationPopupsManagerView implements NotificationManager.View {

    private final int SPACING = 48;
    private final List<PopupHandle> activeNotifications = new ArrayList<PopupHandle>();
    private final List<PopupHandle> pendingRemovals = new ArrayList<PopupHandle>();
    //When true we are in the process of removing a notification message
    private boolean removing = false;
    private int initialSpacing = SPACING;
    private IsWidget container;

    @Override
    public void setContainer(final IsWidget container) {
        this.container = PortablePreconditions.checkNotNull("container",
                                                            container);
    }

    @Override
    public void setInitialSpacing(int spacing) {
        this.initialSpacing = spacing;
    }

    @Override
    public NotificationPopupHandle show(NotificationEvent event,
                                        Command hideCommand) {
        if (container == null) {
            throw new IllegalStateException("The setContainer() method hasn't been called!");
        }

        final NotificationPopupView view = new NotificationPopupView();
        final PopupHandle popupHandle = new PopupHandle(view,
                                                        event);
        activeNotifications.add(popupHandle);
        int size = activeNotifications.size();
        int topMargin = (size == 1) ? initialSpacing : (size * SPACING) - (SPACING - initialSpacing);
        view.setPopupPosition(getLeftPosition(container.asWidget()) + getMargin(),
                              getTopPosition(container.asWidget()) + topMargin);
        view.setNotification(event.getNotification());
        view.setType(event.getType());
        view.setNotificationWidth(getWidth() + "px");
        view.show(hideCommand);
        return popupHandle;
    }

    private int getTopPosition(final Widget widget) {
        int top = widget.getAbsoluteTop();
        // if top is negative (due to scrolling) we try to align with the parent
        // to make sure the notifications are always visible
        if (top < 0 && widget.getParent() != null) {
            top = getTopPosition(widget.getParent());
        }
        return Math.max(top,
                        0);
    }

    private int getLeftPosition(final Widget widget) {
        int left = widget.getAbsoluteLeft();
        // if left is negative (due to scrolling) we try to align with the parent
        // to make sure the notifications are always visible
        if (left < 0 && widget.getParent() != null) {
            left = getLeftPosition(widget.getParent());
        }
        return Math.max(left,
                        0);
    }

    @Override
    public void hide(final NotificationPopupHandle handle) {
        if (container == null) {
            throw new IllegalStateException("The setContainer() method hasn't been called!");
        }

        final int removingIndex = activeNotifications.indexOf(handle);
        if (removingIndex == -1) {
            return;
        }
        if (removing) {
            pendingRemovals.add((PopupHandle) handle);
            return;
        }
        removing = true;
        final NotificationPopupView view = ((PopupHandle) handle).view;
        final LinearFadeOutAnimation fadeOutAnimation = new LinearFadeOutAnimation(view) {
            @Override
            public void onUpdate(double progress) {
                super.onUpdate(progress);
                for (int i = removingIndex; i < activeNotifications.size(); i++) {
                    NotificationPopupView v = activeNotifications.get(i).view;
                    final int left = v.getPopupLeft();
                    final int top = (int) (((i + 1) * SPACING) - (progress * SPACING))
                            - (SPACING - initialSpacing) + getTopPosition(container.asWidget());
                    v.setPopupPosition(left,
                                       top);
                }
            }

            @Override
            public void onComplete() {
                super.onComplete();
                view.hide();
                activeNotifications.remove(handle);
                removing = false;
                if (pendingRemovals.size() > 0) {
                    PopupHandle popupHandle = pendingRemovals.remove(0);
                    hide(popupHandle);
                }
            }
        };
        fadeOutAnimation.run(500);
    }

    @Override
    public void hideAll() {
        for (NotificationPopupHandle handle : activeNotifications) {
            hide(handle);
        }
    }

    @Override
    public boolean isShowing(NotificationEvent event) {
        for (PopupHandle handle : activeNotifications) {
            if (handle.event.equals(event)) {
                return true;
            }
        }
        return false;
    }

    //80% of container width
    private int getWidth() {
        return (int) (container.asWidget().getElement().getClientWidth() * 0.8);
    }

    //10% of container width
    private int getMargin() {
        return (container.asWidget().getElement().getClientWidth() - getWidth()) / 2;
    }

    private static class PopupHandle implements NotificationPopupHandle {

        final NotificationPopupView view;
        final NotificationEvent event;

        PopupHandle(NotificationPopupView view,
                    NotificationEvent event) {
            this.view = PortablePreconditions.checkNotNull("view",
                                                           view);
            this.event = PortablePreconditions.checkNotNull("event",
                                                            event);
        }
    }
}


text:
package net.scalytica.symbiotic.api.types

import java.util.UUID

trait IdOps[A <: Id] {

  implicit def asId(s: String): A

  implicit def asOptId(maybeId: Option[String]): Option[A] =
    maybeId.map(s => asId(s))

  implicit def asOptId(s: String): Option[A] = asOptId(Option(s))

  def fromUuid(uuid: java.util.UUID): A = asId(uuid.toString)

  @throws(classOf[IllegalArgumentException])
  def unsafeAsUuid(id: A): UUID = java.util.UUID.fromString(id.value)

  def create(): A = asId(java.util.UUID.randomUUID.toString)

  def createOpt(): Option[A] = asOptId(java.util.UUID.randomUUID.toString)

}


text:
using System.Collections.Generic;
using Avalonia.Controls;
using Xunit;

namespace Avalonia.Input.UnitTests
{
    public class KeyboardNavigationTests_Tab
    {
        [Fact]
        public void Next_Continue_Returns_Next_Control_In_Container()
        {
            Button current;
            Button next;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    new StackPanel
                    {
                        Children =
                        {
                            new Button { Name = "Button1" },
                            (current = new Button { Name = "Button2" }),
                            (next = new Button { Name = "Button3" }),
                        }
                    },
                    new StackPanel
                    {
                        Children =
                        {
                            new Button { Name = "Button4" },
                            new Button { Name = "Button5" },
                            new Button { Name = "Button6" },
                        }
                    },
                }
            };

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);

            Assert.Equal(next, result);
        }

        [Fact]
        public void Next_Continue_Returns_First_Control_In_Next_Sibling_Container()
        {
            Button current;
            Button next;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    new StackPanel
                    {
                        Children =
                        {
                            new Button { Name = "Button1" },
                            new Button { Name = "Button2" },
                            (current = new Button { Name = "Button3" }),
                        }
                    },
                    new StackPanel
                    {
                        Children =
                        {
                            (next = new Button { Name = "Button4" }),
                            new Button { Name = "Button5" },
                            new Button { Name = "Button6" },
                        }
                    },
                }
            };

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);

            Assert.Equal(next, result);
        }

        [Fact]
        public void Next_Skips_Unfocusable_Siblings()
        {
            Button current;
            Button next;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    new StackPanel
                    {
                        Children =
                        {
                            new Button { Name = "Button1" },
                            new Button { Name = "Button2" },
                            new StackPanel
                            {
                                Children =
                                {
                                    (current = new Button { Name = "Button3" }),
                                }
                            },
                            new TextBlock { Name = "TextBlock" },
                            (next = new Button { Name = "Button4" }),
                        }
                    },
                    new Button { Name = "Button5" },
                    new Button { Name = "Button6" },
                }
            };

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);

            Assert.Equal(next, result);
        }

        [Fact]
        public void Next_Continue_Doesnt_Enter_Panel_With_TabNavigation_None()
        {
            Button current;
            Button next;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    new StackPanel
                    {
                        Children =
                        {
                            (next = new Button { Name = "Button1" }),
                            new Button { Name = "Button2" },
                            (current = new Button { Name = "Button3" }),
                        }
                    },
                    new StackPanel
                    {
                        [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.None,
                        Children =
                        {
                            new StackPanel
                            {
                                Children =
                                {
                                    new Button { Name = "Button4" },
                                    new Button { Name = "Button5" },
                                    new Button { Name = "Button6" },
                                }
                            },
                        }
                    }
                }
            };

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);

            Assert.Equal(next, result);
        }

        [Fact]
        public void Next_Continue_Returns_Next_Sibling()
        {
            Button current;
            Button next;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    new StackPanel
                    {
                        Children =
                        {
                            new Button { Name = "Button1" },
                            new Button { Name = "Button2" },
                            (current = new Button { Name = "Button3" }),
                        }
                    },
                    (next = new Button { Name = "Button4" }),
                }
            };

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);

            Assert.Equal(next, result);
        }

        [Fact]
        public void Next_Skips_Non_TabStop_Siblings()
        {
            Button current;
            Button next;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    new StackPanel
                    {
                        Children =
                        {
                            new Button { Name = "Button1" },
                            new Button { Name = "Button2" },
                            (current = new Button { Name = "Button3" }),
                            new Button { Name="Button4", [KeyboardNavigation.IsTabStopProperty] = false }
                        }
                    },
                    (next = new Button { Name = "Button5" }),
                }
            };

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);

            Assert.Equal(next, result);
        }

        [Fact]
        public void Next_Continue_Returns_First_Control_In_Next_Uncle_Container()
        {
            Button current;
            Button next;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    new StackPanel
                    {
                        Children =
                        {
                            new StackPanel
                            {
                                Children =
                                {
                                    new Button { Name = "Button1" },
                                    new Button { Name = "Button2" },
                                    (current = new Button { Name = "Button3" }),
                                }
                            },
                        },
                    },
                    new StackPanel
                    {
                        Children =
                        {
                            (next = new Button { Name = "Button4" }),
                            new Button { Name = "Button5" },
                            new Button { Name = "Button6" },
                        }
                    },
                }
            };

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);

            Assert.Equal(next, result);
        }

        [Fact]
        public void Next_Continue_Returns_Child_Of_Top_Level()
        {
            Button next;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    (next = new Button { Name = "Button1" }),
                }
            };

            var result = KeyboardNavigationHandler.GetNext(top, NavigationDirection.Next);

            Assert.Equal(next, result);
        }

        [Fact]
        public void Next_Continue_Wraps()
        {
            Button current;
            Button next;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    new StackPanel
                    {
                        Children =
                        {
                            new StackPanel
                            {
                                Children =
                                {
                                    (next = new Button { Name = "Button1" }),
                                    new Button { Name = "Button2" },
                                    new Button { Name = "Button3" },
                                }
                            },
                        },
                    },
                    new StackPanel
                    {
                        Children =
                        {
                            new Button { Name = "Button4" },
                            new Button { Name = "Button5" },
                            (current = new Button { Name = "Button6" }),
                        }
                    },
                }
            };

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);

            Assert.Equal(next, result);
        }

        [Fact]
        public void Next_Cycle_Returns_Next_Control_In_Container()
        {
            Button current;
            Button next;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    new StackPanel
                    {
                        [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                        Children =
                        {
                            new Button { Name = "Button1" },
                            (current = new Button { Name = "Button2" }),
                            (next = new Button { Name = "Button3" }),
                        }
                    },
                    new StackPanel
                    {
                        Children =
                        {
                            new Button { Name = "Button4" },
                            new Button { Name = "Button5" },
                            new Button { Name = "Button6" },
                        }
                    },
                }
            };

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);

            Assert.Equal(next, result);
        }

        [Fact]
        public void Next_Cycle_Wraps_To_First()
        {
            Button current;
            Button next;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    new StackPanel
                    {
                        [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                        Children =
                        {
                            (next = new Button { Name = "Button1" }),
                            new Button { Name = "Button2" },
                            (current = new Button { Name = "Button3" }),
                        }
                    },
                    new StackPanel
                    {
                        Children =
                        {
                            new Button { Name = "Button4" },
                            new Button { Name = "Button5" },
                            new Button { Name = "Button6" },
                        }
                    },
                }
            };

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);

            Assert.Equal(next, result);
        }

        [Fact]
        public void Next_Contained_Returns_Next_Control_In_Container()
        {
            Button current;
            Button next;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    new StackPanel
                    {
                        [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Contained,
                        Children =
                        {
                            new Button { Name = "Button1" },
                            (current = new Button { Name = "Button2" }),
                            (next = new Button { Name = "Button3" }),
                        }
                    },
                    new StackPanel
                    {
                        Children =
                        {
                            new Button { Name = "Button4" },
                            new Button { Name = "Button5" },
                            new Button { Name = "Button6" },
                        }
                    },
                }
            };

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);

            Assert.Equal(next, result);
        }

        [Fact]
        public void Next_Contained_Stops_At_End()
        {
            Button current;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    new StackPanel
                    {
                        [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Contained,
                        Children =
                        {
                            new Button { Name = "Button1" },
                            new Button { Name = "Button2" },
                            (current = new Button { Name = "Button3" }),
                        }
                    },
                    new StackPanel
                    {
                        Children =
                        {
                            new Button { Name = "Button4" },
                            new Button { Name = "Button5" },
                            new Button { Name = "Button6" },
                        }
                    },
                }
            };

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);

            Assert.Null(result);
        }

        [Fact]
        public void Next_Once_Moves_To_Next_Container()
        {
            Button current;
            Button next;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    new StackPanel
                    {
                        [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Once,
                        Children =
                        {
                            new Button { Name = "Button1" },
                            (current = new Button { Name = "Button2" }),
                            new Button { Name = "Button3" },
                        }
                    },
                    new StackPanel
                    {
                        Children =
                        {
                            (next = new Button { Name = "Button4" }),
                            new Button { Name = "Button5" },
                            new Button { Name = "Button6" },
                        }
                    },
                }
            };

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);

            Assert.Equal(next, result);
        }

        [Fact]
        public void Next_Once_Moves_To_Active_Element()
        {
            StackPanel container;
            Button current;
            Button next;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    (container = new StackPanel
                    {
                        [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Once,
                        Children =
                        {
                            new Button { Name = "Button1" },
                            (next = new Button { Name = "Button2" }),
                            new Button { Name = "Button3" },
                        }
                    }),
                    new StackPanel
                    {
                        Children =
                        {
                            new Button { Name = "Button4" },
                            new Button { Name = "Button5" },
                            (current = new Button { Name = "Button6" }),
                        }
                    },
                }
            };

            KeyboardNavigation.SetTabOnceActiveElement(container, next);

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);

            Assert.Equal(next, result);
        }

        [Fact]
        public void Next_None_Moves_To_Next_Container()
        {
            Button current;
            Button next;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    new StackPanel
                    {
                        [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.None,
                        Children =
                        {
                            new Button { Name = "Button1" },
                            (current = new Button { Name = "Button2" }),
                            new Button { Name = "Button3" },
                        }
                    },
                    new StackPanel
                    {
                        Children =
                        {
                            (next = new Button { Name = "Button4" }),
                            new Button { Name = "Button5" },
                            new Button { Name = "Button6" },
                        }
                    },
                }
            };

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);

            Assert.Equal(next, result);
        }

        [Fact]
        public void Next_None_Skips_Container()
        {
            StackPanel container;
            Button current;
            Button next;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    (container = new StackPanel
                    {
                        [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.None,
                        Children =
                        {
                            new Button { Name = "Button1" },
                            new Button { Name = "Button2" },
                            new Button { Name = "Button3" },
                        }
                    }),
                    new StackPanel
                    {
                        Children =
                        {
                            (next = new Button { Name = "Button4" }),
                            new Button { Name = "Button5" },
                            (current = new Button { Name = "Button6" }),
                        }
                    },
                }
            };

            KeyboardNavigation.SetTabOnceActiveElement(container, next);

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);

            Assert.Equal(next, result);
        }

        [Fact]
        public void Previous_Continue_Returns_Previous_Control_In_Container()
        {
            Button current;
            Button next;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    new StackPanel
                    {
                        Children =
                        {
                            new Button { Name = "Button1" },
                            (next = new Button { Name = "Button2" }),
                            (current = new Button { Name = "Button3" }),
                        }
                    },
                    new StackPanel
                    {
                        Children =
                        {
                            new Button { Name = "Button4" },
                            new Button { Name = "Button5" },
                            new Button { Name = "Button6" },
                        }
                    },
                }
            };

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);

            Assert.Equal(next, result);
        }

        [Fact]
        public void Previous_Continue_Returns_Last_Control_In_Previous_Sibling_Container()
        {
            Button current;
            Button next;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    new StackPanel
                    {
                        Children =
                        {
                            new Button { Name = "Button1" },
                            new Button { Name = "Button2" },
                            (next = new Button { Name = "Button3" }),
                        }
                    },
                    new StackPanel
                    {
                        Children =
                        {
                            (current = new Button { Name = "Button4" }),
                            new Button { Name = "Button5" },
                            new Button { Name = "Button6" },
                        }
                    },
                }
            };

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);

            Assert.Equal(next, result);
        }

        [Fact]
        public void Previous_Continue_Returns_Last_Child_Of_Sibling()
        {
            Button current;
            Button next;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    new StackPanel
                    {
                        Children =
                        {
                            new Button { Name = "Button1" },
                            new Button { Name = "Button2" },
                            (next = new Button { Name = "Button3" }),
                        }
                    },
                    (current = new Button { Name = "Button4" }),
                }
            };

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);

            Assert.Equal(next, result);
        }

        [Fact]
        public void Previous_Continue_Returns_Last_Control_In_Previous_Nephew_Container()
        {
            Button current;
            Button next;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    new StackPanel
                    {
                        Children =
                        {
                            new StackPanel
                            {
                                Children =
                                {
                                    new Button { Name = "Button1" },
                                    new Button { Name = "Button2" },
                                    (next = new Button { Name = "Button3" }),
                                }
                            },
                        },
                    },
                    new StackPanel
                    {
                        Children =
                        {
                            (current = new Button { Name = "Button4" }),
                            new Button { Name = "Button5" },
                            new Button { Name = "Button6" },
                        }
                    },
                }
            };

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);

            Assert.Equal(next, result);
        }

        [Fact]
        public void Previous_Continue_Wraps()
        {
            Button current;
            Button next;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    new StackPanel
                    {
                        Children =
                        {
                            new StackPanel
                            {
                                Children =
                                {
                                    (current = new Button { Name = "Button1" }),
                                    new Button { Name = "Button2" },
                                    new Button { Name = "Button3" },
                                }
                            },
                        },
                    },
                    new StackPanel
                    {
                        Children =
                        {
                            new Button { Name = "Button4" },
                            new Button { Name = "Button5" },
                            (next = new Button { Name = "Button6" }),
                        }
                    },
                }
            };

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);

            Assert.Equal(next, result);
        }

        [Fact]
        public void Previous_Continue_Returns_Parent()
        {
            Button current;

            var top = new Decorator
            {
                Focusable = true,
                Child = current = new Button
                {
                    Name = "Button",
                }
            };

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);

            Assert.Equal(top, result);
        }

        [Fact]
        public void Previous_Cycle_Returns_Previous_Control_In_Container()
        {
            Button current;
            Button next;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    new StackPanel
                    {
                        [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                        Children =
                        {
                            (next = new Button { Name = "Button1" }),
                            (current = new Button { Name = "Button2" }),
                            new Button { Name = "Button3" },
                        }
                    },
                    new StackPanel
                    {
                        Children =
                        {
                            new Button { Name = "Button4" },
                            new Button { Name = "Button5" },
                            new Button { Name = "Button6" },
                        }
                    },
                }
            };

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);

            Assert.Equal(next, result);
        }

        [Fact]
        public void Previous_Cycle_Wraps_To_Last()
        {
            Button current;
            Button next;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    new StackPanel
                    {
                        [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                        Children =
                        {
                            (current = new Button { Name = "Button1" }),
                            new Button { Name = "Button2" },
                            (next = new Button { Name = "Button3" }),
                        }
                    },
                    new StackPanel
                    {
                        Children =
                        {
                            new Button { Name = "Button4" },
                            new Button { Name = "Button5" },
                            new Button { Name = "Button6" },
                        }
                    },
                }
            };

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);

            Assert.Equal(next, result);
        }

        [Fact]
        public void Previous_Contained_Returns_Previous_Control_In_Container()
        {
            Button current;
            Button next;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    new StackPanel
                    {
                        [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Contained,
                        Children =
                        {
                            (next = new Button { Name = "Button1" }),
                            (current = new Button { Name = "Button2" }),
                            new Button { Name = "Button3" },
                        }
                    },
                    new StackPanel
                    {
                        Children =
                        {
                            new Button { Name = "Button4" },
                            new Button { Name = "Button5" },
                            new Button { Name = "Button6" },
                        }
                    },
                }
            };

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);

            Assert.Equal(next, result);
        }

        [Fact]
        public void Previous_Contained_Stops_At_Beginning()
        {
            Button current;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    new StackPanel
                    {
                        [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Contained,
                        Children =
                        {
                            (current = new Button { Name = "Button1" }),
                            new Button { Name = "Button2" },
                            new Button { Name = "Button3" },
                        }
                    },
                    new StackPanel
                    {
                        Children =
                        {
                            new Button { Name = "Button4" },
                            new Button { Name = "Button5" },
                            new Button { Name = "Button6" },
                        }
                    },
                }
            };

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);

            Assert.Null(result);
        }

        [Fact]
        public void Previous_Once_Moves_To_Previous_Container()
        {
            Button current;
            Button next;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    new StackPanel
                    {
                        Children =
                        {
                            new Button { Name = "Button1" },
                            new Button { Name = "Button2" },
                            (next = new Button { Name = "Button3" }),
                        }
                    },
                    new StackPanel
                    {
                        [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Once,
                        Children =
                        {
                            new Button { Name = "Button4" },
                            (current = new Button { Name = "Button5" }),
                            new Button { Name = "Button6" },
                        }
                    },
                }
            };

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);

            Assert.Equal(next, result);
        }

        [Fact]
        public void Previous_Once_Moves_To_Active_Element()
        {
            StackPanel container;
            Button current;
            Button next;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    (container = new StackPanel
                    {
                        [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Once,
                        Children =
                        {
                            new Button { Name = "Button1" },
                            (next = new Button { Name = "Button2" }),
                            new Button { Name = "Button3" },
                        }
                    }),
                    new StackPanel
                    {
                        Children =
                        {
                            (current = new Button { Name = "Button4" }),
                            new Button { Name = "Button5" },
                            new Button { Name = "Button6" },
                        }
                    },
                }
            };

            KeyboardNavigation.SetTabOnceActiveElement(container, next);

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);

            Assert.Equal(next, result);
        }

        [Fact]
        public void Previous_Once_Moves_To_First_Element()
        {
            Button current;
            Button next;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    new StackPanel
                    {
                        [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Once,
                        Children =
                        {
                            (next = new Button { Name = "Button1" }),
                            new Button { Name = "Button2" },
                            new Button { Name = "Button3" },
                        }
                    },
                    new StackPanel
                    {
                        Children =
                        {
                            (current = new Button { Name = "Button4" }),
                            new Button { Name = "Button5" },
                            new Button { Name = "Button6" },
                        }
                    },
                }
            };

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);

            Assert.Equal(next, result);
        }

        [Fact]
        public void Previous_Contained_Doesnt_Select_Child_Control()
        {
            Decorator current;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Contained,
                Children =
                {
                    (current = new Decorator
                    {
                        Focusable = true,
                        Child = new Button(),
                    })
                }
            };

            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);

            Assert.Null(result);
        }

        [Fact]
        public void Respects_TabIndex_Moving_Forwards()
        {
            Button start;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    new StackPanel
                    {
                        Children =
                        {
                            new Button { Name = "Button1", TabIndex = 5 },
                            (start = new Button { Name = "Button2", TabIndex = 2 }),
                            new Button { Name = "Button3", TabIndex = 1 },
                        }
                    },
                    new StackPanel
                    {
                        Children =
                        {
                            new Button { Name = "Button4", TabIndex = 3  },
                            new Button { Name = "Button5", TabIndex = 6  },
                            new Button { Name = "Button6", TabIndex = 4  },
                        }
                    },
                }
            };

            var result = new List<string>();
            var current = (IInputElement)start;

            do
            {
                result.Add(((IControl)current).Name);
                current = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);
            } while (current is object && current != start);

            Assert.Equal(new[]
            {
                "Button2", "Button4", "Button6", "Button1", "Button5", "Button3"
            }, result);
        }

        [Fact]
        public void Respects_TabIndex_Moving_Backwards()
        {
            Button start;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    new StackPanel
                    {
                        Children =
                        {
                            new Button { Name = "Button1", TabIndex = 5 },
                            (start = new Button { Name = "Button2", TabIndex = 2 }),
                            new Button { Name = "Button3", TabIndex = 1 },
                        }
                    },
                    new StackPanel
                    {
                        Children =
                        {
                            new Button { Name = "Button4", TabIndex = 3  },
                            new Button { Name = "Button5", TabIndex = 6  },
                            new Button { Name = "Button6", TabIndex = 4  },
                        }
                    },
                }
            };

            var result = new List<string>();
            var current = (IInputElement)start;

            do
            {
                result.Add(((IControl)current).Name);
                current = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Previous);
            } while (current is object && current != start);

            Assert.Equal(new[]
            {
                "Button2", "Button3", "Button5", "Button1", "Button6", "Button4"
            }, result);
        }

        [Fact]
        public void Cannot_Focus_Child_Of_Disabled_Control()
        {
            Button start;
            Button expected;

            var top = new StackPanel
            {
                [KeyboardNavigation.TabNavigationProperty] = KeyboardNavigationMode.Cycle,
                Children =
                {
                    (start = new Button { Name = "Button1" }),
                    new Border
                    {
                        IsEnabled = false,
                        Child = new Button { Name = "Button2" },
                    },
                    (expected = new Button { Name = "Button3" }),
                }
            };

            var current = (IInputElement)start;
            var result = KeyboardNavigationHandler.GetNext(current, NavigationDirection.Next);

            Assert.Same(expected, result);
        }
    }
}


text:
import datomisca._

import scala.concurrent._
import scala.concurrent.duration.Duration

/*
 * Adapted from https://gist.github.com/pelle/2635666
 */

object AccountsSchema {
  // Namespaces
  val account = new Namespace("account")
  val trans   = new Namespace("trans")
  val fn      = new Namespace("fn")

  // Attributes
  val name       = Attribute(account / "name",        SchemaType.string, Cardinality.one)
                     .withDoc("The name of the account")
                     .withUnique(Unique.value)
                     .withFullText(true)
  val balance    = Attribute(account / "balance",     SchemaType.bigdec, Cardinality.one)
                     .withDoc("The account balance")
  val minBalance = Attribute(account / "min-balance", SchemaType.bigdec, Cardinality.one)
                  .withDoc("The minimum permitted balance for the account")

  val amount = Attribute(trans / "amount", SchemaType.bigdec, Cardinality.one)
                 .withDoc("The transaction amount")
  val from   = Attribute(trans / "from", SchemaType.ref, Cardinality.one)
                 .withDoc("The sending account")
  val to     = Attribute(trans / "to",   SchemaType.ref, Cardinality.one)
                 .withDoc("The receiving account")

  val creditFn = AddTxFunction(fn / "credit") ("db", "id", "amount") ("clojure") {
    """
    (let [ e           (datomic.api/entity db id)
           min-balance (:account/min-balance e 0)
           balance     (+ (:account/balance e 0) amount) ]
           (if (>= balance min-balance)
             [[:db/add id :account/balance balance]]
             (throw (java.lang.IllegalStateException. "Insufficient funds"))))
    """
  }
  val transferFn = AddTxFunction(fn / "transfer") ("db", "from", "to", "amount") ("clojure") {
    """
    [
      [:fn/credit from (- amount)]
      [:fn/credit to   amount]
    ]
    """
  }

  // Schema
  val schema = Seq(
    // account, trans, fn,
    name, balance, minBalance,
    amount, from, to,
    creditFn, transferFn
  )

}

object AccountsTxData {
  import AccountsSchema._

  val issuer = (
    SchemaEntity.newBuilder
      += (name       -> "Issuer")
      += (balance    -> BigDecimal(0))
      += (minBalance -> BigDecimal(-1000))
  ) withId DId(Partition.USER)

  val bob = (
    SchemaEntity.newBuilder
      += (AccountsSchema.name -> "Bob")
      += (balance             -> BigDecimal(0))
      += (minBalance          -> BigDecimal(0))
  ) withId DId(Partition.USER)

  val alice = (
    SchemaEntity.newBuilder
      += (AccountsSchema.name -> "Alice")
      += (balance             -> BigDecimal(0))
      += (minBalance          -> BigDecimal(0))
  ) withId DId(Partition.USER)

  val sampleTxData = Seq(issuer, bob, alice)

  def transfer(fromAcc: Long, toAcc: Long, transAmount: BigDecimal, note: String): Seq[TxData] = {
    val txId = DId(Partition.TX)
    Seq(
      InvokeTxFunction(transferFn.ident)(fromAcc: java.lang.Long, toAcc: java.lang.Long, transAmount.bigDecimal),
      Entity.add(txId)(
        Datomic.KW(":db/doc") -> note,
        from.ident    -> fromAcc,
        to.ident      -> toAcc,
        amount.ident  -> transAmount
      )
    )
  }

  def credit(toAcc: Long, amount: BigDecimal): TxData =
    InvokeTxFunction(creditFn.ident)(toAcc: java.lang.Long, amount.bigDecimal)
}

object AccountsQueries {
  val queryAccounts = Query("""
    [
      :find ?a
      :in $
      :where
        [?a :account/name]
    ]
  """)

  val findAccountByName = Query("""
    [
      :find ?a
      :in $ ?name
      :where
        [?a :account/name ?name]
    ]
  """)

  val queryAllTransactions = Query("""
    [
      :find ?tx
      :in $
      :where
        [?tx :trans/amount]
    ]
  """)

  val rulesParty = Query.rules("""
    [
      [[party ?t ?a]
         [?t :trans/from ?a]]
      [[party ?t ?a]
         [?t :trans/to ?a]]
    ]
  """)

  val queryAccountTransactions = Query("""
    [
      :find ?t
      :in $ % ?a
      :where
        (party ?t ?a)
    ]
  """)
}

object Accounts {
  // IF RUNNING FROM SBT RUNTIME :
  // This imports a helper Execution Context provided by Datomisca
  // to enhance default Scala one with access to ExecutorService
  // to be able to shut the service down after program execution.
  // Without this shutdown, when running in SBT, at second execution,
  // you get weird Clojure cache execution linked to classloaders issues...
  //
  // IF NOT IN SBT RUNTIME :
  // You can use classic Scala global execution context
  import datomisca.executioncontext.ExecutionContextHelper._

  // Datomic URI definition
  val uri = "datomic:mem://datomisca-accounts-sample"

  // Datomic Connection as an implicit in scope
  implicit lazy val conn = Datomic.connect(uri)

  def main(args: Array[String]) {
    import AccountsSchema.{name, from, to}
    import AccountsQueries._
    import AccountsTxData.{transfer, credit}
    Datomic.createDatabase(uri)

    Await.result(
      for {
        _ <- Datomic.transact(AccountsSchema.schema)
        _ <- Datomic.transact(AccountsTxData.sampleTxData)
      } yield (),
      Duration("3 seconds")
    )

    val issuerId =
      Datomic.q(findAccountByName, Datomic.database, "Issuer").head.asInstanceOf[Long]
    val bobId =
      Datomic.q(findAccountByName, Datomic.database, "Bob").head.asInstanceOf[Long]
    val aliceId =
      Datomic.q(findAccountByName, Datomic.database, "Alice").head.asInstanceOf[Long]

    Await.result(
      for {
        _ <- Datomic.transact(transfer(issuerId, aliceId, BigDecimal(77), "Issuance to Alice"))
        _ =  Thread.sleep(2000)
        _ <- Datomic.transact(transfer(issuerId, bobId,   BigDecimal(23), "Issuance to Bob"))
        _ =  Thread.sleep(2000)
        _ <- Datomic.transact(transfer(aliceId, bobId,    BigDecimal(7),  "Dinner"))
      } yield (),
      Duration("10 seconds")
    )

    val dumpAcc: (Any => Unit) = {
      case eid: Long =>
        val entity = Datomic.database.entity(eid)
        println(entity.toMap)
    }

    val dumpTx: (Any => Unit) = {
      case eid: Long =>
        val entity = Datomic.database.entity(eid)
        def getName(entity: Entity, kw: Keyword) =
          entity.as[Entity](kw).as[String](name.ident)
        println(
          entity.toMap +
          (from.ident.toString -> getName(entity, from.ident)) +
          (to.ident.toString   -> getName(entity, to.ident))
        )
    }

    println("All accounts")
    Datomic.q(queryAccounts, Datomic.database) foreach dumpAcc
    println()

    println("All transactions")
    Datomic.q(queryAllTransactions, Datomic.database) foreach dumpTx
    println()

    println("Issuers's account")
    dumpAcc(issuerId)
    println("Issuers's transactions")
    Datomic.q(queryAccountTransactions, Datomic.database, rulesParty, issuerId) foreach dumpTx
    println()

    println("Bob's account")
    dumpAcc(bobId)
    println("Bob's transactions")
    Datomic.q(queryAccountTransactions, Datomic.database, rulesParty, bobId) foreach dumpTx
    println()

    println("Alice's account")
    dumpAcc(aliceId)
    println("Alice's transactions")
    Datomic.q(queryAccountTransactions, Datomic.database, rulesParty, aliceId) foreach dumpTx
    println()

    try {
      Await.result(
        Datomic.transact(transfer(aliceId, bobId, BigDecimal(71),  "Car")),
        Duration("3 seconds")
      )
    } catch {
      case ex: java.lang.IllegalStateException =>
        println("A transaction to transfer 71 from Alice to Bob should fail.")
        println(s"It failed with the message ${ex.getMessage}")
      case ex: Throwable =>
        println(s"Unexpected exception $ex")
    }

    Datomic.shutdown(true)

    // IF RUNNING FROM SBT RUNTIME :
    // without this, in SBT, if you run the program 2x, it fails
    // with weird cache exception linked to the way SBT manages
    // execution context and classloaders...
    defaultExecutorService.shutdownNow()
  }
}


text:
This directory contains a standardized TCP benchmark. This helps to evaluate the
performance of netstack and native networking stacks under various conditions.

## `tcp_benchmark`

This benchmark allows TCP throughput testing under various conditions. The setup
consists of an iperf client, a client proxy, a server proxy and an iperf server.
The client proxy and server proxy abstract the network mechanism used to
communicate between the iperf client and server.

The setup looks like the following:

```
 +--------------+  (native)            +--------------+
 | iperf client |[lo @ 10.0.0.1]------>| client proxy |
 +--------------+                      +--------------+
                                    [client.0 @ 10.0.0.2]
                            (netstack)  |            |  (native)
                                        +------+-----+
                                               |
                                             [br0]
                                               |
          Network emulation applied ---> [wan.0:wan.1]
                                               |
                                             [br1]
                                               |
                                        +------+-----+
                            (netstack)  |            |  (native)
                                     [server.0 @ 10.0.0.3]
 +--------------+                      +--------------+
 | iperf server |<------[lo @ 10.0.0.4]| server proxy |
 +--------------+            (native)  +--------------+
```

Different configurations can be run using different arguments. For example:

*   Native test under normal internet conditions: `tcp_benchmark`
*   Native test under ideal conditions: `tcp_benchmark --ideal`
*   Netstack client under ideal conditions: `tcp_benchmark --client --ideal`
*   Netstack client with 5% packet loss: `tcp_benchmark --client --ideal --loss
    5`

Use `tcp_benchmark --help` for full arguments.

This tool may be used to easily generate data for graphing. For example, to
generate a CSV for various latencies, you might do:

```
rm -f /tmp/netstack_latency.csv /tmp/native_latency.csv
latencies=$(seq 0 5 50;
            seq 60 10 100;
            seq 125 25 250;
            seq 300 50 500)
for latency in $latencies; do
  read throughput client_cpu server_cpu <<< \
    $(./tcp_benchmark --duration 30 --client --ideal --latency $latency)
  echo $latency,$throughput,$client_cpu >> /tmp/netstack_latency.csv
done
for latency in $latencies; do
  read throughput client_cpu server_cpu <<< \
    $(./tcp_benchmark --duration 30 --ideal --latency $latency)
  echo $latency,$throughput,$client_cpu >> /tmp/native_latency.csv
done
```

Similarly, to generate a CSV for various levels of packet loss, the following
would be appropriate:

```
rm -f /tmp/netstack_loss.csv /tmp/native_loss.csv
losses=$(seq 0 0.1 1.0;
         seq 1.2 0.2 2.0;
         seq 2.5 0.5 5.0;
         seq 6.0 1.0 10.0)
for loss in $losses; do
  read throughput client_cpu server_cpu <<< \
    $(./tcp_benchmark --duration 30 --client --ideal --latency 10 --loss $loss)
  echo $loss,$throughput,$client_cpu >> /tmp/netstack_loss.csv
done
for loss in $losses; do
  read throughput client_cpu server_cpu <<< \
    $(./tcp_benchmark --duration 30 --ideal --latency 10 --loss $loss)
  echo $loss,$throughput,$client_cpu >> /tmp/native_loss.csv
done
```