package hmda.api.http

import akka.event.{ LoggingAdapter, NoLogging }
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.util.Timeout
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import scala.concurrent.duration._
import org.scalatest.{ BeforeAndAfterAll, MustMatchers, WordSpec }
import hmda.api.demo.DemoData
import hmda.api.model.Filings
import hmda.api.persistence.FilingPersistence._

class FilingHttpApiSpec extends WordSpec with MustMatchers with ScalatestRouteTest with FilingsHttpApi with BeforeAndAfterAll {
  override val log: LoggingAdapter = NoLogging
  override implicit val timeout: Timeout = Timeout(5.seconds)

  val ec = system.dispatcher

  override def beforeAll(): Unit = {
    createFilings("12345", system)
    DemoData.loadData(system)
  }

  "Filings HTTP API" must {
    "return a list of filings for a financial institution" in {
      Get("/institutions/12345/filings") ~> filingsRoutes ~> check {
        status mustBe StatusCodes.OK
        responseAs[Filings] mustBe Filings(DemoData.filings.filter(f => f.fid == "12345").reverse)
      }
    }

  }

}

Add filings http api tes

Add filings http api tes


object Solution {
  import scala.collection.mutable.{HashMap, LinkedHashSet}

  val factorialOfDigits = (1 to 9).foldLeft(Vector(1)) { (x, y) =>
    x :+ y * x.last
  }
  val limit = 1e6.toInt
  val chainCache = Array.fill(limit + 1)(0)
  val chainLengthCache = HashMap[Int, Int](
    169 -> 3, 363601 -> 3, 1454 -> 3, 871 -> 2,
    45361 -> 2, 872 -> 2, 45362 -> 2).withDefaultValue(0)

  def nextNumber(x: Int): Int = {

    def nextNumberAux(x: Int): Int = {
      var xx = x
      var result = 0
      while (xx >= 10) {
        result += factorialOfDigits(xx % 10)
        xx /= 10
      }
      // deal with x = 0
      result + factorialOfDigits(xx)
    }
    if (x <= limit) {
      if (chainCache(x) == 0) chainCache(x) = nextNumberAux(x)
      chainCache(x)
    }
    else nextNumberAux(x)
  }

  def chainLength(x: Int): Int = {

    def chainLenthSearch(x: Int, visted: LinkedHashSet[Int]) {
      // we find result in the cache
      if (chainLengthCache(x) != 0) {
        val cLen = chainLengthCache(x)
        var len = visted.size + cLen
        for (i <- visted) {
          if (i <= limit) {
            chainLengthCache(i) = len
          }
          len -= 1
        }
      }
      // we hit a cycle.
      else if (visted(x)) {
        val nums = visted.toVector
        val index = nums.indexOf(x)
        val (left, right) = nums.splitAt(index)
        var len = visted.size
        for (i <- left) {
          if (i <= limit) {
            chainLengthCache(i) = len
          }
          len -= 1
        }
        for (i <- right) chainLengthCache(i) = len
      }
      else {
        chainLenthSearch(nextNumber(x), visted + x)
      }
    }

    if (chainLengthCache(x) != 0) chainLengthCache(x)
    else {
      chainLenthSearch(x, LinkedHashSet.empty[Int])
      chainLengthCache(x)
    }
  }

  def numbersOfChainLength(n: Int, l: Int): Array[Int] = {
    (0 to n).filter(x => chainLength(x) == l).toArray
  }

  def main(args: Array[String]) {
    for (i <- 1 to readInt) {
      val Array(n, l) = readLine.split(" ").map(_.toInt)
      val numbers = numbersOfChainLength(n, l)
      if (numbers.size == 0) println(-1)
      else println(numbers.mkString(" "))
    }
  }
}

Add solution to problem 73.

Add solution to problem 73.


package latis.reader

import latis.dm._
import scala.collection.immutable._
import latis.writer.AsciiWriter

/**
 * Make a toy Dataset to test the LaTiS API against.
 */
class ToyDatasetAccessor extends DatasetAccessor {

  /**
   * Make a Dataset.
   */
  def getDataset() = {
    //
    val v1 = new Real
    val v2 = new Real
    new Dataset(this, Seq(v1, v2))
  }

  def close() {}

}

object ToyDatasetAccessor extends App {

  //make a DatasetAccessor
  val da = new ToyDatasetAccessor()

  //get the Dataset
  val ds = da.getDataset()

  //write the Dataset
  val writer = new AsciiWriter(System.out)
  writer.write(ds)

}

Add a concrete DatasetAccessor so we can experiment with the API.


package com.anchortab.migrate

import com.anchortab.model._

import net.liftweb._
  import http._
    import js._
      import JsCmds._
    import SHtml._
    import LiftRules._
  import common._
  import util._
    import Helpers._
  import json._
    import Extraction._
    import JsonDSL._
  import mongodb.BsonDSL._

import com.ecwid.mailchimp._
  import method.helper._

object RetrieveMailchimpUsernames {
  implicit val formats = DefaultFormats

  def run = {
    println("Retrieving mailchimp usernames for users with mailchimp credentials.")

    val mcClient = new MailChimpClient
    val gadMethod = new GetAccountDetailsMethod
    gadMethod.exclude = "modules" :: "orders" :: "rewards-credits" ::
      "rewards-inspections" :: "rewards-referrals" :: "rewards-applied" :: Nil

    for {
      user <- User.findAll
      credentials <- user.credentialsFor("Mailchimp")
      token <- credentials.serviceCredentials.get("token")
    } {
      gadMethod.apikey = token

      val accountDetails = tryo(mcClient.execute(gadMethod))

      for (details <- accountDetails) {
        val serviceCredential = UserServiceCredentials("Mailchimp", details.username, Map("token" -> token))

        User.update("_id" -> user._id, "$pull" ->
          ("serviceCredentials" -> ("serviceName" -> "Mailchimp"))
        )

        User.update("_id" -> user._id, "$addToSet" ->(
          ("serviceCredentials" -> decompose(serviceCredential))
        ))
      }
    }
  }
}

Add a migration for MC usernames.

Add a migration for MC usernames.


/*
 * Copyright 2016 Nicolas Rinaudo
 *
 * 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 kantan.csv

import java.io.File
import kantan.csv.laws.discipline._
import org.scalatest.FunSuite
import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.typelevel.discipline.scalatest.Discipline

class FileCodecTests extends FunSuite with GeneratorDrivenPropertyChecks with Discipline {
  checkAll("CellCodec[File]", CellCodecTests[File].bijectiveCodec[Int, Float])
}

Add tests for the `File` codec instances.


object Test {

  @dotty.annotation.inline
  def swap[T](x: T, x_= : T => Unit, y: T, y_= : T => Unit) = {
    val t = x
    x_=(y)
    y_=(t)
  }

  def main(args: Array[String]) = {
    var x = 1
    var y = 2
    @dotty.annotation.inline def setX(z: Int) = x = z
    @dotty.annotation.inline def setY(z: Int) = y = z
    swap[Int](x, setX, y, setY)
    assert(x == 2 && y == 1)
  }
}

Test case for closure inlining

Test case for closure inlining

This test works, but closures are not currently inlined.
That's a still to do.


/**
 * Copyright (c) 2012 Kaj Magnus Lindberg (born 1979)
 */

package com.debiki.v0

/**
 * Fills in no stack trace, and is therefore cheap to throw (like simple `return`s).
 */
class QuickException extends Exception {

  // Fill in no stack trace. Calculating the stack trace is very expensive,
  // and this is a control flow exception rather than an error condition.
  // (Well, actually, the end user might have made an error, but that's
  // expected :-)  )
  override def fillInStackTrace(): Throwable = this

}

class DebikiException(val errorCode: String, val details: String)
  extends QuickException {

  override def getMessage = s"$details [error $errorCode]"

}

object DebikiException {

  def apply(errorCode: String, details: String) =
    new DebikiException(errorCode, details)

}

Add classes QuickException and DebikiException.


object Solution {
  import scala.collection.mutable.{HashSet, PriorityQueue}

  // It's a topological sort with lexicographically.
  // See http://en.wikipedia.org/wiki/Topological_sorting
  def solve(xs: Seq[String]): String = {
    val ord = new Ordering[Int] { def compare(x: Int, y: Int) = y.compare(x) }
    val minQueue = PriorityQueue[Int]()(ord)
    val previous = Array.fill(128)(HashSet.empty[Int])
    val next = Array.fill(128)(HashSet.empty[Int])
    val chars = HashSet.empty[Int]
    for (x <- xs) {
      for (c <- x) chars.add(c)

      x.zip(x.tail).foreach { case (x, y) =>
        next(x).add(y)
        previous(y).add(x)
      }
    }
    minQueue ++= chars.filter(x => previous(x).size == 0)
    var result = List.empty[Char]
    while (minQueue.size > 0) {
      val node = minQueue.dequeue
      result = node.toChar :: result
      for (i <- next(node)) {
        previous(i).remove(node)
        if (previous(i).size == 0) minQueue.enqueue(i)
      }
    }
    val s = result.mkString
    if (s.size == chars.size) s.reverse else "SMTH WRONG"
  }

  def main(args: Array[String]) {
    val t = readInt
    val logins = (1 to t).map(x => readLine)
    println(solve(logins)
  }
}

Add solution to problem 79. It's a topological_sorting with lexicographically order.


package com.negrisoli.algorithms.implementation

object ModifiedKaprekarNumbers {

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

