text:
package quasar.physical.marklogic.fs

import slamdata.Predef._
import quasar.{Planner => QPlanner}
import quasar.contrib.pathy._
import quasar.contrib.scalaz._
import quasar.effect.uuid._
import quasar.fp.numeric._
import quasar.fs.{FileSystemError, MonadFsErr}
import quasar.physical.marklogic.ErrorMessages
import quasar.physical.marklogic.qscript._
import quasar.physical.marklogic.xquery._
import quasar.physical.marklogic.xquery.syntax._
import quasar.physical.marklogic.xcc._

import com.marklogic.xcc.types.{XdmItem, XSString}
import eu.timepit.refined.auto._
import pathy.Path._
import scalaz._, Scalaz._
import scalaz.stream.Process

object ops {
  import expr.{func, let_}

  /** Appends the given contents to the file, which must already exist. */
  def appendToFile[F[_]: Monad: Xcc: UuidReader: PrologW: PrologL, FMT: SearchOptions, A](
    file: AFile,
    contents: A
  )(implicit
    C:  AsContent[FMT, A],
    SP: StructuralPlanner[F, FMT]
  ): F[ErrorMessages \/ Vector[XccError]] = {
    def appendQuery(src: AFile): F[MainModule] =
      main10ml {
        SP.leftShift(fileRoot[FMT](src))
          .flatMap(lib.appendChildNodes[F, FMT].apply(fileRoot[FMT](file), _))
      }

    val tmpFile = UuidReader[F] asks { uuid =>
      renameFile(file, fn => FileName(s"${fn.value}-$uuid"))
    }

    Xcc[F].transact(for {
      tmp  <- tmpFile
      errs <- insertFile[F, FMT, A](tmp, contents)
      main <- appendQuery(tmp)
      _    <- Xcc[F].execute(main)
      _    <- deleteFile(tmp)
    } yield errs)
  }

  /** Deletes the given directory and all descendants, recursively. */
  def deleteDir[F[_]: Xcc: Applicative, FMT: SearchOptions](dir: ADir): F[Executed] = {
    val file = $("file")

    Xcc[F].executeQuery(fn.map(
      func(file.render) { xdmp.documentDelete(fn.baseUri(~file)) },
      directoryDocuments[FMT](pathUri(dir).xs, true)))
  }

  /** Deletes the given file, erroring if it doesn't exist. */
  def deleteFile[F[_]: Xcc](file: AFile): F[Executed] =
    Xcc[F].executeQuery(xdmp.documentDelete(pathUri(file).xs))

  /** Returns whether any file descendants of the given dir have the specified format. */
  def descendantsHavingFormatExist[F[_]: Xcc: Functor, FMT: SearchOptions](dir: ADir): F[Boolean] = {
    val main = main10ml(lib.descendantsHavingFormatExist[W, FMT] apply pathUri(dir).xs)
    Xcc[F].results(main.value) map booleanResult
  }

  /** The set of child directories and files of the given directory. */
  def directoryContents[F[_]: Bind: Xcc, FMT: SearchOptions](dir: ADir): F[Set[PathSegment]] = {
    def parseDir(s: String): Option[PathSegment] =
      UriPathCodec.parseRelDir(s) flatMap dirName map (_.left)

    def parseFile(s: String): Option[PathSegment] =
      UriPathCodec.parseRelFile(s) map (f => fileName(f).right)

    val nextUri =
      uriLexiconEnabled[F] map (_.fold(
        lib.descendantUriFromLexicon[W].fn,
        lib.descendantUriFromDocQuery[W].fn))

    val asSegments: XdmItem => Set[PathSegment] = {
      case item: XSString =>
        val str = item.asString
        (parseDir(str) orElse parseFile(str)).toSet

      case _ => Set()
    }

    Xcc[F].transact(for {
      f     <- nextUri
      mm    =  main10ml((f >>= lib.directoryContents[W, FMT])(pathUri(dir).xs))
      items <- Xcc[F].results(mm.value)
      segs  =  items foldMap asSegments
    } yield segs)
  }

  /** Returns whether the file exists, regardless of format. */
  def fileExists[F[_]: Functor: Xcc](file: AFile): F[Boolean] =
    Xcc[F].queryResults(fn.docAvailable(pathUri(file).xs)) map booleanResult

  /** Returns whether the file having the given format exists. */
  def fileHavingFormatExists[F[_]: Functor: Xcc, FMT: SearchOptions](file: AFile): F[Boolean] =
    Xcc[F].queryResults(fn.exists(fileNode[FMT](file))) map booleanResult

  /** Insert the given contents into the file, overwriting any existing contents
    * and creating the file otherwise. Returns any errors encountered, either
    * with the contents or during the process of insertion itself.
    */
  def insertFile[F[_]: Monad: Xcc, FMT, A](
    file: AFile,
    contents: A
  )(implicit
    C: AsContent[FMT, A]
  ): F[ErrorMessages \/ Vector[XccError]] = {
    val uri         = pathUri(file)
    val contentUri  = ContentUri.getOption(uri) \/> s"Malformed content URI: $uri".wrapNel
    val content     = contentUri >>= (C.asContent[ErrorMessages \/ ?](_, contents))

    EitherT.fromDisjunction[F](content)
      .flatMapF(c => Xcc[F].insert[Id](c) map (_.right[ErrorMessages]))
      .run
  }

  /** Move `src` to `dst` overwriting any existing contents. */
  def moveDir[F[_]: Monad: Xcc, FMT: SearchOptions](src: ADir, dst: ADir): F[Executed] = {
    val (file, srcUri, dstUri) = ($("file"), $("srcUri"), $("dstUri"))

    val doMoveDir = lib.moveFile[W, FMT].fn map { moveF =>
      fn.map(
        func(file.render) {
          let_(
            srcUri := fn.baseUri(~file),
            dstUri := fn.concat(
                        pathUri(dst).xs,
                        fn.substringAfter(~srcUri, pathUri(src).xs)))
          .return_(moveF(~srcUri, ~dstUri))
        },
        directoryDocuments[FMT](pathUri(src).xs, true))
    }

    (src =/= dst) whenM Xcc[F].execute(main10ml(doMoveDir).value) as Executed.executed
  }

  /** Move `src` to `dst` overwriting any existing contents. */
  def moveFile[F[_]: Monad: Xcc, FMT: SearchOptions](src: AFile, dst: AFile): F[Executed] = {
    val main = main10ml(lib.moveFile[W, FMT] apply (pathUri(src).xs, pathUri(dst).xs))
    (src =/= dst) whenM Xcc[F].execute(main.value) as Executed.executed
  }

  /** Returns whether the given path exists having the specified format. */
  def pathHavingFormatExists[F[_]: Functor: Xcc, FMT: SearchOptions](path: APath): F[Boolean] =
    refineType(path).fold(descendantsHavingFormatExist[F, FMT], fileHavingFormatExists[F, FMT])

  /** Attempts to pretty print the given expression. */
  def prettyPrint[F[_]: Monad: MonadFsErr: Xcc](xqy: XQuery): F[Option[XQuery]] = {
    val prettyPrinted =
      Xcc[F].queryResults(xdmp.prettyPrint(XQuery(s"'$xqy'")))
        .map(_.headOption collect { case s: XSString => XQuery(s.asString) })

    Xcc[F].handleWith(prettyPrinted) {
      case err @ XccError.QueryError(_, cause) =>
        MonadFsErr[F].raiseError(
          FileSystemError.qscriptPlanningFailed(QPlanner.InternalError(
            err.shows, Some(cause))))

      // NB: As this is only for pretty printing, if we fail for some other reason
      //     just return an empty result.
      case _ => none[XQuery].point[F]
    }
  }

  /** Stream of the left-shifted contents of the given file. */
  def readFile[F[_]: Monad: Xcc: PrologL, FMT: SearchOptions](
    file: AFile,
    offset: Natural,
    limit: Option[Positive]
  )(implicit
    SP: StructuralPlanner[F, FMT]
  ): Process[F, XdmItem] = {
    val query = SP.leftShift(fileRoot[FMT](file)) map { items =>
      (offset.value + 1, limit.map(_.value.xqy)) match {
        case (1, None) => items
        case (o, l)    => fn.subsequence(items, o.xqy, l)
      }
    }

    main10ml(query).liftM[Process].flatMap(Xcc[F].evaluate)
  }

  /** Appends contents to an existing file, creating it otherwise. */
  def upsertFile[F[_]: Monad: Xcc: UuidReader: PrologW: PrologL, FMT: SearchOptions, A](
    file: AFile,
    contents: A
  )(implicit
    C:  AsContent[FMT, A],
    SP: StructuralPlanner[F, FMT]
  ): F[ErrorMessages \/ Vector[XccError]] =
    fileExists[F](file).ifM(
      appendToFile[F, FMT, A](file, contents),
      insertFile[F, FMT, A](file, contents))

  /** Returns whether the URI lexicon is enabled. */
  def uriLexiconEnabled[F[_]: Functor: Xcc]: F[Boolean] = {
    val main = main10ml {
      admin.getConfiguration[W] >>= (admin.databaseGetUriLexicon[W](_, xdmp.database()))
    }

    Xcc[F].results(main.value) map booleanResult
  }

  ////

  private type W[A] = Writer[Prologs, A]

  private def main10ml[F[_]: Functor: PrologL](query: F[XQuery]): F[MainModule] =
    MainModule fromWritten (query strengthL Version.`1.0-ml`)
}


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

namespace APIMonLib.Hooks.ws2_32.dll
{
    public class Hook_listen : AbstractHookDescription
    {
        //public override APIFullName api_full_name { get { return new APIFullName("ws2_32.dll", "listen"); } }

        protected override Delegate createHookDelegate()
        {
            return new WS2_32Support.Dlisten(listen_Hooked);
        }

        // this is where we are intercepting all file accesses!
        public int listen_Hooked(IntPtr socket, int backlog)
        {
            preprocessHook();

            // call original API...
            int result = WS2_32Support.listen(socket, backlog);
			TransferUnit transfer_unit = createTransferUnit();
			transfer_unit[Color.Handle] = socket.ToInt32();

			if (result != WS2_32Support.SOCKET_ERROR) makeCallBack(transfer_unit);

            return result;
        }

		public struct Color {
			public const string Handle = "SocketHandle";
		}
    }
}

redpajama_set_name: RedPajamaGithub


text:
@class MRMover;

@protocol MRMoverDelegate <NSObject>
- (void)moverExited:(MRMover*)mover;
@end

@interface MRMover : NSObject

@property (nonatomic, assign) id<MRMoverDelegate> delegate;
@property (nonatomic, strong) SKNode *node;
@property (nonatomic, assign) MRPoint startPoint;
@property (nonatomic, assign) MRPoint endPoint;
@property (nonatomic, assign) MRPoint worldPoint;
@property (nonatomic, assign) MRPoint velocity;
@property (nonatomic, assign) CGFloat transitTime;
@property (nonatomic, readonly) BOOL hasVelocity;

- (id)initWithNode:(SKNode*)node;
- (BOOL)update;

@end


text:
package org.lwjgl.system.windows;

import java.nio.*;

import org.lwjgl.*;
import org.lwjgl.system.*;

import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.MemoryUtil.*;
import static org.lwjgl.system.MemoryStack.*;

/**
 * Contains the security descriptor for an object and specifies whether the handle retrieved by specifying this structure is inheritable. This structure
 * provides security settings for objects created by various functions, such as {@code CreateFile}, {@code CreatePipe}, {@code CreateProcess},
 * {@code RegCreateKeyEx}, or {@code RegSaveKeyEx}.
 *
 *
Member documentation

 *
 *

 *
{@code nLength} – the size, in bytes, of this structure. Set this value to {@link #SIZEOF}.

 *
{@code lpSecurityDescriptor} –
 * a pointer to a {@code SECURITY_DESCRIPTOR} structure that controls access to the object. If the value of this member is {@code NULL}, the object is assigned
 * the default security descriptor associated with the access token of the calling process. This is not the same as granting access to everyone by
 * assigning a {@code NULL} discretionary access control list (DACL). By default, the default DACL in the access token of a process allows access only to the
 * user represented by the access token.

 *
{@code bInheritHandle} – specifies whether the returned handle is inherited when a new process is created. If this member is {@code TRUE}, the new process inherits the handle.

 *

 *
 *
Layout

 *
 *
struct SECURITY_ATTRIBUTES {
    DWORD nLength;
    LPVOID lpSecurityDescriptor;
    BOOL bInheritHandle;
}

 */
