text:
package graph

import (
	"fmt"

	"github.com/google/badwolf/triple"
	"github.com/google/badwolf/triple/node"
	"github.com/google/badwolf/triple/predicate"
	"github.com/wallix/awless/graph/internal/rdf"
)

type Graph struct {
	rdfG *rdf.Graph
}

func NewGraph() *Graph {
	return &Graph{rdf.NewGraph()}
}

func NewGraphFromFile(filepath string) (*Graph, error) {
	g, err := rdf.NewGraphFromFile(filepath)
	return &Graph{g}, err
}

func (g *Graph) AddResource(resources ...*Resource) error {
	for _, res := range resources {
		triples, err := res.marshalRDF()
		if err != nil {
			return err
		}

		g.rdfG.Add(triples...)
	}
	return nil
}

func (g *Graph) AddGraph(gph *Graph) {
	g.rdfG.AddGraph(gph.rdfG)
}

func (g *Graph) AddParentRelation(parent, child *Resource) error {
	return g.addRelation(parent, child, rdf.ParentOfPredicate)
}

func (g *Graph) AddAppliesOnRelation(parent, child *Resource) error {
	return g.addRelation(parent, child, rdf.AppliesOnPredicate)
}

func (g *Graph) GetResource(t string, id string) (*Resource, error) {
	resource := InitResource(id, t)

	node, err := resource.toRDFNode()
	if err != nil {
		return resource, err
	}

	propsTriples, err := g.rdfG.TriplesForSubjectPredicate(node, rdf.PropertyPredicate)
	if err != nil {
		return resource, err
	}
	if er := resource.Properties.unmarshalRDF(propsTriples); er != nil {
		return resource, er
	}

	metaTriples, err := g.rdfG.TriplesForSubjectPredicate(node, rdf.MetaPredicate)
	if err != nil {
		return resource, err
	}
	if err := resource.Meta.unmarshalRDF(metaTriples); err != nil {
		return resource, err
	}

	return resource, nil
}

func (g *Graph) FindResource(id string) (*Resource, error) {
	byId := &ById{id}
	resources, err := byId.Resolve(g)
	if err != nil {
		return nil, err
	}
	if len(resources) == 1 {
		return resources[0], nil
	} else if len(resources) > 1 {
		return nil, fmt.Errorf("multiple resources with id '%s' found", id)
	}

	return nil, nil
}

func (g *Graph) FindResourcesByProperty(key string, value interface{}) ([]*Resource, error) {
	byProperty := ByProperty{key, value}
	return byProperty.Resolve(g)
}

func (g *Graph) GetAllResources(t string) ([]*Resource, error) {
	byType := &ByType{t}
	return byType.Resolve(g)
}

func (g *Graph) ResolveResources(resolvers ...Resolver) ([]*Resource, error) {
	var resources []*Resource
	for _, resolv := range resolvers {
		rs, err := resolv.Resolve(g)
		if err != nil {
			return resources, err
		}
		resources = append(resources, rs...)
	}

	return resources, nil
}

func (g *Graph) ListResourcesDependingOn(start *Resource) ([]*Resource, error) {
	var resources []*Resource

	node, err := start.toRDFNode()
	if err != nil {
		return resources, err
	}

	relations, err := g.rdfG.ListAttachedFrom(node, rdf.AppliesOnPredicate)
	if err != nil {
		return resources, err
	}
	for _, node := range relations {
		res, err := g.GetResource(newResourceType(node), node.ID().String())
		if err != nil {
			return resources, err
		}
		resources = append(resources, res)
	}

	return resources, nil
}

func (g *Graph) Accept(v Visitor) error {
	return v.Visit(g)
}

func (g *Graph) Unmarshal(data []byte) error {
	return g.rdfG.Unmarshal(data)
}

func (g *Graph) MustMarshal() string {
	return g.rdfG.MustMarshal()
}

func (g *Graph) Marshal() ([]byte, error) {
	return g.rdfG.Marshal()
}

func (g *Graph) addRelation(one, other *Resource, pred *predicate.Predicate) error {
	n, err := other.toRDFNode()
	if err != nil {
		return err
	}

	oneN, err := node.NewNodeFromStrings("/"+one.Type(), one.Id())
	if err != nil {
		return err
	}

	t, err := triple.New(oneN, pred, triple.NewNodeObject(n))
	if err != nil {
		return err
	}

	g.rdfG.Add(t)

	return nil
}


text:
"""Base class for SHADHO task managers.

Classes
-------
Manager
    Base class for task managers.
"""

class Manager():
    """Base class for task managers.

    Notes
    -----
    To implement a new local or distributed manager, create an __init__
    method and override all
    """
    def __init__(self):
        pass

    def add_task(self, tag, cmd, params):
        """Add a task for the manger to run.

        Override this with all of the arguments necessary to run the task.

        Parameters
        ----------
        cmd
            Command or function to run in the task.
        tag : str
            Task id generated by SHADHO.
        params : dict
            Generarted hyperparameters to send to the task.
        """
        raise NotImplementedError

    def can_accept_tasks(self):
        """
        """
        raise NotImplementedError

    def handle_success(self):
        """
        """
        raise NotImplementedError

    def handle_failure(self):
        """
        """
        raise NotImplementedError

    def run_task(self):
        """
        """
        raise NotImplementedError

redpajama_set_name: RedPajamaGithub


text: mail/index


text:
<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>
	<parent>
		<artifactId>http</artifactId>
		<groupId>com.ericsson.research.trap.transports</groupId>
		<version>1.4.0-SNAPSHOT</version>
		<relativePath>../pom.xml</relativePath>
	</parent>
	<artifactId>http-server-servlet-2.5</artifactId>
	<name>Trap HTTP Server using HTTPServlet interface</name>

	<repositories>
		<repository>
			<id>trap-snapshots</id>
			<url>https://oss.sonatype.com/content/repositories/snapshots</url>
			<releases>
				<enabled>false</enabled>
			</releases>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</repository>
	</repositories>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>com.ericsson.research.trap</groupId>
			<artifactId>trap-core</artifactId>
			<version>1.4.0-SNAPSHOT</version>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-jdk14</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>javax</groupId>
			<artifactId>javaee-api</artifactId>
			<version>6.0</version>
			<scope>provided</scope>
		</dependency>
	</dependencies>
	<description>HTTP Transport, server side, using HTTPServlet.</description>
</project>


text:
package com.example;

import static lt.util.Log.*;

public class LtConfig {

  public LtConfig() {
    log("LtConfig build");
  }

}


text:
//
//  mysql_parserAppDelegate.m
//  mysql.parser
//
//  Created by Mike on 03.04.12.
//  Copyright 2012 Oracle Corporation. All rights reserved.
//

// These are redefined by the parser.

#import "mysql_parserAppDelegate.h"

#include <sstream>
#include <vector>

#include <stdlib.h>

static std::string last_error;