    val solution = findKaprekar(p, q).toList match {
      case Nil => "INVALID RANGE"
      case xs => xs mkString " "
    }

    println(solution)
  }

  def findKaprekar(start: Int, end: Int) = {
    (start to end) map (_.toLong) filter { n =>
      val d = n.toString().length()
      val s = "0" + (n * n).toString
      val (l, r) = s.splitAt(s.size - d)
      l.toLong + r.toLong == n
    }
  }

}

Add Modified kaprekar numbers solution.

Add Modified kaprekar numbers solution.


object Solution {

  def main(args: Array[String]) {
    val strings = (1 to readInt).map(x => readLine.toSet))
    val intersect = strings.reduceLeft { _ & _ }
    println(intersect.size)
  }
}

Add solution to problem Gem Stones.

Add solution to problem Gem Stones.


object Solution {

  def main(args: Array[String]) {
    val t = readLine.toInt
    for (_ <- 1 to t) {
      val n = readLine
      val num = n.toLong
      println(n.map(_.asDigit).filter(x => x != 0 && num % x == 0).size)
    }
  }
}

Add solution to problem Find Digits.

Add solution to problem Find Digits.


package scala.in.programming.function_and_closure

/**
  * Scala compiler not make new stack when invoke recursion,
  * reuse same stack frames and optimize a tail recursion.
  *
  *
  * A Tail Recursion is invoke self in last position.
  *
  * Scala compiler has limit that optimize a tail recursion,
  * because implements High Level tail recursion difficult use to JVM command line.
  *
  * Scala compiler possible optimize when invoke same function.
  *
  * @author loustler
  * @since 02/08/2017 23:20
  */
object TailRecursion extends App {
  def boom(x: Int): Int =
    if ( x == 0 ) throw new RuntimeException("Boom!")
    else boom(x - 1)

  boom(3) // It'll throw RuntimeException. When you test this code has to commented.

  /**
    * This is example for Tail Recursion made by me(loustler).
    *
    * It is not exist example in PIS.
    *
    * @param x
    * @param y
    * @return
    */
  def decrease(x: Int, y: Int): Int =
    if ( y == 0 ) x else decrease(x - 1, y - 1)

  println(decrease(10, 3))
}

Add example for tail recursion

Add example for tail recursion


// needed for the tests (ci/checksourcemaps.sh)
addSbtPlugin("org.foundweekends.giter8" % "sbt-giter8" % "0.11.0-M4")

Bring back sbt-giter8 as it's needed to run the tests.


package uk.ac.wellcome.platform.merger.pairwise_transforms
import uk.ac.wellcome.models.work.internal.UnidentifiedWork

/** If we have a Miro work and a Sierra work with a single item,
  * the Sierra work replaces the Miro work (because this is metadata
  * that we can update).
  *
  * Specifically:
  *
  *   - We copy across all the identifiers from the Miro work (except
  *     those which contain Sierra identifiers)
  *   - We copy across the Miro location to the Sierra work *if* the
  *     Sierra work doesn't already have a digital location.
  *     In this case, the Sierra digital location supersedes the one
  *     from Miro.
  *
  */
object MiroSierraWorkPair extends PairwiseMerger {
  def mergeAndRedirectWork(miroWork: UnidentifiedWork,
                           sierraWork: UnidentifiedWork): Option[PairwiseResult] =
    None
}

Create the Miro/Sierra digital work pair stub


object Solution {

  def evenSubsets(even: Int, odd: Int) = {
    val p =1e9.toInt + 7
    (BigInt(2).modPow(even + math.max(0, odd - 1), p) - 1) % p
  }

  def main(args: Array[String]) {
    val _ = readLine
    val nums = readLine.split(" ").map(_.toInt)
    val even = nums.filter(_ % 2  == 0).size
    val odd = nums.size - even
    println(evenSubsets(even, odd))
  }
}

Add solution to problem A Chocolate Fiesta. The number of even non-empty subsets equals pow(2, numOfEven + max(numOfOdd - 1, 0)).


object Solution {
  import scala.collection.mutable.BitSet

  def stringReduction(s: String): String = {
    val charSet = BitSet.empty
    for (c <- s if !charSet(c)) yield {
      charSet += c
      c
    }
  }

  def main(args: Array[String]) {
    val s = readLine
    println(stringReduction(s))
  }
}

Add solution to first solution to fp/recursion domain problem. It's much elegant to for comprehension to accomplish this functionality. Will consider a recursion version.


object Solution {

  def numberOfDivisors(n: Int): Int = n match {
    case x if x <= 0 => 0
    case 1 => 1
    case x =>
      var i = 2
      while (i * i <= x && x % i != 0) {
        i += 1
      }
      if (i * i <= x) {
        var j = 1
        var num = n
        while (num % i == 0) {
          num /= i
          j += 1
        }
        j * numberOfDivisors(num)
      }
      else 2
  }

  def main(args: Array[String]) {
    for (_ <- 1 to readInt) {
      val n = readInt
      if (n % 2 == 0) println(numberOfDivisors(n / 2))
      else println(0)
    }
  }
}

Add solution to problem Sherlock and Divisors. This code smells. Should refactor it.


package ccf.server

import ccf.operation.Operation
import ccf.transport.{ClientId, ChannelId}
import ccf.messaging.ConcurrentOperationMessage
import collection.mutable.ArrayBuffer

class ClientState[T <: Operation](val channel: ChannelId, synchronizer: OperationSynchronizer[T]) {
  def receive(msg: ConcurrentOperationMessage[T]): T = {
    synchronizer.receiveRemoteOperation(msg)
  }
  def send(op: T): ConcurrentOperationMessage[T] = {
    synchronizer.createLocalOperation(op)
  }
}

Introduce client state to keep track of clients in server

The server needs to transform operations for each client and keep track
of their states. The state is encapsulated into this class.

Signed-off-by: Aki Saarinen <2c8035bb80cf98a391872dcbe797b269d759f6d9@reaktor.fi>


object Solution {

  // This function is used to generate the last digits for every complement
  // in m * n = p
  def genTails(n: Int) = {
    for { i <- 1 to n
          j <- 1 to n if j != i
          k <- j + 1 to n if k != i && (k * j - i) % 10 == 0} yield (i, j, k)
  }

  def genPandigitalProduct(n: Int, tails: (Int, Int, Int)): Vector[Int] = {
    val set = (1 to n).toSet
    val (a, b, c) = tails

    // The number of product digits will be n / 2, and we already have 1 digit
    // choosen.
    val pSize = n / 2 - 1
    val choices = set - a - b -c
    val result = scala.collection.mutable.Set.empty[Int]
    var pitr = choices.toVector.permutations
    while(pitr.hasNext) {
      val permutation = pitr.next
      val (p, remain) = permutation.splitAt(pSize)
      val product = (p.foldLeft(0) { case (x, y) => x * 10 + y }) * 10 + a
      val hasProduct =
        (0 to math.min(pSize, n - 3 -pSize)).map(remain.splitAt(_)).map {
          case (x, y) =>
            List(x :+ b, y :+ c).map(z => z.reduceLeft { 10 * _ + _ }).product
        } exists { _ == product }
      if (hasProduct) result.add(product)
    }
    result.toVector
  }

  def main(args: Array[String]) {
    val n = readLine.toInt
    val tails = genTails(n)
    val sum = tails.flatMap(genPandigitalProduct(n, _)).toSet.sum
    println(sum)
  }
}

Add solution to problem 32. This code looks complicated and should be refactored later.


/**
 * Copyright 2016 Matthew Farmer
 *
 * 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 frmr.scyig

import frmr.scyig.models._

package object pprint {
  implicit class SchedulePrettyPrinter(schedule: Seq[ScheduledRoundMatch]) {
    def pprint = {
      val trials = schedule.collect {
        case trial: Trial => trial
      }

      val byes = schedule.collect {
        case bye: Bye => bye
      }

      println("=== SCHEDULE ===\n")

      for ((trial, index) <- trials.zipWithIndex) {
        val number = index + 1
        println(s"$number.\t${trial.prosecution.name.value} from ${trial.prosecution.organization.map(_.value).getOrElse("none")}")
        println("\tvs")
        println(s"\t${trial.defense.name.value} from ${trial.defense.organization.map(_.value).getOrElse("none")}")
        println(s"\tPresiding Judge: ${trial.presidingJudge.name.value} from ${trial.presidingJudge.organization.map(_.value).getOrElse("none")}")
        if (trial.scoringJudge.isDefined) {
          println(s"\tScoring Judge: ${trial.scoringJudge.get.name.value} from ${trial.scoringJudge.get.organization.map(_.value).getOrElse("none")}")
        }
        println("")
      }

      println("=== BYES ===\n")

      println(byes.mkString(","))
    }
  }
}

Add some pretty printer implicits for console testing.


package hercules.utils

import org.scalatest.FlatSpec
import org.scalatest.Matchers
import java.io.File
import java.net.URI
import java.net.InetAddress

class ConversionsTest extends FlatSpec with Matchers {

  val file = new File("/test/file")
  val expected = "file://" + InetAddress.getLocalHost().getHostName() + "/test/file"

  "A file2URI conversion" should "correctly convert a file to a URI " in {

    val actual = Conversions.file2URI(file)
    assert(expected === actual.toString())

  }

  it should "do so implicitly if imported" in {

    import Conversions.file2URI

    val actual: URI = file
    assert(expected === actual.toString())

  }

}

Add unit test for conversions

Add unit test for conversions


package com.socrata.soda.server.export

import java.io.{DataInputStream, FileInputStream}
import org.velvia.MsgPack
import org.velvia.MsgPackUtils._
import com.vividsolutions.jts.io.WKBReader

/**
 * App that takes a SoQLPack binary file and dumps out the header and rows
 * This should be moved into part of the main instead of test package, but this would
 * mess up the java -jar soda-fountain-assembly experience...
 *
 * Run in the soda-fountain directory like:
 *   sbt 'soda-fountain-lib/test:run com.socrata.soda.server.export.SoQLPackDumper /tmp/soqlpack.in'
 *
 * Sorry wanted to make this work on STDIN but SBT is not cooperating.  Fix this once we
 * fix the SBT assembly issue.
 */
