object Solution {
  import java.math.BigInteger

  // This code came from
  // http://stackoverflow.com/questions/18828377/biginteger-count-the-number-of-decimal-digits-in-a-scalable-method
  def log10(bigNumber: BigInteger): Int = {
    var digits = 0
    var huge = bigNumber
    var bits = huge.bitLength()
    // Serious reductions.
    while (bits > 4) {
      // 4 > log[2](10) so we should not reduce it too far.
      val reduce = bits / 4;
      // Divide by 10^reduce
      huge = huge.divide(BigInteger.TEN.pow(reduce));
      // Removed that many decimal digits.
      digits += reduce;
      // Recalculate bitLength
      bits = huge.bitLength();
    }
    // Now 4 bits or less - add 1 if necessary.
    if ( huge.intValue() > 9 ) {
      digits += 1;
    }
    return digits;
  }

  def main(args: Array[String]) {
    val n = readLine.toInt
    var (num, den) = (BigInt(1393), BigInt(185))
    for (i <- 8 to n) {
      val nc = log10(num.bigInteger)
      val dc = log10(den.bigInteger)
      if (nc - dc > 0) println(i)
      num = num + 2 * den
      den = num - den
    }
  }
}

Add solution to problem 57. BigInt again.


package com.sksamuel.elastic4s.analyzers

import org.scalatest.{Matchers, WordSpec}

class TruncateTokenFilterTest extends WordSpec with TokenFilterDsl with Matchers {

  "TruncateTokenFilter builder" should {
    "not set any defaults" in {
      truncateTokenFilter("testy").json.string shouldBe """{"type":"truncate"}"""
    }
  }
}

Add failing test for truncate token filter


package net.sansa_stack.inference.spark.forwardchaining.axioms

import net.sansa_stack.owl.spark.rdd.FunctionalSyntaxOWLAxiomsRDDBuilder
import net.sansa_stack.owl.spark.rdd.OWLAxiomsRDD
import org.scalatest.FunSuite
import org.semanticweb.owlapi.model.OWLAxiom
import org.apache.spark.sql.SparkSession
import org.apache.spark.SparkContext
import org.apache.spark.rdd.RDD

class ForwardRuleReasonerRDFSTest extends FunSuite {

  val sparkSession = SparkSession.builder
        .master("local[*]")
        .config("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
        .appName("OWL Axioms Forward Rule Reasoner")
        .getOrCreate()

  val sc: SparkContext = sparkSession.sparkContext

  val reasoner = new ForwardRuleReasonerRDFS(sc, 4)

  test("RDFS Axiom Forward Chaining Rule Reasoner") {

      val input = getClass.getResource("/ont_functional.owl").getPath

      var owlAxiomsRDD: OWLAxiomsRDD = FunctionalSyntaxOWLAxiomsRDDBuilder.build(sparkSession, input)
      val reasoner: RDD[OWLAxiom] = new ForwardRuleReasonerRDFS(sc, 4).apply(owlAxiomsRDD, input)

      assert(reasoner.count() == 16)

  }
}

Test for RDFS forward chaining rule reasoner


object Solution {

  def isSquare(n: Long): (Boolean, Long) = {
    // fail fast
    if (n < 0 || (n & 2) != 0 || (n & 7) == 5 || (n & 11) == 8) return (false, -1)
    if (n == 0) return (true, 0)
    val x = math.sqrt(n).toLong
    (x * x == n, x)
  }

  def main(args: Array[String]) {
    val Array(n, a, b) = readLine.split(" ").map(_.toLong)
    (a, b) match {
      case (3, 5) =>
        var m, p = 1L
        while (p < n) {
          if (isSquare(8 * p + 1)._1) println(p)
          m += 1
          p = m * (3 * m - 1) / 2
        }
      case (5, 6) =>
        var m, p = 1L
        while (p < n) {
          val (isSq, root) = isSquare(8 * p + 1)
          if (isSq && ((root + 1) & 3) == 0) println(p)
          m += 1
          p = m * (3 * m - 1) / 2
        }
      case _ =>
    }
  }
}

Add solution to problem 45. The isSquare may not be a good name


package controllers.graphql

import akka.http.scaladsl.model.{HttpEntity, MediaTypes, StatusCodes}
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.util.ByteString
import models.counter.Counter
import org.scalatest.{Matchers, WordSpec}
import spray.json._
import util.Injecting

class GraphQLControllerSpec extends WordSpec with Matchers with ScalatestRouteTest with Injecting {

  val routes: Route = inject[GraphQLController].Routes
  val addServerCounter = ByteString(
    """
      [
          {
              "query" : "mutation Increment { addServerCounter(amount: 2) { amount } }"
          }
      ]
    """.stripMargin
  )

  "GraphQLControler" must {

    "increment amount of counter" in {
      implicit val counterJsonReader = CounterJsonReader

      val contentType = MediaTypes.`application/json`
      val addServerCounterEntity = HttpEntity(contentType, addServerCounter)

      Post("/graphql", addServerCounterEntity) ~> routes ~> check {

        status shouldBe StatusCodes.OK
        contentType shouldBe MediaTypes.`application/json`

        val counter = responseAs[String].parseJson.convertTo[Counter]
        counter.amount shouldBe 2
      }
    }
  }
}

object CounterJsonReader extends JsonReader[Counter] {
  override def read(json: JsValue): Counter = {
    val fields = json.asJsObject.fields
    val serverCounter = fields("data").asJsObject.fields("addServerCounter")
    val amount: JsNumber = serverCounter.asJsObject.fields("amount").asInstanceOf[JsNumber]
    Counter(amount.value.toInt)
  }
}

Add test for 'addServerCounter' GraphQL mutation


package modules.user.graphql.resolvers

import modules.user.model.{RegisterUserInput, UserPayload}

import scala.concurrent.Future

trait UserResolver {

  def register(registerUserInput: RegisterUserInput): Future[UserPayload]
}

Add 'GraphQL' resolver for 'User'

Add 'GraphQL' resolver for 'User'


package org.labrad

import io.netty.buffer.ByteBuf
import java.nio.charset.StandardCharsets.UTF_8

package object data {
  implicit class Flattenable[T](val value: T) extends AnyVal {
    /**
     * Flatten this scala object into labrad data.
     *
     * There must be a setter for this type T available
     * in implicit scope.
     */
    def toData(tag: String)(implicit setter: Setter[T]): Data = {
      val data = Data(tag)
      data.set(value)
      data
    }
  }

  implicit class RichByteBuf(val buf: ByteBuf) extends AnyVal {
    /**
     * Write the length of a chunk of data as a 4-byte prefix field.
     * We do this by first reserving so space for the length field
     * and recording its location, then executing the provided function
     * and keeping track of how many bytes are written, and finally
     * going back and filling in the correct length.
     */
    def writeLen(f: => Unit): ByteBuf = {
      val idx = buf.writerIndex
      buf.writeInt(0)
      val start = buf.writerIndex
      f
      val len = buf.writerIndex - start
      buf.setInt(idx, len)
    }

    def writeData(data: Data): ByteBuf = {
      data.flatten(buf)
      buf
    }

    def writeUtf8String(s: String): ByteBuf = {
      buf.writeBytes(s.getBytes(UTF_8))
    }

    /**
     * Consume all readable bytes of this byte buffer as a byte array.
     */
    def toByteArray: Array[Byte] = {
      val bytes = Array.ofDim[Byte](buf.readableBytes)
      buf.getBytes(buf.readerIndex, bytes)
      bytes
    }
  }
}

Include RichByteBuf extension methods for ByteBuf handling.


package com.codiply.barrio.neighbors

import scala.concurrent.duration._

import akka.actor.Actor
import akka.actor.Actor.Receive
import akka.actor.ActorRef
import akka.actor.Props
import akka.actor.PoisonPill
import Point._

object NeighborAggregatorActor {
  def props(
      coordinates: Coordinates,
      kNeighbors: Int,
      distance: DistanceMetric,
      replyTo: ActorRef,
      expectedNumberOfResponses: Int,
      timeout: FiniteDuration) = Props(new NeighborAggregatorActor(
          coordinates, kNeighbors, distance, replyTo, expectedNumberOfResponses, timeout))
}

object NeighborAggregatorActorProtocol {
  object DoSendAggregate
}

class NeighborAggregatorActor(
    coordinates: Coordinates,
    kNeighbors: Int,
    distance: DistanceMetric,
    originalQuerySender: ActorRef,
    expectedNumberOfResponses: Int,
    timeout: FiniteDuration) extends Actor {
  import NeighborhoodPatchActorProtocol._
  import NeighborAggregatorActorProtocol._
  import context.dispatcher

  var nearestNeighbors: List[Point] = Nil
  var outstandingResponses = expectedNumberOfResponses

  context.system.scheduler.scheduleOnce(timeout, self, DoSendAggregate)

  def receive: Receive = {
    case GetNeighborsResponse(neighbors) =>
      this.nearestNeighbors = (nearestNeighbors ++ neighbors).sortBy(p =>
        distance(coordinates, p.coordinates)).take(kNeighbors)
      this.outstandingResponses -= 1
      if (this.outstandingResponses <= 0) self ! DoSendAggregate
    case DoSendAggregate =>
      originalQuerySender ! GetNeighborsResponse(nearestNeighbors)
      context.stop(self)
  }
}

Create NeighborAggregatorActor to aggregate responses at node or cluster level


package com.signalcollect.triplerush.sparql

import com.signalcollect.triplerush.TripleRush
import org.scalatest.{Matchers, FlatSpec}
import scala.collection.JavaConversions.asScalaIterator

class Sparql11SyntaxTest extends FlatSpec with Matchers{

  it should "read manifest.ttl of syntax-fed and write a query against to get tests and their type in them" in {
    val tr = new TripleRush
    val manifestFile = "src/test/resources/sparql-1.1-w3c/syntax-fed/manifest.ttl"
    val graph = new TripleRushGraph(tr)
    implicit val model = graph.getModel
    tr.loadNtriples(manifestFile)
    tr.prepareExecution
    val query =
      """
        |		PREFIX mf:  <http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#>
        |		PREFIX qt:  <http://www.w3.org/2001/sw/DataAccess/tests/test-query#>
        |   PREFIX dawgt: <http://www.w3.org/2001/sw/DataAccess/tests/test-dawg#>
        |   PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
        |				SELECT ?TestURI ?Name ?Action ?Type
        |		WHERE { [] rdf:first ?TestURI.
        |		        ?TestURI a ?Type ;
        |		                 mf:name ?Name ;
        |		                 mf:action ?Action ;
        |		                 dawgt:approval dawgt:Approved .
        |		        FILTER(?Type IN (mf:PositiveSyntaxTest11, mf:NegativeSyntaxTest11, mf:PositiveUpdateSyntaxTest11, mf:NegativeUpdateSyntaxTest11))
        |		 }
      """.stripMargin
    val results = Sparql(query)
    results.size should be(3)
  }

}

Test to read syntax-fed from w3c specifications and retrieve tests and their types from it.


object Main {
    def main(args: Array[String]) {
        val a = io.StdIn.readLine().toDouble
        val b = io.StdIn.readLine().toDouble
        val c = io.StdIn.readLine().toDouble

        println("MEDIA = %.1f".format((a * 2.0 + b * 3.0 + c * 5.0) / 10.0))
    }
}

Solve Average 2 in scala

Solve Average 2 in scala


package org.precompiler.scala101.ch09

/**
  *
  * @author Richard Li
  */
object MatchingWithExtractors extends App {
  def process(input: String): Unit = {
    input match {
      case Command() => println(s"Processing command ${input}")
      case _ => println(s"Unknown input ${input}")
    }
  }

  def processCommandLine(input: String): Unit = {
    input match {
      case CommandLine(cmd, args) => println(s"cmd: ${cmd}, args: ${args}")
      case _ => println(s"Unknown command line: ${input}")
    }
  }

  def processCommandLineWithCheck(input: String): Unit = {
    input match {
      case CommandLine(cmd @ Command(), args) => println(s"-cmd: ${cmd}, args: ${args}")
      case _ => println(s"-Unknown command line: ${input}")
    }
  }

  process("ls")
  process("cd")
  process("dir")

  processCommandLine("ls")
  processCommandLine("cd ..")
  processCommandLine("rm -r")

  processCommandLineWithCheck("ls")
  processCommandLineWithCheck("cd ..")
  processCommandLineWithCheck("rm -r")
}

object Command {
  def unapply(input: String): Boolean = {
    if (input == "ls" || input == "cd") true else false
  }
}

object CommandLine {
  def unapply(input: String): Option[(String, String)] = {
    if (input != null) {
      if (input.trim.contains(" ")) {
        val tokens = input.trim.split(" ")
        Some((tokens(0), tokens(1)))
      } else {
        None
      }
    } else {
      None
    }
  }
}

Add matching with extractors demo

Add matching with extractors demo


package monocle.function

import monocle.MonocleSuite
import monocle.function.Snoc._
import monocle.function.Plated._
import org.scalacheck.Prop._

class PlatedSpec extends MonocleSuite {

