text:
package rest

import "strings"

// route recursively route a (sub)resource request
func (r *requestHandler) route(path string, lookup *Lookup, resources map[string]*subResource) {
	// Split the path into path components
	c := strings.Split(path, "/")

	if len(c) == 0 {
		return
	}

	// Shift the resource name from the path components
	name, c := c[0], c[1:]

	// First component must match a resource
	if sr, found := resources[name]; found {
		resource := sr.resource
		if len(c) >= 1 {
			// If there are some components left, the path targets an item or an alias

			// Shift the item id from the path components
			var id string
			id, c = c[0], c[1:]

			// Handle sub-resources (/resource1/id1/resource2/id2)
			if len(c) >= 1 {
				subName := c[0]
				if sub, found := resource.resources[subName]; found {
					// Check if the item exists before going farther
					lookup.Fields["id"] = id
					l, err := resource.handler.Find(lookup, 1, 1)
					if err != nil {
						r.sendError(err)
						return
					} else if len(l.Items) == 0 {
						r.sendError(NotFoundError)
						return
					}
					// Move item's current id to the sub resource's filter
					delete(lookup.Fields, "id")
					lookup.Fields[sub.field] = id
					path = strings.Join(c, "/")
					r.route(path, lookup, resource.resources)
				} else {
					r.sendError(&Error{404, "Resource not found", nil})
				}
				return
			}

			// Handle aliases (/resource/alias or /resource1/id1/resource2/alias)
			if alias, found := resource.aliases[id]; found {
				// Apply aliases query to the request
				q := r.req.URL.Query()
				for key, values := range alias {
					for _, value := range values {
						q.Add(key, value)
					}
				}
				r.handleResourceRequest(resource, lookup)
				return
			}

			// Set the id filter
			lookup.Fields["id"] = id

			r.handleItemRequest(resource, lookup)
		} else {
			r.handleResourceRequest(resource, lookup)
		}
	} else {
		r.sendError(&Error{404, "Resource not found", nil})
	}
}

func (r *requestHandler) handleResourceRequest(resource *Resource, lookup *Lookup) {
	switch r.req.Method {
	case "OPTIONS":
		methods := []string{}
		if resource.conf.isModeAllowed(List) {
			methods = append(methods, "HEAD", "GET")
		}
		if resource.conf.isModeAllowed(Create) {
			methods = append(methods, "POST")
		}
		if resource.conf.isModeAllowed(Clear) {
			methods = append(methods, "DELETE")
		}
		r.res.Header().Set("Allow", strings.Join(methods, ", "))
	case "HEAD", "GET":
		if !resource.conf.isModeAllowed(List) {
			r.sendError(InvalidMethodError)
			return
		}
		r.handleListRequestGET(lookup, resource)
	case "POST":
		if !resource.conf.isModeAllowed(Create) {
			r.sendError(InvalidMethodError)
			return
		}
		r.handleListRequestPOST(lookup, resource)
	case "DELETE":
		if !resource.conf.isModeAllowed(Clear) {
			r.sendError(InvalidMethodError)
			return
		}
		r.handleListRequestDELETE(lookup, resource)
	default:
		r.sendError(InvalidMethodError)
	}
}

func (r *requestHandler) handleItemRequest(resource *Resource, lookup *Lookup) {
	switch r.req.Method {
	case "OPTIONS":
		methods := []string{}
		if resource.conf.isModeAllowed(Read) {
			methods = append(methods, "HEAD", "GET")
		}
		if resource.conf.isModeAllowed(Create) || resource.conf.isModeAllowed(Replace) {
			methods = append(methods, "PUT")
		}
		if resource.conf.isModeAllowed(Update) {
			methods = append(methods, "PATCH")
			// See http://tools.ietf.org/html/rfc5789#section-3
			r.res.Header().Set("Allow-Patch", "application/json")
		}
		if resource.conf.isModeAllowed(Update) {
			methods = append(methods, "DELETE")
		}
		r.res.Header().Set("Allow", strings.Join(methods, ", "))
	case "HEAD", "GET":
		if !resource.conf.isModeAllowed(Read) {
			r.sendError(InvalidMethodError)
			return
		}
		r.handleItemRequestGET(lookup, resource)
	case "PUT":
		if !resource.conf.isModeAllowed(Create) && !resource.conf.isModeAllowed(Replace) {
			r.sendError(InvalidMethodError)
			return
		}
		r.handleItemRequestPUT(lookup, resource)
	case "PATCH":
		if !resource.conf.isModeAllowed(Update) {
			r.sendError(InvalidMethodError)
			return
		}
		r.handleItemRequestPATCH(lookup, resource)
	case "DELETE":
		if !resource.conf.isModeAllowed(Delete) {
			r.sendError(InvalidMethodError)
			return
		}
		r.handleItemRequestDELETE(lookup, resource)
	default:
		r.sendError(InvalidMethodError)
	}
}


text:
.. Django Invite documentation master file, created by
   sphinx-quickstart on Tue Nov 11 17:33:12 2014.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to Django Invite's documentation!
=============================================

Contents:

.. toctree::
   :maxdepth: 2

   quickstart
   configuration
   permissions
   password-reset

redpajama_set_name: RedPajamaGithub


text:
using System;
using Convenient.Asserts.Core;

namespace Convenient.Asserts
{
    public class Throws
    {
        public static ExceptionStatementBuilder<TException> A<TException>() where TException : Exception
        {
            return new ExceptionStatementBuilder<TException>();
        }
    }
}


text:
import csv
import pytest

from main import (
    matrix_threat_scope,
    matrix_protection_capability,
    matrix_attack_effectiveness,
    matrix_occurrence,
    matrix_threat_likelihood,
    matrix_harm,
    matrix_valuation,
    matrix_impact,
    matrix_risk,
)

def test_truth():
    assert True

@pytest.fixture
def bra_permutations():
    """Loads the permutations and builds out a dictionary that can be used
    to get all the answers, including intermediate steps."""

    def string_to_bool(s):
        return True if s == "TRUE" else False

    permutations = []

    with open("permutations.tsv", "r") as tsvfile:
        reader = csv.DictReader(tsvfile, dialect="excel-tab")
        for row in reader:
            permutations.append({
                # Questions
                'skills_required':
                    string_to_bool(row["Is skill required?"]),
                'resources_required':
                    string_to_bool(row[
                                       "Does the attack require significant resources?"]),
                'failure_rate':
                    string_to_bool(row["Can the defenses fail?"]),
                'coverage':
                    string_to_bool(row[
                                       "Does the defense cover all access points to the asset?"]),
                'vulnerability_accessible':
                    string_to_bool(row["Are there any pre-conditions to the attack?"]),
                'preconditions':
                    string_to_bool(row["Is the vulnerability always present?"]),
                'asset_cost':
                    string_to_bool(row["Significant repair cost?"]),
                'asset_value':
                    string_to_bool(row["Significant business value?"]),
                'internal':
                    string_to_bool(row["Consequences from internal sources?"]),
                'external':
                    string_to_bool(row["Consequences from external sources?"]),

                # Intermediate matrix calculations
                'matrix_threat_scope': row["Threat"],
                'matrix_protection_capability': row["Protection"],
                'matrix_attack_effectiveness': row["Effectiveness"],
                'matrix_occurrence': row["Occurrence"],
                'matrix_threat_likelihood': row["Likelihood"],
                'matrix_harm': row["Harm"],
                'matrix_valuation': row["Valuation"],
                'matrix_impact': row["Impact"],
                'matrix_likelihood': row["Likelihood"],
                'matrix_risk': row["Risk"],
            })
        return permutations

def test_matrix_threat_scope(bra_permutations):
    for p in bra_permutations:
        assert matrix_threat_scope(
            p["skills_required"], p["resources_required"]
        ) == p["matrix_threat_scope"]

def test_matrix_protection_capability(bra_permutations):
    for p in bra_permutations:
        assert matrix_protection_capability(
            p["failure_rate"], p["coverage"]
        ) == p["matrix_protection_capability"]

def test_matrix_attack_effectiveness(bra_permutations):
    for p in bra_permutations:
        assert matrix_attack_effectiveness(
            p["matrix_threat_scope"],
            p["matrix_protection_capability"]
        ) == p["matrix_attack_effectiveness"]

def test_matrix_occurrence(bra_permutations):
    for p in bra_permutations:
        assert matrix_occurrence(
            p["vulnerability_accessible"], p["preconditions"]
        ) == p["matrix_occurrence"]

def test_matrix_threat_likelihood(bra_permutations):
    for p in bra_permutations:
        assert matrix_threat_likelihood(
            p["matrix_attack_effectiveness"],
            p["matrix_occurrence"]
        ) == p["matrix_threat_likelihood"]

def test_matrix_harm(bra_permutations):
    for p in bra_permutations:
        assert matrix_harm(
            p["internal"], p["external"]
        ) == p["matrix_harm"]

def test_matrix_valuation(bra_permutations):
    for p in bra_permutations:
        assert matrix_valuation(
            p["asset_value"], p["asset_cost"]
        ) == p["matrix_valuation"]

def test_matrix_impact(bra_permutations):
    for p in bra_permutations:
        assert matrix_impact(
            p["matrix_harm"], p["matrix_valuation"]
        ) == p["matrix_impact"]

def test_matrix_risk(bra_permutations):
    for p in bra_permutations:
        assert matrix_risk(
            p["matrix_impact"], p["matrix_likelihood"]
        ) == p["matrix_risk"]


text:
package org.apache.jackrabbit.oak.plugins.blob.db;

import java.sql.Connection;

import org.apache.jackrabbit.oak.spi.blob.AbstractBlobStoreTest;
import org.h2.jdbcx.JdbcConnectionPool;

/**
 * Tests the DbBlobStore implementation.
 */
public class DbBlobStoreTest extends AbstractBlobStoreTest {

    private Connection sentinel;
    private JdbcConnectionPool cp;

    @Override
    public void setUp() throws Exception {
        Class.forName("org.h2.Driver");
        cp = JdbcConnectionPool.create("jdbc:h2:mem:", "", "");
        sentinel = cp.getConnection();
        DbBlobStore blobStore = new DbBlobStore();
        blobStore.setConnectionPool(cp);
        blobStore.setBlockSize(128);
        blobStore.setBlockSizeMin(48);
        this.store = blobStore;
    }

    @Override
    public void tearDown() throws Exception {
        super.tearDown();
        if (sentinel != null) {
            sentinel.close();
        }
        cp.dispose();
    }

    protected int getArtifactSize() {
        return 4160;
    }

}


text:
package scala.pickling
package generator

import scala.reflect.api.Universe

/** This is the portion of code which can actually generate a pickler/unpickler object instance
  * from the IR AST.
  *
  *
  */
