package aws

import com.amazonaws.services.dynamodbv2.AmazonDynamoDBAsyncClient
import com.amazonaws.services.dynamodbv2.model._

import scala.concurrent.Future

object AsyncDynamo {
  def keyEquals(s: String) = new Condition()
    .withComparisonOperator(ComparisonOperator.EQ)
    .withAttributeValueList(new AttributeValue(s))

  def keyGE(s: String) = new Condition()
    .withComparisonOperator(ComparisonOperator.GE)
    .withAttributeValueList(new AttributeValue(s))

  def keyLT(s: String) = new Condition()
    .withComparisonOperator(ComparisonOperator.LT)
    .withAttributeValueList(new AttributeValue(s))
}

class AsyncDynamo(client: AmazonDynamoDBAsyncClient) {
  import AWSAsync._
  // These work but are red because Intellij is broken
  def putItem(putItemRequest: PutItemRequest): Future[PutItemResult] = wrapAsyncMethod(client.putItemAsync, putItemRequest)
  def query(queryRequest: QueryRequest): Future[QueryResult] = wrapAsyncMethod(client.queryAsync, queryRequest)
}

package aws

import com.amazonaws.services.dynamodbv2.AmazonDynamoDBAsyncClient
import com.amazonaws.services.dynamodbv2.model._

import scala.concurrent.Future

object AsyncDynamo {
  def keyEquals(s: String) = new Condition()
    .withComparisonOperator(ComparisonOperator.EQ)
    .withAttributeValueList(new AttributeValue(s))

  def keyGE(s: String) = new Condition()
    .withComparisonOperator(ComparisonOperator.GE)
    .withAttributeValueList(new AttributeValue(s))

  def keyLT(s: String) = new Condition()
    .withComparisonOperator(ComparisonOperator.LT)
    .withAttributeValueList(new AttributeValue(s))

  def keyBetween(a: String, b: String) = new Condition()
    .withComparisonOperator(ComparisonOperator.BETWEEN)
    .withAttributeValueList(new AttributeValue(a), new AttributeValue(b))
}

class AsyncDynamo(client: AmazonDynamoDBAsyncClient) {
  import AWSAsync._
  // These work but are red because Intellij is broken
  def putItem(putItemRequest: PutItemRequest): Future[PutItemResult] = wrapAsyncMethod(client.putItemAsync, putItemRequest)
  def query(queryRequest: QueryRequest): Future[QueryResult] = wrapAsyncMethod(client.queryAsync, queryRequest)
}

Add support for keyBetween condition

Add support for keyBetween condition


package uk.ac.wellcome.platform.transformer.transformers

import org.scalatest.Matchers
import uk.ac.wellcome.models.transformable.Transformable
import uk.ac.wellcome.models.work.internal.TransformedBaseWork

trait TransformableTestBase[T <: Transformable] extends Matchers {

  val transformer: TransformableTransformer[T]

  def transformToWork(transformable: T): TransformedBaseWork = {
    val triedMaybeWork = transformer.transform(transformable, version = 1)
    if (triedMaybeWork.isFailure) triedMaybeWork.failed.get.printStackTrace()
    triedMaybeWork.isSuccess shouldBe true
    triedMaybeWork.get.get
  }

  def assertTransformToWorkFails(transformable: T): Unit = {
    transformer
      .transform(transformable, version = 1)
      .isSuccess shouldBe false
  }
}

package uk.ac.wellcome.platform.transformer.transformers

import org.scalatest.Matchers
import uk.ac.wellcome.models.transformable.Transformable
import uk.ac.wellcome.models.work.internal.TransformedBaseWork

import scala.util.Try

trait TransformableTestBase[T <: Transformable] extends Matchers {

  val transformer: TransformableTransformer[T]

  def transformToWork(transformable: T): TransformedBaseWork = {
    val triedWork: Try[TransformedBaseWork] = transformer.transform(transformable, version = 1)
    if (triedWork.isFailure) triedWork.failed.get.printStackTrace()
    triedWork.isSuccess shouldBe true
    triedWork.get
  }

  def assertTransformToWorkFails(transformable: T): Unit = {
    transformer
      .transform(transformable, version = 1)
      .isSuccess shouldBe false
  }
}

Fix the core of the tests that expects an Option


/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You 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 org.apache.toree.plugins.dependencies

import java.net.URL
import java.lang.{ ClassLoader => JClassLoader }

/**
  * Created by mariu on 2016-07-16.
  */
object ClassLoaderHelper {

  def URLClassLoader(urls: Seq[URL], parent: JClassLoader) = {
    new scala.reflect.internal.util.ScalaClassLoader.URLClassLoader(urls, parent)
  }
}

/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You 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 org.apache.toree.plugins.dependencies

import java.net.URL
import java.lang.{ ClassLoader => JClassLoader }

object ClassLoaderHelper {

  def URLClassLoader(urls: Seq[URL], parent: JClassLoader) = {
    new scala.reflect.internal.util.ScalaClassLoader.URLClassLoader(urls, parent)
  }
}

Remove author info based on ASF best practice


package com.twitter.scalding

import org.scalatest.{ WordSpec, Matchers }

class TypedSketchJoinJobForEmptyKeys(args: Args) extends Job(args) {
  // Deal with when a key appears in left but not right
  val leftTypedPipe = TypedPipe.from(List((1, 1111)))
  val rightTypedPipe = TypedPipe.from(List((3, 3333), (4, 4444)))

  implicit def serialize(k: Int) = k.toString.getBytes
  leftTypedPipe
    .sketch(1)
    .leftJoin(rightTypedPipe)
    .map{
      case (a, (b, c)) =>
        (a, b, c.getOrElse(-1))
    }
    .write(TypedTsv("output"))
}

class TypedSketchJoinJobForEmptyKeysTest extends WordSpec with Matchers {
  import Dsl._
  "A TypedSketchJoinJobForEmptyKeysTest" should {
    "Sketch leftJoin should be the same an Join which is empty" in {
      JobTest(new TypedSketchJoinJobForEmptyKeys(_))
        .sink[(Int, Int, Int)](TypedTsv[(Int, Int, Int)]("output")) { outBuf =>
          val unordered = outBuf.toSet
          unordered should have size 1
          unordered should contain (1, 1111, -1)
        }
        .run
        .finish
    }
  }
}

package com.twitter.scalding

import org.scalatest.{ WordSpec, Matchers }

class TypedSketchJoinJobForEmptyKeys(args: Args) extends Job(args) {
  // Deal with when a key appears in left but not right
  val leftTypedPipe = TypedPipe.from(List((1, 1111)))
  val rightTypedPipe = TypedPipe.from(List((3, 3333), (4, 4444)))

  implicit def serialize(k: Int) = k.toString.getBytes
  leftTypedPipe
    .sketch(1)
    .leftJoin(rightTypedPipe)
    .map {
      case (a, (b, c)) =>
        (a, b, c.getOrElse(-1))
    }
    .write(TypedTsv("output"))
}

class TypedSketchJoinJobForEmptyKeysTest extends WordSpec with Matchers {
  import Dsl._
  "A TypedSketchJoinJobForEmptyKeysTest" should {
    "Sketch leftJoin with a single left key should be correct" in {
      JobTest(new TypedSketchJoinJobForEmptyKeys(_))
        .sink[(Int, Int, Int)](TypedTsv[(Int, Int, Int)]("output")) { outBuf =>
          outBuf should have size 1
          val unordered = outBuf.toSet
          unordered should contain (1, 1111, -1)
        }
        .run
        .finish
    }
  }
}

Fix messag on new test

Fix messag on new test


package io.vertx.asyncsql.test.postgresql

import org.junit.Test
import org.vertx.scala.core.json._
import org.vertx.testtools.VertxAssert._
import io.vertx.asyncsql.test.{ BaseSqlTests, SqlTestVerticle }
import scala.concurrent.Future

class BadlyConfiguredPostgreSqlTest extends SqlTestVerticle {

  override def getConfig() = baseConf.putString("database", "nonexistent")

  @Test
  def testNonExistentDatabase(): Unit = asyncTest {
    expectError(raw("SELECT 0")) map { reply =>
      assertTrue(reply.getString("message").contains("nonexistent"))
    }
  }
}

package io.vertx.asyncsql.test.postgresql

import org.junit.Test
import org.vertx.scala.core.json._
import org.vertx.testtools.VertxAssert._
import io.vertx.asyncsql.test.{ BaseSqlTests, SqlTestVerticle }
import scala.concurrent.Future

class BadlyConfiguredPostgreSqlTest extends SqlTestVerticle {

  override def getConfig() = baseConf.putString("username", "vertx").putString("password", "test").putString("database", "nonexistent")

  @Test
  def testNonExistentDatabase(): Unit = asyncTest {
    expectError(raw("SELECT 0")) map { reply =>
      assertTrue(reply.getString("message").contains("nonexistent"))
    }
  }

}

Fix Jenkins configuration in test

Fix Jenkins configuration in test

Signed-off-by: Joern Bernhardt <7b85a41a628204b76aba4326273a3ccc74bd009a@campudus.com>


import java.awt.Color
import javax.swing.JPanel
import com.github.oetzi.echo.Behaviour

package display {
	class ColorPanel extends JPanel {
		def setBackground(color : Behaviour[Color]) {
			new Thread(new Runnable {
				def run() {
					var last = null
					while (true) {
						val now = color.now
						if (last != now) {
							ColorPanel.super.setBackground(now)
						}
						Thread.sleep(20)
					}
				}
			}).start()
		}
	}

	class Observer[T] extends EventSource[T] {
		//this will replace the code in setBackground
	}
}

import java.awt.Color
import javax.swing.JPanel
import com.github.oetzi.echo.Behaviour
import com.github.oetzi.echo.EventSource

package display {
	class ColorPanel extends JPanel {
		def setBackground(color : Behaviour[Color]) {
			new Observer(color).each(event => super.setBackground(event))
		}
	}

	class Observer[T](val behaviour : Behaviour[T]) extends EventSource[T] {
		new Thread(new Runnable() {
			def run() {
				var last = null
				while (true) {
					val now = behaviour.now
					if (last != now) {
						Observer.this.occur(now)
					}
					Thread.sleep(20)
				}
			}
		}).start()
	}
}

Implement prototype observer in the color example


package com.twitter.scrooge.thrift_validation
import scala.collection.JavaConverters._

object ThriftValidationException {

  /**
   *  A java compatible exception which is used to communicate when a thrift_validation
   *  has failed with the respective [[ThriftValidationViolation]]
   *
   *  @param endpoint   thrift method the invalid request tries to reach
   *  @param requestClazz  the type of request that was passed in
   *  @param validationViolations all violations collected while deserializing the thrift object
   */
  def create(
    endpoint: String,
    requestClazz: Class[_],
    validationViolations: java.util.Set[ThriftValidationViolation]
  ): ThriftValidationException =
    ThriftValidationException(endpoint, requestClazz, validationViolations.asScala.toSet)
}