  test("children on Stream is consistent with .tail") {
    check { (h: Int, t: Stream[Int]) =>
      val s = h #:: t
      children(s) === List(s.tail)
    }
  }

  test("universe on Stream is consistent with .tails") {
    check { (s: Stream[Int]) =>
      universe(s) === s.tails.toStream
    }
  }

  test("rewrite on Stream is able to change the last node") {
    check { (x: Int, y: Int, z: Int) =>
      rewrite[Stream[Int]] {
        case Stream(n) if n != x =>
          Some(Stream(x))
        case _ => None
      }(Stream(x, y, z)) === Stream(x, y, x)
    }
  }

  test("rewriteOf initOption on Stream is able to change the first node") {
    check { (x: Int, y: Int, z: Int) =>
      rewriteOf(initOption[Stream[Int], Int].asSetter) {
        case Stream(n) if n != z => Some(Stream(z))
        case _ => None
      }(Stream(x, y, z)) === Stream(z, y, z)
    }
  }

  test("transform on Stream can change the last element without a guard") {
    check { (i: Int, x: Int, y: Int, xs: Stream[Int]) =>
      transform[Stream[Int]] {
        case Stream(_) => Stream(i)
        case xs => xs
      }(xs #::: Stream(y, x)) === xs #::: Stream(y, i)
    }
  }

  test("transform initOption on Stream can change the first element without a guard") {
    check { (i: Int, x: Int, y: Int, xs: Stream[Int]) =>
      transformOf(initOption[Stream[Int], Int].asSetter) {
        case Stream(_) => Stream(i)
        case xs => xs
      }(x #:: y #:: xs) === i #:: y #:: xs
    }
  }

}

Add some specs for Plated

Add some specs for Plated


object Solution {

  // perfect digit invariant
  // A PDI is a number equals to the sum of power p of its digits
  def isPDI(n: Int, p: Int): Boolean = {
    var num = n
    var powerSum = 0
    while (num != 0) {
      powerSum += math.pow(num % 10, p).toInt
      num /= 10
    }
    powerSum == n
  }

  def main(args: Array[String]) {
    val p = readLine.toInt
    val limit = (p + 1) * math.pow(9, p).toInt
    val PDIs = for (i <- 2 to limit if isPDI(i, p)) yield i
    println(PDIs.foldLeft(0l) { _ + _ })
  }
}

Add solution to problem 30. The brute force version doesn't feel very right, but it do pass the hackerrank test cases.


/* NSC -- new Scala compiler
 * Copyright 2005-2011 LAMP/EPFL
 * @author Paul Phillips
 */

package scala.tools.partest

import scala.tools.nsc.interpreter.ILoop

/** A trait for testing repl code.  It drops the first line
 *  of output because the real repl prints a version number.
 */
abstract class ReplTest extends App {
  def code: String
  def eval() = (ILoop run code).lines drop 1
  def show() = eval() foreach println

  show()
}

Break 9 tests, fix 9 tests, realize you broke t...

Break 9 tests, fix 9 tests, realize you broke the test you checked in
between +9 and -9. Fix that and generalize the repl tests a little. I
think we're all the way there. No review.


package uk.ac.wellcome.platform.sierra_bib_merger

import scala.concurrent.ExecutionContext

object GlobalExecutionContext {
  // This ensures we have enough threads when running in ECS.  If we use
  // the implicit global execution context, the application is thread-starved
  // and records fall into a hole.  See the discussion on
  // https://github.com/wellcometrust/platform-api/issues/159 for details

  implicit val context =
    ExecutionContext.fromExecutor(new java.util.concurrent.ForkJoinPool(64))
}

Add the missing execution context to the bib_merger


package akka.viz.serialization

import org.scalatest.{Matchers, FlatSpec}

class CustomSerializersTest extends FlatSpec with Matchers {

  "MessageSerialization" should "have default serializers" in {

    MessageSerialization.serialize("Test") shouldBe "\"Test\""
    MessageSerialization.serialize(1) shouldBe "1"
    MessageSerialization.serialize(1L) shouldBe "1"
    MessageSerialization.serialize(1.1) shouldBe "1.1"
    MessageSerialization.serialize(true) shouldBe "true"

  }

}

Verify serialization of few simple types


package repositories

import factories.UUIDFactory
import model.persisted.assessmentcentre.{ Event, EventType, VenueType }
import org.joda.time.{ LocalDate, LocalTime }
import testkit.MongoRepositorySpec

class AssessmentEventsRepositorySpec extends MongoRepositorySpec {

  override val collectionName: String = CollectionNames.ASSESSMENT_EVENTS
  lazy val repository = repositories.assessmentEventsRepository
  val events = List(
    Event(id = UUIDFactory.generateUUID(), eventType = EventType.FSAC, location = "London",
      venue = VenueType.LONDON_FSAC.toString, date = LocalDate.now(), capacity = 67, minViableAttendees = 60,
      attendeeSafetyMargin = 10, startTime = LocalTime.now(), endTime = LocalTime.now().plusHours(3), skillRequirements = Map()),

    Event(id = UUIDFactory.generateUUID(), eventType = EventType.FSAC, location = "London",
      venue = VenueType.LONDON_FSAC.toString, date = LocalDate.now(), capacity = 67, minViableAttendees = 60,
      attendeeSafetyMargin = 10, startTime = LocalTime.now().plusMinutes(30), endTime = LocalTime.now().plusHours(3),
      skillRequirements = Map()),

    Event(id = UUIDFactory.generateUUID(), eventType = EventType.SKYPE_INTERVIEW, location = "Newcastle",
      venue = VenueType.NEWCASTLE_LONGBENTON.toString, date = LocalDate.now(), capacity = 67, minViableAttendees = 60,
      attendeeSafetyMargin = 10, startTime = LocalTime.now(), endTime = LocalTime.now().plusHours(3), skillRequirements = Map())
  )

  "Assessment Events" should {
    "create indexes for the repository" in {
      val indexes = indexesWithFields(repository)
      indexes must contain theSameElementsAs
        Seq(List("eventType", "date", "location", "venue"), List("_id"))
    }

    "save and fetch events" in {
      repository.save(events).futureValue
      val result = repository.fetchEvents(None, None).futureValue
      result mustBe events
    }

    "filter FSAC events" in {
      repository.save(events).futureValue
      val result = repository.fetchEvents(Some("FSAC"), None).futureValue
      result.size mustBe 2
      result.map(_.eventType) mustBe List(EventType.FSAC, EventType.FSAC)
    }

    "filter NEWCASTLE_LONGBENTON events" in {
      repository.save(events).futureValue
      val result = repository.fetchEvents(None, Some("NEWCASTLE_LONGBENTON")).futureValue

      result.size mustBe 1
      result.head.venue mustBe VenueType.NEWCASTLE_LONGBENTON.toString
    }
  }
}

Add integration tests for assessment events repository


package dotty.tools.benchmarks.tuples

import org.openjdk.jmh.annotations._

@State(Scope.Thread)
class TupleOps {
  var tuple1: Tuple = _
  var tuple2: Tuple = _

  @Setup
  def setup(): Unit = {
    tuple1 = ()
    for (i <- 1 until 15)
      tuple1 = s"elem$i" *: tuple1

    tuple2 = ()
    for (i <- 1 until 10)
      tuple2 = s"elem$i" *: tuple2
  }

  def tupleFlatMap(tuple: Tuple, f: [A] => A => Tuple): Tuple = {
    def tailRecFlatMap(t: Tuple, acc: Tuple): Tuple = t match {
      case () => acc
      case x *: rest => tailRecFlatMap(rest, acc ++ f(x))
    }
    tailRecFlatMap(tuple, ())
  }

  def tupleReverse(tuple: Tuple): Tuple = {
    def tailRecReverse(t: Tuple, acc: Tuple): Tuple = t match {
      case () => acc
      case x *: rest => tailRecReverse(rest, x *: acc)
    }
    tailRecReverse(tuple, ())
  }

  @Benchmark
  def reverse(): Tuple = {
    tupleReverse(tuple1)
  }

  @Benchmark
  def flatMap(): Tuple = {
    tupleFlatMap(tuple2, [A] => (x: A) => (x, x))
  }
}

Add global benchmark on tuples

Add global benchmark on tuples


object Solution {

  def hasCommon(s: String, t: String): Boolean = {
    (s.toSet & t.toSet).size >= 1
  }

  def main(args: Array[String]) {
    for (_ <- 1 to readInt) {
      val s = readLine
      val t = readLine
      if (hasCommon(s, t)) println("YES") else println("NO")
    }
  }
}

Add solution to problem Two Strings.

Add solution to problem Two Strings.


package com.sageserpent.americium

import org.scalatest.{FlatSpec, Matchers}

class TrialsSpec extends FlatSpec with Matchers{
  /*
  1.   A constant case yields just one trial.
  2.   A constant case that provokes an exception will result in an exception referencing that case.
  3.   A choice yields all and only the cases given to the choice.
  4.   A choice that includes cases that provoke exceptions will result in an exception that references one of those cases.
  5.   An alternation yields all and only the cases that would be covered by the alternates in isolation.
  6.   An alternation that over trials that in isolation include cases that provoke exceptions will result in an exception that references one of those cases.
  7.   In general, trials yield the same cases.
  8.   In general, trials result in the same exception and referenced case (and recipe).
  9.   In general, a trial that results in an exception provides a recipe that will recreate the same case.
  10.  'Trials' is a functor.
  11.  'Trials' is a monad.
  12.  When a case provokes an exception, the exception yielded refers to a case that is either the same as the original or is simpler.
   */
}

Relocate 'Trials' to be deliverable code.


import play.PlayImport.PlayKeys._

name := "apidoc-example-union-types"

organization := "com.gilt.apidoc.generator"

scalaVersion in ThisBuild := "2.11.4"

lazy val generated = project
  .in(file("generated"))
  .enablePlugins(PlayScala)
  .settings(
    libraryDependencies ++= Seq(
      ws
    )
  )

lazy val api = project
  .in(file("api"))
  .dependsOn(generated)
  .aggregate(generated)
  .enablePlugins(PlayScala)
  .settings(
    routesImport += "com.gilt.apidoc.example.union.types.v0.Bindables._",
    libraryDependencies ++= Seq(
      ws,
      "org.scalatestplus" %% "play" % "1.2.0" % "test"
    )
  )

import play.PlayImport.PlayKeys._

name := "apidoc-example-union-types"

organization := "com.gilt.apidoc.generator"

scalaVersion in ThisBuild := "2.11.5"

lazy val generated = project
  .in(file("generated"))
  .enablePlugins(PlayScala)
  .settings(
    libraryDependencies ++= Seq(
      ws
    )
  )

lazy val api = project
  .in(file("api"))
  .dependsOn(generated)
  .aggregate(generated)
  .enablePlugins(PlayScala)
  .settings(
    routesImport += "com.gilt.apidoc.example.union.types.v0.Bindables._",
    libraryDependencies ++= Seq(
      ws,
      "org.scalatestplus" %% "play" % "1.2.0" % "test"
    )
  )

Update example to scala 2.11.5

Update example to scala 2.11.5


package perftest

import perftest.client.Client

import java.net.URL

object Perftest {
  private def usage = println("Usage: Perftest [client|server] URL")
  private def parse(args: Array[String]) = if (args.length > 1) Some(args(0), new URL(args(1))) else None
  def main(args: Array[String]) = parse(args) match {
    case Some(("server", url)) => error("server not yet supported")
    case Some(("client", url)) => Client.main(Array(url.toString))
    case None                  => usage
  }
}

perftest: Implement a single main for running client and server

A single main for running a client or server instance allows easy
creation of a jar package including a manifest file defining
'Main-class' attribute.

Currently, supports execution of perftest.Client through invocation of
its #main, but this is subject to change in the subsequent changes.

Signed-off-by: Karim Osman <94396faf6cc817be76165477038b3cfa832e89a4@reaktor.fi>
Acked-by: Harri Salokorpi <eefb23b8deb8c30dca252cd0ae751b67337dc69f@reaktor.fi>


package quasar.project

object Versions {
  val algebraVersion      = "1.0.0"
  val argonautVersion     = "6.2.2"
  val catsEffectVersion   = "1.1.0"
  val disciplineVersion   = "0.7.2"
  val jawnVersion         = "0.14.1"
  val jawnfs2Version      = "0.14.1"
  val matryoshkaVersion   = "0.18.3"
  val monocleVersion      = "1.4.0"
  val pathyVersion        = "0.2.11"
  val refinedVersion      = "0.8.3"
  val scodecBitsVersion   = "1.1.2"
  val scalacheckVersion   = "1.14.0"
  val scalazVersion       = "7.2.26"
  val scalazStreamVersion = "0.8.6a"
  val scoptVersion        = "3.5.0"
  val shapelessVersion    = "2.3.3"
  val simulacrumVersion   = "0.10.0"
  val specsVersion        = "4.3.3"
  val spireVersion        = "0.16.0"
  val akkaVersion         = "2.5.1"
  val fs2Version          = "1.0.2"
  val slf4sVersion        = "1.7.25"
}

package quasar.project

object Versions {
  val algebraVersion      = "1.0.0"
  val argonautVersion     = "6.2.2"
  val catsEffectVersion   = "1.1.0"
  val disciplineVersion   = "0.7.2"
  val jawnVersion         = "0.14.1"
  val jawnfs2Version      = "0.14.1"
  val matryoshkaVersion   = "0.18.3"
  val monocleVersion      = "1.4.0"
  val pathyVersion        = "0.2.11"
  val refinedVersion      = "0.8.3"
  val scodecBitsVersion   = "1.1.2"
  val scalacheckVersion   = "1.14.0"
  val scalazVersion       = "7.2.27"
  val scalazStreamVersion = "0.8.6a"
  val scoptVersion        = "3.5.0"
  val shapelessVersion    = "2.3.3"
  val simulacrumVersion   = "0.10.0"
  val specsVersion        = "4.3.3"
  val spireVersion        = "0.16.0"
  val akkaVersion         = "2.5.1"
  val fs2Version          = "1.0.2"
  val slf4sVersion        = "1.7.25"
}

Update scalaz-concurrent, scalaz-core to 7.2.27


package org.jetbrains.plugins.scala.lang.typeInference

import org.jetbrains.plugins.scala.{PerfCycleTests, ScalaVersion, Scala_2_11, Scala_2_13}
import org.jetbrains.plugins.scala.base.ScalaLightCodeInsightFixtureTestAdapter
import org.junit.experimental.categories.Category

@Category(Array(classOf[PerfCycleTests]))
class RepeatedParametersTest extends ScalaLightCodeInsightFixtureTestAdapter {
  override protected def supportedIn(version: ScalaVersion): Boolean = version == Scala_2_13

  def testSCL16016(): Unit = checkTextHasNoErrors(
    """
      |def test(ii: Int*): Unit = {
      |  val x: Seq[Int] = ii
      |}
      |""".stripMargin
  )
}

@Category(Array(classOf[PerfCycleTests]))
class UnapplySeqRepeatedParametersTest extends ScalaLightCodeInsightFixtureTestAdapter {
  override protected def supportedIn(version: ScalaVersion): Boolean = version >= Scala_2_11

  def testSCL16110(): Unit = checkTextHasNoErrors(
    """
      |object BugDemo {
      |  case class Cell(value: Int) {
      |    def text: String = value.toString
      |  }
      |  val cells: List[Cell] = List(Cell(1))
      |  val List(cell) = cells // Error: IDEA inferred type for 'cell' as Any instead of 'Cell'
      |  cell.text // Error: 'text' is highlighted as an error (because the incorrect inference)
      |}
      |""".stripMargin
  )

  def testSCL15627(): Unit = checkTextHasNoErrors(
    """
      |object Main {
      |  val aSeq = Seq(1, 2, 3)
      |  val sum = aSeq match {
      |    case Seq(a, b, c) => a + b + c // Cannot resolve symbol +
      |  }
      |}
      |""".stripMargin
  )
}

Add basic tests for option-less unapplySeq and repeated parameter types

(#SCL-16110, #SCL-16016)


package notebok.util

import org.scalatest._
import notebook.util.Reflector

class ReflectorTests extends FunSpec with Matchers with BeforeAndAfterAll {

  object SomeObject {
    val a = "aValue"
    val b = "bValue"
  }

  case class SomeCaseClass(a: String)

  class SomeClass {
    val a = "aValue"
  }

  describe("Reflector.toObjArray (returns fieldName -> value pairs)") {
    it("works with objects") {
      Reflector.toObjArray(SomeObject).toMap shouldBe Map("a" -> "aValue", "b" -> "bValue")
    }

    it("works with case classes") {
      Reflector.toObjArray(SomeCaseClass(a = "aValue")).toMap shouldBe Map("a" -> "aValue")
    }

    it("works with regular classes") {
      Reflector.toObjArray(new SomeClass).toMap shouldBe Map("a" -> "aValue")
    }
  }

  describe("Reflector.toFieldNameArray") {
    it("returns fieldNames") {
      Reflector.toFieldNameArray(SomeObject) shouldBe List("a", "b")
    }
  }

  describe("Reflector.toFieldValueArray") {
    it("returns field values") {
      Reflector.toFieldValueArray(SomeObject) shouldBe List("aValue", "bValue")
    }
  }

}

Add tests for object Reflector

Add tests for object Reflector


package uk.ac.wellcome.models.work.generators

import uk.ac.wellcome.models.generators.RandomStrings
import uk.ac.wellcome.models.work.internal._

trait SubjectGenerators extends RandomStrings {
  def createSubjectWith(
    concepts: List[Displayable[AbstractRootConcept]] = createConcepts
  ): Displayable[Subject[Displayable[AbstractRootConcept]]] =
    Unidentifiable(
      Subject(
        label = randomAlphanumeric(10),
        concepts = concepts
      )
    )

  def createSubject: Displayable[Subject[Displayable[AbstractRootConcept]]] =
    createSubjectWith()

  private def createConcepts: List[Displayable[AbstractRootConcept]] =
    (1 to 3)
      .map { _ => Unidentifiable(Concept(randomAlphanumeric(15))) }
      .asInstanceOf[List[Displayable[AbstractRootConcept]]]
}

Add generators for identified Subjects

Add generators for identified Subjects


object Typedef {
  // Simple type alias
  type MyInt = Int

  // Also type lambdas
  type MyType[x] = x

  // Type aliases are correctly unaliased.
  def add(a: MyInt, b: MyInt): MyInt = {
    a + b
  }

  // Type lambdas are correctly evaluated and unaliased.
  def succ(a: MyType[Int]): Int = {
    require( a < 2147483647 )
    val res = a + 1
    res
  } ensuring( res => res > a)
}

Add benchmark containing type aliases.

Add benchmark containing type aliases.


package org.scalacheck.examples

import org.scalacheck.{Prop, Properties}

object Examples extends Properties("Examples") {

  property("list tail") = Prop.forAll { (n: Int, l: List[Int]) =>
    (n :: l).tail == l
  }

  property("list head") = Prop.forAll { l: List[Int] =>
    if (l.isEmpty) {
      Prop.throws(classOf[java.util.NoSuchElementException]) { l.head }
    } else {
      l.head == l(0)
    }
  }

  case class Person (
    firstName: String,
    lastName: String,
    age: Int
  ) {
    def isTeenager = age >= 13 && age <= 19
  }

  val genPerson = {
    import org.scalacheck.Gen.{choose, value}
    for {
      firstName <- "Alan" | "Ada" | "Alonzo"
      lastName <- "Lovelace" | "Turing" | "Church"
      age <- choose(1,100)
    } yield Person(firstName, lastName, age)
  }

  import org.scalacheck.Arbitrary

  implicit val arbPerson = Arbitrary(genPerson)

  property("ex1") = Prop.forAll { p: Person =>
    p.isTeenager == (p.age >= 13 && p.age <= 19)
  }

}

Add more examples to the tests

Add more examples to the tests


package laika.sbt

import sbt._
import Keys._
import laika.api.Parse
import laika.template.ParseTemplate
import laika.tree.Documents._
import laika.tree.Elements._
import laika.directive.Directives._
import laika.parse.rst.Directives.Directive
import laika.parse.rst.TextRoles.TextRole

object LaikaSbtPlugin {

  object LaikaKeys {

    val site = TaskKey[File]("site", "Generates a static website")

    val docTypeMatcher = SettingKey[Path => DocumentType]("docTypeMatcher", "Matches a path to a Laika document type")

    val encoding = SettingKey[String]("encoding", "The character encoding")

    val markupParser = SettingKey[Parse]("markupParser", "The parser for text markup files")

    val templateParser = SettingKey[ParseTemplate]("templateParser", "The parser for template files")

    val parse = TaskKey[DocumentTree]("parse", "Parses all text markup and template files")

    val rewriteRules = SettingKey[Seq[DocumentContext => PartialFunction[Element,Option[Element]]]]("rewriteRules", "Custom rewrite rules to add to the standard rules")

    val rewrite = TaskKey[DocumentTree]("rewrite", "Applies all rewrite rules to the document tree")

    val renderers = SettingKey[Seq[_ => PartialFunction[Element,Unit]]]("renderers", "Custom renderers overriding the defaults per node type")

    val parallel = SettingKey[Boolean]("parallel", "Indicates whether parsers and renderers should run in parallel")

    val spanDirectives = SettingKey[Seq[Spans.Directive]]("spanDirectives", "Directives for inline markup")

    val blockDirectives = SettingKey[Seq[Blocks.Directive]]("blockDirectives", "Directives for block-level markup")

    val templateDirectives = SettingKey[Seq[Templates.Directive]]("templateDirectives", "Directives for templates")

    val rstSpanDirectives = SettingKey[Seq[Directive[Span]]]("rstSpanDirectives", "Inline directives for reStructuredText")

    val rstBlockDirectives = SettingKey[Seq[Directive[Block]]]("rstBlockDirectives", "Block directives for reStructuredText")

    val rstTextRoles = SettingKey[Seq[TextRole]]("rstTextRoles", "Custom text roles for reStructuredText")

    val includeAPI = SettingKey[Boolean]("includeAPI", "Indicates whether API documentation should be copied to the site")

    val copyAPI = TaskKey[File]("copyAPI", "Copies the API documentation to the site")

  }

}

Add new plugin object and define all keys


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

package me.footlights.api.ajax {

class RichWebRequest(req:WebRequest) {
	def map[T](f:WebRequest => T) = f(req)
}

object RichWebRequest {
	implicit def webReqToRichWebReq(r:WebRequest) = new RichWebRequest(r)
}

}

Add RichWebRequest for the Scala lovers.


#!/bin/sh
exec scala "$0" "$@"
!#

/*
 * Shamelessly copied from https://github.com/akka/akka/blob/master/scripts/authors.scala
 * Usage:
 *    authors.scala tag1 tag2
 *
 * or if on non unixy os:
 *    scala authors.scala tag1 tag2
 *
 * requires scala 2.13.x+ and command line git on path
 */

import scala.sys.process._

require(args.length == 2, "usage: authors prevTag currTag")

val gitCmd = "git log --no-merges --shortstat -z --minimal -w -C " + args(0) + ".." + args(1)

case class Stats(name: String, email: String, commits: Int = 0, inserts: Int = 0, deletes: Int = 0, filesChanged: Int = 0)

val AuthorExp = """Author: (.*) <([^>]+)>""".r
val FilesExp = """(\d+)\sfile[s]? changed""".r
val InsertionsExp = """(\d+)\sinsertion[s]?\(\+\)""".r
val DeletionsExp = """(\d+)\sdeletion[s]?\(-\)""".r

val entries = gitCmd.lazyLines_!.foldLeft("")(_ + "\n" + _).split('\u0000')

val map = entries.foldLeft(Map.empty[String, Stats]) { (map, entry) =>
  val lines = entry.trim.split('\n')
  val authorLine = lines(1)
  val summary = lines.last

  val statsEntry = authorLine match {
    case AuthorExp(name, email) =>
      map.get(name.toLowerCase).orElse {
        // look for same email, but different name
        map.values.find(_.email.equalsIgnoreCase(email)).orElse {
          Some(Stats(name, email))
        }
      }
    case _ =>
      println(s"Unparseable author line: \n$authorLine\n in entry $entry")
      None
  }

  val updatedEntry =
    statsEntry.map(entry => summary.trim.split(',').map(_.trim).foldLeft(entry.copy(commits = entry.commits + 1)) {
      case (entry, FilesExp(f)) => entry.copy(filesChanged = entry.filesChanged + f.toInt)
      case (entry, InsertionsExp(a)) => entry.copy(inserts = entry.inserts + a.toInt)
      case (entry, DeletionsExp(d)) => entry.copy(deletes = entry.deletes + d.toInt)
      case (entry, uff) =>
        println(s"Couldn't parse summary section for $entry '$uff'")
        entry
    })

  updatedEntry.fold(
    map
  )(entry => map + (entry.name.toLowerCase -> entry))
}

val sorted = map.values.toSeq.sortBy(s => (s.commits, s.inserts + s.deletes)).reverse

println("commits  added  removed")
sorted.foreach { entry =>
  println("%7d%7d%9d %s".format(entry.commits, entry.inserts, entry.deletes, entry.name))
}

Add committer list generation script

Add committer list generation script


object Solution {

  def canProtectAll(r: Int, k: Int): Boolean = {
    val sr = math.sqrt(r).toInt
    val squares = (1 to sr).map(x => x * x).toSet
    val count = squares.filter(x => squares(r - x)).size
    val totalCount = if (sr * sr == r) 4 + 4 * count else 4 * count
    totalCount <= k
  }

  def main(args: Array[String]) {
    val t = readInt
    for (_ <- 1 to t) {
      val Array(r, k) = readLine.split(" ").map(_.toInt)
      if (canProtectAll(r, k)) println("possible") else println("impossible")
    }
  }
}

Add solution to problem Circle City.

Add solution to problem Circle City.


package org.elasticsearch.spark.cfg

import org.elasticsearch.spark.serialization.ReflectionUtils._
import org.junit.Test
import org.junit.Assert._
import org.hamcrest.Matchers._
import org.apache.spark.SparkConf
import org.elasticsearch.hadoop.cfg.PropertiesSettings

class SparkConfigTest {

  @Test
  def testProperties() {
    val cfg = new SparkConf().set("type", "onegative")
    val settings = new SparkSettingsManager().load(cfg)
    val props = new PropertiesSettings().load(settings.save())
    assertEquals("onegative", props.getProperty("type"))
  }

  @Test
  def testSparkProperties() {
    val cfg = new SparkConf().set("spark.type", "onegative")
    val settings = new SparkSettingsManager().load(cfg)
    val props = new PropertiesSettings().load(settings.save())
    assertEquals("onegative", props.getProperty("type"))
  }

  @Test
  def testSparkPropertiesOverride() {
    val cfg = new SparkConf().set("spark.type", "fail").set("type", "win")
    val settings = new SparkSettingsManager().load(cfg)
    val props = new PropertiesSettings().load(settings.save())
    assertEquals("win", props.getProperty("type"))
  }
}

Add test for properties handling

Add test for properties handling

relates #591


package mdmoss.doobiegen.db

import doobie.imports._
import mdmoss.doobiegen.db.schema.gen.Test
import org.specs2.mutable.Specification

import scalaz.concurrent.Task

object UsageSpec extends Specification {

  val transactor = DriverManagerTransactor[Task]("org.postgresql.Driver", "jdbc:postgresql:gen", "test", "test")

  val work = for {
    test1 <- Test.insert(Some(1)).run
    test2 <- Test.create(Some(2))
  } yield ()

  "Doobiegen methods" >> {

    "Must run without errors when called correctly" >> {
      transactor.trans(work).run must_== (())
    }

  }

}

Add start of super simple test

Add start of super simple test


package com.wavesplatform.lang

import com.wavesplatform.lang.v1.evaluator.ctx.impl.waves.Types
import org.scalatest.{FreeSpec, Matchers}

class TypesTest extends FreeSpec with Matchers {

  "lib version 3" - {
    val types = Types.buildWavesTypes(true, StdLibVersion.V3)

    "there should be only one InvokeScriptTransaction" in {
      types.count(c => c.name == "InvokeScriptTransaction") shouldEqual 1
    }
  }

  "lib version 2" - {
    val types = Types.buildWavesTypes(true, StdLibVersion.V2)

    "there should be no InvokeScriptTransaction" in {
      types.count(c => c.name == "InvokeScriptTransaction") shouldEqual 0
    }
  }
}

SC-96: Test for InvokeScriptTransaction CaseType inclusion with lib version


package gitbucket.core.servlet

import javax.servlet.http.{HttpServlet, HttpServletRequest, HttpServletResponse}

import gitbucket.core.plugin.PluginRegistry
import gitbucket.core.util.FileUtil
import org.apache.commons.io.IOUtils

/**
 * Supply assets which are provided by plugins.
 */
class PluginAssetsServlet extends HttpServlet {

  override def doGet(req: HttpServletRequest, resp: HttpServletResponse): Unit = {
    val assetsMappings = PluginRegistry().getAssetsMappings
    val path = req.getRequestURI.substring(req.getContextPath.length)

    assetsMappings
      .find    { case (prefix, _, _) => path.startsWith("/plugin-assets" + prefix) }
      .flatMap { case (prefix, resourcePath, classLoader) =>
        val resourceName = path.substring(("/plugin-assets" + prefix).length)
        Option(classLoader.getResourceAsStream(resourcePath + resourceName))
      }
      .map { in =>
        try {
          val bytes = IOUtils.toByteArray(in)
          resp.setContentLength(bytes.length)
          resp.setContentType(FileUtil.getContentType(path, bytes))
          resp.getOutputStream.write(bytes)
        } finally {
          in.close()
        }
      }
      .getOrElse {
        resp.setStatus(404)
      }
  }

}

package gitbucket.core.servlet

import javax.servlet.http.{HttpServlet, HttpServletRequest, HttpServletResponse}

import gitbucket.core.plugin.PluginRegistry
import gitbucket.core.util.FileUtil
import org.apache.commons.io.IOUtils

/**
 * Supply assets which are provided by plugins.
 */
class PluginAssetsServlet extends HttpServlet {

  override def doGet(req: HttpServletRequest, resp: HttpServletResponse): Unit = {
    val assetsMappings = PluginRegistry().getAssetsMappings
    val path = req.getRequestURI.substring(req.getContextPath.length)

    assetsMappings
      .find    { case (prefix, _, _) => path.startsWith("/plugin-assets" + prefix) }
      .flatMap { case (prefix, resourcePath, classLoader) =>
        val resourceName = path.substring(("/plugin-assets" + prefix).length)
        Option(classLoader.getResourceAsStream(resourcePath.replaceFirst("^/", "") + resourceName))
      }
      .map { in =>
        try {
          val bytes = IOUtils.toByteArray(in)
          resp.setContentLength(bytes.length)
          resp.setContentType(FileUtil.getContentType(path, bytes))
          resp.getOutputStream.write(bytes)
        } finally {
          in.close()
        }
      }
      .getOrElse {
        resp.setStatus(404)
      }
  }

}

Remove head / from resource path

Remove head / from resource path


package com.busymachines.commons.util

import scala.math._

object Levenshtein {

  private def minimum(i1: Int, i2: Int, i3: Int) =
    min(min(i1, i2), i3)

  def distance(s1: String, s2: String) = {
    val dist = Array.tabulate(s2.length + 1, s1.length + 1) { (j, i) => if (j == 0) i else if (i == 0) j else 0}

    for (j <- 1 to s2.length; i <- 1 to s1.length)
      dist(j)(i) = if (s2(j - 1) == s1(i - 1)) dist(j - 1)(i - 1)
      else minimum(dist(j - 1)(i) + 1, dist(j)(i - 1) + 1, dist(j - 1)(i - 1) + 1)

    dist(s2.length)(s1.length)
  }
}

Add levenshtein algoritmh for fuzzy address matching


package org.scalacheck

import java.util.HashMap
import scala.collection.JavaConversions._
import scala.collection.immutable.IntMap
import org.scalacheck.Prop.{forAll, AnyOperators}

object IntMapSpec extends org.scalacheck.Properties("IntMap") {
  /** Compare a HashMap and an IntMap for equality */
  private def eqMaps(hm: HashMap[Int,Any], im: IntMap[Any]) = {
    im.keys.forall(hm.containsKey) &&
    hm.keySet.containsAll(im.keys) &&
    im.keys.forall(k => im(k) == hm(k))
  }

  /** Create an IntMap and a HashMap with the same contents */
  private def createMaps(l: List[Int]) = {
    val mappings = for(n <- l) yield (n, new Object)
    val im = IntMap(mappings: _*)
    val hm = new HashMap[Int, Any]
    for((n,x) <- mappings) hm.put(n,x)
    (hm, im)
  }

  property("size") = forAll { l: List[Int] =>
    val (refMap, intMap) = createMaps(l)
    intMap.size ?= refMap.size
  }
  property("isEmpty") = forAll { l: List[Int] =>
    val (refMap, intMap) = createMaps(l)
    intMap.isEmpty ?= refMap.isEmpty
  }
  property("add") = forAll { (l: List[Int], k: Int, v: String) =>
    val (refMap, intMap) = createMaps(l)
    refMap.put(k, v)
    eqMaps(refMap, intMap + (k -> v))
  }
  property("remove") = forAll { (l: List[Int], k: Int) =>
    val (refMap, intMap) = createMaps(l)
    refMap.remove(k)
    eqMaps(refMap, intMap - k)
  }
}

Add some example properties to the tests


object Test {

  implicit def F2ToT2(f: Function2[Int, Int, Int]): Tuple2[Int, Int] => Int = {
    ???
    x => f(x._1, x._2)
  }

  def main(args: Array[String]): Unit = {
    val f: Tuple2[Int, Int] => Int = (x: Int, y: Int) => x + y
    f((3, 4))
  }

}

Add example of implicit conversion that would be overlooked


// scalac: -Werror
object ExhaustivityWarnBugReportMinimal {
  //sealed is needed for the warning
  sealed trait FoundNode[T]/*presence of parameters is irrelevant*/
  // This also causes a warning:
  // sealed abstract class FoundNode[T]/*presence of parameters is irrelevant*/
  case class FoundFilter[T](/*presence of parameters is irrelevant*/) extends FoundNode[T]
  case class FoundTypeCase[T](/*presence of parameters is irrelevant*/) extends FoundNode[T]
  val f: Some[_] = ???
  f match {
    case x: Some[t] => //no warning
  }
  //With these variants, no warnings:
  //val v: (Some[Int], FoundNode[_]) = (???, ???)
  //val v: (Some[AnyRef], FoundNode[_]) = (???, ???)
  //val v: (Some[String], FoundNode[_]) = (???, ???)

  val v: (Some[_], FoundNode[_]) = (???, ???)
  //Warning here:
  v match { // was: "It would fail on the following inputs: (_, FoundFilter()), (_, FoundTypeCase())"
    case (x: Some[t], _: FoundNode[_]) =>
  }
  v match { // was: "It would fail on the following input: (_, _)"
    case (x: Some[t], _) =>
  }

  v match { // was: "It would fail on the following input: (_, _)"
    case (x: Some[_], _) =>
  }
  case class Foo[T]()

  val vp: (Foo[_], FoundNode[_]) = (???, ???)
  vp match { // was: "It would fail on the following input: (_, _)"
    case (x: Foo[_], _) =>
  }

  //No warning here:
  v match {
    case (Some(y), _) =>
  }

  v match {
    case (x, _) =>
  }

  val v2: (Some[_], Int) = (???, ???)
  v2 match {
    case (x: Some[t], _) =>
  }

  val v3: (Option[_], FoundNode[_]) = (???, ???)
  v match {
    case (x: Option[_], _) =>
  }
}

Add some tuple + inexhaustive retroactive tests


object Solution {

  def sievePrimeGenerator(n: Int): (Array[Int], Array[Boolean]) = {
    val nums = Array.fill(n + 1)(true)
    nums(0) = false
    nums(1) = false
    val primes = for (i <- (2 to n).toIterator if nums(i)) yield {
      var j = 2
      while (i * j <= n) {
        nums(i * j) = false
        j += 1
      }
      i
    }
    (primes.toArray, nums)
  }

  def isPrime(x: Long,
              primes: Array[Int],
              primeTable: Array[Boolean]): Boolean = {
    val size = primeTable.size - 1
    val sizeSquare = 1L * size * size
    x match {
      case p if p < 0 => false
      case p if p <= size => primeTable(p.toInt)
      case p if p <= sizeSquare =>
        for (prime <- primes) {
          if (p % prime == 0) return false
        }
        true
      case p =>
        for (prime <- primes) {
          if (p % prime == 0) return false
        }
        var start = (sizeSquare - 5) / 6 * 6 + 5
        while (start * start <= p) {
          if (p % start == 0 || p % (start + 2) == 0) return false
          start += 6
        }
        true
    }
  }

  def main(args: Array[String]) {
    val n = readLine.toInt
    val ratio = 1.0 * n / 100
    var i = 3L
    var primeCount = 3L
    var totalCount = 5L
    val (primes, primeTable) = sievePrimeGenerator(1e7.toInt)
    while (1.0 * primeCount / totalCount >= ratio) {
      val iSquare = i * i
      i += 2
      var newPrimeCount = 0
      var j = 1
      while (j <= 3) {
        if (isPrime(iSquare + (i - 1) * j, primes, primeTable))
          newPrimeCount += 1
        j += 1
      }
      primeCount += newPrimeCount
      totalCount += 4
    }
    println(i)
  }
}

Add partial solution to problem 58. It timed out for the last four tests on hackerrank. This is a sync commit.


package edu.umass.ciir.strepsi

/**
 * User: dietz
 * Date: 2/24/14
 * Time: 3:50 PM
 */
class ScoredPassage(val documentName: String, val begin:Int, val end:Int, val rank: Int, val score: Double) {
  var _source:String=""
  def source = _source
  def source_=(s:String) {
    _source = s
  }

  def withNewRank(newrank:Int):ScoredPassage = {
    val x = new ScoredPassage(documentName, begin, end, newrank, score)
    x.source = _source
    x
  }

  override def toString: String = {
    documentName + " " + rank + " " + formatScore(score) + " galago"
  }

  def toString(qid: String): String = {
    qid + " Q0 " + documentName + " " + rank + " " + formatScore(score) + " galago"
  }

  def toTRECformat(qid: String): String = {
    qid + " Q0 " + documentName + " " + rank + " " + formatScore(score) + " galago"
  }

  protected def formatScore(score: Double): String = {
    val difference: Double = Math.abs(score - score.asInstanceOf[Int])
    if (difference < 0.00001) {
      Integer.toString(score.asInstanceOf[Int])
    } else {
      "%10.8f".format(score)
    }
  }
}

Rework strepsent and eqfe to work with GalagoSearcherWithType


import scala.util.Random

/**
 *
 * @author ponkotuy
 * Date: 15/02/14.
 */
object ListVector {
  def main(args: Array[String]) {
    val size = 1000
    val count = 10000
    val random = new Random(0)
    val list = (1 to size).map(_ => random.nextInt()).toList
    val vector = list.toVector
    val array = list.toArray
    val times = Map(
      "Vector Sort" -> timer { (1 to count).foreach { _ => vector.sorted.apply(10) } },
      "Array Sort" -> timer { (1 to count).foreach { _ => array.sorted.apply(10) } },
      "List Sort" -> timer { (1 to count).foreach { _ => list.sorted.apply(10) } }
    )
    println(times)
  }

  def timer(f: => Unit): Long = {
    val start = System.currentTimeMillis()
    f
    System.currentTimeMillis() - start
  }
}

Add profiling to Vector VS List

Add profiling to Vector VS List


// When uncommented this line will be identified as an unused import by -Ywarn-unused-import
// import scala.MatchError

object BadThings {
  // When uncommented, this line will be identified as inferring any by the -Xlint scalac switches
  // val xLintExample = Seq(1 -> 2, 2 -> "3")

  // When uncommented this line will be identified as a compiler error because of -deprecation and -Xfatal-warnings
  // val deprecationExample = Seq(1, 2, 3).toSet()

  // When uncommented, this line will be identifed as an unintentional string concatenation by WartRemover
  // val wartRemoverExample = Seq(1, 2) :+ 3

  // When uncommented this line will be identified as a bad idea by Foursquare Linter
  // val fourSquareLinterExample = Array(1,2,3).toString

  // When uncommented and an 'n' added to the method name Scalastyle will identify this as writing to stdout
  // printl("Typically we don't want to ship writing to standard out in production code.")
}

Add a sample file to demonstrate static analysis.


// vim: ts=2 sw=2 et
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.debiki.v0

import org.specs._
import org.specs.runner.{ConsoleRunner, JUnit4}
import java.{util => ju}

//class StatsCalcTest extends JUnit4(StatsCalcSpec)
//object StatsCalcTestRunner extends ConsoleRunner(StatsCalcSpec)

class StatsCalcTest extends SpecificationWithJUnit {
/*
Cannot debug this:
class StatsCalcTest extends SpecificationWithJUnit {
NetBeans says:
  Testsuite: com.debiki.v0.StatsCalcTest
  Tests run: 1, Failures: 0, Errors: 1, Time elapsed: 0 sec

  Null Test:         Caused an ERROR
  null
  java.lang.ExceptionInInitializerError
          at java.lang.Class.forName0(Native Method)
          at java.lang.Class.forName(Class.java:169)
  Caused by: java.lang.RuntimeException: Uncompilable source code
   - interface expected here
          at com.debiki.v0.StatsCalcTest.<clinit>(StatsCalcTest.java:2)
*/

//object StatsCalcSpec extends Specification {

  val post = Post("a", "root", new ju.Date, None, "test")
  val debate = Debate("test", post :: Nil, Nil)
  val vote_interesting = Vote(post.id, "?", new ju.Date, List("interesting"))

  "For an unrated post, StatsCalc" should {
    "find no statistics" in {
      val calcer = new StatsCalc(debate)
      val rating = calcer.scoreFor(post.id)
      rating.voteCount must_== 0
      rating.maxLabelSum must_== 0
      rating.labelStats.size must_== 0
    }
  }

  "For a post with one rating, StatsCalc" should {
    "find one rating" in {
      val debate2 = debate + vote_interesting
      val calcer = new StatsCalc(debate2)
      val rating = calcer.scoreFor(post.id)
      rating.voteCount must_== 1
      rating.maxLabelSum must_== 1.0f
      rating.labelStats.size must_== 1
      val labelStats = rating.labelStats("interesting")
      labelStats.sum must_== 1.0f
      labelStats.fraction must_== 1.0f
      // Don't know exactly what fractionLowerBound should be,
      // but rather low, since the algorithm adds 4 fake votes, 2 of which
      // excludes the "interesting" label.
      labelStats.fractionLowerBound must be_>(0.0f)
      labelStats.fractionLowerBound must be_<(0.5f)
    }
  }

}

Add forgotten statistics test file.

Add forgotten statistics test file.


import scala.io.Source
/**
  * @author loustler
  * @since 01/14/2017 18:21
  */

def widthofLength(s: String)  = s.length.toString.length

// 예제와는 다름, travis에서 compile error를 방지 하기 위함
def wordCountInFile(fileName: String): Unit = {
  if (args.length > 0) {
    val lines = Source.fromFile(fileName).getLines().toList

    /**
      * Return longest line in lines.
      *
      * reduceLeft to LinearSeqOptimzed#reduceLeft(function)
      *
      * Reduce from left to right do function.
      *
      */
    val longestLine = lines.reduceLeft(
      (a, b) => if (a.length > b.length) a else b
    )

    val maxWidth  = widthofLength(longestLine)

    for ( line <- lines) {
      val numSpaces = maxWidth - widthofLength(line)
      val padding = " " * numSpaces
      println(padding + line.length + " | " + line)
    }
  }
  else
    Console.err.println("Please enter filename")
}

Add scala script that count word in file


package test

class Sett[A] {

  def incl(elem: A): Sett[A] = ???

  inline final def + (elem: A): Sett[A] = incl(elem)
}

object Sett {
  def apply[A](elems: A*): Sett[A] = ???
}

class Test {
  Sett(1) + 1
}

Add original test that caused the whole rewrite


package com.softwaremill.codebrag.domain

import org.joda.time.DateTime
import org.bson.types.ObjectId

abstract class CommentBase(val id: ObjectId, val commitId: ObjectId, val authorId: ObjectId, val message: String, val postingTime: DateTime)

case class CommitComment(override val id: ObjectId, override val commitId: ObjectId, override val authorId: ObjectId, override val message: String, override val postingTime: DateTime)
  extends CommentBase(id, commitId, authorId, message, postingTime)

case class InlineComment(commitComment: CommitComment, fileName: String, lineNumber: Int)
  extends CommentBase(commitComment.id, commitComment.commitId, commitComment.authorId, commitComment.message, commitComment.postingTime) {

  require((fileName != null && lineNumber != null),  "Inline comments must have non-empty fileName and lineNumber fields")
}

package com.softwaremill.codebrag.domain

import org.joda.time.DateTime
import org.bson.types.ObjectId

abstract class CommentBase(val id: ObjectId, val commitId: ObjectId, val authorId: ObjectId, val message: String, val postingTime: DateTime)

case class CommitComment(override val id: ObjectId, override val commitId: ObjectId, override val authorId: ObjectId, override val message: String, override val postingTime: DateTime)
  extends CommentBase(id, commitId, authorId, message, postingTime)

case class InlineComment(commitComment: CommitComment, fileName: String, lineNumber: Int)
  extends CommentBase(commitComment.id, commitComment.commitId, commitComment.authorId, commitComment.message, commitComment.postingTime) {

  require((fileName != null && lineNumber > 0),  "Inline comments must have non-empty fileName and >0 lineNumber fields")
}

Fix guard condition in inline comment

Fix guard condition in inline comment


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

import org.scalatest.FlatSpec
import org.scalatest.Matchers
import org.schedoscope.DriverTests
import org.schedoscope.dsl.Field.v
import org.schedoscope.dsl.Parameter.p
import test.eci.datahub.Click
import test.eci.datahub.ClickOfEC0101
import org.schedoscope.dsl.Structure
import org.schedoscope.dsl.FieldLike
  case class Contingency() extends Structure {
	  val o11 = fieldOf[Long]
	  val o12 = fieldOf[Long]
      val o21 = fieldOf[Long]
      val o22 = fieldOf[Long]
  }
  case class Nested() extends Structure {
	  val value = fieldOf[Long]
	  val nested = fieldOf[Contingency]
  }
class ViewSerdeTest extends FlatSpec with Matchers {

  "view Serde" should "deserialize structures" taggedAs (DriverTests) in {
	  val c = new Contingency()
	  val json = """{"value":1, "nested":{"o11":1,"o12":0,"o21":0,"o22":11}}"""
	  val res=ViewSerDe.deserializeField(manifest[Nested], json)
      assert(res==Map("value" -> 1, "nested" -> Map("o11"->1,"o12"->0,"o21"->0,"o22"->11)))

  }
  "view Serde" should "deserialize Lists" taggedAs (DriverTests) in {
	  assert(ViewSerDe.deserializeField(manifest[List[Long]], "[]")==List())
	  assert(ViewSerDe.deserializeField(manifest[List[Long]], "[1,2,3]")==List(1,2,3))

  }
}

Add some simple Tests for SerDe

Add some simple Tests for SerDe


package uk.ac.wellcome.messaging.message

import com.google.inject.Provides
import com.twitter.inject.TwitterModule
import javax.inject.Singleton

import uk.ac.wellcome.messaging.sns.SNSConfig
import uk.ac.wellcome.models.aws.S3Config

object MessageConfigModule extends TwitterModule {
  private val topicArn = flag[String](
    "aws.message.sns.topic.arn", "", "ARN of the SNS topic used for messaging")

  private val bucketName =
    flag[String](
      "aws.message.s3.bucketName", "",
      "Name of the S3 bucket holding messaging pointers")
  private val endpoint = flag[String](
    "aws.message.s3.endpoint", "",
    "Endpoint of S3. The region will be used if the endpoint is not provided")
  private val accessKey =
    flag[String]("aws.message.s3.accessKey", "", "AccessKey to access S3")
  private val secretKey =
    flag[String]("aws.smessage.3.secretKey", "", "SecretKey to access S3")

  @Singleton
  @Provides
  def providesMessageConfig(): MessageConfig = {
    val snsConfig = SNSConfig(topicArn = topicArn())
    val s3Config = S3Config(
      bucketName = bucketName(),
      endpoint = endpoint(),
      accessKey = accessKey(),
      secretKey = secretKey()
    )
    MessageConfig(snsConfig = snsConfig, s3Config = s3Config)
  }
}

Create a module for injecting MessageConfig


/* https://www.hackerrank.com/challenges/flatland-space-stations */
package com.negrisoli.algorithms.implementation

object FlatlandSpaceStations {

  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)
    val List(n, m) = ((0 to 1) map (i => sc.nextInt)).toList
    val stations = ((0 to m - 1) map (i => sc.nextInt)).toList

    print(calculateDistance(n, stations))
  }

  def calculateDistance(n: Int, unsortedStations: List[Int]): Int = {
    val stations = unsortedStations.sorted

    val first = stations(0)
    val middle = stations.sliding(2).map { x => x match {
      case x :: y :: xs => (y - x) / 2
      case _ => 0
    }}.max
    val last = (n - 1) - stations.last

    List(first, middle, last).max
  }

}

Add Flatland Space Stations solution.

Add Flatland Space Stations solution.


/*
 * 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 com.johnsnowlabs.ml.tensorflow.sentencepiece

import com.johnsnowlabs.nlp.annotators.common.{IndexedToken, TokenPiece}

/**
 *
 * @param spp StencePieceWrapper loaded from either from disk or a saved Spark NLP model
 * @param caseSensitive whether it cares about uppercase or lowercases
 * @param delimiterId what is the part prefix id
 */
private[ml] class SentencepieceEncoder
(
  spp: SentencePieceWrapper,
  caseSensitive: Boolean,
  delimiterId: Int = 13
) {
  /**
   *
   * @param token IndexedToken input that is used for encoding to piece tokens and piece ids
   * @return Array of TokenPiece which are piece tokens with piece ids
   */
  def encode(token: IndexedToken): Array[TokenPiece] = {

    val text = token.token
    var start = 0
    var end = text.length

    val tokenContent = if (caseSensitive) token.token else token.token.toLowerCase()
    val wordPieces = spp.getSppModel.encodeAsPieces(tokenContent).toArray.map(x=>x.toString)
    val pieceIds = spp.getSppModel.encodeAsIds(tokenContent)
    wordPieces.zip(pieceIds).filter(id => id._2 != delimiterId).map{ piece =>
      val tokenPiece = TokenPiece(piece._1, token.token, piece._2, start == 0, token.begin + start, token.end)
      start = end
      end = text.length
      tokenPiece
    }
  }
}

Create a new SentencePieceEncoder [ski ci]


object VarDefault {
  case class AA(var x: Int = 555, y: Int = 222)