private[pickling]  trait SourceGenerator extends Macro with FastTypeTagMacros {
  import c.universe._

  def pickleNull(builder: c.Tree): c.Tree =
    q"""_root_.scala.pickling.Defaults.nullPickler.pickle(null, $builder)"""

  def allowNonExistentField(impl: Tree): c.Tree = {
    q"""try $impl catch {
            case _: _root_.scala.pickling.PicklingException =>
            // TODO - Don't just ignore bad things, figure out how to actually read the class file for reals.
            // We could basically by blocked by scala here, though.
          }"""
  }
  def generatePickleImplFromAst(picklerAst: PicklerAst): c.Tree = {

    def genGetField(x: GetField): c.Tree = {
      def pickleLogic(isStaticallyElided: Boolean, fieldValue: Tree, tpe: Type): Tree = {
        val fieldPickler = c.fresh(newTermName("fieldPickler"))
        val elideHint =
          if (isStaticallyElided) q"b.hintElidedType($fieldPickler.tag)" else q""
        // NOTE; This will look up an IMPLICIT pickler for the value, based on the type.
        //       This is how we chain our macros to find all the valid types.
        q"""
           val $fieldPickler = _root_.scala.Predef.implicitly[_root_.scala.pickling.Pickler[$tpe]]
           $elideHint
           $fieldPickler.pickle($fieldValue, b)"""
      }

      def putField(getterLogic: Tree, isStaticallyElided: Boolean, tpe: Type): c.Tree =
        q"builder.putField(${x.name}, b => ${pickleLogic(isStaticallyElided, getterLogic, tpe)})"

      x.getter match {
        case x: IrField =>
          // TODO - handle
          val tpe = x.tpe[c.universe.type](c.universe)
          val staticallyElided = tpe.isEffectivelyFinal || tpe.isEffectivelyPrimitive
          if(x.isScala || !x.isPublic) {
            // We always have to use reflection for scala fields right now.  Additionally, for Scala fields, we
            // actually have no idea if they exist at runtime, so we allow failure for now, which is EVIL, but we have no alternative.
            val result = reflectivelyGet(newTermName("picklee"), x)(fm => fm)
            val rTerm = c.fresh(newTermName("result"))
            val logic = q"""val $rTerm = { ..$result }
                            ${putField(q"$rTerm.asInstanceOf[$tpe]", staticallyElided, tpe)}"""
            if(x.isScala) allowNonExistentField(logic) else logic
          } else putField(q"picklee.${newTermName(x.fieldName)}", staticallyElided, tpe)
        case _: IrConstructor =>
          // This is a logic erorr
          sys.error(s"Pickling logic error.  Found constructor when trying to pickle field ${x.name}.")
        case y: IrMethod =>
          val tpe = y.returnType(c.universe)
          val staticallyElided = {
            // TODO - Figure this out
            tpe.isEffectivelyFinal || tpe.isEffectivelyPrimitive
          }
          if (y.isPublic) putField(q"picklee.${newTermName(y.methodName)}", staticallyElided, tpe)
          else {
            val result = reflectivelyGet(newTermName("picklee"), y)(fm => putField(q"${fm}.asInstanceOf[${y.returnType(u).asInstanceOf[c.Type]}]", staticallyElided, tpe))
            q"""..$result"""
          }
      }
    }

    def genSubclassDispatch(x: SubclassDispatch): c.Tree = {
      val tpe = x.parent.tpe[c.universe.type](c.universe)
      val clazzName = newTermName("clazz")
        val compileTimeDispatch: List[CaseDef] = (x.subClasses map { subtpe =>
        val tpe = subtpe.tpe[c.universe.type](c.universe)
        CaseDef(Bind(clazzName, Ident(nme.WILDCARD)), q"clazz == classOf[$tpe]", createPickler(tpe, q"builder"))
      })(collection.breakOut)

      val failDispatch = {
        val dispatcheeNames = x.subClasses.map(_.className).mkString(", ")
        val otherTermName = newTermName("other")
        val throwUnknownTag =
          if(x.subClasses.isEmpty) {
            q"""throw _root_.scala.pickling.PicklingException("Class " + clazz + " not recognized by pickler")"""
        } else q"""throw _root_.scala.pickling.PicklingException("Class " + clazz + " not recognized by pickler, looking for one of: " + $dispatcheeNames)"""
        CaseDef(Bind(otherTermName, Ident(nme.WILDCARD)), throwUnknownTag)
      }
      val runtimeDispatch = CaseDef(Ident(nme.WILDCARD), EmptyTree, createRuntimePickler(q"builder"))
      // TODO - Figure out if we can handle runtime dispatch...
      val unknownDispatch =
        if(x.lookupRuntime) List(runtimeDispatch)
        else List(failDispatch)

      val picklerLookup = q"""
        val clazz = if (picklee != null) picklee.getClass else null
        ${Match(q"clazz", compileTimeDispatch ++ unknownDispatch)}
      """
      val subclasses =
        q"""
          val pickler: _root_.scala.pickling.Pickler[_] = $picklerLookup
          pickler.asInstanceOf[_root_.scala.pickling.Pickler[$tpe]].pickle(picklee, builder)
        """
      // If we have parent behavior, we need to do a quick instanceOf check first.
      x.parentBehavior match {
        case None => subclasses
        case Some(b) =>
          val parentTpe = x.parent.tpe[c.universe.type](c.universe)
          val impl = generatePickleImplFromAst(b)
          q"""if(classOf[$parentTpe] == picklee.getClass) $impl else $subclasses"""
      }
    }
    def genPickleEntry(op: PickleEntry): c.Tree = {
      val nested =
        op.ops.toList map genPickleOp
      val oid = c.fresh(newTermName("oid"))
      // TODO - hint known size
      val shareHint: List[c.Tree] =
        if(shareNothing) List(q"()")
        else List(q"val $oid = _root_.scala.pickling.internal.`package`.lookupPicklee(picklee)", q"builder.hintOid($oid)")
      /*val shareLogic: c.Tree =
        if(shareNothing) q"..$nested"
        else q"if($oid == -1) { ..$nested }"*/
      q"""
         ..$shareHint
         builder.beginEntry(picklee, tag)
         ..$nested
         builder.endEntry()
       """
    }
    def genPickleOp(op: PicklerAst): c.Tree =
      op match {
        case PickleBehavior(ops) => q"""..${ops.map(genPickleOp)}"""
        case x: GetField => genGetField(x)
        case x: PickleEntry => genPickleEntry(x)
        case x: SubclassDispatch => genSubclassDispatch(x)
        case x: PickleExternalizable => genExternalizablePickle(newTermName("picklee"), newTermName("builder"), x)
      }
    genPickleOp(picklerAst)
  }

  // Code which will lookup a runtime pickler.
  def createRuntimePickler(builder: c.Tree): c.Tree = q"""
    val classLoader = this.getClass.getClassLoader
    _root_.scala.pickling.internal.GRL.lock()
    val tag = try {
      _root_.scala.pickling.FastTypeTag.mkRaw(clazz, _root_.scala.reflect.runtime.universe.runtimeMirror(classLoader))
    } finally _root_.scala.pickling.internal.GRL.unlock()
    _root_.scala.pickling.internal.`package`.currentRuntime.picklers.genPickler(classLoader, clazz, tag)
  """

  def createPickler(tpe: c.Type, builder: c.Tree): c.Tree = q"""
    val pickler = _root_.scala.Predef.implicitly[_root_.scala.pickling.Pickler[$tpe]]
    pickler
  """

  def checkNullPickle(pickleLogic: c.Tree): c.Tree =
    q"""
        if(null == picklee) {
          _root_.scala.pickling.Defaults.nullPickler.pickle(null, builder)
        } else $pickleLogic"""

  def genPicklerLogic[T: c.WeakTypeTag](picklerAst: PicklerAst): c.Tree = {
    // TODO - The pickler logic should actually check to make sure the thing passed is actually a FOO, and
    //        If it is not, we delegate to a runtime pickler.
    //        ALTHOUGH, we could, instead, delegate that as function of the AST that we can encode, so
    //        The presence of runtime code is controlled by generation algorithms, rather than the code generator.
    //        We could still disable the generation here.
    //        This is somethign the current algorithm does which we do not do.
    checkNullPickle(generatePickleImplFromAst(picklerAst))
  }

  def genUnpicklerLogic[T: c.WeakTypeTag](unpicklerAst: UnpicklerAst): c.Tree = {
    // TODO - Make sure this lines up with existing unpickler logic
    val unpickleLogic = generateUnpickleImplFromAst(unpicklerAst)
    // Handle null + Ref types first
    unpickleNull(unpickleRef(unpickleLogic))
  }

  /** Wraps unpickle logic with the logic on how to handle `null` values.   Assumes the term `tagKey` is available. */
  def unpickleNull(unpickleLogic: c.Tree): c.Tree = {
    q""" if (tagKey == _root_.scala.pickling.FastTypeTag.Null.key) null else $unpickleLogic"""
  }
  /** Wraps unpickle logic with the logic on how to handle `Ref` values.   Assumes the terms `tagKey` and `reader` are available. */
  def unpickleRef(unpickleLogic: c.Tree): c.Tree = {
    q"""if (tagKey == _root_.scala.pickling.FastTypeTag.Ref.key) {
         _root_.scala.Predef.implicitly[_root_.scala.pickling.Unpickler[_root_.scala.pickling.refs.Ref]].unpickle(tagKey, reader)
       } else $unpickleLogic"""
  }

  def readField(name: String, tpe: Type): c.Tree = {
    val readerName = c.fresh(newTermName("reader"))
    val unpicklerName    = c.fresh(newTermName("unpickler$unpickle$"))
    // TODO - is this the right place to do this?
    val staticHint       = if (tpe.isEffectivelyFinal) q"$readerName.hintElidedType($unpicklerName.tag)" else q"";

    val resultName = c.fresh(newTermName("result"))
    // TODO - may be able to drop locally.
      q"""
         _root_.scala.Predef.locally {
           val $readerName = reader.readField($name)
           var $unpicklerName: _root_.scala.pickling.Unpickler[$tpe] = null
           $unpicklerName = _root_.scala.Predef.implicitly[_root_.scala.pickling.Unpickler[$tpe]]
           $staticHint
           val typeString = $readerName.beginEntry()
           val $resultName = $unpicklerName.unpickle(typeString, $readerName)
           $readerName.endEntry()
           $resultName.asInstanceOf[$tpe]
         }
       """
  }

  def genConstructorUnpickle(cons: CallConstructor): c.Tree = {
    // Note, this is a bit ugly.
    var idx = 0
    val names = cons.fieldNames
    val tpess = cons.constructor.parameterTypes[c.universe.type](c.universe)
    val argss =
      tpess map { tpes =>
         tpes map { tpe =>
           val name = names(idx)
           idx += 1
           readField(name, tpe)
         }
      }
    val tpe = cons.constructor.returnType[c.universe.type](c.universe)
    // TODO - Handle reflective case.
    if(cons.requiresReflection) sys.error(s"Unable to reflectively call constructors, currently.")
    else {
      if(cons.constructor.parameterNames.isEmpty) q"""new ${tpe}"""
      else {
        q"new $tpe(...$argss)"
      }
    }
  }
  def genCallModuleFactory(cons: CallModuleFactory): c.Tree = {
    // Note, this is a bit ugly.
    var idx = 0
    val names = cons.fields
    val tpess = cons.factoryMethod.parameterTypes[c.universe.type](c.universe)
    val argss =
      tpess map { tpes =>
        tpes map { tpe =>
          val name = names(idx)
          idx += 1
          readField(name, tpe)
        }
      }
    val tpe = cons.factoryMethod.returnType[c.universe.type](c.universe)
    // TODO - Handle reflective case.
    val result = if(cons.requiresReflection) sys.error(s"Unable to reflectively call factory methods, currently.")
    else {
      if(cons.factoryMethod.parameterNames.isEmpty) q"${tpe}.${newTermName(cons.factoryMethod.methodName)}()"
      else {
        q"${tpe}.${newTermName(cons.factoryMethod.methodName)}(...$argss)"
      }
    }
    result
  }

  /** Creates a `set` operation that reads a value from the pickle and writes it into the object.
    *
    * Note: This assumes there exists a `result` name in scope which is the currently instantiated unpickle object.
    */
  def genSetField(s: SetField): c.Tree = {
    s.setter match {
      case x: IrMethod =>
        x.parameterTypes[c.universe.type ](c.universe) match {
          case List(List(tpe)) =>
            val read = readField(s.name, tpe)
            if(x.isPublic) {
              q"""
                 result.${newTermName(x.methodName)}($read)
               """
            } else reflectivelySet(newTermName("result"), x, read)
          case x => sys.error(s"Cannot handle a setting method that does not take exactly one parameter, found parameters: $x")
        }

      case x: IrField =>
        val tpe = x.tpe[c.universe.type](c.universe)
        val read = readField(s.name, tpe)
        val staticallyElided = tpe.isEffectivelyFinal || tpe.isEffectivelyPrimitive
        if(x.isScala || !x.isPublic || x.isFinal) {
          reflectivelySet(newTermName("result"), x, read)
        } else q"""result.${newTermName(x.fieldName)} = $read"""
    }

  }

  val ShortType = typeOf[Short]
  val CharType = typeOf[Char]
  val IntType = typeOf[Int]
  val LongType = typeOf[Long]
  val FloatType = typeOf[Float]
  val DoubleType = typeOf[Double]
  val BooleanType = typeOf[Boolean]
  /** This will lift any primitive value into  the java-boxed version (usefulf or reflective code.) */
  def liftPrimitives(value: c.Tree, tpe: Type): c.Tree = {
    tpe match {
      case ShortType => q"new _root_.java.lang.Short($value)"
      case CharType => q"new _root_.java.lang.Character($value)"
      case IntType => q"new _root_.java.lang.Integer($value)"
      case LongType => q"new _root_.java.lang.Long($value)"
      case FloatType => q"new _root_.java.lang.Float($value)"
      case DoubleType => q"new _root_.java.lang.Double($value)"
      case BooleanType => q"new _root_.java.lang.Boolean($value)"
      case _ => value
    }
  }

  def createUnpickler(tpe: Type): Tree =
    q"_root_.scala.Predef.implicitly[_root_.scala.pickling.Unpickler[$tpe]]"
  def genSubclassUnpickler(x: SubclassUnpicklerDelegation): c.Tree = {
    val tpe = x.parent.tpe[c.universe.type](c.universe)
    // TODO - Allow runtime pickler lookup if enabled...
    val defaultCase =
      if(x.lookupRuntime) CaseDef(Ident(nme.WILDCARD), EmptyTree, q"_root_.scala.pickling.internal.`package`.currentRuntime.picklers.genUnpickler(_root_.scala.pickling.internal.`package`.currentMirror, tagKey)")
      else CaseDef(Ident(nme.WILDCARD), EmptyTree, q"""throw new _root_.scala.pickling.PicklingException("Cannot unpickle, Unexpected tag: " + tagKey + " not recognized.")""")
    val subClassCases =
       x.subClasses.toList map { sc =>
         val stpe = sc.tpe[c.universe.type](c.universe)
         val skey = stpe.key
         CaseDef(Literal(Constant(skey)), EmptyTree, createUnpickler(stpe))
       }
    val subClass =
      q"""val unpickler: _root_.scala.pickling.Unpickler[_] = ${Match(q"tagKey", subClassCases ++ List(defaultCase))}
        unpickler.asInstanceOf[_root_.scala.pickling.Unpickler[$tpe]].unpickle(tagKey, reader)
        """
    x.parentBehavior match {
      case None => subClass
      case Some(p) =>
        val ptree = generateUnpickleImplFromAst(p)
        q"""if(tagKey == ${tpe.key}) $ptree else $subClass"""
    }
  }
  def genUnpickleSingleton(s: UnpickleSingleton): c.Tree = {
    val tpe = s.tpe.tpe[c.universe.type](c.universe)
    val m = tpe.typeSymbol.asClass.module
    q"$m"
  }

  def genAllocateInstance(x: AllocateInstance): c.Tree = {
    val tpe = x.tpe.tpe[c.universe.type](c.universe)
    q"""_root_.scala.concurrent.util.Unsafe.instance.allocateInstance(classOf[$tpe]).asInstanceOf[$tpe]"""
  }

  def generateUnpickleImplFromAst(unpicklerAst: UnpicklerAst): c.Tree = {
    unpicklerAst match {
      case c: CallConstructor => genConstructorUnpickle(c)
      case c: CallModuleFactory => genCallModuleFactory(c)
      case x: SetField => genSetField(x)
      case x: SubclassUnpicklerDelegation => genSubclassUnpickler(x)
      case x: UnpickleSingleton => genUnpickleSingleton(x)
      case x: AllocateInstance => genAllocateInstance(x)
        // TODO - This is kind of hacky, should be a temproary workaround for a better solution.
      case x: UnpickleExternalizable => genExternalizablUnPickle(newTermName("reader"), x)
      case x: UnpickleBehavior =>
        val behavior = x.operations.map(generateUnpickleImplFromAst).toList
        // TODO - This is kind of hacky.  We're trying to make sure during unpickling we always register/unregister appropriately...
        x.operations match {
          case List() => q"null"
          case List(head: SubclassUnpicklerDelegation) => generateUnpickleImplFromAst(head)
            // TODO - Can we assume that ever additional operation is something which manipualtes the result?
          case hd :: tail =>
            val hdTree = generateUnpickleImplFromAst(hd)
            val tlTree = tail.map(generateUnpickleImplFromAst)
            // Note: We are *always* generating the unpickle sharing code, in the event that
            //       someone pickles with sharing, but we try to unpickle without it.
            q"""_root_.scala.Predef.locally {
                  val oid = _root_.scala.pickling.internal.`package`.preregisterUnpicklee()
                  val result = $hdTree;
                  _root_.scala.pickling.internal.`package`.registerUnpicklee(result, oid)
                  ..$tlTree;
                  result
                }"""
        }
    }
  }

  /** generates the tree which will construct + return a new instance of a Pickler class, capable of
    * pickling an instance of type T, using the behavior outlined by the PicklerAst.
    */
  def generatePicklerClass[T: c.WeakTypeTag](picklerAst: PicklerAst): c.Tree = {
    val tpe = computeType[T]
    val picklerName = c.fresh((syntheticBaseName(tpe) + "Pickler"): TermName)
    val createTagTree = super[FastTypeTagMacros].impl[T]
    q"""
      _root_.scala.Predef.locally {
        implicit object $picklerName extends _root_.scala.pickling.Pickler[$tpe] with _root_.scala.pickling.Generated {
          def pickle(picklee: $tpe, builder: _root_.scala.pickling.PBuilder): _root_.scala.Unit = ${genPicklerLogic[T](picklerAst)}
          def tag: _root_.scala.pickling.FastTypeTag[$tpe] = $createTagTree
        }
        $picklerName
      }
    """
  }

  def generateUnpicklerClass[T: c.WeakTypeTag](unpicklerAst: UnpicklerAst): c.Tree = {
    val tpe = computeType[T]
    val unpicklerName = c.fresh((syntheticBaseName(tpe) + "Unpickler"): TermName)
    val createTagTree = super[FastTypeTagMacros].impl[T]
    val unpickleLogic = genUnpicklerLogic[T](unpicklerAst)
    q"""
       _root_.scala.Predef.locally {
          implicit object $unpicklerName extends  _root_.scala.pickling.Unpickler[$tpe] with _root_.scala.pickling.Generated {
            def unpickle(tagKey: _root_.java.lang.String, reader: _root_.scala.pickling.PReader): _root_.scala.Any = $unpickleLogic
            def tag: _root_.scala.pickling.FastTypeTag[$tpe] = $createTagTree
          }
          $unpicklerName : _root_.scala.pickling.Unpickler[$tpe] with _root_.scala.pickling.Generated
       }
     """
  }

  def generatePicklerUnpicklerClass[T: c.WeakTypeTag](impl: PickleUnpickleImplementation): c.Tree = {
    val tpe = computeType[T]
    val name = c.fresh((syntheticBaseName(tpe) + "PicklerUnpickler"): TermName)
    val createTagTree = super[FastTypeTagMacros].impl[T]
    val unpickleLogic = genUnpicklerLogic[T](impl.unpickle)
    val pickleLogic = genPicklerLogic[T](impl.pickle)
    q"""
       _root_.scala.Predef.locally {
          implicit object $name extends _root_.scala.pickling.AbstractPicklerUnpickler[$tpe] with _root_.scala.pickling.Generated {
            //import _root_.scala.language.existentials
            override def pickle(picklee: $tpe, builder: _root_.scala.pickling.PBuilder): _root_.scala.Unit = $pickleLogic
            override def unpickle(tagKey: _root_.java.lang.String, reader: _root_.scala.pickling.PReader): _root_.scala.Any = $unpickleLogic
            override def tag: _root_.scala.pickling.FastTypeTag[$tpe] = $createTagTree
          }
          $name : _root_.scala.pickling.AbstractPicklerUnpickler[$tpe] with _root_.scala.pickling.Generated
       }
     """
  }

  /** Given a tree which unpickles a value, we regsiter that value with its OID hint so that
    * we can effectively deserialized later references.
    */
  def registerUnPickledRef(instantiationLogic: c.Tree): c.Tree = {
    // TODO - We may not want to ALWAYS do this, some kind of enabling flag...
    val instance = c.fresh(newTermName("instance"))
    // TODO - Rather than using the package object, we should grab the 'current runtime' interface and use that.
    q"""
              val oid = _root_.scala.pickling.internal.`package`.preregisterUnpicklee()
              val $instance = $instantiationLogic
              _root_.scala.pickling.internal.`package`.registerUnpicklee($instance, oid)
              $instance
            """
  }

  def computeType[T: c.WeakTypeTag]: Type = {
    val originalTpe = weakTypeOf[T]
    // Note: this makes it so modules work, things like foo.type.
    //       For some reason we get an issue with not having == defined on Class[_] otherwise.
    // TODO - fix this for certain primitive types, like Null, etc.
    if(originalTpe.termSymbol.isModule) originalTpe.widen
    else originalTpe
  }

  // -- Externalizable Hackery --
  def genExternalizablePickle(target: TermName, builder: TermName, pe: PickleExternalizable): c.Tree = {
    val out = c.fresh(newTermName("out"))
    val objectOutTpe = typeOf[scala.pickling.util.GenObjectOutput]
    val fieldName = "$ext"
    q"""val $out = new _root_.scala.pickling.util.GenObjectOutput
        $target.writeExternal($out)
        $builder.putField($fieldName, b =>
          _root_.scala.pickling.functions.pickleInto($out, b)
        )
     """
  }
  def genExternalizablUnPickle(reader: TermName, pe: UnpickleExternalizable): c.Tree = {
    val tpe = pe.tpe.tpe[c.universe.type](c.universe)
    val readerName = c.fresh(newTermName("readerName"))
    val target = c.fresh(newTermName("out"))
    val objectOutTpe = typeOf[scala.pickling.util.GenObjectOutput]
    val fieldName = "$ext"
    q"""
       val $target = _root_.scala.concurrent.util.Unsafe.instance.allocateInstance(classOf[$tpe]).asInstanceOf[$tpe]
       val $readerName = reader.readField($fieldName)
       val out = {
         val up = _root_.scala.Predef.implicitly[_root_.scala.pickling.Unpickler[$objectOutTpe]]
         up.unpickleEntry($readerName).asInstanceOf[$objectOutTpe]
       }
       val in = out.toInput
       $target.readExternal(in)
       $target
        """
  }

  // ---- Reflective Helper Methods ----

  def reflectivelyGet(target: TermName, value: IrMember)(body: c.Tree => c.Tree): List[c.Tree] = {
    // TODO - Should we use scala reflection?
    // TODO - Should we trap errors and return better error messages?
    // TODO - We should attempt to SAVE the reflective methods/fields somewhere so we aren't
    //        looking them up all the time.
    // TODO - We should handle `owner` and Declared vs. inherited Fields/Methods.
    val valueTree =
      value match {
        case field: IrField =>

          val get = q"""
              _root_.scala.Predef.locally {
                val cls = $target.getClass
                val field = _root_.scala.pickling.internal.Reflect.getField(cls, ${field.javaReflectionName})
                field.setAccessible(true)
                field.get($target)
             }"""
          get

        // Private scala methods may not encode normally for case classes.  This is a hack which goes after the field.
        // TODO - We should update this to look for the accessor method which scala generally exposes for the deconstructor.
        case mthd: IrMethod if mthd.isScala && mthd.isPrivate =>
          val fieldName = mthd.javaReflectionName
          // TODO - We may need to do a specialied lookup for magic named methods.
          q"""_root_.scala.Predef.locally {
                  val mthd = _root_.scala.pickling.internal.Reflect.getMethod($target.getClass, ${mthd.javaReflectionName}, Array())
                  mthd.setAccessible(true)
                  mthd.invoke($target)
                }"""
        case mthd: IrMethod =>
          q"""_root_.scala.Predef.locally {
                  val mthd = _root_.scala.pickling.internal.Reflect.getMethod($target.getClass, ${mthd.javaReflectionName}, Array())
                  mthd.setAccessible(true)
                  mthd.invoke($target)
                }"""
      }
    List(body(valueTree))
  }
  def reflectivelySet(target: TermName, setter: IrMember, value: c.Tree): c.Tree = {
    // TODO - Should we use scala reflection?
    // TODO - Should we trap errors and return better error messages?
    // TODO - We should attempt to SAVE the reflective methods/fields somewhere so we aren't
    //        looking them up all the time.
    setter match {
      case field: IrField =>
        val fieldTerm = c.fresh(newTermName("field"))
        val result = q"""
                 val $fieldTerm = _root_.scala.pickling.internal.Reflect.getField($target.getClass, ${field.javaReflectionName})
                 $fieldTerm.setAccessible(true)
                 $fieldTerm.set($target, ${liftPrimitives(value, field.tpe[c.universe.type](c.universe))})"""
        // Workaround for issues with not being able to accurate read scala symbols.
        if(field.isScala) allowNonExistentField(result) else result
      case mthd: IrMethod =>
        val methodTerm = c.fresh(newTermName("mthd"))
        // TODO - We should ensure types align.
        val List(List(tpe)) = mthd.parameterTypes[c.universe.type](c.universe)
        q"""
                val $methodTerm = _root_.scala.pickling.internal.Reflect.getMethod($target.getClass, ${mthd.javaReflectionName}, Array(classOf[$tpe]))
                $methodTerm.setAccessible(true)
                $methodTerm.invoke($target, ${liftPrimitives(value, tpe)})
              """
    }

  }

  // -- End Reflective Helper Methods --

}