extern "C" {

  void on_parse_error(struct ANTLR3_BASE_RECOGNIZER_struct * recognizer, pANTLR3_UINT8 * tokenNames)
  {
    std::ostringstream error;

    pANTLR3_PARSER parser;
    pANTLR3_TREE_PARSER tparser;
    pANTLR3_LEXER lexer;

    pANTLR3_INT_STREAM is;
    pANTLR3_STRING ttext;
    pANTLR3_STRING ftext;
    pANTLR3_EXCEPTION ex;
    pANTLR3_COMMON_TOKEN theToken;
    pANTLR3_BASE_TREE theBaseTree;
    pANTLR3_COMMON_TREE theCommonTree;

    // Retrieve some info for easy reading.
    //
    ex = recognizer->state->exception;
    ttext = NULL;

    // See if there is a 'filename' we can use
    //
    if	(ex->streamName == NULL)
    {
      if	(((pANTLR3_COMMON_TOKEN)(ex->token))->type == ANTLR3_TOKEN_EOF)
        error << "-end of input-(";
      else
        error << "-unknown source-(";
    }
    else
    {
      ftext = ex->streamName->to8(ex->streamName);
      error << ftext->chars << "(";
    }

    // Next comes the line number.
    error << recognizer->state->exception->line << ") ";

    // How we determine the next piece is dependent on which thing raised the error.
    switch (recognizer->type)
    {
      case ANTLR3_TYPE_LEXER:
      {
        lexer = (pANTLR3_LEXER)(recognizer->super);
        parser = NULL;
        tparser = NULL;

        error << " : lexer error " << recognizer->state->exception->type << " : " <<	(pANTLR3_UINT8)(ex->message);
        error << ", at offset " << recognizer->state->exception->charPositionInLine + 1;

        {
          ANTLR3_INT32	width;

          width	= ANTLR3_UINT32_CAST(( (pANTLR3_UINT8)(lexer->input->data) + (lexer->input->size(lexer->input) )) - (pANTLR3_UINT8)(ex->index));

          if	(width >= 1)
          {
            if	(isprint(ex->c))
              error << " near '" << (char)ex->c << "' :\n";
            else
              error << " near char(" << (ANTLR3_UINT8)(ex->c) << ") :\n";
          }
          else
          {
            error << "(end of input).\n\t This indicates a poorly specified lexer RULE\n\t or unterminated input element such as: \"STRING[\"]\n";
            width = ANTLR3_UINT32_CAST(((pANTLR3_UINT8)(lexer->input->data)+(lexer->input->size(lexer->input))) - (pANTLR3_UINT8)(lexer->rec->state->tokenStartCharIndex));
          }
        }

        break;
      }

      case	ANTLR3_TYPE_PARSER:
        lexer = NULL;
        parser = (pANTLR3_PARSER) (recognizer->super);
        tparser = NULL;

        is = parser->tstream->istream;
        theToken = (pANTLR3_COMMON_TOKEN)(recognizer->state->exception->token);
        ttext = theToken->toString(theToken);

        error << " : parser error " << recognizer->state->exception->type << " : " <<	(pANTLR3_UINT8)(ex->message);
        error << ", at offset " << recognizer->state->exception->charPositionInLine;
        if  (theToken != NULL)
        {
          if (theToken->type == ANTLR3_TOKEN_EOF)
            error << ", at <EOF>";
          else
            error << "\n    near " << (ttext == NULL ? (pANTLR3_UINT8)"<no text for the token>" : ttext->chars) << "\n    ";
        }
        break;

    case	ANTLR3_TYPE_TREE_PARSER:
        lexer = NULL;
        parser = NULL;
      tparser		= (pANTLR3_TREE_PARSER) (recognizer->super);
      is			= tparser->ctnstream->tnstream->istream;
      theBaseTree	= (pANTLR3_BASE_TREE)(recognizer->state->exception->token);
      ttext		= theBaseTree->toStringTree(theBaseTree);

      if  (theBaseTree != NULL)
      {
        theCommonTree	= (pANTLR3_COMMON_TREE)	    theBaseTree->super;

        if	(theCommonTree != NULL)
          theToken	= (pANTLR3_COMMON_TOKEN)theBaseTree->getToken(theBaseTree);

        error << " : tree parser error " << recognizer->state->exception->type << " : " <<	(pANTLR3_UINT8)(recognizer->state->exception->message);
        error << ", at offset " << theBaseTree->getCharPositionInLine(theBaseTree) << ", near " << ttext->chars;
      }
      break;

    default:
      error << "Internal error: unknown recognizer type appeared in error reporting.\n";
      return;
      break;
    }

    // Although this function should generally be provided by the implementation, this one
    // should be as helpful as possible for grammar developers and serve as an example
    // of what you can do with each exception type. In general, when you make up your
    // 'real' handler, you should debug the routine with all possible errors you expect
    // which will then let you be as specific as possible about all circumstances.
    //
    // Note that in the general case, errors thrown by tree parsers indicate a problem
    // with the output of the parser or with the tree grammar itself. The job of the parser
    // is to produce a perfect (in traversal terms) syntactically correct tree, so errors
    // at that stage should really be semantic errors that your own code determines and handles
    // in whatever way is appropriate.
    switch  (ex->type)
    {
    case	ANTLR3_UNWANTED_TOKEN_EXCEPTION:

      // Indicates that the recognizer was fed a token which seesm to be
      // spurious input. We can detect this when the token that follows
      // this unwanted token would normally be part of the syntactically
      // correct stream. Then we can see that the token we are looking at
      // is just something that should not be there and throw this exception.
      //
      if	(tokenNames == NULL)
        error << " : Extraneous input...";
      else
      {
        if	(ex->expecting == ANTLR3_TOKEN_EOF)
          error << " : Extraneous input - expected <EOF>\n";
        else
          error << " : Extraneous input - expected " << tokenNames[ex->expecting] <<  "...\n";
      }
      break;

    case	ANTLR3_MISSING_TOKEN_EXCEPTION:

      // Indicates that the recognizer detected that the token we just
      // hit would be valid syntactically if preceeded by a particular
      // token. Perhaps a missing ';' at line end or a missing ',' in an
      // expression list, and such like.
      //
      if	(tokenNames == NULL)
      {
        error << " : Missing token (" << ex->expecting << ")...\n";
      }
      else
      {
        if	(ex->expecting == ANTLR3_TOKEN_EOF)
          error << " : Missing <EOF>\n";
        else
          error << " : Missing " << tokenNames[ex->expecting] << " \n";
      }
      break;

    case	ANTLR3_RECOGNITION_EXCEPTION:

      // Indicates that the recognizer received a token
      // in the input that was not predicted. This is the basic exception type
      // from which all others are derived. So we assume it was a syntax error.
      // You may get this if there are not more tokens and more are needed
      // to complete a parse for instance.
      error << " : syntax error...\n";
      break;

    case    ANTLR3_MISMATCHED_TOKEN_EXCEPTION:

      // We were expecting to see one thing and got another. This is the
      // most common error if we coudl not detect a missing or unwanted token.
      // Here you can spend your efforts to
      // derive more useful error messages based on the expected
      // token set and the last token and so on. The error following
      // bitmaps do a good job of reducing the set that we were looking
      // for down to something small. Knowing what you are parsing may be
      // able to allow you to be even more specific about an error.
      if	(tokenNames == NULL)
        error << " : syntax error...\n";
      else
      {
        if	(ex->expecting == ANTLR3_TOKEN_EOF)
          error << " : expected <EOF>\n";
        else
          error << " : expected " << tokenNames[ex->expecting] << " ...\n";
      }
      break;

    case	ANTLR3_NO_VIABLE_ALT_EXCEPTION:
      error << " unexpected input\n";

      break;

    case	ANTLR3_MISMATCHED_SET_EXCEPTION:

      {
        ANTLR3_UINT32	  count;
        ANTLR3_UINT32	  bit;
        ANTLR3_UINT32	  size;
        ANTLR3_UINT32	  numbits;
        pANTLR3_BITSET	errBits;

        // This means we were able to deal with one of a set of
        // possible tokens at this point, but we did not see any
        // member of that set.
        error << " : unexpected input...\n  expected one of : ";

        // What tokens could we have accepted at this point in the parse?
        count   = 0;
        errBits = antlr3BitsetLoad(ex->expectingSet);
        numbits = errBits->numBits(errBits);
        size    = errBits->size(errBits);

        if  (size > 0)
        {
          // However many tokens we could have dealt with here, it is usually
          // not useful to print ALL of the set here. I arbitrarily chose 8
          // here, but you should do whatever makes sense for you of course.
          // No token number 0, so look for bit 1 and on.
          for	(bit = 1; bit < numbits && count < 8 && count < size; bit++)
          {
            // TODO: This doesn;t look right - should be asking if the bit is set!!
            if  (tokenNames[bit])
            {
              error << (count > 0 ? ", " : "") << tokenNames[bit];
              count++;
            }
          }
          error << "\n";
        }
        else
        {
          error << "Actually dude, we didn't seem to be expecting anything here, or at least\n";
          error << "I could not work out what I was expecting, like so many of us these days!\n";
        }
      }
      break;

    case	ANTLR3_EARLY_EXIT_EXCEPTION:

      // We entered a loop requiring a number of token sequences
      // but found a token that ended that sequence earlier than
      // we should have done.
      error << " : missing elements...\n";
      break;

    default:

      // We don't handle any other exceptions here, but you can
      // if you wish. If we get an exception that hits this point
      // then we are just going to report what we know about the
      // token.
      error << " : syntax not recognized...\n";
      break;
    }

    last_error += error.str();
  }

  // Here we just fake some charsets, as we don't have the entire parser context.
  std::string charsets[] = {"utf8", "ucs2", "big5", "latin2", "ujis", "binary", "cp1250", "latin1"};

  /**
   * Checks the given identifier whether it is an actually defined charset, which directs
   * the lexer to either classify it apropriately.
   */
  ANTLR3_UINT32 check_charset(void *payload, pANTLR3_STRING text)
  {
    // Get the actual token text and skip the initial underscore char.
    // There's an additional char at the end of the input for some reason (maybe a lexer bug),
    // so we also ignore the last char.
    std::string token_text((const char*)text->chars + 1, text->len - 2);
    std::transform(token_text.begin(), token_text.end(), token_text.begin(), ::tolower);

    for (int i = 0; i < sizeof(charsets) / sizeof(charsets[0]); i++)
      if (charsets[i] == token_text)
        return UNDERSCORE_CHARSET;
    return IDENTIFIER;
  }

  /**
   * Checks the given text if it is equal to "\N" (w/o quotes and in uppercase). We need this extra
   * check as our lexer is case insensitive.
   */
  ANTLR3_UINT32 check_null(pANTLR3_STRING text)
  {
    std::string token_text((const char*)text->chars, text->len - 1);
    if (token_text == "\\N")
        return NULL2_SYMBOL;
    return ANTLR3_TOKEN_INVALID;
  }

}

NSString *sql1 = @"select 2 as expected, /*!01000/**/*/ 2 as result";
NSString *sql2 = @"select (select\n t1.id as a, sakila.actor.actor_id b, t2.id c, "
  "(select  1 * 0.123, a from t3) from  `ÄÖÜ丈` t1, sakila.actor as t2\n"
  "where ((t1.id = t2.id)) and (t1.id = sakila.actor.actor_id)) as r1, 2";
NSString *sql3 = @"select 1 from\n\t{OJ d left outer join e on a = b} left outer join ee on aa = bb,\n\ta t1 force index for "
  "order by (a, b),\n\t(select 2 from zz) yy straight_join (select 3) as xx on ww,\n\t(b, c),\n\t(f, g) inner join h using (aa, bb),\n"
  "\t(h) straight_join `schema`.`table` on yy < zz natural right join ({OJ i left outer join j on ii = jj})";
NSString *sql4 = @"CREATE PROCEDURE do_insert(value INT)\nBEGIN\n  -- declare variables to hold diagnostics area information\n"
  "  DECLARE code CHAR(5) DEFAULT '00000';\n  DECLARE msg TEXT;\n  DECLARE rows INT;\n  DECLARE result TEXT;\n"
  "  -- declare exception handler for failed insert\n  DECLARE CONTINUE HANDLER FOR SQLEXCEPTION\n    BEGIN\n"
  "      GET DIAGNOSTICS CONDITION 1\n        code = RETURNED_SQLSTATE, msg = MESSAGE_TEXT;\n    END;\n\n"
  "  -- perform the insert\n  INSERT INTO t1 (int_col) VALUES(value);\n  -- check whether the insert was successful\n"
  "  IF code = '00000' THEN\n    GET DIAGNOSTICS rows = ROW_COUNT;\n   -- SET result = CONCAT('insert succeeded, row count = ',rows);\n"
  "  ELSE\n   -- SET result = CONCAT('insert failed, error = ',code,', message = ',msg);\n  END IF;\n"
  "  -- say what happened\n  SELECT result;\nEND";
NSString *sql5 = @"grant alter (a, b) on table * to 'mike'@'%'";
NSString *sql6 = @"select A, B, A OR B, A XOR B, A AND B from t1_30237_bool where C is null order by A, B";
NSString *sql7 = @"select count(distinct a.actor_id), phone, first_name, a.last_name, country.country \n"
  "from sakila.actor a, address aa, country\nwhere (a.actor_id = 0 and country_id > 0) \ngroup by actor_id";
NSString *sql8 = @"drop user current_user(), 'mike'@localhost";
NSString *sql9 = @"CREATE definer = `root`@`localhost` trigger `upd_film` AFTER UPDATE ON `film` FOR EACH ROW BEGIN\n"
  "  IF (old.title != new.title) or (old.description != new.description)\n"
  "  THEN\n"
  "    UPDATE film_text\n"
  "      SET title=new.title,\n"
  "          description=new.description,\n"
  "          film_id=new.film_id\n"
  "    WHERE film_id=old.film_id;\n"
  "  END IF;\n"
  "END";

@implementation mysql_parserAppDelegate

@synthesize window;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {

  // Make the SQL edit control scroll horizontally too.
  [[text textContainer] setContainerSize: NSMakeSize(FLT_MAX, FLT_MAX)];
  [[text textContainer] setWidthTracksTextView: NO];
  [text setString: sql9];
}

- (NSString*)dumpTree: (pANTLR3_BASE_TREE)tree state: (pANTLR3_RECOGNIZER_SHARED_STATE)state indentation: (NSString*)indentation
{
  NSString *result;

  ANTLR3_UINT32 char_pos = tree->getCharPositionInLine(tree);
  ANTLR3_UINT32 line = tree->getLine(tree);
  pANTLR3_STRING token_text = tree->getText(tree);

  pANTLR3_COMMON_TOKEN token = tree->getToken(tree);
  NSString *utf8 = [NSString stringWithUTF8String: (const char*)token_text->chars];
  if (token != NULL) {
    ANTLR3_UINT32 token_type = token->getType(token);

    pANTLR3_UINT8 token_name;
    if (token_type != ANTLR3_TOKEN_EOF)
      token_name = state->tokenNames[token_type];
    if (token_type == ANTLR3_TOKEN_EOF || token_name == (pANTLR3_UINT8)ANTLR3_TOKEN_EOF)
      token_name = (pANTLR3_UINT8)"ANTLR3_TOKEN_EOF";

    result = [NSString stringWithFormat: @"%@(line: %i, offset: %i, length: %lli, index: %lli, %s [%i])    %@\n",
              indentation, line, char_pos, token->stop - token->start + 1,  token->index, token_name, token_type, utf8];
  } else {
    result = [NSString stringWithFormat: @"%@(line: %i, offset: %i, nil)    %@\n", indentation, line, char_pos, utf8];
  }

  for (ANTLR3_UINT32 index = 0; index < tree->getChildCount(tree); index++)
  {
    pANTLR3_BASE_TREE child = (pANTLR3_BASE_TREE)tree->getChild(tree, index);
    NSString *child_text = [self dumpTree: child state: state indentation: [indentation stringByAppendingString: @"\t"]];
    result = [result stringByAppendingString: child_text];
  }
  return result;
}

