package spark.debugger

import java.io._

import scala.collection.immutable
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

import spark.Logging

/**
 * Writes events to an event log on disk.
 */
class EventLogWriter {
  private var eventLog: Option[EventLogOutputStream] = None
  setEventLogPath(Option(System.getProperty("spark.arthur.logPath")))
  private val checksumVerifier = new ChecksumVerifier
  val subscribers = new ArrayBuffer[EventLogEntry => Unit]

  def setEventLogPath(eventLogPath: Option[String]) {
    eventLog =
      for {
        elp <- eventLogPath
        file = new File(elp)
        if !file.exists
      } yield new EventLogOutputStream(new FileOutputStream(file))
  }

  def subscribe(callback: EventLogEntry => Unit) {
    subscribers.append(callback)
  }

  def log(entry: EventLogEntry) {
    for (l <- eventLog) {
      l.writeObject(entry)
    }
    entry match {
      case c: ChecksumEvent => checksumVerifier.verify(c)
      case _ => {}
    }
    for (s <- subscribers) {
      s(entry)
    }
  }

  def flush() {
    for (l <- eventLog) {
      l.flush()
    }
  }

  def stop() {
    for (l <- eventLog) {
      l.close()
    }
  }
}

package spark.debugger

import java.io._
import java.util.UUID

import scala.collection.immutable
import scala.collection.mutable
import scala.collection.mutable.ArrayBuffer

import spark.Logging

/**
 * Writes events to an event log on disk. Logging is thread-safe.
 */
class EventLogWriter extends Logging {
  private var eventLog: Option[EventLogOutputStream] = None
  setEventLogPath(Option(System.getProperty("spark.debugger.logPath")))
  private val checksumVerifier = new ChecksumVerifier
  val subscribers = new ArrayBuffer[EventLogEntry => Unit]

  def setEventLogPath(eventLogPath: Option[String]) {
    val path = eventLogPath.getOrElse {
      val dir = System.getProperty("spark.local.dir", System.getProperty("java.io.tmpdir"))
      new File(dir, "spark-debugger-event-log-" + UUID.randomUUID).getPath
    }
    val file = new File(path)
    if (!file.exists) {
      logInfo("Writing to event log %s".format(path))
      eventLog = Some(new EventLogOutputStream(new FileOutputStream(file)))
    } else {
      logWarning("Event log %s already exists".format(path))
      eventLog = None
    }
  }

  def subscribe(callback: EventLogEntry => Unit) {
    subscribers.append(callback)
  }

  def log(entry: EventLogEntry) {
    for (l <- eventLog) {
      l.writeObject(entry)
    }
    entry match {
      case c: ChecksumEvent => checksumVerifier.verify(c)
      case _ => {}
    }
    for (s <- subscribers) {
      s(entry)
    }
  }

  def flush() {
    for (l <- eventLog) {
      l.flush()
    }
  }

  def stop() {
    for (l <- eventLog) {
      l.close()
    }
  }
}

Debug to a temp file by default

Debug to a temp file by default


package controllers

import play.api._
import play.api.mvc._

object Plugin extends Controller {
  def route(path: String) : Action[AnyContent] = Action {
    Ok("Done")
  }
}

package controllers

import org.mozilla.javascript.Context
import org.mozilla.javascript.Function
import org.mozilla.javascript.Scriptable
import play.api._
import play.api.mvc._

// FIXME: Move GamePlugin and its related classes, traits and objects to beyond package.
private trait GamePlugin {
  // FIXME: Pass request parameters along with path and
  // make it possible to return the result asynchronously.
  def handle(path: String): String
}

// FIXME: Handle script errors.
private object GamePlugin {
  def apply(): GamePlugin = {
    // FIXME: Don't hardcode plugin source code here.
    val source = "function handle(path) { return 'Hello ' + path; }"
    val cx: Context = Context.enter()
    try {
      val scope: Scriptable = cx.initStandardObjects()
      cx.evaluateString(scope, source, "source", 1, null)
      // FIXME: Don't hardcode the name of handler function.
      // FIXME: handler might be Scriptable.NOT_FOUND if there is no function named "handle".
      // Also, it might not be an instance of Function.
      val handler = scope.get("handle", scope).asInstanceOf[Function]
      new GamePluginImpl(scope, handler)
    } finally {
      Context.exit()
    }
  }

  private class GamePluginImpl(scope: Scriptable, handler: Function) extends GamePlugin {
    def handle(path: String): String = {
      val cx: Context = Context.enter()
      try {
        val args: Array[AnyRef] = Array(path)
        val result = handler.call(cx, scope, scope, args)
        result.toString
      } finally {
        Context.exit()
      }
    }
  }
}

object Plugin extends Controller {
  private val gamePlugin: GamePlugin = GamePlugin()

  def route(path: String) : Action[AnyContent] = Action { request =>
    val result = gamePlugin.handle(request.path)
    Ok(result)
  }
}

Implement a simple plugin system for game logic.

GameLogic allows Beyond users to write game logics in JavaScript. It accepts an
incoming request to the plugin path and returns a response.

This is a proof-of-concept implementation, so plugin path and scripts are all
hardcoded. Also there is no way to register a plugin. More patches will follow.


package uk.ac.wellcome.platform.api.controllers

import javax.inject.{Inject, Singleton}

import com.sksamuel.elastic4s.ElasticClient
import com.sksamuel.elastic4s.ElasticDsl._
import com.twitter.finagle.http.Request
import com.twitter.finatra.http.Controller
import uk.ac.wellcome.utils.GlobalExecutionContext.context

@Singleton
class ManagementController @Inject()(
  elasticClient: ElasticClient
) extends Controller {

  get("/management/healthcheck") { request: Request =>
    response.ok.json(Map("message" -> "ok"))
  }

  get("/management/clusterhealth") { request: Request =>
    elasticClient
      .execute { clusterHealth() }
      .map(health => response.ok.json(health.status))
  }
}

package uk.ac.wellcome.platform.api.controllers

import javax.inject.{Inject, Singleton}

import com.sksamuel.elastic4s.TcpClient
import com.sksamuel.elastic4s.ElasticDsl._
import com.twitter.finagle.http.Request
import com.twitter.finatra.http.Controller
import uk.ac.wellcome.utils.GlobalExecutionContext.context

@Singleton
class ManagementController @Inject()(
  elasticClient: TcpClient
) extends Controller {

  get("/management/healthcheck") { request: Request =>
    response.ok.json(Map("message" -> "ok"))
  }

  get("/management/clusterhealth") { request: Request =>
    elasticClient
      .execute { clusterHealth() }
      .map(health => response.ok.json(health.status))
  }
}

Fix one final use of TcpClient/ElasticClient


package org.jetbrains.bsp

import java.io.File
import java.net.URI
import java.nio.file.Paths
import java.util.concurrent.CompletableFuture

import org.eclipse.lsp4j.jsonrpc.ResponseErrorException

object BspUtil {

  implicit class ResponseErrorExceptionOps(err: ResponseErrorException) {
    def toBspError: BspError = {
      BspErrorMessage(s"bsp error: ${err.getMessage} (${err.getResponseError.getCode})")
    }
  }

  implicit class StringOps(str: String) {
    def toURI: URI = new URI(str)
  }

  implicit class URIOps(uri: URI) {
    def toFile: File = new File(uri)
  }

  implicit class CompletableFutureOps[T](cf: CompletableFuture[T]) {
    def catchBspErrors :CompletableFuture[Either[BspError,T]] = cf.handle { (result, error) =>
      if (error != null) error match {
        case responseError: ResponseErrorException =>
          Left(responseError.toBspError)
        case other: Throwable => throw other
      } else Right(result)
    }
  }

}

package org.jetbrains.bsp

import java.io.File
import java.net.URI
import java.nio.file.Paths
import java.util.concurrent.CompletableFuture

import org.eclipse.lsp4j.jsonrpc.ResponseErrorException

object BspUtil {

  implicit class ResponseErrorExceptionOps(err: ResponseErrorException) {
    def toBspError: BspError = {
      BspErrorMessage(s"bsp error: ${err.getMessage} (${err.getResponseError.getCode})")
    }
  }

  implicit class StringOps(str: String) {
    def toURI: URI = new URI(str)
  }

  implicit class URIOps(uri: URI) {
    def toFile: File = Paths.get(uri).toFile
  }

  implicit class CompletableFutureOps[T](cf: CompletableFuture[T]) {
    def catchBspErrors :CompletableFuture[Either[BspError,T]] = cf.handle { (result, error) =>
      if (error != null) error match {
        case responseError: ResponseErrorException =>
          Left(responseError.toBspError)
        case other: Throwable => throw other
      } else Right(result)
    }
  }

}

Use target.baseDirectory instead of target.id.uri to get base directory for a target-> module mapping. Use common base of source roots as a fallback if baseDirectory is not set.

SCL-14851 fixed


package k2b6s9j.boatcraft.api.registry

import java.util.{HashMap, List, Map}

import scala.collection.JavaConversions.asScalaBuffer

import k2b6s9j.boatcraft.api.traits.Material
import net.minecraft.item.ItemStack

/** Contains the methods needed to register Materials with BoatCraft:Core. */
object MaterialRegistry
{
	var materials: Map[String, Material] = new HashMap[String, Material]

  /** Adds a single Material to the Map used by BoatCraft:Core for boat creation.
    *
    * @param newMaterial the Material being registered
    */
	def addMaterial(newMaterial: Material)
	{
		materials put(newMaterial toString, newMaterial)
	}

  /** Adds a list of Materials to the Map used by BoatCraft:Core for boat creation.
    *
    * @param newMaterials list of Materials being registered
    */
	def addMaterials(newMaterials: List[Material])
	{
		for (material <- newMaterials)
			materials put(material toString, material)
	}

	def getMaterial(name: String) =
		materials get name

	def getMaterial(stack: ItemStack) =
		materials get (stack.stackTagCompound getString "material")
}

package k2b6s9j.boatcraft.api.registry

import java.util.{HashMap, List, Map}

import scala.collection.JavaConversions.asScalaBuffer

import k2b6s9j.boatcraft.api.traits.Material
import net.minecraft.item.ItemStack

/** Contains the methods needed to register Materials with BoatCraft:Core. */
object MaterialRegistry
{
	var materials: Map[String, Material] = new HashMap[String, Material]

  /** Adds a single Material to the Map used by BoatCraft:Core for boat creation.
    *
    * @param newMaterial the Material being registered
    */
	def addMaterial(newMaterial: Material)
	{
		materials put(newMaterial toString, newMaterial)
	}

  /** Adds a list of Materials to the Map used by BoatCraft:Core for boat creation.
    *
    * @param newMaterials list of Materials being registered
    */
	def addMaterials(newMaterials: List[Material])
	{
		for (material <- newMaterials)
			materials put(material toString, material)
	}

  /** Returns a registered Material associated with a certain name.
    *
    * @param name name of registered Material
    * @return registered Material
    */
	def getMaterial(name: String) =
		materials get name

  /** Returns a registered Material associated with a certain ItemStack.
    *
    * @param stack ItemStack of registered Material
    * @return registered Material
    */
	def getMaterial(stack: ItemStack) =
		materials get (stack.stackTagCompound getString "material")
}

Add documentation comments for getMaterial()


/* Copyright 2009-2015 EPFL, Lausanne */

package leon
package verification

import purescala.Definitions._
import purescala.Expressions._
import purescala.ExprOps._

abstract class Tactic(vctx: VerificationContext) {
  val description : String

  def generateVCs(fd: FunDef): Seq[VC] = {
    fd.fullBody = matchToIfThenElse(fd.fullBody)
    generatePostconditions(fd) ++
    generatePreconditions(fd) ++
    generateCorrectnessConditions(fd)
  }

  def generatePostconditions(function: FunDef): Seq[VC]
  def generatePreconditions(function: FunDef): Seq[VC]
  def generateCorrectnessConditions(function: FunDef): Seq[VC]

  // Helper functions
  protected def precOrTrue(fd: FunDef): Expr = fd.precondition match {
    case Some(pre) => pre
    case None => BooleanLiteral(true)
  }

  protected def collectWithPC[T](f: PartialFunction[Expr, T])(expr: Expr): Seq[(T, Expr)] = {
    CollectorWithPaths(f).traverse(expr)
  }

  protected def sizeLimit(s: String, limit: Int) = {
    require(limit > 3)
    // Crop the call to display it properly
    val res = s.takeWhile(_ != '\n').take(limit)
    if (res == s) {
      res
    } else {
      res + " ..."
    }
  }
}