  def ff() = {
    val a = AA()
    assert(a.x == 555)
    assert(a.y == 222)
    a.x = 100
    assert(a.x == 100)
    assert(a.y == 222)
  }

}

Add example for var with default value in case class


object Solution {

  def binSearch(nums: Array[Int], v: Int): Int = {

    def binSearchAux(nums: Array[Int], lo: Int, hi: Int): Int = {
      if (lo >= hi) return -lo - 1
      val mid = lo + (hi - lo) / 2
      if (nums(mid) > v) binSearchAux(nums, lo, mid)
      else if (nums(mid) < v) binSearchAux(nums, mid + 1, hi)
      else mid
    }
    binSearchAux(nums, 0, nums.size)
  }

  def main(args: Array[String]) {
    val v = readLine.toInt
    val _ = readLine
    val nums = readLine.split(" ").map(_.toInt)
    println(binSearch(nums, v))
  }
}

Add solution to the intro challenges of Arrays and Sorting. This is a simple binary search algorithm


package net.sansa_stack.examples.spark.query

import net.sansa_stack.rdf.spark.io._
import net.sansa_stack.rdf.spark.model._
import org.apache.jena.riot.Lang
import org.apache.spark.sql.SparkSession

object HDTQuery {

  def main(args: Array[String]) {
    parser.parse(args, Config()) match {
      case Some(config) =>
        run(config.in, config.query)
      case None =>
        println(parser.usage)
    }
  }