- (NSString*)dumpTokens: (pANTLR3_BASE_TREE)tree state: (pANTLR3_RECOGNIZER_SHARED_STATE)state
{
  NSString *result;

  ANTLR3_UINT32 char_pos = tree->getCharPositionInLine(tree);
  ANTLR3_UINT32 line = tree->getLine(tree);
  pANTLR3_STRING token_text = tree->getText(tree);

  pANTLR3_COMMON_TOKEN token = tree->getToken(tree);
  if (token != NULL) {
    ANTLR3_UINT32 token_type = token->getType(token);
    pANTLR3_UINT8 token_name = state->tokenNames[token_type];
    if (token_name == (pANTLR3_UINT8)ANTLR3_TOKEN_EOF)
      token_name = (pANTLR3_UINT8)"ANTLR3_TOKEN_EOF";

    result = [NSString stringWithFormat: @"(%s) ", token_name];
  } else {
    result = @"";
  }

  for (ANTLR3_UINT32 index = 0; index < tree->getChildCount(tree); index++)
  {
    pANTLR3_BASE_TREE child = (pANTLR3_BASE_TREE)tree->getChild(tree, index);
    NSString *child_text = [self dumpTokens: child state: state];
    result = [result stringByAppendingString: child_text];
  }
  return result;
}

- (unsigned)getSqlModes
{
  unsigned result = 0;

  if (modeIgnoreSpaceButton.state == NSOnState)
    result |= SQL_MODE_IGNORE_SPACE;
  if (modeAnsiQuotesButton.state == NSOnState)
    result |= SQL_MODE_ANSI_QUOTES;
  if (modePipesAsConcatButton.state == NSOnState)
    result |= SQL_MODE_PIPES_AS_CONCAT;
  if (modeHighNotPrecedenceButton.state == NSOnState)
    result |= SQL_MODE_HIGH_NOT_PRECEDENCE;
  if (modeNoBackslashEscapeButton.state == NSOnState)
    result |= SQL_MODE_NO_BACKSLASH_ESCAPES;

  return result;
}

- (unsigned)getServerVersion
{
  NSString *t = versionText.stringValue;
  if (t.length == 0)
    return 50630;
  return t.intValue;
}

- (IBAction)parseFromClipboard: (id)sender
{
  [text selectAll: sender];
  [text pasteAsPlainText: sender];
  [self parse: sender];
}

- (IBAction)parse: (id)sender
{
  last_error = "";
  [errorText setString: @""];

  pANTLR3_INPUT_STREAM input;
  pMySQLLexer lexer;
  pANTLR3_COMMON_TOKEN_STREAM tokens;
  pMySQLParser parser;

  RecognitionContext context = {[self getServerVersion], [self getSqlModes], nil};

  NSString *sql = [text string];
  std::string utf8 = [sql UTF8String];
  input = antlr3StringStreamNew((pANTLR3_UINT8)utf8.c_str(), ANTLR3_ENC_UTF8, utf8.size(), (pANTLR3_UINT8)"sql-script");
  input->setUcaseLA(input, ANTLR3_TRUE); // Make input case-insensitive. String literals must all be upper case in the grammar!

  lexer = MySQLLexerNew(input);
  lexer->pLexer->rec->state->userp = &context;
  tokens = antlr3CommonTokenStreamSourceNew(ANTLR3_SIZE_HINT, TOKENSOURCE(lexer));
  parser = MySQLParserNew(tokens);
  parser->pParser->rec->state->userp = &context;

  pANTLR3_BASE_TREE tree = parser->query(parser).tree;

  NSString *combinedErrorText = @"No errors found";
  ANTLR3_UINT32 error_count = parser->pParser->rec->state->errorCount;
  error_count += lexer->pLexer->rec->state->errorCount;
  if (error_count > 0) {
    combinedErrorText = [NSString stringWithFormat: @"%i errors found\n%s", error_count, last_error.c_str()];
  }
  [errorText setString: combinedErrorText];

  if (tree != NULL) {
    NSString *token_text = [self dumpTree: tree state: parser->pParser->rec->state indentation: @""];
    [output setString: token_text];
  } else {
    [output setString: @"no tree"];
  }

  // Must manually clean up.
  parser->free(parser);
  tokens ->free(tokens);
  lexer->free(lexer);
  input->close(input);
}

- (BOOL)parseQuery: (NSString *)query version: (unsigned)serverVersion modes: (unsigned)sqlModes
{
  pANTLR3_INPUT_STREAM input;
  pMySQLLexer lexer;
  pANTLR3_COMMON_TOKEN_STREAM tokens;
  pMySQLParser parser;

  RecognitionContext context = {serverVersion, sqlModes, nil};

  std::string utf8 = [query UTF8String];
  input = antlr3StringStreamNew((pANTLR3_UINT8)utf8.c_str(), ANTLR3_ENC_UTF8, utf8.size(), (pANTLR3_UINT8)"sql-script");
  input->setUcaseLA(input, ANTLR3_TRUE);

  lexer = MySQLLexerNew(input);
  lexer->pLexer->rec->state->userp = &context;
  tokens = antlr3CommonTokenStreamSourceNew(ANTLR3_SIZE_HINT, TOKENSOURCE(lexer));
  parser = MySQLParserNew(tokens);
  parser->pParser->rec->state->userp = &context;

  MySQLParser_query_return ast = parser->query(parser);

  BOOL result = last_error.size() == 0;

  // Must manually clean up.
  parser->free(parser);
  tokens ->free(tokens);
  lexer->free(lexer);
  input->close(input);

  return result;
}

bool parse_and_compare(const std::string query, pANTLR3_BASE_TREE tree, unsigned sql_modes, unsigned server_version)
{
  pANTLR3_INPUT_STREAM input;
  pMySQLLexer lexer;
  pANTLR3_COMMON_TOKEN_STREAM tokens;
  pMySQLParser parser;

  RecognitionContext context = {server_version, sql_modes, nil};

  input = antlr3StringStreamNew((pANTLR3_UINT8)query.c_str(), ANTLR3_ENC_UTF8, query.size(), (pANTLR3_UINT8)"sql-script");
  input->setUcaseLA(input, ANTLR3_TRUE);

  lexer = MySQLLexerNew(input);
  lexer->pLexer->rec->state->userp = &context;
  tokens = antlr3CommonTokenStreamSourceNew(ANTLR3_SIZE_HINT, TOKENSOURCE(lexer));
  parser = MySQLParserNew(tokens);
  parser->pParser->rec->state->userp = &context;

  MySQLParser_query_return ast = parser->query(parser);

  BOOL result = parser->pParser->rec->state->errorCount == 0;
  if (result)
  {
    // If there was no error then check the order of tokens.
  }

  parser->free(parser);
  tokens ->free(tokens);
  lexer->free(lexer);
  input->close(input);

  return result;
}

- (IBAction)selectFile: (id)sender
{
  NSOpenPanel *panel = [NSOpenPanel openPanel];
  panel.canChooseDirectories = NO;
  panel.allowsMultipleSelection = NO;
  panel.canChooseFiles = YES;
  panel.allowedFileTypes = [NSArray arrayWithObjects: @"txt", @"sql", nil];
  panel.directoryURL = [NSURL fileURLWithPath: [pathEdit stringValue]];
  if ([panel runModal] == NSFileHandlingPanelOKButton) {
    pathEdit.stringValue = panel.URL.path;
  }
}

- (void)appendStepText: (NSString *)newText
{
  stepsList.string = [stepsList.string stringByAppendingString: newText];
}

- (IBAction)startTests: (id)sender
{
  if (running) {
    stopTests = YES;
    return;
  }

  NSString *fileName = pathEdit.stringValue;
  NSError *error = nil;
  NSString *contents = [NSString stringWithContentsOfFile: fileName encoding: NSUTF8StringEncoding error: &error];
  if (error != nil) {
    NSAlert *alert = [NSAlert alertWithError: error];
    [alert runModal];
    return;
  }

  stopTests = NO;
  queryText.string = @"";
  last_error = "";

  statusText.stringValue = @"Counting queries...";
  stepsList.string = @"Counting queries\n";
  progressLabel.stringValue = @"0 of 0";

  [self countQueriesInFile: fileName];
  [self appendStepText: [NSString stringWithFormat: @"Found %lu queries in file\n", (unsigned long)queryCount]];

  [topView setNeedsDisplay: YES];

  NSThread *thread = [[[NSThread alloc] initWithTarget: self
                                              selector: @selector(runTestsWithData:)
                                                object: contents] autorelease];
  [thread setStackSize: 8 * 1024 * 1024];
  [thread start];
}

- (void)countQueriesInFile: (NSString*)fileName
{

  NSFileHandle * file = [NSFileHandle fileHandleForReadingAtPath: fileName];
  NSUInteger chunkSize = 1024 * 1024;
  NSData * chunk = [file readDataOfLength: chunkSize];
  queryCount = 0;
  NSUInteger seenDollars = 0;
  while ([chunk length] > 0) {
    const char *chars = (const char *)[chunk bytes];
    for (int index = 0; index < [chunk length]; ++index) {
      switch (chars[index]) {
        case '$':
          seenDollars++;
          break;
        case '\n':
          if (seenDollars == 2) {
            seenDollars = 0;
            queryCount++;
          }
          break;
        default:
          seenDollars = 0;
          break;
      }
    }
    chunk = [file readDataOfLength: chunkSize];
  }

}

- (void)runTestsWithData: (NSString*)data
{
  try {
    // 1. Part: parse example queries from file.
    statusText.stringValue = @"Running tests from file...";
    [self appendStepText: @"Running tests from file\n"];

    NSUInteger count = 0;
    BOOL gotError = NO;
    NSArray *queries = [data componentsSeparatedByString: @"$$\n"];
    unsigned serverVersion = [self getServerVersion];
    unsigned sqlModes = [self getSqlModes];
    for (NSString* query in queries) {
      if (stopTests)
        break;

      if (query.length > 0) {
        progressLabel.stringValue = [NSString stringWithFormat: @"%lu of %lu", ++count, queryCount];
        [progressLabel setNeedsDisplay];
        if (![self parseQuery: query version: serverVersion modes: sqlModes])
        {
          statusText.stringValue = @"Error encountered, offending query below:";
          queryText.string = query;
          gotError = YES;
          break;
        }
      }
    }

    // 2. Part: parse queries with function names for foreign keys.
    if (!gotError && !stopTests)
    {
      [self appendStepText: [NSString stringWithFormat: @"Parsed %lu queries in file successfully.\n", (unsigned long)queryCount]];

      [self appendStepText: @"Running function name tests\n"];
      statusText.stringValue = @"Running function name tests...";
      gotError = ![self runFunctionNamesTest];
    }

    // 3. Part: parse queries for correct operator precedence.
    if (!gotError && !stopTests)
    {
      [self appendStepText: @"Running operator precedence tests\n"];
      statusText.stringValue = @"Running operator precedence tests...";
      gotError = ![self runOperatorPrecedenceTests];
    }

    if (stopTests)
      statusText.stringValue = @"Execution stopped by user.";
    else
      if (!gotError)
        statusText.stringValue = @"All queries parsed fine. Great!";
    running = NO;
  } catch (std::exception& e) {
    running = NO;
    statusText.stringValue = [NSString stringWithFormat: @"Parser raised exception: %s", e.what()];
  }

}

/**
 * Generates queries with many MySQL functions (all?) used in foreign key creation (parser bug #21114).
 * Note: this test is currently only partially useful as most of the used functions are not reserved words
 *       (and hence not contained in the grammar). This might change if the parsing process does an
 *       explicit differentiation between general identifiers and function names.
 * Returns YES if all went ok.
 */
