package es.uvigo.ei.sing.funpep
package contrib

import java.nio.file.Path

import scalaz.Scalaz._

import data.Config.syntax._
import util.IOUtils._

object Clustal {

  val devNull = "/dev/null".toPath

  def distanceMatrix(input: Path, alignment: Path, distmat: Path): ConfiguredT[IOThrowable, String] =
    ConfiguredT {
      config ⇒ execute(s"${config.clustalo} -i $input -o $alignment --distmat-out=$distmat --percent-id --full --force")
    }

  def guideTree(input: Path, alignment: Path, tree: Path): ConfiguredT[IOThrowable, String] =
    ConfiguredT {
      config ⇒ execute(s"${config.clustalo} -i $input -o $alignment --guidetree-out=$tree --full --force")
    }

  def withDistanceMatrixOf[A](input: Path)(f: Path ⇒ IOThrowable[A]): ConfiguredT[IOThrowable, A] = {
    val distMat = input + ".distmat"
    def written = distanceMatrix(input, devNull, distMat)
    def mapped  = f(distMat).liftM[ConfiguredT]
    written *> mapped
  }

}

package es.uvigo.ei.sing.funpep
package contrib

import java.nio.file.Path

import scalaz.Scalaz._

import data.Config.syntax._
import util.IOUtils._

object Clustal {

  val devNull = "/dev/null".toPath
  val threads = Math.min(1, Runtime.getRuntime().availableProcessors() - 3)

  def distanceMatrix(input: Path, alignment: Path, distmat: Path): ConfiguredT[IOThrowable, String] =
    ConfiguredT {
      config ⇒ execute(s"${config.clustalo} -i $input -o $alignment --distmat-out=$distmat --percent-id --full --threads=$threads --force")
    }

  def guideTree(input: Path, alignment: Path, tree: Path): ConfiguredT[IOThrowable, String] =
    ConfiguredT {
      config ⇒ execute(s"${config.clustalo} -i $input -o $alignment --guidetree-out=$tree --full --threads=$threads --force")
    }

  def withDistanceMatrixOf[A](input: Path)(f: Path ⇒ IOThrowable[A]): ConfiguredT[IOThrowable, A] = {
    val distMat = input + ".distmat"
    def written = distanceMatrix(input, devNull, distMat)
    def mapped  = f(distMat).liftM[ConfiguredT]
    written *> mapped
  }

}

Add threaded execution to Clustal

Add threaded execution to Clustal


import BuildUtil._
import sbt.Keys._
import sbt._

object Common extends AutoPlugin {

  override def trigger: PluginTrigger = allRequirements

  override def requires: Plugins = plugins.JvmPlugin

  override lazy val projectSettings: Seq[Setting[_]] = Seq(
    scalaVersion := "2.12.2",
    crossScalaVersions := Seq("2.12.2", "2.11.11"),
    scalacOptions ++= Seq(
      "-deprecation",
      "-unchecked",
      "-feature",
      "-Xlint",
      "-language:higherKinds",
      "-language:implicitConversions",
      "-language:experimental.macros"
    ),
    scalacOptions ++= byScalaVersion {
      case (2, 12) => Seq(
        "-opt:l:method"
      )
      case (2, 11) => Seq(
        // lambda syntax for SAM types
        "-Xexperimental"
      )
    }.value,
    updateOptions := updateOptions.value.withCachedResolution(true),
    incOptions := incOptions.value.withLogRecompileOnMacro(false)
  )

}

import BuildUtil._
import sbt.Keys._
import sbt._

object Common extends AutoPlugin {

  override def trigger: PluginTrigger = allRequirements

  override def requires: Plugins = plugins.JvmPlugin

  override lazy val projectSettings: Seq[Setting[_]] = Seq(
    scalaVersion := "2.12.2",
    crossScalaVersions := Seq("2.12.2", "2.11.11"),
    scalacOptions ++= Seq(
      "-deprecation",
      "-unchecked",
      "-feature",
      "-Xlint",
      "-language:higherKinds",
      "-language:implicitConversions",
      "-language:experimental.macros"
    ),
    scalacOptions ++= byScalaVersion {
      case (2, 12) => Seq(
        "-opt:l:method"
      )
      case (2, 11) => Seq(
        // lambda syntax for SAM types
        "-Xexperimental"
      )
    }.value,
    updateOptions := updateOptions.value.withCachedResolution(true),
    incOptions := incOptions.value.withLogRecompileOnMacro(false)
  ) ++
    Seq(Compile, Test).map { c =>
      scalacOptions in (c, console) := {
        val opts = (scalacOptions in (c, console)).value
        CrossVersion.partialVersion(scalaVersion.value) match {
          case Some((2, 12)) =>
            opts.map {
              case "-Xlint" => "-Xlint:-unused,_"
              case otherwise => otherwise
            }
          case _ => opts
        }
      }
    }

}

Disable unused warnings in console

Disable unused warnings in console


import sbt._
import Keys._

object Common {
  val settings: Seq[Def.Setting[_]] = Seq(
    scalaVersion := "2.11.8",
    organization := "uk.ac.wellcome",
    resolvers += Resolver.sonatypeRepo("releases"),
    scalacOptions ++= Seq(
      "-deprecation",
      "-unchecked",
      "-encoding",
      "UTF-8",
      "-Xlint",
      "-Xverify",
      "-Xfatal-warnings",
      "-feature",
      "-language:postfixOps"
    ),
    parallelExecution in Test := false,
    libraryDependencies ++= Dependencies.sharedDependencies
  ) ++
    Search.settings ++
    Swagger.settings ++
    Finatra.settings
}

object Swagger {
  val settings: Seq[Def.Setting[_]] = Seq(
    resolvers +=
      "Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/releases/"
  )
}

object Search {
  val settings: Seq[Def.Setting[_]] = Seq(
    resolvers += "elasticsearch-releases" at "https://artifacts.elastic.co/maven"
  )
}

object Finatra {
  val settings: Seq[Def.Setting[_]] = Seq(
    resolvers += "maven.twttr.com" at "https://maven.twttr.com",
    fork in run := true
  )
}

import sbt._
import Keys._

object Common {
  val settings: Seq[Def.Setting[_]] = Seq(
    scalaVersion := "2.12.6",
    organization := "uk.ac.wellcome",
    resolvers += Resolver.sonatypeRepo("releases"),
    scalacOptions ++= Seq(
      "-deprecation",
      "-unchecked",
      "-encoding",
      "UTF-8",
      "-Xlint",
      "-Xverify",
      // It breaks for scala_2.12 because it returns warnings fo unused imports, unused variables and use of deprecated classes
      // TODO turn this back on once the migration is done
//      "-Xfatal-warnings",
      "-feature",
      "-language:postfixOps"
    ),
    parallelExecution in Test := false,
    libraryDependencies ++= Dependencies.sharedDependencies
  ) ++
    Search.settings ++
    Swagger.settings ++
    Finatra.settings
}

object Swagger {
  val settings: Seq[Def.Setting[_]] = Seq(
    resolvers +=
      "Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/releases/"
  )
}

object Search {
  val settings: Seq[Def.Setting[_]] = Seq(
    resolvers += "elasticsearch-releases" at "https://artifacts.elastic.co/maven"
  )
}

object Finatra {
  val settings: Seq[Def.Setting[_]] = Seq(
    resolvers += "maven.twttr.com" at "https://maven.twttr.com",
    fork in run := true
  )
}

Use newest version of scala

Use newest version of scala


/*
 * 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 wvlet.airframe.spec

import wvlet.airframe.spec.spi.AirSpec
import wvlet.airframe.{Design, _}
import wvlet.log.LogSupport

/**
  *
  */
class TestSpec extends AirSpec with LogSupport {
  info("test spec")

  override protected def design: Design =
    newDesign
      .bind[String].toInstance("my message")

  def hello(m: String): Unit = {
    info(m)
    assert(m == "my message")
  }
}

object TestObjSpec extends AirSpec with LogSupport {
  def objectMethod: String = {
    info("hello companion methods")
    "hello obj"
  }
}

/*
 * 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 wvlet.airframe.spec

import wvlet.airframe.spec.spi.AirSpec
import wvlet.airframe.{Design, _}
import wvlet.log.LogSupport

/**
  *
  */
class TestSpec extends AirSpec with LogSupport {
  info("test spec")

  override protected def design: Design =
    newDesign
      .bind[String].toInstance("my message")

  def hello(m: String): Unit = {
    info(m)
    assert(m == "my message")
  }

  def `support free-style test description`: Unit = {
    info("hello")
  }

}

object TestObjSpec extends AirSpec with LogSupport {
  def objectMethod: String = {
    info("hello companion methods")
    "hello obj"
  }
}

Add free-style test description example

Add free-style test description example


package com.ephox.argonaut

import org.scalacheck.Prop._
import scalaz.Success
import org.scalacheck._
import org.scalacheck.Shrink._
import scalaz._
import Scalaz._

object AltParserTest extends Properties("AltParser") {
  /*
  def validResultsSpec = KnownResults.validResultPairings |> {(json, expectedJSONValue) =>
    val actualParseResult = AltParser.parse(json)
    actualParseResult must_== expectedJSONValue.successNel[JSONError]
  }
  def invalidResultsSpec = KnownResults.parseFailures |> {(json, parseResult) =>
    val actualParseResult = Parser.parse(json)
    actualParseResult === parseResult
  }
  */
  property("Parsed, printed and then parsed again generates the same structure") =
    forAll(JsonGenerators.arrayOrObjectGenerator.map(_.toString).label("arrayOrObject")){json =>
      val firstParsed = AltParser.parse(json)
      ("firstParsed = " + firstParsed) |: {
        val printedJSON = firstParsed.map(jsonValue => jsonValue.nospaces)
        ("printedJSON = " + printedJSON) |: {
          val secondParsed = printedJSON.flatMap(secondJSON => AltParser.parse(secondJSON))
          ("secondParsed = " + secondParsed) |: (firstParsed === secondParsed && secondParsed.isSuccess)
        }
      }
    }
}

package com.ephox.argonaut

import org.scalacheck.Prop._
import scalaz.Success
import org.scalacheck._
import org.scalacheck.Shrink._
import scalaz._
import Scalaz._

object AltParserTest extends Properties("AltParser") {
  /*
  def validResultsSpec = KnownResults.validResultPairings |> {(json, expectedJSONValue) =>
    val actualParseResult = AltParser.parse(json)
    actualParseResult must_== expectedJSONValue.successNel[JSONError]
  }
  def invalidResultsSpec = KnownResults.parseFailures |> {(json, parseResult) =>
    val actualParseResult = Parser.parse(json)
    actualParseResult === parseResult
  }
  */
  property("Parsed, printed and then parsed again generates the same structure") =
    forAll(JsonGenerators.arrayOrObjectGenerator.map(_.toString).label("arrayOrObject")){json =>
      ("aboutToParse = " + json) |: {
        val firstParsed = AltParser.parse(json)
        ("firstParsed = " + firstParsed) |: {
          val printedJSON = firstParsed.map(jsonValue => jsonValue.nospaces)
          ("printedJSON = " + printedJSON) |: {
            val secondParsed = printedJSON.flatMap(secondJSON => AltParser.parse(secondJSON))
            ("secondParsed = " + secondParsed) |: (firstParsed === secondParsed && secondParsed.isSuccess)
          }
        }
      }
    }
}

Add additional label output to alt parser test due to intermittent travis failure


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

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

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


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

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

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

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

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


package dal

import com.softwaremill.clippy._
import com.softwaremill.id.DefaultIdGenerator
import util.BaseSqlSpec

class AdvicesRepositoryTest extends BaseSqlSpec {
  it should "store & read an advice" in {
    // given
    val ar = new AdvicesRepository(database, new DefaultIdGenerator())

    // when
    val stored = ar.store("zzz", "yyy", TypeMismatchError[RegexT](RegexT("x"), None, RegexT("y"), None, None), "z",
      AdviceState.Pending, Library("g", "a", "1"), Contributor(None, None, Some("t")), Some("c")).futureValue

    // then
    val r = ar.findAll().futureValue
    r should have size (1)

    val found = r.head

    stored should be (found)
    found.errorTextRaw should be ("zzz")
    found.patternRaw should be ("yyy")
    found.compilationError should be (TypeMismatchError(RegexT("x"), None, RegexT("y"), None, None))
    found.advice should be ("z")
    found.state should be (AdviceState.Pending)
    found.library should be (Library("g", "a", "1"))
    found.contributor should be (Contributor(None, None, Some("t")))
    found.comment should be (Some("c"))
  }
}