/**
 *  An exception which is used to communicate when a thrift_validation
 *  has failed with the respective [[ThriftValidationViolation]]
 *  @param endpoint   thrift method the invalid request tries to reach
 *  @param requestClazz  the type of request that was passed in
 *  @param validationViolations all violations collected while deserializing the thrift object
 */

final case class ThriftValidationException(
  endpoint: String,
  requestClazz: Class[_],
  validationViolations: Set[ThriftValidationViolation])
    extends RuntimeException {

  override def getMessage: String =
    s""" The validation for request \"${requestClazz.getName}\" to endpoint \"$endpoint\" failed with messages: [ ${validationViolations
      .mkString(",")}]""""
}

package com.twitter.scrooge.thrift_validation
import scala.collection.JavaConverters._

object ThriftValidationException {

  /**
   *  A java compatible exception which is used to communicate when a thrift_validation
   *  has failed with the respective [[ThriftValidationViolation]]
   *
   *  @param endpoint   thrift method the invalid request tries to reach
   *  @param requestClazz  the type of request that was passed in
   *  @param validationViolations all violations collected while deserializing the thrift object
   */
  def create(
    endpoint: String,
    requestClazz: Class[_],
    validationViolations: java.util.Set[ThriftValidationViolation]
  ): ThriftValidationException =
    ThriftValidationException(endpoint, requestClazz, validationViolations.asScala.toSet)
}

/**
 *  An exception which is used to communicate when a thrift_validation
 *  has failed with the respective [[ThriftValidationViolation]]
 *  @param endpoint   thrift method the invalid request tries to reach
 *  @param requestClazz  the type of request that was passed in
 *  @param validationViolations all violations collected while deserializing the thrift object
 */

final case class ThriftValidationException(
  endpoint: String,
  requestClazz: Class[_],
  validationViolations: Set[ThriftValidationViolation])
    extends RuntimeException {

  override def getMessage: String =
    s""" The validation for request \"${requestClazz.getName}\" to endpoint \"$endpoint\" failed with messages: [ ${validationViolations
      .mkString(", ")}]""""
}

finagle/finagle-thrift: Add Tracing support for ValidationReportingFilter

Problem/Solution

Similar to how we report metrics, upon receiving a ThriftValidationsException,
report failed validations via tracing in the ReportingFilter.

JIRA Issues: CSL-11203

Differential Revision: https://phabricator.twitter.biz/D868233


/*
 * Copyright (C) 2011 reuillon
 *
 * This program 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.openmole.commons.tools.obj

import org.objenesis.ObjenesisStd

object Instanciator {
  private val objenesis = new ObjenesisStd

  def instanciate[T](c: Class[T]): T = objenesis.newInstance(c).asInstanceOf[T]

  def instanciate[T](c: Class[T], args: Object*): T = {
    //val argsTypes = args.map{_.getClass}.toArray
    val ctr = c.getConstructor(args.map{_.getClass}.toArray[Class[_]]: _*)

    val isAccessible = ctr.isAccessible
    ctr.setAccessible(true)
    val instance = ctr.newInstance(args)
    ctr.setAccessible(isAccessible)

    instance
  }
}

/*
 * Copyright (C) 2011 reuillon
 *
 * This program 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.openmole.commons.tools.obj

import org.objenesis.ObjenesisStd

object Instanciator {
  private val objenesis = new ObjenesisStd

  def instanciate[T](c: Class[T]): T = objenesis.newInstance(c).asInstanceOf[T]

  def instanciate[T](c: Class[T], args: Array[Object]): T = instanciate(c, args: _*)

  def instanciate[T](c: Class[T], args: Object*): T = {
    //val argsTypes = args.map{_.getClass}.toArray
    val ctr = c.getConstructor(args.map{_.getClass}.toArray[Class[_]]: _*)

    val isAccessible = ctr.isAccessible
    ctr.setAccessible(true)
    val instance = ctr.newInstance(args)
    ctr.setAccessible(isAccessible)

    instance
  }
}

Add java style var args.

Add java style var args.


package hmda.validation.rules.lar.validity

import hmda.parser.fi.lar.LarGenerators
import hmda.validation.dsl.Success
import org.scalatest.prop.PropertyChecks
import org.scalatest.{ MustMatchers, PropSpec }

class V220Spec extends PropSpec with PropertyChecks with MustMatchers with LarGenerators {
  property("Loan Type must = 1,2,3, or 4") {
    forAll(larGen) { lar =>
      whenever(lar.id == 2) {
        V220(lar.loan) mustBe Success()
      }
    }
  }
}

package hmda.validation.rules.lar.validity

import hmda.model.fi.lar.{ Loan, LoanApplicationRegister }
import hmda.parser.fi.lar.LarGenerators
import hmda.validation.dsl.{ Failure, Success }
import org.scalacheck.Gen
import org.scalatest.prop.PropertyChecks
import org.scalatest.{ MustMatchers, PropSpec }

class V220Spec extends PropSpec with PropertyChecks with MustMatchers with LarGenerators {
  property("Loan Type must = 1,2,3, or 4") {
    forAll(larGen) { lar =>
      whenever(lar.id == 2) {
        V220(lar.loan) mustBe Success()
      }
    }
  }

  val badLoanTypeGen: Gen[Int] = {
    val belowRange = Gen.choose(Integer.MIN_VALUE, 0)
    val aboveRange = Gen.choose(5, Integer.MAX_VALUE)
    Gen.oneOf(belowRange, aboveRange)
  }

  property("Loan Type other than 1,2,3,4 is invalid") {
    forAll(larGen, badLoanTypeGen) { (lar: LoanApplicationRegister, x: Int) =>
      val invalidLoan: Loan = lar.loan.copy(loanType = x)
      V220(invalidLoan) mustBe Failure("is not contained in valid values domain")
    }
  }

}

Test the failure case for V220

Test the failure case for V220

LoanType must be 1,2,3, or 4


package org.fusesource.fabric.monitor.plugins

/**
 * Builds the default monitor set for a typical JVM
 */
class DefaultJvmMonitorSetBuilder extends MonitorSetBuilder("JvmStatistics") {

  def configure {
    archive("5m")
/*
    TODO can we support more than one archive???

    archive("24h", "1m")
    archive("30d", "1h")
    archive("1y", "1d")
*/

    jmxDataSources(
      // heap
      "java.lang:name=Par Survivor Space,type=MemoryPool/Usage/used" -> "jvm.heap.parSurvivor",
      "java.lang:name=CMS Old Gen,type=MemoryPool/Usage/used" -> "jvm.heap.cmsOldGen",
      "java.lang:name=Par Eden Space,type=MemoryPool/Usage/used" -> "jvm.heap.ParEden",

      // non heap
      "java.lang:name=CMS Perm Gen,type=MemoryPool/Usage/used" -> "jvm.nonHeap.cmsPerm",
      "java.lang:name=Code Cache,type=MemoryPool/Usage/used" -> "jvm.nonHeap.code",

      // memory summaries
      "java.lang:type=Memory/HeapMemoryUsage/used" -> "jvm.heap.summary",
      "java.lang:type=Memory/NonHeapMemoryUsage/used" -> "jvm.nonHeap.summary",

      // other stuff
      "java.lang:type=Threading/ThreadCount" -> "jvm.threading.count"
    )
  }

}

package org.fusesource.fabric.monitor.plugins

/**
 * Builds the default monitor set for a typical JVM
 */
class DefaultJvmMonitorSetBuilder extends MonitorSetBuilder("JvmStatistics") {

  def configure {
    archive("5m")
    archive("24h", "1m")
    archive("1y", "1h")

/*
    TODO can we support more than one archive???

    archive("24h", "1m")
    archive("30d", "1h")
    archive("1y", "1d")
*/

    jmxDataSources(
      // heap
      "java.lang:name=Par Survivor Space,type=MemoryPool/Usage/used" -> "jvm.heap.parSurvivor",
      "java.lang:name=CMS Old Gen,type=MemoryPool/Usage/used" -> "jvm.heap.cmsOldGen",
      "java.lang:name=Par Eden Space,type=MemoryPool/Usage/used" -> "jvm.heap.ParEden",

      // non heap
      "java.lang:name=CMS Perm Gen,type=MemoryPool/Usage/used" -> "jvm.nonHeap.cmsPerm",
      "java.lang:name=Code Cache,type=MemoryPool/Usage/used" -> "jvm.nonHeap.code",

      // memory summaries
      "java.lang:type=Memory/HeapMemoryUsage/used" -> "jvm.heap.summary",
      "java.lang:type=Memory/NonHeapMemoryUsage/used" -> "jvm.nonHeap.summary",

      // other stuff
      "java.lang:type=Threading/ThreadCount" -> "jvm.threading.count"
    )
  }

}

Archive up to a year of data.

Archive up to a year of data.


package intelmedia.ws.funnel {

  import scala.concurrent.duration._

  package object instruments extends Instruments(5 minutes, Monitoring.default) with DefaultKeys {
    JVM.instrument(this)
    Clocks.instrument(this)
  }

}

package intelmedia.ws {

  import scalaz.concurrent.Task
  import scalaz.stream.Process

  package object funnel {
    type DatapointParser = java.net.URL => Process[Task,Datapoint[Any]]
  }

}

package intelmedia.ws.funnel {

  import scala.concurrent.duration._

  package object instruments extends Instruments(1 minute, Monitoring.default) with DefaultKeys {
    JVM.instrument(this)
    Clocks.instrument(this)
  }

}

package intelmedia.ws {

  import scalaz.concurrent.Task
  import scalaz.stream.Process

  package object funnel {
    type DatapointParser = java.net.URL => Process[Task,Datapoint[Any]]
  }

}

Set the default window to 60 seconds

Set the default window to 60 seconds


addSbtPlugin("org.xerial.sbt"     % "sbt-sonatype"             % "2.3")
addSbtPlugin("com.jsuereth"       % "sbt-pgp"                  % "1.1.1")
addSbtPlugin("io.get-coursier"    % "sbt-coursier"             % "1.1.0-M7")
addSbtPlugin("org.scoverage"      % "sbt-scoverage"            % "1.5.1")
addSbtPlugin("com.geirsson"       % "sbt-scalafmt"             % "1.5.1")
addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "0.5.0")
addSbtPlugin("org.scala-js"       % "sbt-scalajs"              % "0.6.25")
addSbtPlugin("com.typesafe.sbt"   % "sbt-ghpages"              % "0.6.2")
addSbtPlugin("com.eed3si9n"       % "sbt-unidoc"               % "0.4.2")