object SoQLPackDumper extends App {
  // val dis = new DataInputStream(System.in)
  val dis = new DataInputStream(new FileInputStream(args(0)))
  val headerMap = MsgPack.unpack(dis, MsgPack.UNPACK_RAW_AS_STRING).asInstanceOf[Map[String, Any]]
  println("--- Schema ---")
  headerMap.foreach { case (key, value) => println("%25s: %s".format(key, value)) }
  val types = headerMap.as[Seq[Map[String, String]]]("schema").map { m => m("t") }

  println("\n---")

  val reader = new WKBReader

  while (dis.available > 0) {
    // Don't unpack raw byte arrays as Strings - they might be Geometries or other blobs
    val row = MsgPack.unpack(dis, 0).asInstanceOf[Seq[Any]]
    for (i <- 0 until row.length) {
      if (Set("point", "multiline", "multipolygon") contains types(i)) {
        print(reader.read(row(i).asInstanceOf[Array[Byte]]))
      } else if (types(i) == "text") {
        print(new String(row(i).asInstanceOf[Array[Byte]]))
      } else {
        print(row(i).toString)
      }
      print(", ")
    }
    println
  }

}

Add an app to dump out SoQLPack output... only from a file for now


object Solution {

  def nonMersennePrimeRSD(a: Int, b: Int, c: Int, d: Int, p: Long): Long = {
    // Fucking BigInt to long overflow! Must mod first.
    (a * BigInt(b).modPow(c, p) + d).mod(p).toLong
  }

  def main(args: Array[String]) {
    val t = readInt
    val p = 1e12.toLong
    var sum = 0L
    for (i <- 1 to t) {
      val Array(a, b, c, d) = readLine.split(" ").map(_.toInt)
      sum = (sum + nonMersennePrimeRSD(a, b, c, d, p)) % p
    }
    println("%012d".format(sum))
  }
}

Add solution to problem 97.

Add solution to problem 97.


/*
 * Copyright 2014–2020 SlamData Inc.
 *
 * 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 quasar.contrib.cats.data

import quasar.contrib.scalaz.{MonadError_, MonadTell_}

import cats.data.Kleisli

object kleisli {
  implicit def catsDataKleisliMonadError_[E, F[_]: MonadError_[?[_], E], A]
      : MonadError_[Kleisli[F, A, ?], E] =
    new MonadError_[Kleisli[F, A, ?], E] {
      def raiseError[B](e: E): Kleisli[F, A, B] =
        Kleisli(_ => MonadError_[F, E].raiseError[B](e))

      def handleError[B](fb: Kleisli[F, A, B])(f: E => Kleisli[F, A, B]): Kleisli[F, A, B] =
        Kleisli(a => MonadError_[F, E].handleError(fb(a))(e => f(e)(a)))
    }

  implicit def catsDataKleisliMonadTell[W, F[_]: MonadTell_[?[_], W], A]
      : MonadTell_[Kleisli[F, A, ?], W] =
    new MonadTell_[Kleisli[F, A, ?], W] {
      def writer[B](w: W, b: B): Kleisli[F, A, B] =
        Kleisli(_ => MonadTell_[F, W].writer(w, b))
    }
}

Add contrib instances for cats.data.Kleisli


libraryDependencies += "com.lihaoyi" % "ammonite" % "0.8.1" % "test" cross CrossVersion.full
initialCommands in (Test, console) := """ammonite.Main().run()"""

Add Ammonite REPL to SBT projects

Add Ammonite REPL to SBT projects

http://www.cakesolutions.net/teamblogs/improving-workflow-with-local-sbt-files


package quotidian.web

import javax.servlet.http.{HttpServlet, HttpServletRequest => Request, HttpServletResponse => Response}
import quotidian.{Config,Logging}
import quotidian.model.Quote

class QuoteIndexServlet extends HttpServlet with Logging {
	val Labels = Config.Labels
	override def doPost(request:Request, response:Response) {
		val http = HttpHelper(request,response)
		val id = http(Quote.Id)
		val text = http(Quote.Text,Labels(Quote.Text))
		val source = http(Quote.Source,Labels(Quote.Source))
		val context = http(Quote.Context,Labels(Quote.Context))
		try {
			Config.qc.index(Quote(id.get,text.get,source.get,context.get))
			response.setStatus(Response.SC_OK)
		} catch {
			case e => response.setStatus(Response.SC_INTERNAL_SERVER_ERROR)
		}
	}
}

Add Servlet to handle indexing tasks

Add Servlet to handle indexing tasks


package com.negrisoli.algorithms.implementation

object SherlockAndSquares {

  def main(args:Array[String]) {
    val sc = new java.util.Scanner(System.in)
    val nTests = sc.nextInt()
    for (i <- 0 to nTests-1) {
      val begin = sc.nextInt()
      val end = sc.nextInt()

      var i =  math.sqrt(begin).ceil.toInt
      var j =  math.sqrt(end).floor.toInt
      printf("%d\n", j - i + 1)
    }
  }

}

Add sherlock and squares solution.

Add sherlock and squares solution.


package uk.ac.wellcome.platform.ingestor.fixtures

import com.sksamuel.elastic4s.http.HttpClient
import org.scalatest.Suite
import uk.ac.wellcome.monitoring.MetricsSender
import uk.ac.wellcome.monitoring.test.fixtures.{MetricsSender => MetricsSenderFixture}
import uk.ac.wellcome.platform.ingestor.services.WorksIndexer
import uk.ac.wellcome.test.fixtures._

trait WorkIndexerFixture extends Akka with MetricsSenderFixture { this: Suite =>
  def withWorkIndexer[R](
    esType: String,
    elasticClient: HttpClient,
    metricsSender: MetricsSender)(testWith: TestWith[String, R]): R = {
    val workIndexer = new WorkIndexer(
      esType = esType,
      elasticClient = elasticClient,
      metricsSender = metricsSender
    )

    testWith(workIndexer)
  }

  def withWorkIndexerFixtures[R](esType: String, elasticClient: HttpClient)(testWith: TestWith[String, R]): R = {
    withActorSystem { actorSystem =>
      withMetricsSender(actorSystem) { metricsSender =>
        withWorkIndexer(esType, elasticClient, metricsSender) { workIndexer =>
          testWith(workIndexer)
        }
      }
    }
  }
}

Create a new WorkIndexer fixture

Create a new WorkIndexer fixture


package ch.usi.inf.l3.sana.oberon0.names

import ch.usi.inf.l3.sana
import sana.ooj
import sana.tiny

import tiny.names.Name

trait StdNames extends ooj.names.StdNames {
  val UNRESOLVED           = Name("<UNRESOLVED>")

  val NEW_TYPE_NAME_BASE   = Name("$NEW_TYPE_NAME_")
}

object StdNames extends StdNames

Add standard names for oberon

Add standard names for oberon


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

        println("MEDIA = %.5f".format((a * 3.5 + b * 7.5) / 11.0))
    }
}

Solve Average 1 in scala

Solve Average 1 in scala


abstract class A {
  val s: Int
  assert(s == 1)
}

class B(val s: Int) extends A

object Test extends B(1) {
  def main(args: Array[String]): Unit = {
    s
  }
}

Test that fields are correctly set before super constructor is called.


import stainless.lang._
import stainless.annotation._

object MutableTuple {
  case class Foo(var value: BigInt)
  case class Bar(var value: BigInt)

  def t1(pair: (Foo, Bar)) = {
    pair._1.value = 1
    assert(pair._1.value == 1)
  }
}

Add benchmark for tuple with mutable types


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

package doodle
package syntax

import doodle.algebra.{Picture, Size}

trait SizeSyntax {
  implicit class SizePictureOps[Alg[x[_]] <: Size[x], F[_], A](
      picture: Picture[Alg, F, A]) {
    def height: Picture[Alg, F, Double] =
      Picture { implicit algebra: Alg[F] =>
        algebra.height(picture(algebra))
      }

    def width: Picture[Alg, F, Double] =
      Picture { implicit algebra: Alg[F] =>
        algebra.width(picture(algebra))
      }

    def size: Picture[Alg, F, (Double, Double)] =
      Picture { implicit algebra: Alg[F] =>
        algebra.size(picture(algebra))
      }
  }
}

Add syntax for Size algebra

Add syntax for Size algebra

This syntax is not much use without at least a Functor constraint on the
F in Picture


object Solution {

  def main(args: Array[String]) {
    val n = readLine.toInt
    val nums = readLine.split(" ").map(_.toInt)
    val sortedNums = nums.sorted
    val diffs = (1 until n).map(i => math.abs(sortedNums(i) - sortedNums(i - 1)))
    val minDiff = diffs.min
    val pairs = (0 until n - 1).flatMap { i =>
      if (diffs(i) == minDiff) Some(sortedNums(i) + " " + sortedNums(i + 1))
      else None
    }
    println(pairs.mkString(" "))
  }
}

Add solution to problem Closest Numbers.


object Solution {

  def main(args: Array[String]) {
    val n = readLine.toInt
    val start = math.pow(10, n - 1)
    val end = start * 10
    val intStart = math.pow(start, 1d / n).toLong - 1
    val intEnd = math.pow(end, 1d / n).toLong + 1
    for (i <- intStart until intEnd) {
      val num = BigInt(i).pow(n)
      if (num >= BigInt(10).pow(n - 1) && num < BigInt(10).pow(n)) println(num)
    }
  }
}

Add solution to problem 63. 1e19 will overflow for Long value. Should be more careful and view it later.


package websocket4s.spray

import akka.actor.{ActorSystem, Props, ActorRef}
import akka.io.Tcp
import akka.util.Timeout
import spray.can.websocket.UpgradedToWebSocket
import spray.can.websocket.frame.TextFrame
import spray.routing.Route

import scala.concurrent._
import scala.concurrent.duration._

/**
 * Created by namnguyen on 6/12/15.
 */