- (BOOL)runFunctionNamesTest
{
  static const char* functions[] = {
    "acos",
    "adddate",
    "addtime"
    "aes_decrypt",
    "aes_encrypt",
    "area",
    "asbinary",
    "asin",
    "astext",
    "aswkb",
    "aswkt",
    "atan",
    "atan2",
    "benchmark",
    "bin",
    "bit_count",
    "bit_length",
    "ceil",
    "ceiling",
    "centroid",
    "character_length",
    "char_length",
    "coercibility",
    "compress",
    "concat",
    "concat_ws",
    "connection_id",
    "conv",
    "convert_tz",
    "cos",
    "cot",
    "crc32",
    "crosses",
    "datediff",
    "date_format",
    "dayname",
    "dayofmonth",
    "dayofweek",
    "dayofyear",
    "decode",
    "degrees",
    "des_decrypt",
    "des_encrypt",
    "dimension",
    "disjoint",
    "elt",
    "encode",
    "encrypt",
    "endpoint",
    "envelope",
    "equals",
    "exp",
    "export_set",
    "exteriorring",
    "extractvalue",
    "find_in_set",
    "floor",
    "found_rows",
    "from_days",
    "from_unixtime",
    "geomcollfromtext",
    "geomcollfromwkb",
    "geometrycollectionfromtext",
    "geometrycollectionfromwkb",
    "geometryfromtext",
    "geometryfromwkb",
    "geometryn",
    "geometrytype",
    "geomfromtext",
    "geomfromwkb",
    "get_lock",
    "glength",
    "greatest",
    "hex",
    "ifnull",
    "inet_aton",
    "inet_ntoa",
    "instr",
    "interiorringn",
    "intersects",
    "isclosed",
    "isempty",
    "isnull",
    "issimple",
    "is_free_lock",
    "is_used_lock",
    "last_day",
    "last_insert_id",
    "lcase",
    "least",
    "length",
    "linefromtext",
    "linefromwkb",
    "linestringfromtext",
    "linestringfromwkb",
    "ln",
    "load_file",
    "locate",
    "log",
    "log10",
    "log2",
    "lower",
    "lpad",
    "ltrim",
    "makedate",
    "maketime",
    "make_set",
    "master_pos_wait",
    "mbrcontains",
    "mbrdisjoint",
    "mbrequal",
    "mbrintersects",
    "mbroverlaps",
    "mbrtouches",
    "mbrwithin",
    "md5",
    "mlinefromtext",
    "mlinefromwkb",
    "monthname",
    "mpointfromtext",
    "mpointfromwkb",
    "mpolyfromtext",
    "mpolyfromwkb",
    "multilinestringfromtext",
    "multilinestringfromwkb",
    "multipointfromtext",
    "multipointfromwkb",
    "multipolygonfromtext",
    "multipolygonfromwkb",
    "name_const",
    "nullif",
    "numgeometries",
    "numinteriorrings",
    "numpoints",
    "oct",
    "octet_length",
    "ord",
    "overlaps",
    "period_add",
    "period_diff",
    "pi",
    "pointfromtext",
    "pointfromwkb",
    "pointn",
    "polyfromtext",
    "polyfromwkb",
    "polygonfromtext",
    "polygonfromwkb",
    "pow",
    "power",
    "quote",
    "radians",
    "rand",
    "release_lock",
    "reverse",
    "round",
    "row_count",
    "rpad",
    "rtrim",
    "sec_to_time",
    "session_user",
    "sha",
    "sha1",
    "sign",
    "sin",
    "sleep",
    "soundex",
    "space",
    "sqrt",
    "srid",
    "startpoint",
    "strcmp",
    "str_to_date",
    "subdate",
    "substring_index",
    "subtime",
    "system_user",
    "tan",
    "timediff",
    "time_format",
    "time_to_sec",
    "touches",
    "to_days",
    "ucase",
    "uncompress",
    "uncompressed_length",
    "unhex",
    "unix_timestamp",
    "updatexml",
    "upper",
    "uuid",
    "version",
    "weekday",
    "weekofyear",
    "within",
    "x",
    "y",
    "yearweek"};

  const char *query1 = "CREATE TABLE %s(\n"
    "col1 int not null,\n"
    "col2 int not null,\n"
    "col3 varchar(10),\n"
    "CONSTRAINT pk PRIMARY KEY (col1, col2)\n"
    ") ENGINE InnoDB";

  const char *query2 = "CREATE TABLE bug21114_child(\n"
    "pk int not null,\n"
    "fk_col1 int not null,\n"
    "fk_col2 int not null,\n"
    "fk_col3 int not null,\n"
    "fk_col4 int not null,\n"
    "CONSTRAINT fk_fct FOREIGN KEY (fk_col1, fk_col2)\n"
    "REFERENCES %s(col1, col2),\n"
    "CONSTRAINT fk_fct_space FOREIGN KEY (fk_col3, fk_col4)\n"
    "REFERENCES %s (col1, col2)\n"
    ") ENGINE InnoDB";

  NSInteger count = sizeof(functions) / sizeof(functions[0]);
  unsigned serverVersion = [self getServerVersion];
  unsigned sqlModes = [self getSqlModes];
  for (size_t i = 0; i < count; i++)
  {
    if (stopTests)
      return NO;

    NSString *query = [NSString stringWithFormat: [NSString stringWithUTF8String: query1], functions[i]];
    if (query.length > 0) {
      progressLabel.stringValue = [NSString stringWithFormat: @"%lu of %li", i + 1, count];
      [progressLabel setNeedsDisplay];
      if (![self parseQuery: query version: serverVersion modes: sqlModes])
      {
        statusText.stringValue = @"Error encountered, offending query below:";
        queryText.string = query;
        return NO;
      }
    }

    query = [NSString stringWithFormat: [NSString stringWithUTF8String: query2], functions[i], functions[i]];
    if (query.length > 0) {
      [progressLabel setNeedsDisplay];
      if (![self parseQuery: query version: serverVersion modes: sqlModes])
      {
        statusText.stringValue = @"Error encountered, offending query below:";
        queryText.string = query;
        return NO;
      }
    }
  }
  return YES;
}