public class SECURITY_ATTRIBUTES extends Struct implements NativeResource {

	/** The struct size in bytes. */
	public static final int SIZEOF;

	public static final int ALIGNOF;

	/** The struct member offsets. */
	public static final int
		NLENGTH,
		LPSECURITYDESCRIPTOR,
		BINHERITHANDLE;

	static {
		Layout layout = __struct(
			__member(4),
			__member(POINTER_SIZE),
			__member(4)
		);

		SIZEOF = layout.getSize();
		ALIGNOF = layout.getAlignment();

		NLENGTH = layout.offsetof(0);
		LPSECURITYDESCRIPTOR = layout.offsetof(1);
		BINHERITHANDLE = layout.offsetof(2);
	}

	SECURITY_ATTRIBUTES(long address, ByteBuffer container) {
		super(address, container);
	}

	/**
	 * Creates a {@link SECURITY_ATTRIBUTES} instance at the current position of the specified {@link ByteBuffer} container. Changes to the buffer's content will be
	 * visible to the struct instance and vice versa.
	 *
	 *
The created instance holds a strong reference to the container object.

	 */
	public SECURITY_ATTRIBUTES(ByteBuffer container) {
		this(memAddress(container), checkContainer(container, SIZEOF));
	}

	@Override
	public int sizeof() { return SIZEOF; }

	/** Returns the value of the {@code nLength} field. */
	public int nLength() { return nnLength(address()); }
	/** Returns the value of the {@code lpSecurityDescriptor} field. */
	public long lpSecurityDescriptor() { return nlpSecurityDescriptor(address()); }
	/** Returns the value of the {@code bInheritHandle} field. */
	public boolean bInheritHandle() { return nbInheritHandle(address()) != 0; }

	/** Sets the specified value to the {@code nLength} field. */
	public SECURITY_ATTRIBUTES nLength(int value) { nnLength(address(), value); return this; }
	/** Sets the specified value to the {@code lpSecurityDescriptor} field. */
	public SECURITY_ATTRIBUTES lpSecurityDescriptor(long value) { nlpSecurityDescriptor(address(), value); return this; }
	/** Sets the specified value to the {@code bInheritHandle} field. */
	public SECURITY_ATTRIBUTES bInheritHandle(boolean value) { nbInheritHandle(address(), value ? 1 : 0); return this; }

	/** Initializes this struct with the specified values. */
	public SECURITY_ATTRIBUTES set(
		int nLength,
		long lpSecurityDescriptor,
		boolean bInheritHandle
	) {
		nLength(nLength);
		lpSecurityDescriptor(lpSecurityDescriptor);
		bInheritHandle(bInheritHandle);

		return this;
	}

	/** Unsafe version of {@link #set(SECURITY_ATTRIBUTES) set}. */
	public SECURITY_ATTRIBUTES nset(long struct) {
		memCopy(struct, address(), SIZEOF);
		return this;
	}

	/**
	 * Copies the specified struct data to this struct.
	 *
	 * @param src the source struct
	 *
	 * @return this struct
	 */
	public SECURITY_ATTRIBUTES set(SECURITY_ATTRIBUTES src) {
		return nset(src.address());
	}

	// -----------------------------------

	/** Returns a new {@link SECURITY_ATTRIBUTES} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed. */
	public static SECURITY_ATTRIBUTES malloc() {
		return create(nmemAlloc(SIZEOF));
	}

	/** Returns a new {@link SECURITY_ATTRIBUTES} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed. */
	public static SECURITY_ATTRIBUTES calloc() {
		return create(nmemCalloc(1, SIZEOF));
	}

	/** Returns a new {@link SECURITY_ATTRIBUTES} instance allocated with {@link BufferUtils}. */
	public static SECURITY_ATTRIBUTES create() {
		return new SECURITY_ATTRIBUTES(BufferUtils.createByteBuffer(SIZEOF));
	}

	/** Returns a new {@link SECURITY_ATTRIBUTES} instance for the specified memory address or {@code null} if the address is {@code NULL}. */
	public static SECURITY_ATTRIBUTES create(long address) {
		return address == NULL ? null : new SECURITY_ATTRIBUTES(address, null);
	}

	/**
	 * Returns a new {@link SECURITY_ATTRIBUTES.Buffer} instance allocated with {@link MemoryUtil#memAlloc memAlloc}. The instance must be explicitly freed.
	 *
	 * @param capacity the buffer capacity
	 */
	public static Buffer malloc(int capacity) {
		return create(nmemAlloc(capacity * SIZEOF), capacity);
	}

	/**
	 * Returns a new {@link SECURITY_ATTRIBUTES.Buffer} instance allocated with {@link MemoryUtil#memCalloc memCalloc}. The instance must be explicitly freed.
	 *
	 * @param capacity the buffer capacity
	 */
	public static Buffer calloc(int capacity) {
		return create(nmemCalloc(capacity, SIZEOF), capacity);
	}

	/**
	 * Returns a new {@link SECURITY_ATTRIBUTES.Buffer} instance allocated with {@link BufferUtils}.
	 *
	 * @param capacity the buffer capacity
	 */
	public static Buffer create(int capacity) {
		return new Buffer(BufferUtils.createByteBuffer(capacity * SIZEOF));
	}

	/**
	 * Create a {@link SECURITY_ATTRIBUTES.Buffer} instance at the specified memory.
	 *
	 * @param address  the memory address
	 * @param capacity the buffer capacity
	 */
	public static Buffer create(long address, int capacity) {
		return address == NULL ? null : new Buffer(address, null, -1, 0, capacity, capacity);
	}

	// -----------------------------------

	/** Returns a new {@link SECURITY_ATTRIBUTES} instance allocated on the thread-local {@link MemoryStack}. */
	public static SECURITY_ATTRIBUTES mallocStack() {
		return mallocStack(stackGet());
	}

	/** Returns a new {@link SECURITY_ATTRIBUTES} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero. */
	public static SECURITY_ATTRIBUTES callocStack() {
		return callocStack(stackGet());
	}

	/**
	 * Returns a new {@link SECURITY_ATTRIBUTES} instance allocated on the specified {@link MemoryStack}.
	 *
	 * @param stack the stack from which to allocate
	 */
	public static SECURITY_ATTRIBUTES mallocStack(MemoryStack stack) {
		return create(stack.nmalloc(ALIGNOF, SIZEOF));
	}

	/**
	 * Returns a new {@link SECURITY_ATTRIBUTES} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
	 *
	 * @param stack the stack from which to allocate
	 */
	public static SECURITY_ATTRIBUTES callocStack(MemoryStack stack) {
		return create(stack.ncalloc(ALIGNOF, 1, SIZEOF));
	}

	/**
	 * Returns a new {@link SECURITY_ATTRIBUTES.Buffer} instance allocated on the thread-local {@link MemoryStack}.
	 *
	 * @param capacity the buffer capacity
	 */
	public static Buffer mallocStack(int capacity) {
		return mallocStack(capacity, stackGet());
	}

	/**
	 * Returns a new {@link SECURITY_ATTRIBUTES.Buffer} instance allocated on the thread-local {@link MemoryStack} and initializes all its bits to zero.
	 *
	 * @param capacity the buffer capacity
	 */
	public static Buffer callocStack(int capacity) {
		return callocStack(capacity, stackGet());
	}

	/**
	 * Returns a new {@link SECURITY_ATTRIBUTES.Buffer} instance allocated on the specified {@link MemoryStack}.
	 *
	 * @param stack the stack from which to allocate
	 * @param capacity the buffer capacity
	 */
	public static Buffer mallocStack(int capacity, MemoryStack stack) {
		return create(stack.nmalloc(ALIGNOF, capacity * SIZEOF), capacity);
	}

	/**
	 * Returns a new {@link SECURITY_ATTRIBUTES.Buffer} instance allocated on the specified {@link MemoryStack} and initializes all its bits to zero.
	 *
	 * @param stack the stack from which to allocate
	 * @param capacity the buffer capacity
	 */
	public static Buffer callocStack(int capacity, MemoryStack stack) {
		return create(stack.ncalloc(ALIGNOF, capacity, SIZEOF), capacity);
	}

	// -----------------------------------

	/** Unsafe version of {@link #nLength}. */
	public static int nnLength(long struct) { return memGetInt(struct + SECURITY_ATTRIBUTES.NLENGTH); }
	/** Unsafe version of {@link #lpSecurityDescriptor}. */
	public static long nlpSecurityDescriptor(long struct) { return memGetAddress(struct + SECURITY_ATTRIBUTES.LPSECURITYDESCRIPTOR); }
	/** Unsafe version of {@link #bInheritHandle}. */
	public static int nbInheritHandle(long struct) { return memGetInt(struct + SECURITY_ATTRIBUTES.BINHERITHANDLE); }

	/** Unsafe version of {@link #nLength(int) nLength}. */
	public static void nnLength(long struct, int value) { memPutInt(struct + SECURITY_ATTRIBUTES.NLENGTH, value); }
	/** Unsafe version of {@link #lpSecurityDescriptor(long) lpSecurityDescriptor}. */
	public static void nlpSecurityDescriptor(long struct, long value) { memPutAddress(struct + SECURITY_ATTRIBUTES.LPSECURITYDESCRIPTOR, checkPointer(value)); }
	/** Unsafe version of {@link #bInheritHandle(boolean) bInheritHandle}. */
	public static void nbInheritHandle(long struct, int value) { memPutInt(struct + SECURITY_ATTRIBUTES.BINHERITHANDLE, value); }

	/**
	 * Validates pointer members that should not be {@code NULL}.
	 *
	 * @param struct the struct to validate
	 */
	public static void validate(long struct) {
		checkPointer(memGetAddress(struct + SECURITY_ATTRIBUTES.LPSECURITYDESCRIPTOR));
	}

	/**
	 * Calls {@link #validate(long)} for each struct contained in the specified struct array.
	 *
	 * @param array the struct array to validate
	 * @param count the number of structs in {@code array}
	 */
	public static void validate(long array, int count) {
		for ( int i = 0; i < count; i++ )
			validate(array + i * SIZEOF);
	}

	// -----------------------------------

	/** An array of {@link SECURITY_ATTRIBUTES} structs. */
	public static class Buffer extends StructBuffer<SECURITY_ATTRIBUTES, Buffer> implements NativeResource {

		/**
		 * Creates a new {@link SECURITY_ATTRIBUTES.Buffer} instance backed by the specified container.
		 *
		 * Changes to the container's content will be visible to the struct buffer instance and vice versa. The two buffers' position, limit, and mark values
		 * will be independent. The new buffer's position will be zero, its capacity and its limit will be the number of bytes remaining in this buffer divided
		 * by {@link SECURITY_ATTRIBUTES#SIZEOF}, and its mark will be undefined.
		 *
		 *
The created buffer instance holds a strong reference to the container object.

		 */
		public Buffer(ByteBuffer container) {
			super(container, container.remaining() / SIZEOF);
		}

		Buffer(long address, ByteBuffer container, int mark, int pos, int lim, int cap) {
			super(address, container, mark, pos, lim, cap);
		}

		@Override
		protected Buffer self() {
			return this;
		}

		@Override
		protected Buffer newBufferInstance(long address, ByteBuffer container, int mark, int pos, int lim, int cap) {
			return new Buffer(address, container, mark, pos, lim, cap);
		}