addSbtPlugin("com.simplytyped" % "sbt-antlr4" % "0.8.1")

// For setting explicit versions for each commit
addSbtPlugin("com.dwijnand" % "sbt-dynver"     % "3.0.0")
addSbtPlugin("com.47deg"    % "sbt-microsites" % "0.7.24")

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

addSbtPlugin("org.xerial.sbt"     % "sbt-sonatype"             % "2.3")
addSbtPlugin("com.jsuereth"       % "sbt-pgp"                  % "1.1.1")
addSbtPlugin("io.get-coursier"    % "sbt-coursier"             % "1.1.0-M7")
addSbtPlugin("org.scoverage"      % "sbt-scoverage"            % "1.5.1")
addSbtPlugin("com.geirsson"       % "sbt-scalafmt"             % "1.5.1")
addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "0.5.0")
addSbtPlugin("org.scala-js"       % "sbt-scalajs"              % "0.6.25")
addSbtPlugin("com.typesafe.sbt"   % "sbt-ghpages"              % "0.6.2")
addSbtPlugin("com.eed3si9n"       % "sbt-unidoc"               % "0.4.2")

addSbtPlugin("com.simplytyped" % "sbt-antlr4" % "0.8.1")

// For setting explicit versions for each commit
addSbtPlugin("com.dwijnand" % "sbt-dynver"     % "3.0.0")
addSbtPlugin("com.47deg"    % "sbt-microsites" % "0.7.25")

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

Upgrade sbt-microsoft to fix twitter image link


/*
 * Copyright (C) 2010 Romain Reuillon
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.openmole.core.batch.environment

import org.openmole.core.batch.storage._

class SerializedJob(
  val storage: StorageService,
  val path: String,
  val inputFile: String,
  val runtime: Runtime,
  var cleaned: Boolean = false)

/*
 * Copyright (C) 2010 Romain Reuillon
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.openmole.core.batch.environment

import org.openmole.core.batch.storage._

case class SerializedJob(
  storage: StorageService,
  path: String,
  inputFile: String,
  runtime: Runtime,
  cleaned: Boolean = false)

Make serialized job a case class.

Make serialized job a case class.


package lila.analyse

import scala.concurrent.Future

import chess.Color
import play.api.libs.json.Json

import lila.game.{ Game, Namer }

final class TimeChart(game: Game, moves: List[String]) {

  private val pgnMoves = moves.toIndexedSeq

  def series = Json stringify {
    Json.obj(
      "white" -> points(true),
      "black" -> points(false)
    )
  }

  private def points(white: Boolean) = indexedMoveTimes collect {
    case (m, ply) if (white ^ (ply % 2 == 1)) =>
      val mt = if (m < 0.5) 0 else m
      val san = ~(pgnMoves lift ply)
      val turn = 1 + (ply - 1) / 2
      val dots = if (ply % 2 == 1) "..." else "."
      Json.obj(
        "name" -> s"$turn$dots $san",
        "x" -> ply,
        "y" -> (if (white) mt else -mt)
      )
  }

  def maxTime = moveTimes.foldLeft(0f) {
    case (x, y) => if (y > x) y else x
  }

  private val moveTimes = game.moveTimesInSeconds
  private val indexedMoveTimes = game.moveTimesInSeconds.zipWithIndex
}

package lila.analyse

import scala.concurrent.Future

import chess.Color
import play.api.libs.json.Json

import lila.game.{ Game, Namer }

final class TimeChart(game: Game, moves: List[String]) {

  private val pgnMoves = moves.toIndexedSeq

  def series = Json stringify {
    Json.obj(
      "white" -> points(true),
      "black" -> points(false)
    )
  }

  private def points(white: Boolean) = indexedMoveTimes collect {
    case (m, ply) if (white ^ (ply % 2 == 1)) =>
      val mt = if (m < 0.5) 0 else m
      val san = ~(pgnMoves lift ply)
      val turn = ((ply/2).floor + 1).toInt
      val dots = if (ply % 2 == 1) "..." else "."
      Json.obj(
        "name" -> s"$turn$dots $san",
        "x" -> ply,
        "y" -> (if (white) mt else -mt)
      )
  }

  def maxTime = moveTimes.foldLeft(0f) {
    case (x, y) => if (y > x) y else x
  }

  private val moveTimes = game.moveTimesInSeconds
  private val indexedMoveTimes = game.moveTimesInSeconds.zipWithIndex
}

Fix move numbering in timeChart

Fix move numbering in timeChart


import scala.quoted._
import scala.quoted.autolift._

object Test {
  def main(args: Array[String]): Unit = {
    implicit val toolbox: scala.quoted.Toolbox = scala.quoted.Toolbox.make(getClass.getClassLoader)
    def expr(i: Int) given QuoteContext = '{
      val a = 3 + ${i}
      2 + a
    }
    for (i <- 0 to 200)
      run {
        expr(i)
      }
  }
}

import scala.quoted._
import scala.quoted.autolift._

object Test {
  def main(args: Array[String]): Unit = {
    implicit val toolbox: scala.quoted.Toolbox = scala.quoted.Toolbox.make(getClass.getClassLoader)
    def expr(i: Int) given QuoteContext = '{
      val a = 3 + ${i}
      2 + a
    }
    for (i <- 0 to 100)
      run {
        expr(i)
      }
  }
}

Reduce running time of quote test

Reduce running time of quote test

It timed out in http://dotty-ci.epfl.ch/lampepfl/dotty/13982/5.


/**
 * Copyright 2011-2012 eBusiness Information, Groupe Excilys (www.excilys.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.
 */
package com.excilys.ebi.gatling.core.init
import java.util.concurrent.atomic.AtomicBoolean

trait Initializable {

	protected var initialized = new AtomicBoolean(false)
}

/**
 * Copyright 2011-2012 eBusiness Information, Groupe Excilys (www.excilys.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.
 */
package com.excilys.ebi.gatling.core.init
import java.util.concurrent.atomic.AtomicBoolean

trait Initializable {

	protected val initialized = new AtomicBoolean(false)
}

Make initialized a val and not a var

Make initialized a val and not a var


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 TsValidationEngineSpec extends PropSpec with PropertyChecks with MustMatchers with TsGenerators with CommonTsValidationEngine 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 TsValidationEngineSpec extends PropSpec with PropertyChecks with MustMatchers with TsGenerators with CommonTsValidationEngine with ScalaFutures with CommonTsValidationSpec {
//
//  override implicit val ec: ExecutionContext = scala.scalajs.concurrent.JSExecutionContext.Implicits.runNow

//}

Disable TsValidationSpec for JS runtime (Travis CI Failure)


package org.orbeon.oxf.xforms.library

import org.orbeon.macros.XPathFunction
import org.orbeon.oxf.xml.OrbeonFunctionLibrary
import org.orbeon.saxon.function.RandomSupport

trait CryptoFunctions extends OrbeonFunctionLibrary {

  @XPathFunction
  def random(isSeed: Boolean = true): Double =
    RandomSupport.evaluate(isSeed = true)
}

package org.orbeon.oxf.xforms.library

import org.orbeon.macros.XPathFunction
import org.orbeon.oxf.xml.OrbeonFunctionLibrary
import org.scalajs.dom.crypto.GlobalCrypto

import scala.scalajs.js.typedarray.{DataView, Int8Array}

trait CryptoFunctions extends OrbeonFunctionLibrary {
  @XPathFunction
  def random(isSeed: Boolean = true): Double =
    CryptoFunctions.random()
}

object CryptoFunctions {
  def random(): Double = {

    val ints = new Int8Array(8)
    GlobalCrypto.crypto.getRandomValues(ints)

    // https://stackoverflow.com/questions/34575635/cryptographically-secure-float
    ints(7) = 63
    ints(6) = (ints(6) | 0xf0).toByte

    new DataView(ints.buffer).getFloat64(0, littleEndian = true) - 1
  }
}

Use JavaScript `Crypto` API to produce `random()`


import scalariform.formatter.preferences._

name := "icfpc2015"

organization := "eu.shiftforward"

version := "0.1-SNAPSHOT"

scalaVersion := "2.11.7"

libraryDependencies ++= Seq(
  "com.github.nscala-time"     %% "nscala-time"     % "2.0.0",
  "com.typesafe"                % "config"          % "1.3.0",
  "io.spray"                   %% "spray-json"      % "1.3.2",
  "org.specs2"                 %% "specs2-core"     % "3.6.4"  % "test")

scalariformSettings

ScalariformKeys.preferences := ScalariformKeys.preferences.value.
  setPreference(AlignParameters, true)

scalacOptions ++= Seq(
  "-deprecation",
  "-unchecked",
  "-feature",
  "-language:implicitConversions",
  "-language:higherKinds")

Revolver.settings

test in assembly := {}

mainClass in assembly := Some("eu.shiftforward.icfpc2015.Main")

Configure sbt-assembly for running the correct App


sbtPlugin := true

name := "sbt-native-packager"

organization := "com.typesafe.sbt"

version := "0.5.5"

scalacOptions in Compile += "-deprecation"

libraryDependencies += "org.apache.commons" % "commons-compress" % "1.4.1"

site.settings

com.typesafe.sbt.SbtSite.SiteKeys.siteMappings <+= (baseDirectory) map { dir =>
  val nojekyll = dir / "src" / "site" / ".nojekyll"
  nojekyll -> ".nojekyll"
}

site.sphinxSupport()

ghpages.settings

git.remoteRepo := "git@github.com:sbt/sbt-native-packager.git"

publishTo := Some(Resolver.url("sbt-plugin-releases", new URL("http://scalasbt.artifactoryonline.com/scalasbt/sbt-plugin-releases/"))(Resolver.ivyStylePatterns))

publishMavenStyle := false

sbtPlugin := true

name := "sbt-native-packager"

organization := "com.typesafe.sbt"

version := "0.6.0"

scalacOptions in Compile += "-deprecation"

libraryDependencies += "org.apache.commons" % "commons-compress" % "1.4.1"

site.settings

com.typesafe.sbt.SbtSite.SiteKeys.siteMappings <+= (baseDirectory) map { dir =>
  val nojekyll = dir / "src" / "site" / ".nojekyll"
  nojekyll -> ".nojekyll"
}

site.sphinxSupport()

ghpages.settings

git.remoteRepo := "git@github.com:sbt/sbt-native-packager.git"

publishTo := Some(Resolver.url("sbt-plugin-releases", new URL("http://scalasbt.artifactoryonline.com/scalasbt/sbt-plugin-releases/"))(Resolver.ivyStylePatterns))

publishMavenStyle := false

Bump version number to denote major changes.


import com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-build"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.1.0"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.5.9",
      "com.ning" % "async-http-client" % "1.9.40",
      "org.scalatest" %% "scalatest" % "3.0.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 com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-build"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.1.1"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.5.9",
      "com.ning" % "async-http-client" % "1.9.40",
      "org.scalatest" %% "scalatest" % "3.0.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")
  }
}