package dal

import com.softwaremill.clippy._
import com.softwaremill.id.DefaultIdGenerator
import util.BaseSqlSpec
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.concurrent.IntegrationPatience

class AdvicesRepositoryTest extends BaseSqlSpec with ScalaFutures with IntegrationPatience {
  it should "store & read an advice" in {
    // given
    val ar = new AdvicesRepository(database, new DefaultIdGenerator())

    // when
    val stored = ar.store("zzz", "yyy", TypeMismatchError[RegexT](RegexT("x"), None, RegexT("y"), None, None), "z",
      AdviceState.Pending, Library("g", "a", "1"), Contributor(None, None, Some("t")), Some("c")).futureValue

    // then
    val r = ar.findAll().futureValue
    r should have size (1)

    val found = r.head

    stored should be (found)
    found.errorTextRaw should be ("zzz")
    found.patternRaw should be ("yyy")
    found.compilationError should be (TypeMismatchError(RegexT("x"), None, RegexT("y"), None, None))
    found.advice should be ("z")
    found.state should be (AdviceState.Pending)
    found.library should be (Library("g", "a", "1"))
    found.contributor should be (Contributor(None, None, Some("t")))
    found.comment should be (Some("c"))
  }
}

Add better patience to a flakey test

Add better patience to a flakey test


package uk.ac.wellcome.models

import com.amazonaws.services.dynamodbv2.model.AttributeValue
import com.gu.scanamo.DynamoFormat
import com.gu.scanamo.error.DynamoReadError

trait Sourced extends Id {
  val sourceId: String
  val sourceName: String
  val id: String = Sourced.id(sourceName, sourceId)
}

object Sourced {
  def id(sourceName: String, sourceId: String) = s"$sourceName/$sourceId"
}

package uk.ac.wellcome.models

trait Sourced extends Id {
  val sourceId: String
  val sourceName: String
  val id: String = Sourced.id(sourceName, sourceId)
}

object Sourced {
  def id(sourceName: String, sourceId: String) = s"$sourceName/$sourceId"
}

Remove an unused AWS import

Remove an unused AWS import


package net.detunized.iteratorz

class PackingIteratorSpec extends IteratorSpec[(String, Int)] {
  private[this] type S = String

  "pack single elements" in {
    check(mk("A"), ("A", 1))
    check(mk("A", "B"), ("A", 1), ("B", 1))
    check(mk("A", "B", "C"), ("A", 1), ("B", 1), ("C", 1))
  }

  "pack repeating elements" in {
    check(mk("A", "A"), ("A", 2))
    check(mk("A", "A", "A"), ("A", 3))
  }

  "pack mixed single and repeated elements" in {
    check(mk("A", "A", "B"), ("A", 2), ("B", 1))
    check(mk("A", "B", "B"), ("A", 1), ("B", 2))
    check(mk("A", "B", "B", "C", "C", "C"), ("A", 1), ("B", 2), ("C", 3))
    check(mk("A", "A", "A", "B", "B", "C"), ("A", 3), ("B", 2), ("C", 1))
    check(mk("A", "A", "B", "C", "C", "C"), ("A", 2), ("B", 1), ("C", 3))
  }

  protected def mkEmpty = mk()
  private[this] def mk(s: S*) = new PackingIterator(s.iterator)
}

package net.detunized.iteratorz

class PackingIteratorSpec extends IteratorSpec[(String, Int)] {
  private[this] type S = String

  "pack single elements" in {
    check(mk("A"), "A" -> 1)
    check(mk("A", "B"), "A" -> 1, "B" -> 1)
    check(mk("A", "B", "C"), "A" -> 1, "B" -> 1, "C" -> 1)
  }

  "pack repeating elements" in {
    check(mk("A", "A"), "A" -> 2)
    check(mk("A", "A", "A"), "A" -> 3)
  }

  "pack mixed single and repeated elements" in {
    check(mk("A", "A", "B"), "A" -> 2, "B" -> 1)
    check(mk("A", "B", "B"), "A" -> 1, "B" -> 2)
    check(mk("A", "B", "B", "C", "C", "C"), "A" -> 1, "B" -> 2, "C" -> 3)
    check(mk("A", "A", "A", "B", "B", "C"), "A" -> 3, "B" -> 2, "C" -> 1)
    check(mk("A", "A", "B", "C", "C", "C"), "A" -> 2, "B" -> 1, "C" -> 3)
  }

  protected def mkEmpty = mk()
  private[this] def mk(s: S*) = new PackingIterator(s.iterator)
}

Change pair notation from (_, _) to _ -> _


package io.flow.oneapi

case class Module(name: String, serviceNames: Set[String]) {
  assert(
    name.toLowerCase() == name,
    "Module name must be in lower case"
  )
  assert(
    serviceNames.forall { n => n.toLowerCase() == n },
    "All service names must be in lower case"
  )
}

object Module {

  val General: Module = Module("general", Set("common", "feed", "healthcheck", "link", "organization", "search", "session", "token", "user"))
  val Webhook: Module = Module("webhook", Set("webhook"))

  val All = Seq(
    Module("localization", Set("catalog", "experience")),
    Module("pricing", Set("currency")),
    Module("landed cost", Set("harmonization")),
    Module("payment", Set("payment")),
    Module("logistics", Set("fulfillment", "inventory", "label", "ratecard", "return", "tracking")),
    Webhook,
    Module("customer service", Set.empty),
    Module("geolocation", Set("location")),
    Module("reference", Set("reference")),
    Module("partner", Set("partner")),
    General
  )

  def findByServiceName(name: String): Option[Module] = {
    All.find(_.serviceNames.map(_.toLowerCase).contains(name.toLowerCase))
  }

  def findByModuleName(name: String): Option[Module] = {
    All.find(_.name.toLowerCase == name.toLowerCase)
  }

  def moduleSortIndex(name: String): Int = {
    findByModuleName(name) match {
      case Some(module) => All.indexOf(module)
      case None => Int.MaxValue
    }
  }
}

package io.flow.oneapi

case class Module(name: String, serviceNames: Set[String]) {
  assert(
    name.toLowerCase() == name,
    "Module name must be in lower case"
  )
  assert(
    serviceNames.forall { n => n.toLowerCase() == n },
    "All service names must be in lower case"
  )
}

object Module {

  val General: Module = Module("general", Set("common", "feed", "healthcheck", "link", "organization", "search", "session", "token", "user"))
  val Webhook: Module = Module("webhook", Set("webhook"))

  val All = Seq(
    Module("localization", Set("catalog", "experience")),
    Module("pricing", Set("currency")),
    Module("landed cost", Set("harmonization")),
    Module("payment", Set("payment")),
    Module("logistics", Set("fulfillment", "inventory", "label", "ratecard", "return", "tracking")),
    Webhook,
    Module("customer service", Set.empty),
    Module("geolocation", Set("location")),
    Module("reference", Set("reference")),
    Module("partner", Set("partner")),
    Module("calculator", Set("calculator")),
    General
  )

  def findByServiceName(name: String): Option[Module] = {
    All.find(_.serviceNames.map(_.toLowerCase).contains(name.toLowerCase))
  }

  def findByModuleName(name: String): Option[Module] = {
    All.find(_.name.toLowerCase == name.toLowerCase)
  }

  def moduleSortIndex(name: String): Int = {
    findByModuleName(name) match {
      case Some(module) => All.indexOf(module)
      case None => Int.MaxValue
    }
  }
}

Add calculator as a module

Add calculator as a module


package actors

import akka.actor.Actor
import play.api.libs.ws.WSClient
import javax.inject.Inject
import scala.concurrent.Future
import play.api.libs.ws.WSResponse
import scala.concurrent.ExecutionContext.Implicits._
import models.VappFactory

case class Delete(vm_id : String, count : Int = 10)

class DeleteActor (ws: WSClient, func: () => Future[WSResponse], cookie : () => String) extends Actor{

  def receive = {
    case Delete(vm_id, count) => {
      func().map(response => {
        val vapp = VappFactory(response.xml)
        if(count < 0 ){
          println("Delete Time out : VM not shutdown")
        }
        else if(vapp.vms.filter(_.id==vm_id).head.active){
          self ! Delete(vm_id,count-1)
        }
        else{
           ws.url("https://vcloud-director-http-2.ccr.eisti.fr/api/vApp/vm-" + vm_id).withHeaders(
          "Cookie" -> cookie(),
          "Accept" -> "application/*+xml;version=1.5"
        ).delete
        println("Deleting VM")
        }
    })
    }
  }

}

package actors

import akka.actor.Actor
import play.api.libs.ws.WSClient
import javax.inject.Inject
import scala.concurrent.Future
import play.api.libs.ws.WSResponse
import scala.concurrent.ExecutionContext.Implicits._
import models.VappFactory
import scala.concurrent.duration._

case class Delete(vm_id : String, count : Int = 10)

class DeleteActor (ws: WSClient, func: () => Future[WSResponse], cookie : () => String) extends Actor{

  def receive = {
    case Delete(vm_id, count) => {
      func().map(response => {
        val vapp = VappFactory(response.xml)
        if(count < 0 ){
          println("Delete Time out : VM not shutdown")
        }
        else if(vapp.vms.filter(_.id==vm_id).head.active){
          println("Vm not powerOff yet, trying again")
          context.system.scheduler.scheduleOnce(2 seconds, self ,Delete(vm_id,count-1))
        }
        else{
           ws.url("https://vcloud-director-http-2.ccr.eisti.fr/api/vApp/vm-" + vm_id).withHeaders(
          "Cookie" -> cookie(),
          "Accept" -> "application/*+xml;version=1.5"
        ).delete
        println("Deleting VM")
        }
    })
    }
  }

}

Delete VM : add schedule waiting the VM is power off before delete


package de.bripkens.ha

import akka.actor.{Actor, ActorLogging, Props}
import com.fasterxml.jackson.databind.ObjectMapper
import de.bripkens.ha.reporting.{ConsoleReporter, SlackReporter}

object AppActor {

  final val Name = "app"

  def props(mapper: ObjectMapper, config: Configuration) = Props(new AppActor(mapper, config))
}

class AppActor(val mapper: ObjectMapper, val config: Configuration) extends Actor
                                                                    with ActorLogging {

  val reporters = config.reporters.map{ case (name, reporterConfig) =>
    val props = reporterConfig match {
      case config@ConsoleReporterConfig(_)           => ConsoleReporter.props(mapper, config)
      case config@SlackReporterConfig(_, _, _, _, _) => SlackReporter.props(mapper, config)
    }

    val actor = context.actorOf(props, s"reporter-$name")
    (name, actor)
  }

  config.endpoints.foreach { endpoint =>
    if (!reporters.contains(endpoint.reporter)) {
      log.error(s"Reporter ${endpoint.reporter} does not exist.")
      System.exit(1)
    }
    val reporter = reporters(endpoint.reporter)
    context.actorOf(
      HealthCheckActor.props(mapper, config, endpoint, reporter),
      s"healthCheck-${endpoint.id}"
    )
  }

  override def receive: Receive = {
    case unsupported => log.error(s"Unsupported message received: $unsupported")
  }
}

package de.bripkens.ha

import akka.actor.{Actor, ActorLogging, Props}
import com.fasterxml.jackson.databind.ObjectMapper
import de.bripkens.ha.reporting.{ConsoleReporter, SlackReporter}

object AppActor {

  final val Name = "app"

  def props(mapper: ObjectMapper, config: Configuration) = Props(new AppActor(mapper, config))
}

class AppActor(val mapper: ObjectMapper, val config: Configuration) extends Actor
                                                                    with ActorLogging {

  val reporters = config.reporters.map{ case (name, reporterConfig) =>
    val props = reporterConfig match {
      case config: ConsoleReporterConfig => ConsoleReporter.props(mapper, config)
      case config: SlackReporterConfig   => SlackReporter.props(mapper, config)
    }

    val actor = context.actorOf(props, s"reporter-$name")
    (name, actor)
  }

  config.endpoints.foreach { endpoint =>
    if (!reporters.contains(endpoint.reporter)) {
      log.error(s"Reporter ${endpoint.reporter} does not exist.")
      System.exit(1)
    }
    val reporter = reporters(endpoint.reporter)
    context.actorOf(
      HealthCheckActor.props(mapper, config, endpoint, reporter),
      s"healthCheck-${endpoint.id}"
    )
  }

  override def receive: Receive = {
    case unsupported => log.error(s"Unsupported message received: $unsupported")
  }
}