		@Override
		protected SECURITY_ATTRIBUTES newInstance(long address) {
			return new SECURITY_ATTRIBUTES(address, container);
		}

		@Override
		protected int sizeof() {
			return SIZEOF;
		}

		/** Returns the value of the {@code nLength} field. */
		public int nLength() { return SECURITY_ATTRIBUTES.nnLength(address()); }
		/** Returns the value of the {@code lpSecurityDescriptor} field. */
		public long lpSecurityDescriptor() { return SECURITY_ATTRIBUTES.nlpSecurityDescriptor(address()); }
		/** Returns the value of the {@code bInheritHandle} field. */
		public boolean bInheritHandle() { return SECURITY_ATTRIBUTES.nbInheritHandle(address()) != 0; }

		/** Sets the specified value to the {@code nLength} field. */
		public SECURITY_ATTRIBUTES.Buffer nLength(int value) { SECURITY_ATTRIBUTES.nnLength(address(), value); return this; }
		/** Sets the specified value to the {@code lpSecurityDescriptor} field. */
		public SECURITY_ATTRIBUTES.Buffer lpSecurityDescriptor(long value) { SECURITY_ATTRIBUTES.nlpSecurityDescriptor(address(), value); return this; }
		/** Sets the specified value to the {@code bInheritHandle} field. */
		public SECURITY_ATTRIBUTES.Buffer bInheritHandle(boolean value) { SECURITY_ATTRIBUTES.nbInheritHandle(address(), value ? 1 : 0); return this; }

	}

}


text:
package ddl_test

import (
	"fmt"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	. "github.com/pingcap/check"
	"github.com/pingcap/errors"
	"github.com/pingcap/parser"
	"github.com/pingcap/parser/ast"
	"github.com/pingcap/parser/model"
	"github.com/pingcap/parser/terror"
	"github.com/pingcap/tidb/ddl"
	"github.com/pingcap/tidb/domain"
	"github.com/pingcap/tidb/executor"
	"github.com/pingcap/tidb/infoschema"
	"github.com/pingcap/tidb/kv"
	"github.com/pingcap/tidb/session"
	"github.com/pingcap/tidb/sessionctx"
	"github.com/pingcap/tidb/store/mockstore"
	"github.com/pingcap/tidb/util/admin"
	"github.com/pingcap/tidb/util/sqlexec"
	"github.com/pingcap/tidb/util/testkit"
	"github.com/pingcap/tidb/util/testleak"
	"golang.org/x/net/context"
)

var _ = Suite(&testStateChangeSuite{})

type testStateChangeSuite struct {
	lease time.Duration
	store kv.Storage
	dom   *domain.Domain
	se    session.Session
	p     *parser.Parser
}

func (s *testStateChangeSuite) SetUpSuite(c *C) {
	testleak.BeforeTest()
	s.lease = 200 * time.Millisecond
	ddl.WaitTimeWhenErrorOccured = 1 * time.Microsecond
	var err error
	s.store, err = mockstore.NewMockTikvStore()
	c.Assert(err, IsNil)
	session.SetSchemaLease(s.lease)
	s.dom, err = session.BootstrapSession(s.store)
	c.Assert(err, IsNil)
	s.se, err = session.CreateSession4Test(s.store)
	c.Assert(err, IsNil)
	_, err = s.se.Execute(context.Background(), "create database test_db_state")
	c.Assert(err, IsNil)
	_, err = s.se.Execute(context.Background(), "use test_db_state")
	c.Assert(err, IsNil)
	s.p = parser.New()
}

func (s *testStateChangeSuite) TearDownSuite(c *C) {
	s.se.Execute(context.Background(), "drop database if exists test_db_state")
	s.se.Close()
	s.dom.Close()
	s.store.Close()
	testleak.AfterTest(c)()
}

// TestShowCreateTable tests the result of "show create table" when we are running "add index" or "add column".
func (s *testStateChangeSuite) TestShowCreateTable(c *C) {
	tk := testkit.NewTestKit(c, s.store)
	tk.MustExec("use test")
	tk.MustExec("create table t (id int, index idx (id))")

	var checkErr error
	prevState := model.StateNone
	callback := &ddl.TestDDLCallback{}
	callback.OnJobUpdatedExported = func(job *model.Job) {
		if job.SchemaState == prevState || checkErr != nil {
			return
		}
		if job.SchemaState != model.StatePublic {
			result := tk.MustQuery("show create table t")
			got := result.Rows()[0][1]
			var expected string
			if job.Type == model.ActionAddIndex {
				expected = "CREATE TABLE `t` (\n  `id` int(11) DEFAULT NULL,\n  KEY `idx` (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin"
			} else if job.Type == model.ActionAddColumn {
				expected = "CREATE TABLE `t` (\n  `id` int(11) DEFAULT NULL,\n  KEY `idx` (`id`),\n  KEY `idx1` (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin"
			}
			if got != expected {
				checkErr = errors.Errorf("got %s, expected %s", got, expected)
			}
		}
	}
	d := s.dom.DDL()
	d.(ddl.DDLForTest).SetHook(callback)
	tk.MustExec("alter table t add index idx1(id)")
	c.Assert(checkErr, IsNil)
	tk.MustExec("alter table t add column c int")
	c.Assert(checkErr, IsNil)
}

func (s *testStateChangeSuite) TestTwoStates(c *C) {
	cnt := 5
	// New the testExecInfo.
	testInfo := &testExecInfo{
		execCases: cnt,
		sqlInfos:  make([]*sqlInfo, 4),
	}
	for i := 0; i < len(testInfo.sqlInfos); i++ {
		sqlInfo := &sqlInfo{cases: make([]*stateCase, cnt)}
		for j := 0; j < cnt; j++ {
			sqlInfo.cases[j] = new(stateCase)
		}
		testInfo.sqlInfos[i] = sqlInfo
	}
	err := testInfo.createSessions(s.store, "test_db_state")
	c.Assert(err, IsNil)
	// Fill the SQLs and expected error messages.
	testInfo.sqlInfos[0].sql = "insert into t (c1, c2, c3, c4) value(2, 'b', 'N', '2017-07-02')"
	testInfo.sqlInfos[1].sql = "insert into t (c1, c2, c3, d3, c4) value(3, 'b', 'N', 'a', '2017-07-03')"
	unknownColErr := errors.New("unknown column d3")
	testInfo.sqlInfos[1].cases[0].expectedCompileErr = unknownColErr
	testInfo.sqlInfos[1].cases[1].expectedCompileErr = unknownColErr
	testInfo.sqlInfos[1].cases[2].expectedCompileErr = unknownColErr
	testInfo.sqlInfos[1].cases[3].expectedCompileErr = unknownColErr
	testInfo.sqlInfos[2].sql = "update t set c2 = 'c2_update'"
	testInfo.sqlInfos[3].sql = "replace into t values(5, 'e', 'N', '2017-07-05')'"
	testInfo.sqlInfos[3].cases[4].expectedCompileErr = errors.New("Column count doesn't match value count at row 1")
	alterTableSQL := "alter table t add column d3 enum('a', 'b') not null default 'a' after c3"
	s.test(c, "", alterTableSQL, testInfo)
	// TODO: Add more DDL statements.
}

func (s *testStateChangeSuite) test(c *C, tableName, alterTableSQL string, testInfo *testExecInfo) {
	_, err := s.se.Execute(context.Background(), `create table t (
		c1 int,
		c2 varchar(64),
		c3 enum('N','Y') not null default 'N',
		c4 timestamp on update current_timestamp,
		key(c1, c2))`)
	c.Assert(err, IsNil)
	defer s.se.Execute(context.Background(), "drop table t")
	_, err = s.se.Execute(context.Background(), "insert into t values(1, 'a', 'N', '2017-07-01')")
	c.Assert(err, IsNil)

	callback := &ddl.TestDDLCallback{}
	prevState := model.StateNone
	var checkErr error
	err = testInfo.parseSQLs(s.p)
	c.Assert(err, IsNil, Commentf("error stack %v", errors.ErrorStack(err)))
	times := 0
	callback.OnJobUpdatedExported = func(job *model.Job) {
		if job.SchemaState == prevState || checkErr != nil || times >= 3 {
			return
		}
		times++
		switch job.SchemaState {
		case model.StateDeleteOnly:
			// This state we execute every sqlInfo one time using the first session and other information.
			err = testInfo.compileSQL(0)
			if err != nil {
				checkErr = err
				break
			}
			err = testInfo.execSQL(0)
			if err != nil {
				checkErr = err
			}
		case model.StateWriteOnly:
			// This state we put the schema information to the second case.
			err = testInfo.compileSQL(1)
			if err != nil {
				checkErr = err
			}
		case model.StateWriteReorganization:
			// This state we execute every sqlInfo one time using the third session and other information.
			err = testInfo.compileSQL(2)
			if err != nil {
				checkErr = err
				break
			}
			err = testInfo.execSQL(2)
			if err != nil {
				checkErr = err
				break
			}
			// Mock the server is in `write only` state.
			err = testInfo.execSQL(1)
			if err != nil {
				checkErr = err
				break
			}
			// This state we put the schema information to the fourth case.
			err = testInfo.compileSQL(3)
			if err != nil {
				checkErr = err
			}
		}
	}
	d := s.dom.DDL()
	d.(ddl.DDLForTest).SetHook(callback)
	_, err = s.se.Execute(context.Background(), alterTableSQL)
	c.Assert(err, IsNil)
	err = testInfo.compileSQL(4)
	c.Assert(err, IsNil)
	err = testInfo.execSQL(4)
	c.Assert(err, IsNil)
	// Mock the server is in `write reorg` state.
	err = testInfo.execSQL(3)
	c.Assert(err, IsNil)
	c.Assert(errors.ErrorStack(checkErr), Equals, "")
	callback = &ddl.TestDDLCallback{}
	d.(ddl.DDLForTest).SetHook(callback)
}

type stateCase struct {
	session            session.Session
	rawStmt            ast.StmtNode
	stmt               sqlexec.Statement
	expectedExecErr    error
	expectedCompileErr error
}

type sqlInfo struct {
	sql string
	// cases is multiple stateCases.
	// Every case need to be executed with the different schema state.
	cases []*stateCase
}

// testExecInfo contains some SQL information and the number of times each SQL is executed
// in a DDL statement.
type testExecInfo struct {
	// execCases represents every SQL need to be executed execCases times.
	// And the schema state is different at each execution.
	execCases int
	// sqlInfos represents this test information has multiple SQLs to test.
	sqlInfos []*sqlInfo
}

func (t *testExecInfo) createSessions(store kv.Storage, useDB string) error {
	var err error
	for i, info := range t.sqlInfos {
		for j, c := range info.cases {
			c.session, err = session.CreateSession4Test(store)
			if err != nil {
				return errors.Trace(err)
			}
			_, err = c.session.Execute(context.Background(), "use "+useDB)
			if err != nil {
				return errors.Trace(err)
			}
			// It's used to debug.
			c.session.SetConnectionID(uint64(i*10 + j))
		}
	}
	return nil
}

func (t *testExecInfo) parseSQLs(p *parser.Parser) error {
	if t.execCases <= 0 {
		return nil
	}
	var err error
	for _, sqlInfo := range t.sqlInfos {
		seVars := sqlInfo.cases[0].session.GetSessionVars()
		charset, collation := seVars.GetCharsetInfo()
		for j := 0; j < t.execCases; j++ {
			sqlInfo.cases[j].rawStmt, err = p.ParseOneStmt(sqlInfo.sql, charset, collation)
			if err != nil {
				return errors.Trace(err)
			}
		}
	}
	return nil
}