text:
package data;

import java.nio.file.Path;

import data.charArray.IReadableCharArray;
import data.longArray.ILongArray;
import dataContracts.DataFactoryType;

public interface IDataFactory
{
    public IReadableCharArray getCharArray(DataFactoryType dataType, Path filePath);
    public IReadableCharArray createCharArray(char[] chars);
    public ILongArray createLongArray(DataFactoryType dataType, long size);
}


text:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="32dp"
        android:text="Recording"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_below="@+id/textView1"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="37dp"
        android:scaleType="fitXY"
        android:src="@android:drawable/presence_audio_online" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/imageView1"
        android:layout_marginTop="67dp"
        android:layout_toLeftOf="@+id/imageView1"
        android:onClick="start"
        android:text="start" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button1"
        android:layout_alignBottom="@+id/button1"
        android:layout_alignRight="@+id/textView1"
        android:layout_marginRight="40dp"
        android:onClick="stop"
        android:text="stop" />

    <Button
        android:id="@+id/button3"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button2"
        android:layout_centerHorizontal="true"
        android:onClick="play"
        android:text="play" />

</RelativeLayout>


text:
<component name="ProjectRunConfigurationManager">
  <configuration default="false" name="Run" type="NodeJSConfigurationType" factoryName="Node.js" path-to-node="/usr/local/bin/node" path-to-js-file="build/server/www.js" application-parameters="--config ./config.yaml" working-dir="$PROJECT_DIR$">
    <browser url="http://localhost:9090/" />
    <method />
  </configuration>