autocommit: Update configuration to record version 0.1.1


ThisBuild / fork in Test := true

ThisBuild / scalacOptions ++= Seq("-deprecation", "-feature", "-Xfatal-warnings")

ThisBuild / organization := "com.socrata"

ThisBuild / resolvers += "socrata" at "https://repo.socrata.com/artifactory/libs-release"

val commonPG = project in file("common-pg")

val storePG = (project in file("store-pg")).
  dependsOn(commonPG % "compile;test->test")

val soqlServerPG = (project in file("soql-server-pg")).
  dependsOn(commonPG, storePG % "test->test")

disablePlugins(AssemblyPlugin)

releaseProcess -= ReleaseTransformations.publishArtifacts

ThisBuild / fork in Test := true

ThisBuild / scalacOptions ++= Seq("-deprecation", "-feature", "-Xfatal-warnings")

ThisBuild / organization := "com.socrata"

ThisBuild / resolvers += "socrata" at "https://repo.socrata.com/artifactory/libs-release"

val commonPG = project in file("common-pg")

val storePG = (project in file("store-pg")).
  dependsOn(commonPG % "compile;test->test")

// You look at this, and you think "why is there a commonPG and a storePG
// if soqlServerPG is just going to depend on both anyway?"  And you would
// be right to do so!  This has a dependency on store pg because the
// migrations are run by the soql-server container, but the _code_ to do
// so lives in storePG, but the _migrations themselves_ live in soqlServerPG.
// So, ugh... put it on the list of things to fix one day, but for now
// I just want to get staging unbroken again.  When that is fixed, remove
// "compile;" from the dependency spec below so that soqlServerPG only
// depends on storePG's test configuration.
val soqlServerPG = (project in file("soql-server-pg")).
  dependsOn(commonPG, storePG % "compile;test->test")

disablePlugins(AssemblyPlugin)

releaseProcess -= ReleaseTransformations.publishArtifacts

Make soqlServerPG depend on storePG again for now


name := "area-451"

scalaVersion := "2.11.7"

lazy val root = (project in file(".")).enablePlugins(PlayScala)

libraryDependencies ++= Seq(
  filters,
  "com.mohiva" %% "play-html-compressor" % "0.6.3"
)

doc in Compile <<= target.map(_ / "none")

name := "area-451"

scalaVersion := "2.11.7"

lazy val root = (project in file(".")).enablePlugins(PlayScala)

libraryDependencies ++= Seq(
  filters,
  "com.mohiva" %% "play-html-compressor" % "0.6.3"
)

doc in Compile := target.map(_ / "none").value

Fix sbt warning "`<<=` operator is deprecated"


name := "proxy"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

lazy val root = project
  .in(file("."))
  .enablePlugins(PlayScala)
  .enablePlugins(NewRelic)
  .settings(commonSettings: _*)
  .settings(
    libraryDependencies ++= Seq(
      filters,
      ws,
      "com.jason-goodwin" %% "authentikat-jwt" % "0.4.3",
      "org.yaml" % "snakeyaml" % "1.17",
      "org.scalatestplus.play" %% "scalatestplus-play" % "1.5.0" % "test"
    )
  )

val credsToUse = Option(System.getenv("ARTIFACTORY_USERNAME")) match {
  case None => Credentials(Path.userHome / ".ivy2" / ".artifactory")
  case _ => Credentials("Artifactory Realm","flow.artifactoryonline.com",System.getenv("ARTIFACTORY_USERNAME"),System.getenv("ARTIFACTORY_PASSWORD"))
}

lazy val commonSettings: Seq[Setting[_]] = Seq(
  name <<= name("proxy-" + _),
  scalacOptions += "-feature",
  sources in (Compile,doc) := Seq.empty,
  publishArtifact in (Compile, packageDoc) := false,
  credentials += credsToUse,
  resolvers += "scalaz-bintray" at "https://dl.bintray.com/scalaz/releases",
  resolvers += "Artifactory" at "https://flow.artifactoryonline.com/flow/libs-release/"
)

version := "0.0.19"

name := "proxy"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

lazy val root = project
  .in(file("."))
  .enablePlugins(PlayScala)
  .enablePlugins(NewRelic)
  .settings(commonSettings: _*)
  .settings(
    libraryDependencies ++= Seq(
      filters,
      ws,
      "com.jason-goodwin" %% "authentikat-jwt" % "0.4.3",
      "org.yaml" % "snakeyaml" % "1.17",
      "org.scalatestplus.play" %% "scalatestplus-play" % "1.5.0" % "test"
    )
  )

val credsToUse = Option(System.getenv("ARTIFACTORY_USERNAME")) match {
  case None => Credentials(Path.userHome / ".ivy2" / ".artifactory")
  case _ => Credentials("Artifactory Realm","flow.artifactoryonline.com",System.getenv("ARTIFACTORY_USERNAME"),System.getenv("ARTIFACTORY_PASSWORD"))
}

lazy val commonSettings: Seq[Setting[_]] = Seq(
  name <<= name("proxy-" + _),
  scalacOptions += "-feature",
  sources in (Compile,doc) := Seq.empty,
  publishArtifact in (Compile, packageDoc) := false,
  credentials += credsToUse,
  resolvers += "scalaz-bintray" at "https://dl.bintray.com/scalaz/releases",
  resolvers += "Artifactory" at "https://flow.artifactoryonline.com/flow/libs-release/"
)

version := "0.0.20"

autocommit: Update configuration to record version 0.0.20


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.3" % 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"

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.3" % 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.10"

autocommit: Update configuration to record version 0.1.10


name := "lib-reference-scala"

organization := "io.flow"

scalaVersion := "2.13.6"

lazy val allScalacOptions = Seq(
  "-feature",
  "-Xfatal-warnings",
  "-unchecked",
  "-Xcheckinit",
  "-Xlint:adapted-args",
  "-Ypatmat-exhaust-depth", "100", // Fixes: Exhaustivity analysis reached max recursion depth, not all missing cases are reported.
  "-Wconf:src=generated/.*:silent",
  "-Wconf:src=target/.*:silent", // silence the unused imports errors generated by the Play Routes
)

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "org.scalatest" %% "scalatest" % "3.2.10" % Test,
    ),
    credentials += Credentials(
      "Artifactory Realm",
      "flow.jfrog.io",
      System.getenv("ARTIFACTORY_USERNAME"),
      System.getenv("ARTIFACTORY_PASSWORD")
    )
  )

publishTo := {
  val host = "https://flow.jfrog.io/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")
  }
}

scalacOptions ++= allScalacOptions

version := "0.2.94"

name := "lib-reference-scala"

organization := "io.flow"

scalaVersion := "2.13.6"

lazy val allScalacOptions = Seq(
  "-feature",
  "-Xfatal-warnings",
  "-unchecked",
  "-Xcheckinit",
  "-Xlint:adapted-args",
  "-Ypatmat-exhaust-depth", "100", // Fixes: Exhaustivity analysis reached max recursion depth, not all missing cases are reported.
  "-Wconf:src=generated/.*:silent",
  "-Wconf:src=target/.*:silent", // silence the unused imports errors generated by the Play Routes
)

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "org.scalatest" %% "scalatest" % "3.2.10" % Test,
    ),
    credentials += Credentials(
      "Artifactory Realm",
      "flow.jfrog.io",
      System.getenv("ARTIFACTORY_USERNAME"),
      System.getenv("ARTIFACTORY_PASSWORD")
    )
  )

publishTo := {
  val host = "https://flow.jfrog.io/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")
  }
}

scalacOptions ++= allScalacOptions

version := "0.2.95"

autocommit: Update configuration to record version 0.2.95


name := "s2-geometry-library"

version := "1.0"

scalaVersion := "2.11.5"

libraryDependencies ++= Seq(
  "com.google.guava" % "guava" % "r05",
  "org.hamcrest" % "hamcrest-all" % "1.3",
  "junit" % "junit" % "4.10",
  "com.google.code.findbugs" % "jsr305" % "3.0.0"
)

exportJars := true

name := "s2-geometry-library-java-sbt"
organization := "com.colisweb"
version := "1.0"

scalaVersion := "2.11.6"

libraryDependencies ++= Seq(
  "com.google.guava" % "guava" % "r05",
  "org.hamcrest" % "hamcrest-all" % "1.3",
  "junit" % "junit" % "4.10",
  "com.google.code.findbugs" % "jsr305" % "3.0.0"
)

publishArtifact in (Compile, packageDoc) := false

Remove doc generation when publish-local


name := "lib-reference-scala"

organization := "io.flow"

scalaVersion in ThisBuild := "2.12.5"

crossScalaVersions := Seq("2.12.4", "2.11.12", "2.10.6")

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "org.scalatest" %% "scalatest" % "3.0.5" % 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.66"

name := "lib-reference-scala"

organization := "io.flow"

scalaVersion in ThisBuild := "2.12.5"

crossScalaVersions := Seq("2.12.4", "2.11.12", "2.10.6")

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "org.scalatest" %% "scalatest" % "3.0.5" % 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.67"

autocommit: Update configuration to record version 0.1.67


name := "lib-apidoc-json-validation"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.0.20"

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.5.9",
      "org.scalatest" %% "scalatest" % "2.2.6" % 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")
  }
}

name := "lib-apidoc-json-validation"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.0.20"

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.5.9",
      "org.scalatest" %% "scalatest" % "3.0.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")
  }
}

Upgrade org.scalatest.scalatest from 2.2.6 to 3.0.0


package dotty.tastydoc
package comment

trait CommentCleaner {
  import Regexes._
  import java.util.regex.Matcher

  def clean(comment: String): List[String] = {
    def cleanLine(line: String): String = {
      // Remove trailing whitespaces
      TrailingWhitespace.replaceAllIn(line, "") match {
        case CleanCommentLine(ctl) => ctl
        case tl => tl
      }
    }
    val strippedComment = comment.trim.stripPrefix("/*").stripSuffix("*/")
    val safeComment = DangerousTags.replaceAllIn(strippedComment, { htmlReplacement(_) })
    val javadoclessComment = JavadocTags.replaceAllIn(safeComment, { javadocReplacement(_) })
    val markedTagComment =
      SafeTags.replaceAllIn(javadoclessComment, { mtch =>
        Matcher.quoteReplacement(safeTagMarker + mtch.matched + safeTagMarker)
      })
    markedTagComment.linesIterator.toList map (cleanLine)
  }
}

package dotty.tastydoc
package comment

trait CommentCleaner {
  import Regexes._
  import java.util.regex.Matcher