  def run(input: String, query: String): Unit = {

    println("===========================================")
    println("| SANSA - HDT example                     |")
    println("===========================================")

    val spark = SparkSession.builder
      .master("local[*]")
      .config("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
      .appName("SANSA - HDT")
      .getOrCreate()

    val lang = Lang.NTRIPLES
    val triples = spark.rdf(lang)(input)

    val triples_hdt = triples.asHDT()

    import net.sansa_stack.query.spark.query._
    val result = triples_hdt.sparqlHDT(query)

    spark.close()

  }

  case class Config(in: String = "", query: String = "")

  val parser = new scopt.OptionParser[Config]("SANSA - HDT example") {

    head(" SANSA - HDT example")

    opt[String]('i', "input").required().valueName("<path>").
      action((x, c) => c.copy(in = x)).
      text("path to file that contains the data (in N-Triples format)")

    opt[String]('q', "query").required().valueName("SPARQL query").
      action((x, c) => c.copy(query = x)).
      text("the SPARQL query")

    help("help").text("prints this usage text")
  }

}

Add HDT example for Spark

Add HDT example for Spark


package trivial.rest

import com.twitter.finatra.test.SpecHelper
import com.twitter.finatra.{Controller, FinatraServer}
import org.jboss.netty.handler.codec.http.HttpHeaders.Names._
import org.scalatest.{MustMatchers, WordSpec}

class EndToEndSpec extends WordSpec with MustMatchers with SpecHelper {
  override def server = new FinatraServer {
    val app = new Controller with Rest {
      resource[Spaceship](GetAll)
      resource[Vector](GetAll)
    }
    register(app)
  }