</component>


text:
<?php

namespace GarageManager;

use GarageManager\Vehicle\Car;
use GarageManager\Vehicle\Bike;

abstract class Helper
{

    // Create garage
    public static function createGarage()
    {
        return new Garage();
    }

    // Get interface type
    private static function getSapiType()
    {
        $sapiType = php_sapi_name();
        switch ($sapiType) {
            case 'cli':
            case 'cli-server':
                return 'cli';
                break;
            case 'apache':
            case 'apache2filter':
            case 'apache2handler':
            case 'fpm-fcgi':
                return 'browser';
                break;
            default:
                return null;
        }
    }

    // Get name of file
    private static function getFileName()
    {
        switch (Helper::getSapiType()) {
            case 'cli':
                if ($GLOBALS['_SERVER']['argc'] == 2) {
                    return trim($GLOBALS['_SERVER']['argv'][1]);
                }
                break;
            case 'browser':
                if (isset($_GET['file'])) {
                    return trim($_GET['file']);
                }
                break;
        }
        return null;
    }

    // Creates Vehicles. Primary source: XML, Secondary: JSON
    public static function createVehicles()
    {
        $file = explode('.', Helper::getFileName());
        $extension = strtolower($file[1]);
        switch ($extension) {
            case 'xml':
                return Helper::createVehiclesXML(Helper::getFileName());
                break;
            case 'json':
                return Helper::createVehiclesJSON(Helper::getFileName());
                break;
            default:
                return null;
        }
    }

    // Create array of Vehicles from XML file
    private static function createVehiclesXML($file)
    {
        $vehicleArray =[];
        $xml = simplexml_load_file($file);
        $temp = json_decode(json_encode($xml), true);

        foreach ($temp['vehicle'] as &$vehicle) {
            // Casting values
            foreach ($vehicle['status']['tires']['tire'] as &$tire) {
                $tire = (float) $tire;
            }
            foreach ($vehicle['status']['engine'] as &$engine) {
                $engine = (int) $engine;
            }
            foreach ($vehicle['status']['break']['discs']['disc'] as &$breakDisc) {
                $breakDisc = (int) $breakDisc;
            }
            $vehicle['status']['break']['oil'] = (int) $vehicle['status']['break']['oil'];
            $vehicle['status']['steering'] = (int) $vehicle['status']['steering'];
            $vehicle['status']['exhaust'] = (int) $vehicle['status']['exhaust'];
            // Removing extra levels
            array_splice($vehicle['status']['tires'], 0, 1, $vehicle['status']['tires']['tire']);
            array_splice($vehicle['status']['break']['discs'], 0, 1, $vehicle['status']['break']['discs']['disc']);
        }
        $temp = $temp['vehicle'];
        //var_dump($temp);
        foreach ($temp as $v) {
            if ($v['type'] == 'car') {
                $vehicleArray[] = new Car($v);
            } elseif ($v['type'] == 'bike') {
                $vehicleArray[] = new Bike($v);
            }
        }
        return $vehicleArray;
    }

    // Create array of Vehicles from JSON file
    private static function createVehiclesJSON($file)
    {
        $vehicleArray = [];
        $json = file_get_contents($file);
        $json = json_decode($json, true);
        foreach ($json as $v) {
            if ($v['type'] == 'car') {
                $vehicleArray[] = new Car($v);
            } elseif ($v['type'] == 'bike') {
                $vehicleArray[] = new Bike($v);
            }
        }
        return $vehicleArray;
    }

    /*
     * DEPRECATED : Create array of Vehicles from XML file
     *
     * private static function createVehiclesXML ($file) {
        $vehicleArray = [];
        $temp = simplexml_load_string(file_get_contents($file), 'SimpleXMLElement', LIBXML_NOCDATA);
        $xml = json_decode(json_encode($temp), TRUE);
        $xml = $xml['vehicle'];
        foreach ($xml as $v) {
            if ($v['type'] == 'car') {
                $vehicleArray[] = new Car($v);
            } elseif($v['type'] == 'bike') {
                $vehicleArray[] = new Bike($v);
            }
        }
        return $vehicleArray;
    }*/
}


text:
package de.saxsys.mvvmfx.utils.itemlist;

import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import static org.assertj.core.api.Assertions.assertThat;

/**
 * Tests for {@link ItemList}.
 *
 * @author sialcasa
 *
 */
public class ItemListTest {