object SprayServer {
  implicit val system = ActorSystem("on-spray-websocket")

  def main(args:Array[String]):Unit = {
    val workerProps = (conn: ActorRef) =>
      Props(classOf[WebSocketActor], conn)
    implicit val timeout = Timeout(2 second)
    val (server, command) = WebSocketServer.start("127.0.0.1", 8080, workerProps)
    val binding = Await.result(command, 2 second) match {
      case bound: Tcp.Bound => bound
      case other => throw new Exception(s"failed to bring up server $other")
    }
    val address = binding.localAddress
    println(address.getHostName)
    println(address.getPort)
  }
}

class WebSocketActor(conn:ActorRef) extends SimpleWebSocketComboWorker(conn){
  override def route: Route = path("hello") {
    get {
      complete {

Greetings!

      }
    }
  }

  /** User-defined websocket handler. */
  override def websockets: Receive = {
    case UpgradedToWebSocket => println("connection upgrade")
    case TextFrame(v) => send(TextFrame(v))
  }
}

Add Spray main file to run the socket server - For Testing


/* sbt -- Simple Build Tool
 * Copyright 2008, 2009 Mark Harrah
 */
package xsbt

import xsbti.Logger
import scala.tools.nsc.{ GenericRunnerCommand, Interpreter, InterpreterLoop, ObjectRunner, Settings }
import scala.tools.nsc.interpreter.InteractiveReader
import scala.tools.nsc.reporters.Reporter
import scala.tools.nsc.util.ClassPath

import dotty.tools.dotc.repl.REPL
import dotty.tools.dotc.repl.REPL.Config

class ConsoleInterface {
  def commandArguments(
    args: Array[String],
    bootClasspathString: String,
    classpathString: String,
    log: Logger
  ): Array[String] = args

  def run(args: Array[String],
          bootClasspathString: String,
          classpathString: String,
          initialCommands: String,
          cleanupCommands: String,
          loader: ClassLoader,
          bindNames: Array[String],
          bindValues: Array[Any],
          log: Logger
  ): Unit = {
    val completeArgs =
      args                                    :+
      "-bootclasspath" :+ bootClasspathString :+
      "-classpath"     :+ classpathString

    println("Starting dotty interpreter...")
    val repl = ConsoleInterface.customRepl(
      initialCommands :: Nil,
      cleanupCommands :: Nil,
      bindNames zip bindValues
    )
    repl.process(completeArgs)
  }
}

object ConsoleInterface {
  def customConfig(
    initCmds: List[String],
    cleanupCmds: List[String],
    boundVals: Array[(String, Any)]
  ) = new Config {
    override val initialCommands: List[String] = initCmds
    override val cleanupCommands: List[String] = cleanupCmds
    override val boundValues: Array[(String, Any)] = boundVals
  }

  def customRepl(cfg: Config): REPL = new REPL {
    override lazy val config = cfg
  }

  def customRepl(
    initCmds: List[String],
    cleanupCmds: List[String],
    boundVals: Array[(String, Any)]
  ): REPL = customRepl(customConfig(initCmds, cleanupCmds, boundVals))
}

Add console interface for sbt

Add console interface for sbt


package org.collperf

trait PerformanceTest extends DSL {

  def executor: Executor

  def reporter: Reporter

}

object PerformanceTest {

  object Executor {

    trait LocalMin extends PerformanceTest {
      lazy val executor = execution.LocalExecutor(Aggregator.min)
    }

    trait NewJvmMedian extends PerformanceTest {
      lazy val executor = execution.NewJvmExecutor(Aggregator.average)
    }

  }

  object Reporter {

    trait Console extends PerformanceTest {
      lazy val reporter = new reporting.ConsoleReporter
    }

    trait Chart extends PerformanceTest {
      lazy val reporter = new reporting.ChartReporter("", reporting.ChartReporter.ChartFactory.XYLine())
    }

    trait Html extends PerformanceTest {
      lazy val reporter = new reporting.HtmlReporter(reporting.HtmlReporter.Renderer.all: _*)
    }

  }

}

package org.collperf

trait PerformanceTest extends DSL {

  def executor: Executor

  def reporter: Reporter

}

object PerformanceTest {

  object Executor {

    trait LocalMin extends PerformanceTest {
      lazy val executor = execution.LocalExecutor(Aggregator.min, new org.collperf.Executor.Measurer.Default())
    }

    trait NewJvmMedian extends PerformanceTest {
      lazy val executor = execution.NewJvmExecutor(Aggregator.average, new org.collperf.Executor.Measurer.Default())
    }

  }

  object Reporter {

    trait Console extends PerformanceTest {
      lazy val reporter = new reporting.ConsoleReporter
    }

    trait Chart extends PerformanceTest {
      lazy val reporter = new reporting.ChartReporter("", reporting.ChartReporter.ChartFactory.XYLine())
    }

    trait Html extends PerformanceTest {
      lazy val reporter = new reporting.HtmlReporter(reporting.HtmlReporter.Renderer.all: _*)
    }

  }

}

Fix a bug in previous commit.

Fix a bug in previous commit.


import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO

object Dilation{

  /**
	    * Method to dilate an Image it will expand the pixels in the image it will fill all the missing pixel in the image
	    * @param Image,@param structuring_element @param typeImage @param size_of_median_filter
	    * @return
      *structuring element tells in which shape you want to expand the pixel
      *Median filter is used in this algorithm
    	*/

	def min_occurance(list : List[Int]) : Int = {
        	list.sorted(Ordering.Int)
		var len : Int = list.length
		var min : Int = len * 2
		var count : Int = 1
		var index : Int  = 0
		var pixel : Int = 0
		while ( index < len) {
			var index2 : Int = index
			while (index2 + 1 < len && list(index) == list(index2 + 1)) {
				count = count + 1
				index2 = index2 + 1
				index = index2
			}
			if (min > count) {
			    pixel = list(index2)
			    min = count
			}
			index = index + 1
			count  = 1
		}
		return pixel
	}

	def dilation(image : BufferedImage, struct : Array[Array[Int]], image_type : String, median_value : Int) : BufferedImage = {
		var height : Int = image.getHeight();
		var width : Int = image.getWidth();
		var dilation_image = image
		if (image_type == "png") {
			var image1 = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB)
			dilation_image = image1
		 } else {
			var image1 = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)
			dilation_image = image1
		}
		var pixel : Int = 0
		var i : Int = 0
		var col : Int = 0
		var row : Int = 0
		for (i <- 0 to height - 1) {
			for (j <- 0 to width - 1) {
				var list : List[Int] = List()
				var count : Int = 0
		    		if ((i - median_value >= 0) && (i + median_value < height) && (j - median_value >= 0) && (j + median_value < width)) {
					row = 0
					col = 0
					for (k <- i - median_value to i + median_value) {
					 	for (l <- j - median_value to j + median_value) {
							pixel = image.getRGB(l, k) * struct(col)(row)
							list = pixel +: list
							col = col + 1
						}
						row = row + 1
						col = 0
					}
					pixel = min_occurance(list)
				} else {
					pixel = image.getRGB(j, i)
				}
				dilation_image.setRGB(j, i, pixel)
			}
		}
		return dilation_image
	}
}

Expand pixels in an Image using Median Filter


package com.twitter.scalding

object TypedArgs {
  implicit final def typedArgs(args: Args): TypedArgs = new TypedArgs(args)
}

class TypedArgs(val args: Args) {

  private def asType[T](f: (String, String) => T): (String, String) => T = {
    (key: String, value: String) =>
      {
        try {
          f(key, value)
        } catch {
          case e: NumberFormatException =>
            throw ArgsException("Invalid value %s for --%s".format(value, key))
        }
      }
  }