/* Copyright 2009-2015 EPFL, Lausanne */

package leon
package verification

import purescala.Definitions._
import purescala.Expressions._
import purescala.ExprOps._

abstract class Tactic(vctx: VerificationContext) {
  val description : String

  def generateVCs(fd: FunDef): Seq[VC] = {
    generatePostconditions(fd) ++
    generatePreconditions(fd) ++
    generateCorrectnessConditions(fd)
  }

  def generatePostconditions(function: FunDef): Seq[VC]
  def generatePreconditions(function: FunDef): Seq[VC]
  def generateCorrectnessConditions(function: FunDef): Seq[VC]

  // Helper functions
  protected def precOrTrue(fd: FunDef): Expr = fd.precondition match {
    case Some(pre) => pre
    case None => BooleanLiteral(true)
  }

  protected def collectWithPC[T](f: PartialFunction[Expr, T])(expr: Expr): Seq[(T, Expr)] = {
    CollectorWithPaths(f).traverse(expr)
  }

  protected def sizeLimit(s: String, limit: Int) = {
    require(limit > 3)
    // Crop the call to display it properly
    val res = s.takeWhile(_ != '\n').take(limit)
    if (res == s) {
      res
    } else {
      res + " ..."
    }
  }
}

Remove mutation in tactics. Fix path-conditions of matchs with guards


import sbt._
import Keys._

object Settings {
  lazy val organizationName: String = "com.busymachines"

  lazy val bmCommonsHomepage: String = "https://github.com/busymachines/busymachines-commons"

  def commonSettings: Seq[Setting[_]] =
    Seq(
      organization in ThisBuild := organizationName,
      homepage := Some(url(bmCommonsHomepage)),
      scalaVersion := Dependencies.`scala_2.12`,
      //      crossScalaVersions := Dependencies.seqOfCrossScalaVersions
    ) ++
      scalaCompilerSettings

  def scalaCompilerSettings: Seq[Setting[_]] = Nil
}

import sbt._
import Keys._

object Settings {
  lazy val organizationName: String = "com.busymachines"

  lazy val bmCommonsHomepage: String = "https://github.com/busymachines/busymachines-commons"

  def commonSettings: Seq[Setting[_]] =
    Seq(
      organization in ThisBuild := organizationName,
      homepage := Some(url(bmCommonsHomepage)),
      scalaVersion := Dependencies.`scala_2.12`,
      //      crossScalaVersions := Dependencies.seqOfCrossScalaVersions
    ) ++ scalaCompilerSettings

  def scalaCompilerSettings: Seq[Setting[_]] = Seq(
    scalacOptions ++= Seq(
      "-Ywarn-unused-import",
      "-Ypartial-unification",
      "-deprecation"
    )
  )
}

Add -Ypartial-unification, and deprecated compiler flags


package codesample.scala.helloworld

object HelloScala extends App {

  // fibonacci sequence calculator
  def fib(fibNumberPosition: Int): Int = {

    def fibIterator(iter: Int, currentLesser: Int, currentHigher: Int) : Int = {
      if (fibNumberPosition == iter)
        currentHigher
      else
        fibIterator(iter + 1, currentHigher, currentLesser + currentHigher)
    }

    fibIterator(1, 0, 1)
  }

  // Newton's square root func
  def newtonSqrt(x: Double) : Double = {

    def newtonItr(x: Double, guess: Double): Double = {
      if (isGoodEnough(x, guess)) guess
      else newtonItr(x, improve(x, guess))
    }

    def abs(x: Double) = {if (x < 0) -x else x}
    def isGoodEnough(x: Double, guess: Double): Boolean = {
      abs(x - guess*guess) < 0.001 }
    def improve(x: Double, guess: Double) : Double = {
      (guess + x/guess) / 2
    }

    newtonItr(x, 1)

  }

  println("Hello, Scala!")
  println(fib(3)) // 1 1 2 3 5 8 13
  println(newtonSqrt(2))
}

package codesample.scala.helloworld

object HelloScala extends App {

  // fibonacci sequence calculator
  def fib(fibNumberPosition: Int): Int = {

    def fibIterator(iter: Int, currentLesser: Int, currentHigher: Int) : Int = {
      if (fibNumberPosition == iter)
        currentHigher
      else
        fibIterator(iter + 1, currentHigher, currentLesser + currentHigher)
    }

    fibIterator(1, 0, 1)
  }

  // Newton's square root func
  def newtonSqrt(x: Double) : Double = {

    def newtonItr(x: Double, guess: Double): Double = {
      if (isGuessGoodEnough(x, guess)) guess
      else newtonItr(x, improveGuess(x, guess))
    }

    def abs(x: Double) = {if (x < 0) -x else x}
    def isGuessGoodEnough(x: Double, guess: Double): Boolean = {
      abs(x - guess*guess) < 0.001 }
    def improveGuess(x: Double, guess: Double) : Double = {
      (guess + x/guess) / 2
    }

    newtonItr(x, 1)

  }

  println("Hello, Scala!")
  println(fib(3)) // 1 1 2 3 5 8 13
  println(newtonSqrt(2))
}

Improve naming for sqrt functon

Improve naming for sqrt functon


/*
 * bytefrog: a tracing framework for the JVM. For more information
 * see http://code-pulse.com/bytefrog
 *
 * Copyright (C) 2014 Applied Visions - http://securedecisions.avi.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import sbt._

object Dependencies {
	lazy val scalaMock = "org.scalamock" %% "scalamock-scalatest-support" % "3.0.1" % "test"
	lazy val reactive= "cc.co.scala-reactive" %% "reactive-core"	% "0.3.2.1"
	lazy val asm = Seq(
		"org.ow2.asm" % "asm" % "5.0.4",
		"org.ow2.asm" % "asm-commons" % "5.0.4"
	)
}

/*
 * bytefrog: a tracing framework for the JVM. For more information
 * see http://code-pulse.com/bytefrog
 *
 * Copyright (C) 2014 Applied Visions - http://securedecisions.avi.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import sbt._

object Dependencies {
	lazy val scalaMock = "org.scalamock" %% "scalamock-scalatest-support" % "3.0.1" % "test"
	lazy val reactive= "cc.co.scala-reactive" %% "reactive-core"	% "0.3.2.1"
	lazy val asm = Seq(
		"org.ow2.asm" % "asm" % "5.1",
		"org.ow2.asm" % "asm-commons" % "5.1"
	)
}

Update ASM dependency reference for Java 8 support


import com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-build"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.1.14"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.5.10",
      "com.ning" % "async-http-client" % "1.9.40",
      "org.scalatest" %% "scalatest" % "3.0.1" % Test
    )
  )

publishTo := {
  val host = "https://flow.artifactoryonline.com/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}

import com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-build"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.1.15"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.5.10",
      "com.ning" % "async-http-client" % "1.9.40",
      "org.scalatest" %% "scalatest" % "3.0.1" % Test
    )
  )

publishTo := {
  val host = "https://flow.artifactoryonline.com/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}

autocommit: Update configuration to record version 0.1.15


sbtPlugin := true

name := "xsbt-idea"

organization := "org.sbtidea"

scalacOptions := Seq("-deprecation", "-unchecked")

Add -deprecation -unchecked to scalacOptions.


name := "debiki-core"

organization := "com.debiki"

version := "0.0.2-SNAPSHOT"

scalaVersion := "2.8.1"

resolvers += "Scala-Tools Maven2 Repository" at "http://scala-tools.org/repo-releases"

libraryDependencies ++= Seq(
  "org.scala-lang" % "scala-library" % "2.8.1",
  "org.yaml" % "snakeyaml" % "1.6",
  "com.google.guava" % "guava" % "r09",
  "commons-codec" % "commons-codec" % "1.5",
  "net.liftweb" %% "lift-common" % "2.2",
  "net.liftweb" %% "lift-util" % "2.2",
  "junit" % "junit" % "4.7" % "test",
  "org.scala-tools.testing" %% "specs" % "1.6.6" % "test"
)

name := "debiki-core"

organization := "com.debiki"

version := "0.0.2-SNAPSHOT"

scalaVersion := "2.9.1"

resolvers += "Scala-Tools Maven2 Repository" at "http://scala-tools.org/repo-releases"

libraryDependencies ++= Seq(
  "org.scala-lang" % "scala-library" % "2.9.1",
  "org.yaml" % "snakeyaml" % "1.6",
  "com.google.guava" % "guava" % "r09",
  "commons-codec" % "commons-codec" % "1.5",
  "net.liftweb" %% "lift-common" % "2.4-M5",
  "net.liftweb" %% "lift-util" % "2.4-M5",
  "junit" % "junit" % "4.7" % "test",
  "org.scala-tools.testing" %% "specs" % "1.6.9" % "test"
)

Upgrade to Scala 2.9.1 and Lift-Web 2.4-M5

From Scala 2.8.1 and Lift-Web 2.2. Requires Specs 1.6.9 not 1.6.6.


import sbt._

// http://groups.google.com/group/simple-build-tool/msg/c32741357ac58f18
trait TestWith extends BasicScalaProject {
  def testWithCompileClasspath: Seq[BasicScalaProject] = Nil
  def testWithTestClasspath: Seq[BasicScalaProject] = Nil
  override def testCompileAction = super.testCompileAction dependsOn((testWithTestClasspath.map(_.testCompile) ++ testWithCompileClasspath.map(_.compile)) : _*)
  override def testClasspath = (super.testClasspath /: (testWithTestClasspath.map(_.testClasspath) ++  testWithCompileClasspath.map(_.compileClasspath) ))(_ +++ _)
  override def deliverProjectDependencies = super.deliverProjectDependencies ++ testWithTestClasspath.map(_.projectID % "test")
}

import sbt._

// http://groups.google.com/group/simple-build-tool/msg/c32741357ac58f18
trait TestWith extends BasicScalaProject {
  def testWithCompileClasspath: Seq[BasicScalaProject] = Nil
  def testWithTestClasspath: Seq[BasicScalaProject] = Nil
  override def testCompileAction = super.testCompileAction dependsOn((testWithTestClasspath.map(_.testCompile) ++ testWithCompileClasspath.map(_.compile)) : _*)
  override def testClasspath = (super.testClasspath /: (testWithTestClasspath.map(_.testClasspath) ++  testWithCompileClasspath.map(_.compileClasspath) ))(_ +++ _)
  // Our test-with dependencies need to publish before we deliver ourselves...
  override def dependencies = super.dependencies ++ testWithCompileClasspath ++ testWithTestClasspath
  // ... but we still want them in test scope.
  override def deliverProjectDependencies = {
    val testDeps = testWithTestClasspath map { _.projectID }
    super.deliverProjectDependencies map { dep =>
      if (testDeps.contains(dep)) { dep % "test" } else dep
    }
  }
}

Fix the intermittent sbt.ResolveException on scalatra-scalatest.

The Scalatra test projects need to be published before the projects that
use them.  By adding the TestWith classpath to the dependencies, we
should now be able to build cleanly from the top level, regardless of
whether those test projects are already in a repo.


package com.twitter.finagle.serverset2.client

import com.twitter.finagle.stats.StatsReceiver
import com.twitter.util.{Closable, Duration, Future, Time, Timer}

class StateTracker(
  statsReceiver: StatsReceiver,
  samplePeriod: Duration,
  timer: Timer
) extends Closable {

  private[this] var currState: Option[SessionState] = None
  private[this] var lastSample: Time = Time.now

  private[this] val timerTask = timer.schedule(Time.now + samplePeriod, samplePeriod) {
    sample()
  }

  def close(deadline: Time): Future[Unit] = {
    timerTask.close(deadline)
  }

  def transition(newState: SessionState): Unit = synchronized {
    sample()
    currState = Some(newState)
  }

  private[this] def sample(): Unit = synchronized {
    val now = Time.now
    val delta = now - lastSample
    lastSample = now
    currState foreach { state =>
      statsReceiver.counter(s"${state.name}_duration_ms").incr(delta.inMilliseconds.toInt)
    }
  }
}

package com.twitter.finagle.serverset2.client

import com.twitter.finagle.stats.{Counter, StatsReceiver}
import com.twitter.util.{Closable, Duration, Future, Time, Timer}

class StateTracker(
  statsReceiver: StatsReceiver,
  samplePeriod: Duration,
  timer: Timer
) extends Closable {

  private[this] var currCounter: Option[Counter] = None
  private[this] var lastSample: Time = Time.now

  private[this] val timerTask = timer.schedule(Time.now + samplePeriod, samplePeriod) {
    sample()
  }

  def close(deadline: Time): Future[Unit] = {
    timerTask.close(deadline)
  }

  def transition(newState: SessionState): Unit = synchronized {
    sample()
    currCounter = Some(statsReceiver.counter(s"${newState.name}_duration_ms"))
  }

  private[this] def sample(): Unit = synchronized {
    val now = Time.now
    val delta = now - lastSample
    lastSample = now
    currCounter.foreach { counter => counter.incr(delta.inMilliseconds.toInt) }
  }
}

finagle-serverset: Make statetracker cache counter instead of state.

Problem:
The statetracker creates a new counter everytime it samples and
outputs the time in current state.

Solution:
Instead of caching the current state, we can just cache the a
counter which will prevent a new counter from being created.

RB_ID=902951


package steve

import com.datasift.dropwizard.scala.ScalaApplication
import com.google.inject.Stage
import com.hubspot.dropwizard.guice.GuiceBundle
import com.typesafe.config.ConfigFactory
import health.SteveHealthCheck
import io.dropwizard.setup.{Bootstrap, Environment}
import org.flywaydb.core.Flyway

object SteveServer extends ScalaApplication[SteveConfiguration] {
  val guiceBundle = GuiceBundle.newBuilder()
    .addModule(new SteveModule)
    .enableAutoConfig("controller", "steve")
    .setConfigClass(classOf[SteveConfiguration])
    .build(Stage.PRODUCTION)

  override def init(bootstrap: Bootstrap[SteveConfiguration]): Unit = {
    val flyway = new Flyway()
    val dbConfig = ConfigFactory.load().getConfig("steveDatasource.properties").resolve()
    val jdbcURL = s"jdbc:postgresql://${dbConfig.getString("serverName")}:${dbConfig.getString("portNumber")}/${dbConfig.getString("databaseName")}"
    flyway.setDataSource(jdbcURL, dbConfig.getString("user"), dbConfig.getString("password"))
    flyway.migrate()
    bootstrap.addBundle(guiceBundle)
  }

  override def run(configuration: SteveConfiguration, environment: Environment): Unit = {
    environment.healthChecks().register("steve", new SteveHealthCheck)
    environment.jersey().setUrlPattern("/*")
  }
}

package steve

import com.datasift.dropwizard.scala.ScalaApplication
import com.google.inject.Stage
import com.hubspot.dropwizard.guice.GuiceBundle
import com.typesafe.config.ConfigFactory
import health.SteveHealthCheck
import io.dropwizard.configuration.{EnvironmentVariableSubstitutor, SubstitutingSourceProvider}
import io.dropwizard.setup.{Bootstrap, Environment}
import org.flywaydb.core.Flyway

object SteveServer extends ScalaApplication[SteveConfiguration] {
  val guiceBundle = GuiceBundle.newBuilder()
    .addModule(new SteveModule)
    .enableAutoConfig("controller", "steve")
    .setConfigClass(classOf[SteveConfiguration])
    .build(Stage.PRODUCTION)

  override def init(bootstrap: Bootstrap[SteveConfiguration]): Unit = {
    bootstrap.setConfigurationSourceProvider(
      new SubstitutingSourceProvider(
        bootstrap.getConfigurationSourceProvider,
        new EnvironmentVariableSubstitutor(false))
    )
    val flyway = new Flyway()
    val dbConfig = ConfigFactory.load().getConfig("steveDatasource.properties").resolve()
    val jdbcURL = s"jdbc:postgresql://${dbConfig.getString("serverName")}:${dbConfig.getInt("portNumber").toString}/${dbConfig.getString("databaseName")}"
    flyway.setDataSource(jdbcURL, dbConfig.getString("user"), dbConfig.getString("password"))
    flyway.migrate()
    bootstrap.addBundle(guiceBundle)
  }

  override def run(configuration: SteveConfiguration, environment: Environment): Unit = {
    environment.healthChecks().register("steve", new SteveHealthCheck)
    environment.jersey().setUrlPattern("/*")
  }
}

Substitute environment variables in YML.


package org.scalafmt.cli

import java.io.File

import org.scalafmt.util.AbsoluteFile
import org.scalafmt.util.FileOps

object FileTestOps {

  /**
    * The inverse of [[dir2string]]. Given a string representation creates the
    * necessary files/directories with respective file contents.
    */
  def string2dir(layout: String): AbsoluteFile = {
    val root = File.createTempFile("root", "root")
    root.delete()
    root.mkdir()
    layout.split("(?=\n/)").foreach { row =>
      val path :: contents :: Nil =
        row.stripPrefix("\n").split("\n", 2).toList
      val file = new File(root, path)
      file.getParentFile.mkdirs()
      FileOps.writeFile(file, contents)
    }
    AbsoluteFile.fromPath(root.getAbsolutePath).get
  }

  /** Gives a string representation of a directory. For example
    *
    * /build.sbt
    * val x = project
    * /src/main/scala/Main.scala
    * object A { def main = Unit }
    * /target/scala-2.11/foo.class
    * ^!*@#@!*#&@*!&#^
    */
  def dir2string(file: AbsoluteFile): String = {
    FileOps
      .listFiles(file.jfile)
      .sorted
      .map { path =>
        val contents = FileOps.readFile(path)
        s"""|${path.stripPrefix(file.jfile.getPath)}
            |$contents""".stripMargin
      }
      .mkString("\n")
      .replace(File.separator, "/") // ensure original separators
  }

}