Use typed pattern, since we're not really destructuring here


package org.http4s.circe

import cats.Applicative
import io.circe.Encoder
import org.http4s.EntityEncoder

/**
  * Derive [[EntityEncoder]] if implicit [[Encoder]] is in the scope without need to explicitly call `jsonEncoderOf`
  */
trait CirceEntityEncoder {
  implicit def circeEntityEncoder[F[_]: Applicative, A: Encoder]: EntityEncoder[F, A] =
    jsonEncoderOf[F, A]
}

object CirceEntityEncoder extends CirceEntityEncoder

package org.http4s.circe

import io.circe.Encoder
import org.http4s.EntityEncoder

/**
  * Derive [[EntityEncoder]] if implicit [[Encoder]] is in the scope without need to explicitly call `jsonEncoderOf`
  */
trait CirceEntityEncoder {
  implicit def circeEntityEncoder[F[_], A: Encoder]: EntityEncoder[F, A] =
    jsonEncoderOf[F, A]
}

object CirceEntityEncoder extends CirceEntityEncoder

Remove Applicative constraint from ciriceEntityEncoder


package calcpi

object pi extends App {
    var n = 500000000

    if (args.length == 1) {
        n = Integer.parseInt(args(0))
    }

    println("Calculating PI using:")
    println("  " + n + " slices")
    println("  1 processes")

    val start = System.currentTimeMillis();

    var psum = 0.0d;
    val step = 1d/n;

    for (i <-  1 to n) {
        var x = (i - 0.5d) * step
        psum = psum + 4d/(1d + (x * x))
    }

    var mypi = psum * step;

    val stop = System.currentTimeMillis();
    val difference = stop - start;
    val time = difference/1000.0d;

    println("Obtained value of PI: " + mypi);
    println("Time taken: " + time + " seconds");
}

package calcpi

object pi {

    def estimate_pi(n: Int): Double = {
        var psum = 0.0d;
        val step = 1d/n;

        for (i <-  1 to n) {
            var x = (i - 0.5d) * step
            psum = psum + 4d/(1d + (x * x))
        }

        psum * step

    }

    def main(args: Array[String]) {
        var n = 500000000

        if (args.length == 1) {
            n = Integer.parseInt(args(0))
        }

        println("Calculating PI using:")
        println("  " + n + " slices")
        println("  1 processes")

        val start = System.currentTimeMillis();

        var mypi = estimate_pi(n)

        val stop = System.currentTimeMillis();
        val difference = stop - start;
        val time = difference/1000.0d;

        println("Obtained value of PI: " + mypi);
        println("Time taken: " + time + " seconds");
  }
}

Rework to make more sense.

Rework to make more sense.


package cpup.mc.lib.util

import net.minecraft.util.{IIcon, ResourceLocation}
import cpw.mods.fml.relauncher.{Side, SideOnly}
import org.lwjgl.opengl.GL11
import net.minecraft.client.Minecraft
import net.minecraft.client.renderer.Tessellator

@SideOnly(Side.CLIENT)
object GUIUtil {
	val itemsIcon = new ResourceLocation("textures/atlas/items.png")
	def mc = Minecraft.getMinecraft
	def tess = Tessellator.instance

	def drawItemIconAt(icon: IIcon, x: Int, y: Int, z: Double, width: Int, height: Int) {
		GL11.glMatrixMode(5890)
		GL11.glPushMatrix
		mc.renderEngine.bindTexture(itemsIcon)
		tess.startDrawingQuads
		tess.addVertexWithUV(x,         y,          z, icon.getMinU, icon.getMinV)
		tess.addVertexWithUV(x,         y + height, z, icon.getMinU, icon.getMaxV)
		tess.addVertexWithUV(x + width, y + height, z, icon.getMaxU, icon.getMaxV)
		tess.addVertexWithUV(x + width, y,          z, icon.getMaxU, icon.getMinV)
		tess.draw
		GL11.glPopMatrix
		GL11.glMatrixMode(5888)
	}
}

package cpup.mc.lib.util

import net.minecraft.util.{IIcon, ResourceLocation}
import cpw.mods.fml.relauncher.{Side, SideOnly}
import org.lwjgl.opengl.GL11
import net.minecraft.client.Minecraft
import net.minecraft.client.renderer.Tessellator

@SideOnly(Side.CLIENT)
object GUIUtil {
	val itemsIcon = new ResourceLocation("textures/atlas/items.png")
	def mc = Minecraft.getMinecraft
	def tess = Tessellator.instance

	def drawItemIconAt(icon: IIcon, x: Double, y: Double, z: Double, width: Double, height: Double) {
		GL11.glMatrixMode(5890)
		GL11.glPushMatrix
		mc.renderEngine.bindTexture(itemsIcon)
		tess.startDrawingQuads
		tess.addVertexWithUV(x,         y,          z, icon.getMinU, icon.getMinV)
		tess.addVertexWithUV(x,         y + height, z, icon.getMinU, icon.getMaxV)
		tess.addVertexWithUV(x + width, y + height, z, icon.getMaxU, icon.getMaxV)
		tess.addVertexWithUV(x + width, y,          z, icon.getMaxU, icon.getMinV)
		tess.draw
		GL11.glPopMatrix
		GL11.glMatrixMode(5888)
	}
}

Use doubles instead of ints

Use doubles instead of ints


import sbt._
import Keys._
import org.portablescala.sbtplatformdeps.PlatformDepsPlugin.autoImport._

object Dependencies {
  lazy val jaxbApi = "javax.xml.bind" % "jaxb-api" % "2.3.1" % "test"

  lazy val jodaTime = Seq(
    "joda-time" % "joda-time" % "2.10.13",
    "org.joda" % "joda-convert" % "2.2.2"
  )
  lazy val jackson = Seq(
    "com.fasterxml.jackson.core" % "jackson-databind" % "2.13.2"
  )
  lazy val scalaz_core = Def.setting(
    "org.scalaz" %%% "scalaz-core" % "7.3.6"
  )
  lazy val paranamer = "com.thoughtworks.paranamer" % "paranamer" % "2.8"
  lazy val scalatest = Def.setting(
    Seq("org.scalatest" %%% "scalatest-wordspec" % "3.2.11" % "test")
  )
  lazy val scalatestScalacheck = Def.setting(
    Seq("org.scalatestplus" %%% "scalacheck-1-15" % "3.2.11.0" % "test")
  )

  lazy val scalaXml = Def.setting {
    "org.scala-lang.modules" %%% "scala-xml" % "2.0.1"
  }
}

import sbt._
import Keys._
import org.portablescala.sbtplatformdeps.PlatformDepsPlugin.autoImport._

object Dependencies {
  lazy val jaxbApi = "javax.xml.bind" % "jaxb-api" % "2.3.1" % "test"

  lazy val jodaTime = Seq(
    "joda-time" % "joda-time" % "2.10.14",
    "org.joda" % "joda-convert" % "2.2.2"
  )
  lazy val jackson = Seq(
    "com.fasterxml.jackson.core" % "jackson-databind" % "2.13.2"
  )
  lazy val scalaz_core = Def.setting(
    "org.scalaz" %%% "scalaz-core" % "7.3.6"
  )
  lazy val paranamer = "com.thoughtworks.paranamer" % "paranamer" % "2.8"
  lazy val scalatest = Def.setting(
    Seq("org.scalatest" %%% "scalatest-wordspec" % "3.2.11" % "test")
  )
  lazy val scalatestScalacheck = Def.setting(
    Seq("org.scalatestplus" %%% "scalacheck-1-15" % "3.2.11.0" % "test")
  )

  lazy val scalaXml = Def.setting {
    "org.scala-lang.modules" %%% "scala-xml" % "2.0.1"
  }
}

Update joda-time to 2.10.14 in master

Update joda-time to 2.10.14 in master


object Chop {
    def main(args: Array[String]) {
        println("Chop!")
    }
}

object Chop {
  def main(args: Array[String]) {
    println("Chop!")
  }

  def chop[A <: Ordered[A]](item : A, seq : Seq[A]) : Int = {
    if(seq.nonEmpty) {
      val midIndex = seq.length / 2
      if(seq.apply(midIndex) > item) {
        chop(item, seq.slice(0, midIndex / 2))
      } else if(seq.apply(midIndex) < item) {
        chop(item, seq.slice(midIndex + 1, seq.length))
      } else {
        midIndex
      }
    } else {
      -1
    }
  }
}

Add first attempt at Scala chop

Kata02: Add first attempt at Scala chop


import sbt._
import com.twitter.sbt._

class KilldeerProject(info: ProjectInfo) extends StandardProject(info) {
  val codehaus = "codehaus" at "http://repository.codehaus.org/"

  val specs = "org.scala-tools.testing" % "specs_2.8.0" % "1.6.5"
  val jetty = "org.eclipse.jetty" % "jetty-http" % "7.1.5.v20100705"
  val jettyServer = "org.eclipse.jetty" % "jetty-server" % "7.1.5.v20100705"
  val jettyServlet = "org.eclipse.jetty" % "jetty-servlet" % "7.1.5.v20100705"
  val jettyCont = "org.eclipse.jetty" % "jetty-continuation" % "7.1.5.v20100705"

  override def mainClass = Some("com.twitter.killdeer.Killdeer")
}

import sbt._
import com.twitter.sbt._

class KilldeerProject(info: ProjectInfo) extends StandardProject(info) {
  val codehaus = "codehaus" at "http://repository.codehaus.org/"

  val specs = "org.scala-tools.testing" % "specs_2.8.0" % "1.6.5"
  val jetty = "org.eclipse.jetty" % "jetty-http" % "7.1.5.v20100705"
  val jettyServer = "org.eclipse.jetty" % "jetty-server" % "7.1.5.v20100705"
  val jettyServlet = "org.eclipse.jetty" % "jetty-servlet" % "7.1.5.v20100705"
  val jettyCont = "org.eclipse.jetty" % "jetty-continuation" % "7.1.5.v20100705"

  // Renaming it to 1.2.0a so it doesn't read the broken POM file from the internet.
  val colt = "colt" % "colt" % "1.2.0a"

  override def mainClass = Some("com.twitter.killdeer.Killdeer")
}

Add colt dependency for distributions.

Add colt dependency for distributions.


import org.jsoup.Jsoup
import org.jsoup.safety.Whitelist
import language.implicitConversions

package ems {

import org.jsoup.nodes.Document
import org.jsoup.nodes.Entities.EscapeMode

package object model {
    implicit class HtmlCleaner(val string: String) extends AnyVal{
      def noHtml = {
        val settings = new Document.OutputSettings()
        settings.indentAmount(0)
        settings.escapeMode(EscapeMode.xhtml)
        settings.prettyPrint(false)
        Jsoup.clean(string, "", Whitelist.none(), settings)
      }
    }
  }
}

import org.jsoup.Jsoup
import org.jsoup.safety.Whitelist
import language.implicitConversions