	private static final String PERSON3_NAME = "Person3";
	private static final String PREFIX = "SOME WORDS ";
	// List which comes from the model and should be displayed in a view.
	private ObservableList<Person> listWithModelObjects;
	// Defines the mapping between model elements and view representation
	private ModelToStringFunction<Person> stringMapper;
	// New element which encapsulates and maps the 2 lists
	private ItemList<Person> itemList;
	private Person person1 = new Person("Person1");
	private Person person2 = new Person("Person2");
	private Person person3 = new Person(PERSON3_NAME);

	/**
	 * Prepares the test.
	 */
	@Before
	public void init() {

		// Create the items in the model
		listWithModelObjects = FXCollections.observableArrayList();
		listWithModelObjects.add(person1);
		listWithModelObjects.add(person2);
		listWithModelObjects.add(person3);

		// Create the mapper
		stringMapper = new ModelToStringFunction<Person>() {
			@Override
			public String apply(Person object) {
				return PREFIX + object.name;
			}
		};

		itemList = new ItemList<>(listWithModelObjects, stringMapper);
	}

	/**
	 * Checks whether the mapping from the model to the string representation works.
	 */
	@Test
	public void mapFromModelToString() {
		Assert.assertEquals(PREFIX + PERSON3_NAME, itemList
				.stringListProperty().get(2));
	}

	/**
	 * Check whether the string list changes when the item list changes (add item).
	 */
	@Test
	public void addItemToItemList() {
		Assert.assertEquals(3, itemList.stringListProperty().size());
		Assert.assertEquals(3, listWithModelObjects.size());
		listWithModelObjects.add(new Person("addedPerson"));
		Assert.assertEquals(4, itemList.stringListProperty().size());
		Assert.assertEquals(4, listWithModelObjects.size());
	}

	/**
	 * Check whether the string list changes when the item list changes (remove item).
	 */
	@Test
	public void removeItemFromItemList() {
		Assert.assertEquals(3, itemList.stringListProperty().size());
		Assert.assertEquals(3, listWithModelObjects.size());
		listWithModelObjects.remove(0);
		Assert.assertEquals(2, itemList.stringListProperty().size());
		Assert.assertEquals(2, listWithModelObjects.size());
	}

	@Test
	public void removeMultipleItemsFromItemList() {
		listWithModelObjects.removeAll(person1, person2);
		Assert.assertEquals(1, listWithModelObjects.size());
		Assert.assertEquals(1, itemList.stringListProperty().size());
		Assert.assertEquals(person3, listWithModelObjects.get(0));
		Assert.assertEquals(PREFIX + PERSON3_NAME, itemList
				.stringListProperty().get(0));
	}

	@Test
	public void removeAllItemsFromItemList() {
		listWithModelObjects.clear();
		Assert.assertEquals(0, listWithModelObjects.size());
		Assert.assertEquals(0, itemList.stringListProperty().size());
	}

	@Test
	public void addItemToItemListAtIndex() {
		listWithModelObjects.add(1, new Person("addedPerson"));
		Assert.assertEquals(4, itemList.stringListProperty().size());
		Assert.assertEquals(4, listWithModelObjects.size());
		Assert.assertEquals(PREFIX + "addedPerson", itemList
				.stringListProperty().get(1));
	}

	@Test
	public void addMultipleItemsToItemList() {
		listWithModelObjects.addAll(new Person("added1"), new Person("added2"));
		Assert.assertEquals(5, listWithModelObjects.size());
		Assert.assertEquals(5, itemList.stringListProperty().size());
		Assert.assertEquals(PREFIX + "added1", itemList.stringListProperty()
				.get(3));
		Assert.assertEquals(PREFIX + "added2", itemList.stringListProperty()
				.get(4));
	}

	@Test
	public void replaceItemInItemListAtIndex() {
		listWithModelObjects.set(1, new Person("replacedPerson"));
		Assert.assertEquals(3, listWithModelObjects.size());
		Assert.assertEquals(3, itemList.stringListProperty().size());
		Assert.assertEquals(PREFIX + "replacedPerson", itemList
				.stringListProperty().get(1));
	}

	/**
	 * This test is used to reproduce the bug #281.
	 *
	 * When multiple elements are added to the list in a single method call ({@link ObservableList#addAll(Object[])},
	 * only a single change event should be fired.
	 */
	@Test
	public void addMultipleItemsEventListener() {
		AtomicInteger counter = new AtomicInteger(0);

		itemList.getTargetList().addListener((ListChangeListener<String>) c -> {
			counter.incrementAndGet();
		});

		listWithModelObjects.addAll(new Person("one"), new Person("two"), new Person("three"));

		assertThat(counter.get()).isEqualTo(1);
	}

	@Test
	public void removeMultipleItemsEventListener() {
		AtomicInteger counter = new AtomicInteger(0);

		itemList.getTargetList().addListener((ListChangeListener<String>) c -> {
			counter.incrementAndGet();
		});

		listWithModelObjects.removeAll(person1, person3);

		assertThat(counter.get()).isEqualTo(1);
	}
}


text:
import logging
import os
import re

from .. import parsing
from .. import annotation
from . import BatchCreator

logger = logging.getLogger(__name__)

class FlowcellSubmissionBuilder(object):
    """
    Prepares workflow batch submissions for all unaligned projects
    from a flowcell run.
    """
    def __init__(self, path, endpoint, db, workflow_dir=None,
                 all_workflows=True):
        logger.debug("creating `FlowcellSubmissionBuilder` instance "
                     "for path '{}'".format(path))
        self.path = path
        self.endpoint = endpoint
        self.db = db
        if workflow_dir is not None:
            self.workflow_dir = workflow_dir
        self.all_workflows = all_workflows
        self._init_annotator()

    def _init_annotator(self):
        logger.debug("initializing `FlowcellRunAnnotator` instance")
        path_items = parsing.parse_flowcell_path(self.path)
        self.annotator = annotation.FlowcellRunAnnotator(
            run_id=path_items['run_id'],
            pipeline_root=path_items['pipeline_root'],
            db=self.db
        )

    def get_workflow_options(self, optimized_only=True):
        logger.debug("collecting workflow templates from '{}'"
                     .format(self.workflow_dir))
        workflow_opts = [os.path.join(self.workflow_dir, f)
                         for f in os.listdir(self.workflow_dir)
                         if 'Galaxy-API' not in f
                         and not re.search('^\.', f)
                         and re.search('.txt$', f)]
        workflow_opts.sort()
        logger.debug("found the following workflow options: {}"
                     .format([os.path.basename(f) for f in workflow_opts]))

        if optimized_only:
            workflow_opts = [f for f in workflow_opts
                             if re.search('optimized', f)]
            logger.debug("keeping only optimized workflows: {}"
                         .format([os.path.basename(f) for f in workflow_opts]))

        return workflow_opts

    def _get_project_paths(self):
        unaligned_path = self.annotator.get_unaligned_path()
        logger.debug("collecting unaligned projects in '{}'"
                     .format(unaligned_path))
        self.project_paths = [os.path.join(unaligned_path, p)
                              for p in self.annotator.get_projects()]
        self.project_paths.sort()
        logger.debug("found the following unaligned projects: {}"
                     .format([os.path.basename(os.path.normpath(f))
                              for f in self.project_paths]))

    def _assign_workflows(self):
        workflow_opts = self.get_workflow_options(
            optimized_only=not self.all_workflows
        )
        build_opts = ['GRCh38.77', 'GRCh38.91', 'NCBIM37.67', 'GRCm38.91', 'hg19', 'mm10', 'mm9', 'ebv']
        self._get_project_paths()

        continue_assign = True
        batch_map = {}
        while continue_assign:
            print("\nFound the following projects: "
                  "[current workflows (w) and builds (b) selected]")
            for i, p in enumerate(self.project_paths):
                opts_p = map(lambda x: x[0],
                             filter(lambda x: p in x[1], batch_map.items()))

                w_p = ['w:{}'.format([w for w, k in enumerate(workflow_opts)
                                      if k == opt[0]][0])
                       for opt in opts_p]
                b_p = ['b:{}'.format(opt[1]) for opt in opts_p]
                s_p = ['stranded' if opt[2] else 'unstranded'
                       for opt in opts_p]

                print("   {} : {} {}".format(i, os.path.basename(p),
                                             zip(w_p, b_p, s_p)))

            p_i = raw_input("\nType the number of the project you wish "
                            "to select or hit enter to finish: ")

            if len(p_i):
                selected_project = self.project_paths[int(p_i)]

                for j, w in enumerate(workflow_opts):
                    print("   {} : {}".format(j, os.path.basename(w)))
                w_j = raw_input(("\nSelect the number of the workflow to use "
                                 "for project {}: ")
                                .format(os.path.basename(selected_project)))
                selected_workflow = workflow_opts[int(w_j)]

                for j, b in enumerate(build_opts):
                    print("   {} : {}".format(j, b))
                b_j = raw_input(("\nSelect the genome build (and release, "
                                 "if applicable) to use for project {}: ")
                                .format(os.path.basename(selected_project)))
                selected_build = build_opts[int(b_j)]

                s_j = raw_input("\nIs the library type stranded? (y/[n]): ")
                stranded = s_j == 'y'

                batch_key = (selected_workflow, selected_build, stranded)
                batch_map.setdefault(batch_key, []).append(
                    selected_project
                )
                logger.debug("current state of batch map: {}"
                             .format(batch_map))
            else:
                continue_assign = False
        self.batch_map = batch_map

    def _get_batch_tags(self, paths):
        group_tag = parsing.get_flowcell_id(self.path)
        subgroup_tags = [parsing.get_project_label(p) for p in paths]

        return group_tag, subgroup_tags

    def run(self, sort=False, num_samples=None):
        if not hasattr(self, 'batch_map'):
            self._assign_workflows()

        batch_paths = []
        for batchkey, projects in self.batch_map.items():
            workflow, build, stranded = batchkey

            # Need to handle new version of BaseSpace directory structure,
            # Old dir structure:
            # Project Folder -> Lib Folder -> fastq.gz file(s)
            # New dir structure:
            # Project Folder -> FASTQ Folder -> Lib Folder -> fastq.gz file(s)
            for i in range(0, len(projects)):
                # If new structure, there should only be one FASTQ folder.
                # IF old structure, first folder should contain a libID
                subdir = [s for s in os.listdir(projects[i])
                          if not re.search('DS_Store', s)][0]

                logger.debug("Subdirectory of {} identified as {}"
                             .format(projects[i], subdir))

                if (not re.search('lib[0-9]+', subdir) and
                    not re.search('DS_Store', subdir)):
                    logger.debug("New BaseSpace dir type. Moving from {} to {}"
                                 .format(projects[i], subdir))
                    projects[i] = os.path.join(projects[i], subdir)

            logger.info("Building batch for workflow '{}' and build '{}' "
                        "with samples from projects: {}"
                        .format(os.path.basename(workflow), build, projects))
            group_tag, subgroup_tags = self._get_batch_tags(projects)

            creator = BatchCreator(
                paths=projects,
                workflow_template=workflow,
                endpoint=self.endpoint,
                base_dir=self.path,
                submit_dir='globus_batch_submission',
                group_tag=group_tag,
                subgroup_tags=subgroup_tags,
                sort=sort,
                num_samples=num_samples,
                build=build,
                stranded=stranded
            )
            batch_paths.append(creator.create_batch())
            logger.debug("workflow batch parameters saved in file '{}'"
                         .format(batch_paths[-1]))

        return batch_paths


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