func (t *testExecInfo) compileSQL(idx int) (err error) {
	for _, info := range t.sqlInfos {
		c := info.cases[idx]
		compiler := executor.Compiler{Ctx: c.session}
		se := c.session
		ctx := context.TODO()
		se.PrepareTxnCtx(ctx)
		sctx := se.(sessionctx.Context)
		if err = executor.ResetContextOfStmt(sctx, c.rawStmt); err != nil {
			return errors.Trace(err)
		}
		c.stmt, err = compiler.Compile(ctx, c.rawStmt)
		if c.expectedCompileErr != nil {
			if err == nil {
				err = errors.Errorf("expected error %s but got nil", c.expectedCompileErr)
			} else if strings.Contains(err.Error(), c.expectedCompileErr.Error()) {
				err = nil
			}
		}
		if err != nil {
			return errors.Trace(err)
		}
	}
	return nil
}

func (t *testExecInfo) execSQL(idx int) error {
	for _, sqlInfo := range t.sqlInfos {
		c := sqlInfo.cases[idx]
		if c.expectedCompileErr != nil {
			continue
		}
		_, err := c.stmt.Exec(context.TODO())
		if c.expectedExecErr != nil {
			if err == nil {
				err = errors.Errorf("expected error %s but got nil", c.expectedExecErr)
			} else if strings.Contains(err.Error(), c.expectedExecErr.Error()) {
				err = nil
			}
		}
		if err != nil {
			return errors.Trace(err)
		}
		err = c.session.CommitTxn(context.TODO())
		if err != nil {
			return errors.Trace(err)
		}
	}
	return nil
}

type sqlWithErr struct {
	sql       string
	expectErr error
}

type expectQuery struct {
	sql  string
	rows []string
}

func (s *testStateChangeSuite) TestAppendEnum(c *C) {
	_, err := s.se.Execute(context.Background(), `create table t (
			c1 varchar(64),
			c2 enum('N','Y') not null default 'N',
			c3 timestamp on update current_timestamp,
			c4 int primary key,
			unique key idx2 (c2, c3))`)
	c.Assert(err, IsNil)
	defer s.se.Execute(context.Background(), "drop table t")
	_, err = s.se.Execute(context.Background(), "insert into t values('a', 'N', '2017-07-01', 8)")
	c.Assert(err, IsNil)
	// Make sure these sqls use the the plan of index scan.
	_, err = s.se.Execute(context.Background(), "drop stats t")
	c.Assert(err, IsNil)
	se, err := session.CreateSession(s.store)
	c.Assert(err, IsNil)
	_, err = se.Execute(context.Background(), "use test_db_state")
	c.Assert(err, IsNil)

	_, err = s.se.Execute(context.Background(), "insert into t values('a', 'A', '2018-09-19', 9)")
	c.Assert(err.Error(), Equals, "[table:1366]Incorrect enum value: 'A' for column 'c2' at row 1")
	failAlterTableSQL1 := "alter table t change c2 c2 enum('N') DEFAULT 'N'"
	_, err = s.se.Execute(context.Background(), failAlterTableSQL1)
	c.Assert(err.Error(), Equals, "[ddl:203]unsupported modify column the number of enum column's elements is less than the original: 2")
	failAlterTableSQL2 := "alter table t change c2 c2 int default 0"
	_, err = s.se.Execute(context.Background(), failAlterTableSQL2)
	c.Assert(err.Error(), Equals, "[ddl:203]unsupported modify column charset binary not match origin utf8")
	alterTableSQL := "alter table t change c2 c2 enum('N','Y','A') DEFAULT 'A'"
	_, err = s.se.Execute(context.Background(), alterTableSQL)
	c.Assert(err, IsNil)
	_, err = se.Execute(context.Background(), "insert into t values('a', 'A', '2018-09-20', 10)")
	c.Assert(err, IsNil)
	_, err = se.Execute(context.Background(), "insert into t (c1, c3, c4) values('a', '2018-09-21', 11)")
	c.Assert(err, IsNil)

	tk := testkit.NewTestKit(c, s.store)
	tk.MustExec("use test_db_state")
	result, err := s.execQuery(tk, "select c4, c2 from t order by c4 asc")
	c.Assert(err, IsNil)
	expected := []string{"8 N", "10 A", "11 A"}
	checkResult(result, testkit.Rows(expected...))

	_, err = s.se.Execute(context.Background(), "update t set c2='N' where c4 = 10")
	c.Assert(err, IsNil)
	result, err = s.execQuery(tk, "select c2 from t where c4 = 10")
	c.Assert(err, IsNil)
	expected = []string{"8 N", "10 N", "11 A"}
	checkResult(result, testkit.Rows(expected...))
}

// https://github.com/pingcap/tidb/pull/6249 fixes the following two test cases.
func (s *testStateChangeSuite) TestWriteOnlyWriteNULL(c *C) {
	sqls := make([]sqlWithErr, 1)
	sqls[0] = sqlWithErr{"insert t set c1 = 'c1_new', c3 = '2019-02-12', c4 = 8 on duplicate key update c1 = values(c1)", nil}
	addColumnSQL := "alter table t add column c5 int not null default 1 after c4"
	expectQuery := &expectQuery{"select c4, c5 from t", []string{"8 1"}}
	// TODO: This case should always fail in write-only state, but it doesn't. We use write-reorganization state here to keep it running stable. It need a double check.
	s.runTestInSchemaState(c, model.StateWriteReorganization, "", addColumnSQL, sqls, expectQuery)
}

func (s *testStateChangeSuite) TestWriteOnlyOnDupUpdate(c *C) {
	sqls := make([]sqlWithErr, 3)
	sqls[0] = sqlWithErr{"delete from t", nil}
	sqls[1] = sqlWithErr{"insert t set c1 = 'c1_dup', c3 = '2018-02-12', c4 = 2 on duplicate key update c1 = values(c1)", nil}
	sqls[2] = sqlWithErr{"insert t set c1 = 'c1_new', c3 = '2019-02-12', c4 = 2 on duplicate key update c1 = values(c1)", nil}
	addColumnSQL := "alter table t add column c5 int not null default 1 after c4"
	expectQuery := &expectQuery{"select c4, c5 from t", []string{"2 1"}}
	// TODO: This case should always fail in write-only state, but it doesn't. We use write-reorganization state here to keep it running stable. It need a double check.
	s.runTestInSchemaState(c, model.StateWriteReorganization, "", addColumnSQL, sqls, expectQuery)
}

// TestWriteOnly tests whether the correct columns is used in PhysicalIndexScan's ToPB function.
func (s *testStateChangeSuite) TestWriteOnly(c *C) {
	sqls := make([]sqlWithErr, 3)
	sqls[0] = sqlWithErr{"delete from t where c1 = 'a'", nil}
	sqls[1] = sqlWithErr{"update t use index(idx2) set c1 = 'c1_update' where c1 = 'a'", nil}
	sqls[2] = sqlWithErr{"insert t set c1 = 'c1_insert', c3 = '2018-02-12', c4 = 1", nil}
	addColumnSQL := "alter table t add column c5 int not null default 1 first"
	s.runTestInSchemaState(c, model.StateWriteOnly, "", addColumnSQL, sqls, nil)
}

// TestDeletaOnly tests whether the correct columns is used in PhysicalIndexScan's ToPB function.
func (s *testStateChangeSuite) TestDeleteOnly(c *C) {
	sqls := make([]sqlWithErr, 1)
	sqls[0] = sqlWithErr{"insert t set c1 = 'c1_insert', c3 = '2018-02-12', c4 = 1",
		errors.Errorf("Can't find column c1")}
	dropColumnSQL := "alter table t drop column c1"
	s.runTestInSchemaState(c, model.StateDeleteOnly, "", dropColumnSQL, sqls, nil)
}

func (s *testStateChangeSuite) runTestInSchemaState(c *C, state model.SchemaState, tableName, alterTableSQL string,
	sqlWithErrs []sqlWithErr, expectQuery *expectQuery) {
	_, err := s.se.Execute(context.Background(), `create table t (
		c1 varchar(64),
		c2 enum('N','Y') not null default 'N',
		c3 timestamp on update current_timestamp,
		c4 int primary key,
		unique key idx2 (c2, c3))`)
	c.Assert(err, IsNil)
	defer s.se.Execute(context.Background(), "drop table t")
	_, err = s.se.Execute(context.Background(), "insert into t values('a', 'N', '2017-07-01', 8)")
	c.Assert(err, IsNil)
	// Make sure these sqls use the the plan of index scan.
	_, err = s.se.Execute(context.Background(), "drop stats t")
	c.Assert(err, IsNil)

	callback := &ddl.TestDDLCallback{}
	prevState := model.StateNone
	var checkErr error
	times := 0
	se, err := session.CreateSession(s.store)
	c.Assert(err, IsNil)
	_, err = se.Execute(context.Background(), "use test_db_state")
	c.Assert(err, IsNil)
	callback.OnJobUpdatedExported = func(job *model.Job) {
		if job.SchemaState == prevState || checkErr != nil || times >= 3 {
			return
		}
		times++
		if job.SchemaState != state {
			return
		}
		for _, sqlWithErr := range sqlWithErrs {
			_, err = se.Execute(context.Background(), sqlWithErr.sql)
			if !terror.ErrorEqual(err, sqlWithErr.expectErr) {
				checkErr = err
				break
			}
		}
	}
	d := s.dom.DDL()
	d.(ddl.DDLForTest).SetHook(callback)
	_, err = s.se.Execute(context.Background(), alterTableSQL)
	c.Assert(err, IsNil)
	c.Assert(errors.ErrorStack(checkErr), Equals, "")
	callback = &ddl.TestDDLCallback{}
	d.(ddl.DDLForTest).SetHook(callback)

	if expectQuery != nil {
		tk := testkit.NewTestKit(c, s.store)
		tk.MustExec("use test_db_state")
		result, err := s.execQuery(tk, expectQuery.sql)
		c.Assert(err, IsNil)
		err = checkResult(result, testkit.Rows(expectQuery.rows...))
		c.Assert(err, IsNil)
	}
}

func (s *testStateChangeSuite) execQuery(tk *testkit.TestKit, sql string, args ...interface{}) (*testkit.Result, error) {
	comment := Commentf("sql:%s, args:%v", sql, args)
	rs, err := tk.Exec(sql, args...)
	if err != nil {
		return nil, err
	}
	result := tk.ResultSetToResult(rs, comment)
	return result, nil
}

func checkResult(result *testkit.Result, expected [][]interface{}) error {
	got := fmt.Sprintf("%s", result.Rows())
	need := fmt.Sprintf("%s", expected)
	if got != need {
		return fmt.Errorf("need %v, but got %v", need, got)
	}
	return nil
}

func (s *testStateChangeSuite) CheckResult(tk *testkit.TestKit, sql string, args ...interface{}) (*testkit.Result, error) {
	comment := Commentf("sql:%s, args:%v", sql, args)
	rs, err := tk.Exec(sql, args...)
	if err != nil {
		return nil, err
	}
	result := tk.ResultSetToResult(rs, comment)
	return result, nil
}