  private def asInt = asType((name, value) => java.lang.Integer.parseInt(value))
  private def asDouble = asType((name, value) => java.lang.Double.parseDouble(value))
  private def asLong = asType((name, value) => java.lang.Long.parseLong(value))
  private def asFloat = asType((name, value) => java.lang.Float.parseFloat(value))

  def int(key: String, default: Int): Int = {
    args.optional(key).map(asInt(key, _)).getOrElse(default)
  }

  def int(key: String): Int = {
    asInt(key, args(key))
  }

  def long(key: String, default: Long): Long = {
    args.optional(key).map(asLong(key, _)).getOrElse(default)
  }

  def long(key: String): Long = {
    asLong(key, args(key))
  }

  def float(key: String, default: Float): Float = {
    args.optional(key).map(asFloat(key, _)).getOrElse(default)
  }

  def float(key: String): Float = {
    asFloat(key, args(key))
  }

  def double(key: String, default: Double): Double = {
    args.optional(key).map(asDouble(key, _)).getOrElse(default)
  }

  def double(key: String): Double = {
    asDouble(key, args(key))
  }

}

Add helpers for typed args

Add helpers for typed args


///////////////////////////////////////////////////////////////////////////////
//  UserFrequency.scala
//
//  Copyright (C) 2013 Ben Wing, The University of Texas at Austin
//
//  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 opennlp.textgrounder
package gridlocate

import scala.collection.mutable

import util.collection._
import util.print.{errprint, warning}

/**
 * A class used to implement user-frequency calculations. We are passed in
 * triples of (term, user, cell) and eventually can retrieve counts of unique
 * users for a given term in a cell. For efficiency, both term and user must
 * be given as integers; use memoization as necessary to map them down.
 */
class UserFrequencyModel[Co](
  val grid: GeoGrid[Co]
) {
  // For each cell, we have a set listing the term-user pairs seen. We
  // encode them as a Long for speed and memory savings.
  val term_user_pairs = setmap[GeoCell[Co], Long]()

  /**
   * Record an occurrence of a given term token seen, along with the user
   * generating the token and the cell it goes in.
   */
  def add_triple(term: Int, user: Int, cell: GeoCell[Co]) {
    // This is a bit tricky. We need to combine two ints into a long, but to do
    // this properly we need to treat the int that goes into the lower 32 bits
    // as unsigned. Java (hence Scala) doesn't provide unsigned integers, but
    // an unsigned cast to long can be faked by anding the int with
    // 0xFFFFFFFFL, which effectively converts the int to a long and then
    // strips off the upper 32 bits, which get set if the int is negative.
    // These issues don't arise with the int that goes into the higher
    // portion of the long, nor do they arise converting back to ints.
    term_user_pairs(cell) += (term << 32L) + (user & 0xFFFFFFFFL)
  }

  /**
   * Return a map from memoized words to counts of the unique users for a
   * given word in a given cell.
   */
  def get_term_counts(cell: GeoCell[Co]) = {
    val terms = term_user_pairs(cell).map {
      pair => (pair >> 32).toInt
    }
    val map = intmap[Int]()
    for (term <- terms)
      map(term) += 1
    map
  }
}