  // TODO - CAS - 20/04/15 - This is a lie. It behaves differently when running normally -
  // charset is not defined. Need to debug the Finatra source to find out why.
  "Charset for JSON data is UTF-8" in {
    get("/spaceship.json")

    response.getHeader(CONTENT_TYPE) must equal("application/json; charset=UTF-8")
  }
}

Create an EndToEnd spec, using Finatra's SpecHelper. Turns out this behaves differently from the production code; not sure why yet.


package ch.usi.inf.l3.sana.brokenj.errors

import ch.usi.inf.l3.sana
import sana.tiny.errors.ErrorCode
import sana.primj

trait ErrorCodes extends primj.errors.ErrorCodes {
  case object DOUBLE_LABEL_DEF extends ErrorCode {
    val message: String = "Label is already defined"
  }
}

object ErrorCodes extends ErrorCodes

Add error codes for brokenj

Add error codes for brokenj


object Solution {

  def sievePrimeGenerator(n: Int): (List[Int], Array[Boolean]) = {
    val nums = Array.fill(n + 1)(true)
    nums(0) = false
    nums(1) = false
    val primes = for (i <- (2 to n) if nums(i)) yield {
      var j = 2
      while (i * j <= n) {
        nums(i * j) = false
        j += 1
      }
      i
    }
    (primes.toList, nums)
  }