  def clean(comment: String): List[String] = {
    def cleanLine(line: String): String = {
      // Remove trailing whitespaces
      TrailingWhitespace.replaceAllIn(line, "") match {
        case CleanCommentLine(ctl) => ctl
        case tl => tl
      }
    }
    val strippedComment = comment.trim.stripPrefix("/*").stripSuffix("*/")
    val safeComment = DangerousTags.replaceAllIn(strippedComment, { htmlReplacement(_) })
    val javadoclessComment = JavadocTags.replaceAllIn(safeComment, { javadocReplacement(_) })
    val markedTagComment =
      SafeTags.replaceAllIn(javadoclessComment, { mtch =>
        Matcher.quoteReplacement(s"$safeTagMarker${mtch.matched}$safeTagMarker")
      })
    markedTagComment.linesIterator.toList map (cleanLine)
  }
}

Replace deprecated + on Char

Replace deprecated + on Char


import play.PlayImport.PlayKeys._

name := "lib-play"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.7"

crossScalaVersions := Seq("2.11.7")

version := "0.0.41"

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.42"

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")
  }
}

autocommit: Update configuration to record version 0.0.42


enablePlugins(JavaOnlySettings)

name := "ivy-s3-resolver"
organization := "ohnosequences"

bucketSuffix := "era7.com"

javaVersion := "1.7"
javacOptions ++= Seq(
  "-Xlint:deprecation"
)

libraryDependencies ++= Seq(
  "com.amazonaws" % "aws-java-sdk-s3" % "1.11.197",
  "org.apache.ivy" % "ivy" % "2.4.0"
)

bintrayReleaseOnPublish := true
bintrayOrganization := Some(organization.value)
bintrayPackageLabels := Seq("ivy", "s3", "resolver")

publishTo := (publishTo in bintray).value

enablePlugins(JavaOnlySettings)

name := "ivy-s3-resolver"
organization := "ohnosequences"

bucketSuffix := "era7.com"

javaVersion := "1.8"
javacOptions ++= Seq(
  "-Xlint:deprecation"
)

libraryDependencies ++= Seq(
  "com.amazonaws" % "aws-java-sdk-s3" % "1.11.197",
  "org.apache.ivy" % "ivy" % "2.4.0"
)

bintrayReleaseOnPublish := true
bintrayOrganization := Some(organization.value)
bintrayPackageLabels := Seq("ivy", "s3", "resolver")

publishTo := (publishTo in bintray).value

Update Java version to 1.8

Update Java version to 1.8


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.3",
  "io.circe" %% "circe-generic" % "0.11.1",
  "org.http4s" %% "http4s-blaze-client" % "0.20.8",
  "org.http4s" %% "http4s-circe" % "0.20.8",
)

// 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.0"

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.3",
  "io.circe" %% "circe-generic" % "0.11.1",
  "org.http4s" %% "http4s-blaze-client" % "0.20.9",
  "org.http4s" %% "http4s-circe" % "0.20.9",
)

// 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.0"

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


package org.jetbrains.plugins.scala.performance.highlighting.projectHighlighting

import java.util.concurrent.TimeUnit

import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess
import org.jetbrains.plugins.scala.SlowTests
import org.junit.experimental.categories.Category

/**
  * Author: Svyatoslav Ilinskiy
  * Date: 10/23/15.
  */
@Category(Array(classOf[SlowTests]))
class ScalaCommunityHighlightingPerformanceTest extends PerformanceSbtProjectHighlightingTestBase {

  override protected def getExternalSystemConfigFileName: String = "build.sbt"

  override def githubUsername: String = "JetBrains"

  override def githubRepoName: String = "intellij-scala"

  override def revision: String = "493444f6465d0eddea75ac5cd5a848cc30d48ae5"

  def testPerformanceScalaCommunityScalaPsiUtil() = doTest("ScalaPsiUtil.scala", TimeUnit.SECONDS.toMillis(20))

  def testPerformanceScalaCommunityScalaAnnotator() = doTest("ScalaAnnotator.scala", TimeUnit.SECONDS.toMillis(15))

  override def doTest(path: String, timeout: Long): Unit = {
    VfsRootAccess.SHOULD_PERFORM_ACCESS_CHECK = false
    super.doTest(path, timeout)
  }
}

package org.jetbrains.plugins.scala.performance.highlighting.projectHighlighting

import java.util.concurrent.TimeUnit.SECONDS

import com.intellij.openapi.vfs.newvfs.impl.VfsRootAccess
import org.jetbrains.plugins.scala.SlowTests
import org.junit.experimental.categories.Category

/**
  * Author: Svyatoslav Ilinskiy
  * Date: 10/23/15.
  */
@Category(Array(classOf[SlowTests]))
class ScalaCommunityHighlightingPerformanceTest extends PerformanceSbtProjectHighlightingTestBase {

  override protected def getExternalSystemConfigFileName: String = "build.sbt"

  override def githubUsername: String = "JetBrains"

  override def githubRepoName: String = "intellij-scala"

  override def revision: String = "493444f6465d0eddea75ac5cd5a848cc30d48ae5"

  def testPerformanceScalaCommunityScalaPsiUtil() = doTest("ScalaPsiUtil.scala", SECONDS.toMillis(20))

  def testPerformanceScalaCommunityScalaAnnotator() = doTest("ScalaAnnotator.scala", SECONDS.toMillis(15))

  def testPerformanceScalaCommunityScalaEvaluatorBuilderUtil() =
    doTest("ScalaEvaluatorBuilderUtil.scala", SECONDS.toMillis(20))

  def testPerformanceScalaCommunityConformance() = doTest("Conformance.scala", SECONDS.toMillis(20))

  def testPerformanceScalaCommunityScalaSpacingProcessor() = doTest("ScalaSpacingProcessor.scala", SECONDS.toMillis(20))

  override def doTest(path: String, timeout: Long): Unit = {
    VfsRootAccess.SHOULD_PERFORM_ACCESS_CHECK = false
    super.doTest(path, timeout)
  }
}

Add more file to Scala community performance test


package common.actors

import akka.actor.{Actor, ActorLogging, ActorRef}
import akka.stream.scaladsl.{Sink, Source}
import akka.stream.{ActorMaterializer, OverflowStrategy}
import core.graphql.UserContext
import javax.inject.Inject
import akka.pattern._
import common.ActorUtil
import common.actors.Dispatcher.DispatcherInput

import scala.concurrent.{ExecutionContext, Future}

object Dispatcher {

  final val name = "Dispatcher"

  case class DispatcherInput(input: Any,
                             context: UserContext,
                             resolverActor: ActorRef,
                             sender: ActorRef,
                             filtersBefore: List[ActorRef] = Nil,
                             filtersAfter: List[ActorRef] = Nil)

  case class FilterBeforeInput(input: Any,
                               context: UserContext,
                               dispatcherActor: ActorRef,
                               filtersBefore: List[ActorRef])

  case class FilterAfterInput(input: Any,
                              output: Any,
                              context: UserContext,
                              dispatcherActor: ActorRef,
                              filtersAfter: List[ActorRef])

  case class ResolverInput(input: Any,
                           context: UserContext,
                           dispatcherActor: ActorRef)

}

class Dispatcher @Inject()(implicit actorMaterializer: ActorMaterializer,
                           executionContext: ExecutionContext) extends Actor
  with ActorLogging
  with ActorUtil {

  override def receive: Receive = {
    case dispatcherInput: DispatcherInput => {
      sendMessageToActor[Any](dispatcherInput.resolverActor, dispatcherInput.input)
        .pipeTo(dispatcherInput.sender)
    }
  }
}

package common.actors

import akka.actor.{Actor, ActorLogging, ActorRef}
import akka.stream.scaladsl.{Sink, Source}
import akka.stream.{ActorMaterializer, OverflowStrategy}
import core.graphql.UserContext
import javax.inject.Inject
import akka.pattern._
import common.ActorUtil
import common.actors.Dispatcher.DispatcherInput

import scala.concurrent.{ExecutionContext, Future}

object Dispatcher {

  final val name = "Dispatcher"

  case class DispatcherInput(input: Any,
                             context: UserContext,
                             resolverActor: ActorRef,
                             sender: ActorRef,
                             filtersBefore: List[ActorRef] = Nil,
                             filtersAfter: List[ActorRef] = Nil)

  case class FilterBeforeInput(input: Any,
                               context: UserContext,
                               dispatcherActor: ActorRef,
                               filtersBefore: List[ActorRef])

  case class FilterAfterInput(input: Any,
                              output: Any,
                              context: UserContext,
                              dispatcherActor: ActorRef,
                              filtersAfter: List[ActorRef])

  case class ResolverMessage(input: Any, context: UserContext)

  sealed trait InterceptorResultStatus

  final case class Failure(e: Exception) extends InterceptorResultStatus

  final object Success extends InterceptorResultStatus

}

class Dispatcher @Inject()(implicit actorMaterializer: ActorMaterializer,
                           executionContext: ExecutionContext) extends Actor
  with ActorLogging
  with ActorUtil {

  override def receive: Receive = {
    case dispatcherInput: DispatcherInput => {
      sendMessageToActor[Any](dispatcherInput.resolverActor, dispatcherInput.input)
        .pipeTo(dispatcherInput.sender)
    }
  }
}

Use InterceptorResultStatus trait to check a status of an interceptor execution


package dotty.tools
package dotc
package fromtasty

import io.{JarArchive, AbstractFile, Path}
import core.Contexts._

class TASTYRun(comp: Compiler, ictx: Context) extends Run(comp, ictx) {
  override def compile(files: List[AbstractFile]): Unit = {
    val units = tastyUnits(files)
    compileUnits(units)
  }

  private def tastyUnits(files: List[AbstractFile]): List[TASTYCompilationUnit] =
    val fromTastyIgnoreList = ctx.settings.YfromTastyIgnoreList.value.toSet
    // Resolve class names of tasty and jar files
    val classNames = files.flatMap { file =>
      file.extension match
        case "jar" =>
          JarArchive.open(Path(file.path), create = false).allFileNames()
            .filter(e => Path.extension(e) == "tasty" && !fromTastyIgnoreList(e))
            .map(e => e.stripSuffix(".tasty").replace("/", "."))
            .toList
        case "tasty" => TastyFileUtil.getClassName(file)
        case _ =>
          report.error(s"File extension is not `tasty` or `jar`: ${file.path}")
          Nil
    }
    classNames.map(new TASTYCompilationUnit(_))
}

package dotty.tools
package dotc
package fromtasty

import io.{JarArchive, AbstractFile, Path}
import core.Contexts._
import java.io.File

class TASTYRun(comp: Compiler, ictx: Context) extends Run(comp, ictx) {
  override def compile(files: List[AbstractFile]): Unit = {
    val units = tastyUnits(files)
    compileUnits(units)
  }