package org.scalafmt.cli

import java.io.File
import java.nio.file.Files

import org.scalafmt.util.AbsoluteFile
import org.scalafmt.util.FileOps

object FileTestOps {

  /**
    * The inverse of [[dir2string]]. Given a string representation creates the
    * necessary files/directories with respective file contents.
    */
  def string2dir(layout: String): AbsoluteFile = {
    val root = Files.createTempDirectory("root").toFile
    layout.split("(?=\n/)").foreach { row =>
      val path :: contents :: Nil =
        row.stripPrefix("\n").split("\n", 2).toList
      val file = new File(root, path)
      file.getParentFile.mkdirs()
      FileOps.writeFile(file, contents)
    }
    AbsoluteFile.fromPath(root.getAbsolutePath).get
  }

  /** Gives a string representation of a directory. For example
    *
    * /build.sbt
    * val x = project
    * /src/main/scala/Main.scala
    * object A { def main = Unit }
    * /target/scala-2.11/foo.class
    * ^!*@#@!*#&@*!&#^
    */
  def dir2string(file: AbsoluteFile): String = {
    FileOps
      .listFiles(file.jfile)
      .sorted
      .map { path =>
        val contents = FileOps.readFile(path)
        s"""|${path.stripPrefix(file.jfile.getPath)}
            |$contents""".stripMargin
      }
      .mkString("\n")
      .replace(File.separator, "/") // ensure original separators
  }

}

Fix minor inefficiency in test infrastructure


package com.earldouglas.xwp

import sbt._
import sbt.Def.taskKey
import sbt.Def.settingKey

object TomcatPlugin extends AutoPlugin {

  object autoImport {
    lazy val Tomcat = config("tomcat").hide
  }

  import ContainerPlugin.autoImport._
  import autoImport._

  override def requires = ContainerPlugin

  override val projectConfigurations = Seq(Tomcat)

  val webappRunner = "com.github.jsimone" % "webapp-runner" % "8.5.15.1"

  override lazy val projectSettings =
    ContainerPlugin.containerSettings(Tomcat) ++
      inConfig(Tomcat)(
        Seq( containerLibs := Seq(webappRunner.intransitive())
           , containerMain := "webapp.runner.launch.Main"
           )
      )
}

package com.earldouglas.xwp

import sbt._
import sbt.Def.taskKey
import sbt.Def.settingKey

object TomcatPlugin extends AutoPlugin {

  object autoImport {
    lazy val Tomcat = config("tomcat").hide
  }

  import ContainerPlugin.autoImport._
  import autoImport._

  override def requires = ContainerPlugin

  override val projectConfigurations = Seq(Tomcat)

  val webappRunner = "com.github.jsimone" % "webapp-runner" % "9.0.24.0"

  override lazy val projectSettings =
    ContainerPlugin.containerSettings(Tomcat) ++
      inConfig(Tomcat)(
        Seq( containerLibs := Seq(webappRunner.intransitive())
           , containerMain := "webapp.runner.launch.Main"
           )
      )
}

Update default webapp-runner to the latest version


package handlers

import javax.inject.{Inject, Singleton}

import controllers.ServerProxyDefinition
import io.apibuilder.validation.FormData
import lib.{ProxyRequest, ResolvedToken, Route}
import play.api.mvc.Result

import scala.concurrent.{ExecutionContext, Future}

/**
  * Converts url form encodes into a JSON body, then
  * delegates processing to the application json handler
  */
@Singleton
class UrlFormEncodedHandler @Inject() (
  applicationJsonHandler: ApplicationJsonHandler
) extends Handler {

  override def process(
    definition: ServerProxyDefinition,
    request: ProxyRequest,
    route: Route,
    token: ResolvedToken
  )(
    implicit ec: ExecutionContext
  ): Future[Result] = {
    val newBody = FormData.parseEncodedToJsObject(
      request.bodyUtf8.getOrElse {
        // TODO: Return 422 on invalid content herek
        sys.error(s"Request[${request.requestId}] Failed to serialize body as string for ContentType.UrlFormEncoded")
      }
    )

    applicationJsonHandler.processJson(
      definition,
      request,
      route,
      token,
      newBody
    )
  }

}

package handlers

import javax.inject.{Inject, Singleton}

import controllers.ServerProxyDefinition
import io.apibuilder.validation.FormData
import lib.{ProxyRequest, ResolvedToken, Route}
import play.api.mvc.Result

import scala.concurrent.{ExecutionContext, Future}

/**
  * Converts url form encodes into a JSON body, then
  * delegates processing to the application json handler
  */
@Singleton
class UrlFormEncodedHandler @Inject() (
  applicationJsonHandler: ApplicationJsonHandler
) extends Handler {

  override def process(
    definition: ServerProxyDefinition,
    request: ProxyRequest,
    route: Route,
    token: ResolvedToken
  )(
    implicit ec: ExecutionContext
  ): Future[Result] = {
    request.bodyUtf8 match {
      case None => Future.successful(
        request.responseUnprocessableEntity(
          "Url form encoded requests must contain body encoded in ;UTF-8'"
        )
      )

      case Some(body) => {
        applicationJsonHandler.processJson(
          definition,
          request,
          route,
          token,
          FormData.parseEncodedToJsObject(body)
        )
      }
    }
  }

}

Return 422 on invalid encoding for url/form encoded


addSbtPlugin("com.frugalmechanic" % "fm-sbt-common" % "0.7.0")

addSbtPlugin("com.frugalmechanic" % "fm-sbt-common" % "0.8.0")

Upgrade to Upgrade to fm-sbt-common 0.8.0


package uk.ac.wellcome.platform.archive.archivist.flow

import akka.NotUsed
import akka.stream.scaladsl.{Flow, Source}
import com.amazonaws.services.s3.AmazonS3
import grizzled.slf4j.Logging
import uk.ac.wellcome.platform.archive.archivist.models.{ArchiveJob, BagUploaderConfig}
import uk.ac.wellcome.platform.archive.common.models.ArchiveComplete

object ArchiveZipFileFlow extends Logging {
  def apply(config: BagUploaderConfig)(
    implicit s3Client: AmazonS3
  ): Flow[ZipFileDownloadComplete, ArchiveComplete, NotUsed] = {

    Flow[ZipFileDownloadComplete].flatMapConcat {
      case ZipFileDownloadComplete(zipFile, ingestRequest) =>
        Source
          .single(zipFile)
          .map(ArchiveJob.create(_, config))
          .collect{case Right(job) => job}
          // TODO: Log error here
          .via(ArchiveJobFlow(config.bagItConfig.digestDelimiterRegexp))
          .collect {case Right(archiveJob) => archiveJob}
          .map(job =>
            ArchiveComplete(
              job.bagLocation,
              ingestRequest
            ))
    }
  }
}

package uk.ac.wellcome.platform.archive.archivist.flow