  def isTruncatablePrime(p: Int, primeTable: Array[Boolean]): Boolean = {
    val digits = p.toString.map(_.asDigit)
    val truncatesFromRight = digits.foldLeft(List(0)) { (x, y) =>
      x.head * 10 + y :: x
    } dropRight(1)
    var base = 1
    var prime = p
    var pp = 0
    val truncatesFromLeft = for (i <- 1 to digits.length) yield {
      pp += (prime % 10) * base
      base *= 10
      prime /= 10
      pp
    }
    (truncatesFromLeft ++ truncatesFromRight).forall(primeTable(_))
  }

  def main(args: Array[String]) {
    val n = readLine.toInt
    val (primes, primeTable) = sievePrimeGenerator(n - 1)
    val sum = primes.drop(4).filter(x => isTruncatablePrime(x, primeTable)).sum
    println(sum)
  }
}

Add solution to problem 37. The sievePrimeGenerator don't set the 0 and 1 to be false as a prime


/**
 * https://www.hackerrank.com/challenges/points-on-rectangle
 */
package com.negrisoli.mathematics.geometry

import scala.Vector

object PointOnRetangle {

  def main(args: Array[String]) {
        val sc = new java.util.Scanner(System.in);
        val queries = sc.nextInt

        for (i <- 1 to queries) {
            val pointsSize = sc.nextInt
            val points = (1 to pointsSize * 2).map(j => sc.nextInt).sliding(2, 2).toList

            val min = points.reduceLeft((x, y) => Vector(x(0) min y(0), x(1) min y(1)))
            val max = points.reduceLeft((x, y) => Vector(x(0) max y(0), x(1) max y(1)))

            val allPointsAreOnEdge = points.forall({
                x => (x(0) == min(0) || x(0) == max(0)) || (x(1) == min(1) || x(1) == max(1))
            })
            println(if (allPointsAreOnEdge) "YES" else "NO")
        }
  }

}

Add point on retangle solution.

Add point on retangle solution.


package org.precompiler.scala101.ch03

/**
  *
  * @author Richard Li
  */
object ImplicitParameters {
  // global scope implicit variable
  implicit val vodafone = new Wifi("Vodafone")

  class Wifi(name: String) {
    override def toString: String = name
  }

  def connectToNetwork(user: String)(implicit wifi: Wifi): Unit = {
    println(s"User ${user} connected to WIFI ${wifi}")
  }

  def atOffice(): Unit = {
    println("----office----")
    // method scope implicit variable
    // will get ambiguous implicit values runtime exception if
    // multiple implicit values of the same type found in scope
    // implicit val officeNetwork = new Wifi("Office")
    val cafeteriaNetwork = new Wifi("Cafe")
    connectToNetwork("guest")(cafeteriaNetwork)
    connectToNetwork("John Doe")
  }

  def atHome(): Unit = {
    println("----home----")
    // implicit val homeNetwork = new Wifi("Home")
    connectToNetwork("Scott Tiger")
  }

  def main(args: Array[String]): Unit = {
    atOffice()
    atHome()
  }
}

Add implicit parameters example code.

Add implicit parameters example code.


package edu.cmu.lti.nlp.amr

import java.io.File
import java.io.FileOutputStream
import java.io.PrintStream
import java.io.BufferedOutputStream
import java.io.OutputStreamWriter
import java.lang.Math.abs
import java.lang.Math.log
import java.lang.Math.exp
import java.lang.Math.random
import java.lang.Math.floor
import java.lang.Math.min
import java.lang.Math.max
import scala.io.Source
import scala.util.matching.Regex
import scala.collection.mutable.Map
import scala.collection.mutable.Set
import scala.collection.mutable.ArrayBuffer

object CheckAMR {
    val usage = """Usage: scala -classpath . edu.cmu.lti.nlp.amr.CheckAMR < amr_corpus > output"""
    type OptionMap = Map[Symbol, Any]