func (s *testStateChangeSuite) TestShowIndex(c *C) {
	_, err := s.se.Execute(context.Background(), `create table t(c1 int primary key, c2 int)`)
	c.Assert(err, IsNil)
	defer s.se.Execute(context.Background(), "drop table t")

	callback := &ddl.TestDDLCallback{}
	prevState := model.StateNone
	tk := testkit.NewTestKit(c, s.store)
	tk.MustExec("use test_db_state")
	showIndexSQL := `show index from t`
	var checkErr error
	callback.OnJobUpdatedExported = func(job *model.Job) {
		if job.SchemaState == prevState || checkErr != nil {
			return
		}
		switch job.SchemaState {
		case model.StateDeleteOnly, model.StateWriteOnly, model.StateWriteReorganization:
			result, err1 := s.execQuery(tk, showIndexSQL)
			if err1 != nil {
				checkErr = err1
				break
			}
			checkErr = checkResult(result, testkit.Rows("t 0 PRIMARY 1 c1 A 0 <nil> <nil>  BTREE  "))
		}
	}

	d := s.dom.DDL()
	d.(ddl.DDLForTest).SetHook(callback)
	alterTableSQL := `alter table t add index c2(c2)`
	_, err = s.se.Execute(context.Background(), alterTableSQL)
	c.Assert(err, IsNil)
	c.Assert(errors.ErrorStack(checkErr), Equals, "")

	result, err := s.execQuery(tk, showIndexSQL)
	c.Assert(err, IsNil)
	err = checkResult(result, testkit.Rows("t 0 PRIMARY 1 c1 A 0 <nil> <nil>  BTREE  ", "t 1 c2 1 c2 A 0 <nil> <nil> YES BTREE  "))
	c.Assert(err, IsNil)
	callback = &ddl.TestDDLCallback{}
	d.(ddl.DDLForTest).SetHook(callback)

	c.Assert(err, IsNil)

	_, err = s.se.Execute(context.Background(), `create table tr(
		id int, name varchar(50),
		purchased date
	)
	partition by range( year(purchased) ) (
    	partition p0 values less than (1990),
    	partition p1 values less than (1995),
    	partition p2 values less than (2000),
    	partition p3 values less than (2005),
    	partition p4 values less than (2010),
    	partition p5 values less than (2015)
   	);`)
	c.Assert(err, IsNil)
	defer s.se.Execute(context.Background(), "drop table tr")
	_, err = s.se.Execute(context.Background(), "create index idx1 on tr (purchased);")
	c.Assert(err, IsNil)
	result, err = s.execQuery(tk, "show index from tr;")
	c.Assert(err, IsNil)
	err = checkResult(result, testkit.Rows("tr 1 idx1 1 purchased A 0 <nil> <nil> YES BTREE  "))
	c.Assert(err, IsNil)
}

func (s *testStateChangeSuite) TestParallelAlterModifyColumn(c *C) {
	sql := "ALTER TABLE t MODIFY COLUMN b int FIRST;"
	f := func(c *C, err1, err2 error) {
		c.Assert(err1, IsNil)
		c.Assert(err2, IsNil)
		_, err := s.se.Execute(context.Background(), "select * from t")
		c.Assert(err, IsNil)
	}
	s.testControlParallelExecSQL(c, sql, sql, f)
}

func (s *testStateChangeSuite) TestParallelColumnModifyingDefinition(c *C) {
	sql1 := "insert into t(b) values (null);"
	sql2 := "alter table t change b b2 bigint not null;"
	f := func(c *C, err1, err2 error) {
		c.Assert(err1, IsNil)
		if err2 != nil {
			c.Assert(err2.Error(), Equals, "[ddl:1265]Data truncated for column 'b2' at row 1")
		}
	}
	s.testControlParallelExecSQL(c, sql1, sql2, f)
}

func (s *testStateChangeSuite) TestParallelChangeColumnName(c *C) {
	sql1 := "ALTER TABLE t CHANGE a aa int;"
	sql2 := "ALTER TABLE t CHANGE b aa int;"
	f := func(c *C, err1, err2 error) {
		// Make sure only a DDL encounters the error of 'duplicate column name'.
		var oneErr error
		if (err1 != nil && err2 == nil) || (err1 == nil && err2 != nil) {
			if err1 != nil {
				oneErr = err1
			} else {
				oneErr = err2
			}
		}
		c.Assert(oneErr.Error(), Equals, "[schema:1060]Duplicate column name 'aa'")
	}
	s.testControlParallelExecSQL(c, sql1, sql2, f)
}

func (s *testStateChangeSuite) TestParallelAlterAddIndex(c *C) {
	sql1 := "ALTER TABLE t add index index_b(b);"
	sql2 := "CREATE INDEX index_b ON t (c);"
	f := func(c *C, err1, err2 error) {
		c.Assert(err1, IsNil)
		c.Assert(err2.Error(), Equals, "[ddl:1061]index already exist index_b")
	}
	s.testControlParallelExecSQL(c, sql1, sql2, f)
}

func (s *testStateChangeSuite) TestParallelDropColumn(c *C) {
	sql := "ALTER TABLE t drop COLUMN c ;"
	f := func(c *C, err1, err2 error) {
		c.Assert(err1, IsNil)
		c.Assert(err2.Error(), Equals, "[ddl:1091]column c doesn't exist")
	}
	s.testControlParallelExecSQL(c, sql, sql, f)
}

func (s *testStateChangeSuite) TestParallelCreateAndRename(c *C) {
	sql1 := "create table t_exists(c int);"
	sql2 := "alter table t rename to t_exists;"
	defer s.se.Execute(context.Background(), "drop table t_exists")
	f := func(c *C, err1, err2 error) {
		c.Assert(err1, IsNil)
		c.Assert(err2.Error(), Equals, "[schema:1050]Table 't_exists' already exists")
	}
	s.testControlParallelExecSQL(c, sql1, sql2, f)
}

type checkRet func(c *C, err1, err2 error)

func (s *testStateChangeSuite) testControlParallelExecSQL(c *C, sql1, sql2 string, f checkRet) {
	_, err := s.se.Execute(context.Background(), "use test_db_state")
	c.Assert(err, IsNil)
	_, err = s.se.Execute(context.Background(), "create table t(a int, b int, c int)")
	c.Assert(err, IsNil)
	defer s.se.Execute(context.Background(), "drop table t")

	callback := &ddl.TestDDLCallback{}
	times := 0
	callback.OnJobUpdatedExported = func(job *model.Job) {
		if times != 0 {
			return
		}
		var qLen int
		for {
			kv.RunInNewTxn(s.store, false, func(txn kv.Transaction) error {
				jobs, err1 := admin.GetDDLJobs(txn)
				if err1 != nil {
					return err1
				}
				qLen = len(jobs)
				return nil
			})
			if qLen == 2 {
				break
			}
			time.Sleep(5 * time.Millisecond)
		}
		times++
	}
	d := s.dom.DDL()
	d.(ddl.DDLForTest).SetHook(callback)

	wg := sync.WaitGroup{}
	var err1 error
	var err2 error
	se, err := session.CreateSession(s.store)
	c.Assert(err, IsNil)
	_, err = se.Execute(context.Background(), "use test_db_state")
	c.Assert(err, IsNil)
	se1, err := session.CreateSession(s.store)
	c.Assert(err, IsNil)
	_, err = se1.Execute(context.Background(), "use test_db_state")
	c.Assert(err, IsNil)
	wg.Add(2)
	ch := make(chan struct{})
	go func() {
		defer wg.Done()
		close(ch)
		_, err1 = se.Execute(context.Background(), sql1)
	}()
	go func() {
		defer wg.Done()
		<-ch
		// Make sure sql2 is executed after the sql1.
		time.Sleep(time.Millisecond * 10)
		_, err2 = se1.Execute(context.Background(), sql2)
	}()

	wg.Wait()
	f(c, err1, err2)

	callback = &ddl.TestDDLCallback{}
	d.(ddl.DDLForTest).SetHook(callback)
}

func (s *testStateChangeSuite) testParallelExecSQL(c *C, sql string) {
	se, err := session.CreateSession(s.store)
	c.Assert(err, IsNil)
	_, err = se.Execute(context.Background(), "use test_db_state")
	c.Assert(err, IsNil)

	se1, err1 := session.CreateSession(s.store)
	c.Assert(err1, IsNil)
	_, err = se1.Execute(context.Background(), "use test_db_state")
	c.Assert(err, IsNil)

	var err2, err3 error
	wg := sync.WaitGroup{}

	callback := &ddl.TestDDLCallback{}
	once := sync.Once{}
	callback.OnJobUpdatedExported = func(job *model.Job) {
		// sleep a while, let other job enqueue.
		once.Do(func() {
			time.Sleep(time.Millisecond * 10)
		})
	}

	d := s.dom.DDL()
	d.(ddl.DDLForTest).SetHook(callback)

	wg.Add(2)
	go func() {
		defer wg.Done()
		_, err2 = se.Execute(context.Background(), sql)
	}()

	go func() {
		defer wg.Done()
		_, err3 = se1.Execute(context.Background(), sql)
	}()
	wg.Wait()
	c.Assert(err2, IsNil)
	c.Assert(err3, IsNil)
	callback = &ddl.TestDDLCallback{}
	d.(ddl.DDLForTest).SetHook(callback)
}

// TestCreateTableIfNotExists parallel exec create table if not exists xxx. No error returns is expected.
func (s *testStateChangeSuite) TestCreateTableIfNotExists(c *C) {
	defer s.se.Execute(context.Background(), "drop table test_not_exists")
	s.testParallelExecSQL(c, "create table if not exists test_not_exists(a int);")
}

// TestCreateDBIfNotExists parallel exec create database if not exists xxx. No error returns is expected.
func (s *testStateChangeSuite) TestCreateDBIfNotExists(c *C) {
	defer s.se.Execute(context.Background(), "drop database test_not_exists")
	s.testParallelExecSQL(c, "create database if not exists test_not_exists;")
}

// TestParallelDDLBeforeRunDDLJob tests a session to execute DDL with an outdated information schema.
// This test is used to simulate the following conditions:
// In a cluster, TiDB "a" executes the DDL.
// TiDB "b" fails to load schema, then TiDB "b" executes the DDL statement associated with the DDL statement executed by "a".
func (s *testStateChangeSuite) TestParallelDDLBeforeRunDDLJob(c *C) {
	defer s.se.Execute(context.Background(), "drop table test_table")
	_, err := s.se.Execute(context.Background(), "use test_db_state")
	c.Assert(err, IsNil)
	_, err = s.se.Execute(context.Background(), "create table test_table (c1 int, c2 int default 1, index (c1))")
	c.Assert(err, IsNil)

	// Create two sessions.
	se, err := session.CreateSession(s.store)
	c.Assert(err, IsNil)
	_, err = se.Execute(context.Background(), "use test_db_state")
	c.Assert(err, IsNil)
	se1, err := session.CreateSession(s.store)
	c.Assert(err, IsNil)
	_, err = se1.Execute(context.Background(), "use test_db_state")
	c.Assert(err, IsNil)

	intercept := &ddl.TestInterceptor{}
	firstConnID := uint64(1)
	finishedCnt := int32(0)
	interval := 5 * time.Millisecond
	var sessionCnt int32 // sessionCnt is the number of sessions that goes into the function of OnGetInfoSchema.
	intercept.OnGetInfoSchemaExported = func(ctx sessionctx.Context, is infoschema.InfoSchema) infoschema.InfoSchema {
		// The following code is for testing.
		// Make sure the two sessions get the same information schema before executing DDL.
		// After the first session executes its DDL, then the second session executes its DDL.
		var info infoschema.InfoSchema
		atomic.AddInt32(&sessionCnt, 1)
		for {
			// Make sure there are two sessions running here.
			if atomic.LoadInt32(&sessionCnt) == 2 {
				info = is
				break
			}
			time.Sleep(interval)
		}

		currID := ctx.GetSessionVars().ConnectionID
		for {
			seCnt := atomic.LoadInt32(&sessionCnt)
			// Make sure the two session have got the same information schema. And the first session can continue to go on,
			// or the frist session finished this SQL(seCnt = finishedCnt), then other sessions can continue to go on.
			if currID == firstConnID || seCnt == finishedCnt {
				break
			}
			time.Sleep(interval)
		}

		return info
	}
	d := s.dom.DDL()
	d.(ddl.DDLForTest).SetInterceptoror(intercept)

	// Make sure the connection 1 executes a SQL before the connection 2.
	// And the connection 2 executes a SQL with an outdated information schema.
	wg := sync.WaitGroup{}
	wg.Add(2)
	go func() {
		defer wg.Done()

		se.SetConnectionID(firstConnID)
		_, err1 := se.Execute(context.Background(), "alter table test_table drop column c2")
		c.Assert(err1, IsNil)
		atomic.StoreInt32(&sessionCnt, finishedCnt)
	}()
	go func() {
		defer wg.Done()

		se1.SetConnectionID(2)
		_, err2 := se1.Execute(context.Background(), "alter table test_table add column c2 int")
		c.Assert(err2, NotNil)
		c.Assert(strings.Contains(err2.Error(), "Information schema is changed"), IsTrue)
	}()

	wg.Wait()

	intercept = &ddl.TestInterceptor{}
	d.(ddl.DDLForTest).SetInterceptoror(intercept)
}