import akka.NotUsed
import akka.stream.scaladsl.{Flow, Source}
import com.amazonaws.services.s3.AmazonS3
import grizzled.slf4j.Logging
import uk.ac.wellcome.platform.archive.archivist.models.{ArchiveJob, BagUploaderConfig}
import uk.ac.wellcome.platform.archive.common.models.ArchiveComplete

object ArchiveZipFileFlow extends Logging {
  def apply(config: BagUploaderConfig)(
    implicit s3Client: AmazonS3
  ): Flow[ZipFileDownloadComplete, ArchiveComplete, NotUsed] = {

    Flow[ZipFileDownloadComplete].flatMapConcat {
      case ZipFileDownloadComplete(zipFile, ingestRequest) =>
        // TODO report progress here
        Source
          .single(zipFile)
          .map(ArchiveJob.create(_, config))
          .collect{case Right(job) => job}
          .via(ArchiveJobFlow(config.bagItConfig.digestDelimiterRegexp))
          .collect {case Right(archiveJob) => archiveJob}
          .map(job =>
            ArchiveComplete(
              job.bagLocation,
              ingestRequest
            ))
    }
  }
}

Add a TODO to mark where we should add the reporting flow


package ingraph.tests

import org.scalatest.FunSuite

class BiValidationTest extends FunSuite {

  val testCases: Seq[LdbcSnbTestCase] = Seq(2
  //  , 3, 4, 6, 7, 8, 9, 12, 15, 17, 23, 24
  ) map (new LdbcSnbTestCase("bi", _))

  testCases.foreach {
    tc =>
      test(s"${tc.name}") {
        val neo4jResults   = TestRunners.neo4jTestRunner(tc)
        val ingraphResults = TestRunners.ingraphTestRunner(tc)

        println("neo4j results:   " + neo4jResults)
        println("ingraph results: " + ingraphResults)

//        println(tc.parameters.mkString("Parameters: (\n\t", "\n\t", "\n)"))
//        println(neo4jResult.mkString("Results: (\n\t", "\n\t", "\n)"))
//        assert(neo4jResults.equals(ingraphResults))
      }
  }

}

package ingraph.tests

import org.scalatest.FunSuite

class BiValidationTest extends FunSuite {

  val testCases: Seq[LdbcSnbTestCase] = Seq(2, 3, 4, 6, 7, 8, 9, 12, 15, 17, 23, 24) map (new LdbcSnbTestCase("bi", _))

  testCases.foreach {
    tc =>
      test(s"${tc.name}") {
        val neo4jResults   = TestRunners.neo4jTestRunner(tc)
        val ingraphResults = TestRunners.ingraphTestRunner(tc)

        println("neo4j results:   " + neo4jResults)
        println("ingraph results: " + ingraphResults)

//        println(tc.parameters.mkString("Parameters: (\n\t", "\n\t", "\n)"))
//        println(neo4jResult.mkString("Results: (\n\t", "\n\t", "\n)"))
//        assert(neo4jResults.equals(ingraphResults))
      }
  }

}

Add queries back to testing

Add queries back to testing


import java.lang.reflect.Constructor

import models.User
import play.api.{Logger, Application}
import play.api.libs.concurrent.Akka
import play.api.mvc.WithFilters
import securesocial.core.RuntimeEnvironment
import security.{MongoUserService, ApplicationRuntimeEnvironment}
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global

object Global extends WithFilters(HttpsRedirectFilter) {
  override def getControllerInstance[A](controllerClass: Class[A]): A = {
    val instance = controllerClass.getConstructors.find { c =>
      val params = c.getParameterTypes
      params.length == 1 && params(0) == classOf[RuntimeEnvironment[User]]
    }.map {
      _.asInstanceOf[Constructor[A]].newInstance(ApplicationRuntimeEnvironment)
    }
    instance.getOrElse(super.getControllerInstance(controllerClass))
  }

  override def onStart(app: Application): Unit = {
    Akka.system(app).scheduler.scheduleOnce(10 seconds) {
      Logger.info("Run after 10 seconds")
    }

    Akka.system(app).scheduler.schedule(11 seconds, 1 second) {
      Logger.info("Every second")
    }
  }
}

import java.lang.reflect.Constructor

import models.User
import play.api.Application
import play.api.libs.concurrent.Akka
import play.api.mvc.WithFilters
import securesocial.core.RuntimeEnvironment
import security.{MongoUserService, ApplicationRuntimeEnvironment}
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global

object Global extends WithFilters(HttpsRedirectFilter) {
  override def getControllerInstance[A](controllerClass: Class[A]): A = {
    val instance = controllerClass.getConstructors.find { c =>
      val params = c.getParameterTypes
      params.length == 1 && params(0) == classOf[RuntimeEnvironment[User]]
    }.map {
      _.asInstanceOf[Constructor[A]].newInstance(ApplicationRuntimeEnvironment)
    }
    instance.getOrElse(super.getControllerInstance(controllerClass))
  }
}

Revert "Test scheduling on Heroku."

Revert "Test scheduling on Heroku."

This reverts commit 21067b4915e2817acdaa1d01448d0e30bd841088.


import leon.annotation._
import leon.lang._

object Acc {

  case class Acc(checking : BigInt, savings : BigInt)

  def putAside(x: BigInt, a: Acc): Acc = {
    require (x > 0 && notRed(a) && a.checking >= x)
      Acc(a.checking - x, a.savings + x)
  } ensuring {
    r => notRed(r) && sameTotal(a, r)
  }

  def sameTotal(a1: Acc, a2: Acc): Boolean = {
    a1.checking + a1.savings == a2.checking + a2.savings
  }

  def notRed(a: Acc) : Boolean = {
    a.checking >= 0 && a.savings >= 0
  }

}

Implement Ensuring, Choose as HOFs

Implement Ensuring, Choose as HOFs


/*
 * Copyright (c) 2002-2015 "Neo Technology,"
 * Network Engine for Objects in Lund AB [http://neotechnology.com]
 *
 * This file is part of Neo4j.
 *
 * Neo4j is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.neo4j.cypher.internal.helpers

trait RandomizedTestSupport {
  val N: Double  = testRandomizer.nextDouble() * 1E6
  println("N: " + N)
}

/*
 * Copyright (c) 2002-2015 "Neo Technology,"
 * Network Engine for Objects in Lund AB [http://neotechnology.com]
 *
 * This file is part of Neo4j.
 *
 * Neo4j is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.neo4j.cypher.internal.helpers

trait RandomizedTestSupport {

  /**
   * Minimum number of nodes in the database.
   * This value is needed for correct cardinality estimations.
   */
  private val MIN_N = 1500

  /**
   * Total number of nodes in the database.
   */
  val N: Double = testRandomizer.nextDouble() * 1E6 + MIN_N
  println("N: " + N)
}

Add lower bound for number of nodes in randomized tests


package application

import java.io.File

import org.specs2.execute.{AsResult, Result}
import org.specs2.mutable.Around
import org.specs2.specification.Scope
import play.api.ApplicationLoader.Context
import play.api.test.Helpers
import play.api.{Application, ApplicationLoader, BuiltInComponents, Environment, LoggerConfigurator, Mode}

trait WithPlayApp extends Around with Scope {
  lazy val app: Application = new TestApplicationLoader(configureComponents).load(context)

  private def context = ApplicationLoader.createContext(
    new Environment(new File("."), classOf[TestApplicationLoader].getClassLoader, Mode.Test)
  )

  override def around[T: AsResult](t: => T): Result = {
    Helpers.running(app)(AsResult.effectively(t))
  }

  def configureComponents(context: Context): BuiltInComponents
}

class TestApplicationLoader(configureComponents: Context => BuiltInComponents) extends ApplicationLoader {
  override def load(context: Context): Application = {
    configureLoggers(context)
    configureComponents(context).application
  }

  private def configureLoggers(context: Context) = {
    LoggerConfigurator(context.environment.classLoader).foreach {
      _.configure(context.environment)
    }
  }
}

package application

import org.specs2.execute.{AsResult, Result}
import org.specs2.mutable.Around
import org.specs2.specification.Scope
import play.api.ApplicationLoader.Context
import play.api.test.Helpers
import play.api.{Application, ApplicationLoader, BuiltInComponents, Environment, LoggerConfigurator}

trait WithPlayApp extends Around with Scope {

  private def context: Context = Context.create(Environment.simple())

  lazy val app: Application = new TestApplicationLoader(configureComponents).load(context)

  override def around[T: AsResult](t: => T): Result = {
    Helpers.running(app)(AsResult.effectively(t))
  }

  def configureComponents(context: Context): BuiltInComponents
}

class TestApplicationLoader(configureComponents: Context => BuiltInComponents) extends ApplicationLoader {
  override def load(context: Context): Application = {
    configureLoggers(context)
    configureComponents(context).application
  }

  private def configureLoggers(context: Context) = {
    LoggerConfigurator(context.environment.classLoader).foreach {
      _.configure(context.environment)
    }
  }
}

Use new Context.create to instanciate a new Context


pomExtra in Global := {
  <url>https://github.com/blemale/scaffeine</url>
    <licenses>
      <license>
        <name>Apache 2</name>
        <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
      </license>
    </licenses>
    <scm>
      <connection>scm:git:github.com/blemale/scaffeine.git</connection>
      <developerConnection>scm:git:git@github.com:blemale/scaffeine.git</developerConnection>
      <url>github.com/blemale/scaffeine.git</url>
    </scm>
    <developers>
      <developer>
        <id>blemale</id>
        <name>Bastien LEMALE</name>
        <url>https://github.com/blemale)</url>
      </developer>
    </developers>
}

pomExtra in Global := {
  <url>https://github.com/blemale/scaffeine</url>
    <licenses>
      <license>
        <name>Apache 2</name>
        <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
      </license>
    </licenses>
    <scm>
      <connection>scm:git:github.com/blemale/scaffeine.git</connection>
      <developerConnection>scm:git:git@github.com:blemale/scaffeine.git</developerConnection>
      <url>github.com/blemale/scaffeine.git</url>
    </scm>
    <developers>
      <developer>
        <id>blemale</id>
        <name>Bastien LEMALE</name>
        <url>https://github.com/blemale</url>
      </developer>
    </developers>
}

Fix typo in dev homepage

Fix typo in dev homepage


package sbt.util

import sbt.internal.util._

import org.scalatest._

class LogExchangeSpec extends FlatSpec with Matchers {
  import LogExchange._

  checkTypeTag("stringTypeTagThrowable", stringTypeTagThrowable, StringTypeTag[Throwable])
  checkTypeTag("stringTypeTagTraceEvent", stringTypeTagTraceEvent, StringTypeTag[TraceEvent])
  checkTypeTag("stringTypeTagSuccessEvent", stringTypeTagSuccessEvent, StringTypeTag[SuccessEvent])

  private def checkTypeTag[A, B](name: String, actual: A, expected: B): Unit =
    s"LogExchange.$name" should s"match real StringTypeTag[$expected]" in assert(actual == expected)
}

package sbt.util

import sbt.internal.util._

import org.scalatest._

class LogExchangeSpec extends FlatSpec with Matchers {
  import LogExchange._

  checkTypeTag("stringTypeTagThrowable", stringTypeTagThrowable, StringTypeTag[Throwable])
  checkTypeTag("stringTypeTagTraceEvent", stringTypeTagTraceEvent, StringTypeTag[TraceEvent])
  checkTypeTag("stringTypeTagSuccessEvent", stringTypeTagSuccessEvent, StringTypeTag[SuccessEvent])

  private def checkTypeTag[A](name: String, inc: StringTypeTag[A], exp: StringTypeTag[A]): Unit =
    s"LogExchange.$name" should s"match real StringTypeTag[$exp]" in {
      val StringTypeTag(incomingString) = inc
      val StringTypeTag(expectedString) = exp
      if ((incomingString startsWith "scala.") || (expectedString startsWith "scala.")) {
        // > historically [Scala] has been inconsistent whether `scala.` is included, or not
        // > would it be hard to make the test accept either result?
        // https://github.com/scala/community-builds/pull/758#issuecomment-409760633
        assert((incomingString stripPrefix "scala.") == (expectedString stripPrefix "scala."))
      } else {
        assert(incomingString == expectedString)
      }
    }
}

Make checkTypeTag lenient on "scala." type prefix


package providers

import scala.concurrent.Future
import play.api.libs.concurrent.Execution.Implicits._
import util.WithTiming._
import models.{LocationWithWeather, Location}

trait WeatherFetchStrategies {
  this: Providers =>

  def provider(name: String): Location => Future[LocationWithWeather] = { location =>
    providers(name).getLocationWithWeather(location) withTiming
  }