- (BOOL)runOperatorPrecedenceTests
{
#define TEST_ERROR \
{\
  statusText.stringValue = @"Error encountered, offending query below:";\
  queryText.string = [NSString stringWithUTF8String: query.c_str()];\
  return NO;\
}

  unsigned sql_modes = [self getSqlModes];
  unsigned server_version = [self getServerVersion];

  // Testing OR, XOR, AND
  std::string query = "select A, B, A OR B, A XOR B, A AND B from t1_30237_bool where C is null order by A, B";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that OR is associative
  query = "select A, B, C, (A OR B) OR C, A OR (B OR C), A OR B OR C from t1_30237_bool order by A, B, C";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  query = "select count(*) from t1_30237_bool where ((A OR B) OR C) != (A OR (B OR C))";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that XOR is associative
  query = "select A, B, C, (A XOR B) XOR C, A XOR (B XOR C), A XOR B XOR C from t1_30237_bool order by A, B, C";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  query = "select count(*) from t1_30237_bool where ((A XOR B) XOR C) != (A XOR (B XOR C))";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that AND is associative
  query = "select A, B, C, (A AND B) AND C, A AND (B AND C), A AND B AND C from t1_30237_bool order by A, B, C";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  query = "select count(*) from t1_30237_bool where ((A AND B) AND C) != (A AND (B AND C))";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that AND has precedence over OR
  query = "select A, B, C, (A OR B) AND C, A OR (B AND C), A OR B AND C from t1_30237_bool order by A, B, C";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select count(*) from t1_30237_bool where (A OR (B AND C)) != (A OR B AND C)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select A, B, C, (A AND B) OR C, A AND (B OR C), A AND B OR C from t1_30237_bool order by A, B, C";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select count(*) from t1_30237_bool where ((A AND B) OR C) != (A AND B OR C)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that AND has precedence over XOR
  query = "select A, B, C, (A XOR B) AND C, A XOR (B AND C), A XOR B AND C from t1_30237_bool order by A, B, C";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select count(*) from t1_30237_bool where (A XOR (B AND C)) != (A XOR B AND C)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select A, B, C, (A AND B) XOR C, A AND (B XOR C), A AND B XOR C from t1_30237_bool order by A, B, C";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select count(*) from t1_30237_bool where ((A AND B) XOR C) != (A AND B XOR C)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that XOR has precedence over OR
  query = "select A, B, C, (A XOR B) OR C, A XOR (B OR C), A XOR B OR C from t1_30237_bool order by A, B, C";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select count(*) from t1_30237_bool where ((A XOR B) OR C) != (A XOR B OR C)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select A, B, C, (A OR B) XOR C, A OR (B XOR C), A OR B XOR C from t1_30237_bool order by A, B, C";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select count(*) from t1_30237_bool where (A OR (B XOR C)) != (A OR B XOR C)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that NOT has precedence over OR
  query = "select (NOT FALSE) OR TRUE, NOT (FALSE OR TRUE), NOT FALSE OR TRUE";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that NOT has precedence over XOR
  query = "select (NOT FALSE) XOR FALSE, NOT (FALSE XOR FALSE), NOT FALSE XOR FALSE";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that NOT has precedence over AND
  query = "select (NOT FALSE) AND FALSE, NOT (FALSE AND FALSE), NOT FALSE AND FALSE";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that NOT is associative
  query = "select NOT NOT TRUE, NOT NOT NOT FALSE";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that IS has precedence over NOT
  query = "select (NOT NULL) IS TRUE, NOT (NULL IS TRUE), NOT NULL IS TRUE";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select (NOT NULL) IS NOT TRUE, NOT (NULL IS NOT TRUE), NOT NULL IS NOT TRUE";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select (NOT NULL) IS FALSE, NOT (NULL IS FALSE), NOT NULL IS FALSE";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select (NOT NULL) IS NOT FALSE, NOT (NULL IS NOT FALSE), NOT NULL IS NOT FALSE";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select (NOT TRUE) IS UNKNOWN, NOT (TRUE IS UNKNOWN), NOT TRUE IS UNKNOWN";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select (NOT TRUE) IS NOT UNKNOWN, NOT (TRUE IS NOT UNKNOWN), NOT TRUE IS NOT UNKNOWN";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select (NOT TRUE) IS NULL, NOT (TRUE IS NULL), NOT TRUE IS NULL";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select (NOT TRUE) IS NOT NULL, NOT (TRUE IS NOT NULL), NOT TRUE IS NOT NULL";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that IS [NOT] NULL predicates are associative
  // Documenting existing behavior in 5.0.48
  query = "select FALSE IS NULL IS NULL IS NULL";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select TRUE IS NOT NULL IS NOT NULL IS NOT NULL";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that comparison operators are left associative
  query = "select 1 <=> 2 <=> 2, (1 <=> 2) <=> 2, 1 <=> (2 <=> 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 1 = 2 = 2, (1 = 2) = 2, 1 = (2 = 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 1 != 2 != 3, (1 != 2) != 3, 1 != (2 != 3)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 1 <> 2 <> 3, (1 <> 2) <> 3, 1 <> (2 <> 3)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 1 < 2 < 3, (1 < 2) < 3, 1 < (2 < 3)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 3 <= 2 <= 1, (3 <= 2) <= 1, 3 <= (2 <= 1)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 1 > 2 > 3, (1 > 2) > 3, 1 > (2 > 3)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 1 >= 2 >= 3, (1 >= 2) >= 3, 1 >= (2 >= 3)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that | is associative
  query = "select 0xF0 | 0x0F | 0x55, (0xF0 | 0x0F) | 0x55, 0xF0 | (0x0F | 0x55)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that & is associative
  query = "select 0xF5 & 0x5F & 0x55, (0xF5 & 0x5F) & 0x55, 0xF5 & (0x5F & 0x55)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that << is left associative
  query = "select 4 << 3 << 2, (4 << 3) << 2, 4 << (3 << 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that >> is left associative
  query = "select 256 >> 3 >> 2, (256 >> 3) >> 2, 256 >> (3 >> 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that & has precedence over |
  query = "select 0xF0 & 0x0F | 0x55, (0xF0 & 0x0F) | 0x55, 0xF0 & (0x0F | 0x55)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 0x55 | 0xF0 & 0x0F, (0x55 | 0xF0) & 0x0F, 0x55 | (0xF0 & 0x0F)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that << has precedence over |
  query = "select 0x0F << 4 | 0x0F, (0x0F << 4) | 0x0F, 0x0F << (4 | 0x0F)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 0x0F | 0x0F << 4, (0x0F | 0x0F) << 4, 0x0F | (0x0F << 4)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that >> has precedence over |
  query = "select 0xF0 >> 4 | 0xFF, (0xF0 >> 4) | 0xFF, 0xF0 >> (4 | 0xFF)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 0xFF | 0xF0 >> 4, (0xFF | 0xF0) >> 4, 0xFF | (0xF0 >> 4)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that << has precedence over &
  query = "select 0x0F << 4 & 0xF0, (0x0F << 4) & 0xF0, 0x0F << (4 & 0xF0)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 0xF0 & 0x0F << 4, (0xF0 & 0x0F) << 4, 0xF0 & (0x0F << 4)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that >> has precedence over &
  query = "select 0xF0 >> 4 & 0x55, (0xF0 >> 4) & 0x55, 0xF0 >> (4 & 0x55)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 0x0F & 0xF0 >> 4, (0x0F & 0xF0) >> 4, 0x0F & (0xF0 >> 4)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that >> and << have the same precedence
  query = "select 0xFF >> 4 << 2, (0xFF >> 4) << 2, 0xFF >> (4 << 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 0x0F << 4 >> 2, (0x0F << 4) >> 2, 0x0F << (4 >> 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that binary + is associative
  query = "select 1 + 2 + 3, (1 + 2) + 3, 1 + (2 + 3)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that binary - is left associative
  query = "select 1 - 2 - 3, (1 - 2) - 3, 1 - (2 - 3)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that binary + and binary - have the same precedence
  // and are evaluated left to right
  query = "select 1 + 2 - 3, (1 + 2) - 3, 1 + (2 - 3)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 1 - 2 + 3, (1 - 2) + 3, 1 - (2 + 3)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that binary + has precedence over |
  query = "select 0xF0 + 0x0F | 0x55, (0xF0 + 0x0F) | 0x55, 0xF0 + (0x0F | 0x55)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 0x55 | 0xF0 + 0x0F, (0x55 | 0xF0) + 0x0F, 0x55 | (0xF0 + 0x0F)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that binary + has precedence over &
  query = "select 0xF0 + 0x0F & 0x55, (0xF0 + 0x0F) & 0x55, 0xF0 + (0x0F & 0x55)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 0x55 & 0xF0 + 0x0F, (0x55 & 0xF0) + 0x0F, 0x55 & (0xF0 + 0x0F)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that binary + has precedence over <<
  query = "select 2 + 3 << 4, (2 + 3) << 4, 2 + (3 << 4)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 3 << 4 + 2, (3 << 4) + 2, 3 << (4 + 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that binary + has precedence over >>
  query = "select 4 + 3 >> 2, (4 + 3) >> 2, 4 + (3 >> 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 3 >> 2 + 1, (3 >> 2) + 1, 3 >> (2 + 1)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that binary - has precedence over |
  query = "select 0xFF - 0x0F | 0x55, (0xFF - 0x0F) | 0x55, 0xFF - (0x0F | 0x55)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 0x55 | 0xFF - 0xF0, (0x55 | 0xFF) - 0xF0, 0x55 | (0xFF - 0xF0)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that binary - has precedence over &
  query = "select 0xFF - 0xF0 & 0x55, (0xFF - 0xF0) & 0x55, 0xFF - (0xF0 & 0x55)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 0x55 & 0xFF - 0xF0, (0x55 & 0xFF) - 0xF0, 0x55 & (0xFF - 0xF0)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that binary - has precedence over <<
  query = "select 16 - 3 << 2, (16 - 3) << 2, 16 - (3 << 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 4 << 3 - 2, (4 << 3) - 2, 4 << (3 - 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that binary - has precedence over >>
  query = "select 16 - 3 >> 2, (16 - 3) >> 2, 16 - (3 >> 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 16 >> 3 - 2, (16 >> 3) - 2, 16 >> (3 - 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that * is associative
  query = "select 2 * 3 * 4, (2 * 3) * 4, 2 * (3 * 4)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that * has precedence over |
  query = "select 2 * 0x40 | 0x0F, (2 * 0x40) | 0x0F, 2 * (0x40 | 0x0F)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 0x0F | 2 * 0x40, (0x0F | 2) * 0x40, 0x0F | (2 * 0x40)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that * has precedence over &
  query = "select 2 * 0x40 & 0x55, (2 * 0x40) & 0x55, 2 * (0x40 & 0x55)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 0xF0 & 2 * 0x40, (0xF0 & 2) * 0x40, 0xF0 & (2 * 0x40)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that * has precedence over <<
  // Actually, can't prove it for the first case,
  // since << is a multiplication by a power of 2,
  // and * is associative
  query = "select 5 * 3 << 4, (5 * 3) << 4, 5 * (3 << 4)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 2 << 3 * 4, (2 << 3) * 4, 2 << (3 * 4)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that * has precedence over >>
  // >> is a multiplication by a (negative) power of 2,
  // see above.
  query = "select 3 * 4 >> 2, (3 * 4) >> 2, 3 * (4 >> 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 4 >> 2 * 3, (4 >> 2) * 3, 4 >> (2 * 3)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that * has precedence over binary +
  query = "select 2 * 3 + 4, (2 * 3) + 4, 2 * (3 + 4)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 2 + 3 * 4, (2 + 3) * 4, 2 + (3 * 4)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that * has precedence over binary -
  query = "select 4 * 3 - 2, (4 * 3) - 2, 4 * (3 - 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 4 - 3 * 2, (4 - 3) * 2, 4 - (3 * 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that / is left associative
  query = "select 15 / 5 / 3, (15 / 5) / 3, 15 / (5 / 3)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that / has precedence over |
  query = "select 105 / 5 | 2, (105 / 5) | 2, 105 / (5 | 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 105 | 2 / 5, (105 | 2) / 5, 105 | (2 / 5)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that / has precedence over &
  query = "select 105 / 5 & 0x0F, (105 / 5) & 0x0F, 105 / (5 & 0x0F)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 0x0F & 105 / 5, (0x0F & 105) / 5, 0x0F & (105 / 5)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that / has precedence over <<
  query = "select 0x80 / 4 << 2, (0x80 / 4) << 2, 0x80 / (4 << 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 0x80 << 4 / 2, (0x80 << 4) / 2, 0x80 << (4 / 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that / has precedence over >>
  query = "select 0x80 / 4 >> 2, (0x80 / 4) >> 2, 0x80 / (4 >> 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 0x80 >> 4 / 2, (0x80 >> 4) / 2, 0x80 >> (4 / 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that / has precedence over binary +
  query = "select 0x80 / 2 + 2, (0x80 / 2) + 2, 0x80 / (2 + 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 0x80 + 2 / 2, (0x80 + 2) / 2, 0x80 + (2 / 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that / has precedence over binary -
  query = "select 0x80 / 4 - 2, (0x80 / 4) - 2, 0x80 / (4 - 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 0x80 - 4 / 2, (0x80 - 4) / 2, 0x80 - (4 / 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // TODO: %, DIV, MOD

  // Testing that ^ is associative
  query = "select 0xFF ^ 0xF0 ^ 0x0F, (0xFF ^ 0xF0) ^ 0x0F, 0xFF ^ (0xF0 ^ 0x0F)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 0xFF ^ 0xF0 ^ 0x55, (0xFF ^ 0xF0) ^ 0x55, 0xFF ^ (0xF0 ^ 0x55)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that ^ has precedence over |
  query = "select 0xFF ^ 0xF0 | 0x0F, (0xFF ^ 0xF0) | 0x0F, 0xFF ^ (0xF0 | 0x0F)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 0xF0 | 0xFF ^ 0xF0, (0xF0 | 0xFF) ^ 0xF0, 0xF0 | (0xFF ^ 0xF0)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that ^ has precedence over &
  query = "select 0xFF ^ 0xF0 & 0x0F, (0xFF ^ 0xF0) & 0x0F, 0xFF ^ (0xF0 & 0x0F)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 0x0F & 0xFF ^ 0xF0, (0x0F & 0xFF) ^ 0xF0, 0x0F & (0xFF ^ 0xF0)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that ^ has precedence over <<
  query = "select 0xFF ^ 0xF0 << 2, (0xFF ^ 0xF0) << 2, 0xFF ^ (0xF0 << 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 0x0F << 2 ^ 0xFF, (0x0F << 2) ^ 0xFF, 0x0F << (2 ^ 0xFF)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that ^ has precedence over >>
  query = "select 0xFF ^ 0xF0 >> 2, (0xFF ^ 0xF0) >> 2, 0xFF ^ (0xF0 >> 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 0xFF >> 2 ^ 0xF0, (0xFF >> 2) ^ 0xF0, 0xFF >> (2 ^ 0xF0)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that ^ has precedence over binary +
  query = "select 0xFF ^ 0xF0 + 0x0F, (0xFF ^ 0xF0) + 0x0F, 0xFF ^ (0xF0 + 0x0F)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 0x0F + 0xFF ^ 0xF0, (0x0F + 0xFF) ^ 0xF0, 0x0F + (0xFF ^ 0xF0)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that ^ has precedence over binary -
  query = "select 0xFF ^ 0xF0 - 1, (0xFF ^ 0xF0) - 1, 0xFF ^ (0xF0 - 1)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 0x55 - 0x0F ^ 0x55, (0x55 - 0x0F) ^ 0x55, 0x55 - (0x0F ^ 0x55)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that ^ has precedence over *
  query = "select 0xFF ^ 0xF0 * 2, (0xFF ^ 0xF0) * 2, 0xFF ^ (0xF0 * 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 2 * 0xFF ^ 0xF0, (2 * 0xFF) ^ 0xF0, 2 * (0xFF ^ 0xF0)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that ^ has precedence over /
  query = "select 0xFF ^ 0xF0 / 2, (0xFF ^ 0xF0) / 2, 0xFF ^ (0xF0 / 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 0xF2 / 2 ^ 0xF0, (0xF2 / 2) ^ 0xF0, 0xF2 / (2 ^ 0xF0)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that ^ has precedence over %
  query = "select 0xFF ^ 0xF0 % 0x20, (0xFF ^ 0xF0) % 0x20, 0xFF ^ (0xF0 % 0x20)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 0xFF % 0x20 ^ 0xF0, (0xFF % 0x20) ^ 0xF0, 0xFF % (0x20 ^ 0xF0)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that ^ has precedence over DIV
  query = "select 0xFF ^ 0xF0 DIV 2, (0xFF ^ 0xF0) DIV 2, 0xFF ^ (0xF0 DIV 2)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query = "select 0xF2 DIV 2 ^ 0xF0, (0xF2 DIV 2) ^ 0xF0, 0xF2 DIV (2 ^ 0xF0)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

  // Testing that ^ has precedence over MOD
  query = "select 0xFF ^ 0xF0 MOD 0x20, (0xFF ^ 0xF0) MOD 0x20, 0xFF ^ (0xF0 MOD 0x20)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR
  query =  "select 0xFF MOD 0x20 ^ 0xF0, (0xFF MOD 0x20) ^ 0xF0, 0xFF MOD (0x20 ^ 0xF0)";
  if (!parse_and_compare(query, NULL, sql_modes, server_version))
    TEST_ERROR

#undef TEST_ERROR

    return YES;
}

#pragma mark -
#pragma mark Action handling