text:
package com.delmar.test.web.vo;

import lombok.Data;

import java.util.List;

/**
 * Created by 刘大磊 on 2016/10/13 16:53.
 */
@Data
public class UserParam implements java.io.Serializable {
    private List<UserVo> userVoList;
}


text:
using System;
using System.Linq;

class Cycling
{
    static void Main()
    {
        int n = int.Parse(Console.ReadLine());

        int totalMinutes = 0;
        int bestAverageSpeed = 0;
        int bestIndex = 0; // Index of best average speed day

        for (int i = 0; i < n; i++)
        {
            string lineReader = Console.ReadLine();
            string[] tokens = lineReader.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            int minutes = int.Parse(tokens[0]) * 60 + int.Parse(tokens[1]); // All minutes = Hours * 60 + Minutes
            int distance = int.Parse(tokens[2]) * 1000; // Distance in metres = Distance in km * 1000;

            totalMinutes += minutes;

            if (distance / minutes > bestAverageSpeed)
            {
                bestAverageSpeed = distance / minutes;
                bestIndex = i + 1;
            }
        }

        Console.WriteLine("{0} {1} {2} {3}",
            totalMinutes / 24 / 60 % 24, totalMinutes / 60 % 24, totalMinutes % 60, bestIndex);
        //          DAYS                        HOURS                MINUTES
    }
}


text:
#include "muliple_game_server.h"
#include "muliple_wrap_direct3dvertexshader9.h"

WrapperDirect3DVertexShader9::WrapperDirect3DVertexShader9(IDirect3DVertexShader9* ptr, int _id): m_vs(ptr), id(_id) {
	Log::log("WrapperDirect3DVertexShader9 constructor called!\n");
	m_list.AddMember(ptr, this);
}

int WrapperDirect3DVertexShader9::GetID() {
	return this->id;
}

void WrapperDirect3DVertexShader9::SetID(int id) {
	this->id = id;
}

IDirect3DVertexShader9* WrapperDirect3DVertexShader9::GetVS9() {
	return m_vs;
}

WrapperDirect3DVertexShader9* WrapperDirect3DVertexShader9::GetWrapperVertexShader(IDirect3DVertexShader9* ptr) {
	WrapperDirect3DVertexShader9* ret = (WrapperDirect3DVertexShader9*)( m_list.GetDataPtr(ptr) );
	if(ret == NULL) {
		Log::log("WrapperDirect3DPixelShader9::GetWrapperPixelShader(), ret is NULL\n");
	}
	return ret;
}

/*** IUnknown methods ***/
STDMETHODIMP WrapperDirect3DVertexShader9::QueryInterface(THIS_ REFIID riid, void** ppvObj) {
	HRESULT hr = m_vs->QueryInterface(riid, ppvObj);
	*ppvObj = this;
	return hr;
}
STDMETHODIMP_(ULONG) WrapperDirect3DVertexShader9::AddRef(THIS) {
	return m_vs->AddRef();
}
STDMETHODIMP_(ULONG) WrapperDirect3DVertexShader9::Release(THIS) {
	Log::log("WrapperDirect3DVertexShader9::Release() called! id:%d\n", id);
	return m_vs->Release();
}