namespace Testity.Common
{
	[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, Inherited = true)]
	public class ImplementationRequiresTypeAttribute : ImplementationMetadataAttribute
	{
		public readonly Type ImplementationType;

		public ImplementationRequiresTypeAttribute(EngineType type, Type typeObj)
			: base(type)
		{
			ImplementationType = typeObj;
	}
	}
}


text:
<?php

/**
* <auto-generated>
*     This code was generated by Codezu.
*
*     Changes to this file may cause incorrect behavior and will be lost if
*     the code is regenerated.
* </auto-generated>
*/

namespace Mozu\Api\Resources\Commerce\Orders\Attributedefinition;

use Mozu\Api\Clients\Commerce\Orders\Attributedefinition\AttributeClient;
use Mozu\Api\ApiContext;

/**
* Use the Order Attribute Definition resource to manage the attributes that uniquely describe orders, such as the associated shopping season or "How did you hear about us?" information. Merchants can display order attributes on the order summary, the order confirmation page, invoices, or packing slips.
*/
class AttributeResource {

		private $apiContext;

	public function __construct(ApiContext $apiContext)
	{
		$this->apiContext = $apiContext;
	}

	/**
	* Retrieves a list of order attributes according to any filter criteria or sort options.
	*
	* @param string $filter A set of expressions that consist of a field, operator, and value and represent search parameter syntax when filtering results of a query. Valid operators include equals (eq), does not equal (ne), greater than (gt), less than (lt), greater than or equal to (ge), less than or equal to (le), starts with (sw), or contains (cont). For example - "filter=IsDisplayed+eq+true"
	* @param int $pageSize The number of results to display on each page when creating paged results from a query. The maximum value is 200.
	* @param string $responseFields Use this field to include those fields which are not included by default.
	* @param string $sortBy The property by which to sort results and whether the results appear in ascending (a-z) order, represented by ASC or in descending (z-a) order, represented by DESC. The sortBy parameter follows an available property. For example: "sortBy=productCode+asc"
	* @param int $startIndex When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with a PageSize of 25, to get the 51st through the 75th items, use startIndex=3.
	* @return AttributeCollection
	* @deprecated deprecated since version 1.17
	*/
	public function getAttributes($startIndex =  null, $pageSize =  null, $sortBy =  null, $filter =  null, $responseFields =  null)
	{
		$mozuClient = AttributeClient::getAttributesClient($startIndex, $pageSize, $sortBy, $filter, $responseFields);
		$mozuClient = $mozuClient->withContext($this->apiContext);
		$mozuClient->execute();
		return $mozuClient->getResult();

	}

/**
	* Retrieves a list of order attributes according to any filter criteria or sort options.
	*
	* @param string $filter A set of expressions that consist of a field, operator, and value and represent search parameter syntax when filtering results of a query. Valid operators include equals (eq), does not equal (ne), greater than (gt), less than (lt), greater than or equal to (ge), less than or equal to (le), starts with (sw), or contains (cont). For example - "filter=IsDisplayed+eq+true"
	* @param int $pageSize The number of results to display on each page when creating paged results from a query. The maximum value is 200.
	* @param string $responseFields Use this field to include those fields which are not included by default.
	* @param string $sortBy The property by which to sort results and whether the results appear in ascending (a-z) order, represented by ASC or in descending (z-a) order, represented by DESC. The sortBy parameter follows an available property. For example: "sortBy=productCode+asc"
	* @param int $startIndex When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with a PageSize of 25, to get the 51st through the 75th items, use startIndex=3.
	* @return Promise - use $promise->then(sucessfn, errorfn). successFn is passed Mozu\Api\MozuResult. errorFn is passed Mozu\Api\ApiException
	*/
	public function getAttributesAsync($startIndex =  null, $pageSize =  null, $sortBy =  null, $filter =  null, $responseFields =  null)
	{
		$mozuClient = AttributeClient::getAttributesClient($startIndex, $pageSize, $sortBy, $filter, $responseFields);
		$mozuClient = $mozuClient->withContext($this->apiContext);
		return $mozuClient->executeAsync();

	}

	/**
	* Returns the list of vocabulary values defined for the order attribute specified in the request.
	*
	* @param string $attributeFQN The fully qualified name of the attribute, which is a user defined attribute identifier.
	* @return array|AttributeVocabularyValue
	* @deprecated deprecated since version 1.17
	*/
	public function getAttributeVocabularyValues($attributeFQN)
	{
		$mozuClient = AttributeClient::getAttributeVocabularyValuesClient($attributeFQN);
		$mozuClient = $mozuClient->withContext($this->apiContext);
		$mozuClient->execute();
		return $mozuClient->getResult();

	}

/**
	* Returns the list of vocabulary values defined for the order attribute specified in the request.
	*
	* @param string $attributeFQN The fully qualified name of the attribute, which is a user defined attribute identifier.
	* @return Promise - use $promise->then(sucessfn, errorfn). successFn is passed Mozu\Api\MozuResult. errorFn is passed Mozu\Api\ApiException
	*/
	public function getAttributeVocabularyValuesAsync($attributeFQN)
	{
		$mozuClient = AttributeClient::getAttributeVocabularyValuesClient($attributeFQN);
		$mozuClient = $mozuClient->withContext($this->apiContext);
		return $mozuClient->executeAsync();

	}

	/**
	* Retrieves the details of the order attribute specified in the request.
	*
	* @param string $attributeFQN The fully qualified name of the attribute, which is a user defined attribute identifier.
	* @param string $responseFields Use this field to include those fields which are not included by default.
	* @return Attribute
	* @deprecated deprecated since version 1.17
	*/
	public function getAttribute($attributeFQN, $responseFields =  null)
	{
		$mozuClient = AttributeClient::getAttributeClient($attributeFQN, $responseFields);
		$mozuClient = $mozuClient->withContext($this->apiContext);
		$mozuClient->execute();
		return $mozuClient->getResult();

	}

/**
	* Retrieves the details of the order attribute specified in the request.
	*
	* @param string $attributeFQN The fully qualified name of the attribute, which is a user defined attribute identifier.
	* @param string $responseFields Use this field to include those fields which are not included by default.
	* @return Promise - use $promise->then(sucessfn, errorfn). successFn is passed Mozu\Api\MozuResult. errorFn is passed Mozu\Api\ApiException
	*/
	public function getAttributeAsync($attributeFQN, $responseFields =  null)
	{
		$mozuClient = AttributeClient::getAttributeClient($attributeFQN, $responseFields);
		$mozuClient = $mozuClient->withContext($this->apiContext);
		return $mozuClient->executeAsync();

	}

	/**
	* Create and save a new attribute. These attributes are used in products and product options.
	*
	* @param string $responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
	* @param Attribute $attribute Properties of an attribute used to describe customers or orders.
	* @return Attribute
	* @deprecated deprecated since version 1.17
	*/
	public function createAttribute($attribute, $responseFields =  null)
	{
		$mozuClient = AttributeClient::createAttributeClient($attribute, $responseFields);
		$mozuClient = $mozuClient->withContext($this->apiContext);
		$mozuClient->execute();
		return $mozuClient->getResult();

	}

/**
	* Create and save a new attribute. These attributes are used in products and product options.
	*
	* @param string $responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
	* @return Promise - use $promise->then(sucessfn, errorfn). successFn is passed Mozu\Api\MozuResult. errorFn is passed Mozu\Api\ApiException
	*/
	public function createAttributeAsync($attribute, $responseFields =  null)
	{
		$mozuClient = AttributeClient::createAttributeClient($attribute, $responseFields);
		$mozuClient = $mozuClient->withContext($this->apiContext);
		return $mozuClient->executeAsync();

	}

	/**
	* Updates an existing attribute with attribute properties to set.
	*
	* @param string $attributeFQN Fully qualified name for an attribute.
	* @param string $responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
	* @param Attribute $attribute Properties of an attribute used to describe customers or orders.
	* @return Attribute
	* @deprecated deprecated since version 1.17
	*/
	public function updateAttribute($attribute, $attributeFQN, $responseFields =  null)
	{
		$mozuClient = AttributeClient::updateAttributeClient($attribute, $attributeFQN, $responseFields);
		$mozuClient = $mozuClient->withContext($this->apiContext);
		$mozuClient->execute();
		return $mozuClient->getResult();

	}

/**
	* Updates an existing attribute with attribute properties to set.
	*
	* @param string $attributeFQN Fully qualified name for an attribute.
	* @param string $responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss.
	* @return Promise - use $promise->then(sucessfn, errorfn). successFn is passed Mozu\Api\MozuResult. errorFn is passed Mozu\Api\ApiException
	*/
	public function updateAttributeAsync($attribute, $attributeFQN, $responseFields =  null)
	{
		$mozuClient = AttributeClient::updateAttributeClient($attribute, $attributeFQN, $responseFields);
		$mozuClient = $mozuClient->withContext($this->apiContext);
		return $mozuClient->executeAsync();

	}

}

?>


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package tests.gl_320.draw;

import com.jogamp.opengl.GL;
import static com.jogamp.opengl.GL2ES3.*;
import com.jogamp.opengl.GL3;
import com.jogamp.opengl.util.GLBuffers;
import com.jogamp.opengl.util.glsl.ShaderCode;
import com.jogamp.opengl.util.glsl.ShaderProgram;
import framework.BufferUtils;
import glm.glm;
import glm.mat._4.Mat4;
import framework.Profile;
import framework.Semantic;
import framework.Test;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;

/**
 *
 * @author GBarbieri
 */
public class Gl_320_draw_without_vertex_attrib extends Test {

    public static void main(String[] args) {
        Gl_320_draw_without_vertex_attrib gl_320_draw_without_vertex_attrib = new Gl_320_draw_without_vertex_attrib();
    }

    public Gl_320_draw_without_vertex_attrib() {
        super("gl-320-draw-without-vertex-attrib", Profile.CORE, 3, 2);
    }

    private final String SHADERS_SOURCE = "draw-without-vertex-attrib";
    private final String SHADERS_ROOT = "src/data/gl_320/draw";

    private int programName, uniformTransform;
    private IntBuffer bufferName = GLBuffers.newDirectIntBuffer(1), vertexArrayName = GLBuffers.newDirectIntBuffer(1);
    private FloatBuffer clearDepth = GLBuffers.newDirectFloatBuffer(new float[]{1.0f});
    private FloatBuffer clearColor = GLBuffers.newDirectFloatBuffer(new float[]{0.0f, 0.0f, 0.0f, 1.0f});