package ems {

import org.jsoup.nodes.Document
import org.jsoup.nodes.Entities.EscapeMode
import java.nio.charset.Charset

package object model {
    implicit class HtmlCleaner(val string: String) extends AnyVal{
      def noHtml = {
        val settings = new Document.OutputSettings()
        settings.indentAmount(0)
        settings.escapeMode(EscapeMode.xhtml)
        settings.prettyPrint(false)
        settings.charset(Charset.forName("UTF-8"))
        Jsoup.clean(string, "", Whitelist.none(), settings).
          replace(""", "\"").
          replace("'", "'").
          replace("&", "&")

      }
    }
  }
}

Fix quotes, apos and ampersands

Fix quotes, apos and ampersands


/*
 * 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 dbis.pig.op

import dbis.pig.plan._
import dbis.pig.schema._

import scala.collection.mutable.ArrayBuffer

case class SplitBranch(val outPipeName: String, val expr: Expr)

/**
 * SplitInto represents the SPLIT INTO operator of Pig.
 *
 * @param initialInPipeName the names of the input pipe.
 * @param splits a list of split branches (output pipe + condition)
 */
case class SplitInto(val initialInPipeName: String, val splits: List[SplitBranch])
  extends PigOperator("", initialInPipeName) {

  override def initialOutPipeNames: List[String] = splits.map{ case branch => branch.outPipeName }

  override def lineageString: String = {
    s"""SPLIT%""" + super.lineageString
  }
}

/*
 * 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 dbis.pig.op

case class SplitBranch(val outPipeName: String, val expr: Predicate)

/**
 * SplitInto represents the SPLIT INTO operator of Pig.
 *
 * @param initialInPipeName the names of the input pipe.
 * @param splits a list of split branches (output pipe + condition)
 */
case class SplitInto(val initialInPipeName: String, val splits: List[SplitBranch])
  extends PigOperator("", initialInPipeName) {

  override def initialOutPipeNames: List[String] = splits.map{ case branch => branch.outPipeName }

  override def lineageString: String = {
    s"""SPLIT%""" + super.lineageString
  }
}

Make SplitBranch's expr a Predicate

Make SplitBranch's expr a Predicate

We're going to turn SplitBranches into Filters, so we might as well
force the expression to be a Predicate.


package io.flow.oneapi

sealed trait TextDatatype

object TextDatatype {

  case object List extends TextDatatype
  case object Map extends TextDatatype
  case class Singleton(name: String) extends TextDatatype

  val ListRx = "^\\[(.*)\\]$".r
  val MapRx = "^map\\[(.*)\\]$".r
  val MapDefaultRx = "^map$".r
}

/**
  * Parses a text datatype, removing specific namespaces as those
  * names are expected to be local
  */
case class TextDatatypeParser() {
  import TextDatatype._

  def parse(value: String): Seq[TextDatatype] = {
    value match {
      case ListRx(t) => Seq(TextDatatype.List) ++ parse(t)
      case MapRx(t) => Seq(TextDatatype.Map) ++ parse(t)
      case MapDefaultRx() => Seq(TextDatatype.Map, TextDatatype.Singleton("string"))
      case _ => Seq(TextDatatype.Singleton(value.split("\\.").last))
    }
  }

  def toString(parts: Seq[TextDatatype]): String = {
    parts.toList match {
      case Nil => ""
      case Singleton(name) :: Nil => name

      case one :: rest => {
        one match {
          case List => "[" + toString(rest) + "]"
          case Map => "map[" + toString(rest) + "]"
          case Singleton(_) => sys.error("Did not expect singleton here")
        }

      }
    }
  }

}

package io.flow.oneapi

import scala.util.matching.Regex

sealed trait TextDatatype

object TextDatatype {

  case object List extends TextDatatype
  case object Map extends TextDatatype
  case class Singleton(name: String) extends TextDatatype

  val ListRx: Regex = "^\\[(.*)\\]$".r
  val MapRx: Regex = "^map\\[(.*)\\]$".r
  val MapDefaultRx: Regex = "^map$".r
}

/**
  * Parses a text datatype, removing specific namespaces as those
  * names are expected to be local
  */
case class TextDatatypeParser() {
  import TextDatatype._

  def parse(value: String): Seq[TextDatatype] = {
    value match {
      case ListRx(t) => Seq(TextDatatype.List) ++ parse(t)
      case MapRx(t) => Seq(TextDatatype.Map) ++ parse(t)
      case MapDefaultRx() => Seq(TextDatatype.Map, TextDatatype.Singleton("string"))
      case _ => Seq(TextDatatype.Singleton(
        maybeStripNamespace(value)
      ))
    }
  }

  def toString(parts: Seq[TextDatatype]): String = {
    parts.toList match {
      case Nil => ""
      case Singleton(name) :: Nil => name

      case one :: rest => {
        one match {
          case List => "[" + toString(rest) + "]"
          case Map => "map[" + toString(rest) + "]"
          case Singleton(_) => sys.error("Did not expect singleton here")
        }

      }
    }
  }

  def maybeStripNamespace(value: String): String = {
    val parts = value.split("\\.")
    if (parts.contains("external") || parts.contains("misc")) {
      value
    } else {
      parts.last
    }
  }

}

Add hack to preserve external/misc namespaces


package templates

import org.fusesource.scalate.support.TemplatePackage
import org.fusesource.scalate.{Binding, TemplateSource}

/**
 * Defines some common imports, attributes and methods across templates in package foo and below
 */
class ScalatePackage extends TemplatePackage {

  /** Returns the Scala code to add to the top of the generated template method */
   def header(source: TemplateSource, bindings: List[Binding]) = """
import model._
  """
}

package templates

import org.fusesource.scalate.support.TemplatePackage
import org.fusesource.scalate.{Binding, TemplateSource}

/**
 * Defines some common imports, attributes and methods across templates in package foo and below
 */
class ScalatePackage extends TemplatePackage {

  /** Returns the Scala code to add to the top of the generated template method */
   def header(source: TemplateSource, bindings: List[Binding]) = """
// import model._
  """
}

Comment out model import by default

Comment out model import by default


package intellij.haskell.runconfig.console

import com.intellij.openapi.actionSystem.{ActionPromoter, AnAction, DataContext}
import com.intellij.openapi.editor.actions.EnterAction
import com.intellij.util.containers.ContainerUtil

import java.util
import java.util.Comparator

class HaskellConsoleActionPromoter extends ActionPromoter {
  private val Comparator = new Comparator[AnAction]() {
    def compare(o1: AnAction, o2: AnAction): Int = {
      (notEnter(o1), notEnter(o2)) match {
        case (false, true) => 1
        case (true, false) => -1
        case _ => 0
      }
    }

    private def notEnter(o: AnAction) = !o.isInstanceOf[EnterAction]
  }

  def promote(actions: util.List[_ <: AnAction], context: DataContext): util.List[AnAction] = {
    val result = new util.ArrayList[AnAction](actions)
    ContainerUtil.sort(result, Comparator)
    result
  }

}

package intellij.haskell.runconfig.console

import com.intellij.openapi.actionSystem.{ActionPromoter, AnAction, DataContext}
import com.intellij.openapi.editor.actions.EnterAction
import com.intellij.util.containers.ContainerUtil

import java.util
import java.util.Comparator

class HaskellConsoleActionPromoter extends ActionPromoter {
  private val Comparator = new Comparator[AnAction]() {
    def compare(o1: AnAction, o2: AnAction): Int = {
      (notEnter(o1), notEnter(o2)) match {
        case (false, true) => 1
        case (true, false) => -1
        case _ => 0
      }
    }

    private def notEnter(o: AnAction) = !o.isInstanceOf[EnterAction]
  }

  override def promote(actions: util.List[_ <: AnAction], context: DataContext): util.List[AnAction] = {
    val result = new util.ArrayList[AnAction](actions)
    ContainerUtil.sort(result, Comparator)
    result
  }

}

Fix compilation against new IntelliJ 12.5284.40


package hmda.api

import akka.actor.ActorSystem
import akka.event.Logging
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import com.typesafe.config.ConfigFactory
import hmda.api.http.HttpApi

object HmdaApi extends App with HttpApi {

  override implicit val system = ActorSystem("hmda")
  override implicit val materializer = ActorMaterializer()
  implicit val ec = system.dispatcher

  override val log = Logging(system, getClass)
  val config = ConfigFactory.load()

  lazy val host = config.getString("hmda.http.host")
  lazy val port = config.getInt("hmda.http.port")

  val http = Http().bindAndHandle(
    routes,
    host,
    port
  )

  http onFailure {
    case ex: Exception =>
      log.error(ex, "Failed to bind to {}:{}", host, port)
  }

}

package hmda.api

import akka.actor.ActorSystem
import akka.event.Logging
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import com.typesafe.config.ConfigFactory
import hmda.api.http.{ HttpApi, LarHttpApi }

object HmdaApi extends App with HttpApi with LarHttpApi {

  override implicit val system = ActorSystem("hmda")
  override implicit val materializer = ActorMaterializer()
  implicit val ec = system.dispatcher

  override val log = Logging(system, getClass)
  val config = ConfigFactory.load()

  lazy val host = config.getString("hmda.http.host")
  lazy val port = config.getInt("hmda.http.port")

  val http = Http().bindAndHandle(
    routes ~ larRoutes,
    host,
    port
  )

  http onFailure {
    case ex: Exception =>
      log.error(ex, "Failed to bind to {}:{}", host, port)
  }

}

Add LAR API to application

Add LAR API to application


import sbt._
import sbt.Keys._
import android.Keys._
import android.Plugin._

object Build extends android.AutoBuild
{
	lazy val main = Project( "toolbelt", file( "." ) )
		.settings( buildAar: _* )
		.settings(
			libraryDependencies ++= Seq(
				"org.scala-lang" % "scala-reflect" % scalaVersion.value,
				"com.android.support" % "support-v4" % "20.0.0",
				"com.github.japgolly.android" % "svg-android" % "2.0.6"
			),
			name := "Toolbelt",
			organization := "com.taig.android",
			scalaVersion := "2.11.2",
			scalacOptions ++= Seq(
				"-deprecation",
				"-feature",
				"-language:dynamics",
				"-language:implicitConversions",
				"-language:reflectiveCalls"
			),
			version := "0.0.8-BETA",
			libraryProject in Android := true,
			minSdkVersion in Android := "10",
			targetSdkVersion in Android := "19"
		)
}

import sbt._
import sbt.Keys._
import android.Keys._
import android.Plugin._

object Build extends android.AutoBuild
{
	lazy val main = Project( "toolbelt", file( "." ) )
		.settings( buildAar: _* )
		.settings(
			libraryDependencies ++= Seq(
				"org.scala-lang" % "scala-reflect" % scalaVersion.value,
				"com.android.support" % "support-v4" % "20.0.0",
				"com.github.japgolly.android" % "svg-android" % "2.0.6"
			),
			name := "Toolbelt",
			organization := "com.taig.android",
			scalaVersion := "2.11.2",
			scalacOptions ++= Seq(
				"-deprecation",
				"-feature",
				"-language:dynamics",
				"-language:implicitConversions",
				"-language:reflectiveCalls"
			),
			version := "0.0.9-BETA",
			libraryProject in Android := true,
			minSdkVersion in Android := "10",
			targetSdkVersion in Android := "19"
		)
}

Set project version to 0.0.9-BETA

Set project version to 0.0.9-BETA


addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "1.1.1")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.11.0")
addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.9.14")
addSbtPlugin("com.github.sbt" % "sbt-pgp" % "2.2.0")
addSbtPlugin("com.github.sbt" % "sbt-release" % "1.1.0")
addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "1.2.0")
addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.2.0")
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.11.0")
addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.4.7")
addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.6")

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

addSbtPlugin("com.typesafe" % "sbt-mima-plugin" % "1.1.1")
addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.11.0")
addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.9.14")
addSbtPlugin("com.github.sbt" % "sbt-pgp" % "2.2.0")
addSbtPlugin("com.github.sbt" % "sbt-release" % "1.1.0")
addSbtPlugin("org.portable-scala" % "sbt-scala-native-crossproject" % "1.2.0")
addSbtPlugin("org.portable-scala" % "sbt-scalajs-crossproject" % "1.2.0")
addSbtPlugin("org.scala-js" % "sbt-scalajs" % "1.11.0")
addSbtPlugin("org.scala-native" % "sbt-scala-native" % "0.4.7")
addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.5.0")

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

Update sbt-scalafmt to 2.5.0 in master

Update sbt-scalafmt to 2.5.0 in master


libraryDependencies += "org.scala-lang" % "scala-compiler" % scalaVersion.value

addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "2.5")

addSbtPlugin("com.jsuereth" % "sbt-pgp" % "1.1.1")

libraryDependencies += "org.scala-lang" % "scala-compiler" % scalaVersion.value

addSbtPlugin("org.xerial.sbt" % "sbt-sonatype" % "3.8.1")

addSbtPlugin("com.jsuereth" % "sbt-pgp" % "2.0.1")

Update to latest sbt-pgp sbt-sonatype

Update to latest sbt-pgp sbt-sonatype


package org.jetbrains.plugins.scala.base

import com.intellij.openapi.module.Module
import org.jetbrains.plugins.scala.TestFixtureProvider
import org.jetbrains.plugins.scala.base.libraryLoaders.LibraryLoader
import org.jetbrains.plugins.scala.debugger.{ScalaVersion, Scala_2_10}

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

trait ScalaSdkOwner {

  implicit val version: ScalaVersion

  protected def librariesLoaders: Seq[LibraryLoader]

  protected lazy val myLoaders: ListBuffer[LibraryLoader] = mutable.ListBuffer.empty[LibraryLoader]

  protected def setUpLibraries(implicit module: Module): Unit = {

    librariesLoaders.foreach { loader =>
      myLoaders += loader
      loader.init
    }
  }

  protected def disposeLibraries(implicit module: Module): Unit = {
    myLoaders.foreach(_.clean)
    myLoaders.clear()
  }

}

// Java compatibility
trait DefaultScalaSdkOwner extends ScalaSdkOwner with TestFixtureProvider {
  override implicit val version: ScalaVersion = Scala_2_10
}

package org.jetbrains.plugins.scala.base

import com.intellij.openapi.module.Module
import org.jetbrains.plugins.scala.TestFixtureProvider
import org.jetbrains.plugins.scala.base.libraryLoaders.LibraryLoader
import org.jetbrains.plugins.scala.debugger.{ScalaVersion, Scala_2_13}

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

trait ScalaSdkOwner {

  implicit val version: ScalaVersion

  protected def librariesLoaders: Seq[LibraryLoader]

  protected lazy val myLoaders: ListBuffer[LibraryLoader] = mutable.ListBuffer.empty[LibraryLoader]

  protected def setUpLibraries(implicit module: Module): Unit = {

    librariesLoaders.foreach { loader =>
      myLoaders += loader
      loader.init
    }
  }

  protected def disposeLibraries(implicit module: Module): Unit = {
    myLoaders.foreach(_.clean)
    myLoaders.clear()
  }

}

// Java compatibility
trait DefaultScalaSdkOwner extends ScalaSdkOwner with TestFixtureProvider {
  override implicit val version: ScalaVersion = Scala_2_13
}

Use scala varsion 2.13 as default in tests

 #SCL-15634 fixed


/*
 * Copyright (C) 2011 <mathieu.leclaire at openmole.org>
 *
 * 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 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.ide.core.implementation.action

import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import org.openmole.ide.core.model.commons.TransitionType._
import org.openmole.ide.core.implementation.workflow.ConnectorWidget

class AggregationTransitionAction(connectionWidget: ConnectorWidget) extends ActionListener{
  override def actionPerformed(ae: ActionEvent)= {
    if (connectionWidget.transition.transitionType == BASIC_TRANSITION) connectionWidget.transition.transitionType = AGGREGATION_TRANSITION
    else connectionWidget.transition.transitionType = BASIC_TRANSITION
    connectionWidget.drawTransitionType
  }
}

/*
 * Copyright (C) 2011 <mathieu.leclaire at openmole.org>
 *
 * 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 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.ide.core.implementation.action

import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import org.openmole.ide.core.model.commons.TransitionType._
import org.openmole.ide.core.implementation.data.CheckData
import org.openmole.ide.core.implementation.workflow.ConnectorWidget

class AggregationTransitionAction(connectionWidget: ConnectorWidget) extends ActionListener{
  override def actionPerformed(ae: ActionEvent)= {
    if (connectionWidget.transition.transitionType == BASIC_TRANSITION) connectionWidget.transition.transitionType = AGGREGATION_TRANSITION
    else connectionWidget.transition.transitionType = BASIC_TRANSITION
    connectionWidget.drawTransitionType
    CheckData.checkMole(connectionWidget.scene.manager)
  }
}

Check workflow when a Aggregation is set


package ch.usi.inf.l3.sana.ooj.ast.augmenters

import ch.usi.inf.l3.sana
import sana.tiny.types.Type
import sana.tiny.symbols.Symbol
import sana.tiny.ast.IdentApi

trait AugmentedIdent {

  def tree: IdentApi

  def isMethodIdent: Boolean =
    tree.attributes.get('isMethod).map(_.asInstanceOf[Boolean]).getOrElse(false)

  def isMethodIdent_=(flag: Boolean): Unit =
    tree.attributes = tree.attributes + ('isMethod -> flag)

  def argumentTypes: Option[List[Type]] =
    tree.attributes.get('argumentTypes).map(_.asInstanceOf[List[Type]])

  def argumentTypes_=(argTypes: List[Type]): Unit =
    tree.attributes = tree.attributes + ('argumentTypes -> argTypes)

  def isConstructorIdent: Boolean =
    tree.attributes.get('isConstructorIdent)
      .map(_.asInstanceOf[Boolean]).getOrElse(false)

  def isConstructorIdent_=(flag: Boolean): Unit =
    tree.attributes = tree.attributes + ('isConstructorIdent -> flag)
}

package ch.usi.inf.l3.sana.ooj.ast.augmenters

import ch.usi.inf.l3.sana
import sana.tiny.types.Type
import sana.tiny.symbols.Symbol
import sana.tiny.ast.IdentApi

trait AugmentedIdent {

  def tree: IdentApi

  def isMethodIdent: Boolean =
    tree.attributes.get('isMethod).map(_.asInstanceOf[Boolean]).getOrElse(false)

  def isMethodIdent_=(flag: Boolean): Unit =
    tree.attributes = tree.attributes + ('isMethod -> flag)

  def argumentTypes: Option[List[Type]] =
    tree.attributes.get('argumentTypes).map(_.asInstanceOf[List[Type]])

  def argumentTypes_=(argTypes: List[Type]): Unit =
    tree.attributes = tree.attributes + ('argumentTypes -> argTypes)

  def isConstructorIdent: Boolean =
    tree.attributes.get('isConstructorIdent)
      .map(_.asInstanceOf[Boolean]).getOrElse(false)

  def isConstructorIdent_=(flag: Boolean): Unit =
    tree.attributes = tree.attributes + ('isConstructorIdent -> flag)

  def isExplicitConstructorInvocation: Boolean =
    tree.attributes.get('isExplicitConstructorInvocation)
      .map(_.asInstanceOf[Boolean]).getOrElse(false)

  def isExplicitConstructorInvocation_=(flag: Boolean): Unit =
    tree.attributes =
      tree.attributes + ('isExplicitConstructorInvocation -> flag)

}

Add an attribute for explicit constructor invocation


import sbt._
import Keys._
import Tools.onVersionTask

object ScalaSettings {
  type Sett = Project.Setting[_]

  lazy val all: Seq[Sett] = Seq(
    crossVersion := CrossVersion.full
  , scalaVersion := "2.9.2"
  , crossScalaVersions := Seq("2.9.2", "2.10.0")
  , scalacOptions <++= onVersionTask(
      all = Seq("-deprecation", "-unchecked", "-optimise")
    , on210 = Seq("-Yinline-warnings", "-feature", "-language:implicitConversions", "-language:higherKinds", "-language:postfixOps")
    )
  )
}

import sbt._
import Keys._
import Tools.onVersionTask

object ScalaSettings {
  type Sett = Project.Setting[_]

  lazy val all: Seq[Sett] = Seq(
    scalaVersion := "2.9.2"
  , crossScalaVersions := Seq("2.9.2", "2.10.0")
  , scalacOptions <++= onVersionTask(
      all = Seq("-deprecation", "-unchecked", "-optimise")
    , on210 = Seq("-Yinline-warnings", "-feature", "-language:implicitConversions", "-language:higherKinds", "-language:postfixOps")
    )
  )
}

Remove CrossVersion.fill as mentioned on IRC the other day.


package org.scalafmt.config

import scala.reflect.ClassTag

import metaconfig._
import metaconfig.Configured._

object ReaderUtil {
  // Poor mans coproduct reader
  def oneOf[T: ClassTag](options: sourcecode.Text[T]*): ConfDecoder[T] =
    oneOfImpl(lowerCase, options)

  def oneOfIgnoreBackticks[T: ClassTag](
      options: sourcecode.Text[T]*): ConfDecoder[T] =
    oneOfImpl(lowerCaseNoBackticks, options)

  private val lowerCase: String => String = s => s.toLowerCase
  private val lowerCaseNoBackticks: String => String = s =>
    s.toLowerCase().replace("`", "")

  private def oneOfImpl[T: ClassTag](
      sanitize: String => String,
      options: Seq[sourcecode.Text[T]]): ConfDecoder[T] = {
    val m = options.map(x => sanitize(x.source) -> x.value).toMap
    ConfDecoder.instance[T] {
      case Conf.Str(x) =>
        m.get(sanitize(x)) match {
          case Some(y) =>
            Ok(y)
          case None =>
            val available = m.keys.mkString(", ")
            val msg = s"Unknown input '$x'. Expected one of: $available"
            ConfError.msg(msg).notOk
        }
    }
  }
}

package org.scalafmt.config

import scala.reflect.ClassTag

import metaconfig._
import metaconfig.Configured._

object ReaderUtil {
  // Poor mans coproduct reader
  def oneOf[T: ClassTag](options: sourcecode.Text[T]*): ConfDecoder[T] =
    oneOfImpl(lowerCase, options)

  def oneOfIgnoreBackticks[T: ClassTag](
      options: sourcecode.Text[T]*): ConfDecoder[T] =
    oneOfImpl(lowerCaseNoBackticks, options)

  private def lowerCase(s: String): String = s.toLowerCase
  private def lowerCaseNoBackticks(s: String): String =
    s.toLowerCase().replace("`", "")

  private def oneOfImpl[T: ClassTag](
      sanitize: String => String,
      options: Seq[sourcecode.Text[T]]): ConfDecoder[T] = {
    val m = options.map(x => sanitize(x.source) -> x.value).toMap
    ConfDecoder.instance[T] {
      case Conf.Str(x) =>
        m.get(sanitize(x)) match {
          case Some(y) =>
            Ok(y)
          case None =>
            val available = m.keys.mkString(", ")
            val msg = s"Unknown input '$x'. Expected one of: $available"
            ConfError.msg(msg).notOk
        }
    }
  }
}

Replace function vals with methods

Replace function vals with methods


package scala.meta.internal.metap

final case class Settings(
    paths: List[String] = Nil,
    proto: Boolean = false
)

object Settings {
  def parse(args: List[String]): Option[Settings] = {
    def loop(settings: Settings, allowOptions: Boolean, args: List[String]): Option[Settings] = {
      args match {
        case "--" +: rest =>
          loop(settings, false, args)
        case "-proto" +: rest if allowOptions =>
          loop(settings.copy(proto = true), true, rest)
        case flag +: rest if allowOptions && flag.startsWith("-") =>
          println(s"unknown flag $flag")
          None
        case path +: rest =>
          val paths1 = settings.paths :+ path
          loop(settings.copy(paths = paths1), true, rest)
        case Nil =>
          Some(settings)
      }
    }
    loop(Settings(), true, args)
  }
}

package scala.meta.internal.metap

final case class Settings(
    paths: List[String] = Nil,
    pretty: Boolean = true,
    proto: Boolean = false
)

object Settings {
  def parse(args: List[String]): Option[Settings] = {
    def loop(settings: Settings, allowOptions: Boolean, args: List[String]): Option[Settings] = {
      args match {
        case "--" +: rest =>
          loop(settings, false, args)
        case "-pretty" +: rest if allowOptions =>
          loop(settings.copy(pretty = true, proto = false), true, rest)
        case "-proto" +: rest if allowOptions =>
          loop(settings.copy(pretty = false, proto = true), true, rest)
        case flag +: rest if allowOptions && flag.startsWith("-") =>
          println(s"unknown flag $flag")
          None
        case path +: rest =>
          val paths1 = settings.paths :+ path
          loop(settings.copy(paths = paths1), true, rest)
        case Nil =>
          Some(settings)
      }
    }
    loop(Settings(), true, args)
  }
}

Add metap -pretty to mirror metap -proto


package gov.wicourts.json.formlet

import argonaut.Argonaut.jString
import argonaut.Json
import scalaz.{@>, Lens}

case class FieldView(name: String, value: Option[Json], label: Option[String], errorName: String) {
  def obj: JsonObjectBuilder = {
    val metadata = label.map(l =>
      "metadata" -> Json.obj("label" -> jString(l))
    ).toList

    val valueItem = value.map(("value", _)).toList

    val all = valueItem ++ metadata

    new JsonObjectBuilder(
      if (all.isEmpty) Nil
      else List(name -> Json.obj(all: _*))
    )
  }

  def toJson: Json = obj.toJson
}

object FieldView {
  val label: FieldView @> Option[String] =
    Lens.lensu[FieldView, Option[String]](
      (a, value) => a.copy(label = value),
      _.label
    )

  val errorName: FieldView @> String =
    Lens.lensu[FieldView, String](
      (a, value) => a.copy(errorName = value),
      _.errorName
    )
}

package gov.wicourts.json.formlet

import argonaut.Argonaut.jString
import argonaut.Json

import scalaz.std.list._
import scalaz.std.option._
import scalaz.syntax.monad._
import scalaz.syntax.std.option._

import scalaz.{@>, Lens}

case class FieldView(name: String, value: Option[Json], label: Option[String], errorName: String) {
  def obj: JsonObjectBuilder = {
    val metadataItems =
      List(
        label.map(l => ("label", jString(l)))
      ).map(_.toList).join

    val metadata = metadataItems.headOption.as(
      ("metadata", Json.obj(metadataItems: _*))
    ).toList

    val valueItem = value.map(("value", _)).toList

    val all = valueItem ++ metadata

    new JsonObjectBuilder(
      if (all.isEmpty) Nil
      else List(name -> Json.obj(all: _*))
    )
  }

  def toJson: Json = obj.toJson
}

object FieldView {
  val label: FieldView @> Option[String] =
    Lens.lensu[FieldView, Option[String]](
      (a, value) => a.copy(label = value),
      _.label
    )

  val errorName: FieldView @> String =
    Lens.lensu[FieldView, String](
      (a, value) => a.copy(errorName = value),
      _.errorName
    )
}

Bring back the scalaz version.

Bring back the scalaz version.

In anticipation that it will eventually be useful.


package com.socrata.soda.server

import com.socrata.http.server._
import com.socrata.http.server.responses._
import com.socrata.http.server.implicits._

import java.io.FileInputStream
import java.util.Properties
import javax.servlet.http.HttpServletRequest
import com.socrata.datacoordinator.client.{CuratedDataCoordinatorClient, DataCoordinatorClient}
import com.socrata.soda.server.persistence.PostgresStore
import com.socrata.querycoordinator.client.CuratedQueryCoordinatorClient

object SodaFountainJetty {
  def main(args:Array[String]) {

    val fountain = new SodaFountain with PostgresStore with CuratedDataCoordinatorClient with CuratedQueryCoordinatorClient with SodaRouter

    val server = new SocrataServerJetty(fountain.route, port = 8080)
    server.run
  }
}

package com.socrata.soda.server

import com.socrata.http.server._
import com.socrata.http.server.responses._
import com.socrata.http.server.implicits._

import java.io.FileInputStream
import java.util.Properties
import javax.servlet.http.HttpServletRequest
import com.socrata.datacoordinator.client.{CuratedDataCoordinatorClient, DataCoordinatorClient}
import com.socrata.soda.server.persistence.PostgresStore
import com.socrata.querycoordinator.client.CuratedQueryCoordinatorClient
import services.SodaService

object SodaFountainJetty {
  def main(args:Array[String]) {

    val fountain = new SodaFountain with PostgresStore with CuratedDataCoordinatorClient with CuratedQueryCoordinatorClient with SodaRouter
    val server = new SocrataServerJetty(fountain.route, port = SodaService.config.getConfig("network").getInt("port"))
    server.run
  }
}

Use network port in config.

Use network port in config.


package cpup.lib

object Util {
	def checkNull[T, R](obj: T, fn: (T) => R, default: R): R = {
		if(obj == null) {
			default
		} else {
			fn(obj)
		}
	}
}

package cpup.lib

object Util {
	def checkNull[R](obj: R, default: R): R = {
		if(obj == null) {
			default
		} else {
			obj
		}
	}
}

Make checkNull just check for null and return a default


package io.shaka.http

import io.shaka.http.Http._
import io.shaka.http.HttpHeader.CONTENT_TYPE
import io.shaka.http.ContentType.APPLICATION_FORM_URLENCODED
import io.shaka.http.FormParameters.{fromEntity, toEntity}
import scala.Some

object Request {
  def POST(url: Url) = Request(Method.POST, url)

  def GET(url: Url) = Request(Method.GET, url)

  def HEAD(url: Url) = Request(Method.HEAD, url)
}

case class Request(method: Method, url: Url, headers: Headers = Headers.Empty, entity: Option[Entity] = None) {
  def formParameters(parameters: FormParameter*): Request = {
    val existingFormParameters = entity.fold(List[FormParameter]())(fromEntity)
    copy(
      entity = Some(toEntity(existingFormParameters ++ parameters)),
      headers = (CONTENT_TYPE -> APPLICATION_FORM_URLENCODED.value) :: headers
    )
  }

  def header(header: HttpHeader, value: String): Request = copy(headers = (header, value) :: headers)

  def contentType(value: String) = header(CONTENT_TYPE, value)

  def contentType(value: ContentType) = header(CONTENT_TYPE, value.value)

  def entity(content: String) = copy(entity = Some(Entity(content)))
}

package io.shaka.http

import io.shaka.http.Http._
import io.shaka.http.HttpHeader.CONTENT_TYPE
import io.shaka.http.ContentType.APPLICATION_FORM_URLENCODED
import io.shaka.http.FormParameters.{fromEntity, toEntity}
import scala.Some

object Request {

  object GET {
    def apply(url: Url) = Request(Method.GET, url)

    def unapply(req: Request): Option[String] = if (req.method == Method.GET) Some(req.url) else None
  }

  object POST {
    def apply(url: Url) = Request(Method.POST, url)

    def unapply(req: Request): Option[String] = if (req.method == Method.POST) Some(req.url) else None
  }

  object HEAD {
    def apply(url: Url) = Request(Method.HEAD, url)

    def unapply(req: Request): Option[String] = if (req.method == Method.HEAD) Some(req.url) else None
  }
}

case class Request(method: Method, url: Url, headers: Headers = Headers.Empty, entity: Option[Entity] = None) {
  def formParameters(parameters: FormParameter*): Request = {
    val existingFormParameters = entity.fold(List[FormParameter]())(fromEntity)
    copy(
      entity = Some(toEntity(existingFormParameters ++ parameters)),
      headers = (CONTENT_TYPE -> APPLICATION_FORM_URLENCODED.value) :: headers
    )
  }

  def header(header: HttpHeader, value: String): Request = copy(headers = (header, value) :: headers)

  def contentType(value: String) = header(CONTENT_TYPE, value)

  def contentType(value: ContentType) = header(CONTENT_TYPE, value.value)

  def entity(content: String) = copy(entity = Some(Entity(content)))
}

Add unapply for GET,POST,HEAD so can use to pattern match in case statements


package registration.services

import java.util.UUID

import error.NotificationsError
import models.{UniqueDeviceIdentifier, _}
import registration.models.LegacyRegistration
import scalaz.\/
import scalaz.syntax.either._

class LegacyRegistrationConverter {

  def toRegistration(legacyRegistration: LegacyRegistration): NotificationsError \/ Registration = {
    val unsupportedPlatform: NotificationsError \/ Registration =
      UnsupportedPlatform(legacyRegistration.device.platform).left

    Platform.fromString(legacyRegistration.device.platform).fold(unsupportedPlatform) { platform =>
      Registration(
        deviceId = legacyRegistration.device.pushToken,
        platform = platform,
        // The Windows app sends a device generated guid as the userId, not a real Guardian user id so udid is equivalent
        userId = legacyRegistration.device.udid,
        topics = topics(legacyRegistration)
      ).right
    }
  }

  private def topics(request: LegacyRegistration): Set[Topic] = {
    val topics = for {
      topics <- request.preferences.topics.toList
      topic <- topics
      topicType <- TopicType.fromString(topic.`type`)
    } yield Topic(topicType, topic.name) // todo: check this

    val matchTopics = for {
      topics <- request.preferences.matches.toList
      topic <- topics
    } yield Topic(TopicTypes.FootballMatch, topic.matchId) // todo: check this

    val breakingTopic = if (request.preferences.receiveNewsAlerts)
      Some(Topic(TopicTypes.Breaking, request.preferences.edition))
    else None

    (topics ++ matchTopics ++ breakingTopic.toList).toSet
  }
}

package registration.services

import java.util.UUID

import error.NotificationsError
import models.{UniqueDeviceIdentifier, _}
import registration.models.LegacyRegistration
import scalaz.\/
import scalaz.syntax.either._

class LegacyRegistrationConverter {

  def toRegistration(legacyRegistration: LegacyRegistration): NotificationsError \/ Registration = {
    val unsupportedPlatform: NotificationsError \/ Registration =
      UnsupportedPlatform(legacyRegistration.device.platform).left

    Platform.fromString(legacyRegistration.device.platform).fold(unsupportedPlatform) { platform =>
      Registration(
        deviceId = legacyRegistration.device.pushToken,
        platform = platform,
        // The Windows app sends a device generated guid as the userId, not a real Guardian user id so udid is equivalent
        userId = legacyRegistration.device.udid,
        topics = topics(legacyRegistration)
      ).right
    }
  }

  private def topics(request: LegacyRegistration): Set[Topic] = {
    val topics = for {
      topics <- request.preferences.topics.toList
      topic <- topics
      topicType <- TopicType.fromString(topic.`type`)
    } yield Topic(topicType, topic.name) // todo: check this

    val matchTopics = for {
      topics <- request.preferences.matches.toList
      topic <- topics
    } yield Topic(TopicTypes.FootballMatch, topic.matchId) // todo: check this

    val breakingTopic = if (request.preferences.receiveNewsAlerts)
      Some(Topic(TopicTypes.Breaking, request.preferences.edition.toLowerCase))
    else None

    (topics ++ matchTopics ++ breakingTopic.toList).toSet
  }
}

Fix editions for legacy registrations

Fix editions for legacy registrations

iOS app sends editions as uppercase


package sttp.client.testing.websocket

import java.nio.channels.ClosedChannelException

import org.scalatest.Suite
import org.scalatest.flatspec.AsyncFlatSpecLike
import sttp.capabilities.WebSockets
import sttp.client.testing.HttpTest.wsEndpoint
import sttp.client._
import sttp.monad.MonadError
import sttp.client.testing.ConvertToFuture

import scala.concurrent.duration._
import scala.concurrent.duration.FiniteDuration
import sttp.monad.syntax._
import sttp.ws.WebSocket

trait WebSocketBufferOverflowTest[F[_]] { outer: Suite with AsyncFlatSpecLike with WebSocketTest[F] =>
  val backend: SttpBackend[F, WebSockets]
  implicit val monad: MonadError[F]
  implicit val convertToFuture: ConvertToFuture[F]
  def bufferCapacity: Int

  it should "error if incoming messages overflow the buffer" in {
    basicRequest
      .get(uri"$wsEndpoint/ws/echo")
      .response(asWebSocketAlways { (ws: WebSocket[F]) =>
        send(ws, bufferCapacity + 1).flatMap { _ =>
          eventually(10.millis, 500) {
            ws.isOpen().map(_ shouldBe false)
          }
        }
      })
      .send(backend)
      .map(_.body)
      .handleError {
        case _: ClosedChannelException => succeed.unit
      }
      .toFuture()
  }

  def eventually[T](interval: FiniteDuration, attempts: Int)(f: => F[T]): F[T]
}

package sttp.client.testing.websocket

import java.nio.channels.ClosedChannelException

import org.scalatest.Suite
import org.scalatest.flatspec.AsyncFlatSpecLike
import sttp.capabilities.WebSockets
import sttp.client.testing.HttpTest.wsEndpoint
import sttp.client._
import sttp.monad.MonadError
import sttp.client.testing.ConvertToFuture

import scala.concurrent.duration._
import scala.concurrent.duration.FiniteDuration
import sttp.monad.syntax._
import sttp.ws.WebSocket

trait WebSocketBufferOverflowTest[F[_]] { outer: Suite with AsyncFlatSpecLike with WebSocketTest[F] =>
  val backend: SttpBackend[F, WebSockets]
  implicit val monad: MonadError[F]
  implicit val convertToFuture: ConvertToFuture[F]
  def bufferCapacity: Int

  it should "error if incoming messages overflow the buffer" in {
    basicRequest
      .get(uri"$wsEndpoint/ws/echo")
      .response(asWebSocketAlways { (ws: WebSocket[F]) =>
        send(ws, bufferCapacity + 100).flatMap { _ =>
          eventually(10.millis, 500) {
            ws.isOpen().map(_ shouldBe false)
          }
        }
      })
      .send(backend)
      .map(_.body)
      .handleError {
        case _: ClosedChannelException => succeed.unit
      }
      .toFuture()
  }

  def eventually[T](interval: FiniteDuration, attempts: Int)(f: => F[T]): F[T]
}

Make buffering test more resilient

Make buffering test more resilient


import sbt.Project.projectToRef

lazy val jsProjects = Seq(js)
lazy val scalaV = "2.11.5"

lazy val jvm = project.settings(
  scalaVersion := scalaV,
  scalaJSProjects := jsProjects,
  pipelineStages := Seq(scalaJSProd, gzip),
  libraryDependencies ++= Seq(
    "com.vmunier" %% "play-scalajs-scripts" % "0.1.0",
    "org.webjars" % "jquery" % "1.11.1"
  ),
  EclipseKeys.skipParents in ThisBuild := false).
  enablePlugins(PlayScala).
  aggregate(jsProjects.map(projectToRef): _*).
  dependsOn(sharedJvm)

lazy val js = project.settings(
  scalaVersion := scalaV,
  persistLauncher := true,
  persistLauncher in Test := false,
  sourceMapsDirectories += sharedJs.base / "..",
  libraryDependencies += "org.scala-js" %%% "scalajs-dom" % "0.8.0").
  enablePlugins(ScalaJSPlugin, ScalaJSPlay).
  dependsOn(sharedJs)

lazy val shared = crossProject.crossType(CrossType.Pure).
  settings(scalaVersion := scalaV).
  jsConfigure(_ enablePlugins ScalaJSPlay).
  jsSettings(sourceMapsBase := baseDirectory.value / "..")

lazy val sharedJvm = shared.jvm
lazy val sharedJs = shared.js

// loads the jvm project at sbt startup
onLoad in Global := (Command.process("project jvm", _: State)) compose (onLoad in Global).value

import sbt.Project.projectToRef

lazy val jsProjects = Seq(js)
lazy val scalaV = "2.11.5"

lazy val jvm = project.settings(
  scalaVersion := scalaV,
  scalaJSProjects := jsProjects,
  pipelineStages := Seq(scalaJSProd, gzip),
  libraryDependencies ++= Seq(
    "com.vmunier" %% "play-scalajs-scripts" % "0.1.0",
    "org.webjars" % "jquery" % "1.11.1"
  ),
  EclipseKeys.skipParents in ThisBuild := false).
  enablePlugins(PlayScala).
  aggregate(jsProjects.map(projectToRef): _*).
  dependsOn(sharedJvm)

lazy val js = project.settings(
  scalaVersion := scalaV,
  persistLauncher := true,
  persistLauncher in Test := false,
  sourceMapsDirectories += sharedJs.base / "..",
  unmanagedSourceDirectories in Compile := Seq((scalaSource in Compile).value),
  libraryDependencies += "org.scala-js" %%% "scalajs-dom" % "0.8.0").
  enablePlugins(ScalaJSPlugin, ScalaJSPlay).
  dependsOn(sharedJs)

lazy val shared = crossProject.crossType(CrossType.Pure).
  settings(scalaVersion := scalaV).
  jsConfigure(_ enablePlugins ScalaJSPlay).
  jsSettings(sourceMapsBase := baseDirectory.value / "..")

lazy val sharedJvm = shared.jvm
lazy val sharedJs = shared.js

// loads the jvm project at sbt startup
onLoad in Global := (Command.process("project jvm", _: State)) compose (onLoad in Global).value

Set unmanagedSourceDirectories to contain the Scala directory only. It is to prevent the creation of an empty src/main/java directory under the Scala.js project. The play run command used to create that folder because jvm aggregates the js project and watches unmanagedSourceDirectories from the js project which contains both a scala and a java folder by default.


import com.github.retronym.SbtOneJar._

oneJarSettings

name := "api-lint"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.0.22"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.5.0",
      "com.ning" % "async-http-client" % "1.9.34",
      "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-lint"

organization := "io.flow"

scalaVersion in ThisBuild := "2.11.8"

version := "0.0.23"

exportJars := true

lazy val root = project
  .in(file("."))
  .settings(
    libraryDependencies ++= Seq(
      "com.typesafe.play" %% "play-json" % "2.5.0",
      "com.ning" % "async-http-client" % "1.9.34",
      "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.23


import AndroidKeys._

AndroidProject.androidSettings

AndroidMarketPublish.settings

name := "Spiel"

version := "3.0.0"

scalaVersion := "2.9.2"

scalacOptions ++= Seq("-deprecation")

platformName in Android := "android-17"

keystorePath in Android := Path.userHome / ".keystore" / "spiel.keystore"

keyalias in Android := "spiel"

libraryDependencies := Seq(
  "rhino" % "js" % "1.7R2" from "http://android-scripting.googlecode.com/hg/rhino/rhino1_7R2.jar",
  "net.databinder" % "dispatch-lift-json_2.9.1" % "0.7.8",
  "org.ccil.cowan.tagsoup" % "tagsoup" % "1.2.1"
)

proguardOption in Android := """
  -keep class info.spielproject.spiel.** { *; }
  -keep class org.mozilla.javascript.* { *; }
  -keep class org.mozilla.javascript.ast.* { *; }
  -keep class org.mozilla.javascript.json.* { *; }
  -keep class org.mozilla.javascript.jdk15.* { *; }
  -keep class org.mozilla.javascript.regexp.* { *; }
  -keep class org.mozilla.javascript.resources.* { *; }
"""

import AndroidKeys._

AndroidProject.androidSettings

AndroidMarketPublish.settings

name := "Spiel"

version := "3.0.0"

scalaVersion := "2.9.2"

scalacOptions ++= Seq("-deprecation")

platformName in Android := "android-17"

keystorePath in Android := Path.userHome / ".keystore" / "spiel.keystore"

keyalias in Android := "spiel"

libraryDependencies := Seq(
  "rhino" % "js" % "1.7R2" from "http://android-scripting.googlecode.com/hg/rhino/rhino1_7R2.jar",
  "net.databinder" % "dispatch-lift-json_2.9.1" % "0.7.8",
  "org.ccil.cowan.tagsoup" % "tagsoup" % "1.2.1"
)

proguardOption in Android := """
  -keep class scala.collection.SeqLike { public protected *; }
  -keep class info.spielproject.spiel.** { *; }
  -keep class org.mozilla.javascript.* { *; }
  -keep class org.mozilla.javascript.ast.* { *; }
  -keep class org.mozilla.javascript.json.* { *; }
  -keep class org.mozilla.javascript.jdk15.* { *; }
  -keep class org.mozilla.javascript.regexp.* { *; }
  -keep class org.mozilla.javascript.resources.* { *; }
"""

Add additional Proguard directive needed for upgrade to Scala 2.10.

--HG--
extra : convert_revision : dfd98427c8aa4bd8b189f91a923062950a290af1


crossBuildingSettings

sbtPlugin := true

name := "sbt-haxe"

organization := "com.qifun"

scalacOptions += "-deprecation"

scalacOptions += "-feature"

version := "0.1.5-SNAPSHOT"

CrossBuilding.crossSbtVersions := Seq("0.12", "0.13")

publishTo <<= (isSnapshot) { isSnapshot: Boolean =>
  if (isSnapshot)
    Some("snapshots" at "https://oss.sonatype.org/content/repositories/snapshots")
  else
    Some("releases" at "https://oss.sonatype.org/service/local/staging/deploy/maven2")
}

crossBuildingSettings

sbtPlugin := true

name := "sbt-haxe"

organization := "com.qifun"

scalacOptions += "-deprecation"

scalacOptions += "-feature"

CrossBuilding.crossSbtVersions := Seq("0.13")

Delete the settings copy from sbt-cppp

Delete the settings copy from sbt-cppp


import sbt._

class LiftJson(info: ProjectInfo) extends DefaultProject(info) {
  val paranamer  = "com.thoughtworks.paranamer" % "paranamer" % "2.0" % "compile->default"
  val junit      = "junit" % "junit" % "4.5"
  val specs      = "org.scala-tools.testing" %% "specs" % "1.6.5"
  val scalacheck = "org.scala-tools.testing" %% "scalacheck" % "1.7"

  override def compileOptions = super.compileOptions ++ compileOptions("-unchecked")

  override def ivyXML =
    <publications>
      <artifact name="lift-json" type="jar" ext="jar"/>
    </publications>
}

import sbt._

class LiftJson(info: ProjectInfo) extends DefaultProject(info) {
  val paranamer  = "com.thoughtworks.paranamer" % "paranamer" % "2.0" % "compile->default"
  val junit      = "junit" % "junit" % "4.5" % "test"
  val specs      = "org.scala-tools.testing" %% "specs" % "1.6.5" % "test"
  val scalacheck = "org.scala-tools.testing" %% "scalacheck" % "1.7" % "test"

  override def compileOptions = super.compileOptions ++ compileOptions("-unchecked")

  override def ivyXML =
    <publications>
      <artifact name="lift-json" type="jar" ext="jar"/>
    </publications>
}

Test scope for test libs

Test scope for test libs


package com.socrata.soda.server

import com.rojoma.simplearm.util._
import com.socrata.http.server.SocrataServerJetty
import com.socrata.http.server.curator.CuratorBroker
import com.socrata.soda.server.config.SodaFountainConfig
import com.socrata.thirdparty.curator.DiscoveryFromConfig
import com.socrata.thirdparty.metrics.{SocrataHttpSupport, MetricsOptions, MetricsReporter}
import com.typesafe.config.ConfigFactory

object SodaFountainJetty extends App {
  val config = new SodaFountainConfig(ConfigFactory.load())
  val metricsOptions = MetricsOptions(config.codaMetrics)
  for {
    sodaFountain <- managed(new SodaFountain(config))
    discovery <- managed(DiscoveryFromConfig.unmanaged(classOf[Void],
                                                       sodaFountain.curator,
                                                       config.discovery))
  } {
    discovery.start()
    val reporter = new MetricsReporter(metricsOptions)

    val server = new SocrataServerJetty(
      sodaFountain.handle,
      port = config.network.port,
      extraHandlers = List(SocrataHttpSupport.getHandler(metricsOptions)),
      broker = new CuratorBroker[Void](discovery,
                                       config.serviceAdvertisement.address,
                                       config.serviceAdvertisement.service,
                                       None))

    server.run()
  }
}

package com.socrata.soda.server

import com.rojoma.simplearm.util._
import com.socrata.http.server.SocrataServerJetty
import com.socrata.http.server.curator.CuratorBroker
import com.socrata.soda.server.config.SodaFountainConfig
import com.socrata.thirdparty.curator.DiscoveryFromConfig
import com.socrata.thirdparty.metrics.{SocrataHttpSupport, MetricsOptions, MetricsReporter}
import com.typesafe.config.ConfigFactory

object SodaFountainJetty extends App {
  val config = new SodaFountainConfig(ConfigFactory.load())
  val metricsOptions = MetricsOptions(config.codaMetrics)
  for {
    sodaFountain <- managed(new SodaFountain(config))
    discovery <- managed(DiscoveryFromConfig.unmanaged(classOf[Void],
                                                       sodaFountain.curator,
                                                       config.discovery))
    reporter <- MetricsReporter.managed(metricsOptions)
  } {
    discovery.start()

    val server = new SocrataServerJetty(
      sodaFountain.handle,
      port = config.network.port,
      extraHandlers = List(SocrataHttpSupport.getHandler(metricsOptions)),
      broker = new CuratorBroker[Void](discovery,
                                       config.serviceAdvertisement.address,
                                       config.serviceAdvertisement.service,
                                       None))

    server.run()
  }
}

Use managed version of MetricsReporter

Use managed version of MetricsReporter


package org.jetbrains.plugins.cbt.project.template

import java.io.File
import com.intellij.openapi.util.io.FileUtil._
import org.jetbrains.plugins.scala.project.Version
import org.jetbrains.sbt.RichFile

object CbtProjectGenerator {
  def apply(root: File, scalaVersion: Version): Unit = {
    (root / "src").mkdirs()
    writeToFile(root / "build" / "build.scala", BuildFileTemplate(scalaVersion))
  }
}

object BuildFileTemplate {
  def apply(scalaVersion: Version): String =
    """
      |import cbt._
      |
      |class Build(val  context: Context) extends BaseBuild {
      |}
    """.stripMargin
}

package org.jetbrains.plugins.cbt.project.template

import java.io.File
import com.intellij.openapi.util.io.FileUtil._
import org.jetbrains.plugins.scala.project.Version
import org.jetbrains.sbt.RichFile

object CbtProjectGenerator {
  def apply(root: File, scalaVersion: Version): Unit = {
    (root / "src").mkdirs()
    writeToFile(root / "build" / "build.scala", BuildFileTemplate(scalaVersion))
  }
}

object BuildFileTemplate {
  def apply(scalaVersion: Version): String =
    s"""
      |import cbt._
      |
      |class Build(val context: Context) extends BaseBuild {
      |  override def defaultScalaVersion = "${scalaVersion.toString}"
      |}
    """.stripMargin
}

Add different scala version support

Add different scala version support


name := """play-reactive-couchbase"""

version := "1.0-SNAPSHOT"

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

scalaVersion := "2.11.7"

routesGenerator := InjectedRoutesGenerator

resolvers += "ReactiveCouchbase Releases" at "https://raw.github.com/ReactiveCouchbase/repository/master/releases/"

libraryDependencies ++= Seq(
  "org.reactivecouchbase" %% "reactivecouchbase-core" % "0.3",
  "org.reactivecouchbase" %% "reactivecouchbase-play" % "0.3",
  "org.scalatestplus.play" %% "scalatestplus-play" % "1.5.0" % "test" withSources(),
  "org.scalaz" %% "scalaz-core" % "7.2.6",
  "org.mockito" % "mockito-core" % "1.10.19"
)

resolvers += "scalaz-bintray" at "http://dl.bintray.com/scalaz/releases"

scalacOptions in ThisBuild ++= Seq("-feature", "-language:postfixOps")

name := """play-reactive-couchbase"""

version := "1.0-SNAPSHOT"

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

scalaVersion := "2.11.8"

routesGenerator := InjectedRoutesGenerator

resolvers += "ReactiveCouchbase Releases" at "https://raw.github.com/ReactiveCouchbase/repository/master/releases/"

libraryDependencies ++= Seq(
  "org.reactivecouchbase" %% "reactivecouchbase-core" % "0.3",
  "org.reactivecouchbase" %% "reactivecouchbase-play" % "0.3",
  "org.scalatestplus.play" %% "scalatestplus-play" % "1.5.0" % "test" withSources(),
  "org.scalaz" %% "scalaz-core" % "7.2.6",
  "org.mockito" % "mockito-core" % "1.10.19"
)

resolvers += "scalaz-bintray" at "http://dl.bintray.com/scalaz/releases"

scalacOptions in ThisBuild ++= Seq("-feature", "-language:postfixOps")

Upgrade scala version to 2.11.8

Upgrade scala version to 2.11.8


package unfiltered.scalatest.netty

import io.netty.util.ResourceLeakDetector
import org.scalatest.{ Suite, Outcome }
import unfiltered.netty.Http
import unfiltered.scalatest.Hosted

trait Planned extends Served { self: Hosted =>
  def setup = _.handler(unfiltered.netty.cycle.Planify(intent))
  def intent[A, B]: unfiltered.Cycle.Intent[A, B]
}

trait Served extends Suite with Hosted {
  // Enables paranoid resource leak detection which reports where the leaked object was accessed recently,
  // at the cost of the highest possible overhead (for testing purposes only).
  ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.PARANOID)

  def setup: Http => Http
  def getServer = setup(Http(port))

  override protected def withFixture(test: NoArgTest): Outcome = {
    val server = getServer
    server.start()
    try {
      test() // Invoke the test function
    } finally {
      server.stop()
      server.destroy()
    }
  }
}

package unfiltered.scalatest.netty

import io.netty.util.ResourceLeakDetector
import org.scalatest.{ Suite, Outcome }
import unfiltered.netty.Server
import unfiltered.scalatest.Hosted

trait Planned extends Served { self: Hosted =>
  def setup = _.plan(unfiltered.netty.cycle.Planify(intent))
  def intent[A, B]: unfiltered.Cycle.Intent[A, B]
}

trait Served extends Suite with Hosted {
  // Enables paranoid resource leak detection which reports where the leaked object was accessed recently,
  // at the cost of the highest possible overhead (for testing purposes only).
  ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.PARANOID)

  def setup: Server => Server
  def getServer = setup(Server.http(port))

  override protected def withFixture(test: NoArgTest): Outcome = {
    val server = getServer
    server.start()
    try {
      test() // Invoke the test function
    } finally {
      server.stop()
      server.destroy()
    }
  }
}

Update scalatest base to use the new netty builder.


name := "pureconfig-cron4s"

libraryDependencies += {
  val cron4sVersion = CrossVersion.partialVersion(scalaVersion.value) match {
    case Some((2, n)) if n < 12 => "0.5.0"
    case _                      => "0.6.0"
  }

  "com.github.alonsodomin.cron4s" %% "cron4s-core" % cron4sVersion
}

developers := List(
  Developer("bardurdam", "Bárður Viberg Dam", "bardurdam@gmail.com", url("https://github.com/bardurdam")))

osgiSettings

OsgiKeys.exportPackage := Seq("pureconfig.module.cron4s.*")
OsgiKeys.privatePackage := Seq()
OsgiKeys.importPackage := Seq(s"""scala.*;version="[${scalaBinaryVersion.value}.0,${scalaBinaryVersion.value}.50)"""", "*")

name := "pureconfig-cron4s"

crossScalaVersions := List("2.13.1", "2.12.9")

libraryDependencies += "com.github.alonsodomin.cron4s" %% "cron4s-core" % "0.6.0"

developers := List(
  Developer("bardurdam", "Bárður Viberg Dam", "bardurdam@gmail.com", url("https://github.com/bardurdam")))

osgiSettings

OsgiKeys.exportPackage := Seq("pureconfig.module.cron4s.*")
OsgiKeys.privatePackage := Seq()
OsgiKeys.importPackage := Seq(s"""scala.*;version="[${scalaBinaryVersion.value}.0,${scalaBinaryVersion.value}.50)"""", "*")

Drop 2.11 support in cron4s

Drop 2.11 support in cron4s


package uk.ac.wellcome.platform.idminter.model

import com.google.inject.Inject
import com.twitter.inject.annotations.Flag
import scalikejdbc._

/** Represents a set of identifiers as stored in MySQL */
case class Identifier(CanonicalID: String, MiroID: String)

object Identifier {
  def apply(p: SyntaxProvider[Identifier])(rs: WrappedResultSet): Identifier =
    Identifier(rs.string(p.resultName.CanonicalID),
               rs.string(p.resultName.MiroID))
}

class IdentifiersTable @Inject()(
  @Flag("aws.rds.identifiers.database") database: String,
  @Flag("aws.rds.identifiers.table") table: String)
    extends SQLSyntaxSupport[Identifier] {
  override val schemaName = Some(database)
  override val tableName = table
  override val useSnakeCaseColumnName = false
  override val columns = Seq("CanonicalID", "ontologyType", "MiroID")

  val i = this.syntax("i")
}

package uk.ac.wellcome.platform.idminter.model

import com.google.inject.Inject
import com.twitter.inject.annotations.Flag
import scalikejdbc._

/** Represents a set of identifiers as stored in MySQL */
case class Identifier(
  CanonicalID: String,
  MiroID: String,
  ontologyType: String = "Work"
)

object Identifier {
  def apply(p: SyntaxProvider[Identifier])(rs: WrappedResultSet): Identifier =
    Identifier(
      CanonicalID = rs.string(p.resultName.CanonicalID),
      MiroID = rs.string(p.resultName.MiroID),
      ontologyType = rs.string(p.resultName.ontologyType)
    )
}

class IdentifiersTable @Inject()(
  @Flag("aws.rds.identifiers.database") database: String,
  @Flag("aws.rds.identifiers.table") table: String)
    extends SQLSyntaxSupport[Identifier] {
  override val schemaName = Some(database)
  override val tableName = table
  override val useSnakeCaseColumnName = false
  override val columns = Seq("CanonicalID", "ontologyType", "MiroID")

  val i = this.syntax("i")
}

Update the Identifier class with the ontologyType field


package play.api

import play.api.mvc._

/**
 * A Play plugin.
 *
 * You can define a Play plugin this way:
 * {{{
 * class MyPlugin(app: Application) extends Plugin
 * }}}
 *
 * The plugin class must be declared in a play.plugins file available in the classpath root:
 * {{{
 * myapp.MyPlugin:1000
 * }}}
 * The associated int defines the plugin priority.
 */
trait Plugin {

  /**
   * Called when the application starts.
   */
  def onStart() {}

  /**
   * Called when the application stops.
   */
  def onStop() {}

  /**
   * Is the plugin enabled?
   */
  def enabled: Boolean = true
}

package play.api

import play.api.mvc._

/**
 * A Play plugin.
 *
 * You can define a Play plugin this way:
 * {{{
 * class MyPlugin(app: Application) extends Plugin
 * }}}
 *
 * The plugin class must be declared in a play.plugins file available in the classpath root:
 * {{{
 * 1000:myapp.MyPlugin
 * }}}
 * The associated int defines the plugin priority.
 */
trait Plugin {

  /**
   * Called when the application starts.
   */
  def onStart() {}

  /**
   * Called when the application stops.
   */
  def onStop() {}

  /**
   * Is the plugin enabled?
   */
  def enabled: Boolean = true
}

Fix reverse syntax in docs

Fix reverse syntax in docs


package beyond

import akka.actor.Actor
import akka.actor.ActorLogging
import java.io.File
import scala.sys.process.Process

// FIXME: Extract ProcessLauncher trait from MongoDBLauncher and reuse it
// once we have more than one process launchers.
// FIXME: Shutdown the server and crash this actor if the underlying MongoDB
// server does not respond.
class MongoDBLauncher extends Actor with ActorLogging {
  // FIXME: Add more mongod paths.
  private val mongodPaths = Seq(
    "/usr/bin/mongod",
    "/opt/local/bin/mongod" // Max OS X Port default path
  )

  private var process: Option[Process] = _

  override def preStart() {
    val dbPath = new File(Global.mongoDBPath)
    if (!dbPath.exists()) {
      dbPath.mkdirs()
    }

    mongodPaths.find(new File(_).isFile).map {
      path =>
        val processBuilder = Process(Seq(path, "--dbpath", dbPath.getCanonicalPath))
        process = Some(processBuilder.run())
        log.info("MongoDB started")
    }.getOrElse {
      throw new LauncherInitializationException
    }
  }

  override def postStop() {
    process.foreach(_.destroy())
    process = None
    log.info("MongoDB stopped")
  }

  override def receive: Receive = {
    case _ =>
  }
}

package beyond

import akka.actor.Actor
import akka.actor.ActorLogging
import java.io.File
import scala.sys.process.Process

// FIXME: Extract ProcessLauncher trait from MongoDBLauncher and reuse it
// once we have more than one process launchers.
// FIXME: Shutdown the server and crash this actor if the underlying MongoDB
// server does not respond.
class MongoDBLauncher extends Actor with ActorLogging {
  // FIXME: Add more mongod paths.
  private val mongodPaths = Seq(
    "/usr/bin/mongod",
    "/opt/local/bin/mongod", // Max OS X Port default path
    "C:/Program Files/MongoDB 2.6 Standard/bin/mongod.exe" // Windows default path
  )

  private var process: Option[Process] = _

  override def preStart() {
    val dbPath = new File(Global.mongoDBPath)
    if (!dbPath.exists()) {
      dbPath.mkdirs()
    }

    mongodPaths.find(new File(_).isFile).map {
      path =>
        val processBuilder = Process(Seq(path, "--dbpath", dbPath.getCanonicalPath))
        process = Some(processBuilder.run())
        log.info("MongoDB started")
    }.getOrElse {
      throw new LauncherInitializationException
    }
  }

  override def postStop() {
    process.foreach(_.destroy())
    process = None
    log.info("MongoDB stopped")
  }

  override def receive: Receive = {
    case _ =>
  }
}

Add MongoDB binary path for Windows.

Add MongoDB binary path for Windows.