  private def tastyUnits(files: List[AbstractFile]): List[TASTYCompilationUnit] =
    val fromTastyIgnoreList = ctx.settings.YfromTastyIgnoreList.value.toSet
    // Resolve class names of tasty and jar files
    val classNames = files.flatMap { file =>
      file.extension match
        case "jar" =>
          JarArchive.open(Path(file.path), create = false).allFileNames()
            .map(_.stripPrefix(File.separator)) // change paths from absolute to relative
            .filter(e => Path.extension(e) == "tasty" && !fromTastyIgnoreList(e))
            .map(e => e.stripSuffix(".tasty").replace(File.separator, "."))
            .toList
        case "tasty" => TastyFileUtil.getClassName(file)
        case _ =>
          report.error(s"File extension is not `tasty` or `jar`: ${file.path}")
          Nil
    }
    classNames.map(new TASTYCompilationUnit(_))
}

Fix traversing jar files with tasty inspector


import com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-build"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.0.72"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.5.4",
      "com.ning" % "async-http-client" % "1.9.39",
      "org.scalatest" %% "scalatest" % "2.2.6" % 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.0.73"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.5.4",
      "com.ning" % "async-http-client" % "1.9.39",
      "org.scalatest" %% "scalatest" % "2.2.6" % 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.0.73


import com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-build"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.0.65"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.5.4",
      "com.ning" % "async-http-client" % "1.9.39",
      "org.scalatest" %% "scalatest" % "2.2.6" % 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.0.66"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.5.4",
      "com.ning" % "async-http-client" % "1.9.39",
      "org.scalatest" %% "scalatest" % "2.2.6" % 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.0.66


name := "lib-reference-scala"

organization := "io.flow"

scalaVersion in ThisBuild := "2.12.2"

crossScalaVersions := Seq("2.12.2", "2.11.11", "2.10.6")

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "org.scalatest" %% "scalatest" % "3.0.3" % 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.26"

name := "lib-reference-scala"

organization := "io.flow"

scalaVersion in ThisBuild := "2.12.2"

crossScalaVersions := Seq("2.12.2", "2.11.11", "2.10.6")

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "org.scalatest" %% "scalatest" % "3.0.3" % 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.27"

autocommit: Update configuration to record version 0.1.27


package modules.user.guice.modules

import modules.user.repositories.{UserRepo, UserRepoImpl}
import net.codingwell.scalaguice.ScalaModule

class UserModule extends ScalaModule {
  override def configure() = {
    bind[UserRepo].to[UserRepoImpl]
  }
}

package modules.user.guice.modules

import modules.user.graphql.resolvers.{UserResolver, UserResolverImpl}
import modules.user.repositories.{UserRepo, UserRepoImpl}
import net.codingwell.scalaguice.ScalaModule

class UserModule extends ScalaModule {
  override def configure() = {
    bind[UserResolver].to[UserResolverImpl]
    bind[UserRepo].to[UserRepoImpl]
  }
}

Add bind of 'UserResolver' to an implementation


/* Derived from https://raw.githubusercontent.com/etorreborre/specs2/c0cbfc71390b644db1a5deeedc099f74a237ebde/matcher-extra/src/main/scala-scalaz-7.0.x/org/specs2/matcher/TaskMatchers.scala
 * License: https://raw.githubusercontent.com/etorreborre/specs2/master/LICENSE.txt
 */
package org.http4s.testing

import cats.effect.{IO, Sync}
import scala.concurrent.duration.FiniteDuration

/**
  * Matchers for cats.effect.IO
  */
trait IOMatchers extends RunTimedMatchers[IO] {

  protected implicit def F: Sync[IO] = IO.ioConcurrentEffect
  protected def runWithTimeout[A](fa: IO[A], timeout: FiniteDuration): Option[A] = fa.unsafeRunTimed(timeout)
  protected def runAwait[A](fa: IO[A]) : A = fa.unsafeRunSync

}

object IOMatchers extends IOMatchers

/* Derived from https://raw.githubusercontent.com/etorreborre/specs2/c0cbfc71390b644db1a5deeedc099f74a237ebde/matcher-extra/src/main/scala-scalaz-7.0.x/org/specs2/matcher/TaskMatchers.scala
 * License: https://raw.githubusercontent.com/etorreborre/specs2/master/LICENSE.txt
 */
package org.http4s.testing

import cats.effect.{IO, Sync}
import scala.concurrent.duration.FiniteDuration

/**
  * Matchers for cats.effect.IO
  */
trait IOMatchers extends RunTimedMatchers[IO] {

  protected implicit def F: Sync[IO] = IO.ioEffect
  protected def runWithTimeout[A](fa: IO[A], timeout: FiniteDuration): Option[A] = fa.unsafeRunTimed(timeout)
  protected def runAwait[A](fa: IO[A]) : A = fa.unsafeRunSync

}

object IOMatchers extends IOMatchers

Fix Error: use `ioEffect` instead of the concurrent one.


package jigg.pipeline