Add some code to help implement a user-frequency model (O'Hare Murdock 2012)


package uk.ac.wellcome.models.transformable.sierra

import org.scalatest.{FunSpec, Matchers}

class SierraRecordNumberTest extends FunSpec with Matchers {
  describe("withCheckDigit") {
    it("handles a bib example from the Sierra docs") {
      SierraBibNumber("1024364").withCheckDigit shouldBe "b10243641"
    }

    it("handles an item example from the catalogue") {
      SierraItemNumber("1828888").withCheckDigit shouldBe "i18288881"
    }

    it("adds an 'x' where necessary") {
      SierraItemNumber("1840974").withCheckDigit shouldBe "i1840974x"
    }
  }

  describe("withoutCheckDigit") {
    it("handles a bib example correctly") {
      SierraBibNumber("1024364").withoutCheckDigit shouldBe "1024364"
    }

    it("handles an item example correctly") {
      SierraItemNumber("1828888").withoutCheckDigit shouldBe "1828888"
    }
  }

  it("throws an error if passed a Sierra ID which is non-numeric") {
    assertStringFailsValidation("abcdefg")
  }

  it("throws an error if passed a Sierra ID which is too short") {
    assertStringFailsValidation("123")
  }

  it("throws an error if passed a Sierra ID which is too long") {
    assertStringFailsValidation("12345678")
  }

  private def assertStringFailsValidation(recordNumber: String) = {
    val caught = intercept[IllegalArgumentException] {
      SierraBibNumber(recordNumber)
    }

    caught.getMessage shouldEqual s"requirement failed: Not a 7-digit Sierra record number: $recordNumber"
  }
}

Add some test cases for SierraRecordNumber


object Solution {

  def canBePalindrome(s: String): Boolean = {
    val charCount = Array.fill(256)(0)
    for (c <- s) charCount(c) += 1
    charCount.filter(_ % 2 != 0).size <= 1
  }

  def main(args: Array[String]) {
    val s = readLine
    println(if (canBePalindrome(s)) "YES" else "NO")
  }
}

Add solution to problem Game of Thrones - I.


/**
 * reactive-streams
 *
 * Copyright 2016 juanitodread
 *
 * 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 actors

import akka.actor.Actor
import akka.actor.ActorRef
import akka.actor.Props

import play.api.Logger
import play.api.Play.current
import play.api.libs.concurrent.Execution.Implicits._
import play.api.libs.iteratee.Concurrent
import play.api.libs.iteratee.Enumerator
import play.api.libs.iteratee.Iteratee
import play.api.libs.json.JsValue
import play.api.libs.oauth.OAuthCalculator
import play.api.libs.ws.WS

import util.Common

/**
 * Actor to stream tweets to a web socket
 *
 * @author juanitodread
 *
 */
class TwitterStreamer(out: ActorRef, track: String) extends Actor {
  final val logger = TwitterStreamer.logger

  def receive = {
    case "subscribe" =>
      logger.info("Received subscription from a client")
      TwitterStreamer.subscribe(out, track)
  }
}

object TwitterStreamer {
  final val logger = Logger("TwitterStreamer")

  private var broadcastEnumerator: Option[Enumerator[JsValue]] = None

  def props(out: ActorRef, track: String) = Props(new TwitterStreamer(out, track))

  def connect(track: String): Unit = {
    val url = "https://stream.twitter.com/1.1/statuses/filter.json"
    Common.oAuthAccess.map {
      case (key, token) =>

        // Create iteratee and enumerator
        val (iteratee, enumerator) = Concurrent.joined[Array[Byte]]

        // Send enumerator to our newTweetStream to transform to
        // Enumerator of Tweet
        val tweetStream = Common.newTweetStream(enumerator)

        val (be, _) = Concurrent.broadcast(tweetStream)
        broadcastEnumerator = Some(be)

        WS.url(url)
          .sign(OAuthCalculator(key, token))
          .postAndRetrieveStream(Map("track" -> Seq(track))) { response =>
            logger.info(s"Status: ${response.status}")
            iteratee
          }.map { _ =>
            logger.info("Twitter stream closed")
          }
    } getOrElse {
      logger.error("Credentials not found")
    }
  }

  def subscribe(out: ActorRef, track: String): Unit = {
    if (broadcastEnumerator.isEmpty) {
      connect(track)
    }

    val twitterClient = Iteratee.foreach[JsValue] { tweet => out ! tweet }

    broadcastEnumerator.foreach { enumerator =>
      enumerator run twitterClient
    }
  }

}

Create Actor to stream tweets to a websocket


package mixins;

import scala.collection.mutable._;

class Collections extends HashSet[Int] with ObservableSet[Int,Collections] {
  override def +=(elem: Int): Unit = super.+=(elem);
  override def -=(elem: Int): Unit = super.-=(elem);
  override def clear: Unit = super.clear;

}

object collections extends Collections;

class Collections1 extends HashSet[Int] with ObservableSet[Int,Collections1];
object collections1 extends Collections1;

Test case for abstract override bug in NSC.


package computerdatabase

import io.gatling.core.Predef._
import io.gatling.http.Predef._
import scala.concurrent.duration._

class CatalogueAPiSimulation extends Simulation {

  val httpConf = http.baseUrl("https://api-stage.wellcomecollection.org/catalogue/v2/works")

  // This was taken from https://github.com/dwyl/english-words
  // and copied in the user-files/resources. I'm not committing
  // it because it's about 4MB
  val wordsFeeder = csv("words.csv").random()

  val scn = scenario("BasicSimulation")
    .feed(wordsFeeder)
    .exec(http("all_works").get("/"))
    .exec(http("search").get("/")
      .queryParam("query", "${word}"))
    .repeat(5)(feed(wordsFeeder).exec(http("search images").get("/")
      .queryParam("workType","q,k")
      .queryParam("items.locations.locationType","iiif-image")
      .queryParam("query","${word}")
      .queryParam("pageSize","100")))

  setUp( // 11
    scn.inject(constantUsersPerSec(2) during (20 minutes)) // 12
  ).protocols(httpConf) // 13
}

Add simple simulation used to test stage api response times


//
// FileValueLocator.scala -- Scala class FileValueLocator
// Project PorcE
//
// Created by jthywiss on Sep 20, 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.run.porce.distrib

/** A ValueLocator that looks up java.io.File names in a filename-to-location
  * Map.
  *
  * @author jthywiss
  */
class FileValueLocator(execution: DOrcExecution) extends ValueLocator {
  val filenameLocationMap = Map(
      "adventure-1.txt" -> 1,
      "adventure-2.txt" -> 2,
      "adventure-3.txt" -> 3,
      "adventure-4.txt" -> 4,
      "adventure-5.txt" -> 5,
      "adventure-6.txt" -> 6,
      "adventure-7.txt" -> 7,
      "adventure-8.txt" -> 8,
      "adventure-9.txt" -> 9,
      "adventure-10.txt" -> 10,
      "adventure-11.txt" -> 11,
      "adventure-12.txt" -> 12
      )

  override val currentLocations: PartialFunction[Any, Set[PeerLocation]] = {
    case f: java.io.File if filenameLocationMap.contains(f.getName) => Set(execution.locationForFollowerNum(filenameLocationMap(f.getName)))
  }

  override val permittedLocations: PartialFunction[Any, Set[PeerLocation]] = {
    case f: java.io.File if filenameLocationMap.contains(f.getName) => Set(execution.locationForFollowerNum(filenameLocationMap(f.getName)))
  }

}

Add file to location policy. Broaden shouldInterceptInvocation.

Add file missing in dc9dde6be779816de5de46ec860403150c1b65fb

Add the FileValueLocator class that implements a location policy map for
java.io.File instances.

shouldInterceptInvocation previously only asked the execution about the
location of values that implemented LocationPolicy, but it now checks
any value.


package kantan.xpath.scalaz

import kantan.xpath.{DecodeResult, NodeDecoder}

import scalaz.{Maybe, -\/, \/, \/-}

object codecs {
  implicit def or[A, B](implicit da: NodeDecoder[A], db: NodeDecoder[B]): NodeDecoder[A \/ B] = NodeDecoder { node =>
    da.decode(node).map(a => -\/(a)).orElse(db.decode(node).map(b => \/-(b)))
  }

  implicit def maybe[A](implicit da: NodeDecoder[A]): NodeDecoder[Maybe[A]] = NodeDecoder { node =>
    da.decode(node) match {
      case DecodeResult.NotFound => DecodeResult.success(Maybe.empty)
      case ra => ra.map(Maybe.just)
    }
  }
}

Add NodeDecoder instance for \/ and Maybe.


package cloud4things.cli.configuration

import cloud4things.cli.eventcycle.EventCycle
import cloud4things.cli.reader.Reader

class Configuration(name: String) {

  // List of Readers
  private val readers = new scala.collection.mutable.Map[String, Reader]() {
    override def +=(kv: (String, Reader)): this.type = ???

    override def -=(key: String): this.type = ???

    override def get(key: String): Option[Reader] = ???

    override def iterator: Iterator[(String, Reader)] = ???
  }

  // List of EventCycles
  private val eventCycles = new scala.collection.mutable.Map[String, EventCycle]() {
    override def +=(kv: (String, EventCycle)): this.type = ???

    override def -=(key: String): this.type = ???

    override def get(key: String): Option[EventCycle] = ???

    override def iterator: Iterator[(String, EventCycle)] = ???
  }

  // Add a new reader to a configuration
  def addReader(reader: Reader) = {
    readers += (reader.readerName -> reader)
  }

  // Delete a Reader with name {name}
  def deleteReader(name: String) = {
    readers -= name
  }

  // List all Readers of a given smart-place
  def showReaders() = {
    println("Printing readers ....")
    readers.foreach( r => println (r._1))
  }

  // Add a new EventCycle to a configuration
  def addEventCycle(eventCycle: EventCycle) {
    eventCycles += (eventCycle.eventName -> eventCycle)
  }

  // Delete a EventCycle with name {name}
  def deleteEventCycle(name: String) = {
    eventCycles -= name
  }

  // List all EventCycles
  def showEventCycles() = {
    println("Printing event cycles ....")
    eventCycles.foreach( e => println (e._1))
  }

}

Add a configuration module that allows to store the configuration of different smart-places.


package honor

import org.scalatest.FunSuite

class HonorsSuite extends FunSuite {
  test("Honor category ids are unique") {
    val categories = Honors.values.map(_.category)
    assert(categories.size === categories.distinct.size)
  }
}

Add honor categories unique test

Add honor categories unique test


import scala.tools.nsc._

object Test {

  // works
  def mkReifier(global: Global)(typer: global.analyzer.Typer) = typer

/*
<console>:10: error: not found: value global
      class Reifier(global: Global)(typer: global.analyzer.Typer) { }
*/
  class Reifier(global: Global)(typer: global.analyzer.Typer) { }

}

Add test file in pending/pos

Add test file in pending/pos


package operation

import java.lang.AssertionError

/**
  * @author loustler
  * @since 01/20/2017 20:51
  */
object Order extends App{
  assert( ("Hello" + " World") == "Hello World", "print msg when assertion fail")

  assert( 2 + 5 * 3 == 17)

  try {
    assert( 2 + 5 * 3 == 13, "Fail")
  } catch {

    case e: AssertionError => println(e.getMessage)
  } finally {
    println("Catch Error")
  }

}

Add simple example for order of operation

- plus and asterisk


/**
 * Illustrates a simple map partition to parse JSON data in Scala
 * Loads the data into a case class with the name and a boolean flag
 * if the person loves pandas.
 */
package com.oreilly.learningsparkexamples.scala

import org.apache.spark._
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.DeserializationFeature

case class Person(name: String, lovesPandas: Boolean)

object BasicParseJsonWithJackson {

  def main(args: Array[String]) {
    if (args.length < 3) {
      println("Usage: [sparkmaster] [inputfile] [outputfile]")
      exit(1)
      }
    val master = args(0)
    val inputFile = args(1)
    val outputFile = args(2)
    val sc = new SparkContext(master, "BasicParseJsonWithJackson", System.getenv("SPARK_HOME"))
    val input = sc.textFile(inputFile)
    val parsed = input.map(Json.parse(_))
    // We use asOpt combined with flatMap so that if it fails to parse we
    // get back a None and the flatMap essentially skips the result.
    val result = parsed.flatMap(record => {
      try {
        val mapper = new ObjectMapper with ScalaObjectMapper
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        mapper.registerModule(DefaultScalaModule)
        val person = mapper.readValue(record, classOf[Person])
        Some(record)
      } catch {
        case e: Exception => None
      }
      })
    result.filter(_.lovesPandas).map(Json.toJson(_)).saveAsTextFile(outputFile)
    }
}

Add basic json parsing with jackson example since we might switch to that in ch3


object Solution {

  def maxSumOfContiguousSubarray(nums: Array[Int]): Int = {
    var sum = 0
    var result = sum
    for (n <- nums){
      sum += n
      result = result max sum
      if (sum <= 0) sum = 0
    }
    result
  }

  def main(args: Array[String]) {
    val t = readLine.toInt
    for (_ <- 1 to t) {
      val _ = readLine
      val nums = readLine.split(" ").map(_.toInt)
      val maxSum = nums.filter(_ >= 0).sum
      if (maxSum == 0) {
        val max = nums.max
        println(max + " " + max)
      }
      else println(maxSumOfContiguousSubarray(nums) + " " + maxSum)
    }
  }
}

Add solution to problem the Maximum Subarray.


object Solution {

  // see http://en.wikipedia.org/wiki/Euler%27s_criterion
  def canQuadraticResidueMod(a: Int, m: Int): Boolean = {
    if (m == 2 || a == 0) true
    else {
      BigInt(a).modPow((m - 1) / 2, m) == 1
    }
  }

  def main(args: Array[String]) {
    for (_ <- 1 to readInt) {
      val Array(a, m) = readLine.split(" ").map(_.toInt)
      if (canQuadraticResidueMod(a, m)) println("YES") else println("NO")
    }
  }
}

Add solution to problem Euler's Criterion.


package cc.factorie.app.nlp.lemma
import cc.factorie._
import cc.factorie.app.nlp._

class WordNetLemmatizer(val wordNetDir:String) extends DocumentAnnotator {
  val map = new scala.collection.mutable.HashMap[String,String] {
    override def default(key:String): String = key
  }
  for (f <- Seq("adj.exc", "adv.exc", "noun.exc", "verb.exc")) {
    for (line <- scala.io.Source.fromFile(new java.io.File(wordNetDir+"/"+f)).getLines) {
      val fields = line.split(" ")
      if (fields(0).indexOf('_') == -1) // For now skip multi-word phrases (indicated by underscore in WordNet)
        map(fields(0)) = fields(1)
    }
  }
  def lemma(raw:String): String = {
    map(raw.toLowerCase)
    // TODO Still needs simple de-pluralization and other rules
  }
  def process1(document:Document): Document = {
    for (token <- document.tokens) token.attr += new WordNetTokenLemma(token, lemma(token.string))
    document
  }
  override def tokenAnnotationString(token:Token): String = { val l = token.attr[WordNetTokenLemma]; l.value }
  def prereqAttrs: Iterable[Class[_]] = List(classOf[Token])
  def postAttrs: Iterable[Class[_]] = List(classOf[WordNetTokenLemma])
}
//object WordNetLemmatizer extends WordNetLemmatizer

class WordNetTokenLemma(token:Token, s:String) extends TokenLemma(token, s)

Add skeleton of a WordNet-based Lemmatizer.


import stainless.lang._
import stainless.annotation._

object IntSet {
  case class Empty() extends IntSet
  case class Node(left: IntSet,
                  elem: Int,
                  right: IntSet) extends IntSet

  sealed abstract class IntSet {
    def incl(x: Int): IntSet = this match {
      case Empty() => Node(Empty(),x,Empty())
      case Node(left, elem, right) =>
        if (x < elem) Node(left incl x, elem, right)
        else if (x > elem) Node(left, elem, right incl x)
        else this
    }

    def contains(x: Int): Boolean = this match {
      case Empty() => false
      case Node(left, elem, right) =>
        if (x < elem) left contains x
        else if (x > elem) right contains x
        else true
    }

    def P1(x: Int): Boolean = {
      !(Empty() contains x)
    }.holds

    def P2(s: IntSet, x: Int): Boolean = {
      (s incl x) contains x
    } holds because (s match {
      case Empty() => true
      case Node(left, elem, right) =>
        if (x < elem) P2(left, x)
        else if (x > elem) P2(right, x)
        else true
    })

    def P3(s: IntSet, x: Int,  y: Int): Boolean = {
      require(x != y)
      ((s incl x) contains y) == (s contains y)
    } holds because (s match {
      case Empty() => true
      case Node(left, elem, right) =>
        if (x < elem) P3(left, x, y)
        else if (x > elem) P3(right, x, y)
        else true
    })
  }
}

Add IntSet benchmark that doesn't need assume-checked


package modules.contact.graphql.schema

import core.graphql.GraphQLSchema
import javax.inject.Inject
import modules.contact.graphql.resolvers.ContactResolver
import modules.contact.models.{Contact, ContactPayload}
import sangria.macros.derive.{InputObjectTypeName, ObjectTypeName, deriveInputObjectType, deriveObjectType}
import sangria.marshalling.FromInput
import sangria.schema.{Argument, Field, InputObjectType, ObjectType}
import util.{InputUnmarshallerGenerator, Logger}

class ContactSchema @Inject()(contactResolver: ContactResolver) extends GraphQLSchema with InputUnmarshallerGenerator with Logger {

  implicit val contactInput: InputObjectType[Contact] = deriveInputObjectType[Contact](InputObjectTypeName("ContactInput"))
  implicit val contactInputUnmarshaller: FromInput[Contact] = inputUnmarshaller {
    input =>
      Contact(
        name = input("name").asInstanceOf[String],
        email = input("email").asInstanceOf[String],
        content = input("content").asInstanceOf[String],
      )
  }

  implicit val contactPayload: ObjectType[Unit, ContactPayload] = deriveObjectType(ObjectTypeName("ContactPayload"))

  override def mutations: List[Field[Unit, Unit]] = List(
    Field(
      name = "contact",
      fieldType = contactPayload,
      arguments = List(Argument("input", contactInput)),
      resolve = sc => contactResolver.sendMail(sc.args.arg[Contact]("input"))
    )
  )

  override def queries: List[Field[Unit, Unit]] = List.empty

  override def subscriptions: List[Field[Unit, Unit]] = List.empty
}

Add graphql schema of Contact

Add graphql schema of Contact


package uk.ac.wellcome.platform.transformer.source

import org.scalatest.{FunSpec, Matchers}
import uk.ac.wellcome.utils.JsonUtil._

class MiroTransformableDataTest extends FunSpec with Matchers {

  // This is a simplified example of a failure we saw in the pipeline.
  // Examples: L0068740, V0014729.
  it("parses a JSON string with nulls in the image_keywords_unauth field") {
    val jsonString =
      """
        |{
        |    "image_artwork_date": "1578",
        |    "image_award": null,
        |    "image_award_date": null,
        |    "image_cleared": "Y",
        |    "image_copyright_cleared": "Y",
        |    "image_creator": null,
        |    "image_credit_line": null,
        |    "image_image_desc": "De morbis contagiosis libri septem / [Julien Le Paulmier].",
        |    "image_image_desc_academic": null,
        |    "image_innopac_id": "12062789",
        |    "image_keywords": null,
        |    "image_keywords_unauth": [
        |        null
        |    ],
        |    "image_lc_genre": null,
        |    "image_library_ref_department": [
        |        "EPB"
        |    ],
        |    "image_library_ref_id": [
        |        "4856/B/1"
        |    ],
        |    "image_phys_format": null,
        |    "image_source_code": "WEL",
        |    "image_supp_lettering": null,
        |    "image_tech_file_size": [
        |        "99854740"
        |    ],
        |    "image_title": "De morbis contagiosis libri septem",
        |    "image_use_restrictions": "CC-BY"
        |}
        |
      """.stripMargin

    fromJson[MiroTransformableData](jsonString).isSuccess shouldBe true
  }
}

Add a test that we can deserialise a list of nulls correctly


package core

import org.scalatest.{BeforeAndAfter, BeforeAndAfterAll, FunSpec}
import org.scalatest.Matchers

class InternalParsedDatatypeSpec extends FunSpec with Matchers {

  it("string") {
    val dt = InternalParsedDatatype("string")
    dt.name should be("string")
    dt.container should be(TypeContainer.Singleton)
  }

  it("uuid") {
    val dt = InternalParsedDatatype("uuid")
    dt.name should be("uuid")
    dt.container should be(TypeContainer.Singleton)
  }

  it("list") {
    val dt = InternalParsedDatatype("[string]")
    dt.name should be("string")
    dt.container should be(TypeContainer.List)
  }

  it("list[uuid]") {
    val dt = InternalParsedDatatype("[uuid]")
    dt.name should be("uuid")
    dt.container should be(TypeContainer.List)
  }

  it("map") {
    val dt = InternalParsedDatatype("map[string]")
    dt.name should be("string")
    dt.container should be(TypeContainer.Map)
  }

  it("map defaults to string type") {
    val dt = InternalParsedDatatype("map")
    dt.name should be("string")
    dt.container should be(TypeContainer.Map)
  }

  it("map[uuid]") {
    val dt = InternalParsedDatatype("map[uuid]")
    dt.name should be("uuid")
    dt.container should be(TypeContainer.Map)
  }

}

Add tests for internal parsed datatype

Add tests for internal parsed datatype


package hashing

import bloomfilter.hash.MurmurHash3.LongPair
import bloomfilter.hash.{MurmurHash3 => jMurmurHash3}
import org.openjdk.jmh.annotations.{Benchmark, Scope, State}

@State(Scope.Benchmark)
class MurmurHash3Benchmark {

  val key = Range(0, 64).map(_.toByte).toArray

  @Benchmark
  def javaVersion() = {
    jMurmurHash3.murmurhash3_x64_128(key, 0, key.length, 0, new LongPair)
  }

  @Benchmark
  def scalaVersion() = {
    MurmurHash3.murmurhash3_x64_128(key, 0, key.length, 0)
  }
}

Add simple benchmark for MurmurHash3

Add simple benchmark for MurmurHash3


package cilib
package example

import scalaz._
import Scalaz._
import scalaz.effect._
import scalaz.effect.IO.putStrLn

import eu.timepit.refined.auto._

import spire.implicits._
import spire.math.Interval
import cilib.ga._

object RandomSearchGA extends SafeApp {
  type Ind = Individual[Unit]

  val env =
    Environment(
      cmp = Comparison.dominance(Min),
      eval = Eval.unconstrained(cilib.benchmarks.Benchmarks.spherical[NonEmptyList, Double]).eval,
      bounds = Interval(-5.12, 5.12) ^ 30)

  val randomSelection = (l: NonEmptyList[Ind]) => RVar.sample(2, l).getOrElse(List.empty[Ind])
  val distribution = (position: Double) =>
    Dist.stdNormal.flatMap(x => Dist.gaussian(0, 1.25)).map(_ + position)

  val ga = GA.randomSearch(randomSelection, distribution)

  val swarm = Position.createCollection[Ind](x => Entity((), x))(env.bounds, 20)
  val myGA =
    Iteration
      .sync(ga)
      .map(_.suml)
      .flatMapK(
        r =>
          Step
            .withCompare(o => r.sortWith((x, y) => Comparison.fittest(x.pos, y.pos).apply(o)))
            .map(_.take(20).toNel.getOrElse(sys.error("Impossible -> List is empty?"))))

  override val runc: IO[Unit] =
    putStrLn(Runner.repeat(1000, myGA, swarm).run(env).run(RNG.fromTime).toString)
}

Add example of using a GA to do random search

Signed-off-by: Gary Pamparà <46654e9f53f0e5c1be5f3914582d375e0aa2156c@gmail.com>


import org.scalatest.{Matchers, FlatSpec}
import org.scalatest.prop.GeneratorDrivenPropertyChecks

import me.hawkweisman.util.collection.RepeatableSeq

/**
 * Created by hawk on 5/20/15.
 */
class CollectionSpec extends FlatSpec with GeneratorDrivenPropertyChecks with Matchers {

  "A RepeatableSeq" should "repeat an arbitrary sequence of integers to an arbitrary length" in {
    forAll { (s: Seq[Int], length: Int) =>
      val expected = for {
        i <- 0 to length
        e <- s (i % s.length)
      } yield e

      s take length shouldEqual expected
    }
  }

}

Fix fallout from moving Random into its own package


package com.socrata.http.server.util

import javax.servlet.http.HttpServletRequest

/**
 * Utilities for obtaining a universal request ID for socrata-http apps.
 */
object RequestId {
  type RequestId = String

  val ReqIdHeader = "X-Socrata-RequestId"

  /**
   * Obtains a RequestId from an HTTP request, generating one if not present.
   * @param req the [[HttpServletRequest]] object
   * @returns the RequestId from the request or a generated one
   */
  def getFromRequest(req: HttpServletRequest): RequestId =
    Option(req.getHeader(ReqIdHeader)).getOrElse(generate())

  /**
   * Generates a random Request ID.
   * NOTE: this is probably good enough but should we consider using UUIDs?
   */
  def generate(): RequestId = math.BigInt(128, scala.util.Random).toString(36)
}

Add common request ID logic

Add common request ID logic


/**
 * Licensed to Big Data Genomics (BDG) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The BDG licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.bdgenomics.adam.assembly

/**
 * Empty assembly object, allows Maven build to create sources and javadoc artifacts.
 */
object Assembly {
  // empty
}

Add empty assembly object, allows Maven build to create sources and javadoc artifacts


object Solution {

  // Reverse a positive integer, the return integer is a Long number as the
  // reversed integer may bigger than Int.MaxValue
  def reverseInt(n: Int, base: Int): Long = {
    var reversed = 0l
    // n should be greater than 0, otherwise It just returns 0
    var k = n

    while (k > 0) {
      reversed = base * reversed + k % base
      k /= base
    }
    reversed
  }

  // Generate palindrom numbers which has n digits.
  def palindromGenerator(n: Int): Seq[Int] = n match {
    case x if x <= 0 => throw new Exception(
      s"n should be greater than 0, but found ${n}")
    case 1 => (1 to 9)
    case 2 => (1 to 9).map(x => x * 10 + x)
    case x if x <= 9=>
      val halfSize = x / 2
      val start = math.pow(10, halfSize - 1).toInt
      val end = 10 * start
      if (x % 2 == 0)
        (start until end).map(x => x * end + reverseInt(x, 10).toInt)
      else (0 to 9).flatMap { i =>
        (start until end).map(x => (x * 10 + i) * end + reverseInt(x, 10).toInt)
      }
    case 10 =>
      val start = math.pow(10, 4).toInt
      val end = Int.MaxValue / start
      (start to end).map(x => x * start * 10 + reverseInt(x, 10).toInt)
    case _ => throw new Exception(s"n should less than 10, but found ${n}")
  }

  def isPalindrom(n: Int, base: Int): Boolean = reverseInt(n, base) == n

  def main(args: Array[String]) {
    val Array(n, k) = readLine.split(" ").map(_.toInt)
    val nDigits = n.toString.length
    val lessThanNDigitsSum = (1 until nDigits).flatMap(palindromGenerator(_)).
      filter({ isPalindrom(_, k) }).sum
    val nDigitsSum = palindromGenerator(nDigits).filter({ x =>
      x < n && isPalindrom(x, k)
    }).sum
    println(lessThanNDigitsSum + nDigitsSum)
  }
}

Add solution to problem 36. It's never too careful for integer numbers.


object Solution {

  def main(args: Array[String]) {
    val Array(n, q) = readLine.split(" ").map(_.toInt)
    var a = BigInt(readLine, 2)
    var b = BigInt(readLine, 2)
    var result = List.empty[Int]
    for (_ <- 1 to q) {
      val head :: tail = readLine.split(" ").toList
      head match {
        case "set_a" =>
          val List(idx, x) = tail.map(_.toInt)
          a = if (x == 1) a.setBit(idx) else a.clearBit(idx)
        case "set_b" =>
          val List(idx, x) = tail.map(_.toInt)
          b = if (x == 1) b.setBit(idx) else b.clearBit(idx)
        case "get_c" =>
          val idx = tail.head.toInt
          result = if ((a + b).testBit(idx)) 1 :: result else 0 :: result
      }
    }

    println(result.reverse.mkString)
  }
}

Add solution to Change Bits. The BigInteger class is immutable, hence There are a lot of unnecessary instance creation. The running time of this code on HackerRank is 6.53 at worst. So, should think another way to deal with it.


/*-------------------------------------------------------------------------*\
**  ScalaCheck                                                             **
**  Copyright (c) 2007-2013 Rickard Nilsson. All rights reserved.          **
**  http://www.scalacheck.org                                              **
**                                                                         **
**  This software is released under the terms of the Revised BSD License.  **
**  There is NO WARRANTY. See the file LICENSE for the full text.          **
\*------------------------------------------------------------------------ */

package org.scalacheck.example

import org.scalacheck._
import Gen.{listOf, alphaStr, numChar}

object StringUtils extends Properties("Examples.StringUtils") {

  private object StringUtils {
    def truncate(s: String, n: Int) = {
      if(s.length <= n) s
      else s.substring(0, n) ++ "..."
    }

    def truncate2(s: String, n: Int) = {
      if(n < 0) ""
      else if(s.length <= n) s
      else s.substring(0, n) ++ "..."
    }

    def tokenize(s: String, delim: Char) = {
      val delimStr = new java.lang.Character(delim).toString
      val st = new java.util.StringTokenizer(s, delimStr)
      val tokens = Array.ofDim[String](st.countTokens)
      var i = 0;
      while(st.hasMoreTokens) {
        tokens(i) = st.nextToken()
        i += 1;
      }
      tokens;
    }

    def contains(s: String, subString: String) = {
      s.indexOf(subString) != -1
    }
  }

  property("truncate") = Prop.forAll { (s: String, n: Int) =>
    lazy val t = StringUtils.truncate(s, n)
    if(n < 0)
      Prop.throws(classOf[StringIndexOutOfBoundsException]) { t }
    else
      (s.length <= n && t == s) ||
      (s.length > n && t == s.take(n)+"...")
  }

  property("truncate.precond") = Prop.forAll { (s: String, n: Int) =>
    import Prop.BooleanOperators
    (n >= 0) ==> {
      val t = StringUtils.truncate(s, n)
      (s.length <= n && t == s) ||
      (s.length > n && t == s.take(n)+"...")
    }
  }

  property("truncate2") = Prop.forAll { (s: String, n: Int) =>
    val t = StringUtils.truncate2(s, n)
    if(n < 0)
      t == ""
    else
      (s.length <= n && t == s) ||
      (s.length > n && t == s.take(n)+"...")
  }

  //property("tokenize") = {
  //  import Prop.AnyOperators
  //  Prop.forAll(Gen.listOf(Gen.alphaStr), Gen.numChar) { (ts, d) =>
  //    val str = ts.mkString(d.toString)
  //    StringUtils.tokenize(str, d).toList ?= ts
  //  }
  //}

  property("contains") =
    Prop.forAll { (s1: String, s2: String, s3: String) =>
      StringUtils.contains(s1+s2+s3, s2)
    }
}

Add some example properties as tests

Add some example properties as tests


package view
import java.util.Date
import java.text.SimpleDateFormat
import twirl.api.Html

object helpers {

  /**
   * Format java.util.Date to "yyyy/MM/dd HH:mm:ss".
   */
  def datetime(date: Date): String = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(date)

  /**
   * Format java.util.Date to "yyyy/MM/dd".
   */
  def date(date: Date): String = new SimpleDateFormat("yyyy/MM/dd").format(date)

  /**
   * Converts Markdown of Wiki pages to HTML.
   */
  def markdown(value: String, repository: service.RepositoryService.RepositoryInfo,
               enableWikiLink: Boolean, enableCommitLink: Boolean, enableIssueLink: Boolean)(implicit context: app.Context): Html = {
    Html(Markdown.toHtml(value, repository, enableWikiLink, enableCommitLink, enableIssueLink))
  }

}

package view
import java.util.Date
import java.text.SimpleDateFormat
import twirl.api.Html

/**
 * Provides helper methods for Twirl templates.
 */
object helpers {

  /**
   * Format java.util.Date to "yyyy/MM/dd HH:mm:ss".
   */
  def datetime(date: Date): String = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(date)

  /**
   * Format java.util.Date to "yyyy/MM/dd".
   */
  def date(date: Date): String = new SimpleDateFormat("yyyy/MM/dd").format(date)

  /**
   * Converts Markdown of Wiki pages to HTML.
   */
  def markdown(value: String, repository: service.RepositoryService.RepositoryInfo,
               enableWikiLink: Boolean, enableCommitLink: Boolean, enableIssueLink: Boolean)(implicit context: app.Context): Html = {
    Html(Markdown.toHtml(value, repository, enableWikiLink, enableCommitLink, enableIssueLink))
  }

}

/**
 * Provides implicit conversions for Twirl templates.
 */
object implicits {

  implicit def extendsHtmlSeq(seq: Seq[Html]) = new {
    def mkHtml(separator: String) = Html(seq.mkString(separator))
    def mkHtml(separator: scala.xml.Elem) = Html(seq.mkString(separator.toString))
  }

}

Add a implicit conversion which adds mkHtml to views.implicit.