/*** IDirect3DVertexShader9 methods ***/
STDMETHODIMP WrapperDirect3DVertexShader9::GetDevice(THIS_ IDirect3DDevice9** ppDevice) {
	Log::log("WrapperDirect3DVertexShader9::GetDevice called!\n");
	return m_vs->GetDevice(ppDevice);
}
STDMETHODIMP WrapperDirect3DVertexShader9::GetFunction(THIS_ void* ptr,UINT* pSizeOfData) {
	return m_vs->GetFunction(ptr, pSizeOfData);
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<command-line name="stigmata">
  <definitions>
    <definition name="classpath">
      <short-option>c</short-option>
      <long-option>classpath</long-option>
      <description>$(cli.option.classpath)</description>
      <argument>REQUIRED</argument>
      <argument-name>CLASSPATH</argument-name>
      <value-separator>,</value-separator>
      <multiple-args />
    </definition>

    <definition name="birthmark">
      <short-option>b</short-option>
      <long-option>birthmark</long-option>
      <description>$(cli.option.birthmark)</description>
      <argument>REQUIRED</argument>
      <argument-name>BIRTHMARKS</argument-name>
      <value-separator>,</value-separator>
      <multiple-args />
    </definition>

    <definition name="format">
      <short-option>f</short-option>
      <long-option>format</long-option>
      <description>$(cli.option.format)</description>
      <argument>REQUIRED</argument>
      <argument-name>FORMAT</argument-name>
    </definition>

    <definition name="filter">
      <short-option>F</short-option>
      <long-option>filter</long-option>
      <description>$(cli.option.filter)</description>
      <argument>REQUIRED</argument>
      <argument-name>FILTER_NAME</argument-name>
    </definition>

    <definition name="config-file">
      <long-option>config-file</long-option>
      <description>$(cli.option.config-file)</description>
      <argument>REQUIRED</argument>
      <argument-name>CONFIG-FILE</argument-name>
    </definition>

    <definition name="reset-config">
      <long-option>reset-config</long-option>
      <description>$(cli.option.reset-config)</description>
      <argument>NONE</argument>
    </definition>

    <definition name="extraction-unit">
      <short-option>e</short-option>
      <long-option>extraction-unit</long-option>
      <argument>REQUIRED</argument>
      <argument-name>EXTRACT_UNIT</argument-name>
      <description>$(cli.option.extraction-unit)</description>
    </definition>

    <definition name="store-target">
      <long-option>store-target</long-option>
      <argument>REQUIRED</argument>
      <argument-name>STORE_TARGET</argument-name>
      <description>$(cli.option.store-target)</description>
    </definition>
  </definitions>

  <available-options>
    <option>classpath</option>
    <option>birthmark</option>
    <option>filter</option>
    <option>format</option>
    <option>extraction-unit</option>

    <option>store-target</option>
    <option>config-file</option>
    <option>reset-config</option>
  </available-options>
</command-line>


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/maven-v4_0_0.xsd">
	<parent>
		<artifactId>saiku-core</artifactId>
		<groupId>org.saiku</groupId>
		<version>2.6.1-SNAPSHOT</version>
	</parent>
	<modelVersion>4.0.0</modelVersion>
	<groupId>org.saiku</groupId>
	<artifactId>saiku-web</artifactId>
	<version>2.6.1-SNAPSHOT</version>
	<name>saiku - web</name>
	<packaging>jar</packaging>

	<properties>
		<spring.version>3.0.3.RELEASE</spring.version>
		<spring.security.version>3.0.3.RELEASE</spring.security.version>
	</properties>

	<build>

		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-source-plugin</artifactId>
				<version>2.1.2</version>
				<executions>
					<execution>
						<id>attach-sources</id>
						<phase>package</phase>
						<goals>
							<goal>jar</goal>
						</goals>
					</execution>
				</executions>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.0.2</version>
				<configuration>
					<source>${maven.compiler.source}</source>
					<target>${maven.compiler.target}</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>

			<plugin>
				<groupId>org.mortbay.jetty</groupId>
				<artifactId>maven-jetty-plugin</artifactId>
				<version>6.1.26</version>
				<!-- <configuration> <contextPath>/</contextPath> <scanIntervalSeconds>10</scanIntervalSeconds>
					<stopKey>sparklr</stopKey> <stopPort>9999</stopPort> </configuration> <executions>
					<execution> <id>start-jetty</id> <phase>pre-integration-test</phase> <goals>
					<goal>run</goal> </goals> <configuration> <scanIntervalSeconds>0</scanIntervalSeconds>
					<daemon>true</daemon> </configuration> </execution> <execution> <id>stop-jetty</id>
					<phase>post-integration-test</phase> <goals> <goal>stop</goal> </goals> </execution>
					</executions> -->
			</plugin>

		</plugins>
	</build>
	<dependencies>
		<dependency>
			<groupId>org.saiku</groupId>
			<artifactId>saiku-service</artifactId>
			<version>${project.version}</version>
		</dependency>
		<dependency>
			<groupId>org.saiku</groupId>
			<artifactId>saiku-olap-util</artifactId>
			<version>${project.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.14</version>
		</dependency>
		<!-- Spring modules -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-core</artifactId>
  <version>${spring.version}</version>
</dependency>

 <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-beans</artifactId>
  <version>${spring.version}</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-aop</artifactId>
  <version>${spring.version}</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>${spring.version}</version>
</dependency>
 <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context-support</artifactId>
  <version>${spring.version}</version>
</dependency>

		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-taglibs</artifactId>
			<version>${spring.security.version}</version>
			<exclusions>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring-web</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-ldap</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.enunciate</groupId>
			<artifactId>enunciate-jersey-rt</artifactId>
			<version>${enunciate.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-core</artifactId>
			<version>${jersey.version}</version>
		</dependency>
		<dependency>
			<groupId>com.sun.jersey.contribs</groupId>
			<artifactId>jersey-multipart</artifactId>
			<version>${jersey.version}</version>
		</dependency>

		<dependency>
			<groupId>javax.ws.rs</groupId>
			<artifactId>jsr311-api</artifactId>
			<version>1.1.1</version>
		</dependency>
		<dependency>
			<groupId>com.sun.jersey.jersey-test-framework</groupId>
			<artifactId>jersey-test-framework-core</artifactId>
			<version>${jersey.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.sun.grizzly</groupId>
			<artifactId>grizzly-servlet-webserver</artifactId>
			<version>1.9.18-i</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-all</artifactId>
			<version>1.8.5</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.codehaus.enunciate</groupId>
			<artifactId>enunciate-rt</artifactId>
			<version>${enunciate.version}</version>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.8.2</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>2.2</version>
		</dependency>
		<dependency>
			<groupId>org.codehaus.jettison</groupId>
			<artifactId>jettison</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>hsqldb</groupId>
			<artifactId>hsqldb</artifactId>
			<version>1.8.0.10</version>
		</dependency>
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.2.2</version>
		</dependency>
		<dependency>
			<groupId>commons-pool</groupId>
			<artifactId>commons-pool</artifactId>
			<version>1.4</version>
		</dependency>
		<dependency>
			<groupId>commons-vfs</groupId>
			<artifactId>commons-vfs</artifactId>
			<version>1.0</version>
		</dependency>
		<dependency>
			<groupId>commons-math</groupId>
			<artifactId>commons-math</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.1</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.3</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.security</groupId>
			<artifactId>spring-security-config</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-io</artifactId>
			<version>1.3.2</version>
		</dependency>
		<dependency>
			<groupId>commons-httpclient</groupId>
			<artifactId>commons-httpclient</artifactId>
			<version>20020423</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet.jsp</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.0</version>
			<scope>provided</scope>
		</dependency>

		<!-- Batik/SVG -->
		<dependency>
			<groupId>org.apache.xmlgraphics</groupId>
			<artifactId>batik-transcoder</artifactId>
			<version>1.7</version>
		</dependency>
		<dependency>
			<groupId>org.apache.xmlgraphics</groupId>
			<artifactId>batik-codec</artifactId>
			<version>1.7</version>
		</dependency>
		<dependency>
			<groupId>avalon-framework</groupId>
			<artifactId>avalon-framework</artifactId>
			<version>4.1.5</version>
		</dependency>
		<dependency>
			<groupId>org.apache.xmlgraphics</groupId>
			<artifactId>xmlgraphics-commons</artifactId>
			<version>1.2</version>
		</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.0</version>
</dependency>
<dependency>
	<groupId>rhino</groupId>
<artifactId>js</artifactId>
<version>1.7R2</version>
</dependency>

	</dependencies>
	<reporting>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-javadoc-plugin</artifactId>
				<version>2.7</version>
				<configuration>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.codehaus.mojo</groupId>
				<artifactId>cobertura-maven-plugin</artifactId>
				<version>2.4</version>
			</plugin>
		</plugins>
	</reporting>
</project>


text:
const uint8_t UPDATE_DURRATION = 5;

class Effects{
  public:
    Effects();
    void init();
    void run();
    void setTempo(uint16_t tempo);
    void setSoundInfo(Sound* sound);
    void changeEffect();

  private:
    unsigned long lastRun;
    uint8_t cEffect;
    Effect* currEffect;

    Spin spin;
    Levels levels;
    ShiftFade shiftFade;

    Adafruit_NeoPixel strip;
    EffectData data;
};
#endif


text:
#ifndef GL_CONTEXT_H
#define GL_CONTEXT_H

#include "gl-shadowstate.h"
#include "gl-objects.h"
#include "gl-object-namespace.h"
#include "gl-statesetters.h"

#include <DGLCommon/gl-types.h>
#include <DGLCommon/gl-entrypoints.h>
#include <DGLNet/protocol/msgutils.h>

#include <vector>
#include <queue>
#include <map>
#include <memory>

class DGLDisplayState;

namespace dglState {

class GLContextVersion {
   public:
    enum class Type {
        DT,
        ES,
        UNSUPPORTED,
    };
    GLContextVersion(Type type, int majorVersion = 0, int minorVersion = 0);

    bool check(Type type, int majorVersion = 0, int minorVersion = 0) const;
    void initialize(const char* cVersion);

    int getMajor() const;

    int getNeededApiLibraries(const DGLDisplayState* display);

   private:
    bool m_Initialized;
    int m_MajorVersion;
    int m_MinorVersion;
    Type m_Type;
};

class NativeSurfaceBase;

class GLContextCreationData {
   public:
    GLContextCreationData();
    GLContextCreationData(Entrypoint entryp, opaque_id_t pixelFormat,
                          const std::vector<gl_t>& attribs);
    Entrypoint getEntryPoint() const;
    opaque_id_t getPixelFormat() const;
    const std::vector<gl_t>& getAttribs() const;

   private:
    Entrypoint m_Entrypoint;
    opaque_id_t m_pixelFormat;
    std::vector<gl_t> m_attribs;
};

class GLAuxContext;

class GLContext {
   public:
    GLContext(const DGLDisplayState* dpy, GLContextVersion version,
              opaque_id_t id, const GLContextCreationData& creationData);
    ~GLContext();

    dglnet::message::utils::ContextReport describe();

    NativeSurfaceBase* getNativeReadSurface() const;
    NativeSurfaceBase* getNativeDrawSurface() const;
    void setNativeSurfaces(NativeSurfaceBase* read, NativeSurfaceBase* draw);

    std::shared_ptr<dglnet::DGLResource> queryTexture(gl_t name);
    std::shared_ptr<dglnet::DGLResource> queryBuffer(gl_t name);
    std::shared_ptr<dglnet::DGLResource> queryFramebuffer(gl_t bufferEnum);
    std::shared_ptr<dglnet::DGLResource> queryFBO(gl_t name);
    std::shared_ptr<dglnet::DGLResource> queryRenderbuffer(gl_t name);
    std::shared_ptr<dglnet::DGLResource> queryShader(gl_t name);
    std::shared_ptr<dglnet::DGLResource> queryProgram(gl_t name);
    std::shared_ptr<dglnet::DGLResource> queryGPU();
    std::shared_ptr<dglnet::DGLResource> queryState(gl_t name);

    /**
     * FBO attachment query
     * used for FBO and renderbuffer queries. FBO does not need to be bound
     *
     *
     * @param      fboObject             // FBO object being queried
     * @param      attachment            // Queried attachment point of FBO  (like COLOT_ATTACHMENT0)
     * @param      attachmentType        // texture or renderbuffer
     * @param      queryPixels             // reading pixels will be skipped & null returned if false
     * @param[out] outSamples           // out: returned sample count
     * @param[out] outInternalFormat)   // out: returned internalFormat of attachment
     */
    std::shared_ptr<dglnet::resource::DGLPixelRectangle> queryFramebufferAttachment(
        GLuint fboObject,
        GLenum attachment,
        GLenum attachmentType,
        bool queryPixels,
        GLint* outSamples,
        GLint* outInternalFormat);

    /**
     * texture level query (dispatches to API-specific query implementation)
     */
    std::shared_ptr<dglnet::resource::DGLPixelRectangle> queryTextureLevel(
            const GLTextureObj* tex, int level, int layer, size_t face,
            state_setters::PixelStoreAlignment&);

    /**
     * texture level query (OpenGL, using getters)
     */
    std::shared_ptr<dglnet::resource::DGLPixelRectangle>
            queryTextureLevelGetters(
                    const GLTextureObj* tex, int level, int layer, size_t face,
                    state_setters::PixelStoreAlignment& defAlignment);

    /**
     * texture level query (OpenGL ES, using auxiliary context)
     */
    std::shared_ptr<dglnet::resource::DGLPixelRectangle>
            queryTextureLevelAuxCtx(const GLTextureObj* tex, int level, int layer, size_t face);

    bool isTexture1Dim(GLenum target);
    bool isTexture2Dim(GLenum target);

    /**
     * texture level size query (using getters, or bisection)
     */
    void queryTextureLevelSize(const GLTextureObj* tex, GLuint level,
                               GLint* width, GLint* height, GLint* depth);

    bool textureProbeSizeES(GLenum levelTarget, int level, GLenum formatToRequest, GLenum typeToRequest, const int sizes[3]);
    int textureBisectSizeES(GLenum levelTarget, int level, int coord, int maxSize, GLenum formatToRequest, GLenum typeToRequest);

    /**
     * buffer query using getters
     */
    std::shared_ptr<dglnet::DGLResource> queryBufferGetters(GLBufferObj* buff);

    /**
     * buffer query using auxaliary ctx.
     */
    std::shared_ptr<dglnet::DGLResource> queryBufferAuxCtx(GLBufferObj* buff);

    opaque_id_t getId() const;

    std::pair<bool, GLenum> getPokedError();
    GLenum peekError();

    /**
     * Debugger's specific debug message callback
     */
    static void KHRONOS_APIENTRY
            debugOutputCallback(GLenum source, GLenum type, GLuint id,
                                GLenum severity, GLsizei length,
                                const GLchar* message, const GLvoid* userParam);

    /**
     * non-static function called from debug message callback
     */
    void setDebugOutput(GLenum source, GLenum type, GLuint id, GLenum severity,
                        GLsizei length, const GLchar* message,
                        const GLvoid* userParam);

    /**
     * Returns true, if got debug message output
     */
    bool hasDebugOutput();

    /**
     * Returns last debug message
     */
    const std::string& popDebugOutput();

    /**
     * Setter for custom debug message callback, that can be registered by
     * application
     */
    void setCustomDebugOutputCallback(GLDEBUGPROC callback);

    void startQuery();
    bool endQuery(std::string& message);

    /**
     * Called to tell ctx when if is bound to current thread
     */
    void bound();

    /**
     * Called to tell ctx when it is lazy deleted.
     * returns true, if no longer used
     */
    bool markForDeletionMayDelete();

    /**
     * Called to tell ctx when if is unbound from current thread.
     * returns true, if context was marked for deletion and no longer used
     */
    bool unboundMayDelete();

    /**
     * Getter for context version
     */
    const GLContextVersion& getVersion() const;

    enum class ContextCap {
        PixelBufferObjects,
        FramebufferObjects,
        SeparateReadDrawFramebufferObjects,
        DrawBuffersMRT,
        TextureMultisample,
        RenderBufferMultisample,
        TextureQueryStencilBits,
        ReadBuffersFrontBuffer,
        ReadBuffer,
        CanQueryFramebufferAttachmentBitSize,
        MultipleFramebufferAttachments,
        Has64BitGetters,
        HasGetStringI,
        TextureGetters,
        GetBufferSubData,
        MapBuffer,
        GLSLShaders,
        GenericVertexAttribs,
    };

    /**
     * Context capability check
     */
    bool hasCapability(ContextCap) const;

    /**
     * Getter for context creation data
     */
    const GLContextCreationData& getContextCreationData() const;

    /**
     * Auxiliary context getter
     */
    GLAuxContext* getAuxContext();

    /**
     *  Getter for parent display
     */
    const DGLDisplayState* getDisplay() const;

    /**
     * Getter for shadow state;
     */
    inline GLContextShadowState& shadow() { return m_ShadowState; }

    /**
     * Getter for objects shadow namespace
     */
    inline GLObjectNameSpaces& ns() { return m_ObjectNamespace; }

   private:
    void queryCheckError();

    void firstUse();

    /**
     * API version of underlying GL context
     */
    GLContextVersion m_Version;

    /**
     * WGL or other native API context ID
     */
    opaque_id_t m_Id;

    /**
     * Handle to native surface (drawable), read
     */
    NativeSurfaceBase* m_NativeReadSurface;

    /**
     * Handle to native surface (drawable), draw
     */
    NativeSurfaceBase* m_NativeDrawSurface;

    /**
     * Queue for errors poked from glGetError(), not yet delivered to
     * application
     */
    std::queue<GLenum> m_PokedErrorQueue;

    /**
     * Set if NVX_gpu_memory_info is present
     */
    bool m_HasNVXMemoryInfo;

    /**
     * Set to if pending message from debug output is present
     */
    bool m_HasDebugOutput;

    /**
     * Pending message from debug output
     */
    std::string m_DebugOutput;

    /**
     * Custom debug message callback registered by application
     */
    GLDEBUGPROC m_DebugOutputCallback;

    /**
     * Get state element (using glGetIntegerv)
     */
    void getStateIntegerv(
            const char* name, GLenum value, size_t length,
            dglnet::resource::utils::StateItem* ret);

    /**
    * Get state element (using glGetInteger64v)
    */
    void getStateInteger64v(
            const char* name, GLenum value, size_t length,
            dglnet::resource::utils::StateItem* ret);

    /**
     * Get state element (using glGetFloatv)
     */
    void getStateFloatv(
            const char* name, GLenum value, size_t length,
            dglnet::resource::utils::StateItem* ret);

    /**
     * Get state element (using glGetDoublev)
     */
    void getStateDoublev(
            const char* name, GLenum value, size_t length,
            dglnet::resource::utils::StateItem* ret);

    /**
     * Get state element (using glGetBooleanv)
     */
    void getStateBooleanv(
            const char* name, GLenum value, size_t length,
            dglnet::resource::utils::StateItem* ret);

    /**
     * Get state element (using glIsEnabled)
     */
    void getStateIsEnabled(
            const char* name, GLenum value, size_t,
            dglnet::resource::utils::StateItem* ret);

    /**
     * True if ctx was ever bound, false otherwise
     */
    bool m_EverBound;

    /**
     * Number of threads this context is bound to
     */
    int m_RefCount;

    /**
     * True if deletion is pending
     */
    bool m_ToBeDeleted;

    /**
     * True if queries are now performed on contexts
     */
    bool m_InQuery;

    /**
     * Context creation data - context attributes used on creation of this ctx.
     */
    GLContextCreationData m_CreationData;

    /**
     * Auxiliary context (used on demand, when query cannot be performed on this
     * ctx).
     */
    std::shared_ptr<GLAuxContext> m_AuxContext;

    /**
     * Parent display
     */
    const DGLDisplayState* m_Display;

    /**
     * Shadowed state containter
     *
     * All non-query-able state goes in here
     */
    GLContextShadowState m_ShadowState;

    /**
     * Namespace of shadows for specific GL objects
     */
    GLObjectNameSpaces m_ObjectNamespace;

};

}    // namespace
#endif


text:
#include "CmnTrainers.h"

#include "TrainerInstance.h"

class CTrainersManager :
	public ITrainersContainer
{
public:
	CTrainersManager(void);
	~CTrainersManager(void);

	void				SetAppFolder(CString& csFolder);

	void				CreateContainer();
	void				ReleaseContainer();

	void				LoadInstalledTrainers();
	void				AddTrainer(CString& csPluginFilePath, CString& csPluginFileName);

// ITrainersContainer declarations section
public:
	ENUMERATOR(mTrainers, ITrainer*, CreateEnumerator, GetNextTrainer, posTrainersEnum)

// IObject declarations section
	virtual CString			GetClassString();
	virtual void			QueryInterface(int iIDD, void** ppvObject);

private:
	CList<CTrainerInstance*, CTrainerInstance*>	mTrainerInstances;
	CList<ITrainer*, ITrainer*>					mTrainers;

	CString					csAppFolder;
};


text:
package com.vaadin.tests.components.twincolselect;

import java.util.LinkedHashMap;

import com.vaadin.tests.components.abstractlisting.AbstractMultiSelectTestUI;
import com.vaadin.ui.TwinColSelect;

public class TwinColSelectTestUI
        extends AbstractMultiSelectTestUI<TwinColSelect<Object>> {

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    protected Class<TwinColSelect<Object>> getTestClass() {
        return (Class) TwinColSelect.class;
    }

    @Override
    protected void createActions() {
        super.createActions();
        createRows();
    }

    private void createRows() {
        LinkedHashMap<String, Integer> options = new LinkedHashMap<>();
        options.put("0", 0);
        options.put("1", 1);
        options.put("2", 2);
        options.put("5", 5);
        options.put("10 (default)", 10);
        options.put("50", 50);

        createSelectAction("Rows", CATEGORY_STATE, options, "10 (default)",
                (c, value, data) -> c.setRows(value), null);
    }
}


text:
<resources>
    <string name="app_name">Feel Good*</string>

    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>

    <string name="country_prompt">Choose your country</string>

    <string-array name="country_arrays">
        <item>Lebanon</item>
        <item>Jordan</item>
        <item>Palestine</item>
        <item>Syria</item>
        <item>Iraq</item>
        <item>Bahrain</item>
        <item>Kuwait</item>
        <item>UAE</item>
        <item>Saudi Arabia</item>
        <item>Yemen</item>
        <item>Oman</item>
        <item>Egypt</item>
        <item>Tunisia</item>
        <item>Algeria</item>
        <item>Morocco</item>
        <item>Sudan</item>
        <item>South Sudan</item>
        <item>Qatar</item>
        <item>Mauritania</item>
    </string-array>

    <color name="bgblue">#ADD8E6</color>
</resources>


text:
/*
 * Copyright 2015 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.netty.handler.codec.http2;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Utility methods for hpack tests.
 */
public final class HpackBenchmarkUtil {
    private HpackBenchmarkUtil() {
    }

    /**
     * Internal key used to index a particular set of headers in the map.
     */
    private static class HeadersKey {
        final HpackHeadersSize size;
        final boolean limitToAscii;

        HeadersKey(HpackHeadersSize size, boolean limitToAscii) {
            this.size = size;
            this.limitToAscii = limitToAscii;
        }

        List<HpackHeader> newHeaders() {
            return size.newHeaders(limitToAscii);
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }

            HeadersKey that = (HeadersKey) o;

            if (limitToAscii != that.limitToAscii) {
                return false;
            }
            return size == that.size;
        }

        @Override
        public int hashCode() {
            int result = size.hashCode();
            result = 31 * result + (limitToAscii ? 1 : 0);
            return result;
        }
    }

    private static final Map<HeadersKey, List<HpackHeader>> headersMap;

    static {
        HpackHeadersSize[] sizes = HpackHeadersSize.values();
        headersMap = new HashMap<HeadersKey, List<HpackHeader>>(sizes.length * 2);
        for (HpackHeadersSize size : sizes) {
            HeadersKey key = new HeadersKey(size, true);
            headersMap.put(key, key.newHeaders());

            key = new HeadersKey(size, false);
            headersMap.put(key, key.newHeaders());
        }
    }

    /**
     * Gets headers for the given size and whether the key/values should be limited to ASCII.
     */
    static List<HpackHeader> headers(HpackHeadersSize size, boolean limitToAscii) {
        return headersMap.get(new HeadersKey(size, limitToAscii));
    }

    static Http2Headers http2Headers(HpackHeadersSize size, boolean limitToAscii) {
        List<HpackHeader> hpackHeaders = headersMap.get(new HeadersKey(size, limitToAscii));
        Http2Headers http2Headers = new DefaultHttp2Headers(false);
        for (int i = 0; i < hpackHeaders.size(); ++i) {
            HpackHeader hpackHeader = hpackHeaders.get(i);
            http2Headers.add(hpackHeader.name, hpackHeader.value);
        }
        return http2Headers;
    }
}


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

namespace Tupling
{
    class Program
    {
        static void Main(string[] args)
        {
            var builder = new ContainerBuilder();

            builder.RegisterType<HandleString>().As<IHandler<string>>().SingleInstance();
            builder.RegisterType<HandleInt>().As<IHandler<int>>().SingleInstance();
            var dic = new Dictionary<string, Tuple<Type, Func<object>>>();
            dic.Add("adfas", Tuple.Create (typeof(object), (Func<object>)null));
            Console.WriteLine("Hello World!");
        }
    }

    class HandleString : IHandler<string>
    {
        public void Handle(string parameter)
        {
            Console.WriteLine("Handling string");
        }
    }

    class HandleInt : IHandler<int>
    {
        public void Handle(int parameter)
        {
            Console.WriteLine("Handling int");
        }
    }

    interface IHandler<T>
    {
        void Handle(T parameter);
    }
}


text:
require 'rails_helper'
RSpec.feature 'Pages' do
  it 'visits as normal user' do
    user = create(:user)
    page_object = create(:page, visible: true, public: true, title: 'Motioner')
    create(:page_element, :text, page: page_object, visible: true)
    create(:page_element, :image, page: page_object, visible: true)

    sign_in_as(user, path: page_path(page_object))
    page.status_code.should eq(200)
    find('.headline h1').text.should eq('Motioner')
    page.should_not have_css('.col-md-12 a.pull-right')
  end
end


text:
<?php
/**
 * Config-file for Anax, theme related settings, return it all as array.
 *
 */
return [

    /**
     * Settings for Which theme to use, theme directory is found by path and name.
     *
     * path: where is the base path to the theme directory, end with a slash.
     * name: name of the theme is mapped to a directory right below the path.
     */
    'settings' => [
        'path' => ANAX_INSTALL_PATH . 'theme/',
        'name' => 'anax-grid',
        'cache-less' => false, // change to true in production
    ],

    /**
     * Add default views.
     */
    'views' => [
        [
            'region' => 'header',
            'template' => 'default/header',
            'data' => [],
            'sort' => -1
        ],
        [
            'region' => 'footer',
            'template' => 'default/footer',
            'data' => [],
            'sort' => -1
        ],
        [
            'region' => 'flash',
            'template' => 'default/flash',
            'data' => [],
            'sort' => -1
        ],
        [
            'region' => 'navbar',
            'template' => [
                'callback' => function() {
                    return $this->di->navbar->create();
                },
            ],
            'data' => [],
            'sort' => -1,
        ],
    ],

    /**
     * Data to extract and send as variables to the main template file.
     */
    'data' => [

        // Language for this page.
        'lang' => 'en',

        // Append this value to each <title>
        'title_append' => ' | QA-Science',

        // Stylesheets
        'stylesheets' => [

        ],

        // Lesssheets
        'lesssheets' => [
            'style.less',
            'font-awesome-4.1.0/font-awesome.less',
        ],

        // Inline style
        'style' => null,

        // Favicon
        'favicon' => 'favicon.ico',

        // Path to modernizr or null to disable
        //'modernizr' => 'js/modernizr.js',

        // Path to jquery or null to disable
        //'jquery' => '//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js',

        // Array with javscript-files to include
        'javascript_include' => [

        ],

        // Use google analytics for tracking, set key or null to disable
        'google_analytics' => null,
    ],
];


text:
<?xml version="1.0" encoding="utf-8"?>
<set
  xmlns:android="http://schemas.android.com/apk/res/android">
    <rotate android:duration="1500" android:fromDegrees="0.0" android:toDegrees="360.0" android:pivotX="50.0%" android:pivotY="50.0%" android:repeatCount="infinite" />
</set>


text: CRITICAL: (db02.local lagging 199405 seconds) (db03.local 22 seconds) (db04.local 21 seconds)


text:
require File.dirname(__FILE__) + '/helper'

context 'AmbitiousSphinx Adapter :: Select' do

  specify 'Ruby attributes become Sphinx fields prefixed with @' do
    query = User.select {|m| m.name}.to_hash[:query]
    query.should == "name:"
  end

  specify 'Ruby string becomes Sphinx string' do
    query = User.select {'jon'}.to_hash[:query]
    query.should == %Q("jon")
  end

  specify 'Ruby string becomes Sphinx phrase search' do
    query = User.select {'jon doe'}.to_hash[:query]
    query.should == "\"jon doe\""
  end

  specify 'Ruby == should not be supported' do
    should.raise do User.select {|m| m.name == 'jon'} end
  end

  specify 'Ruby != becomes Sphinx NOT operator' do
    should.raise do User.select {|m| m.name != 'jon'} end
  end

  specify 'Ruby && becomes Sphinx AND operator' do
    query = User.select {'jon' && 'blarg'}.to_hash[:query]
    query.should == %Q("jon" AND "blarg")
  end

  specify 'Ruby || becomes Sphinx OR operator' do
    query = User.select { 'jon' || 'chris'}.to_hash[:query]
    query.should == %Q("jon" OR "chris")
  end

  specify 'Ruby =~ with string' do
    query = User.select {|m| m.name =~ 'chris'}.to_hash[:query]
    query.should == %Q(name:"chris")
  end

  specify 'Ruby =~ with string' do
    query = User.select {|m| m.name =~ 'chris' && m.name =~ 'jon'}.to_hash[:query]
    query.should == %Q(name:"chris" AND name:"jon")
  end

  specify 'Ruby =~ with Regexp' do
    should.raise do User.select {|m| m.name =~ /chris/} end
  end

  specify 'Ruby !~ with string' do
    query = User.select {|m| m.name =~ 'chris' && m.name !~ 'jon'}.to_hash[:query]
    query.should == %Q(name:"chris" AND NOT name:"jon")
  end

  specify 'Ruby !~ with Regexp is not supported' do
    should.raise do User.select {|m| m.name !~ /chris/} end
  end

  specify 'Ruby > should not be supported' do
    should.raise do User.select {|m| m.age > 21} end
  end

  specify 'Ruby >= should not be supported' do
    should.raise do User.select {|m| m.age >= 21} end
  end

  specify 'Ruby < should not be supported' do
    should.raise do User.select {|m| m.age < 21} end
  end

  specify 'Ruby <= should not be supported' do
    should.raise do User.select {|m| m.age <= 21} end
  end

  xspecify 'inspect' do
    User.select { |u| u.name }.inspect.should.match %r(call #to_s or #to_hash)
  end
end


text:
// Copyright (C) 2009 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.gerrit.server.query;

import java.util.Collections;
import java.util.List;

/** Negates the result of another predicate. */
public final class NotPredicate extends Predicate {
  private final Predicate that;

  public NotPredicate(final Predicate that) {
    this.that = that;
  }

  @Override
  public Predicate not() {
    return that;
  }

  @Override
  public List<Predicate> getChildren() {
    return Collections.singletonList(that);
  }

  @Override
  public int hashCode() {
    return ~that.hashCode();
  }

  @Override
  public boolean equals(final Object other) {
    return other instanceof NotPredicate
        && getChildren().equals(((Predicate) other).getChildren());
  }

  @Override
  public String toString() {
    return "-" + that.toString();
  }
}


text:
/**
 * Provides classes which hold informations useful to other classes.
 *
 * @author Detlef G. Herm, 2016-09-26
 * @since 1.0
 *
 */
package de.herm_detlef.java.application;