  val smhi = provider("smhi")

  val yr = provider("yr")

  val firstCompleted: Location => Future[LocationWithWeather] = { location =>
    val weatherF = providers.values.map(_.getLocationWithWeather(location) withTiming)
    Future.firstCompletedOf(weatherF)
  }

  val withRecovery: Location => Future[LocationWithWeather] = { location =>
    smhi(location).recoverWith {
       case _ => yr(location)
    }
  }

  val all: Location => Future[LocationWithWeather] = { location =>

    Future.sequence(
        providers.values
          .map(f => f.getLocationWithWeather(location) withTiming))
          .map(l => l.tail.fold[LocationWithWeather](l.head)(_ merge _)
      )
  }

}

package providers

import scala.concurrent.Future
import play.api.libs.concurrent.Execution.Implicits._
import util.WithTiming._
import models.{LocationWithWeather, Location}

trait WeatherFetchStrategies {
  this: Providers =>

  def provider(name: String): Location => Future[LocationWithWeather] = { location =>
    providers(name).getLocationWithWeather(location) withTiming
  }

  val smhi: (Location) => Future[LocationWithWeather] = provider("smhi")

  val yr: (Location) => Future[LocationWithWeather] = provider("yr")

  val firstCompleted: Location => Future[LocationWithWeather] = { location =>
    yr(location)
    ??? //Todo add instructions
  }

  val withRecovery: Location => Future[LocationWithWeather] = { location =>
    ??? //Todo add instructions
  }

  val all: Location => Future[LocationWithWeather] = { location =>
    ??? //Todo add instructions
  }

}

Add type annotations on provider values

Add type annotations on provider values


package hmda.validation.engine.ts

import hmda.parser.fi.ts.TsGenerators
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.prop.PropertyChecks
import org.scalatest.{ MustMatchers, PropSpec }

import scala.concurrent.ExecutionContext

//TODO: fails if JSExecutionContext.Implicits.queue is used (runNow is deprecated, but works)
class TsValidationEngineSpec extends PropSpec with PropertyChecks with MustMatchers with TsGenerators with TsValidationEngine with ScalaFutures with CommonTsValidationSpec {

  override implicit val ec: ExecutionContext = scala.scalajs.concurrent.JSExecutionContext.Implicits.runNow

}

package hmda.validation.engine.ts

import hmda.parser.fi.ts.TsGenerators
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.prop.PropertyChecks
import org.scalatest.{ MustMatchers, PropSpec }

import scala.concurrent.ExecutionContext

//TODO: fails if JSExecutionContext.Implicits.queue is used (runNow is deprecated, but works)
//TODO: fails in Travis CI with org.scalajs.jsenv.ComJSEnv$ComClosedException: JSCom has been closed
//class TsValidationSpec extends PropSpec with PropertyChecks with MustMatchers with TsGenerators with TsValidationEngine with ScalaFutures with CommonTsValidationSpec {
//
//  override implicit val ec: ExecutionContext = scala.scalajs.concurrent.JSExecutionContext.Implicits.runNow

//}

Disable Ts validation engine test in JS

Disable Ts validation engine test in JS


package org.refptr.iscala
package tests

import org.specs2.mutable.Specification

class InterpreterSpec extends Specification {
    sequential

    val classpath = Sbt.resolveCompiler().classpath
    val intp = new Interpreter(classpath, Nil)

    "IScala's interpreter" should {
        import intp.{interpretWithOutput=>interpret}
        import Results._

        "support primitive values" in {
            interpret("1") must beLike { case Output(Value(_, "Int", _), "", "") => ok }
            interpret("1.0") must beLike { case Output(Value(_, "Double", _), "", "") => ok }
            interpret("\"XXX\"") must beLike { case Output(Value(_, "String", _), "", "") => ok }
        }

        "support function values" in {
            interpret("() => 1") must beLike { case Output(Value(_, "() => Int", _), "", "") => ok }
            interpret("(x: Int) => x + 1") must beLike { case Output(Value(_, "Int => Int", _), "", "") => ok }
            interpret("(x: Int, y: Int) => x*y + 1") must beLike { case Output(Value(_, "(Int, Int) => Int", _), "", "") => ok }
        }

        "support printing" in {
            interpret("println(\"XXX\")") === Output(NoValue, "XXX\n", "")
            interpret("print(\"XXX\")") === Output(NoValue, "XXX", "")
        }
    }
}

package org.refptr.iscala
package tests

import org.specs2.mutable.Specification

object Plain {
    def unapply(data: Data): Option[String] = data match {
        case Data((MIME.`text/plain`, output)) => Some(output)
        case _ => None
    }
}

class InterpreterSpec extends Specification {
    sequential

    val classpath = Sbt.resolveCompiler().classpath
    val intp = new Interpreter(classpath, Nil)

    "IScala's interpreter" should {
        import intp.{interpretWithOutput=>interpret}
        import Results._

        "support primitive values" in {
            interpret("1") must beLike { case Output(Value(_, "Int", Plain("1")), "", "") => ok }
            interpret("1.0") must beLike { case Output(Value(_, "Double", Plain("1.0")), "", "") => ok }
            interpret("\"XXX\"") must beLike { case Output(Value(_, "String", Plain("XXX")), "", "") => ok }
        }

        "support function values" in {
            interpret("() => 1") must beLike { case Output(Value(_, "() => Int", Plain("<function0>")), "", "") => ok }
            interpret("(x: Int) => x + 1") must beLike { case Output(Value(_, "Int => Int", Plain("<function1>")), "", "") => ok }
            interpret("(x: Int, y: Int) => x*y + 1") must beLike { case Output(Value(_, "(Int, Int) => Int", Plain("<function2>")), "", "") => ok }
        }

        "support printing" in {
            interpret("println(\"XXX\")") === Output(NoValue, "XXX\n", "")
            interpret("print(\"XXX\")") === Output(NoValue, "XXX", "")
        }
    }
}

Test generation of the string representation


package org.langmeta
package io

import java.net._

final case class Fragment(base: AbsolutePath, name: RelativePath) {
  def uri: URI = {
    val baseuri = base.toURI.normalize
    if (baseuri.toString.endsWith(".jar")) new URI(s"jar:$baseuri!/$name")
    else base.resolve(name).toURI.normalize
  }
  def syntax: String = uri.toString
  def structure: String = s"""Fragment(${base.structure}, ${name.structure})"""
  override def toString = syntax
}

package org.langmeta
package io

import java.net._
import org.langmeta.internal.io.PathIO

final case class Fragment(base: AbsolutePath, name: RelativePath) {
  def uri: URI = {
    val baseuri = base.toURI.normalize
    if (baseuri.toString.endsWith(".jar")) {
      val reluri = PathIO.toUnix(name.toString)
      new URI(s"jar:$baseuri!/$reluri")
    } else {
      base.resolve(name).toURI.normalize
    }
  }
  def syntax: String = uri.toString
  def structure: String = s"""Fragment(${base.structure}, ${name.structure})"""
  override def toString = syntax
}

Normalize relative path inside jar files for Windows compat.

Path.toString on windows uses backslashes which are invalid in the
relative path section of a jar URI (the part after !/). This commit
converts \ to / in the relative path part.


import sbt._

object Dependencies {
  val CaffeineVersion = "2.3.0"

  val Caffeine = "com.github.ben-manes.caffeine" % "caffeine" % CaffeineVersion
  val Java8Compat = "org.scala-lang.modules" %% "scala-java8-compat" % "0.7.0"
  val Jsr305 = "com.google.code.findbugs" % "jsr305" % "3.0.1"
  val Scalactic = "org.scalactic" %% "scalactic" % "2.2.6"
  val Scalatest = "org.scalatest" %% "scalatest" % "2.2.6"
}

import sbt._

object Dependencies {
  val CaffeineVersion = "2.3.1"

  val Caffeine = "com.github.ben-manes.caffeine" % "caffeine" % CaffeineVersion
  val Java8Compat = "org.scala-lang.modules" %% "scala-java8-compat" % "0.7.0"
  val Jsr305 = "com.google.code.findbugs" % "jsr305" % "3.0.1"
  val Scalactic = "org.scalactic" %% "scalactic" % "2.2.6"
  val Scalatest = "org.scalatest" %% "scalatest" % "2.2.6"
}

Bump caffeine version 2.3.0 -> 2.3.1

Bump caffeine version 2.3.0 -> 2.3.1


addSbtPlugin("com.jsuereth" % "sbt-pgp" % "1.0.1")
addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "1.1")
addSbtPlugin("com.github.gseitz" % "sbt-release" % "1.0.3")
addSbtPlugin("com.github.scalaprops" % "sbt-scalaprops" % "0.1.1")
addSbtPlugin("org.tpolecat" % "tut-plugin" % "0.4.6")
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.2.16")

addSbtPlugin("com.jsuereth" % "sbt-pgp" % "1.0.1")
addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "1.1")
addSbtPlugin("com.github.gseitz" % "sbt-release" % "1.0.3")
addSbtPlugin("com.github.scalaprops" % "sbt-scalaprops" % "0.1.1")
addSbtPlugin("org.tpolecat" % "tut-plugin" % "0.4.7")
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.2.17")

Upgrade to tut 0.4.7 and sbt-jmh 0.2.17

Upgrade to tut 0.4.7 and sbt-jmh 0.2.17


resolvers += Resolver.url("artifactory", url("http://scalasbt.artifactoryonline.com/scalasbt/sbt-plugin-releases"))(Resolver.ivyStylePatterns)

resolvers ++= Seq(
  "jgit-repo" at "http://download.eclipse.org/jgit/maven",
  "sonatype-releases"  at "http://oss.sonatype.org/content/repositories/releases"
)

addSbtPlugin("com.typesafe.sbt" % "sbt-git" % "0.6.2")

addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "0.1.6")

addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.10.0")

addSbtPlugin("com.typesafe.sbt" % "sbt-ghpages" % "0.5.1")

resolvers += Resolver.url("artifactory", url("http://scalasbt.artifactoryonline.com/scalasbt/sbt-plugin-releases"))(Resolver.ivyStylePatterns)

resolvers ++= Seq(
  "jgit-repo" at "http://download.eclipse.org/jgit/maven",
  "sonatype-releases"  at "http://oss.sonatype.org/content/repositories/releases"
)

addSbtPlugin("com.typesafe.sbt" % "sbt-git" % "0.6.2")

addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "0.1.6")

addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.10.2")

addSbtPlugin("com.typesafe.sbt" % "sbt-ghpages" % "0.5.1")

Upgrade sbt assembly to latest version

Upgrade sbt assembly to latest version


libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.2.11"

// https://github.com/coursier/coursier/issues/450
classpathTypes += "maven-plugin"

addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "4.2.4")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.11.0")
addSbtPlugin("com.github.tkawachi" % "sbt-doctest" % "0.10.0")
addSbtPlugin("org.http4s" % "sbt-http4s-org" % "0.14.4")
addSbtPlugin("com.github.sbt" % "sbt-native-packager" % "1.9.11")
addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.3")
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.10.1")
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "2.0.2")

libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.2.11"

// https://github.com/coursier/coursier/issues/450
classpathTypes += "maven-plugin"

addSbtPlugin("com.earldouglas" % "xsbt-web-plugin" % "4.2.4")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.11.0")
addSbtPlugin("com.github.tkawachi" % "sbt-doctest" % "0.10.0")
addSbtPlugin("org.http4s" % "sbt-http4s-org" % "0.14.4")
addSbtPlugin("com.github.sbt" % "sbt-native-packager" % "1.9.11")
addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")
addSbtPlugin("pl.project13.scala" % "sbt-jmh" % "0.4.3")
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.10.1")
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "2.0.3")

Update sbt-scoverage to 2.0.3 in series/0.23


addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "1.0.1")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.10.0")
addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.9.10")
addSbtPlugin("com.github.sbt" % "sbt-pgp" % "2.1.2")
addSbtPlugin("com.timushev.sbt" % "sbt-updates" % "0.6.0")
addSbtPlugin("com.github.sbt" % "sbt-release" % "1.1.0")
addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "1.1.0")
addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.1.0")
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.7.1")
addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.4.1")
addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.5")

scalacOptions ++= Seq("-unchecked", "-deprecation", "-feature")

addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "1.0.1")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.10.0")
addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.9.10")
addSbtPlugin("com.github.sbt" % "sbt-pgp" % "2.1.2")
addSbtPlugin("com.timushev.sbt" % "sbt-updates" % "0.6.0")
addSbtPlugin("com.github.sbt" % "sbt-release" % "1.1.0")
addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "1.1.0")
addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.1.0")
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.7.1")
addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.4.2")
addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.5")

scalacOptions ++= Seq("-unchecked", "-deprecation", "-feature")

Update auxlib, javalib, nativelib, nscplugin, ... to 0.4.2 in master


resolvers += "nexus snapshots" at "http://nexus.scala-tools.org/content/repositories/snapshots"

addSbtPlugin("org.scala-tools.sbt" % "sbt-android-plugin" % "0.6.1-SNAPSHOT")

resolvers += Resolver.url("scalasbt snapshots", new URL("http://scalasbt.artifactoryonline.com/scalasbt/sbt-plugin-snapshots"))(Resolver.ivyStylePatterns)

addSbtPlugin("org.scala-sbt" % "sbt-android-plugin" % "0.6.1-SNAPSHOT")

Update plugin configuration to point to new location and organization.

--HG--
extra : convert_revision : e27bb4974ce98c7fb02d6e418cba99f2e70e49d6


enablePlugins(org.nlogo.build.NetLogoExtension, org.nlogo.build.ExtensionDocumentationPlugin)

version := "1.1.1"

netLogoExtName      := "palette"

netLogoClassManager := "PaletteExtension"

netLogoTarget :=
  org.nlogo.build.NetLogoExtension.directoryTarget(baseDirectory.value)

netLogoZipSources   := false

javaSource in Compile := baseDirectory.value / "src"

javacOptions ++= Seq("-g", "-Xlint:deprecation", "-Xlint:all", "-Xlint:-serial", "-Xlint:-path",
  "-encoding", "us-ascii")

resolvers      += "netlogo" at "https://dl.cloudsmith.io/public/netlogo/netlogo/maven/"
netLogoVersion := "6.2.0-d27b502"
isSnapshot := true

Add isSnapshot := true for debugging convenience


autoScalaLibrary := false

javacOptions ++=
    "-source" :: "1.7" ::
    "-target" :: "1.7" ::
    Nil

libraryDependencies ++=
    "com.android.support" % "design" % "23.1.0" ::
    Nil

name := "FloatingLabelLayout"

normalizedName := "floating-label-layout"

organization := "io.taig.android"

publishArtifact in ( Compile, packageDoc ) := false

scalaVersion := "2.11.7"

scalacOptions ++=
    "-deprecation" ::
    "-feature" ::
    Nil

version := "1.1.0"

autoScalaLibrary := false

javacOptions ++=
    "-source" :: "1.7" ::
    "-target" :: "1.7" ::
    Nil

libraryDependencies ++=
    "com.android.support" % "design" % "23.1.1" ::
    Nil

name := "FloatingLabelLayout"

normalizedName := "floating-label-layout"

organization := "io.taig.android"

publishArtifact in ( Compile, packageDoc ) := false

scalaVersion := "2.11.7"

scalacOptions ++=
    "-deprecation" ::
    "-feature" ::
    Nil

version := "1.1.0"

Upgrade to android support library 23.1.1


name := "cosmos-platform"

organization in ThisBuild := "es.tid.cosmos"

// Note: This is the Scala version used by Play 2.2.0. Ensure Play compatibility before upgrading.
scalaVersion in ThisBuild := "2.10.2"

scalacOptions in ThisBuild ++= Seq("-deprecation", "-feature")

resolvers in ThisBuild ++= Seq(
    DefaultMavenRepository,
    "Cosmos Nexus Repository" at "http://cosmos10/nexus/content/groups/public/",
    "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/",
    Resolver.url("Play", url("http://download.playframework.org/ivy-releases/"))(Resolver.ivyStylePatterns)
)

libraryDependencies in ThisBuild ++= Seq(
    "org.scalatest" %% "scalatest" % "1.9.1" % "test, it",
    "org.mockito" % "mockito-all" % "1.9.5" % "test, it"
)

name := "cosmos-platform"

organization in ThisBuild := "es.tid.cosmos"

// Note: This is the Scala version used by Play 2.2.0. Ensure Play compatibility before upgrading.
scalaVersion in ThisBuild := "2.10.2"

scalacOptions in ThisBuild ++= Seq("-deprecation", "-feature")

addCommandAlias("run-local-it", ";it:compile ;it:test-only * -- -l \"HasExternalDependencies EndToEndTest\"")

resolvers in ThisBuild ++= Seq(
    DefaultMavenRepository,
    "Cosmos Nexus Repository" at "http://cosmos10/nexus/content/groups/public/",
    "Typesafe Repository" at "http://repo.typesafe.com/typesafe/releases/",
    Resolver.url("Play", url("http://download.playframework.org/ivy-releases/"))(Resolver.ivyStylePatterns)
)

libraryDependencies in ThisBuild ++= Seq(
    "org.scalatest" %% "scalatest" % "1.9.1" % "test, it",
    "org.mockito" % "mockito-all" % "1.9.5" % "test, it"
)

Add alias to run local ITs

Add alias to run local ITs


package eu.shiftforward.icfpc2015.solver

import eu.shiftforward.icfpc2015.GameState
import eu.shiftforward.icfpc2015.model.Command

trait Solver {
  def play(initialState: GameState): Seq[Command]
}

object NaivePowerPhrasesSolver extends Solver {

  // right now this is only for documentation
  val knownWords = List(
    "Ei!", // from statement
    "Ia! Ia!", // (?) from problem 3 grid
    "R'lyeh") // (?) from problem 5 grid

  def play(initialState: GameState) = {
    val commandsIter = Iterator.continually("Ei! ".toIterator).flatten

    def fillUntilGameOver(state: GameState, history: List[Char] = Nil): List[Char] =
      if (state.gameOver) history.reverse
      else {
        val next = commandsIter.next()
        fillUntilGameOver(state.nextState(next), next :: history)
      }

    fillUntilGameOver(initialState).map(Command.char)
  }
}

package eu.shiftforward.icfpc2015.solver

import eu.shiftforward.icfpc2015.GameState
import eu.shiftforward.icfpc2015.model.Command

trait Solver {
  def play(initialState: GameState): Seq[Command]
}

/**
 * Points for problems 0 to 3 (2015-08-07 20:21):
 *
 * "Ei! " - [383, 0, 152, 326]
 * "Ei!Ia! Ia!R'lyeh" - [0, 0, 316, 501]
 */
object NaivePowerPhrasesSolver extends Solver {

  // right now this is only for documentation
  val knownWords = List(
    "Ei!", // from statement
    "Ia! Ia!", // from problem 3 grid
    "R'lyeh", // from problem 5 grid
    "Yuggoth") // from problem 7 grid

  def play(initialState: GameState) = {
    val commandsIter = Iterator.continually("Ei! ".toIterator).flatten

    def fillUntilGameOver(state: GameState, history: List[Char] = Nil): List[Char] =
      if (state.gameOver) history.reverse
      else {
        val next = commandsIter.next()
        fillUntilGameOver(state.nextState(next), next :: history)
      }

    fillUntilGameOver(initialState).map(Command.char)
  }
}

Update phrases of power list and add some stats


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

package com.codnos.dbgp

import java.util.concurrent.Callable

trait AwaitilitySupport {
  implicit def byNameFunctionToCallableOfType[T](function: => T): Callable[T] = {
    new Callable[T] {
      def call(): T = function
    }
  }
  implicit def byNameFunctionToRunnable[T](function: => T): Runnable = {
    new Runnable {
      def run(): Unit = function
    }
  }
}

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

package com.codnos.dbgp

import java.util.concurrent.Callable

trait AwaitilitySupport {
  implicit def byNameFunctionToCallableOfType[T](function: () => T): Callable[T] = {
    new Callable[T] {
      def call(): T = function()
    }
  }
  implicit def byNameFunctionToRunnable[T](function: () => T): Runnable = {
    new Runnable {
      def run() = function()
    }
  }
}

Fix awaitility support to actually call the function.


name := "lib-reference-scala"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "org.scalatest" %% "scalatest" % "3.0.2" % Test
    )
  )

publishTo := {
  val host = "https://flow.artifactoryonline.com/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}
version := "0.1.8"

name := "lib-reference-scala"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "org.scalatest" %% "scalatest" % "3.0.2" % Test
    )
  )