    @Override
    protected boolean begin(GL gl) {

        GL3 gl3 = (GL3) gl;

        boolean validated = true;

        if (validated) {
            validated = initBuffer(gl3);
        }
        if (validated) {
            validated = initProgram(gl3);
        }
        if (validated) {
            validated = initVertexArray(gl3);
        }

        return validated && checkError(gl3, "begin");
    }

    private boolean initProgram(GL3 gl3) {

        boolean validated = true;

        // Create program
        if (validated) {

            ShaderCode vertShader = ShaderCode.create(gl3, GL_VERTEX_SHADER, this.getClass(), SHADERS_ROOT, null,
                    SHADERS_SOURCE, "vert", null, true);
            ShaderCode fragShader = ShaderCode.create(gl3, GL_FRAGMENT_SHADER, this.getClass(), SHADERS_ROOT, null,
                    SHADERS_SOURCE, "frag", null, true);

            ShaderProgram program = new ShaderProgram();
            program.add(vertShader);
            program.add(fragShader);

            program.init(gl3);

            programName = program.program();

            gl3.glBindFragDataLocation(programName, Semantic.Frag.COLOR, "color");

            program.link(gl3, System.out);
        }
        // Get variables locations
        if (validated) {

            uniformTransform = gl3.glGetUniformBlockIndex(programName, "Transform");
            gl3.glUniformBlockBinding(programName, uniformTransform, Semantic.Uniform.TRANSFORM0);
        }

        return validated & checkError(gl3, "initProgram");
    }

    private boolean initBuffer(GL3 gl3) {

        IntBuffer uniformBufferOffset = GLBuffers.newDirectIntBuffer(1);

        gl3.glGenBuffers(1, bufferName);

        gl3.glGetIntegerv(GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT, uniformBufferOffset);

        int uniformBlockSize = Math.max(Mat4.SIZE, uniformBufferOffset.get(0));

        gl3.glBindBuffer(GL_UNIFORM_BUFFER, bufferName.get(0));
        gl3.glBufferData(GL_UNIFORM_BUFFER, uniformBlockSize, null, GL_DYNAMIC_DRAW);
        gl3.glBindBuffer(GL_UNIFORM_BUFFER, 0);

        BufferUtils.destroyDirectBuffer(uniformBufferOffset);

        return checkError(gl3, "initBuffer");
    }

    private Boolean initVertexArray(GL3 gl3) {

        gl3.glGenVertexArrays(1, vertexArrayName);
        gl3.glBindVertexArray(vertexArrayName.get(0));
        gl3.glBindVertexArray(0);

        return checkError(gl3, "initVertexArray");
    }

    @Override
    protected boolean render(GL gl) {

        GL3 gl3 = (GL3) gl;

        {
            gl3.glBindBuffer(GL_UNIFORM_BUFFER, bufferName.get(0));
            ByteBuffer pointer = gl3.glMapBufferRange(
                    GL_UNIFORM_BUFFER, 0, Mat4.SIZE,
                    GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT);

            Mat4 projection = glm.perspective_((float) Math.PI * 0.25f, (float) windowSize.x / windowSize.y, 0.1f, 100.0f);
            Mat4 model = new Mat4(1.0f);

            pointer.asFloatBuffer().put(projection.mul(viewMat4()).mul(model).toFa_());

            // Make sure the uniform buffer is uploaded
            gl3.glUnmapBuffer(GL_UNIFORM_BUFFER);
        }

        gl3.glViewport(0, 0, windowSize.x, windowSize.y);

        gl3.glClearBufferfv(GL_DEPTH, 0, clearDepth);
        gl3.glClearBufferfv(GL_COLOR, 0, clearColor);

        gl3.glUseProgram(programName);
        gl3.glBindVertexArray(vertexArrayName.get(0));
        gl3.glBindBufferBase(GL_UNIFORM_BUFFER, Semantic.Uniform.TRANSFORM0, bufferName.get(0));

        gl3.glDrawArraysInstanced(GL_TRIANGLES, 0, 6, 1);

        return true;
    }

    @Override
    protected boolean end(GL gl) {

        GL3 gl3 = (GL3) gl;
        gl3.glDeleteProgram(programName);
        gl3.glDeleteVertexArrays(1, vertexArrayName);
        gl3.glDeleteBuffers(1, bufferName);

        BufferUtils.destroyDirectBuffer(vertexArrayName);
        BufferUtils.destroyDirectBuffer(bufferName);
        BufferUtils.destroyDirectBuffer(clearColor);
        BufferUtils.destroyDirectBuffer(clearDepth);

        return true;
    }
}


text:
package ubic.basecode.math;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import cern.colt.list.DoubleArrayList;
import cern.colt.list.IntArrayList;
import cern.colt.list.ObjectArrayList;

/**
 * Calculate rank statistics for arrays.
 *
 * @author Paul Pavlidis
 *
 */
public class Rank {

    /**
     * Return a permutation which puts the array in sorted order. In other words, the values returned indicate the
     * positions of the sorted values in the original array (the lowest value has the lowest rank, but it could
     * be located anywhere in the array). Indexes start from 0. Tied values are put in an arbitrary ordering.
     *
     * @param array
     * @return
     */
    public static IntArrayList order( DoubleArrayList array ) {
        int size = array.size();
        IntArrayList result = new IntArrayList( new int[size] );

        ObjectArrayList ranks = new ObjectArrayList( size );
        for ( int i = 0; i < size; i++ ) {
            RankData<Double> rd = new RankData<>( i, array.get( i ) );
            ranks.add( rd );
        }
        ranks.sort();

        for ( int i = 0; i < size; i++ ) {
            @SuppressWarnings("unchecked")
            RankData<Double> rd = ( RankData<Double> ) ranks.getQuick( i );
            result.setQuick( i, rd.getIndex() );
        }
        return result;
    }

    /**
     * @param ranks
     * @return
     */
    public static long rankSum( List<Double> ranks ) {
        double sum = 0.0;
        for ( Double rank : ranks ) {
            sum += rank;
        }
        return ( long ) sum;
    }

    /**
     * Rank transform an array. The ranks are constructed based on the sort order of the elements. That is, low values
     * get low numbered ranks starting from 1.
     *

     * Ties are resolved by assigning the average rank for tied values. For example, instead of arbitrarily assigning
     * ties ranks 3,4,5, all three values would get a rank of 4 and no value would get a rank of 3 or 5.
     *

     * Missing values are sorted in their natural order, which means they end up all at one end (at the high ('bad')
     * end)
     *
     * @param array DoubleArrayList
     * @return cern.colt.list.DoubleArrayList
     * @param array, or null if the ranks could not be computed.
     * @return
     */
    public static DoubleArrayList rankTransform( DoubleArrayList array ) {
        return rankTransform( array, false );
    }

    /**
     * Rank transform an array. The ranks are constructed based on the sort order of the elements. That is, low values
     * get low numbered ranks starting from 1, unless you set descending = true.
     *

     * Ties are resolved by assigning the average rank for tied values. For example, instead of arbitrarily assigning
     * ties ranks 3,4,5, all three values would get a rank of 4 and no value would get a rank of 3 or 5.
     *

     * Missing values are sorted in their natural order, which means they end up all at one end (at the high ('bad')
     * end)
     *
     * @param array DoubleArrayList
     * @param descending - reverse the usual ordering so larger values are the the front.
     * @return cern.colt.list.DoubleArrayList, or null if the input is empty or null.
     */
    public static DoubleArrayList rankTransform( DoubleArrayList array, boolean descending ) {
        if ( array == null ) {
            return null;
        }

        int size = array.size();
        if ( size == 0 ) {
            return null;
        }

        List<RankData<Double>> ranks = new ArrayList<RankData<Double>>( size );
        DoubleArrayList result = new DoubleArrayList( new double[size] );

        // store the values with their indices - not sorted yet.
        for ( int i = 0; i < size; i++ ) {
            double v = array.get( i );

            if ( descending ) {
                v = -v;
            }
            RankData<Double> rd = new RankData<Double>( i, v );
            // if ( Double.isNaN( v ) ) throw new IllegalArgumentException( "Missing values are not tolerated." );
            ranks.add( rd );
        }

        Collections.sort( ranks );

        // fill in the results. We iterate over the ranks by order.
        Double prevVal = null;
        int rank = 1;
        int nominalRank = 1; // rank we'd have if no ties.
        for ( int i = 0; i < size; i++ ) {
            RankData<Double> rankData = ranks.get( i );
            int index = rankData.getIndex();
            Double val = rankData.getValue();

            result.set( index, nominalRank ); // might not keep.

            // only bump up ranks if we're not tied with the last one.
            if ( prevVal != null && !val.equals( prevVal ) ) {
                rank = nominalRank;
            } else {
                // tied. Do not advance the rank.
                result.set( index, rank );
            }

            prevVal = val;
            nominalRank++;
        }

        // At this point we may have repeated ranks.

        fixTies( result, ranks );

        return result;
    }

    /**
     * Rank transform a map, where the values are Comparable values we wish to rank. Ties are broken as for the other
     * methods. Ranks are zero-based
     *

     * Missing values are sorted in their natural order, which means they end up all at one end (at the high ('bad')
     * end)
     *
     * @param m java.util.Map with keys Objects, values Doubles.
     * @return A java.util.Map keys=old keys, values=java.lang.Double rank of the key. Non-integer values mean tie
     *         splits.
     */
    public static <K> Map<K, Double> rankTransform( Map<K, ? extends Comparable<?>> m ) {
        return rankTransform( m, false );
    }

    /**
     * Ties are broken as for the other methods. CAUTION - ranks start at 0.
     *

     * Missing values are sorted in their natural order, which means they end up all at one end (at the high ('bad')
     * end)
     *
     * @param <K>
     * @param m
     * @param desc if true, the lowest (first) rank will be for the highest value.
     * @return A java.util.Map keys=old keys, values=java.lang.Double rank of the key. Non-integer values mean tie
     *         splits.
     */
    public static <K> Map<K, Double> rankTransform( Map<K, ? extends Comparable<?>> m, boolean desc ) {

        List<KeyAndValueData<K>> values = new ArrayList<KeyAndValueData<K>>();

        for ( Iterator<K> itr = m.keySet().iterator(); itr.hasNext(); ) {

            K key = itr.next();
            Comparable<?> val = m.get( key );

            values.add( new KeyAndValueData<K>( 0, key, val ) );
        }

        return rankTransform( m, desc, values );
    }