/*
 Copyright 2013-2016 Takafumi Sakakibara and Hiroshi Noji

 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 java.util.Properties
import scala.xml.Node

class RegexDocumentAnnotator(override val name: String, override val props: Properties) extends Annotator {

  @Prop(gloss = "Regular expression to segment documents") var pattern = """\n{2,}"""
  readProps()

  private[this] val documentIDGen = jigg.util.IDGenerator("d")
  override def annotate(annotation: Node): Node = {
    val raw = annotation.text

    val documents = raw.split(pattern).map { str =>
      <document id={ documentIDGen.next }>{ str }</document>
    }

    <root>{ documents }</root>
  }

  override def requires = Set()
  override def requirementsSatisfied = Set(Requirement.Dsplit)
}

package jigg.pipeline

/*
 Copyright 2013-2016 Takafumi Sakakibara and Hiroshi Noji

 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 java.util.Properties
import scala.xml.Node

class RegexDocumentAnnotator(override val name: String, override val props: Properties) extends Annotator {

  @Prop(gloss = "Regular expression to segment documents") var pattern = """\n{2,}"""
  readProps()

  private[this] val documentIDGen = jigg.util.IDGenerator("d")
  override def annotate(annotation: Node): Node = {
    val raw = annotation.text

    var offset = 0

    val documents = raw.split(pattern).map { str =>
      val n = <document
        id={ documentIDGen.next }
        characterOffsetBegin={ offset+"" }
        characterOffsetEnd={ offset+str.size+"" }
      >{ str }</document>
      offset += str.size
      n
    }

    <root>{ documents }</root>
  }

  override def requires = Set()
  override def requirementsSatisfied = Set(Requirement.Dsplit)
}

Document annotator also keeps offset values


object Solution {

  def maxXor(l: Int, r: Int): Int = {
    var result = 0
    for {
      i <- l to r
      j <- i + 1 to r
    } {
      val m = i ^ j
      if (m > result) result = m
    }

    result
  }

  def main(args: Array[String]) {
    var _l:Int = Console.readInt
    var _r:Int = Console.readInt

    val res = maxXor(_l, _r)
    println(res)
  }
}

object Solution {

  def maxXor(l: Int, r: Int): Int = {
    var result = 0
    for {
      i <- l to r
      j <- i + 1 to r
    } {
      val m = i ^ j
      if (m > result) result = m
    }

    result
  }

  def maxXorS(l: Int, r: Int): Int = {
    var p = l ^ r
    var result = 1
    while (p >= 1) {
      p >>= 1
      result <<= 1
    }
    result - 1
  }

  def main(args: Array[String]) {
    var _l:Int = Console.readInt
    var _r:Int = Console.readInt

    val res = maxXor(_l, _r)
    println(res)
  }
}

Add a smarter version of maxXor function. The goal is to find the left most significant bit and all the other bits can be 1 when considering x ^ y in [l, r]. This version also deal with `l == r` situation.


import scala.collection.JavaConversions._
import java.util.Properties
import java.io.File
import com.typesafe.config._

object TypesafeConfigPlugin {
  def appendProperties(staticProperties:Properties, specFile:File):Unit = {
    for (entry <- ConfigFactory.parseFile(specFile).entrySet) {
      staticProperties.put(entry.getKey, entry.getValue.unwrapped)
    }
  }
}

import scala.collection.JavaConversions._
import java.util.Properties
import java.io.File
import com.typesafe.config._

object TypesafeConfigPlugin {
  def appendProperties(staticProperties:Properties, specFile:File):Unit = {
    for (entry <- ConfigFactory.parseFile(specFile).resolve.entrySet) {
      staticProperties.put(entry.getKey, entry.getValue.unwrapped)
    }
  }
}

Resolve references in TypeSafe plugin

Resolve references in TypeSafe plugin


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.5")
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.scala-native" % "sbt-scala-native" % "0.4.7")
addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "1.2.0")
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "2.0.5")

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.7")
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.scala-native" % "sbt-scala-native" % "0.4.7")
addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "1.2.0")
addSbtPlugin("org.scoverage" % "sbt-scoverage" % "2.0.5")

Update sbt-http4s-org to 0.14.7 in series/0.23


// Run sbt/sbt eclipse to create Eclipse project file
addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.4.0")

// Run sbt/sbt gen-idea to create IntelliJ project file
addSbtPlugin("com.github.mpeltonen" % "sbt-idea" % "1.5.2")

// Run sbt/sbt eclipse to create Eclipse project file
addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.3.0")

// Run sbt/sbt gen-idea to create IntelliJ project file
addSbtPlugin("com.github.mpeltonen" % "sbt-idea" % "1.5.2")

Use sbteclipse 2.3.0 because 2.4.0+ has a bug that ignores unmanagedClasspath


package uk.ac.wellcome.platform.common

import org.scalatest.{FunSpec, Matchers}

import uk.ac.wellcome.models.Work
import uk.ac.wellcome.utils.JsonUtil

class WorkTest extends FunSpec with Matchers {
  it("should have an LD type 'Work' when serialised to JSON") {
    val work = Work(
      identifiers=List(),
      label="A book about a blue whale"
    )
    val jsonString = JsonUtil.toJson(work).get

    jsonString.contains("""type":"Work"""") should be (true)
  }
}

class JsonUtilTest extends FunSpec with Matchers {
  it("should not include fields where the value is empty or None") {
    val work = Work(
      identifiers=List(),
      label="A haiku about a heron"
    )
    val jsonString = JsonUtil.toJson(work).get

    jsonString.contains(""""accessStatus":null""") should be (false)
    jsonString.contains(""""identifiers":[]""") should be (false)
  }
}

package uk.ac.wellcome.platform.common

import org.scalatest.{FunSpec, Matchers}

import uk.ac.wellcome.models.Work
import uk.ac.wellcome.utils.JsonUtil

class WorkTest extends FunSpec with Matchers {
  it("should have an LD type 'Work' when serialised to JSON") {
    val work = Work(
      identifiers=List(),
      label="A book about a blue whale"
    )
    val jsonString = JsonUtil.toJson(work).get

    jsonString.contains("""type":"Work"""") should be (true)
  }
}

class JsonUtilTest extends FunSpec with Matchers {
  it("should not include fields where the value is empty or None") {
    val work = Work(
      identifiers=List(),
      label="A haiku about a heron"
    )
    val jsonString = JsonUtil.toJson(work).get

    jsonString.contains(""""accessStatus":null""") should be (false)
    jsonString.contains(""""identifiers":[]""") should be (false)
  }

  it("should round-trip an empty list back to an empty list") {
    val jsonString = """{"accessStatus": [], "label": "A doodle of a dog"}"""
    val parsedWork = JsonUtil.fromJson[Work](jsonString).get
    val extrapolatedString = JsonUtil.toJson(parsedWork).get

    jsonString.contains(""""accessStatus": []""") shouldBe true
  }
}

Make sure an empty list stays as an empty list


package controllers

import play.api._
import play.api.mvc._
import com.mongodb.casbah.Imports._
import com.mongodb.util.JSON._

class Whereuat extends Controller {

  def createAccount = Action {
    val mongoClient = MongoClient("localhost", 27017)
    val db = mongoClient("test")
    val coll = db("test")

    val docs = coll.find()
    val list = docs.toList

    Ok(serialize(list))
  }

  def request = Action {
    val mongoClient = MongoClient("localhost", 27017)
    val db = mongoClient("test")
    val coll = db("test")

    val docs = coll.find()
    val list = docs.toList

    Ok(serialize(list))
  }

  def respond = Action {
    val mongoClient = MongoClient("localhost", 27017)
    val db = mongoClient("test")
    val coll = db("test")

    val docs = coll.find()
    val list = docs.toList

    Ok(serialize(list))
  }

}

package controllers

import play.api._
import play.api.mvc._
import com.mongodb.casbah.Imports._
import com.mongodb.util.JSON._

class Whereuat extends Controller {

  def requestAccount = Action {
    val mongoClient = mongoClient("test")
    val coll = db("test")

    val docs = coll.find()
    val list = docs.toList

    Ok(serialize(list))
  }

  def createAccount = Action {
    val mongoClient = MongoClient("localhost", 27017)
    val db = mongoClient("test")
    val coll = db("test")

    val docs = coll.find()
    val list = docs.toList

    Ok(serialize(list))
  }

  def request = Action {
    val mongoClient = MongoClient("localhost", 27017)
    val db = mongoClient("test")
    val coll = db("test")

    val docs = coll.find()
    val list = docs.toList

    Ok(serialize(list))
  }

  def respond = Action {
    val mongoClient = MongoClient("localhost", 27017)
    val db = mongoClient("test")
    val coll = db("test")

    val docs = coll.find()
    val list = docs.toList

    Ok(serialize(list))
  }

}

Add requestAccount action to controller

Add requestAccount action to controller


/*
 * Copyright 2014 http4s.org
 *
 * 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 org.http4s.blazecore.util

import org.http4s.blaze.util.Execution

import scala.concurrent.ExecutionContext

private[util] trait ParasiticExecutionContextCompat {
  final def parasitic: ExecutionContext = Execution.trampoline
}

/*
 * Copyright 2014 http4s.org
 *
 * 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 org.http4s.blazecore.util

import scala.concurrent.ExecutionContext

private[util] trait ParasiticExecutionContextCompat {
  final def parasitic: ExecutionContext = ExecutionContext.parasitic
}

Use parasitic EC in the blaze for Scala 2.13


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.15",
  "org.http4s" %% "http4s-circe" % "0.20.15",
)

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

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.11.2",
  "org.http4s" %% "http4s-blaze-client" % "0.20.15",
  "org.http4s" %% "http4s-circe" % "0.20.15",
)

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

Fix conflicting circe on plugin path

Fix conflicting circe on plugin path


package ecdc.core

import ecdc.core.TraitReader.ServiceTrait
import ecdc.core.VariableResolver._
import model.Cluster
import testutils.Spec

class VariableResolverSpec extends Spec {
  it should "resolve variables for traits" in {
    val vars = resolveVariables(Seq(ServiceTrait("logging"), ServiceTrait("syslog")), Cluster("production"))
    vars should have size 2
    vars should contain(Variable("LOGGING_SERVICE_KEY", "logging_service_key_production", "trait/logging/cluster/production/var"))
  }
}

package ecdc.core

import ecdc.core.TraitReader.ServiceTrait
import ecdc.core.VariableResolver._
import java.io.File
import model.Cluster
import testutils.Spec

class VariableResolverSpec extends Spec {
  it should "resolve variables for traits" in {
    val vars = resolveVariables(new File("./src/core/src/test/resources/testRepo"), Seq(ServiceTrait("logging"), ServiceTrait("syslog")), Cluster("production"))
    vars should have size 3
    vars should contain(Variable("LOGGING_SERVICE_KEY", "logging_service_key_production", "trait/logging/cluster/production/var"))
  }
}

Add basePath and correct test for VariableResolver


// [https://github.com/xerial/sbt-sonatype]
addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "1.1")
addSbtPlugin("com.jsuereth" % "sbt-pgp" % "1.0.0")

Add SBT plugin for publishing signed archives.


package io.vamp

import com.typesafe.scalalogging.LazyLogging

trait TimeUtil extends LazyLogging {
  def time[R](definition: String, block: ⇒ R): R = {
    val t0 = System.nanoTime()
    val result = block // call-by-name
    val t1 = System.nanoTime()
    logger.info(s"Processing of ${definition} took ${(t1 - t0) / 1000} ms")
    result
  }
}

package io.vamp

import com.typesafe.scalalogging.LazyLogging

trait TimeUtil extends LazyLogging {
  def time[R](definition: String, block: ⇒ R): R = {
    val t0 = System.nanoTime()
    val result = block // call-by-name
    val t1 = System.nanoTime()
    logger.info(s"Processing of ${definition} took ${(t1 - t0) / 1000000} ms")
    result
  }
}

Fix for nanoseconds to millisecond conversion


addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.26")

addSbtPlugin("org.scalastyle" %% "scalastyle-sbt-plugin" % "1.0.0")

addSbtPlugin("com.github.gseitz" % "sbt-release" % "1.0.11")

addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.27")

addSbtPlugin("org.scalastyle" %% "scalastyle-sbt-plugin" % "1.0.0")

addSbtPlugin("com.github.gseitz" % "sbt-release" % "1.0.11")

Update sbt-scalajs, scalajs-library, ... to 0.6.27


addSbtPlugin("com.dwijnand" % "sbt-travisci" % "1.2.0")

addSbtPlugin("com.geirsson" % "sbt-ci-release" % "1.5.3")

addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.0.0")

addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.6.1")

addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.0.1")

addSbtPlugin("com.dwijnand" % "sbt-travisci" % "1.2.0")

addSbtPlugin("com.geirsson" % "sbt-ci-release" % "1.5.3")

addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.0.0")

addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.6.1")

addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.1.0")

Update sbt-scalajs, scalajs-compiler to 1.1.0


addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.11.0")
addSbtPlugin("com.lightbend.sbt" % "sbt-java-formatter" % "0.7.0")
addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")
addSbtPlugin("org.http4s" %% "sbt-http4s-org" % "0.14.7")
addSbtPlugin("org.scalastyle" %% "scalastyle-sbt-plugin" % "1.0.0")

addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.11.0")
addSbtPlugin("com.lightbend.sbt" % "sbt-java-formatter" % "0.8.0")
addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1")
addSbtPlugin("org.http4s" %% "sbt-http4s-org" % "0.14.7")
addSbtPlugin("org.scalastyle" %% "scalastyle-sbt-plugin" % "1.0.0")

Update sbt-java-formatter to 0.8.0 in series/0.23


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

addSbtPlugin("org.scala-sbt" % "sbt-android" % "0.7")

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

addSbtPlugin("com.hagerbot" % "sbt-robovm" % "0.1.0-SNAPSHOT")

addSbtPlugin("com.github.mpeltonen" % "sbt-idea" % "1.5.1")

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

addSbtPlugin("org.scala-sbt" % "sbt-android" % "0.7")

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

addSbtPlugin("com.hagerbot" % "sbt-robovm" % "0.1.0-SNAPSHOT")

addSbtPlugin("com.github.mpeltonen" % "sbt-idea" % "1.6.0")

Update sbt-idea plugin to 1.6.0

Update sbt-idea plugin to 1.6.0


import sbt._
import Keys._

object B extends Build
{
	lazy val dep = Project("dep", file("dep"))
	lazy val use = Project("use", file("use")) settings(
		unmanagedJars in Compile <+= packageBin in (dep, Compile) map Attributed.blank,

    // Disable classpath caching since it does not invalidate modified jars
    // (https://github.com/scala/bug/issues/10295)
    scalacOptions += "-YdisableFlatCpCaching"
	)
}

import sbt._
import Keys._

object B extends Build
{
	lazy val dep = Project("dep", file("dep"))
	lazy val use = Project("use", file("use")) settings(
		unmanagedJars in Compile <+= packageBin in (dep, Compile) map Attributed.blank
	)
}

Enable classpath caching in test case

Enable classpath caching in test case


package tabulate.laws.discipline

import org.scalacheck.Arbitrary
import org.scalacheck.Prop._
import org.typelevel.discipline.Laws
import tabulate.RowCodec
import tabulate.laws.RowCodecLaws

trait RowCodecTests[A] extends Laws {
  def laws: RowCodecLaws[A]
  implicit def arbA: Arbitrary[A]

  def rowCodec[B: Arbitrary, C: Arbitrary]: RuleSet = new DefaultRuleSet(
    name = "rowCodec",
    parent = None,
    "encode reversibility " -> forAll(laws.encodeReversibility _),
    "decode identity" -> forAll(laws.decodeIdentity _),
    "encode identity" -> forAll(laws.encodeIdentity _),
    "decode composition" -> forAll(laws.decodeComposition[B, C] _),
    "encode composition" -> forAll(laws.encodeComposition[B, C] _),
    "csv composition" -> forAll(laws.csvReversibility _)
  )
}

object RowCodecTests {
  def apply[A](implicit a: Arbitrary[A], c: RowCodec[A]): RowCodecTests[A] = new RowCodecTests[A] {
    override def laws = RowCodecLaws[A]
    override implicit def arbA = a
  }
}

package tabulate.laws.discipline

import org.scalacheck.Arbitrary
import org.scalacheck.Prop._
import org.typelevel.discipline.Laws
import tabulate.RowCodec
import tabulate.laws.RowCodecLaws

trait RowCodecTests[A] extends Laws {
  def laws: RowCodecLaws[A]
  implicit def arbA: Arbitrary[A]

  def rowCodec[B: Arbitrary, C: Arbitrary]: RuleSet = new DefaultRuleSet(
    name = "rowCodec",
    parent = None,
    "encode reversibility " -> forAll(laws.encodeReversibility _),
    "decode identity" -> forAll(laws.decodeIdentity _),
    "encode identity" -> forAll(laws.encodeIdentity _),
    "decode composition" -> forAll(laws.decodeComposition[B, C] _),
    "encode composition" -> forAll(laws.encodeComposition[B, C] _),
    "csv reversibility" -> forAll(laws.csvReversibility _)
  )
}

object RowCodecTests {
  def apply[A](implicit a: Arbitrary[A], c: RowCodec[A]): RowCodecTests[A] = new RowCodecTests[A] {
    override def laws = RowCodecLaws[A]
    override implicit def arbA = a
  }
}

Fix incorrect test name: csv /composition/reversibility.


package org.http4s.client

import java.io.IOException
import java.net.InetSocketAddress

import org.http4s.blaze.util.TickWheelExecutor

import scala.concurrent.duration._

import scalaz.\/
import scalaz.concurrent.Strategy.DefaultExecutorService

package object blaze {

  type AddressResult = \/[IOException, InetSocketAddress]

  // Centralize some defaults
  private[blaze] val DefaultTimeout: Duration = 60.seconds
  private[blaze] val DefaultBufferSize: Int = 8*1024
  private[blaze] def ClientDefaultEC = DefaultExecutorService
  private[blaze] val ClientTickWheel = new TickWheelExecutor()

  /** Default blaze client */
  val defaultClient = SimpleHttp1Client(DefaultTimeout, DefaultBufferSize, ClientDefaultEC, None)
}