    def parseOptions(map : OptionMap, list: List[String]) : OptionMap = {
        def isSwitch(s : String) = (s(0) == '-')
        list match {
            case Nil => map
            case "--tokenized" :: value :: tail =>
                      parseOptions(map ++ Map('tokenized -> value), tail)
            case "-v" :: value :: tail =>
                      parseOptions(map ++ Map('verbosity -> value.toInt), tail)
            case option :: tail => println("Error: Unknown option "+option)
                               sys.exit(1)
      }
    }

    def main(args: Array[String]) {

        val options = parseOptions(Map(),args.toList)
        if (options.contains('verbosity)) {
            verbosity = options('verbosity).asInstanceOf[Int]
        }

        val Block = """((?:\n|.)*)\n(\((?:\n|.)*)""".r  // (?: ) is non-capturing group
        var i = 0
        for (block <- Corpus.splitOnNewline(Source.stdin.getLines)) {
            //if (block matches "(.|\n)*\n\\((.|\n)*") { // Does it containt some AMR? . does not match \n
                //val Block(extras, amrstr) = block
                val graph = Graph.parse(block)
                //graph.normalizeInverseRelations
                if (CycleTester.hasCycle(graph.nodes.toList, graph.nodes.map(x => (x, x.relations.map(y => y._2))).toMap)) {
                    println("Contains a cycle")
                } else {
                    println("No cycle")
                }
                i += 1
            //} else {
            //    println(block+"\n")
            //}
        }
    }
}

Add checking for acylic graphs

Add checking for acylic graphs

git-svn-id: 7e37095f1dd393dcbedc6a786761dc891d09176a@976 adcbdfe1-51bf-4484-b097-aa5b931b129a


package org.refptr.iscala
package widgets

sealed trait BorderStyle extends EnumType
object BorderStyle extends Enum[BorderStyle] {
    case object None extends BorderStyle
    case object Hidden extends BorderStyle
    case object Dotted extends BorderStyle
    case object Dashed extends BorderStyle
    case object Solid extends BorderStyle
    case object Double extends BorderStyle
    case object Groove extends BorderStyle
    case object Ridge extends BorderStyle
    case object Inset extends BorderStyle
    case object Outset extends BorderStyle
    case object Initial extends BorderStyle
    case object Inherit extends BorderStyle
}

sealed trait FontStyle extends EnumType
object FontStyle extends Enum[FontStyle] {
    case object Normal extends FontStyle
    case object Italic extends FontStyle
    case object Oblique extends FontStyle
    case object Initial extends FontStyle
    case object Inherit extends FontStyle
}

sealed trait FontWeight extends EnumType
object FontWeight extends Enum[FontWeight] {
    case object Normal extends FontWeight
    case object Bold extends FontWeight
    case object Bolder extends FontWeight
    case object Lighter extends FontWeight
    case object Initial extends FontWeight
    case object Inherit extends FontWeight
    case object `100` extends FontWeight
    case object `200` extends FontWeight
    case object `300` extends FontWeight
    case object `400` extends FontWeight
    case object `500` extends FontWeight
    case object `600` extends FontWeight
    case object `700` extends FontWeight
    case object `800` extends FontWeight
    case object `900` extends FontWeight
}

sealed trait ButtonStyle extends EnumType
object ButtonStyle extends Enum[ButtonStyle] {
    case object Primary extends ButtonStyle
    case object Success extends ButtonStyle
    case object Info extends ButtonStyle
    case object Warning extends ButtonStyle
    case object Danger extends ButtonStyle
}

sealed trait BoxStyle extends EnumType
object BoxStyle extends Enum[BoxStyle] {
    case object Success extends BoxStyle
    case object Info extends BoxStyle
    case object Warning extends BoxStyle
    case object Danger extends BoxStyle
}

sealed trait Orientation extends EnumType
object Orientation extends Enum[Orientation] {
    case object Horizontal extends Orientation
    case object Vertical extends Orientation
}

sealed trait Location extends EnumType
object Location extends Enum[Location] {
    case object Start extends Location
    case object Center extends Location
    case object End extends Location
    case object Baseline extends Location
    case object Stretch extends Location
}

sealed trait Overflow extends EnumType
object Overflow extends Enum[Overflow] {
    case object Visible extends Overflow
    case object Hidden extends Overflow
    case object Scroll extends Overflow
    case object Auto extends Overflow
    case object Initial extends Overflow
    case object Inherit extends Overflow
}

Implement enumerations used by IPython widgets


object Solution {

  def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b,  a % b)

  def existsSubsets(arr: Array[Int]): Boolean = {
    val n = arr.size
    for {
      i <- 0 until n
      j <- i + 1 until n
      if arr(i) != arr(j)
    } {
      if (gcd(arr(i), arr(j)) == 1) return true
    }
    if (n == 1 && arr(0) == 1) true else false
  }

  def main(args: Array[String]) {
    val t = readLine.toInt
    for(_ <- 1 to t) {
      val n = readLine.toInt
      val arr = readLine.split(" ").map(_.toInt)
      if (existsSubsets(arr)) println("YES") else println("NO")
    }
  }
}

Add solution to problem Sherlock and GCD


object Main {
    def main(args: Array[String]) {
        val a = io.StdIn.readLine().toInt
        val b = io.StdIn.readLine().toInt

        println("PROD = " + (a * b))
    }
}

Solve Simple Product in scala

Solve Simple Product in scala


package se.marcuslonnberg.scaladocker.remote.api

import akka.actor.ActorSystem
import akka.stream.MaterializerSettings
import akka.stream.scaladsl2.FlowMaterializer
import akka.testkit.TestKit
import org.scalatest.concurrent.{IntegrationPatience, ScalaFutures}
import org.scalatest.{FlatSpecLike, Inspectors, Matchers}
import se.marcuslonnberg.scaladocker.remote.models.{ContainerConfig, HostConfig, ImageName}

class ContainerApiSpec extends TestKit(ActorSystem("container-api")) with FlatSpecLike with Matchers with ScalaFutures with IntegrationPatience with Inspectors {
  implicit val mat = FlowMaterializer(MaterializerSettings(system))

  val client = DockerClient()

  val busybox = ImageName("busybox")

  "Container API" should "list all containers" in {
    val containerId = client.runLocal(ContainerConfig(busybox, cmd = List("ls", "/")), HostConfig()).futureValue

    val containers = client.containers.list(all = true).futureValue

    forAtLeast(1, containers) { container =>
      container.id shouldEqual containerId
      container.image shouldEqual busybox
      container.command shouldEqual "ls /"
    }
  }

  it should "get info about a container" in {
    val containerId = client.runLocal(ContainerConfig(busybox, cmd = List("ls", "/")), HostConfig()).futureValue

    val container = client.containers.get(containerId).futureValue

    container.id shouldEqual containerId
    container.path shouldEqual "ls"
    container.args should contain theSameElementsInOrderAs Seq("/")

    container.config.image shouldEqual busybox
  }
}

Add tests for container APIs

Add tests for container APIs


package org.scalatddpackt

import org.scalatest.FunSuite

class SetSuite extends FunSuite {

  test("An empty Set should have size 0") {
    assert(Set.empty.size == 0)
  }

  test("Invoking head on an empty Set should produce NoSuchElementException") {
    intercept[NoSuchElementException] {
      Set.empty.head
    }
  }
}

Add FunSpec example from scalatest.org

Add FunSpec example from scalatest.org

Signed-off-by: George K. Thiruvathukal <97f75e7847f9d781491c82d5a21e2f28eba950b0@cs.luc.edu>


object Test extends Application {
  def test[T](t1 : T, t2 : T)(implicit ord : Ordering[T]) = {
    val cmp = ord.compare(t1, t2);
    val cmp2 = ord.compare(t2, t1);

    assert((cmp == 0) == (cmp2 == 0))
    assert((cmp > 0) == (cmp2 < 0))
    assert((cmp < 0) == (cmp2 > 0))
  }

  def testAll[T](t1 : T, t2 : T)(implicit ord : Ordering[T]) = {
    assert(ord.compare(t1, t2) < 0)
    test(t1, t2);
    test(t1, t1);
    test(t2, t2);
  }

  assert(Ordering[String].compare("australopithecus", "brontausaurus") < 0)
  assert(Ordering[Unit].compare((), ()) == 0)

  testAll("bar", "foo");
  testAll[Byte](0, 1);
  testAll(false, true)
  testAll(1, 2);
  testAll(1.0, 2.0);
  testAll(None, Some(1));
  testAll[Iterable[Int]](List(1), List(1, 2));
  testAll[Iterable[Int]](List(1, 2), List(2));
  testAll((1, "bar"), (1, "foo"))
  testAll((1, "foo"), (2, "bar"))
}

Test for default Ordering implementations.


import org.specs2.mutable._
import org.specs2.runner._
import org.junit.runner._

import play.api.test._
import play.api.test.Helpers._
import services.WorksheetService

@RunWith(classOf[JUnitRunner])
class LibrariesSpec extends Specification {

  "Worksheet" should {

    "have access to ScalaUtils" in {
      val code = """
          |import org.scalautils._
          |import TripleEquals._
          |import StringNormalizations._
          |import Explicitly._
          |
          |("Hello" === "hello") (after being lowerCased)
        """.stripMargin

      val worksheet = new WorksheetService

      (worksheet.evaluate(code) \ "userRepr").as[String] must endWith ("true")
    }
  }
}

Test to assert existence of ScalaUtils

[0.0.10] Test to assert existence of ScalaUtils


object Solution {

  def main(args: Array[String]) {
    val p = 1234567
    val t = readLine.toInt
    for (_ <- 1 to t) {
      val _ = readLine
      val routes = readLine.split(" ").map(_.toInt)
      println(routes.foldLeft(1L) { _ * _ % p })
    }
  }
}

Add solution to Connection Towns.

Add solution to Connection Towns.


package com.softwaremill.react.kafka

import akka.stream.scaladsl.{Source, PublisherSink}
import org.reactivestreams.Publisher
import org.reactivestreams.tck.{PublisherVerification, TestEnvironment}

import scala.concurrent.duration.{FiniteDuration, _}
import scala.language.postfixOps

class ReactiveKafkaPublisherSpec(defaultTimeout: FiniteDuration)
  extends PublisherVerification[String](new TestEnvironment(defaultTimeout.toMillis), defaultTimeout.toMillis)
  with ReactiveStreamsTckVerificationBase {

  def this() = this(300 millis)

  override def createPublisher(l: Long) = {
    createHelperPublisher(l)
  }

  def createHelperSource(elements: Long): Source[String] = elements match {
    case 0 => Source.empty()
    case Long.MaxValue => Source(() => List(message).iterator)
    case n if n <= Int.MaxValue => Source(List.fill(n.toInt)(message))
    case n => sys.error("n > Int.MaxValue")
  }

  def createHelperPublisher(elements: Long): Publisher[String] = {
    createHelperSource(elements).runWith(PublisherSink())
  }

  override def createErrorStatePublisher(): Publisher[String] = {
    kafka.consume("error_topic", "groupId")
  }
}

Add specs for the publisher

Add specs for the publisher


/*
 * This file has been copy-pasted from spores.
 * https://github.com/scalacenter/spores/blob/master/core/src/test/scala/scala/spores/TestUtil.scala
 */

package sbt.std

import scala.reflect._

object TestUtil {
  import scala.language.postfixOps
  import tools.reflect.{ ToolBox, ToolBoxError }

  def intercept[T <: Throwable: ClassTag](test: => Any): T = {
    try {
      test
      throw new Exception(s"Expected exception ${classTag[T]}")
    } catch {
      case t: Throwable =>
        if (classTag[T].runtimeClass != t.getClass) throw t
        else t.asInstanceOf[T]
    }
  }

  def eval(code: String, compileOptions: String = ""): Any = {
    val tb = mkToolbox(compileOptions)
    tb.eval(tb.parse(code))
  }

  def mkToolbox(compileOptions: String = ""): ToolBox[_ <: scala.reflect.api.Universe] = {
    val m = scala.reflect.runtime.currentMirror
    import scala.tools.reflect.ToolBox
    m.mkToolBox(options = compileOptions)
  }

  lazy val toolboxClasspath: String = {
    val resource = getClass.getClassLoader.getResource("toolbox.classpath")
    val classpathFile = scala.io.Source.fromFile(resource.toURI)
    val completeSporesCoreClasspath = classpathFile.getLines.mkString
    completeSporesCoreClasspath
  }

  def expectError(errorSnippet: String,
                  compileOptions: String = "-Xmacro-settings:debug-spores",
                  baseCompileOptions: String = s"-cp $toolboxClasspath")(code: String) {
    val errorMessage = intercept[ToolBoxError] {
      eval(code, s"$compileOptions $baseCompileOptions")
    }.getMessage
    val userMessage =
      s"""
         |FOUND: $errorMessage
         |EXPECTED: $errorSnippet
      """.stripMargin
    assert(errorMessage.contains(errorSnippet), userMessage)
  }
}

Add test util to check neg macro tests

Add test util to check neg macro tests


import scala.annotation.unchecked.uncheckedVariance

type Untyped = Null

class Type

abstract class Tree[-T >: Untyped] {
  type ThisTree[T >: Untyped] <: Tree[T]

  protected var myTpe: T @uncheckedVariance = _

  def withType(tpe: Type): ThisTree[Type] = {
    val tree = this.asInstanceOf[ThisTree[Type]]
    tree.myTpe = tpe
    tree
  }
}

case class  Ident[-T >: Untyped]() extends Tree[T]
case class DefDef[-T >: Untyped]() extends Tree[T]

def test[T >: Untyped](tree: Tree[T], tp: Type) = tree.withType(tp) match {
  case Ident()  => 1
  case DefDef() => 2
  case _        => 3
}

Add a test case representing the fallout seen in bootstrapping


/* https://www.hackerrank.com/challenges/circular-array-rotation */
package com.negrisoli.algorithms.warmup

object CircularArrayRotation {

  def main(args: Array[String]): Unit = {
    val sc = new java.util.Scanner(System.in)
    val List(n, k, q) = (0 to 2).map(i => sc.nextInt).toList
    val a = (1 to n).map(i => sc.nextInt).toList

    (1 to q) foreach { i =>
      val m = sc.nextInt
      println(query(a, k % n, m))
    }
  }

  def query(array: List[Int], rotate: Int, index: Int) = {
    array((array.size - rotate + index) % array.size)
  }

}

Add solution to circular array rotation.


package ca.innovativemedicine.vcf.app

import ca.innovativemedicine.vcf.solr._

import java.io.{ File, InputStream, BufferedInputStream, FileInputStream }
import com.typesafe.config.{ Config, ConfigException, ConfigFactory }

case class SolrVcfImportOpts(config: Config, in: Option[InputStream])

object SolrVcfImport extends App {

  parseOpts(SolrVcfImportOpts(ConfigFactory.load(), None), args.toList) match {
    case Left(error) =>
      println(error)

    case Right(opts) =>
      val importer = new ConfiguredSolrVcfImporter with ConfiguredSolrServerProvider with Configured {
        val config = opts.config
      }

      println("Importing VCF to Solr.")
      importer.importVcf(opts.in getOrElse System.in)
      println("Finished!")
  }

  def parseOpts(opts: SolrVcfImportOpts, args: List[String]): Either[String, SolrVcfImportOpts] = args match {
    case Nil =>
      Right(opts)

    case ("-c" | "--config") :: configFilename :: args =>
      try {
        val f = new java.io.File(configFilename)
        if (!f.canRead()) {
          Left("Cannot read config file: %s" format configFilename)
        } else {
          val config = ConfigFactory.parseFile(f)
          parseOpts(opts.copy(config = config.withFallback(opts.config)), args)
        }

      } catch {
        case e: ConfigException =>
          Left("Failed to parse config: " + e.getMessage())
      }

    case vcfFilename :: args =>
      val f = new java.io.File(vcfFilename)
      if (!f.canRead()) {
        Left("Cannot read VCF file: %s" format vcfFilename)
      } else {
        val in = new BufferedInputStream(new FileInputStream(f))
        parseOpts(opts.copy(in = Some(in)), args)
      }
  }
}

Add the VCF Solr importer app.

Add the VCF Solr importer app.


package pl.touk.nussknacker.engine.util.typing

import io.circe.parser._
import org.scalatest.{FunSuite, Inside, Matchers}

class JsonToTypedMapConverterTest extends FunSuite with Matchers with Inside {

  test("should handle decimal scale correctly") {
    val typedMap = JsonToTypedMapConverter.jsonToTypedMap(parse("""{"foo": 0.00}""").right.get)
    inside(typedMap.get("foo")) {
      case bd: java.math.BigDecimal =>
        bd.scale() shouldBe 2
        bd shouldEqual new java.math.BigDecimal("0.00")
    }
  }

}

Test for handling scale properly during json to typed map conversion


object Solution {

  def genPentagonNumbers(n: Int): (Array[Long], Set[Long]) = {
    val result = (1l to n).map(x => x * (3 * x - 1) / 2).toArray
    (result, result.toSet)
  }

  def main(args: Array[String]) {
    val Array(n, k) = readLine.split(" ").map(_.toInt)
    val (penNum, penNumSet) = genPentagonNumbers(n)
    val penNums = (k + 1 until n).filter({ x =>
      val (pn, pk) = (penNum(x), penNum(x - k))
      penNumSet(pn + pk) || penNumSet(pn - pk)
    }).map(penNum(_))
    println(penNums.mkString("\n"))
  }
}

Add solution to problem 44. The space complexity is O(n), which may be not a valid option for very big n.


package uk.ac.wellcome.platform.snapshot_convertor.flow

import akka.stream.scaladsl.{Sink, Source}
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.{FunSpec, Matchers}
import uk.ac.wellcome.display.models.DisplayWork
import uk.ac.wellcome.test.fixtures.Akka
import uk.ac.wellcome.test.utils.JsonTestUtil

import scala.concurrent.ExecutionContextExecutor

class DisplayWorkToJsonStringFlowTest
    extends FunSpec
    with Matchers
    with Akka
    with ScalaFutures
    with JsonTestUtil {

  it("converts a DisplayWork to a correctly-formatted JSON string") {
    withActorSystem { actorSystem =>
      implicit val executionContext: ExecutionContextExecutor =
        actorSystem.dispatcher
      withMaterializer(actorSystem) { materializer =>
        val flow = DisplayWorkToJsonStringFlow()

        val displayWork = DisplayWork(
          id = "cguztabd",
          title = "A collection of curled-up cats in Croatia"
        )

        val expectedJsonString = s"""{
          "id": "${displayWork.id}",
          "title": "${displayWork.title}",
          "creators": [ ],
          "subjects": [ ],
          "type": "Work"
        }"""

        val futureJsonString = Source.single(displayWork)
          .via(flow)
          .runWith(Sink.head)(materializer)

        whenReady(futureJsonString) { jsonString =>
          assertJsonStringsAreEqual(jsonString, expectedJsonString)}
      }
    }
  }
}

snapshot_convertor: Add a test that DisplayWorks are serialised correctly


//
// Config.scala -- Scala class Config
// Project OrcScala
//
// Created by jthywiss on Sep 11, 2017.
//
// Copyright (c) 2017 The University of Texas at Austin. All rights reserved.
//
// Use and redistribution of this file is governed by the license terms in
// the LICENSE file found in the project's top-level directory and also found at
// URL: http://orc.csres.utexas.edu/license.shtml .
//

package orc.util

import java.io.{ File, FileInputStream }
import java.util.Properties

/** A map of settings loaded from configuration files.  The directories
  * listed in the given system property ("orc.config.dirs" by default)
  * are searched for the given filename.  Settings in files found
  * earlier in the list of directories take precedence.  Defaults are
  * loaded from a resource on the class path, namely a file of the given
  * name in the package of the concrete subclass of this class.
  *
  * @author jthywiss
  */
abstract class Config(filename: String, systemProperty: String = "orc.config.dirs") extends scala.collection.immutable.AbstractMap[String,String] with scala.collection.immutable.DefaultMap[String, String]() {

  protected val settings = load()

  override def toString = iterator.map(e => e._1 + "=" + e._2).mkString(s"${getClass.getName}(# filename=$filename; ", ", ", ")")

  protected def load() = {
    def wrapProps(dirs: Iterator[String], inner: Properties): Properties = {
      if (dirs.hasNext) {
        val f = new File(dirs.next(), filename)
        if (f.exists) {
          val wrapper = new Properties(inner)
          wrapper.load(new FileInputStream(f))
          wrapProps(dirs, wrapper)
        } else {
          wrapProps(dirs, inner)
        }
      } else {
        inner
      }
    }

    val defaultsStream = getClass.getResourceAsStream(filename)
    val defaults = if (defaultsStream == null) {
      new Properties()
    } else {
      val defaults = new Properties()
      defaults.load(defaultsStream)
      defaults
    }
    val configDirs = System.getProperty(systemProperty).split(File.pathSeparatorChar)
    wrapProps(configDirs.reverseIterator,defaults)
  }

  override def get(key: String) = {
    val v = settings.getProperty(key)
    if (v != null)
      Some(v)
    else if (settings.containsKey(key))
      Some(null.asInstanceOf[String])
    else
      None
  }

  def iterator: Iterator[(String, String)] = new scala.collection.AbstractIterator[(String, String)]() {
    val si = settings.stringPropertyNames.iterator()
    def hasNext = si.hasNext
    def next() = { val k = si.next(); (k, settings.getProperty(k)) }
  }

}

Add configuration/settings file utility class.


name := "no-carrier"

version := "1.0"

scalaVersion := "2.11.5"

mainClass := Some("com.getbootstrap.no_carrier.Main")

resolvers ++= Seq("snapshots", "releases").map(Resolver.sonatypeRepo)

libraryDependencies += "com.jcabi" % "jcabi-github" % "0.24"

libraryDependencies += "com.typesafe.scala-logging" %% "scala-logging" % "3.1.0"

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

libraryDependencies += "org.specs2" %% "specs2" % "2.3.12" % "test"

// Because jcabi-github:

libraryDependencies += "com.google.code.findbugs" % "annotations" % "2.0.1"

scalacOptions := Seq("-unchecked", "-deprecation", "-feature", "–Xlint", "-encoding", "utf8")

scalacOptions in Test ++= Seq("-Yrangepos")

// parallelExecution in Test := false

Revolver.settings

name := "no-carrier"

version := "1.0"

scalaVersion := "2.11.5"

mainClass := Some("com.getbootstrap.no_carrier.Main")

resolvers ++= Seq("snapshots", "releases").map(Resolver.sonatypeRepo)

val jcabiV = "0.24"

libraryDependencies += "com.jcabi" % "jcabi-github" % jcabiV

libraryDependencies += "com.typesafe.scala-logging" %% "scala-logging" % "3.1.0"

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

libraryDependencies += "org.specs2" %% "specs2" % "2.3.12" % "test"

// Because jcabi-github:

libraryDependencies += "com.google.code.findbugs" % "annotations" % "2.0.1"

packageOptions in (Compile, packageBin) ++= {
  Seq(
    Package.ManifestAttributes("JCabi-Version" -> jcabiV),
    Package.ManifestAttributes("JCabi-Build" -> "abcdef"),
    Package.ManifestAttributes("JCabi-Date" -> "2015-08-01")
  )
}

scalacOptions := Seq("-unchecked", "-deprecation", "-feature", "–Xlint", "-encoding", "utf8")

scalacOptions in Test ++= Seq("-Yrangepos")

// parallelExecution in Test := false

Revolver.settings

Add manifest entries to make jcabi-github happy


import stainless.lang._

object Test {
  def f(n: BigInt): Unit = {
    var i = n
    (while (i > 0) {
      decreases(i)
      i -= 1
    }).inline.opaque.invariant(n == 5)
  }
}

Add benchmark to make sure inlined preconditions are checked


package views.html

/**
 * Contains template helpers, for example for generating HTML forms.
 */
package object helper {

  /**
   * Default inpout structure.
   *
   * {{{
   *

   *

   *
<input type="text" name="username" id="username">

   *
This field is required!

   *
Required field.

   *

   * }}}
   */
  val defaultField = defaultFieldConstructor.f

}

package views.html

/**
 * Contains template helpers, for example for generating HTML forms.
 */
package object helper {

  /**
   * Default inpout structure.
   *
   * {{{
   *

   *

   *
<input type="text" name="username" id="username">

   *
This field is required!

   *
Required field.

   *

   * }}}
   */
  val defaultField = defaultFieldConstructor.f

  /**
   * @return The url-encoded value of `string` using the charset provided by `codec`
   */
  def urlEncode(string: String)(implicit codec: play.api.mvc.Codec): String =
    java.net.URLEncoder.encode(string, codec.charset)

}

Add a helper to url-encode in templates

Add a helper to url-encode in templates


import org.scalatest.FlatSpec
import org.scalatest.Matchers

import Utils.java2js

class StringSpec extends FlatSpec with Matchers {

  import Utils._

  "String length method calls" should "translate into length property access" in {
    val java =
"""
    class Test {
      public void test(String a) {
        int l = a.length();
        String b = "";
        l = b.length();
        l = "".length();
      }
    }

"""

    val expected =
"""
    export default class Test {
      get interfaces_() {
        return [];
      }
      test(a) {
        var l = a.length;
        var b = "";
        l = b.length;
        l = "".length;
      }
      getClass() {
        return Test;
      }
    }

"""

    java2js(java) should equal (expected)
  }
}

Test cases for string length conversion

Test cases for string length conversion


package scala.meta.tests
package parsers

import scala.meta._
import scala.meta.dialects.Scala213

class Scala213Suite extends ParseSuite {
  checkOK("def foo(implicit x: => Int) = 1")
  checkOK("def foo(implicit y: Int, x: => Int) = 1")
}

Copy Dotty tests for by-name implicits to 2.13


import java.time.Instant
import java.net.URI

case class Id[Entity](value: String) extends AnyVal

case class User(
  id: Id[User],
  updatedOn: Instant,
  image: URI,
  nickname: String,
  verified: Boolean,
  deleted: Boolean
)
case class Post(
  id: Id[Post],
  updatedOn: Instant,
  author: Id[User],
  text: String,
  image: URI,
  deleted: Boolean
)
case class Like(
  userId: Id[User],
  postId: Id[Post],
  updatedOn: Instant,
  unliked: Boolean
)
case class Comment(
  id: Id[Comment],
  postId: Id[Post],
  updatedOn: Instant,
  author: Id[User],
  text: String,
  deleted: Boolean
)

object Domain extends App {
  val user = User(Id("1"), Instant.now, new URI(""), "", false, false)
  val post = Post(Id("1"), Instant.now, user.id, "", new URI(""), false)
}

Test case class Id[Entity] form

Test case class Id[Entity] form


package io.gatling.core.assertion

import org.scalatest.{ FlatSpec, Matchers }

import io.gatling.core.assertion._

class AssertionDSLSpec extends FlatSpec with Matchers with AssertionSupport {

  "The Assertion DSL builders" should "produce the expected Assertions ASTs" in {

    global.responseTime.min.is(100) shouldBe Assertion(Global, TimeTarget(ResponseTime, Min), Is(100))
    details("Foo" / "Bar").responseTime.max.lessThan(100) shouldBe Assertion(Details(List("Foo", "Bar")), TimeTarget(ResponseTime, Max), LessThan(100))
    forAll.responseTime.mean.greaterThan(100) shouldBe Assertion(ForAll, TimeTarget(ResponseTime, Mean), GreaterThan(100))
    global.responseTime.stdDev.between(1, 3) shouldBe Assertion(Global, TimeTarget(ResponseTime, StandardDeviation), Between(1, 3))
    global.responseTime.percentile1.is(300) shouldBe Assertion(Global, TimeTarget(ResponseTime, Percentiles1), Is(300))
    global.responseTime.percentile2.in(Set(1, 2, 3)) shouldBe Assertion(Global, TimeTarget(ResponseTime, Percentiles2), In(List(1, 2, 3)))

    global.allRequests.count.is(20) shouldBe Assertion(Global, CountTarget(AllRequests, Count), Is(20))
    forAll.allRequests.percent.lessThan(5) shouldBe Assertion(ForAll, CountTarget(AllRequests, Percent), LessThan(5))

    global.failedRequests.count.greaterThan(10) shouldBe Assertion(Global, CountTarget(FailedRequests, Count), GreaterThan(10))
    details("Foo" / "Bar").failedRequests.percent.between(1, 5) shouldBe Assertion(Details(List("Foo", "Bar")), CountTarget(FailedRequests, Percent), Between(1, 5))

    global.successfulRequests.count.in(Set(1, 2, 4)) shouldBe Assertion(Global, CountTarget(SuccessfulRequests, Count), In(List(1, 2, 4)))
    global.successfulRequests.percent.is(6) shouldBe Assertion(Global, CountTarget(SuccessfulRequests, Percent), Is(6))
  }
}

Add some tests for the Assertion DSL

Add some tests for the Assertion DSL


package hmda.api.http.filing.submissions

import akka.actor.ActorSystem
import akka.cluster.sharding.typed.scaladsl.ClusterSharding
import akka.event.LoggingAdapter
import akka.http.scaladsl.server.Route
import akka.stream.ActorMaterializer
import akka.util.Timeout
import hmda.api.http.directives.HmdaTimeDirectives
import akka.http.scaladsl.server.Directives._
import ch.megard.akka.http.cors.scaladsl.CorsDirectives._
import de.heikoseeberger.akkahttpcirce.FailFastCirceSupport._

import scala.concurrent.ExecutionContext

trait SubmissionHttpApi extends HmdaTimeDirectives {

  implicit val system: ActorSystem
  implicit val materializer: ActorMaterializer
  val log: LoggingAdapter
  implicit val ec: ExecutionContext
  implicit val timeout: Timeout
  val sharding: ClusterSharding

  val submissionCreatePath: Route = ???

//  val submissionLatestPath: Route = ???
//
//  val submissionByIdPath: Route = ???

  def submissionRoutes: Route = {
    handleRejections(corsRejectionHandler) {
      cors() {
        encodeResponse {
          submissionCreatePath
        }
      }
    }
  }

}

Add submission http API trait

Add submission http API trait