- (IBAction)startConversion: (id)sender
{
  NSString *tokenListString = @"";

  NSArray *queries = [queryList.string componentsSeparatedByCharactersInSet: [NSCharacterSet characterSetWithCharactersInString: @"$$"]];
  for (NSString *entry in queries) {
    NSString *query = [entry stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (query.length == 0)
      continue;

    pANTLR3_INPUT_STREAM input;
    pMySQLLexer lexer;
    pANTLR3_COMMON_TOKEN_STREAM tokenStream;
    pMySQLParser parser;

    RecognitionContext context = {[self getServerVersion], [self getSqlModes], nil};

    std::string utf8 = [query UTF8String];
    input = antlr3StringStreamNew((pANTLR3_UINT8)utf8.c_str(), ANTLR3_ENC_UTF8, utf8.size(), (pANTLR3_UINT8)"sql-script");
    input->setUcaseLA(input, ANTLR3_TRUE);

    lexer = MySQLLexerNew(input);
    lexer->pLexer->rec->state->userp = &context;
    tokenStream = antlr3CommonTokenStreamSourceNew(ANTLR3_SIZE_HINT, TOKENSOURCE(lexer));
    parser = MySQLParserNew(tokenStream);
    parser->pParser->rec->state->userp = &context;

    MySQLParser_query_return ast = parser->query(parser);

    if (parser->pParser->rec->state->errorCount > 0) {
      conversionErrorText.stringValue = @"Errors occurred.";
    }

    NSString *tokens;
    if (ast.tree != NULL) {
      tokens = [self dumpTokens: ast.tree state: parser->pParser->rec->state];
    } else {
      tokens = @"(no tree)";
    }
    tokenListString = [tokenListString stringByAppendingString:
                       [NSString stringWithFormat: @"{\"%@\",\nlist_of %@\n},\n", query, tokens]
                       ];

    // Must manually clean up.
    parser->free(parser);
    tokenStream ->free(tokenStream);
    lexer->free(lexer);
    input->close(input);
  }

  tokenList.string = tokenListString;
  conversionErrorText.stringValue = @"Everything went fine.";
}

@end


text:
//
//  trellis.h
//  StochHMM
//
//Permission is hereby granted, free of charge, to any person obtaining a copy of
//this software and associated documentation files (the "Software"), to deal in
//the Software without restriction, including without limitation the rights to
//use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
//the Software, and to permit persons to whom the Software is furnished to do so,
//subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in all
//copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
//FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
//COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
//IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
//CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

#ifndef __StochHMM__new_trellis__
#define __StochHMM__new_trellis__

#include <iostream>
#include <vector>
#include <stdint.h>
#include <vector>
#include <string>
#include <fstream>
#include <bitset>
#include <map>
#include "stochTypes.h"
#include "sequences.h"
#include "hmm.h"
#include "traceback_path.h"
#include "stochMath.h"
#include <stdint.h>
#include <iomanip>
#include "stochTable.h"
#include "sparseArray.h"

namespace StochHMM{

	typedef std::vector<std::vector<int16_t> > int_2D;
	typedef std::vector<std::vector<float> > float_2D;
	typedef std::vector<std::vector<double> > double_2D;
	typedef std::vector<std::vector<long double> > long_double_2D;

	typedef std::vector<std::vector<std::vector<uint16_t> > > int_3D;
	typedef std::vector<std::vector<std::vector<float> > > float_3D;
	typedef std::vector<std::vector<std::vector<double> > > double_3D;
	typedef std::vector<std::vector<std::vector<long double> > > long_double_3D;
//	typedef std::vector<std::vector<std::vector<std::pair<int16_t,int16_t> >

	class nthScore{
	public:
		int16_t st_tb;
		int16_t score_tb;
		double score;
		nthScore():st_tb(0),score_tb(0),score(-INFINITY){};
		nthScore(int16_t st, int16_t tb, double sc):st_tb(st),score_tb(tb),score(sc){};

	};

//	struct nthTrace{
//		int16_t st_tb;
//		int16_t score_tb;
//		nthTrace():st_tb(0),score_tb(0){};
//		nthTrace(int16_t st, int16_t tb):st_tb(st),score_tb(tb){};
//	};

	class nthTrace{
	public:
		std::map<int32_t,int32_t> tb;

		inline void assign(int16_t st, int16_t n_score, int16_t tb_ptr, int16_t tb_sc){
			tb[(((int32_t) st) << 16 | n_score)] = (((int32_t)tb_ptr) << 16) | tb_sc;
		}

		inline void get(int16_t& st, int16_t& n_score){
			int32_t key_val = (((int32_t) st) << 16 | n_score);
			if (tb.count(key_val)){
				st = -1;
			}
			int32_t val = tb[key_val];
			st	= (val >> 16) & 0xFFFF;
			n_score	= val & 0xFFFF;
		}
	};

	/*! \class Trellis
	 *	\brief Implements the HMM scoring trellis and algorithms
	 *
	 *
	 *
	 */
	class trellis{
	public:
		trellis();
		trellis(model* h , sequences* sqs);
		~trellis();
		void reset();
		inline model* getModel(){return hmm;}
		inline sequences* getSeq(){return seqs;}

		/*-----------   Decoding Algorithms ------------*/

		//TODO: Fix these functions so that they evaluate the model and choose a
		// a default algorithm based on the whether the model defines explicit duration
		// states

		void viterbi();
		void viterbi(model* h, sequences* sqs);

		void forward();
		void forward(model* h, sequences* sqs);

//		void forward_viterbi();
//		void forward_viterbi(model* h, sequences* sqs);

		void backward();
		void backward(model* h, sequences* sqs);

		void posterior();
		void posterior(model* h, sequences* sqs);

		void stochastic_viterbi();
		void stochastic_viterbi(model* h, sequences* sqs);

		void stochastic_forward();
		void stochastic_forward(model* h, sequences* sqs);

		void nth_viterbi();
		void nth_viterbi(model* h, sequences* sqs);

		void baum_welch();

		/*-----------	Naive Model Decoding Algorithms -------------*/
		/* These algorithms are the simply coded algorithms with little to no
		 optimizations.
		 */

		void naive_forward();
		void naive_forward(model* h, sequences* sqs);

		void naive_backward();
		void naive_backward(model* h, sequences* sqs);

		void naive_viterbi();
		void naive_viterbi(model* h, sequences* sqs);

		void naive_baum_welch();
		void naive_baum_welch(model* h, sequences* sqs);

		void naive_stochastic_viterbi();
		void naive_stochastic_viterbi(model* h, sequences* sqs);

		void naive_stochastic_forward();
		void naive_stochastic_forward(model* h, sequences* sqs);

		void naive_nth_viterbi(size_t n);
		void naive_nth_viterbi(model* h, sequences* sqs, size_t n);

		/*-----------   Simple Model Decoding Algorithms ------------*/
		/* These algorithms are for use with models that do not define explicit
			duration states or external functions.   Therefore, probabilities can
			be easily computed or referenced.

		 */

		void simple_viterbi();
		void simple_viterbi(model* h, sequences* sqs);

//		void simple_forward_viterbi();
//		void simple_forward_viterbi(model* h, sequences* sqs);

		void simple_forward();
		void simple_forward(model* h, sequences* sqs);

		void simple_backward();
		void simple_backward(model* h, sequences* sqs);

		void simple_posterior();
		void simple_posterior(model* h, sequences* sqs);

		void simple_stochastic_viterbi();
		void simple_stochastic_viterbi(model* h, sequences* sqs);
//		void simple_alt_stochastic_viterbi(model* h, sequences* sqs);
		void simple_simple_stochastic_viterbi(model* h, sequences* sqs);

		void simple_stochastic_forward();
		void simple_stochastic_forward(model* h, sequences* sqs);

		void simple_baum_welch();
		void simple_baum_welch(model* h, sequences* sqs);

		void simple_nth_viterbi(size_t n);
		void simple_nth_viterbi(model* h, sequences* sqs, size_t n);

		/*-----------   Fast Complex Model Decoding Algorithms  ----------*/
		/*	These algorithms are for use with models that define external functions
			or explicit duration states.

			These algorithms store the associated emissions and transitions
			probabilities that were calculated during viterbi algorith.  For later
			use in the forward/backward algorithms.

			The values are stored in dense arrays, so the memory is accessed faster
			at the cost of amount of memory required.
		 */

		void fast_complex_viterbi();
		void fast_complex_viterbi(model* h, sequences* sqs);
//
//		void fast_complex_forward_viterbi();
//		void fast_complex_forward_viterbi(model* h, sequences* sqs);

		void fast_complex_backward();
		void fast_complex_backward(model* h, sequences* sqs);

		void fast_complex_stochastic_viterbi();
		void fast_complex_stochastic_viterbi(model* h, sequences* sqs);

		void fast_complex_stochastic_forward();
		void fast_complex_stochastic_forward(model* h, sequences* sqs);

		void fast_complex_baum_welch();
		void fast_complex_baum_welch(model* h, sequences* sqs);

		/*-----------   Sparse Complex Model Decoding Algorithms  --------*/
		/*	These algorithms store the associated emissions and transitions
			probabilities that were calculated during viterbi algorithm.  For later
			use in the forward/backward algorithms.

			The values are stored in sparse tables (hash map), so access to values
			is slower but with lower amount of memory required.
		 */

		void sparse_complex_viterbi();
		void sparse_complex_viterbi(model* h, sequences* sqs);

//		void sparse_complex_foward_viterbi();
//		void sparse_complex_foward_viterbi(model* h, sequences* sqs);

		void sparse_complex_backward();
		void sparse_complex_backward(model* h, sequences* sqs);

		void sparse_complex_stochastic_forward();
		void sparse_complex_stochastic_forward(model* h, sequences* sqs);

		void sparse_complex_baum_welch();
		void sparse_complex_baum_welch(model* h, sequences* sqs);

		/*---------   Standard Traceback Algorithms --------*/

		void traceback(traceback_path& path);
        void traceback(traceback_path& path ,size_t position, size_t state);
		void traceback_nth(traceback_path& path, size_t n);
		void traceback_posterior(traceback_path& path);

		void traceback_stoch_posterior(traceback_path& path);
		void traceback_stoch_posterior(multiTraceback& paths , size_t reps);

		void traceback_nth_viterbi(multiTraceback&);

		void stochastic_traceback(traceback_path& path);
		void stochastic_traceback(multiTraceback&,size_t);

		inline bool store(){return store_values;}
		inline void store(bool val){store_values=val; return;}

		void print();
		std::string stringify();
		void export_trellis(std::ifstream&);
		void export_trellis(std::string& file);
		inline model* get_model(){return hmm;}

		//Model Baum-Welch Updating
		void update_transitions();
		void update_emissions();

		/*----------- Accessors ---------------*/
		inline double_2D* get_naive_forward_scores(){return dbl_forward_score;}
		inline double_2D* get_naive_backward_scores(){return dbl_backward_score;}
		inline double_2D* get_naive_viterbi_scores(){return dbl_viterbi_score;}
		inline double_2D* get_dbl_posterior(){return dbl_posterior_score;}

		inline float_2D* getForwardTable(){return forward_score;}
		inline float_2D* getBackwardTable(){return backward_score;}
		inline double_2D* getPosteriorTable(){return posterior_score;}

		inline double getForwardProbability(){return ending_forward_prob;}
		inline double getBackwardProbability(){return ending_backward_prob;}

	private:
		double getEndingTransition(size_t);
        double getTransition(state* st, size_t trans_to_state, size_t sequencePosition);
        size_t get_explicit_duration_length(transition* trans, size_t sequencePosition,size_t state_iter, size_t to_state);
        double transitionFuncTraceback(state* st, size_t position, transitionFuncParam* func);

		model* hmm;		//HMM model
        sequences* seqs; //Digitized Sequences
		size_t nth_size; //Size of N to calculate;

		size_t state_size;	//Number of States
		size_t seq_size;	//Length of Sequence

		trellisType type;

		bool store_values;
		bool exDef_defined;

		//Traceback Tables
		int_2D*		traceback_table;	//Simple traceback table
//		int_3D*		nth_traceback_table;//Nth-Viterbi traceback table
		stochTable* stochastic_table;
//		alt_stochTable* alt_stochastic_table;
		alt_simple_stochTable* alt_simple_stochastic_table;

		//Score Tables
		float_2D*	viterbi_score;      //Storing Viterbi scores
		float_2D*	forward_score;      //Storing Forward scores
		float_2D*	backward_score;     //Storing Backward scores
		double_2D*	posterior_score;	//Storing Posterior scores

		double_2D*  dbl_forward_score;
		double_2D*	dbl_viterbi_score;
		double_2D*  dbl_backward_score;
		double_2D*	dbl_posterior_score;
		double_3D*  dbl_baum_welch_score;
		std::vector<std::vector<std::vector<nthScore >* > >* naive_nth_scores;

		std::vector<nthTrace>*  nth_traceback_table;

		//Ending Cells
		double	ending_viterbi_score;
		int16_t	ending_viterbi_tb;
		double	ending_forward_prob;
		double	ending_backward_prob;
		std::vector<nthScore>* ending_nth_viterbi;

//		std::vector<tb_score>*    ending_stoch_tb;
//		std::vector<tb_score>*    ending_nth_viterbi;

		//Cells used for scoring each cell
		std::vector<double>* scoring_current;
		std::vector<double>* scoring_previous;
		std::vector<double>* alt_scoring_current;
		std::vector<double>* alt_scoring_previous;

		std::vector<size_t>* explicit_duration_current;
		std::vector<size_t>* explicit_duration_previous;
		std::vector<size_t>* swap_ptr_duration;

		std::vector<double>* swap_ptr;

		std::vector<std::vector<double>* > complex_emissions;
		std::vector<std::vector<std::map<uint16_t,double>* >* >* complex_transitions;

		std::vector<std::vector<nthScore> >* nth_scoring_current;
		std::vector<std::vector<nthScore> >* nth_scoring_previous;
		std::vector<std::vector<nthScore> >* nth_swap_ptr;
	};

	void sort_scores(std::vector<nthScore>& nth_scores);
	bool _vec_sort(const nthScore& i, const nthScore& j);

}

#endif /* defined(__StochHMM__new_trellis__) */


text:
.class final Lcom/android/server/firewall/NotFilter$1;
.super Lcom/android/server/firewall/FilterFactory;
.source "NotFilter.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/firewall/NotFilter;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = null
.end annotation

# direct methods
.method constructor <init>(Ljava/lang/String;)V
    .locals 0
    .parameter "x0"

    .prologue
    .line 41
    invoke-direct {p0, p1}, Lcom/android/server/firewall/FilterFactory;-><init>(Ljava/lang/String;)V

    return-void
.end method

# virtual methods
.method public newFilter(Lorg/xmlpull/v1/XmlPullParser;)Lcom/android/server/firewall/Filter;
    .locals 6
    .parameter "parser"
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;,
            Lorg/xmlpull/v1/XmlPullParserException;
        }
    .end annotation

    .prologue
    const/4 v5, 0x0

    .line 45
    const/4 v0, 0x0

    .line 46
    .local v0, child:Lcom/android/server/firewall/Filter;
    invoke-interface {p1}, Lorg/xmlpull/v1/XmlPullParser;->getDepth()I

    move-result v2

    .line 47
    .local v2, outerDepth:I
    :goto_0
    invoke-static {p1, v2}, Lcom/android/internal/util/XmlUtils;->nextElementWithin(Lorg/xmlpull/v1/XmlPullParser;I)Z

    move-result v3

    if-eqz v3, :cond_1

    .line 48
    invoke-static {p1}, Lcom/android/server/firewall/IntentFirewall;->parseFilter(Lorg/xmlpull/v1/XmlPullParser;)Lcom/android/server/firewall/Filter;

    move-result-object v1

    .line 49
    .local v1, filter:Lcom/android/server/firewall/Filter;
    if-nez v0, :cond_0

    .line 50
    move-object v0, v1

    goto :goto_0

    .line 52
    :cond_0
    new-instance v3, Lorg/xmlpull/v1/XmlPullParserException;

    const-string v4, "<not> tag can only contain a single child filter."

    invoke-direct {v3, v4, p1, v5}, Lorg/xmlpull/v1/XmlPullParserException;-><init>(Ljava/lang/String;Lorg/xmlpull/v1/XmlPullParser;Ljava/lang/Throwable;)V

    throw v3

    .line 56
    .end local v1           #filter:Lcom/android/server/firewall/Filter;
    :cond_1
    new-instance v3, Lcom/android/server/firewall/NotFilter;

    invoke-direct {v3, v0, v5}, Lcom/android/server/firewall/NotFilter;-><init>(Lcom/android/server/firewall/Filter;Lcom/android/server/firewall/NotFilter$1;)V

    return-object v3