publishTo := {
  val host = "https://flow.artifactoryonline.com/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}
version := "0.1.9"

autocommit: Update configuration to record version 0.1.9


import org.nlogo.build.{ NetLogoExtension, ExtensionDocumentationPlugin }

enablePlugins(NetLogoExtension, ExtensionDocumentationPlugin)

version    := "2.0.1"
isSnapshot := true

netLogoVersion      := "6.2.2"
netLogoExtName      := "palette"
netLogoClassManager := "PaletteExtension"

javaSource in Compile := baseDirectory.value / "src" / "main"
javacOptions ++= Seq("-g", "-Xlint:deprecation", "-Xlint:all", "-Xlint:-serial", "-Xlint:-path", "-encoding", "us-ascii")

scalaVersion := "2.12.12"
scalaSource in Test := baseDirectory.value / "src" / "test"
scalacOptions ++= Seq("-deprecation", "-unchecked", "-Xfatal-warnings", "-feature", "-encoding", "us-ascii")

import org.nlogo.build.{ NetLogoExtension, ExtensionDocumentationPlugin }

enablePlugins(NetLogoExtension, ExtensionDocumentationPlugin)

version    := "2.0.1"
isSnapshot := true

netLogoVersion      := "6.2.2"
netLogoExtName      := "palette"
netLogoClassManager := "PaletteExtension"

javaSource in Compile := baseDirectory.value / "src" / "main"
javacOptions ++= Seq("-g", "-Xlint:deprecation", "-Xlint:all", "-Xlint:-serial", "-Xlint:-path", "-encoding", "us-ascii", "--release", "11")

scalaVersion := "2.12.12"
scalaSource in Test := baseDirectory.value / "src" / "test"
scalacOptions ++= Seq("-deprecation", "-unchecked", "-Xfatal-warnings", "-feature", "-encoding", "us-ascii", "-release", "11")

Add `-release 11` for J11 compatibility

Infrastructure: Add `-release 11` for J11 compatibility


import play.PlayImport.PlayKeys._

name := "lib-play"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.7"

crossScalaVersions := Seq("2.11.7")

version := "0.0.29"

lazy val root = project
  .in(file("."))
  .enablePlugins(PlayScala)
  .settings(
    libraryDependencies ++= Seq(
      ws,
      "org.scalatest" %% "scalatest" % "2.2.6" % "test",
      "org.scalatestplus" %% "play" % "1.4.0" % "test"
    )
)

publishTo := {
  val host = "https://flow.artifactoryonline.com/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}

import play.PlayImport.PlayKeys._

name := "lib-play"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.7"

crossScalaVersions := Seq("2.11.7")

version := "0.0.30"

lazy val root = project
  .in(file("."))
  .enablePlugins(PlayScala)
  .settings(
    libraryDependencies ++= Seq(
      ws,
      "org.scalatest" %% "scalatest" % "2.2.6" % "test",
      "org.scalatestplus" %% "play" % "1.4.0" % "test"
    )
)

publishTo := {
  val host = "https://flow.artifactoryonline.com/flow"
  if (isSnapshot.value) {
    Some("Artifactory Realm" at s"$host/libs-snapshot-local;build.timestamp=" + new java.util.Date().getTime)
  } else {
    Some("Artifactory Realm" at s"$host/libs-release-local")
  }
}

Increment version from 0.0.29 => 0.0.30

Increment version from 0.0.29 => 0.0.30


package ch.usi.inf.l3.sana.robustj.namers

import ch.usi.inf.l3.sana
import sana.primj
import sana.tiny
import sana.calcj
import sana.brokenj
import sana.arrayj
import sana.arrooj
import sana.ooj
import sana.robustj

import tiny.core.TransformationComponent
import tiny.dsl._
import robustj.ast.{TreeFactories, MethodDefApi, TreeCopiers, TreeUpgraders}
import primj.ast.{MethodDefApi => PMethodDefApi}
import tiny.ast.UseTree

@component
trait MethodDefNamerComponent extends
    ooj.namers.MethodDefNamerComponent {
  (mthd: PMethodDefApi) => {
    mthd match {
      case mthd: MethodDefApi                  =>
        val res1 = super.apply(mthd).asInstanceOf[PMethodDefApi]
        val throwsClause = mthd.throwsClause.map { tc =>
          name(tc).asInstanceOf[UseTree]
        }
        // INFO: a bit of hack, but works
        val res2 = TreeUpgraders.upgradeMethodDef(res1)
        TreeCopiers.copyMethodDef(res2)(throwsClause = throwsClause)
      case mthd: PMethodDefApi                  =>
        val res = TreeUpgraders.upgradeMethodDef(mthd)
        name(res)
    }
  }
}

package ch.usi.inf.l3.sana.robustj.namers

import ch.usi.inf.l3.sana
import sana.primj
import sana.tiny
import sana.calcj
import sana.brokenj
import sana.arrayj
import sana.arrooj
import sana.ooj
import sana.robustj

import tiny.core.TransformationComponent
import tiny.dsl._
import tiny.ast.Implicits._
import robustj.symbols.MethodSymbol
import robustj.ast.{TreeFactories, MethodDefApi, TreeCopiers, TreeUpgraders}
import primj.ast.{MethodDefApi => PMethodDefApi}
import tiny.ast.UseTree

@component
trait MethodDefNamerComponent extends
    ooj.namers.MethodDefNamerComponent {
  (mthd: PMethodDefApi) => {
    mthd match {
      case mthd: MethodDefApi                  =>
        val res1 = super.apply(mthd).asInstanceOf[PMethodDefApi]
        val throwsClause = mthd.throwsClause.map { tc =>
          name(tc).asInstanceOf[UseTree]
        }
        res1.symbol.foreach {
          case mthd: MethodSymbol     =>
            mthd.throwsSymbols = throwsClause.flatMap(_.symbol)
          case _                      =>
            ()
        }
        // INFO: a bit of hack, but works
        val res2 = TreeUpgraders.upgradeMethodDef(res1)
        TreeCopiers.copyMethodDef(res2)(throwsClause = throwsClause)
      case mthd: PMethodDefApi                  =>
        val res = TreeUpgraders.upgradeMethodDef(mthd)
        name(res)
    }
  }
}

Add the symbols of exceptions in throws clause to method symbol


package controllers

import util._
import play.api._
import          Play.current
import          mvc._
import          data._
import               Forms._
import          i18n.Messages
import models._

object Comment extends SiteController {

  type CommentForm = Form[String]
  val form = Form("text" -> nonEmptyText)

  private[this] def post(node : Annotated with SitePage)(request : SiteRequest[_]) =
    if (request.access < Permission.COMMENT)
      Forbidden
    else
      /* FIXME: poorly displayed and possibly untranslated error message: */
      form.bindFromRequest()(request).fold(form => BadRequest(form.errors.head.message), { text =>
        node.postComment(text)(request)
        Redirect(node.pageURL)
      })

  def postContainer(c : models.Container.Id) = Container.check(c, Permission.COMMENT)(post _)
  /* specializations of above: */
  def postStudy(s : models.Study.Id) = Study.check(s, Permission.COMMENT)(post _)
  def postSlot(s : models.Slot.Id) = Slot.check(s, Permission.COMMENT)(post _)
  def postAssetLink(c : models.Container.Id, o : models.Asset.Id) = Asset.check(c, o, Permission.COMMENT)(post _)
}

package controllers

import util._
import play.api._
import          Play.current
import          mvc._
import          data._
import               Forms._
import          i18n.Messages
import models._

object Comment extends SiteController {

  type CommentForm = Form[String]
  val form = Form("text" -> nonEmptyText)

  private[this] def post(node : Annotated with SitePage)(request : SiteRequest[_]) =
    if (request.access < Permission.COMMENT)
      Forbidden : Result
    else
      /* FIXME: poorly displayed and possibly untranslated error message: */
      form.bindFromRequest()(request).fold(form => BadRequest(form.errors.head.message), { text =>
        node.postComment(text)(request)
        Redirect(node.pageURL)
      })

  def postContainer(c : models.Container.Id) = Container.check(c, Permission.COMMENT)(post _)
  /* specializations of above: */
  def postStudy(s : models.Study.Id) = Study.check(s, Permission.COMMENT)(post _)
  def postSlot(s : models.Slot.Id) = Slot.check(s, Permission.COMMENT)(post _)
  def postAssetLink(c : models.Container.Id, o : models.Asset.Id) = Asset.check(c, o, Permission.COMMENT)(post _)
}

Fix lingering warning about overloaded result


latestVersion in ThisBuild := "0.7.1"
latestBinaryCompatibleVersion in ThisBuild := Some("0.7.1")
unreleasedModuleNames in ThisBuild := Set()

latestVersion in ThisBuild := "0.7.2"
latestBinaryCompatibleVersion in ThisBuild := Some("0.7.2")
unreleasedModuleNames in ThisBuild := Set()

Set latest version to 0.7.2

Set latest version to 0.7.2


package com.softwaremill.react.kafka

import akka.actor.ActorLogging
import akka.stream.actor.{ActorSubscriber, ActorSubscriberMessage, RequestStrategy}
import kafka.producer.KafkaProducer

private[kafka] class KafkaActorSubscriber[T](
  val producer: KafkaProducer[T],
  props: ProducerProperties[T],
  requestStrategyProvider: () => RequestStrategy
)
    extends ActorSubscriber with ActorLogging {

  override protected val requestStrategy = requestStrategyProvider()

  def receive = {
    case ActorSubscriberMessage.OnNext(element) =>
      processElement(element.asInstanceOf[T])
    case ActorSubscriberMessage.OnError(ex) =>
      handleError(ex)
    case ActorSubscriberMessage.OnComplete =>
      stop()
    case "close_producer" => producer.close()
  }

  private def processElement(element: T) = {
    producer.send(props.encoder.toBytes(element), props.partitionizer(element))
  }

  private def handleError(ex: Throwable) = {
    log.error("Stopping Kafka subscriber due to fatal error.", ex)
    stop()
  }

  def stop() = {
    cleanupResources()
    context.stop(self)
  }

  def cleanupResources(): Unit = producer.close()
}

package com.softwaremill.react.kafka

import akka.actor.ActorLogging
import akka.stream.actor.{ActorSubscriber, ActorSubscriberMessage, RequestStrategy}
import kafka.producer.KafkaProducer

private[kafka] class KafkaActorSubscriber[T](
  val producer: KafkaProducer[T],
  props: ProducerProperties[T],
  requestStrategyProvider: () => RequestStrategy
)
    extends ActorSubscriber with ActorLogging {

  override protected val requestStrategy = requestStrategyProvider()

  def receive = {
    case ActorSubscriberMessage.OnNext(element) =>
      processElement(element.asInstanceOf[T])
    case ActorSubscriberMessage.OnError(ex) =>
      handleError(ex)
    case ActorSubscriberMessage.OnComplete =>
      stop()
    case "close_producer" => producer.close()
  }

  private def processElement(element: T) = {
    producer.send(props.encoder.toBytes(element), props.partitionizer(element))
  }

  private def handleError(ex: Throwable) = {
    log.error(ex, "Stopping Kafka subscriber due to fatal error.")
    stop()
  }

  def stop() = {
    cleanupResources()
    context.stop(self)
  }

  def cleanupResources(): Unit = producer.close()
}

Fix error log messages. Throwable should be the first parameter.


package io.aigar.game

import com.github.jpbetz.subspace.Vector2
import io.aigar.score.ScoreModification
import scala.collection.mutable.MutableList

trait EntityContainer {
  def shouldRespawn(size: Int, min: Int, max: Int): Boolean = {
    val ratio = (size - min).toFloat / (max - min)
    scala.util.Random.nextFloat >= ratio
  }

  def getRespawnPosition(grid: Grid,
                         players: List[Player],
                         respawnRetryAttempts: Int): Option[Vector2] = {
    1 to respawnRetryAttempts foreach { _ =>
      var collides = false
      val newPosition = grid.randomPosition
      for (player <- players) {
        for (cell <- player.cells) {
          if (cell.contains(newPosition)) collides = true
        }
      }
      if (!collides) return Some(newPosition)
    }
    None
  }

  def handleCollision(entities: List[Entity],
                      players: List[Player],
                      scoreModifications: Option[MutableList[ScoreModification]]): List[Entity] ={
    var entitiesReturn = List[Entity]()
    for (entity <- entities){
      for (player <- players) {
        for (cell <- player.cells) {
          if (cell.contains(entity.position)) {
            entitiesReturn :::= onCellCollision(cell, player, entity, scoreModifications)
          }
        }
      }
    }
    entities diff entitiesReturn
  }

  def onCellCollision(cell: Cell,
                      player: Player,
                      entity: Entity,
                      scoreModifications: Option[MutableList[ScoreModification]]): List[Entity]
}

package io.aigar.game

import com.github.jpbetz.subspace.Vector2
import io.aigar.score.ScoreModification
import scala.collection.mutable.MutableList

trait EntityContainer {
  def shouldRespawn(size: Int, min: Int, max: Int): Boolean = {
    val ratio = (size - min).toFloat / (max - min)
    scala.util.Random.nextFloat >= ratio
  }

  def getRespawnPosition(grid: Grid,
                         players: List[Player],
                         respawnRetryAttempts: Int): Option[Vector2] = {
    1 to respawnRetryAttempts foreach { _ =>
      var collides = false
      val newPosition = grid.randomPosition
      for (player <- players) {
        for (cell <- player.cells) {
          if (cell.contains(newPosition)) collides = true
        }
      }
      if (!collides) return Some(newPosition)
    }
    None
  }

  def handleCollision(entities: List[Entity],
                      players: List[Player],
                      scoreModifications: Option[MutableList[ScoreModification]]): List[Entity] ={
    var entitiesReturn = List[Entity]()
    for (entity <- entities){
      for (player <- players) {
        for (cell <- player.cells) {
          if (cell.overlaps(entity)) {
            entitiesReturn :::= onCellCollision(cell, player, entity, scoreModifications)
          }
        }
      }
    }
    entities diff entitiesReturn
  }

  def onCellCollision(cell: Cell,
                      player: Player,
                      entity: Entity,
                      scoreModifications: Option[MutableList[ScoreModification]]): List[Entity]
}

Use overlaps instead of contains

Use overlaps instead of contains


import java.lang.Integer

object IntegerTest {
  def main(args: Array[String]): Unit = {
    testIntegerToString()
  }

  def testIntegerToString() = {
    // issue #270
    println(Integer.toString(1).equals("1"))
    println(Integer.toString(-1).equals("1"))
    println(Integer.toString(123).equals("123"))
    println(Integer.toString(-123).equals("-123"))
    println(Integer.toString(1234).equals("1234"))
    println(Integer.toString(-1234).equals("-1234"))
  }
}

import java.lang.Integer

object IntegerTest {
  def main(args: Array[String]): Unit = {
    testIntegerToString()
  }

  def testIntegerToString() = {
    // issue #270
    assert(Integer.toString(1).equals("1"))
    assert(Integer.toString(-1).equals("-1"))
    assert(Integer.toString(123).equals("123"))
    assert(Integer.toString(-123).equals("-123"))
    assert(Integer.toString(1234).equals("1234"))
    assert(Integer.toString(-1234).equals("-1234"))
  }
}

Put `assert`s in test `run/java-lang-integer`

The scripted tests won't fail unless the execution is actually stopped
by a failed assertion.

Also, fix a typo in the test.


package org.http4s.client.blaze

import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.{SSLContext, X509TrustManager}
import org.http4s.BuildInfo
import org.http4s.blaze.util.TickWheelExecutor
import org.http4s.headers.{AgentProduct, `User-Agent`}
import scala.concurrent.duration._

private[blaze] object bits {
  // Some default objects
  val DefaultResponseHeaderTimeout: Duration = 10.seconds
  val DefaultTimeout: Duration = 60.seconds
  val DefaultBufferSize: Int = 8 * 1024
  val DefaultUserAgent = Some(`User-Agent`(AgentProduct("http4s-blaze", Some(BuildInfo.version))))
  val DefaultMaxTotalConnections = 10
  val DefaultMaxWaitQueueLimit = 256

  val ClientTickWheel = new TickWheelExecutor()

  /** Caution: trusts all certificates and disables endpoint identification */
  lazy val TrustingSslContext: SSLContext = {
    val trustManager = new X509TrustManager {
      def getAcceptedIssuers(): Array[X509Certificate] = Array.empty
      def checkClientTrusted(certs: Array[X509Certificate], authType: String): Unit = {}
      def checkServerTrusted(certs: Array[X509Certificate], authType: String): Unit = {}
    }
    val sslContext = SSLContext.getInstance("TLS")
    sslContext.init(null, Array(trustManager), new SecureRandom)
    sslContext
  }
}

package org.http4s.client.blaze

import java.security.SecureRandom
import java.security.cert.X509Certificate
import javax.net.ssl.{SSLContext, X509TrustManager}
import org.http4s.BuildInfo
import org.http4s.blaze.util.TickWheelExecutor
import org.http4s.headers.{AgentProduct, `User-Agent`}
import scala.concurrent.duration._

private[blaze] object bits {
  // Some default objects
  val DefaultResponseHeaderTimeout: Duration = 10.seconds
  val DefaultTimeout: Duration = 60.seconds
  val DefaultBufferSize: Int = 8 * 1024
  val DefaultUserAgent = Some(`User-Agent`(AgentProduct("http4s-blaze", Some(BuildInfo.version))))
  val DefaultMaxTotalConnections = 10
  val DefaultMaxWaitQueueLimit = 256

  lazy val ClientTickWheel = new TickWheelExecutor()

  /** Caution: trusts all certificates and disables endpoint identification */
  lazy val TrustingSslContext: SSLContext = {
    val trustManager = new X509TrustManager {
      def getAcceptedIssuers(): Array[X509Certificate] = Array.empty
      def checkClientTrusted(certs: Array[X509Certificate], authType: String): Unit = {}
      def checkServerTrusted(certs: Array[X509Certificate], authType: String): Unit = {}
    }
    val sslContext = SSLContext.getInstance("TLS")
    sslContext.init(null, Array(trustManager), new SecureRandom)
    sslContext
  }
}

Make the blaze-client tick wheel executor lazy


package edu.berkeley.cs.succinct

import org.apache.hadoop.conf.Configuration
import org.apache.spark.SparkContext
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.SparkSession

package object annot {

  implicit class SuccinctContext(sc: SparkContext) {
    def annotatedSuccinctFile(filePath: String, annotClassFilter: String = ".*", annotTypeFilter: String = ".*"): AnnotatedSuccinctRDD = {
      AnnotatedSuccinctRDD(sc, filePath, annotClassFilter, annotTypeFilter)
    }
  }

  implicit class SuccinctSession(spark: SparkSession) {
    def annotatedSuccinctFile(filePath: String, annotClassFilter: String = ".*", annotTypeFilter: String = ".*"): AnnotatedSuccinctRDD = {
      AnnotatedSuccinctRDD(spark.sparkContext, filePath, annotClassFilter, annotTypeFilter)
    }
  }

  implicit class AnnotSuccinctRDD(rdd: RDD[(String, String, String)]) {
    def succinctAnnotated: AnnotatedSuccinctRDD = {
      AnnotatedSuccinctRDD(rdd)
    }

    def saveAsAnnotatedSuccinctFile(path: String, conf: Configuration = new Configuration()): Unit = {
      AnnotatedSuccinctRDD(rdd).save(path, conf)
    }
  }

}

package edu.berkeley.cs.succinct

import org.apache.hadoop.conf.Configuration
import org.apache.spark.SparkContext
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.SparkSession

package object annot {

  implicit class SuccinctContext(sc: SparkContext) {
    def annotatedSuccinctFile(filePath: String, annotClassFilter: String = ".*", annotTypeFilter: String = ".*"): AnnotatedSuccinctRDD = {
      AnnotatedSuccinctRDD(sc, filePath, annotClassFilter, annotTypeFilter)
    }
  }

  implicit class SuccinctSession(spark: SparkSession) {
    def annotatedSuccinctFile(filePath: String, annotClassFilter: String = ".*", annotTypeFilter: String = ".*"): AnnotatedSuccinctRDD = {
      AnnotatedSuccinctRDD(spark.sparkContext, filePath, annotClassFilter, annotTypeFilter)
    }
  }

  implicit class AnnotSuccinctRDD(rdd: RDD[(String, String, String)]) {
    def succinctAnnotated: AnnotatedSuccinctRDD = {
      AnnotatedSuccinctRDD(rdd)
    }

    def saveAsAnnotatedSuccinctFile(path: String, conf: Configuration = new Configuration()): Unit = {
      AnnotatedSuccinctRDD.construct(rdd, path, conf)
    }
  }

}

Add shortcut method for converting RDD[(String, String, String)] to AnnotatedSuccinctRDD


scalacOptions := Seq(
  "-deprecation"
)

// For MimeLoader plugin. Dogfooding and hoping it doesn't clash with
// our other sbt plugins.
libraryDependencies ++= List(
  "com.eed3si9n" %% "treehugger" % "0.4.4",
  "io.circe" %% "circe-generic" % "0.12.3",
  "org.http4s" %% "http4s-blaze-client" % "0.20.11",
  "org.http4s" %% "http4s-circe" % "0.20.11",
)

// Hack around a binary conflict in scalameta's dependency on
// fastparse as specified by sbt-doctest-0.9.5.
libraryDependencies += "org.scalameta" %% "scalameta" % "4.2.4"

scalacOptions := Seq(
  "-deprecation"
)

// For MimeLoader plugin. Dogfooding and hoping it doesn't clash with
// our other sbt plugins.
libraryDependencies ++= List(
  "com.eed3si9n" %% "treehugger" % "0.4.4",
  "io.circe" %% "circe-generic" % "0.12.3",
  "org.http4s" %% "http4s-blaze-client" % "0.20.12",
  "org.http4s" %% "http4s-circe" % "0.20.12",
)

// Hack around a binary conflict in scalameta's dependency on
// fastparse as specified by sbt-doctest-0.9.5.
libraryDependencies += "org.scalameta" %% "scalameta" % "4.2.4"

Update http4s-blaze-client, http4s-circe to 0.20.12


package scalacss

import org.scalajs.dom
import org.scalajs.dom.raw.HTMLStyleElement
import scalatags.JsDom._
import all._

trait ScalatagsJsDomImplicits {

  implicit final def styleaToJsDomTag(s: StyleA): Modifier = new Modifier {
    def applyTo(t: dom.Element) = t.classList.add(s.htmlClass)
  }

  implicit final def styleJsDomTagRenderer(implicit s: Renderer[String]): Renderer[TypedTag[HTMLStyleElement]] =
    new ScalatagsJsDomRenderer(s)
}

class ScalatagsJsDomRenderer(s: Renderer[String]) extends Renderer[TypedTag[HTMLStyleElement]] {
  override def apply(css: Css) =
    tags2.style(`type` := "text/css", s(css))
}

package scalacss

import org.scalajs.dom
import org.scalajs.dom.raw.HTMLStyleElement
import scalatags.JsDom._
import all._

trait ScalatagsJsDomImplicits {

  implicit final def styleaToJsDomTag(s: StyleA): Modifier = new Modifier {
    def applyTo(t: dom.Element) = s.htmlClass.split(' ').foreach(cn => t.classList.add(cn))
  }

  implicit final def styleJsDomTagRenderer(implicit s: Renderer[String]): Renderer[TypedTag[HTMLStyleElement]] =
    new ScalatagsJsDomRenderer(s)
}

class ScalatagsJsDomRenderer(s: Renderer[String]) extends Renderer[TypedTag[HTMLStyleElement]] {
  override def apply(css: Css) =
    tags2.style(`type` := "text/css", s(css))
}

Add each class name to the DOM individually, to prevent InvalidCharacterErrors.


name := "l_space"

version := "0.0.1-WORKPRINT"

scalaVersion := "2.11.7"

mainClass := Some("org.mediachain.LSpace")

libraryDependencies ++= Seq(
  "com.michaelpollmeier" % "gremlin-scala_2.11" % "3.1.0-incubating.1",
  "org.typelevel" %% "cats" % "0.4.1"
)

Add gremlin & utility libraries

Add gremlin & utility libraries


latestVersion in ThisBuild := "0.6.0"
latestBinaryCompatibleVersion in ThisBuild := Some("0.6.0")
unreleasedModuleNames in ThisBuild := Set()

latestVersion in ThisBuild := "0.6.1"
latestBinaryCompatibleVersion in ThisBuild := Some("0.6.1")
unreleasedModuleNames in ThisBuild := Set()

Set latest version to 0.6.1

Set latest version to 0.6.1


resolvers ++= Seq(
  "socrata snapshots" at "http://repository-socrata-oss.forge.cloudbees.com/snapshot",
  "socrata releases" at "http://repository-socrata-oss.forge.cloudbees.com/release"
)

addSbtPlugin("com.socrata" % "socrata-cloudbees-sbt" % "0.0.1-SNAPSHOT")

resolvers ++= Seq(
  "socrata releases" at "http://repository-socrata-oss.forge.cloudbees.com/release"
)

addSbtPlugin("com.socrata" % "socrata-cloudbees-sbt" % "1.0.0")

Use the release version of socrata-cloudbees-sbt


package au.gov.dva.sopapi.tests.parsers;

import au.gov.dva.dvasopapi.tests.TestUtils
import au.gov.dva.sopapi.sopref.data.sops.StoredSop
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class LumbarSpondylosisTests extends FunSuite{

//  test("Parse entire RH LS SoP") {
//    val result = ParserTestUtils.executeWholeParsingPipeline("F2014L00933", "sops_rh/F2014L00933.pdf")
//    System.out.print(TestUtils.prettyPrint(StoredSop.toJson(result)))
//
//   // assert(result != null)
//  }
//
//  test("Parse entire BoP LS SoP")
//  {
//    val result = ParserTestUtils.executeWholeParsingPipeline("F2014L00930", "sops_bop/F2014L00930.pdf")
//    System.out.println(TestUtils.prettyPrint(StoredSop.toJson(result)))
// //   assert(result != null)
//  }

}

package au.gov.dva.sopapi.tests.parsers;

import au.gov.dva.dvasopapi.tests.TestUtils
import au.gov.dva.sopapi.sopref.data.sops.StoredSop
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class LumbarSpondylosisTests extends FunSuite{

  test("Parse entire RH LS SoP") {
    val result = ParserTestUtils.executeWholeParsingPipeline("F2014L00933", "sops_rh/F2014L00933.pdf")
    //System.out.print(TestUtils.prettyPrint(StoredSop.toJson(result)))
    assert(result != null)
  }

  test("Parse entire BoP LS SoP")
  {
    val result = ParserTestUtils.executeWholeParsingPipeline("F2014L00930", "sops_bop/F2014L00930.pdf")
    //System.out.println(TestUtils.prettyPrint(StoredSop.toJson(result)))
    assert(result != null)
  }

}

Comment out json printing to see if something in Jackson is the source of failed assertion.


// Comment to get more information during initialization
logLevel := Level.Warn

//resolvers += "Local Repository" at "http://localhost:8090/publish"

// Enable it for Play 2.0.3
resolvers += "Typesafe releases" at "http://repo.typesafe.com/typesafe/releases"

resolvers += Resolver.file("Local Ivy Repository", file(Path.userHome.absolutePath+"/.ivy2/local"))(Resolver.ivyStylePatterns)

resolvers += Resolver.url("Play2war plugin snapshot", url("http://repository-play-war.forge.cloudbees.com/snapshot/"))(Resolver.ivyStylePatterns)

// Use the Play sbt plugin for Play projects
addSbtPlugin("play" % "sbt-plugin" % Option(System.getProperty("play.version")).getOrElse("2.1-RC2"))

//addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.0.0")

addSbtPlugin("com.github.play2war" % "play2-war-plugin" % "0.9-SNAPSHOT")

// Comment to get more information during initialization
logLevel := Level.Warn

//resolvers += "Local Repository" at "http://localhost:8090/publish"

// Enable it for Play 2.0.3
resolvers += "Typesafe releases" at "http://repo.typesafe.com/typesafe/releases"

resolvers += Resolver.file("Local Ivy Repository", file(Path.userHome.absolutePath+"/.ivy2/local"))(Resolver.ivyStylePatterns)

resolvers += Some("snapshots" at "https://oss.sonatype.org/content/repositories/snapshots")

// Use the Play sbt plugin for Play projects
addSbtPlugin("play" % "sbt-plugin" % Option(System.getProperty("play.version")).getOrElse("2.1-RC2"))

//addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.0.0")

addSbtPlugin("com.github.play2war" % "play2-war-plugin" % "0.9-SNAPSHOT")

Migrate from Cloudbees repo to OSS

Migrate from Cloudbees repo to OSS