    /**
     * @param ranksWithTies
     */
    private static void fixTies( DoubleArrayList ranksWithTies, List<? extends RankData<?>> ranks ) {

        int numties = 1;
        Double prev = null;
        int i = 0;
        // iterate over in order of the values.
        for ( int j = ranksWithTies.size(); i < j; i++ ) {
            RankData<?> rankData = ranks.get( i );
            int index = rankData.getIndex();
            double rank = ranksWithTies.getQuick( index );

            if ( prev != null ) {
                if ( rank == prev.doubleValue() ) {
                    // record how many ties we have seen
                    numties++;
                    // System.err.println( "Tied rank: " + rank );
                } else if ( numties > 1 ) {
                    // we're past the batch of ties and need to adjust them
                    for ( int k = 1; k <= numties; k++ ) {
                        int indexOfTied = ranks.get( i - k ).getIndex(); // original rank?
                        double rawRankInTie = ranksWithTies.getQuick( indexOfTied );
                        double meanRank = meanRank( rawRankInTie, numties );
                        ranksWithTies.setQuick( indexOfTied, meanRank );
                    }
                    numties = 1; // reset
                }
                // no tie, nothing needs to be changed.
            }
            prev = rank;
        }

        // cleanup the end of the array if there were ties there.
        if ( numties > 1 ) {
            for ( int k = 1; k <= numties; k++ ) {
                int indexOfTied = ( ( RankData<?> ) ranks.get( i - k ) ).getIndex();
                double rawRankInTie = ranksWithTies.getQuick( indexOfTied );
                double meanRank = meanRank( rawRankInTie, numties );
                ranksWithTies.setQuick( indexOfTied, meanRank );
            }
        }

    }

    /**
     * @param <K>
     * @param ranksWithTies
     * @param ranks
     */
    private static <K> void fixTies( Map<K, Double> ranksWithTies, List<KeyAndValueData<K>> ranks ) {
        int numties = 1;
        Double prev = null;
        int i = 0;
        // iterate over in order of the values.
        for ( int j = ranksWithTies.size(); i < j; i++ ) {
            KeyAndValueData<K> rankData = ranks.get( i );
            double rank = ranksWithTies.get( rankData.getKey() );
            if ( prev != null ) {
                if ( rank == prev.doubleValue() ) {
                    // record how many ties we have seen
                    numties++;
                    // System.err.println( "Tied rank: " + rank );
                } else if ( numties > 1 ) {
                    // we're past the batch of ties and need to adjust them
                    for ( int k = 1; k <= numties; k++ ) {
                        K indexOfTied = ranks.get( i - k ).getKey(); // original key
                        double rawRankInTie = ranksWithTies.get( indexOfTied );
                        double meanRank = meanRank( rawRankInTie, numties );
                        ranksWithTies.put( indexOfTied, meanRank );
                    }
                    numties = 1; // reset
                }
                // no tie, nothing needs to be changed.
            }
            prev = rank;
        }

        // cleanup the end of the array if there were ties there.
        if ( numties > 1 ) {
            for ( int k = 1; k <= numties; k++ ) {
                K indexOfTied = ranks.get( i - k ).getKey();
                double rawRankInTie = ranksWithTies.get( indexOfTied );
                double meanRank = meanRank( rawRankInTie, numties );
                ranksWithTies.put( indexOfTied, meanRank );
            }
        }
    }

    /**
     * @param rawRank
     * @param numties
     * @return
     */
    private static double meanRank( double rawRank, int numties ) {
        double total = 0;
        for ( int i = 0; i < numties; i++ ) {
            total = total + rawRank + i;
        }
        return total / numties;
    }

    /**
     * @param m
     * @param desc
     * @param values this gets sorted.
     * @return A java.util.Map keys=old keys, values=java.lang.Double rank of the key. Non-integer values mean tie
     *         splits.
     */
    @SuppressWarnings("unchecked")
    private static <K> Map<K, Double> rankTransform( Map<K, ? extends Comparable<?>> m, boolean desc,
            List<KeyAndValueData<K>> values ) {

        Collections.sort( values );
        Map<K, Double> result = new HashMap<K, Double>();

        Double rank = 0.0;
        Comparable<K> prevVal = null;
        Double nominalRank = 0.0; // rank we'd have if no ties.
        for ( int i = 0; i < m.size(); i++ ) {
            result.put( values.get( i ).getKey(), ( double ) nominalRank ); // might not keep.

            Comparable<K> val = values.get( i ).getValue();
            // only bump up ranks if we're not tied with the last one.
            if ( prevVal != null && !val.equals( prevVal ) ) {
                rank = nominalRank;
            } else {
                // tied. Do not advance the rank.
                result.put( values.get( i ).getKey(), rank );
            }

            prevVal = val;
            nominalRank++;

        }

        fixTies( result, values );

        if ( desc ) {
            /*
             * Reverse all the values.
             */
            Map<K, Double> finalResult = new HashMap<K, Double>();
            double mr = result.size();
            for ( K k : result.keySet() ) {
                double d = result.get( k );
                finalResult.put( k, mr - d - 1.0 );
            }
            return finalResult;
        }

        return result;
    }
}

/*
 * Helper class for rankTransform map.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
class KeyAndValueData<K> extends RankData {
    private K key;

    public KeyAndValueData( int index, K id, Comparable<?> v ) {
        super( index, v );
        this.key = id;
    }

    public int compareTo( KeyAndValueData<K> other ) {
        return this.value.compareTo( other.getValue() );
    }

    public K getKey() {
        return key;
    }
}

/*
 * Helper class for rankTransform .
 */
class RankData<C extends Comparable<C>> implements Comparable<RankData<C>> {

    int index = 0;

    C value = null;

    public RankData( int tindex, C tvalue ) {
        index = tindex;
        value = tvalue;
    }

    @Override
    public int compareTo( RankData<C> other ) {
        return this.value.compareTo( other.getValue() );
    }

    @SuppressWarnings("unchecked")
    @Override
    public boolean equals( Object obj ) {
        if ( obj == null ) return false;
        if ( !( obj instanceof RankData ) ) return false;
        return this.value.equals( ( ( RankData<C> ) obj ).getValue() );
    }

    public int getIndex() {
        return index;
    }

    public C getValue() {
        return value;
    }

    @Override
    public int hashCode() {
        if ( value == null ) return 1;
        return value.hashCode();
    }

    @Override
    public String toString() {
        return "Index=" + index + " value=" + value;
    }
}


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.service.health;

import com.yahoo.component.annotation.Inject;
import com.yahoo.config.model.api.ApplicationInfo;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.vespa.applicationmodel.ClusterId;
import com.yahoo.vespa.applicationmodel.ConfigId;
import com.yahoo.vespa.applicationmodel.ServiceStatus;
import com.yahoo.vespa.applicationmodel.ServiceStatusInfo;
import com.yahoo.vespa.applicationmodel.ServiceType;
import com.yahoo.vespa.service.duper.DuperModelManager;
import com.yahoo.vespa.service.executor.RunletExecutorImpl;
import com.yahoo.vespa.service.manager.HealthMonitorApi;
import com.yahoo.vespa.service.manager.MonitorManager;
import com.yahoo.vespa.service.monitor.ServiceId;

import java.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Manages all /state/v1/health related monitoring.
 *
 * @author hakon
 */
public class HealthMonitorManager implements MonitorManager, HealthMonitorApi {
    // Weight the following against each other:
    //  - The number of threads N working on health checking
    //  - The health request timeout T
    //  - The max staleness S of the health of an endpoint
    //  - The ideal staleness I of the health of an endpoint
    //
    // The largest zone is main.prod.us-west-1:
    //  - 314 tenant host admins
    //  - 7 proxy host admins
    //  - 3 config host admins
    //  - 3 config servers
    // for a total of E = 327 endpoints
    private static final int MAX_ENDPOINTS = 500;
    private static final Duration HEALTH_REQUEST_TIMEOUT = Duration.ofSeconds(1);
    private static final Duration TARGET_HEALTH_STALENESS = Duration.ofSeconds(10);
    private static final Duration MAX_HEALTH_STALENESS = Duration.ofSeconds(60);
    static final int THREAD_POOL_SIZE = (int) Math.ceil(MAX_ENDPOINTS * HEALTH_REQUEST_TIMEOUT.toMillis() / (double) MAX_HEALTH_STALENESS.toMillis());

    // Keep connections alive 60 seconds (>=MAX_HEALTH_STALENESS) if a keep-alive value has not be
    // explicitly set by the server.
    private static final Duration KEEP_ALIVE = Duration.ofSeconds(60);

    private final ConcurrentHashMap<ApplicationId, ApplicationHealthMonitor> healthMonitors = new ConcurrentHashMap<>();
    private final DuperModelManager duperModel;
    private final ApplicationHealthMonitorFactory applicationHealthMonitorFactory;

    @Inject
    public HealthMonitorManager(DuperModelManager duperModel) {
        this(duperModel, new StateV1HealthModel(TARGET_HEALTH_STALENESS,
                                                HEALTH_REQUEST_TIMEOUT,
                                                KEEP_ALIVE,
                                                new RunletExecutorImpl(THREAD_POOL_SIZE)));
    }

    private HealthMonitorManager(DuperModelManager duperModel, StateV1HealthModel healthModel) {
        this(duperModel, id -> new ApplicationHealthMonitor(id, healthModel));
    }

    /** Default access due to testing. */
    HealthMonitorManager(DuperModelManager duperModel,
                         ApplicationHealthMonitorFactory applicationHealthMonitorFactory) {
        this.duperModel = duperModel;
        this.applicationHealthMonitorFactory = applicationHealthMonitorFactory;
    }

    @Override
    public void applicationActivated(ApplicationInfo application) {
        if (duperModel.isSupportedInfraApplication(application.getApplicationId())) {
            healthMonitors
                    .computeIfAbsent(application.getApplicationId(), applicationHealthMonitorFactory::create)
                    .monitor(application);
        }
    }

    @Override
    public void applicationRemoved(ApplicationId id) {
        ApplicationHealthMonitor monitor = healthMonitors.remove(id);
        if (monitor != null) {
            monitor.close();
        }
    }

    @Override
    public void bootstrapComplete() {
    }

    @Override
    public ServiceStatusInfo getStatus(ApplicationId applicationId,
                                       ClusterId clusterId,
                                       ServiceType serviceType,
                                       ConfigId configId) {
        ApplicationHealthMonitor monitor = healthMonitors.get(applicationId);

        if (monitor == null) {
            return new ServiceStatusInfo(ServiceStatus.NOT_CHECKED);
        }

        return monitor.getStatus(applicationId, clusterId, serviceType, configId);
    }

    @Override
    public List<ApplicationId> getMonitoredApplicationIds() {
        return Collections.list(healthMonitors.keys());
    }

    @Override
    public Map<ServiceId, ServiceStatusInfo> getServices(ApplicationId applicationId) {
        ApplicationHealthMonitor applicationHealthMonitor = healthMonitors.get(applicationId);
        if (applicationHealthMonitor == null) {
            return Map.of();
        }

        return applicationHealthMonitor.getAllServiceStatuses();
    }
}