package org.http4s.client

import java.io.IOException
import java.net.InetSocketAddress
import java.util.concurrent.TimeUnit
import java.util.concurrent._

import org.http4s.blaze.util.TickWheelExecutor

import scala.concurrent.duration._

import scalaz.\/

package object blaze {

  type AddressResult = \/[IOException, InetSocketAddress]

  // Centralize some defaults
  private[blaze] val DefaultTimeout: Duration = 60.seconds
  private[blaze] val DefaultBufferSize: Int = 8*1024
  private[blaze] val ClientDefaultEC = {
    val threadFactory = new ThreadFactory {
      val defaultThreadFactory = Executors.defaultThreadFactory()
      def newThread(r: Runnable): Thread = {
        val t = defaultThreadFactory.newThread(r)
        t.setDaemon(true)
        t
      }
    }

    new ThreadPoolExecutor(
      2,
      Runtime.getRuntime.availableProcessors() * 6,
      60L, TimeUnit.SECONDS,
      new LinkedBlockingQueue[Runnable](),
      threadFactory
    )
  }

  private[blaze] val ClientTickWheel = new TickWheelExecutor()

  /** Default blaze client */
  val defaultClient = SimpleHttp1Client(DefaultTimeout, DefaultBufferSize, ClientDefaultEC, None)
}

Change default blaze client Executor to a variable sized ExecutorService.


package com.softwaremill.clippy

import com.softwaremill.clippy.StringDiff.{DeltaEnd, DeltaStart}
import org.scalatest.{FlatSpec, Matchers}

class StringDiffTest extends FlatSpec with Matchers {

  val testData = List(
    ("Super[String, String]", "Super[Option[String], String]", "expected Super[" + DeltaStart + "String" + DeltaEnd + ", String] but was Super[" + DeltaStart + "Option[String]" + DeltaEnd + ", String]"),
    ("Cool[String, String]", "Super[Option[String], String]", "expected " + DeltaStart + "Cool[String" + DeltaEnd + ", String] but was " + DeltaStart + "Super[Option[String]" + DeltaEnd + ", String]"),
    ("(String, String)", "Super[Option[String], String]", "expected " + DeltaStart + "(String, String)" + DeltaEnd + " but was " + DeltaStart + "Super[Option[String], String]" + DeltaEnd)
  )

  "StringDiff" should "diff" in {
    for ((expected, actual, expectedDiff) <- testData) {

      val diff = new StringDiff(expected, actual).diff("expected %s but was %s")

      diff should equal(expectedDiff)
    }
  }

}

package com.softwaremill.clippy

import com.softwaremill.clippy.StringDiff.{DeltaEnd, DeltaStart}
import org.scalatest.{FlatSpec, Matchers}

class StringDiffTest extends FlatSpec with Matchers {

  val testData = List(
    ("Super[String, String]", "Super[Option[String], String]", "expected Super[" + DeltaStart + "String" + DeltaEnd + ", String] but was Super[" + DeltaStart + "Option[String]" + DeltaEnd + ", String]"),
    ("Cool[String, String]", "Super[Option[String], String]", "expected " + DeltaStart + "Cool[String" + DeltaEnd + ", String] but was " + DeltaStart + "Super[Option[String]" + DeltaEnd + ", String]"),
    ("(String, String)", "Super[Option[String], String]", "expected " + DeltaStart + "(String, String)" + DeltaEnd + " but was " + DeltaStart + "Super[Option[String], String]" + DeltaEnd)
  )

  "StringDiff" should "diff" in {
    for ((expected, actual, expectedDiff) <- testData) {

      val diff = new StringDiff(expected, actual).diff("expected %s but was %s")

      diff should be(expectedDiff)
    }
  }

}

Use 'be' instead of 'equal' in test

Use 'be' instead of 'equal' in test


/*
 * Copyright 2013-2020 http4s.org
 *
 * SPDX-License-Identifier: Apache-2.0
 */

package org.http4s.internal

import scala.collection.immutable
import scala.collection.mutable
import scala.collection.mutable.ListBuffer

private[http4s] object CollectionCompat {
  type LazyList[A] = Stream[A]
  val LazyList = Stream

  def pairsToMultiParams[K, V](map: collection.Seq[(K, Option[V])]): Map[K, immutable.Seq[V]] =
    if (map.isEmpty) Map.empty
    else {
      val m = mutable.Map.empty[K, ListBuffer[V]]
      map.foreach {
        case (k, None) => m.getOrElseUpdate(k, new ListBuffer)
        case (k, Some(v)) => m.getOrElseUpdate(k, new ListBuffer) += v
      }
      m.toMap.mapValues(_.toList)
    }

  def mapValues[K, A, B](map: collection.Map[K, A])(f: A => B): Map[K, B] =
    map.mapValues(f).toMap

  val CollectionConverters = scala.collection.JavaConverters
}

Add copyright headers to 2.12 sources

Add copyright headers to 2.12 sources


package controllers

import java.util.UUID

import scala.concurrent.ExecutionContext.Implicits.global
import play.api.mvc._

object Code extends Controller {

  def generate(orgKey: String, serviceKey: String, version: String, generatorKey: String) = AnonymousOrg.async { request =>
    request.api.Code.getByOrgKeyAndServiceKeyAndVersionAndGeneratorKey(orgKey, serviceKey, version, generatorKey).map {
      case None => Redirect(routes.Versions.show(orgKey, serviceKey, version)).flashing("warning" -> "Version not found")
      case Some(r) => Ok(r.source)
    }
  }

}

package controllers

import java.util.UUID

import scala.concurrent.ExecutionContext.Implicits.global
import play.api.mvc._

object Code extends Controller {

  def generate(orgKey: String, serviceKey: String, version: String, generatorKey: String) = AnonymousOrg.async { request =>
    request.api.Code.getByOrgKeyAndServiceKeyAndVersionAndGeneratorKey(orgKey, serviceKey, version, generatorKey).map {
      case None => Redirect(routes.Versions.show(orgKey, serviceKey, version)).flashing("warning" -> "Version not found")
      case Some(r) => Ok(r.source)
    }.recover {
      case r: com.gilt.apidoc.error.ErrorsResponse => {
        Redirect(routes.Versions.show(orgKey, serviceKey, version)).flashing("warning" -> r.errors.map(_.message).mkString(", "))
      }
    }
  }

}

Handle errors / typos in call to code generator


package util

import java.io.File

/**
 * Provides directories used by GitBucket.
 */
object Directory {

  val GitBucketHome = new File(System.getProperty("user.home"), "gitbucket").getAbsolutePath

  /**
   * Repository names of the specified user.
   */
  def getRepositories(owner: String): List[String] = {
    val dir = new File("%s/repositories/%s".format(GitBucketHome, owner))
    if(dir.exists){
      dir.listFiles.filter(_.isDirectory).map(_.getName.replaceFirst("\\.git$", "")).toList
    } else {
      Nil
    }
  }

  /**
   * Substance directory of the repository.
   */
  def getRepositoryDir(owner: String, repository: String): File =
    new File("%s/repositories/%s/%s.git".format(GitBucketHome, owner, repository))

  /**
   * Temporary directory which is used in the repository viewer.
   */
  def getBranchDir(owner: String, repository: String, branch: String): File =
    new File("%s/tmp/%s/branches/%s/%s".format(GitBucketHome, owner, repository, branch))

  /**
   * Temporary directory which is used in the repository creation.
   * GiyBucket generates initial repository contents in this directory and push them.
   * This directory is removed after the repository creation.
   */
  def getInitRepositoryDir(owner: String, repository: String): File =
    new File("%s/tmp/%s/init-%s".format(GitBucketHome, owner, repository))

}

package util

import java.io.File

/**
 * Provides directories used by GitBucket.
 */
object Directory {

  val GitBucketHome = new File(System.getProperty("user.home"), "gitbucket").getAbsolutePath

  val RepositoryHome = "%s/repositories".format(GitBucketHome)

  /**
   * Repository names of the specified user.
   */
  def getRepositories(owner: String): List[String] = {
    val dir = new File("%s/%s".format(RepositoryHome, owner))
    if(dir.exists){
      dir.listFiles.filter(_.isDirectory).map(_.getName.replaceFirst("\\.git$", "")).toList
    } else {
      Nil
    }
  }

  /**
   * Substance directory of the repository.
   */
  def getRepositoryDir(owner: String, repository: String): File =
    new File("%s/%s/%s.git".format(RepositoryHome, owner, repository))

  /**
   * Temporary directory which is used in the repository viewer.
   */
  def getBranchDir(owner: String, repository: String, branch: String): File =
    new File("%s/tmp/%s/branches/%s/%s".format(GitBucketHome, owner, repository, branch))

  /**
   * Temporary directory which is used in the repository creation.
   * GiyBucket generates initial repository contents in this directory and push them.
   * This directory is removed after the repository creation.
   */
  def getInitRepositoryDir(owner: String, repository: String): File =
    new File("%s/tmp/%s/init-%s".format(GitBucketHome, owner, repository))

}

Add RepositoryHome to point GitBucketHome/repositories.