.end method


text:
An Internet of Things button powered by an [Electric Imp](http://www.electricimp.com "Electric Imp").

![the Eureka button](https://raw.github.com/mezelve/eureka/gh-pages/media/eureka_04.jpg)

Each time I have a good idea, I'll press the Eureka button. A random precomposed tweet will be twittered by [@yoo_ree_kuh](http://www.twitter.com/yoo_ree_kuh) to capture this precious moment. At the same time a counter at [Xively](http://www.xively.com) gets updated, this data can/will be used later.

---

### Software
The Electric Imp system has 2 scripts. One that runs on the device itself and one that runs on a server in the cloud - called the agent. The first one is basicalty there to interact with the IO pins, the 2nd one can send and receive data from/to the Imp and interact with other webservices like Twitter and Xively.

#### Agent code
Here I've used the 2 classes for Twitter and Xively (MIT license) provided by Electric Imp.
- [Twitter Search](https://github.com/electricimp/reference/tree/master/webservices/twitter)
- [Xively Electric Imp Sample Code](https://github.com/electricimp/reference/tree/master/webservices/xively)

You'll also have to create an app for your Twitter account to be able to send tweets: [https://dev.twitter.com](https://dev.twitter.com)

#### Device code
The button is connected to pin 1, which is the wakeup pin. This means that the Eureka button is most of the time asleep and the batteries will last longer, but also that the Imp first needs to wakeup before it can send the timestamp to the agent.

---

### Hardware

#### Components
- an Electric Imp
- an April breakout board
- a push button - I've used a 60mm Arcade Button from Adafruit (the Led is attached to pin 9)
- a switch
- a batterypack or a LiPo battery
- a laser cut case
- screws, headers, hookup wire ...

I modified the Arcade button. I replaced the Led and its resistor (a 100ohm one).

![Fritzing](https://raw.github.com/mezelve/eureka/gh-pages/media/eureka.jpg)

![the main parts](https://raw.github.com/mezelve/eureka/gh-pages/media/eureka_02.jpg)

![almost assembled](https://raw.github.com/mezelve/eureka/gh-pages/media/eureka_03.jpg)

#### Case
I've order a laser cut 3mm plywood case at [Formulor](http://www.formulor.de). You can find the SVG files in the hardware/case folder. Make sure to check the dimensions of your switch and its mounting holes.

![the laser cut parts](https://raw.github.com/mezelve/eureka/gh-pages/media/eureka_01.jpg)


text:
This site is targeted for use by members of the University of California and DataONE communities. Researchers in any field from participating UC campuses (with exception, see Davis below) can use their campus credentials to deposit data in their campus-specific website. Anyone in the world can search, view, and download datasets. The following nine institutions currently participate in publishing data in Dash:

- [UC Berkeley](https://dash.berkeley.edu/)
- [UC Irvine](https://dash.lib.uci.edu/)
- [UC Merced](https://dash.ucmerced.edu/)
- [UC Office of the President](https://dash.ucop.edu/)
- [UC Riverside](https://dash.ucr.edu/)
- [UC Santa Cruz](https://dash.library.ucsc.edu/)
- [UC San Francisco](https://datashare.ucsf.edu/)
- DataONE ONEShare (https://oneshare.cdlib.org/)

## What type of data is within scope?

All types of research data. However, this service is
intended for complete, re-usable, open research datasets and all content must not violate
privacy or copyright, or breach confidentiality or nondisclosure for data
collected from human subjects.

## What are the size limits?

There is a limit of 100gb per data publication. All data files are
stored and preserved in the Merritt Repository. More information about the Merritt
Repository Service is available in the white paper
"[UC3, Merritt and Long-term Preservation](https://merritt.cdlib.org/d/ark%3A%2F13030%2Fm52f7p63/2/producer%2FUC3-Merritt-preservation-latest.pdf)."

## Does the data have to be associated with a publication?

No. We encourage and accept all quality data, regardless of whether they have been
used to publish a paper to be deposited, shared, and preserved.

## How are the datasets discoverable?

All datasets will be indexed by the
[Thomson-Reuters Data Citation Index](http://wokinfo.com/products_tools/multidisciplinary/dci/about/)
and [Scopus](http://www.elsevier.com/online-tools/scopus). Furthermore, each dataset
is given a unique Digital Object Identifier or DOI. Entering the
DOI URL in any browser will take the user to the dataset's landing page in
Merritt. This service also provides a faceted search and browse capability for
direct discovery.

## Who can access and use datasets in Dash?

Every dataset landing page includes usage information associated with the
dataset. Data may be associated with any of the following licensing
terms:

1. Custom Data Use Agreement.
2. [Creative Commons Attribution 4.0 License](https://creativecommons.org/licenses/by/4.0/)
   (CC-BY-4.0). According to the terms of the CC-BY license, reuse of the
   data must include appropriate credit and must indicate if changes were
   made.
3. [Creative Commons Public Domain Dedication Waiver](https://creativecommons.org/publicdomain/zero/1.0/legalcode)
   (CC0). This waiver has no restrictions on use and encourages reuse of
   data for any and all purposes.

All new data intended for ONEshare must be submitted under the terms of
the CC0 waiver; data intended for any of the UC campus instances must be
submitted under the terms of the CC-BY license.

Note: data contributed before standardization to these two licensing
regimes retain their original licensing terms.

Although many researchers would prefer to maintain more control over who
downloads and uses their data, we believe that fully open data best
supports the advancement of knowledge. Read the
[Panton Principles for Open Data in Science](http://pantonprinciples.org/)
for more information.

## What feature do you offer to make my dataset have the broadest reach?

Comprehensive documentation (i.e. metadata) is the key for dicoverability as well as ensuring future researchers understand the data. Without thorough metadata (description of the context of the data file, the context in which
the data were collected, the measurements that were made, and the quality
of the data), the data cannot be found through internet searches or data
indexing services, understood by fellow researchers, or effectively used.

We require a few key pieces of metadata. Additional information can be
included in the "Usage Notes" section of the description, or as a separate
readme.txt file archived alongside the dataset files. The metadata entry
form is based on fields from the
[DataCite schema](http://schema.datacite.org/meta/kernel-3/index.html) and is broadly applicable to data from any field.

## For how long will the data be available?

Data deposited are permanently archived and available through the
[California Digital Library](http://cdlib.org/)'s
[Merritt Repository](https://merritt.cdlib.org/). For a full description
of the services provided by Merritt, see this document:
[UC3, Merritt, and Long-term preservation](https://merritt.cdlib.org/d/ark%3A%2F13030%2Fm52f7p63/2/producer%2FUC3-Merritt-preservation-latest.pdf).

Preservation policy details include:

- **Retention period**: Items will be retained indefinitely, at the
  discretion of the participating campus library and/or UC3.
- **Functional preservation:** We make no promises of usability and
  understandability of deposited objects over time.
- **File preservation**: Data files are replicated with multiple copies in
  multiple geographic locations; metadata are backed up on a nightly
  basis.
- **Fixity and authenticity**: All data files are stored along with a
  SHA-256 checksum of the file content. Regular checks of files against
  their checksums are made. The audit process cycles continually, with a
  current cycle time of approximately two months.
- **Succession plans**: In case of closure of the repository, reasonable
  efforts will be made to integrate all content into suitable alternative
  institutional and/or subject based repositories.

## Can I delete my data?

Data deposited is intended to remain permanently archived and
available. Deletion of a deposited dataset is considered an exceptional
action which normally should be requested and fully justified by the
original contributor (e.g., if sensitive human subject data was not
properly de-identified). If your data must be deleted, contact
[uc3@ucop.edu](mailto:uc3@ucop.edu).


text:
// jQuery Alert Dialogs Plugin
//
// Version 1.1
//
// Cory S.N. LaViska
// A Beautiful Site (http://abeautifulsite.net/)
// 14 May 2009
//
// Visit http://abeautifulsite.net/notebook/87 for more information
//
// Usage:
//		jAlert( message, [title, callback] )
//		jConfirm( message, [title, callback] )
//		jPrompt( message, [value, title, callback] )
//
// History:
//
//		1.00 - Released (29 December 2008)
//
//		1.01 - Fixed bug where unbinding would destroy all resize events
//
// License:
//
// This plugin is dual-licensed under the GNU General Public License and the MIT License and
// is copyright 2008 A Beautiful Site, LLC.
//
(function($) {

	$.alerts = {

		// These properties can be read/written by accessing $.alerts.propertyName from your scripts at any time

		verticalOffset: -75,                // vertical offset of the dialog from center screen, in pixels
		horizontalOffset: 0,                // horizontal offset of the dialog from center screen, in pixels/
		repositionOnResize: true,           // re-centers the dialog on window resize
		overlayOpacity: .01,                // transparency level of overlay
		overlayColor: '#FFF',               // base color of overlay
		draggable: true,                    // make the dialogs draggable (requires UI Draggables plugin)
		okButton: ' Yes ',         // text for the OK button
		cancelButton: ' No ', // text for the Cancel button
		dialogClass: null,                  // if specified, this class will be applied to all dialogs

		// Public methods

		alert: function(message, title, callback) {
			if( title == null ) title = 'Alert';
			$.alerts._show(title, message, null, 'alert', function(result) {
				if( callback ) callback(result);
			});
		},

		confirm: function(message, title, callback) {
			if( title == null ) title = 'Confirm';
			$.alerts._show(title, message, null, 'confirm', function(result) {
				if( callback ) callback(result);
			});
		},

		prompt: function(message, value, title, callback) {
			if( title == null ) title = 'Prompt';
			$.alerts._show(title, message, value, 'prompt', function(result) {
				if( callback ) callback(result);
			});
		},

		// Private methods

		_show: function(title, msg, value, type, callback) {

			$.alerts._hide();
			$.alerts._overlay('show');

			$("BODY").append(
			  '
' +
			    '

' +
			    '
' +
			      '

' +
				'
' +
			  '
');

			if( $.alerts.dialogClass ) $("#popup_container").addClass($.alerts.dialogClass);

			// IE6 Fix
			var pos = ($.browser.msie && parseInt($.browser.version) <= 6 ) ? 'absolute' : 'fixed';

			$("#popup_container").css({
				position: pos,
				zIndex: 99999,
				padding: 0,
				margin: 0
			});

			$("#popup_title").text(title);
			$("#popup_content").addClass(type);
			$("#popup_message").text(msg);
			$("#popup_message").html( $("#popup_message").text().replace(/\n/g, '
') );

			$("#popup_container").css({
				minWidth: $("#popup_container").outerWidth(),
				maxWidth: $("#popup_container").outerWidth()
			});

			$.alerts._reposition();
			$.alerts._maintainPosition(true);

			switch( type ) {
				case 'alert':
					$("#popup_content").after('
<input type="button" value="' + $.alerts.okButton + '" id="popup_ok" />
');
					$("#popup_ok").click( function() {
						$.alerts._hide();
						callback(true);
					});
					$("#popup_ok").focus().keypress( function(e) {
						if( e.keyCode == 13 || e.keyCode == 27 ) $("#popup_ok").trigger('click');
					});
				break;
				case 'confirm':
					$("#popup_content").after('
<input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" />
');
					$("#popup_ok").click( function() {
						$.alerts._hide();
						if( callback ) callback(true);
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback(false);
					});
					$("#popup_ok").focus();
					$("#popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
				break;
				case 'prompt':
					$("#popup_message").append(' <input type="text" size="30" id="popup_prompt" />')
					$("#popup_content").after('
<input type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" />
');
					$("#popup_ok").click( function() {
						var val = $("#popup_prompt").val();
						$.alerts._hide();
						if( callback ) callback( val );
					});
					$("#popup_cancel").click( function() {
						$.alerts._hide();
						if( callback ) callback( null );
					});
					$("#popup_prompt, #popup_ok, #popup_cancel").keypress( function(e) {
						if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
						if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
					});
					if( value ) $("#popup_prompt").val(value);
					$("#popup_prompt").focus().select();
				break;
			}

			// Make draggable
			if( $.alerts.draggable ) {
				try {
					$("#popup_container").draggable({ handle: $("#popup_title") });
					$("#popup_title").css({ cursor: 'move' });
				} catch(e) { /* requires jQuery UI draggables */ }
			}
		},

		_hide: function() {
			$("#popup_container").remove();
			$.alerts._overlay('hide');
			$.alerts._maintainPosition(false);
		},

		_overlay: function(status) {
			switch( status ) {
				case 'show':
					$.alerts._overlay('hide');
					$("BODY").append('

');
					$("#popup_overlay").css({
						position: 'absolute',
						zIndex: 99998,
						top: '0px',
						left: '0px',
						width: '100%',
						height: $(document).height(),
						background: $.alerts.overlayColor,
						opacity: $.alerts.overlayOpacity
					});
				break;
				case 'hide':
					$("#popup_overlay").remove();
				break;
			}
		},

		_reposition: function() {
			var top = (($(window).height() / 2) - ($("#popup_container").outerHeight() / 2)) + $.alerts.verticalOffset;
			var left = (($(window).width() / 2) - ($("#popup_container").outerWidth() / 2)) + $.alerts.horizontalOffset;
			if( top < 0 ) top = 0;
			if( left < 0 ) left = 0;

			// IE6 fix
			if( $.browser.msie && parseInt($.browser.version) <= 6 ) top = top + $(window).scrollTop();

			$("#popup_container").css({
				top: top + 'px',
				left: left + 'px'
			});
			$("#popup_overlay").height( $(document).height() );
		},

		_maintainPosition: function(status) {
			if( $.alerts.repositionOnResize ) {
				switch(status) {
					case true:
						$(window).bind('resize', $.alerts._reposition);
					break;
					case false:
						$(window).unbind('resize', $.alerts._reposition);
					break;
				}
			}
		}

	}

	// Shortuct functions
	jAlert = function(message, title, callback) {
		$.alerts.alert(message, title, callback);
	}

	jConfirm = function(message, title, callback) {
		$.alerts.confirm(message, title, callback);
	};

	jPrompt = function(message, value, title, callback) {
		$.alerts.prompt(message, value, title, callback);
	};

})(jQuery);


text:
package com.compositesw.services.system.admin.archive;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for domainUserPair complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="domainUserPair">
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element name="domainName" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *         <element name="userName" type="{http://www.w3.org/2001/XMLSchema}string"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "domainUserPair", propOrder = {
    "domainName",
    "userName"
})
public class DomainUserPair {

    @XmlElement(required = true)
    protected String domainName;
    @XmlElement(required = true)
    protected String userName;

    /**
     * Gets the value of the domainName property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getDomainName() {
        return domainName;
    }

    /**
     * Sets the value of the domainName property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setDomainName(String value) {
        this.domainName = value;
    }

    /**
     * Gets the value of the userName property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getUserName() {
        return userName;
    }

    /**
     * Sets the value of the userName property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setUserName(String value) {
        this.userName = value;
    }

}


text:
package uk.gov.hmrc.ct.ct600e.v3

import org.mockito.Mockito._
import org.scalatestplus.mockito.MockitoSugar
import org.scalatest.{BeforeAndAfter, Matchers, WordSpec}
import uk.gov.hmrc.cato.time.DateHelper
import uk.gov.hmrc.ct.box.CtValidation
import uk.gov.hmrc.ct.ct600e.v3.retriever.CT600EBoxRetriever
import uk.gov.hmrc.ct.domain.ValidationConstants._

class E40Spec extends WordSpec with MockitoSugar with Matchers with BeforeAndAfter{

  val boxRetriever = mock[CT600EBoxRetriever]
  val NOW = DateHelper.now()
  val APEnd = NOW.minusMonths(1)

  before{
    when(boxRetriever.e4()).thenReturn(E4(APEnd))
  }

  "E40" should {
    "validate" when {
      "false when is empty" in {
        E40(None).validate(boxRetriever) shouldBe Set(CtValidation(boxId = Some("E40"), errorMessageKey = "error.E40.required"))
      }

      val INVALID_DATE_ERROR_MESSAGE: Set[CtValidation] = Set(CtValidation(Some("E40"), s"error.E40.not.betweenInclusive", Some(Seq(toErrorArgsFormat(APEnd), toErrorArgsFormat(NOW)))))

      "false when date before AP end date" in {
        E40(Some(APEnd.minusDays(1))).validate(boxRetriever) shouldBe INVALID_DATE_ERROR_MESSAGE
      }
      "false when date after current date" in {
        E40(Some(NOW.plusDays(1))).validate(boxRetriever) shouldBe INVALID_DATE_ERROR_MESSAGE
      }
      "true when date is current date" in {
        E40(Some(NOW)).validate(boxRetriever) shouldBe Set()
      }
      "true when date is AP end date" in {
        E40(Some(APEnd)).validate(boxRetriever) shouldBe Set()
      }
      "true when date is between now and AP end date" in {
        E40(Some(APEnd.plusDays(1))).validate(boxRetriever) shouldBe Set()
      }
    }
  }

}


text:
/**
 * Authors Stefan Brandle and Jonathan Geisler
 * Date    November, 2004
 * Declaration source file for BoardV2.
 * Please type in your name[s] below:
 *
 *
 */

#ifndef BOARDV2_H
#define BOARDV2_H

using namespace std;

class BoardV2 {
    public:
	// Constructors and such
	BoardV2( int width);
	BoardV2(const BoardV2& other);
	void operator=(const BoardV2& other);
	// General public access functions.
	bool placeShip(int length);
    	char getOpponentView(int row, int col);
    	char getOwnerView(int row, int col);
    	char processShot(int row, int col);
    	bool hasWon();

        const static int MaxBoardSize = 10;     // Maximum board size.

    private:
	// Put prototypes for your private helper functions here.
	void initialize(char board[MaxBoardSize][MaxBoardSize]);
        void chooseValues(int& row, int& col, int& length, bool& horiz);
	bool positionOk(int row, int col, int length, bool horiz);
	void markShip(int row, int col, int length, bool horiz);
        bool isSunk(int row, int col);
        void markSunk(int row, int col);

	// Suggested data variables. Although you can ignore these, it
	// is suggested that you use them. If you change the array definitions,
	// you may have to change some of the prototypes or code that
	// you are given as part of your starter kit.
	char shipBoard[MaxBoardSize][MaxBoardSize];    // Tracks the placed ships and shots
	char shotBoard[MaxBoardSize][MaxBoardSize];    // Tracks where ships are through whole game
	int boardSize;		    // Tracks how many rows/cols are actually being used.

	// Put your private data variables here.
	char shipMark;		    // Used to mark the ships on shipBoard
    int ship3;
    int ship4;
    int ship5;
};

#endif	// End of multiple inclusion control.