├── calculator ├── project │ ├── build.properties │ ├── plugins.sbt │ └── ReactiveBuild.scala ├── src │ ├── main │ │ └── scala │ │ │ ├── calculator │ │ │ ├── Polynomial.scala │ │ │ ├── Calculator.scala │ │ │ ├── TweetLength.scala │ │ │ └── Signal.scala │ │ │ └── common │ │ │ └── package.scala │ └── test │ │ └── scala │ │ └── calculator │ │ └── CalculatorSuite.scala ├── webui.sbt └── build.sbt ├── forcomp ├── project │ ├── build.properties │ ├── project │ │ └── buildPlugins.sbt │ ├── RichJsValue.scala │ ├── RecordingLogger.scala │ ├── Settings.scala │ ├── buildSettings.sbt │ └── StyleChecker.scala ├── lib │ └── cafesat_2.11-0.01.jar ├── .project ├── src │ ├── main │ │ └── scala │ │ │ ├── forcomp │ │ │ └── package.scala │ │ │ └── common │ │ │ └── package.scala │ └── test │ │ └── scala │ │ └── forcomp │ │ └── AnagramsSuite.scala └── .classpath ├── funsets ├── project │ ├── build.properties │ ├── project │ │ └── buildPlugins.sbt │ ├── RichJsValue.scala │ ├── RecordingLogger.scala │ ├── Settings.scala │ ├── buildSettings.sbt │ └── StyleChecker.scala ├── lib │ └── cafesat_2.11-0.01.jar ├── src │ ├── main │ │ └── scala │ │ │ ├── funsets │ │ │ ├── Main.scala │ │ │ └── FunSets.scala │ │ │ └── common │ │ │ └── package.scala │ └── test │ │ └── scala │ │ └── funsets │ │ └── FunSetSuite.scala ├── .project └── .classpath ├── nodescala ├── project │ ├── build.properties │ ├── plugins.sbt │ └── ReactiveBuild.scala ├── src │ ├── main │ │ └── scala │ │ │ ├── common │ │ │ └── package.scala │ │ │ └── nodescala │ │ │ └── Main.scala │ └── test │ │ └── scala │ │ └── nodescala │ │ └── tests.scala └── build.sbt ├── objsets ├── project │ ├── build.properties │ ├── project │ │ └── buildPlugins.sbt │ ├── RichJsValue.scala │ ├── RecordingLogger.scala │ ├── Settings.scala │ ├── buildSettings.sbt │ └── StyleChecker.scala ├── lib │ └── cafesat_2.11-0.01.jar ├── .project ├── src │ ├── main │ │ └── scala │ │ │ ├── common │ │ │ └── package.scala │ │ │ └── objsets │ │ │ └── TweetReader.scala │ └── test │ │ └── scala │ │ └── objsets │ │ └── TweetSetSuite.scala └── .classpath ├── patmat ├── project │ ├── build.properties │ ├── project │ │ └── buildPlugins.sbt │ ├── RichJsValue.scala │ ├── RecordingLogger.scala │ ├── Settings.scala │ ├── buildSettings.sbt │ └── StyleChecker.scala ├── lib │ └── cafesat_2.11-0.01.jar ├── .project ├── src │ ├── main │ │ └── scala │ │ │ └── common │ │ │ └── package.scala │ └── test │ │ └── scala │ │ └── patmat │ │ └── HuffmanSuite.scala └── .classpath ├── quickcheck ├── project │ ├── build.properties │ ├── plugins.sbt │ └── ReactiveBuild.scala ├── src │ ├── main │ │ └── scala │ │ │ ├── quickcheck │ │ │ ├── QuickCheck.scala │ │ │ └── Heap.scala │ │ │ └── common │ │ │ └── package.scala │ └── test │ │ └── scala │ │ └── quickcheck │ │ └── QuickCheckSuite.scala └── build.sbt ├── recfun ├── project │ ├── build.properties │ ├── project │ │ └── buildPlugins.sbt │ ├── RichJsValue.scala │ ├── RecordingLogger.scala │ ├── Settings.scala │ ├── buildSettings.sbt │ └── StyleChecker.scala ├── lib │ └── cafesat_2.11-0.01.jar ├── .project └── src │ ├── test │ └── scala │ │ └── recfun │ │ ├── PascalSuite.scala │ │ ├── CountChangeSuite.scala │ │ └── BalanceSuite.scala │ └── main │ └── scala │ ├── common │ └── package.scala │ └── recfun │ └── Main.scala ├── streams ├── project │ ├── build.properties │ ├── project │ │ └── buildPlugins.sbt │ ├── RichJsValue.scala │ ├── RecordingLogger.scala │ ├── Settings.scala │ ├── buildSettings.sbt │ └── StyleChecker.scala ├── lib │ └── cafesat_2.11-0.01.jar ├── .project └── src │ ├── main │ └── scala │ │ ├── streams │ │ ├── InfiniteTerrain.scala │ │ ├── Bloxorz.scala │ │ ├── StringParserTerrain.scala │ │ └── Solver.scala │ │ └── common │ │ └── package.scala │ └── test │ └── scala │ └── streams │ └── BloxorzSuite.scala ├── actorbintree ├── project │ ├── build.properties │ ├── plugins.sbt │ └── ReactiveBuild.scala ├── src │ └── main │ │ └── scala │ │ ├── common │ │ └── package.scala │ │ └── actorbintree │ │ └── BinaryTreeSet.scala └── build.sbt ├── ass_zip └── example │ ├── project │ ├── build.properties │ ├── project │ │ └── buildPlugins.sbt │ ├── RichJsValue.scala │ ├── RecordingLogger.scala │ ├── Settings.scala │ ├── buildSettings.sbt │ └── StyleChecker.scala │ ├── lib │ └── cafesat_2.10-0.01.jar │ └── src │ └── main │ └── scala │ ├── common │ └── package.scala │ └── example │ └── Lists.scala ├── suggestions ├── project │ ├── build.properties │ ├── plugins.sbt │ └── ReactiveBuild.scala ├── src │ ├── main │ │ ├── scala │ │ │ ├── suggestions │ │ │ │ ├── package.scala │ │ │ │ ├── gui │ │ │ │ │ ├── package.scala │ │ │ │ │ ├── SwingApi.scala │ │ │ │ │ └── WikipediaApi.scala │ │ │ │ ├── observablex │ │ │ │ │ ├── SchedulerEx.scala │ │ │ │ │ └── ObservableEx.scala │ │ │ │ └── search │ │ │ │ │ └── Search.scala │ │ │ └── common │ │ │ │ └── package.scala │ │ └── resources │ │ │ └── suggestions │ │ │ └── wiki-icon.png │ └── test │ │ └── scala │ │ └── suggestions │ │ ├── WikipediaApiTest.scala │ │ └── SwingApiTest.scala └── build.sbt └── .gitignore /calculator/project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=0.13.7 2 | -------------------------------------------------------------------------------- /forcomp/project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=0.13.7 2 | -------------------------------------------------------------------------------- /funsets/project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=0.13.7 2 | -------------------------------------------------------------------------------- /nodescala/project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=0.13.7 2 | -------------------------------------------------------------------------------- /objsets/project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=0.13.7 2 | -------------------------------------------------------------------------------- /patmat/project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=0.13.7 2 | -------------------------------------------------------------------------------- /quickcheck/project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=0.13.7 2 | -------------------------------------------------------------------------------- /recfun/project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=0.13.7 2 | -------------------------------------------------------------------------------- /streams/project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=0.13.7 2 | -------------------------------------------------------------------------------- /actorbintree/project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=0.13.7 2 | -------------------------------------------------------------------------------- /ass_zip/example/project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=0.12.4 2 | -------------------------------------------------------------------------------- /suggestions/project/build.properties: -------------------------------------------------------------------------------- 1 | sbt.version=0.13.7 2 | -------------------------------------------------------------------------------- /quickcheck/project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("ch.epfl.lamp" % "sbt-coursera" % "0.5") 2 | -------------------------------------------------------------------------------- /patmat/lib/cafesat_2.11-0.01.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biubiu/functional-programming-scala/master/patmat/lib/cafesat_2.11-0.01.jar -------------------------------------------------------------------------------- /recfun/lib/cafesat_2.11-0.01.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biubiu/functional-programming-scala/master/recfun/lib/cafesat_2.11-0.01.jar -------------------------------------------------------------------------------- /forcomp/lib/cafesat_2.11-0.01.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biubiu/functional-programming-scala/master/forcomp/lib/cafesat_2.11-0.01.jar -------------------------------------------------------------------------------- /funsets/lib/cafesat_2.11-0.01.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biubiu/functional-programming-scala/master/funsets/lib/cafesat_2.11-0.01.jar -------------------------------------------------------------------------------- /objsets/lib/cafesat_2.11-0.01.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biubiu/functional-programming-scala/master/objsets/lib/cafesat_2.11-0.01.jar -------------------------------------------------------------------------------- /streams/lib/cafesat_2.11-0.01.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biubiu/functional-programming-scala/master/streams/lib/cafesat_2.11-0.01.jar -------------------------------------------------------------------------------- /calculator/project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("ch.epfl.lamp" % "sbt-coursera" % "0.5") 2 | 3 | addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.2") 4 | -------------------------------------------------------------------------------- /forcomp/project/project/buildPlugins.sbt: -------------------------------------------------------------------------------- 1 | // the dependency-graph plugin 2 | // addSbtPlugin("net.virtual-void" % "sbt-dependency-graph" % "0.6.0") 3 | -------------------------------------------------------------------------------- /funsets/project/project/buildPlugins.sbt: -------------------------------------------------------------------------------- 1 | // the dependency-graph plugin 2 | // addSbtPlugin("net.virtual-void" % "sbt-dependency-graph" % "0.6.0") 3 | -------------------------------------------------------------------------------- /nodescala/project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("ch.epfl.lamp" % "sbt-coursera" % "0.5") 2 | 3 | addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.2") 4 | -------------------------------------------------------------------------------- /objsets/project/project/buildPlugins.sbt: -------------------------------------------------------------------------------- 1 | // the dependency-graph plugin 2 | // addSbtPlugin("net.virtual-void" % "sbt-dependency-graph" % "0.6.0") 3 | -------------------------------------------------------------------------------- /patmat/project/project/buildPlugins.sbt: -------------------------------------------------------------------------------- 1 | // the dependency-graph plugin 2 | // addSbtPlugin("net.virtual-void" % "sbt-dependency-graph" % "0.6.0") 3 | -------------------------------------------------------------------------------- /recfun/project/project/buildPlugins.sbt: -------------------------------------------------------------------------------- 1 | // the dependency-graph plugin 2 | // addSbtPlugin("net.virtual-void" % "sbt-dependency-graph" % "0.6.0") 3 | -------------------------------------------------------------------------------- /streams/project/project/buildPlugins.sbt: -------------------------------------------------------------------------------- 1 | // the dependency-graph plugin 2 | // addSbtPlugin("net.virtual-void" % "sbt-dependency-graph" % "0.6.0") 3 | -------------------------------------------------------------------------------- /suggestions/project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("ch.epfl.lamp" % "sbt-coursera" % "0.5") 2 | 3 | addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.2") 4 | -------------------------------------------------------------------------------- /actorbintree/project/plugins.sbt: -------------------------------------------------------------------------------- 1 | addSbtPlugin("ch.epfl.lamp" % "sbt-coursera" % "0.5") 2 | 3 | addSbtPlugin("org.scala-js" % "sbt-scalajs" % "0.6.2") 4 | -------------------------------------------------------------------------------- /ass_zip/example/lib/cafesat_2.10-0.01.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biubiu/functional-programming-scala/master/ass_zip/example/lib/cafesat_2.10-0.01.jar -------------------------------------------------------------------------------- /ass_zip/example/project/project/buildPlugins.sbt: -------------------------------------------------------------------------------- 1 | // the dependency-graph plugin 2 | // addSbtPlugin("net.virtual-void" % "sbt-dependency-graph" % "0.6.0") 3 | -------------------------------------------------------------------------------- /suggestions/src/main/scala/suggestions/package.scala: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | package object suggestions { 6 | 7 | def log(x: Any) = println(x) 8 | 9 | } 10 | -------------------------------------------------------------------------------- /suggestions/src/main/resources/suggestions/wiki-icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/biubiu/functional-programming-scala/master/suggestions/src/main/resources/suggestions/wiki-icon.png -------------------------------------------------------------------------------- /funsets/src/main/scala/funsets/Main.scala: -------------------------------------------------------------------------------- 1 | package funsets 2 | 3 | object Main extends App { 4 | import FunSets._ 5 | println(contains(singletonSet(1), 1)) 6 | println(singletonSet(1)) 7 | println(union(Set(1,2,3), Set(3,4,5))) 8 | } 9 | -------------------------------------------------------------------------------- /suggestions/src/main/scala/suggestions/gui/package.scala: -------------------------------------------------------------------------------- 1 | package suggestions 2 | 3 | import scala.swing.Reactions.Reaction 4 | 5 | package object gui { 6 | 7 | object Reaction { 8 | def apply(r: Reaction) = r 9 | } 10 | 11 | } -------------------------------------------------------------------------------- /suggestions/src/main/scala/suggestions/observablex/SchedulerEx.scala: -------------------------------------------------------------------------------- 1 | package suggestions 2 | package observablex 3 | 4 | import rx.lang.scala.Scheduler 5 | import rx.schedulers.SwingScheduler 6 | 7 | object SchedulerEx { 8 | 9 | val SwingEventThreadScheduler: Scheduler = 10 | rx.lang.scala.JavaConversions.javaSchedulerToScalaScheduler(SwingScheduler.getInstance) 11 | 12 | } 13 | -------------------------------------------------------------------------------- /calculator/src/main/scala/calculator/Polynomial.scala: -------------------------------------------------------------------------------- 1 | package calculator 2 | 3 | object Polynomial { 4 | def computeDelta(a: Signal[Double], b: Signal[Double], 5 | c: Signal[Double]): Signal[Double] = { 6 | ??? 7 | } 8 | 9 | def computeSolutions(a: Signal[Double], b: Signal[Double], 10 | c: Signal[Double], delta: Signal[Double]): Signal[Set[Double]] = { 11 | ??? 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /forcomp/.project: -------------------------------------------------------------------------------- 1 | 2 | progfun-forcomp 3 | 4 | 5 | org.scala-ide.sdt.core.scalabuilder 6 | 7 | 8 | 9 | org.scala-ide.sdt.core.scalanature 10 | org.eclipse.jdt.core.javanature 11 | 12 | 13 | -------------------------------------------------------------------------------- /funsets/.project: -------------------------------------------------------------------------------- 1 | 2 | progfun-funsets 3 | 4 | 5 | org.scala-ide.sdt.core.scalabuilder 6 | 7 | 8 | 9 | org.scala-ide.sdt.core.scalanature 10 | org.eclipse.jdt.core.javanature 11 | 12 | 13 | -------------------------------------------------------------------------------- /objsets/.project: -------------------------------------------------------------------------------- 1 | 2 | progfun-objsets 3 | 4 | 5 | org.scala-ide.sdt.core.scalabuilder 6 | 7 | 8 | 9 | org.scala-ide.sdt.core.scalanature 10 | org.eclipse.jdt.core.javanature 11 | 12 | 13 | -------------------------------------------------------------------------------- /patmat/.project: -------------------------------------------------------------------------------- 1 | 2 | progfun-patmat 3 | 4 | 5 | org.scala-ide.sdt.core.scalabuilder 6 | 7 | 8 | 9 | org.scala-ide.sdt.core.scalanature 10 | org.eclipse.jdt.core.javanature 11 | 12 | 13 | -------------------------------------------------------------------------------- /recfun/.project: -------------------------------------------------------------------------------- 1 | 2 | progfun-recfun 3 | 4 | 5 | org.scala-ide.sdt.core.scalabuilder 6 | 7 | 8 | 9 | org.scala-ide.sdt.core.scalanature 10 | org.eclipse.jdt.core.javanature 11 | 12 | 13 | -------------------------------------------------------------------------------- /streams/.project: -------------------------------------------------------------------------------- 1 | 2 | progfun-streams 3 | 4 | 5 | org.scala-ide.sdt.core.scalabuilder 6 | 7 | 8 | 9 | org.scala-ide.sdt.core.scalanature 10 | org.eclipse.jdt.core.javanature 11 | 12 | 13 | -------------------------------------------------------------------------------- /calculator/webui.sbt: -------------------------------------------------------------------------------- 1 | lazy val webUI = project.in(file("web-ui")). 2 | enablePlugins(ScalaJSPlugin). 3 | settings( 4 | scalaVersion := "2.11.6", 5 | // Add the sources of the calculator project 6 | unmanagedSourceDirectories in Compile += 7 | (scalaSource in (assignmentProject, Compile)).value / "calculator", 8 | libraryDependencies += "org.scala-js" %%% "scalajs-dom" % "0.8.0", 9 | persistLauncher := true 10 | ) 11 | -------------------------------------------------------------------------------- /streams/src/main/scala/streams/InfiniteTerrain.scala: -------------------------------------------------------------------------------- 1 | package streams 2 | 3 | /** 4 | * This trait defines an infinite terrain, where the block can 5 | * go on any position. 6 | * 7 | * It keeps the `startPos` and the `goal` positions abstract. 8 | * 9 | * Using this trait is useful for testing. It can be used to find 10 | * the shortest path between two positions without terrain 11 | * restrictions. 12 | */ 13 | trait InfiniteTerrain extends GameDef { 14 | val terrain: Terrain = (pos: Pos) => true 15 | } 16 | -------------------------------------------------------------------------------- /recfun/src/test/scala/recfun/PascalSuite.scala: -------------------------------------------------------------------------------- 1 | package recfun 2 | 3 | import org.scalatest.FunSuite 4 | 5 | import org.junit.runner.RunWith 6 | import org.scalatest.junit.JUnitRunner 7 | 8 | @RunWith(classOf[JUnitRunner]) 9 | class PascalSuite extends FunSuite { 10 | import Main.pascal 11 | test("pascal: col=0,row=2") { 12 | assert(pascal(0,2) === 1) 13 | } 14 | 15 | test("pascal: col=1,row=2") { 16 | assert(pascal(1,2) === 2) 17 | } 18 | 19 | test("pascal: col=1,row=3") { 20 | assert(pascal(1,3) === 3) 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.log 2 | 3 | # sbt specific 4 | .cache 5 | .history 6 | .lib/ 7 | dist/* 8 | target/ 9 | lib_managed/ 10 | src_managed/ 11 | project/boot/ 12 | project/plugins/project/ 13 | 14 | # Scala-IDE specific 15 | .scala_dependencies 16 | .worksheet 17 | 18 | *.zip 19 | 20 | # Mac system files 21 | .DS_Store 22 | # 23 | *.class 24 | *.log 25 | # 26 | # # sbt specific 27 | .cache/ 28 | .history/ 29 | .lib/ 30 | dist/* 31 | target/ 32 | .idea/ 33 | .idea/* 34 | .idea 35 | lib_managed/ 36 | src_managed/ 37 | project/boot/ 38 | project/plugins/project/ 39 | 40 | # Scala-IDE specific 41 | bin/ 42 | .settings/ 43 | .metadata 44 | *.cache 45 | *.scala_dependencies 46 | *.worksheet 47 | 48 | -------------------------------------------------------------------------------- /forcomp/src/main/scala/forcomp/package.scala: -------------------------------------------------------------------------------- 1 | package object forcomp { 2 | val dictionaryPath = List("forcomp", "linuxwords.txt") 3 | 4 | def loadDictionary = { 5 | val wordstream = Option { 6 | getClass.getClassLoader.getResourceAsStream(dictionaryPath.mkString("/")) 7 | } orElse { 8 | common.resourceAsStreamFromSrc(dictionaryPath) 9 | } getOrElse { 10 | sys.error("Could not load word list, dictionary file not found") 11 | } 12 | try { 13 | val s = io.Source.fromInputStream(wordstream) 14 | s.getLines.toList 15 | } catch { 16 | case e: Exception => 17 | println("Could not load word list: " + e) 18 | throw e 19 | } finally { 20 | wordstream.close() 21 | } 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /recfun/src/test/scala/recfun/CountChangeSuite.scala: -------------------------------------------------------------------------------- 1 | package recfun 2 | 3 | import org.scalatest.FunSuite 4 | 5 | import org.junit.runner.RunWith 6 | import org.scalatest.junit.JUnitRunner 7 | 8 | @RunWith(classOf[JUnitRunner]) 9 | class CountChangeSuite extends FunSuite { 10 | import Main.countChange 11 | test("countChange: example given in instructions") { 12 | assert(countChange(4,List(1,2)) === 3) 13 | } 14 | 15 | test("countChange: sorted CHF") { 16 | assert(countChange(300,List(5,10,20,50,100,200,500)) === 1022) 17 | } 18 | 19 | test("countChange: no pennies") { 20 | assert(countChange(301,List(5,10,20,50,100,200,500)) === 0) 21 | } 22 | 23 | test("countChange: unsorted CHF") { 24 | assert(countChange(300,List(500,5,50,100,20,200,10)) === 1022) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /recfun/src/test/scala/recfun/BalanceSuite.scala: -------------------------------------------------------------------------------- 1 | package recfun 2 | 3 | import org.scalatest.FunSuite 4 | 5 | import org.junit.runner.RunWith 6 | import org.scalatest.junit.JUnitRunner 7 | 8 | @RunWith(classOf[JUnitRunner]) 9 | class BalanceSuite extends FunSuite { 10 | import Main.balance 11 | 12 | test("balance: '(if (zero? x) max (/ 1 x))' is balanced") { 13 | assert(balance("(if (zero? x) max (/ 1 x))".toList)) 14 | } 15 | 16 | test("balance: 'I told him ...' is balanced") { 17 | assert(balance("I told him (that it's not (yet) done).\n(But he wasn't listening)".toList)) 18 | } 19 | 20 | test("balance: ':-)' is unbalanced") { 21 | assert(!balance(":-)".toList)) 22 | } 23 | 24 | test("balance: counting is not enough") { 25 | assert(!balance("())(".toList)) 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /ass_zip/example/project/RichJsValue.scala: -------------------------------------------------------------------------------- 1 | import cc.spray.json._ 2 | 3 | class RichJsValue(js: JsValue) { 4 | def \ (name: String): JsValue = js match { 5 | case JsObject(fields) => 6 | fields(name) 7 | case _ => 8 | throw new IllegalArgumentException("Cannot select field "+ name +" from non-JsObject "+ js) 9 | } 10 | 11 | def hasFieldNamed(name: String) = js match { 12 | case JsObject(fields) => 13 | fields.contains(name) 14 | case _ => 15 | false 16 | } 17 | 18 | def arrayValues: List[JsValue] = js match { 19 | case JsArray(values) => 20 | values 21 | case _ => 22 | throw new IllegalArgumentException("Trying to select values from non-JsArray"+ js) 23 | } 24 | } 25 | 26 | object RichJsValue { 27 | implicit def enrichJsValue(js: JsValue) = new RichJsValue(js) 28 | } 29 | -------------------------------------------------------------------------------- /quickcheck/src/main/scala/quickcheck/QuickCheck.scala: -------------------------------------------------------------------------------- 1 | package quickcheck 2 | 3 | import common._ 4 | 5 | import org.scalacheck._ 6 | import Arbitrary._ 7 | import Gen._ 8 | import Prop._ 9 | 10 | abstract class QuickCheckHeap extends Properties("Heap") with IntHeap { 11 | 12 | property("min1") = forAll { a: Int => 13 | val h = insert(a, empty) 14 | findMin(h) == a 15 | } 16 | 17 | property("min2") = forAll{ (a:Int, b:Int)=> 18 | val h = insert(b, insert(a,empty)) 19 | val m = if (a > b) a else b 20 | findMin(h) == m 21 | } 22 | 23 | property("del1") = forAll { (a: Int, b: Int) => 24 | 25 | } 26 | 27 | lazy val genHeap: Gen[H] = for { 28 | k <- arbitrary[Int] 29 | m <- oneOf(empty, genHeap) 30 | } yield insert(k, m) 31 | 32 | 33 | implicit lazy val arbHeap: Arbitrary[H] = Arbitrary(genHeap) 34 | 35 | } 36 | -------------------------------------------------------------------------------- /suggestions/src/main/scala/suggestions/observablex/ObservableEx.scala: -------------------------------------------------------------------------------- 1 | package suggestions 2 | package observablex 3 | 4 | import scala.concurrent.{Future, ExecutionContext} 5 | import scala.util._ 6 | import scala.util.Success 7 | import scala.util.Failure 8 | import java.lang.Throwable 9 | import rx.lang.scala.Observable 10 | import rx.lang.scala.Scheduler 11 | 12 | object ObservableEx { 13 | 14 | /** Returns an observable stream of values produced by the given future. 15 | * If the future fails, the observable will fail as well. 16 | * 17 | * @param f future whose values end up in the resulting observable 18 | * @return an observable completed after producing the value of the future, or with an exception 19 | */ 20 | def apply[T](f: Future[T])(implicit execContext: ExecutionContext): Observable[T] = { 21 | Observable.from(f) 22 | } 23 | 24 | } -------------------------------------------------------------------------------- /forcomp/project/RichJsValue.scala: -------------------------------------------------------------------------------- 1 | import scala.language.implicitConversions 2 | 3 | import spray.json._ 4 | 5 | class RichJsValue(js: JsValue) { 6 | def \ (name: String): JsValue = js match { 7 | case JsObject(fields) => 8 | fields(name) 9 | case _ => 10 | throw new IllegalArgumentException("Cannot select field "+ name +" from non-JsObject "+ js) 11 | } 12 | 13 | def hasFieldNamed(name: String) = js match { 14 | case JsObject(fields) => 15 | fields.contains(name) 16 | case _ => 17 | false 18 | } 19 | 20 | def arrayValues: List[JsValue] = js match { 21 | case JsArray(values) => 22 | values.toList 23 | case _ => 24 | throw new IllegalArgumentException("Trying to select values from non-JsArray"+ js) 25 | } 26 | } 27 | 28 | object RichJsValue { 29 | implicit def enrichJsValue(js: JsValue) = new RichJsValue(js) 30 | } 31 | -------------------------------------------------------------------------------- /funsets/project/RichJsValue.scala: -------------------------------------------------------------------------------- 1 | import scala.language.implicitConversions 2 | 3 | import spray.json._ 4 | 5 | class RichJsValue(js: JsValue) { 6 | def \ (name: String): JsValue = js match { 7 | case JsObject(fields) => 8 | fields(name) 9 | case _ => 10 | throw new IllegalArgumentException("Cannot select field "+ name +" from non-JsObject "+ js) 11 | } 12 | 13 | def hasFieldNamed(name: String) = js match { 14 | case JsObject(fields) => 15 | fields.contains(name) 16 | case _ => 17 | false 18 | } 19 | 20 | def arrayValues: List[JsValue] = js match { 21 | case JsArray(values) => 22 | values.toList 23 | case _ => 24 | throw new IllegalArgumentException("Trying to select values from non-JsArray"+ js) 25 | } 26 | } 27 | 28 | object RichJsValue { 29 | implicit def enrichJsValue(js: JsValue) = new RichJsValue(js) 30 | } 31 | -------------------------------------------------------------------------------- /objsets/project/RichJsValue.scala: -------------------------------------------------------------------------------- 1 | import scala.language.implicitConversions 2 | 3 | import spray.json._ 4 | 5 | class RichJsValue(js: JsValue) { 6 | def \ (name: String): JsValue = js match { 7 | case JsObject(fields) => 8 | fields(name) 9 | case _ => 10 | throw new IllegalArgumentException("Cannot select field "+ name +" from non-JsObject "+ js) 11 | } 12 | 13 | def hasFieldNamed(name: String) = js match { 14 | case JsObject(fields) => 15 | fields.contains(name) 16 | case _ => 17 | false 18 | } 19 | 20 | def arrayValues: List[JsValue] = js match { 21 | case JsArray(values) => 22 | values.toList 23 | case _ => 24 | throw new IllegalArgumentException("Trying to select values from non-JsArray"+ js) 25 | } 26 | } 27 | 28 | object RichJsValue { 29 | implicit def enrichJsValue(js: JsValue) = new RichJsValue(js) 30 | } 31 | -------------------------------------------------------------------------------- /patmat/project/RichJsValue.scala: -------------------------------------------------------------------------------- 1 | import scala.language.implicitConversions 2 | 3 | import spray.json._ 4 | 5 | class RichJsValue(js: JsValue) { 6 | def \ (name: String): JsValue = js match { 7 | case JsObject(fields) => 8 | fields(name) 9 | case _ => 10 | throw new IllegalArgumentException("Cannot select field "+ name +" from non-JsObject "+ js) 11 | } 12 | 13 | def hasFieldNamed(name: String) = js match { 14 | case JsObject(fields) => 15 | fields.contains(name) 16 | case _ => 17 | false 18 | } 19 | 20 | def arrayValues: List[JsValue] = js match { 21 | case JsArray(values) => 22 | values.toList 23 | case _ => 24 | throw new IllegalArgumentException("Trying to select values from non-JsArray"+ js) 25 | } 26 | } 27 | 28 | object RichJsValue { 29 | implicit def enrichJsValue(js: JsValue) = new RichJsValue(js) 30 | } 31 | -------------------------------------------------------------------------------- /recfun/project/RichJsValue.scala: -------------------------------------------------------------------------------- 1 | import scala.language.implicitConversions 2 | 3 | import spray.json._ 4 | 5 | class RichJsValue(js: JsValue) { 6 | def \ (name: String): JsValue = js match { 7 | case JsObject(fields) => 8 | fields(name) 9 | case _ => 10 | throw new IllegalArgumentException("Cannot select field "+ name +" from non-JsObject "+ js) 11 | } 12 | 13 | def hasFieldNamed(name: String) = js match { 14 | case JsObject(fields) => 15 | fields.contains(name) 16 | case _ => 17 | false 18 | } 19 | 20 | def arrayValues: List[JsValue] = js match { 21 | case JsArray(values) => 22 | values.toList 23 | case _ => 24 | throw new IllegalArgumentException("Trying to select values from non-JsArray"+ js) 25 | } 26 | } 27 | 28 | object RichJsValue { 29 | implicit def enrichJsValue(js: JsValue) = new RichJsValue(js) 30 | } 31 | -------------------------------------------------------------------------------- /streams/project/RichJsValue.scala: -------------------------------------------------------------------------------- 1 | import scala.language.implicitConversions 2 | 3 | import spray.json._ 4 | 5 | class RichJsValue(js: JsValue) { 6 | def \ (name: String): JsValue = js match { 7 | case JsObject(fields) => 8 | fields(name) 9 | case _ => 10 | throw new IllegalArgumentException("Cannot select field "+ name +" from non-JsObject "+ js) 11 | } 12 | 13 | def hasFieldNamed(name: String) = js match { 14 | case JsObject(fields) => 15 | fields.contains(name) 16 | case _ => 17 | false 18 | } 19 | 20 | def arrayValues: List[JsValue] = js match { 21 | case JsArray(values) => 22 | values.toList 23 | case _ => 24 | throw new IllegalArgumentException("Trying to select values from non-JsArray"+ js) 25 | } 26 | } 27 | 28 | object RichJsValue { 29 | implicit def enrichJsValue(js: JsValue) = new RichJsValue(js) 30 | } 31 | -------------------------------------------------------------------------------- /forcomp/project/RecordingLogger.scala: -------------------------------------------------------------------------------- 1 | import sbt._ 2 | import collection.mutable.ListBuffer 3 | 4 | /** 5 | * Logger to capture compiler output, test output 6 | */ 7 | 8 | object RecordingLogger extends Logger { 9 | private val buffer = ListBuffer[String]() 10 | 11 | def hasErrors = buffer.nonEmpty 12 | 13 | def readAndClear() = { 14 | val res = buffer.mkString("\n") 15 | buffer.clear() 16 | res 17 | } 18 | 19 | def clear() { 20 | buffer.clear() 21 | } 22 | 23 | def log(level: Level.Value, message: => String) = 24 | if (level == Level.Error) { 25 | buffer += message 26 | } 27 | 28 | // we don't log success here 29 | def success(message: => String) = () 30 | 31 | // invoked when a task throws an exception. invoked late, when the exception is logged, i.e. 32 | // just before returning to the prompt. therefore we do nothing: storing the exception in the 33 | // buffer would happen *after* the `handleFailure` reads the buffer. 34 | def trace(t: => Throwable) = () 35 | } 36 | -------------------------------------------------------------------------------- /funsets/project/RecordingLogger.scala: -------------------------------------------------------------------------------- 1 | import sbt._ 2 | import collection.mutable.ListBuffer 3 | 4 | /** 5 | * Logger to capture compiler output, test output 6 | */ 7 | 8 | object RecordingLogger extends Logger { 9 | private val buffer = ListBuffer[String]() 10 | 11 | def hasErrors = buffer.nonEmpty 12 | 13 | def readAndClear() = { 14 | val res = buffer.mkString("\n") 15 | buffer.clear() 16 | res 17 | } 18 | 19 | def clear() { 20 | buffer.clear() 21 | } 22 | 23 | def log(level: Level.Value, message: => String) = 24 | if (level == Level.Error) { 25 | buffer += message 26 | } 27 | 28 | // we don't log success here 29 | def success(message: => String) = () 30 | 31 | // invoked when a task throws an exception. invoked late, when the exception is logged, i.e. 32 | // just before returning to the prompt. therefore we do nothing: storing the exception in the 33 | // buffer would happen *after* the `handleFailure` reads the buffer. 34 | def trace(t: => Throwable) = () 35 | } 36 | -------------------------------------------------------------------------------- /objsets/project/RecordingLogger.scala: -------------------------------------------------------------------------------- 1 | import sbt._ 2 | import collection.mutable.ListBuffer 3 | 4 | /** 5 | * Logger to capture compiler output, test output 6 | */ 7 | 8 | object RecordingLogger extends Logger { 9 | private val buffer = ListBuffer[String]() 10 | 11 | def hasErrors = buffer.nonEmpty 12 | 13 | def readAndClear() = { 14 | val res = buffer.mkString("\n") 15 | buffer.clear() 16 | res 17 | } 18 | 19 | def clear() { 20 | buffer.clear() 21 | } 22 | 23 | def log(level: Level.Value, message: => String) = 24 | if (level == Level.Error) { 25 | buffer += message 26 | } 27 | 28 | // we don't log success here 29 | def success(message: => String) = () 30 | 31 | // invoked when a task throws an exception. invoked late, when the exception is logged, i.e. 32 | // just before returning to the prompt. therefore we do nothing: storing the exception in the 33 | // buffer would happen *after* the `handleFailure` reads the buffer. 34 | def trace(t: => Throwable) = () 35 | } 36 | -------------------------------------------------------------------------------- /patmat/project/RecordingLogger.scala: -------------------------------------------------------------------------------- 1 | import sbt._ 2 | import collection.mutable.ListBuffer 3 | 4 | /** 5 | * Logger to capture compiler output, test output 6 | */ 7 | 8 | object RecordingLogger extends Logger { 9 | private val buffer = ListBuffer[String]() 10 | 11 | def hasErrors = buffer.nonEmpty 12 | 13 | def readAndClear() = { 14 | val res = buffer.mkString("\n") 15 | buffer.clear() 16 | res 17 | } 18 | 19 | def clear() { 20 | buffer.clear() 21 | } 22 | 23 | def log(level: Level.Value, message: => String) = 24 | if (level == Level.Error) { 25 | buffer += message 26 | } 27 | 28 | // we don't log success here 29 | def success(message: => String) = () 30 | 31 | // invoked when a task throws an exception. invoked late, when the exception is logged, i.e. 32 | // just before returning to the prompt. therefore we do nothing: storing the exception in the 33 | // buffer would happen *after* the `handleFailure` reads the buffer. 34 | def trace(t: => Throwable) = () 35 | } 36 | -------------------------------------------------------------------------------- /recfun/project/RecordingLogger.scala: -------------------------------------------------------------------------------- 1 | import sbt._ 2 | import collection.mutable.ListBuffer 3 | 4 | /** 5 | * Logger to capture compiler output, test output 6 | */ 7 | 8 | object RecordingLogger extends Logger { 9 | private val buffer = ListBuffer[String]() 10 | 11 | def hasErrors = buffer.nonEmpty 12 | 13 | def readAndClear() = { 14 | val res = buffer.mkString("\n") 15 | buffer.clear() 16 | res 17 | } 18 | 19 | def clear() { 20 | buffer.clear() 21 | } 22 | 23 | def log(level: Level.Value, message: => String) = 24 | if (level == Level.Error) { 25 | buffer += message 26 | } 27 | 28 | // we don't log success here 29 | def success(message: => String) = () 30 | 31 | // invoked when a task throws an exception. invoked late, when the exception is logged, i.e. 32 | // just before returning to the prompt. therefore we do nothing: storing the exception in the 33 | // buffer would happen *after* the `handleFailure` reads the buffer. 34 | def trace(t: => Throwable) = () 35 | } 36 | -------------------------------------------------------------------------------- /streams/project/RecordingLogger.scala: -------------------------------------------------------------------------------- 1 | import sbt._ 2 | import collection.mutable.ListBuffer 3 | 4 | /** 5 | * Logger to capture compiler output, test output 6 | */ 7 | 8 | object RecordingLogger extends Logger { 9 | private val buffer = ListBuffer[String]() 10 | 11 | def hasErrors = buffer.nonEmpty 12 | 13 | def readAndClear() = { 14 | val res = buffer.mkString("\n") 15 | buffer.clear() 16 | res 17 | } 18 | 19 | def clear() { 20 | buffer.clear() 21 | } 22 | 23 | def log(level: Level.Value, message: => String) = 24 | if (level == Level.Error) { 25 | buffer += message 26 | } 27 | 28 | // we don't log success here 29 | def success(message: => String) = () 30 | 31 | // invoked when a task throws an exception. invoked late, when the exception is logged, i.e. 32 | // just before returning to the prompt. therefore we do nothing: storing the exception in the 33 | // buffer would happen *after* the `handleFailure` reads the buffer. 34 | def trace(t: => Throwable) = () 35 | } 36 | -------------------------------------------------------------------------------- /ass_zip/example/project/RecordingLogger.scala: -------------------------------------------------------------------------------- 1 | import sbt._ 2 | import collection.mutable.ListBuffer 3 | 4 | /** 5 | * Logger to capture compiler output, test output 6 | */ 7 | 8 | object RecordingLogger extends Logger { 9 | private val buffer = ListBuffer[String]() 10 | 11 | def hasErrors = buffer.nonEmpty 12 | 13 | def readAndClear() = { 14 | val res = buffer.mkString("\n") 15 | buffer.clear() 16 | res 17 | } 18 | 19 | def clear() { 20 | buffer.clear() 21 | } 22 | 23 | def log(level: Level.Value, message: => String) = 24 | if (level == Level.Error) { 25 | buffer += message 26 | } 27 | 28 | // we don't log success here 29 | def success(message: => String) = () 30 | 31 | // invoked when a task throws an exception. invoked late, when the exception is logged, i.e. 32 | // just before returning to the prompt. therefore we do nothing: storing the exception in the 33 | // buffer would happen *after* the `handleFailure` reads the buffer. 34 | def trace(t: => Throwable) = () 35 | } 36 | -------------------------------------------------------------------------------- /calculator/src/main/scala/calculator/Calculator.scala: -------------------------------------------------------------------------------- 1 | package calculator 2 | 3 | sealed abstract class Expr 4 | final case class Literal(v: Double) extends Expr 5 | final case class Ref(name: String) extends Expr 6 | final case class Plus(a: Expr, b: Expr) extends Expr 7 | final case class Minus(a: Expr, b: Expr) extends Expr 8 | final case class Times(a: Expr, b: Expr) extends Expr 9 | final case class Divide(a: Expr, b: Expr) extends Expr 10 | 11 | object Calculator { 12 | def computeValues( 13 | namedExpressions: Map[String, Signal[Expr]]): Map[String, Signal[Double]] = { 14 | ??? 15 | } 16 | 17 | def eval(expr: Expr, references: Map[String, Signal[Expr]]): Double = { 18 | ??? 19 | } 20 | 21 | /** Get the Expr for a referenced variables. 22 | * If the variable is not known, returns a literal NaN. 23 | */ 24 | private def getReferenceExpr(name: String, 25 | references: Map[String, Signal[Expr]]) = { 26 | references.get(name).fold[Expr] { 27 | Literal(Double.NaN) 28 | } { exprSignal => 29 | exprSignal() 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /calculator/src/main/scala/calculator/TweetLength.scala: -------------------------------------------------------------------------------- 1 | package calculator 2 | 3 | object TweetLength { 4 | final val MaxTweetLength = 140 5 | 6 | def tweetRemainingCharsCount(tweetText: Signal[String]): Signal[Int] = { 7 | ??? 8 | } 9 | 10 | def colorForRemainingCharsCount(remainingCharsCount: Signal[Int]): Signal[String] = { 11 | ??? 12 | } 13 | 14 | /** Computes the length of a tweet, given its text string. 15 | * This is not equivalent to text.length, as tweet lengths count the number 16 | * of Unicode *code points* in the string. 17 | * Note that this is still a simplified view of the reality. Full details 18 | * can be found at 19 | * https://dev.twitter.com/overview/api/counting-characters 20 | */ 21 | private def tweetLength(text: String): Int = { 22 | /* This should be simply text.codePointCount(0, text.length), but it 23 | * is not implemented in Scala.js 0.6.2. 24 | */ 25 | if (text.isEmpty) 0 26 | else { 27 | text.length - text.init.zip(text.tail).count( 28 | (Character.isSurrogatePair _).tupled) 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /streams/src/main/scala/streams/Bloxorz.scala: -------------------------------------------------------------------------------- 1 | package streams 2 | 3 | /** 4 | * A main object that can be used to execute the Bloxorz solver 5 | */ 6 | object Bloxorz extends App { 7 | 8 | /** 9 | * A level constructed using the `InfiniteTerrain` trait which defines 10 | * the terrain to be valid at every position. 11 | */ 12 | object InfiniteLevel extends Solver with InfiniteTerrain { 13 | val startPos = Pos(1,3) 14 | val goal = Pos(5,8) 15 | } 16 | 17 | println(InfiniteLevel.solution) 18 | 19 | /** 20 | * A simple level constructed using the StringParserTerrain 21 | */ 22 | abstract class Level extends Solver with StringParserTerrain 23 | 24 | object Level0 extends Level { 25 | val level = 26 | """------ 27 | |--ST-- 28 | |--oo-- 29 | |--oo-- 30 | |------""".stripMargin 31 | } 32 | 33 | println(Level0.solution) 34 | 35 | /** 36 | * Level 1 of the official Bloxorz game 37 | */ 38 | object Level1 extends Level { 39 | val level = 40 | """ooo------- 41 | |oSoooo---- 42 | |ooooooooo- 43 | |-ooooooooo 44 | |-----ooToo 45 | |------ooo-""".stripMargin 46 | } 47 | 48 | println(Level1.solution) 49 | } 50 | -------------------------------------------------------------------------------- /forcomp/src/main/scala/common/package.scala: -------------------------------------------------------------------------------- 1 | import java.io.File 2 | 3 | package object common { 4 | 5 | /** An alias for the `Nothing` type. 6 | * Denotes that the type should be filled in. 7 | */ 8 | type ??? = Nothing 9 | 10 | /** An alias for the `Any` type. 11 | * Denotes that the type should be filled in. 12 | */ 13 | type *** = Any 14 | 15 | 16 | /** 17 | * Get a child of a file. For example, 18 | * 19 | * subFile(homeDir, "b", "c") 20 | * 21 | * corresponds to ~/b/c 22 | */ 23 | def subFile(file: File, children: String*) = { 24 | children.foldLeft(file)((file, child) => new File(file, child)) 25 | } 26 | 27 | /** 28 | * Get a resource from the `src/main/resources` directory. Eclipse does not copy 29 | * resources to the output directory, then the class loader cannot find them. 30 | */ 31 | def resourceAsStreamFromSrc(resourcePath: List[String]): Option[java.io.InputStream] = { 32 | val classesDir = new File(getClass.getResource(".").toURI) 33 | val projectDir = classesDir.getParentFile.getParentFile.getParentFile.getParentFile 34 | val resourceFile = subFile(projectDir, ("src" :: "main" :: "resources" :: resourcePath): _*) 35 | if (resourceFile.exists) 36 | Some(new java.io.FileInputStream(resourceFile)) 37 | else 38 | None 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /funsets/src/main/scala/common/package.scala: -------------------------------------------------------------------------------- 1 | import java.io.File 2 | 3 | package object common { 4 | 5 | /** An alias for the `Nothing` type. 6 | * Denotes that the type should be filled in. 7 | */ 8 | type ??? = Nothing 9 | 10 | /** An alias for the `Any` type. 11 | * Denotes that the type should be filled in. 12 | */ 13 | type *** = Any 14 | 15 | 16 | /** 17 | * Get a child of a file. For example, 18 | * 19 | * subFile(homeDir, "b", "c") 20 | * 21 | * corresponds to ~/b/c 22 | */ 23 | def subFile(file: File, children: String*) = { 24 | children.foldLeft(file)((file, child) => new File(file, child)) 25 | } 26 | 27 | /** 28 | * Get a resource from the `src/main/resources` directory. Eclipse does not copy 29 | * resources to the output directory, then the class loader cannot find them. 30 | */ 31 | def resourceAsStreamFromSrc(resourcePath: List[String]): Option[java.io.InputStream] = { 32 | val classesDir = new File(getClass.getResource(".").toURI) 33 | val projectDir = classesDir.getParentFile.getParentFile.getParentFile.getParentFile 34 | val resourceFile = subFile(projectDir, ("src" :: "main" :: "resources" :: resourcePath): _*) 35 | if (resourceFile.exists) 36 | Some(new java.io.FileInputStream(resourceFile)) 37 | else 38 | None 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /objsets/src/main/scala/common/package.scala: -------------------------------------------------------------------------------- 1 | import java.io.File 2 | 3 | package object common { 4 | 5 | /** An alias for the `Nothing` type. 6 | * Denotes that the type should be filled in. 7 | */ 8 | type ??? = Nothing 9 | 10 | /** An alias for the `Any` type. 11 | * Denotes that the type should be filled in. 12 | */ 13 | type *** = Any 14 | 15 | 16 | /** 17 | * Get a child of a file. For example, 18 | * 19 | * subFile(homeDir, "b", "c") 20 | * 21 | * corresponds to ~/b/c 22 | */ 23 | def subFile(file: File, children: String*) = { 24 | children.foldLeft(file)((file, child) => new File(file, child)) 25 | } 26 | 27 | /** 28 | * Get a resource from the `src/main/resources` directory. Eclipse does not copy 29 | * resources to the output directory, then the class loader cannot find them. 30 | */ 31 | def resourceAsStreamFromSrc(resourcePath: List[String]): Option[java.io.InputStream] = { 32 | val classesDir = new File(getClass.getResource(".").toURI) 33 | val projectDir = classesDir.getParentFile.getParentFile.getParentFile.getParentFile 34 | val resourceFile = subFile(projectDir, ("src" :: "main" :: "resources" :: resourcePath): _*) 35 | if (resourceFile.exists) 36 | Some(new java.io.FileInputStream(resourceFile)) 37 | else 38 | None 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /patmat/src/main/scala/common/package.scala: -------------------------------------------------------------------------------- 1 | import java.io.File 2 | 3 | package object common { 4 | 5 | /** An alias for the `Nothing` type. 6 | * Denotes that the type should be filled in. 7 | */ 8 | type ??? = Nothing 9 | 10 | /** An alias for the `Any` type. 11 | * Denotes that the type should be filled in. 12 | */ 13 | type *** = Any 14 | 15 | 16 | /** 17 | * Get a child of a file. For example, 18 | * 19 | * subFile(homeDir, "b", "c") 20 | * 21 | * corresponds to ~/b/c 22 | */ 23 | def subFile(file: File, children: String*) = { 24 | children.foldLeft(file)((file, child) => new File(file, child)) 25 | } 26 | 27 | /** 28 | * Get a resource from the `src/main/resources` directory. Eclipse does not copy 29 | * resources to the output directory, then the class loader cannot find them. 30 | */ 31 | def resourceAsStreamFromSrc(resourcePath: List[String]): Option[java.io.InputStream] = { 32 | val classesDir = new File(getClass.getResource(".").toURI) 33 | val projectDir = classesDir.getParentFile.getParentFile.getParentFile.getParentFile 34 | val resourceFile = subFile(projectDir, ("src" :: "main" :: "resources" :: resourcePath): _*) 35 | if (resourceFile.exists) 36 | Some(new java.io.FileInputStream(resourceFile)) 37 | else 38 | None 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /recfun/src/main/scala/common/package.scala: -------------------------------------------------------------------------------- 1 | import java.io.File 2 | 3 | package object common { 4 | 5 | /** An alias for the `Nothing` type. 6 | * Denotes that the type should be filled in. 7 | */ 8 | type ??? = Nothing 9 | 10 | /** An alias for the `Any` type. 11 | * Denotes that the type should be filled in. 12 | */ 13 | type *** = Any 14 | 15 | 16 | /** 17 | * Get a child of a file. For example, 18 | * 19 | * subFile(homeDir, "b", "c") 20 | * 21 | * corresponds to ~/b/c 22 | */ 23 | def subFile(file: File, children: String*) = { 24 | children.foldLeft(file)((file, child) => new File(file, child)) 25 | } 26 | 27 | /** 28 | * Get a resource from the `src/main/resources` directory. Eclipse does not copy 29 | * resources to the output directory, then the class loader cannot find them. 30 | */ 31 | def resourceAsStreamFromSrc(resourcePath: List[String]): Option[java.io.InputStream] = { 32 | val classesDir = new File(getClass.getResource(".").toURI) 33 | val projectDir = classesDir.getParentFile.getParentFile.getParentFile.getParentFile 34 | val resourceFile = subFile(projectDir, ("src" :: "main" :: "resources" :: resourcePath): _*) 35 | if (resourceFile.exists) 36 | Some(new java.io.FileInputStream(resourceFile)) 37 | else 38 | None 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /streams/src/main/scala/common/package.scala: -------------------------------------------------------------------------------- 1 | import java.io.File 2 | 3 | package object common { 4 | 5 | /** An alias for the `Nothing` type. 6 | * Denotes that the type should be filled in. 7 | */ 8 | type ??? = Nothing 9 | 10 | /** An alias for the `Any` type. 11 | * Denotes that the type should be filled in. 12 | */ 13 | type *** = Any 14 | 15 | 16 | /** 17 | * Get a child of a file. For example, 18 | * 19 | * subFile(homeDir, "b", "c") 20 | * 21 | * corresponds to ~/b/c 22 | */ 23 | def subFile(file: File, children: String*) = { 24 | children.foldLeft(file)((file, child) => new File(file, child)) 25 | } 26 | 27 | /** 28 | * Get a resource from the `src/main/resources` directory. Eclipse does not copy 29 | * resources to the output directory, then the class loader cannot find them. 30 | */ 31 | def resourceAsStreamFromSrc(resourcePath: List[String]): Option[java.io.InputStream] = { 32 | val classesDir = new File(getClass.getResource(".").toURI) 33 | val projectDir = classesDir.getParentFile.getParentFile.getParentFile.getParentFile 34 | val resourceFile = subFile(projectDir, ("src" :: "main" :: "resources" :: resourcePath): _*) 35 | if (resourceFile.exists) 36 | Some(new java.io.FileInputStream(resourceFile)) 37 | else 38 | None 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /actorbintree/src/main/scala/common/package.scala: -------------------------------------------------------------------------------- 1 | import java.io.File 2 | 3 | package object common { 4 | 5 | /** An alias for the `Nothing` type. 6 | * Denotes that the type should be filled in. 7 | */ 8 | type ??? = Nothing 9 | 10 | /** An alias for the `Any` type. 11 | * Denotes that the type should be filled in. 12 | */ 13 | type *** = Any 14 | 15 | 16 | /** 17 | * Get a child of a file. For example, 18 | * 19 | * subFile(homeDir, "b", "c") 20 | * 21 | * corresponds to ~/b/c 22 | */ 23 | def subFile(file: File, children: String*) = { 24 | children.foldLeft(file)((file, child) => new File(file, child)) 25 | } 26 | 27 | /** 28 | * Get a resource from the `src/main/resources` directory. Eclipse does not copy 29 | * resources to the output directory, then the class loader cannot find them. 30 | */ 31 | def resourceAsStreamFromSrc(resourcePath: List[String]): Option[java.io.InputStream] = { 32 | val classesDir = new File(getClass.getResource(".").toURI) 33 | val projectDir = classesDir.getParentFile.getParentFile.getParentFile.getParentFile 34 | val resourceFile = subFile(projectDir, ("src" :: "main" :: "resources" :: resourcePath): _*) 35 | if (resourceFile.exists) 36 | Some(new java.io.FileInputStream(resourceFile)) 37 | else 38 | None 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /calculator/src/main/scala/common/package.scala: -------------------------------------------------------------------------------- 1 | import java.io.File 2 | 3 | package object common { 4 | 5 | /** An alias for the `Nothing` type. 6 | * Denotes that the type should be filled in. 7 | */ 8 | type ??? = Nothing 9 | 10 | /** An alias for the `Any` type. 11 | * Denotes that the type should be filled in. 12 | */ 13 | type *** = Any 14 | 15 | 16 | /** 17 | * Get a child of a file. For example, 18 | * 19 | * subFile(homeDir, "b", "c") 20 | * 21 | * corresponds to ~/b/c 22 | */ 23 | def subFile(file: File, children: String*) = { 24 | children.foldLeft(file)((file, child) => new File(file, child)) 25 | } 26 | 27 | /** 28 | * Get a resource from the `src/main/resources` directory. Eclipse does not copy 29 | * resources to the output directory, then the class loader cannot find them. 30 | */ 31 | def resourceAsStreamFromSrc(resourcePath: List[String]): Option[java.io.InputStream] = { 32 | val classesDir = new File(getClass.getResource(".").toURI) 33 | val projectDir = classesDir.getParentFile.getParentFile.getParentFile.getParentFile 34 | val resourceFile = subFile(projectDir, ("src" :: "main" :: "resources" :: resourcePath): _*) 35 | if (resourceFile.exists) 36 | Some(new java.io.FileInputStream(resourceFile)) 37 | else 38 | None 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /nodescala/src/main/scala/common/package.scala: -------------------------------------------------------------------------------- 1 | import java.io.File 2 | 3 | package object common { 4 | 5 | /** An alias for the `Nothing` type. 6 | * Denotes that the type should be filled in. 7 | */ 8 | type ??? = Nothing 9 | 10 | /** An alias for the `Any` type. 11 | * Denotes that the type should be filled in. 12 | */ 13 | type *** = Any 14 | 15 | 16 | /** 17 | * Get a child of a file. For example, 18 | * 19 | * subFile(homeDir, "b", "c") 20 | * 21 | * corresponds to ~/b/c 22 | */ 23 | def subFile(file: File, children: String*) = { 24 | children.foldLeft(file)((file, child) => new File(file, child)) 25 | } 26 | 27 | /** 28 | * Get a resource from the `src/main/resources` directory. Eclipse does not copy 29 | * resources to the output directory, then the class loader cannot find them. 30 | */ 31 | def resourceAsStreamFromSrc(resourcePath: List[String]): Option[java.io.InputStream] = { 32 | val classesDir = new File(getClass.getResource(".").toURI) 33 | val projectDir = classesDir.getParentFile.getParentFile.getParentFile.getParentFile 34 | val resourceFile = subFile(projectDir, ("src" :: "main" :: "resources" :: resourcePath): _*) 35 | if (resourceFile.exists) 36 | Some(new java.io.FileInputStream(resourceFile)) 37 | else 38 | None 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /quickcheck/src/main/scala/common/package.scala: -------------------------------------------------------------------------------- 1 | import java.io.File 2 | 3 | package object common { 4 | 5 | /** An alias for the `Nothing` type. 6 | * Denotes that the type should be filled in. 7 | */ 8 | type ??? = Nothing 9 | 10 | /** An alias for the `Any` type. 11 | * Denotes that the type should be filled in. 12 | */ 13 | type *** = Any 14 | 15 | 16 | /** 17 | * Get a child of a file. For example, 18 | * 19 | * subFile(homeDir, "b", "c") 20 | * 21 | * corresponds to ~/b/c 22 | */ 23 | def subFile(file: File, children: String*) = { 24 | children.foldLeft(file)((file, child) => new File(file, child)) 25 | } 26 | 27 | /** 28 | * Get a resource from the `src/main/resources` directory. Eclipse does not copy 29 | * resources to the output directory, then the class loader cannot find them. 30 | */ 31 | def resourceAsStreamFromSrc(resourcePath: List[String]): Option[java.io.InputStream] = { 32 | val classesDir = new File(getClass.getResource(".").toURI) 33 | val projectDir = classesDir.getParentFile.getParentFile.getParentFile.getParentFile 34 | val resourceFile = subFile(projectDir, ("src" :: "main" :: "resources" :: resourcePath): _*) 35 | if (resourceFile.exists) 36 | Some(new java.io.FileInputStream(resourceFile)) 37 | else 38 | None 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /suggestions/src/main/scala/common/package.scala: -------------------------------------------------------------------------------- 1 | import java.io.File 2 | 3 | package object common { 4 | 5 | /** An alias for the `Nothing` type. 6 | * Denotes that the type should be filled in. 7 | */ 8 | type ??? = Nothing 9 | 10 | /** An alias for the `Any` type. 11 | * Denotes that the type should be filled in. 12 | */ 13 | type *** = Any 14 | 15 | 16 | /** 17 | * Get a child of a file. For example, 18 | * 19 | * subFile(homeDir, "b", "c") 20 | * 21 | * corresponds to ~/b/c 22 | */ 23 | def subFile(file: File, children: String*) = { 24 | children.foldLeft(file)((file, child) => new File(file, child)) 25 | } 26 | 27 | /** 28 | * Get a resource from the `src/main/resources` directory. Eclipse does not copy 29 | * resources to the output directory, then the class loader cannot find them. 30 | */ 31 | def resourceAsStreamFromSrc(resourcePath: List[String]): Option[java.io.InputStream] = { 32 | val classesDir = new File(getClass.getResource(".").toURI) 33 | val projectDir = classesDir.getParentFile.getParentFile.getParentFile.getParentFile 34 | val resourceFile = subFile(projectDir, ("src" :: "main" :: "resources" :: resourcePath): _*) 35 | if (resourceFile.exists) 36 | Some(new java.io.FileInputStream(resourceFile)) 37 | else 38 | None 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /ass_zip/example/src/main/scala/common/package.scala: -------------------------------------------------------------------------------- 1 | import java.io.File 2 | 3 | package object common { 4 | 5 | /** An alias for the `Nothing` type. 6 | * Denotes that the type should be filled in. 7 | */ 8 | type ??? = Nothing 9 | 10 | /** An alias for the `Any` type. 11 | * Denotes that the type should be filled in. 12 | */ 13 | type *** = Any 14 | 15 | 16 | /** 17 | * Get a child of a file. For example, 18 | * 19 | * subFile(homeDir, "b", "c") 20 | * 21 | * corresponds to ~/b/c 22 | */ 23 | def subFile(file: File, children: String*) = { 24 | children.foldLeft(file)((file, child) => new File(file, child)) 25 | } 26 | 27 | /** 28 | * Get a resource from the `src/main/resources` directory. Eclipse does not copy 29 | * resources to the output directory, then the class loader cannot find them. 30 | */ 31 | def resourceAsStreamFromSrc(resourcePath: List[String]): Option[java.io.InputStream] = { 32 | val classesDir = new File(getClass.getResource(".").toURI) 33 | val projectDir = classesDir.getParentFile.getParentFile.getParentFile.getParentFile 34 | val resourceFile = subFile(projectDir, ("src" :: "main" :: "resources" :: resourcePath): _*) 35 | if (resourceFile.exists) 36 | Some(new java.io.FileInputStream(resourceFile)) 37 | else 38 | None 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /nodescala/src/main/scala/nodescala/Main.scala: -------------------------------------------------------------------------------- 1 | package nodescala 2 | 3 | import scala.language.postfixOps 4 | import scala.concurrent._ 5 | import scala.concurrent.duration._ 6 | import ExecutionContext.Implicits.global 7 | import scala.async.Async.{async, await} 8 | 9 | object Main { 10 | 11 | def main(args: Array[String]) { 12 | // 1. instantiate the server at 8191, relative path "/test", 13 | // and have the response return headers of the request 14 | val myServer = new NodeScala.Default(8191) 15 | val myServerSubscription = myServer.start("/test") { request => 16 | for (kv <- request.iterator) yield (kv + "\n").toString 17 | } 18 | 19 | // 2. create a future that expects some user input `x` 20 | // and continues with a `"You entered... " + x` message 21 | val userInterrupted = Future.userInput("Hit ENTER to cancel... ") continueWith { 22 | f => "You entered... " + f.now 23 | } 24 | 25 | // TO IMPLEMENT 26 | // 3. create a future that completes after 20 seconds 27 | // and continues with a `"Server timeout!"` message 28 | val timeOut: Future[String] = ??? 29 | 30 | // TO IMPLEMENT 31 | // 4. create a future that completes when either 20 seconds elapse 32 | // or the user enters some text and presses ENTER 33 | val terminationRequested: Future[String] = ??? 34 | 35 | // TO IMPLEMENT 36 | // 5. unsubscribe from the server 37 | terminationRequested onSuccess { 38 | case msg => ??? 39 | } 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /patmat/src/test/scala/patmat/HuffmanSuite.scala: -------------------------------------------------------------------------------- 1 | package patmat 2 | 3 | import org.scalatest.FunSuite 4 | 5 | import org.junit.runner.RunWith 6 | import org.scalatest.junit.JUnitRunner 7 | 8 | import patmat.Huffman._ 9 | 10 | @RunWith(classOf[JUnitRunner]) 11 | class HuffmanSuite extends FunSuite { 12 | trait TestTrees { 13 | val t1 = Fork(Leaf('a',2), Leaf('b',3), List('a','b'), 5) 14 | val t2 = Fork(Fork(Leaf('a',2), Leaf('b',3), List('a','b'), 5), Leaf('d',4), List('a','b','d'), 9) 15 | } 16 | 17 | test("weight of a larger tree") { 18 | new TestTrees { 19 | assert(weight(t1) === 5) 20 | } 21 | } 22 | 23 | test("chars of a larger tree") { 24 | new TestTrees { 25 | assert(chars(t2) === List('a','b','d')) 26 | } 27 | } 28 | 29 | test("string2chars(\"hello, world\")") { 30 | assert(string2Chars("hello, world") === List('h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd')) 31 | } 32 | 33 | test("makeOrderedLeafList for some frequency table") { 34 | assert(makeOrderedLeafList(List(('t', 2), ('e', 1), ('x', 3))) === List(Leaf('e',1), Leaf('t',2), Leaf('x',3))) 35 | } 36 | 37 | test("combine of some leaf list") { 38 | val leaflist = List(Leaf('e', 1), Leaf('t', 2), Leaf('x', 4)) 39 | assert(combine(leaflist) === List(Fork(Leaf('e',1),Leaf('t',2),List('e', 't'),3), Leaf('x',4))) 40 | } 41 | 42 | test("decode and encode a very short text should be identity") { 43 | new TestTrees { 44 | assert(decode(t1, encode(t1)("ab".toList)) === "ab".toList) 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /ass_zip/example/src/main/scala/example/Lists.scala: -------------------------------------------------------------------------------- 1 | package example 2 | 3 | import common._ 4 | 5 | object Lists { 6 | /** 7 | * This method computes the sum of all elements in the list xs. There are 8 | * multiple techniques that can be used for implementing this method, and 9 | * you will learn during the class. 10 | * 11 | * For this example assignment you can use the following methods in class 12 | * `List`: 13 | * 14 | * - `xs.isEmpty: Boolean` returns `true` if the list `xs` is empty 15 | * - `xs.head: Int` returns the head element of the list `xs`. If the list 16 | * is empty an exception is thrown 17 | * - `xs.tail: List[Int]` returns the tail of the list `xs`, i.e. the the 18 | * list `xs` without its `head` element 19 | * 20 | * ''Hint:'' instead of writing a `for` or `while` loop, think of a recursive 21 | * solution. 22 | * 23 | * @param xs A list of natural numbers 24 | * @return The sum of all elements in `xs` 25 | */ 26 | def sum(xs: List[Int]): Int = ??? 27 | 28 | /** 29 | * This method returns the largest element in a list of integers. If the 30 | * list `xs` is empty it throws a `java.util.NoSuchElementException`. 31 | * 32 | * You can use the same methods of the class `List` as mentioned above. 33 | * 34 | * ''Hint:'' Again, think of a recursive solution instead of using looping 35 | * constructs. You might need to define an auxiliary method. 36 | * 37 | * @param xs A list of natural numbers 38 | * @return The largest element in `xs` 39 | * @throws java.util.NoSuchElementException if `xs` is an empty list 40 | */ 41 | def max(xs: List[Int]): Int = ??? 42 | } 43 | -------------------------------------------------------------------------------- /calculator/src/main/scala/calculator/Signal.scala: -------------------------------------------------------------------------------- 1 | package calculator 2 | 3 | import scala.util.DynamicVariable 4 | 5 | class Signal[T](expr: => T) { 6 | import Signal._ 7 | private var myExpr: () => T = _ 8 | private var myValue: T = _ 9 | private var observers: Set[Signal[_]] = Set() 10 | private var observed: List[Signal[_]] = Nil 11 | update(expr) 12 | 13 | protected def computeValue(): Unit = { 14 | for (sig <- observed) 15 | sig.observers -= this 16 | observed = Nil 17 | val newValue = caller.withValue(this)(myExpr()) 18 | /* Disable the following "optimization" for the assignment, because we 19 | * want to be able to track the actual dependency graph in the tests. 20 | */ 21 | //if (myValue != newValue) { 22 | myValue = newValue 23 | val obs = observers 24 | observers = Set() 25 | obs.foreach(_.computeValue()) 26 | //} 27 | } 28 | 29 | protected def update(expr: => T): Unit = { 30 | myExpr = () => expr 31 | computeValue() 32 | } 33 | 34 | def apply() = { 35 | observers += caller.value 36 | assert(!caller.value.observers.contains(this), "cyclic signal definition") 37 | caller.value.observed ::= this 38 | myValue 39 | } 40 | } 41 | 42 | class Var[T](expr: => T) extends Signal[T](expr) { 43 | override def update(expr: => T): Unit = super.update(expr) 44 | } 45 | 46 | object Var { 47 | def apply[T](expr: => T) = new Var(expr) 48 | } 49 | 50 | object NoSignal extends Signal[Nothing](???) { 51 | override def computeValue() = () 52 | } 53 | 54 | object Signal { 55 | val caller = new DynamicVariable[Signal[_]](NoSignal) 56 | def apply[T](expr: => T) = new Signal(expr) 57 | } 58 | -------------------------------------------------------------------------------- /quickcheck/src/test/scala/quickcheck/QuickCheckSuite.scala: -------------------------------------------------------------------------------- 1 | package quickcheck 2 | 3 | import org.scalatest.FunSuite 4 | 5 | import org.junit.runner.RunWith 6 | import org.scalatest.junit.JUnitRunner 7 | 8 | import org.scalatest.prop.Checkers 9 | import org.scalacheck.Arbitrary._ 10 | import org.scalacheck.Prop 11 | import org.scalacheck.Prop._ 12 | 13 | import org.scalatest.exceptions.TestFailedException 14 | 15 | object QuickCheckBinomialHeap extends QuickCheckHeap with BinomialHeap 16 | 17 | @RunWith(classOf[JUnitRunner]) 18 | class QuickCheckSuite extends FunSuite with Checkers { 19 | def checkBogus(p: Prop) { 20 | var ok = false 21 | try { 22 | check(p) 23 | } catch { 24 | case e: TestFailedException => 25 | ok = true 26 | } 27 | assert(ok, "A bogus heap should NOT satisfy all properties. Try to find the bug!") 28 | } 29 | 30 | test("Binomial heap satisfies properties.") { 31 | check(new QuickCheckHeap with BinomialHeap) 32 | } 33 | 34 | test("Bogus (1) binomial heap does not satisfy properties.") { 35 | checkBogus(new QuickCheckHeap with Bogus1BinomialHeap) 36 | } 37 | 38 | test("Bogus (2) binomial heap does not satisfy properties.") { 39 | checkBogus(new QuickCheckHeap with Bogus2BinomialHeap) 40 | } 41 | 42 | test("Bogus (3) binomial heap does not satisfy properties.") { 43 | checkBogus(new QuickCheckHeap with Bogus3BinomialHeap) 44 | } 45 | 46 | test("Bogus (4) binomial heap does not satisfy properties.") { 47 | checkBogus(new QuickCheckHeap with Bogus4BinomialHeap) 48 | } 49 | 50 | test("Bogus (5) binomial heap does not satisfy properties.") { 51 | checkBogus(new QuickCheckHeap with Bogus5BinomialHeap) 52 | } 53 | 54 | test("") { 55 | checkBogus(new QuickCheckHeap with Bogus2BinomialHeap) 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /streams/src/test/scala/streams/BloxorzSuite.scala: -------------------------------------------------------------------------------- 1 | package streams 2 | 3 | import org.scalatest.FunSuite 4 | 5 | import org.junit.runner.RunWith 6 | import org.scalatest.junit.JUnitRunner 7 | 8 | import Bloxorz._ 9 | 10 | @RunWith(classOf[JUnitRunner]) 11 | class BloxorzSuite extends FunSuite { 12 | 13 | trait SolutionChecker extends GameDef with Solver with StringParserTerrain { 14 | /** 15 | * This method applies a list of moves `ls` to the block at position 16 | * `startPos`. This can be used to verify if a certain list of moves 17 | * is a valid solution, i.e. leads to the goal. 18 | */ 19 | def solve(ls: List[Move]): Block = 20 | ls.foldLeft(startBlock) { case (block, move) => move match { 21 | case Left => block.left 22 | case Right => block.right 23 | case Up => block.up 24 | case Down => block.down 25 | } 26 | } 27 | } 28 | 29 | trait Level1 extends SolutionChecker { 30 | /* terrain for level 1*/ 31 | 32 | val level = 33 | """ooo------- 34 | |oSoooo---- 35 | |ooooooooo- 36 | |-ooooooooo 37 | |-----ooToo 38 | |------ooo-""".stripMargin 39 | 40 | val optsolution = List(Right, Right, Down, Right, Right, Right, Down) 41 | } 42 | 43 | test("terrain function level 1") { 44 | new Level1 { 45 | assert(terrain(Pos(0,0)), "0,0") 46 | assert(!terrain(Pos(4,11)), "4,11") 47 | } 48 | } 49 | 50 | test("findChar level 1") { 51 | new Level1 { 52 | assert(startPos == Pos(1,1)) 53 | } 54 | } 55 | 56 | test("optimal solution for level 1") { 57 | new Level1 { 58 | assert(solve(solution) == Block(goal, goal)) 59 | } 60 | } 61 | 62 | test("optimal solution length for level 1") { 63 | new Level1 { 64 | assert(solution.length == optsolution.length) 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /objsets/src/test/scala/objsets/TweetSetSuite.scala: -------------------------------------------------------------------------------- 1 | package objsets 2 | 3 | import org.scalatest.FunSuite 4 | 5 | import org.junit.runner.RunWith 6 | import org.scalatest.junit.JUnitRunner 7 | 8 | @RunWith(classOf[JUnitRunner]) 9 | class TweetSetSuite extends FunSuite { 10 | trait TestSets { 11 | val set1 = new Empty 12 | val set2 = set1.incl(new Tweet("a", "a body", 20)) 13 | val set3 = set2.incl(new Tweet("b", "b body", 20)) 14 | val c = new Tweet("c", "c body", 7) 15 | val d = new Tweet("d", "d body", 9) 16 | val set4c = set3.incl(c) 17 | val set4d = set3.incl(d) 18 | val set5 = set4c.incl(d) 19 | } 20 | 21 | def asSet(tweets: TweetSet): Set[Tweet] = { 22 | var res = Set[Tweet]() 23 | tweets.foreach(res += _) 24 | res 25 | } 26 | 27 | def size(set: TweetSet): Int = asSet(set).size 28 | 29 | test("filter: on empty set") { 30 | new TestSets { 31 | assert(size(set1.filter(tw => tw.user == "a")) === 0) 32 | } 33 | } 34 | 35 | test("filter: a on set5") { 36 | new TestSets { 37 | assert(size(set5.filter(tw => tw.user == "a")) === 1) 38 | } 39 | } 40 | 41 | test("filter: 20 on set5") { 42 | new TestSets { 43 | assert(size(set5.filter(tw => tw.retweets == 20)) === 2) 44 | } 45 | } 46 | 47 | test("union: set4c and set4d") { 48 | new TestSets { 49 | assert(size(set4c.union(set4d)) === 4) 50 | } 51 | } 52 | 53 | test("union: with empty set (1)") { 54 | new TestSets { 55 | assert(size(set5.union(set1)) === 4) 56 | } 57 | } 58 | 59 | test("union: with empty set (2)") { 60 | new TestSets { 61 | assert(size(set1.union(set5)) === 4) 62 | } 63 | } 64 | 65 | test("descending: set5") { 66 | new TestSets { 67 | val trends = set5.descendingByRetweet 68 | assert(!trends.isEmpty) 69 | assert(trends.head.user == "a" || trends.head.user == "b") 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /calculator/src/test/scala/calculator/CalculatorSuite.scala: -------------------------------------------------------------------------------- 1 | package calculator 2 | 3 | import org.scalatest.FunSuite 4 | 5 | import org.junit.runner.RunWith 6 | import org.scalatest.junit.JUnitRunner 7 | 8 | import org.scalatest._ 9 | 10 | import TweetLength.MaxTweetLength 11 | 12 | @RunWith(classOf[JUnitRunner]) 13 | class CalculatorSuite extends FunSuite with ShouldMatchers { 14 | 15 | /****************** 16 | ** TWEET LENGTH ** 17 | ******************/ 18 | 19 | def tweetLength(text: String): Int = 20 | text.codePointCount(0, text.length) 21 | 22 | test("tweetRemainingCharsCount with a constant signal") { 23 | val result = TweetLength.tweetRemainingCharsCount(Var("hello world")) 24 | assert(result() == MaxTweetLength - tweetLength("hello world")) 25 | 26 | val tooLong = "foo" * 200 27 | val result2 = TweetLength.tweetRemainingCharsCount(Var(tooLong)) 28 | assert(result2() == MaxTweetLength - tweetLength(tooLong)) 29 | } 30 | 31 | test("tweetRemainingCharsCount with a supplementary char") { 32 | val result = TweetLength.tweetRemainingCharsCount(Var("foo blabla \uD83D\uDCA9 bar")) 33 | assert(result() == MaxTweetLength - tweetLength("foo blabla \uD83D\uDCA9 bar")) 34 | } 35 | 36 | 37 | test("colorForRemainingCharsCount with a constant signal") { 38 | val resultGreen1 = TweetLength.colorForRemainingCharsCount(Var(52)) 39 | assert(resultGreen1() == "green") 40 | val resultGreen2 = TweetLength.colorForRemainingCharsCount(Var(15)) 41 | assert(resultGreen2() == "green") 42 | 43 | val resultOrange1 = TweetLength.colorForRemainingCharsCount(Var(12)) 44 | assert(resultOrange1() == "orange") 45 | val resultOrange2 = TweetLength.colorForRemainingCharsCount(Var(0)) 46 | assert(resultOrange2() == "orange") 47 | 48 | val resultRed1 = TweetLength.colorForRemainingCharsCount(Var(-1)) 49 | assert(resultRed1() == "red") 50 | val resultRed2 = TweetLength.colorForRemainingCharsCount(Var(-5)) 51 | assert(resultRed2() == "red") 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /forcomp/project/Settings.scala: -------------------------------------------------------------------------------- 1 | object Settings { 2 | // when changing this, also look at 'scripts/gradingImpl' and the files in s3/settings 3 | // val courseId = "progfun-2012-001" 4 | def baseURL(courseId: String) = 5 | "https://class.coursera.org/" + courseId 6 | 7 | def challengeUrl(courseId: String) = baseURL(courseId) + "/assignment/challenge" 8 | 9 | def submitUrl(courseId: String) = baseURL(courseId) + "/assignment/submit" 10 | 11 | // def forumUrl(courseId: String) = baseURL(courseId) "/forum/index" 12 | 13 | // def submitQueueUrl(courseId: String) = baseURL(courseId) +"/assignment/api/pending_submission" 14 | 15 | def uploadFeedbackUrl(courseId: String) = baseURL(courseId) + "/assignment/api/score" 16 | 17 | val maxSubmitFileSize = { 18 | val mb = 1024 * 1024 19 | 10 * mb 20 | } 21 | 22 | val submissionDirName = "submission" 23 | 24 | val testResultsFileName = "scalaTestLog.txt" 25 | val policyFileName = "allowAllPolicy" 26 | val submissionJsonFileName = "submission.json" 27 | val submissionJarFileName = "submittedSrc.jar" 28 | 29 | // time in seconds that we give scalatest for running 30 | val scalaTestTimeout = 1200 31 | val individualTestTimeout = 40 32 | 33 | // default weight of each test in a GradingSuite, in case no weight is given 34 | val scalaTestDefaultWeigth = 10 35 | 36 | // when students leave print statements in their code, they end up in the output of the 37 | // system process running ScalaTest (ScalaTestRunner.scala); we need some limits. 38 | val maxOutputLines = 10*1000 39 | val maxOutputLineLength = 1000 40 | 41 | val scalaTestReportFileProperty = "scalatest.reportFile" 42 | val scalaTestIndividualTestTimeoutProperty = "scalatest.individualTestTimeout" 43 | val scalaTestReadableFilesProperty = "scalatest.readableFiles" 44 | val scalaTestDefaultWeigthProperty = "scalatest.defaultWeight" 45 | 46 | // debugging / developping options 47 | 48 | // don't decode json and unpack the submission sources, don't upload feedback 49 | val offlineMode = false 50 | } 51 | -------------------------------------------------------------------------------- /funsets/project/Settings.scala: -------------------------------------------------------------------------------- 1 | object Settings { 2 | // when changing this, also look at 'scripts/gradingImpl' and the files in s3/settings 3 | // val courseId = "progfun-2012-001" 4 | def baseURL(courseId: String) = 5 | "https://class.coursera.org/" + courseId 6 | 7 | def challengeUrl(courseId: String) = baseURL(courseId) + "/assignment/challenge" 8 | 9 | def submitUrl(courseId: String) = baseURL(courseId) + "/assignment/submit" 10 | 11 | // def forumUrl(courseId: String) = baseURL(courseId) "/forum/index" 12 | 13 | // def submitQueueUrl(courseId: String) = baseURL(courseId) +"/assignment/api/pending_submission" 14 | 15 | def uploadFeedbackUrl(courseId: String) = baseURL(courseId) + "/assignment/api/score" 16 | 17 | val maxSubmitFileSize = { 18 | val mb = 1024 * 1024 19 | 10 * mb 20 | } 21 | 22 | val submissionDirName = "submission" 23 | 24 | val testResultsFileName = "scalaTestLog.txt" 25 | val policyFileName = "allowAllPolicy" 26 | val submissionJsonFileName = "submission.json" 27 | val submissionJarFileName = "submittedSrc.jar" 28 | 29 | // time in seconds that we give scalatest for running 30 | val scalaTestTimeout = 1200 31 | val individualTestTimeout = 40 32 | 33 | // default weight of each test in a GradingSuite, in case no weight is given 34 | val scalaTestDefaultWeigth = 10 35 | 36 | // when students leave print statements in their code, they end up in the output of the 37 | // system process running ScalaTest (ScalaTestRunner.scala); we need some limits. 38 | val maxOutputLines = 10*1000 39 | val maxOutputLineLength = 1000 40 | 41 | val scalaTestReportFileProperty = "scalatest.reportFile" 42 | val scalaTestIndividualTestTimeoutProperty = "scalatest.individualTestTimeout" 43 | val scalaTestReadableFilesProperty = "scalatest.readableFiles" 44 | val scalaTestDefaultWeigthProperty = "scalatest.defaultWeight" 45 | 46 | // debugging / developping options 47 | 48 | // don't decode json and unpack the submission sources, don't upload feedback 49 | val offlineMode = false 50 | } 51 | -------------------------------------------------------------------------------- /objsets/project/Settings.scala: -------------------------------------------------------------------------------- 1 | object Settings { 2 | // when changing this, also look at 'scripts/gradingImpl' and the files in s3/settings 3 | // val courseId = "progfun-2012-001" 4 | def baseURL(courseId: String) = 5 | "https://class.coursera.org/" + courseId 6 | 7 | def challengeUrl(courseId: String) = baseURL(courseId) + "/assignment/challenge" 8 | 9 | def submitUrl(courseId: String) = baseURL(courseId) + "/assignment/submit" 10 | 11 | // def forumUrl(courseId: String) = baseURL(courseId) "/forum/index" 12 | 13 | // def submitQueueUrl(courseId: String) = baseURL(courseId) +"/assignment/api/pending_submission" 14 | 15 | def uploadFeedbackUrl(courseId: String) = baseURL(courseId) + "/assignment/api/score" 16 | 17 | val maxSubmitFileSize = { 18 | val mb = 1024 * 1024 19 | 10 * mb 20 | } 21 | 22 | val submissionDirName = "submission" 23 | 24 | val testResultsFileName = "scalaTestLog.txt" 25 | val policyFileName = "allowAllPolicy" 26 | val submissionJsonFileName = "submission.json" 27 | val submissionJarFileName = "submittedSrc.jar" 28 | 29 | // time in seconds that we give scalatest for running 30 | val scalaTestTimeout = 1200 31 | val individualTestTimeout = 40 32 | 33 | // default weight of each test in a GradingSuite, in case no weight is given 34 | val scalaTestDefaultWeigth = 10 35 | 36 | // when students leave print statements in their code, they end up in the output of the 37 | // system process running ScalaTest (ScalaTestRunner.scala); we need some limits. 38 | val maxOutputLines = 10*1000 39 | val maxOutputLineLength = 1000 40 | 41 | val scalaTestReportFileProperty = "scalatest.reportFile" 42 | val scalaTestIndividualTestTimeoutProperty = "scalatest.individualTestTimeout" 43 | val scalaTestReadableFilesProperty = "scalatest.readableFiles" 44 | val scalaTestDefaultWeigthProperty = "scalatest.defaultWeight" 45 | 46 | // debugging / developping options 47 | 48 | // don't decode json and unpack the submission sources, don't upload feedback 49 | val offlineMode = false 50 | } 51 | -------------------------------------------------------------------------------- /patmat/project/Settings.scala: -------------------------------------------------------------------------------- 1 | object Settings { 2 | // when changing this, also look at 'scripts/gradingImpl' and the files in s3/settings 3 | // val courseId = "progfun-2012-001" 4 | def baseURL(courseId: String) = 5 | "https://class.coursera.org/" + courseId 6 | 7 | def challengeUrl(courseId: String) = baseURL(courseId) + "/assignment/challenge" 8 | 9 | def submitUrl(courseId: String) = baseURL(courseId) + "/assignment/submit" 10 | 11 | // def forumUrl(courseId: String) = baseURL(courseId) "/forum/index" 12 | 13 | // def submitQueueUrl(courseId: String) = baseURL(courseId) +"/assignment/api/pending_submission" 14 | 15 | def uploadFeedbackUrl(courseId: String) = baseURL(courseId) + "/assignment/api/score" 16 | 17 | val maxSubmitFileSize = { 18 | val mb = 1024 * 1024 19 | 10 * mb 20 | } 21 | 22 | val submissionDirName = "submission" 23 | 24 | val testResultsFileName = "scalaTestLog.txt" 25 | val policyFileName = "allowAllPolicy" 26 | val submissionJsonFileName = "submission.json" 27 | val submissionJarFileName = "submittedSrc.jar" 28 | 29 | // time in seconds that we give scalatest for running 30 | val scalaTestTimeout = 1200 31 | val individualTestTimeout = 40 32 | 33 | // default weight of each test in a GradingSuite, in case no weight is given 34 | val scalaTestDefaultWeigth = 10 35 | 36 | // when students leave print statements in their code, they end up in the output of the 37 | // system process running ScalaTest (ScalaTestRunner.scala); we need some limits. 38 | val maxOutputLines = 10*1000 39 | val maxOutputLineLength = 1000 40 | 41 | val scalaTestReportFileProperty = "scalatest.reportFile" 42 | val scalaTestIndividualTestTimeoutProperty = "scalatest.individualTestTimeout" 43 | val scalaTestReadableFilesProperty = "scalatest.readableFiles" 44 | val scalaTestDefaultWeigthProperty = "scalatest.defaultWeight" 45 | 46 | // debugging / developping options 47 | 48 | // don't decode json and unpack the submission sources, don't upload feedback 49 | val offlineMode = false 50 | } 51 | -------------------------------------------------------------------------------- /recfun/project/Settings.scala: -------------------------------------------------------------------------------- 1 | object Settings { 2 | // when changing this, also look at 'scripts/gradingImpl' and the files in s3/settings 3 | // val courseId = "progfun-2012-001" 4 | def baseURL(courseId: String) = 5 | "https://class.coursera.org/" + courseId 6 | 7 | def challengeUrl(courseId: String) = baseURL(courseId) + "/assignment/challenge" 8 | 9 | def submitUrl(courseId: String) = baseURL(courseId) + "/assignment/submit" 10 | 11 | // def forumUrl(courseId: String) = baseURL(courseId) "/forum/index" 12 | 13 | // def submitQueueUrl(courseId: String) = baseURL(courseId) +"/assignment/api/pending_submission" 14 | 15 | def uploadFeedbackUrl(courseId: String) = baseURL(courseId) + "/assignment/api/score" 16 | 17 | val maxSubmitFileSize = { 18 | val mb = 1024 * 1024 19 | 10 * mb 20 | } 21 | 22 | val submissionDirName = "submission" 23 | 24 | val testResultsFileName = "scalaTestLog.txt" 25 | val policyFileName = "allowAllPolicy" 26 | val submissionJsonFileName = "submission.json" 27 | val submissionJarFileName = "submittedSrc.jar" 28 | 29 | // time in seconds that we give scalatest for running 30 | val scalaTestTimeout = 1200 31 | val individualTestTimeout = 40 32 | 33 | // default weight of each test in a GradingSuite, in case no weight is given 34 | val scalaTestDefaultWeigth = 10 35 | 36 | // when students leave print statements in their code, they end up in the output of the 37 | // system process running ScalaTest (ScalaTestRunner.scala); we need some limits. 38 | val maxOutputLines = 10*1000 39 | val maxOutputLineLength = 1000 40 | 41 | val scalaTestReportFileProperty = "scalatest.reportFile" 42 | val scalaTestIndividualTestTimeoutProperty = "scalatest.individualTestTimeout" 43 | val scalaTestReadableFilesProperty = "scalatest.readableFiles" 44 | val scalaTestDefaultWeigthProperty = "scalatest.defaultWeight" 45 | 46 | // debugging / developping options 47 | 48 | // don't decode json and unpack the submission sources, don't upload feedback 49 | val offlineMode = false 50 | } 51 | -------------------------------------------------------------------------------- /streams/project/Settings.scala: -------------------------------------------------------------------------------- 1 | object Settings { 2 | // when changing this, also look at 'scripts/gradingImpl' and the files in s3/settings 3 | // val courseId = "progfun-2012-001" 4 | def baseURL(courseId: String) = 5 | "https://class.coursera.org/" + courseId 6 | 7 | def challengeUrl(courseId: String) = baseURL(courseId) + "/assignment/challenge" 8 | 9 | def submitUrl(courseId: String) = baseURL(courseId) + "/assignment/submit" 10 | 11 | // def forumUrl(courseId: String) = baseURL(courseId) "/forum/index" 12 | 13 | // def submitQueueUrl(courseId: String) = baseURL(courseId) +"/assignment/api/pending_submission" 14 | 15 | def uploadFeedbackUrl(courseId: String) = baseURL(courseId) + "/assignment/api/score" 16 | 17 | val maxSubmitFileSize = { 18 | val mb = 1024 * 1024 19 | 10 * mb 20 | } 21 | 22 | val submissionDirName = "submission" 23 | 24 | val testResultsFileName = "scalaTestLog.txt" 25 | val policyFileName = "allowAllPolicy" 26 | val submissionJsonFileName = "submission.json" 27 | val submissionJarFileName = "submittedSrc.jar" 28 | 29 | // time in seconds that we give scalatest for running 30 | val scalaTestTimeout = 1200 31 | val individualTestTimeout = 40 32 | 33 | // default weight of each test in a GradingSuite, in case no weight is given 34 | val scalaTestDefaultWeigth = 10 35 | 36 | // when students leave print statements in their code, they end up in the output of the 37 | // system process running ScalaTest (ScalaTestRunner.scala); we need some limits. 38 | val maxOutputLines = 10*1000 39 | val maxOutputLineLength = 1000 40 | 41 | val scalaTestReportFileProperty = "scalatest.reportFile" 42 | val scalaTestIndividualTestTimeoutProperty = "scalatest.individualTestTimeout" 43 | val scalaTestReadableFilesProperty = "scalatest.readableFiles" 44 | val scalaTestDefaultWeigthProperty = "scalatest.defaultWeight" 45 | 46 | // debugging / developping options 47 | 48 | // don't decode json and unpack the submission sources, don't upload feedback 49 | val offlineMode = false 50 | } 51 | -------------------------------------------------------------------------------- /ass_zip/example/project/Settings.scala: -------------------------------------------------------------------------------- 1 | object Settings { 2 | // when changing this, also look at 'scripts/gradingImpl' and the files in s3/settings 3 | // val courseId = "progfun-2012-001" 4 | def baseURL(courseId: String) = 5 | "https://class.coursera.org/" + courseId 6 | 7 | def challengeUrl(courseId: String) = baseURL(courseId) + "/assignment/challenge" 8 | 9 | def submitUrl(courseId: String) = baseURL(courseId) + "/assignment/submit" 10 | 11 | // def forumUrl(courseId: String) = baseURL(courseId) "/forum/index" 12 | 13 | // def submitQueueUrl(courseId: String) = baseURL(courseId) +"/assignment/api/pending_submission" 14 | 15 | def uploadFeedbackUrl(courseId: String) = baseURL(courseId) + "/assignment/api/score" 16 | 17 | val maxSubmitFileSize = { 18 | val mb = 1024 * 1024 19 | 10 * mb 20 | } 21 | 22 | val submissionDirName = "submission" 23 | 24 | val testResultsFileName = "scalaTestLog.txt" 25 | val policyFileName = "allowAllPolicy" 26 | val submissionJsonFileName = "submission.json" 27 | val submissionJarFileName = "submittedSrc.jar" 28 | 29 | // time in seconds that we give scalatest for running 30 | val scalaTestTimeout = 1200 31 | val individualTestTimeout = 40 32 | 33 | // default weight of each test in a GradingSuite, in case no weight is given 34 | val scalaTestDefaultWeigth = 10 35 | 36 | // when students leave print statements in their code, they end up in the output of the 37 | // system process running ScalaTest (ScalaTestRunner.scala); we need some limits. 38 | val maxOutputLines = 10*1000 39 | val maxOutputLineLength = 1000 40 | 41 | val scalaTestReportFileProperty = "scalatest.reportFile" 42 | val scalaTestIndividualTestTimeoutProperty = "scalatest.individualTestTimeout" 43 | val scalaTestReadableFilesProperty = "scalatest.readableFiles" 44 | val scalaTestDefaultWeigthProperty = "scalatest.defaultWeight" 45 | 46 | // debugging / developping options 47 | 48 | // don't decode json and unpack the submission sources, don't upload feedback 49 | val offlineMode = false 50 | } 51 | -------------------------------------------------------------------------------- /suggestions/src/main/scala/suggestions/gui/SwingApi.scala: -------------------------------------------------------------------------------- 1 | package suggestions 2 | package gui 3 | 4 | import scala.language.reflectiveCalls 5 | import scala.collection.mutable.ListBuffer 6 | import scala.collection.JavaConverters._ 7 | import scala.concurrent._ 8 | import scala.concurrent.ExecutionContext.Implicits.global 9 | import scala.util.{ Try, Success, Failure } 10 | import scala.swing.Reactions.Reaction 11 | import scala.swing.event.Event 12 | import rx.lang.scala.Observable 13 | 14 | /** Basic facilities for dealing with Swing-like components. 15 | * 16 | * Instead of committing to a particular widget implementation 17 | * functionality has been factored out here to deal only with 18 | * abstract types like `ValueChanged` or `TextField`. 19 | * Extractors for abstract events like `ValueChanged` have also 20 | * been factored out into corresponding abstract `val`s. 21 | */ 22 | trait SwingApi { 23 | 24 | type ValueChanged <: Event 25 | 26 | val ValueChanged: { 27 | def unapply(x: Event): Option[TextField] 28 | } 29 | 30 | type ButtonClicked <: Event 31 | 32 | val ButtonClicked: { 33 | def unapply(x: Event): Option[Button] 34 | } 35 | 36 | type TextField <: { 37 | def text: String 38 | def subscribe(r: Reaction): Unit 39 | def unsubscribe(r: Reaction): Unit 40 | } 41 | 42 | type Button <: { 43 | def subscribe(r: Reaction): Unit 44 | def unsubscribe(r: Reaction): Unit 45 | } 46 | 47 | implicit class TextFieldOps(field: TextField) { 48 | 49 | /** Returns a stream of text field values entered in the given text field. 50 | * 51 | * @param field the text field 52 | * @return an observable with a stream of text field updates 53 | */ 54 | def textValues: Observable[String] = ??? 55 | 56 | } 57 | 58 | implicit class ButtonOps(button: Button) { 59 | 60 | /** Returns a stream of button clicks. 61 | * 62 | * @param field the button 63 | * @return an observable with a stream of buttons that have been clicked 64 | */ 65 | def clicks: Observable[Button] = ??? 66 | } 67 | 68 | } 69 | -------------------------------------------------------------------------------- /suggestions/src/test/scala/suggestions/WikipediaApiTest.scala: -------------------------------------------------------------------------------- 1 | package suggestions 2 | 3 | 4 | 5 | import language.postfixOps 6 | import scala.concurrent._ 7 | import scala.concurrent.duration._ 8 | import scala.concurrent.ExecutionContext.Implicits.global 9 | import scala.util.{Try, Success, Failure} 10 | import rx.lang.scala._ 11 | import org.scalatest._ 12 | import gui._ 13 | 14 | import org.junit.runner.RunWith 15 | import org.scalatest.junit.JUnitRunner 16 | 17 | 18 | @RunWith(classOf[JUnitRunner]) 19 | class WikipediaApiTest extends FunSuite { 20 | 21 | object mockApi extends WikipediaApi { 22 | def wikipediaSuggestion(term: String) = Future { 23 | if (term.head.isLetter) { 24 | for (suffix <- List(" (Computer Scientist)", " (Footballer)")) yield term + suffix 25 | } else { 26 | List(term) 27 | } 28 | } 29 | def wikipediaPage(term: String) = Future { 30 | "Title: " + term 31 | } 32 | } 33 | 34 | import mockApi._ 35 | 36 | test("WikipediaApi should make the stream valid using sanitized") { 37 | val notvalid = Observable.just("erik", "erik meijer", "martin") 38 | val valid = notvalid.sanitized 39 | 40 | var count = 0 41 | var completed = false 42 | 43 | val sub = valid.subscribe( 44 | term => { 45 | assert(term.forall(_ != ' ')) 46 | count += 1 47 | }, 48 | t => assert(false, s"stream error $t"), 49 | () => completed = true 50 | ) 51 | assert(completed && count == 3, "completed: " + completed + ", event count: " + count) 52 | } 53 | test("WikipediaApi should correctly use concatRecovered") { 54 | val requests = Observable.just(1, 2, 3) 55 | val remoteComputation = (n: Int) => Observable.just(0 to n : _*) 56 | val responses = requests concatRecovered remoteComputation 57 | val sum = responses.foldLeft(0) { (acc, tn) => 58 | tn match { 59 | case Success(n) => acc + n 60 | case Failure(t) => throw t 61 | } 62 | } 63 | var total = -1 64 | val sub = sum.subscribe { 65 | s => total = s 66 | } 67 | assert(total == (1 + 1 + 2 + 1 + 2 + 3), s"Sum: $total") 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /quickcheck/project/ReactiveBuild.scala: -------------------------------------------------------------------------------- 1 | import sbt._ 2 | import Keys._ 3 | import ch.epfl.lamp.CourseraBuild 4 | import ch.epfl.lamp.SbtCourseraPlugin.autoImport._ 5 | 6 | object ProgfunBuild extends CourseraBuild { 7 | override def assignmentSettings: Seq[Setting[_]] = Seq( 8 | // This setting allows to restrict the source files that are compiled and tested 9 | // to one specific project. It should be either the empty string, in which case all 10 | // projects are included, or one of the project names from the projectDetailsMap. 11 | currentProject := "", 12 | 13 | // Packages in src/main/scala that are used in every project. Included in every 14 | // handout, submission. 15 | commonSourcePackages += "common", 16 | 17 | // Packages in src/test/scala that are used for grading projects. Always included 18 | // compiling tests, grading a project. 19 | 20 | libraryDependencies += "ch.epfl.lamp" %% "scala-grading-runtime" % "0.1", 21 | 22 | // Files that we hand out to the students 23 | handoutFiles <<= (baseDirectory, projectDetailsMap, commonSourcePackages) map { 24 | (basedir, detailsMap, commonSrcs) => 25 | (projectName: String) => { 26 | val details = detailsMap.getOrElse(projectName, sys.error("Unknown project name: "+ projectName)) 27 | val commonFiles = (PathFinder.empty /: commonSrcs)((files, pkg) => 28 | files +++ (basedir / "src" / "main" / "scala" / pkg ** "*.scala") 29 | ) 30 | (basedir / "src" / "main" / "scala" / details.packageName ** "*.scala") +++ 31 | commonFiles +++ 32 | (basedir / "src" / "main" / "resources" / details.packageName / "*") +++ 33 | (basedir / "src" / "test" / "scala" / details.packageName ** "*.scala") +++ 34 | (basedir / "build.sbt") +++ 35 | (basedir / "project" / "build.properties") +++ 36 | (basedir / "project" ** ("*.scala" || "*.sbt")) +++ 37 | (basedir / "project" / "scalastyle_config_reactive.xml") +++ 38 | (basedir / "lib_managed" ** "*.jar") +++ 39 | (basedir * (".classpath" || ".project")) +++ 40 | (basedir / ".settings" / "org.scala-ide.sdt.core.prefs") 41 | } 42 | }) 43 | } 44 | -------------------------------------------------------------------------------- /recfun/src/main/scala/recfun/Main.scala: -------------------------------------------------------------------------------- 1 | package recfun 2 | import common._ 3 | 4 | object Main { 5 | def main(args: Array[String]) { 6 | println("Pascal's Triangle") 7 | for (row <- 0 to 10) { 8 | for (col <- 0 to row) 9 | print(pascal(col, row) + " ") 10 | println() 11 | } 12 | } 13 | 14 | /** 15 | * The following pattern of numbers is called Pascal’s triangle. 16 | * 17 | * 1 18 | * 1 1 19 | * 1 2 1 20 | * 1 3 3 1 21 | * 1 4 6 4 1 22 | * ... 23 | * The numbers at the edge of the triangle are all 1, 24 | * and each number inside the triangle is the sum of the two numbers above it. 25 | * Write a function that computes the elements of Pascal’s triangle by means of a recursive process. 26 | */ 27 | def pascal(c: Int, r: Int): Int = { 28 | if (c == 0 )1 29 | else pascal(c - 1, r) + pascal(c - 1, r -1 ) 30 | } 31 | 32 | /** 33 | * Exercise 2 34 | * Write a recursive function which verifies the balancing of parentheses in a string, which we represent as a List[Char] not a String. For example, the function should return true for the following strings: 35 | * 36 | * (if (zero? x) max (/ 1 x)) 37 | * I told him (that it’s not (yet) done). (But he wasn’t listening) 38 | * The function should return false for the following strings: 39 | * :-) 40 | * ())( 41 | */ 42 | def balance(chars: List[Char]): Boolean ={ 43 | def balance0(chars:List[Char], count:Int):Boolean = { 44 | if(chars.isEmpty) { 45 | count == 0 46 | } 47 | else { 48 | chars.head match { 49 | case '(' => balance0(chars.tail,count + 1) 50 | case ')' => (count > 0) && balance0(chars.tail,count - 1) 51 | case _ => balance0(chars.tail,count) 52 | } 53 | } 54 | } 55 | balance0(chars,0) 56 | } 57 | 58 | /** 59 | * Exercise 3 60 | * Write a recursive function that counts how many different ways you can make change for an amount, 61 | * given a list of coin denominations. For example, 62 | * there are 3 ways to give change for 4 if you have coins with denomiation 1 and 2: 1+1+1+1, 1+1+2, 2+2. 63 | */ 64 | def countChange(money: Int, coins: List[Int]): Int = { 65 | println(money, coins) 66 | if(money == 0) 1 67 | else if(money < 0 || coins.isEmpty) 0 68 | else countChange(money, coins.tail) + countChange(money-coins.head,coins) 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /suggestions/src/test/scala/suggestions/SwingApiTest.scala: -------------------------------------------------------------------------------- 1 | package suggestions 2 | 3 | 4 | 5 | import scala.collection._ 6 | import scala.concurrent._ 7 | import scala.concurrent.ExecutionContext.Implicits.global 8 | import scala.util.{Try, Success, Failure} 9 | import scala.swing.event.Event 10 | import scala.swing.Reactions.Reaction 11 | import rx.lang.scala._ 12 | import org.scalatest._ 13 | import gui._ 14 | 15 | import org.junit.runner.RunWith 16 | import org.scalatest.junit.JUnitRunner 17 | 18 | @RunWith(classOf[JUnitRunner]) 19 | class SwingApiTest extends FunSuite { 20 | 21 | object swingApi extends SwingApi { 22 | class ValueChanged(val textField: TextField) extends Event 23 | 24 | object ValueChanged { 25 | def unapply(x: Event) = x match { 26 | case vc: ValueChanged => Some(vc.textField) 27 | case _ => None 28 | } 29 | } 30 | 31 | class ButtonClicked(val source: Button) extends Event 32 | 33 | object ButtonClicked { 34 | def unapply(x: Event) = x match { 35 | case bc: ButtonClicked => Some(bc.source) 36 | case _ => None 37 | } 38 | } 39 | 40 | class Component { 41 | private val subscriptions = mutable.Set[Reaction]() 42 | def subscribe(r: Reaction) { 43 | subscriptions add r 44 | } 45 | def unsubscribe(r: Reaction) { 46 | subscriptions remove r 47 | } 48 | def publish(e: Event) { 49 | for (r <- subscriptions) r(e) 50 | } 51 | } 52 | 53 | class TextField extends Component { 54 | private var _text = "" 55 | def text = _text 56 | def text_=(t: String) { 57 | _text = t 58 | publish(new ValueChanged(this)) 59 | } 60 | } 61 | 62 | class Button extends Component { 63 | def click() { 64 | publish(new ButtonClicked(this)) 65 | } 66 | } 67 | } 68 | 69 | import swingApi._ 70 | 71 | test("SwingApi should emit text field values to the observable") { 72 | val textField = new swingApi.TextField 73 | val values = textField.textValues 74 | 75 | val observed = mutable.Buffer[String]() 76 | val sub = values subscribe { 77 | observed += _ 78 | } 79 | 80 | // write some text now 81 | textField.text = "T" 82 | textField.text = "Tu" 83 | textField.text = "Tur" 84 | textField.text = "Turi" 85 | textField.text = "Turin" 86 | textField.text = "Turing" 87 | 88 | assert(observed == Seq("T", "Tu", "Tur", "Turi", "Turin", "Turing"), observed) 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /funsets/src/main/scala/funsets/FunSets.scala: -------------------------------------------------------------------------------- 1 | package funsets 2 | 3 | 4 | /** 5 | * 2. Purely Functional Sets. 6 | */ 7 | object FunSets { 8 | /** 9 | * We represent a set by its characteristic function, i.e. 10 | * its `contains` predicate. 11 | */ 12 | type Set = Int => Boolean 13 | 14 | /** 15 | * Indicates whether a set contains a given element. 16 | */ 17 | def contains(s: Set, elem: Int): Boolean = s(elem) 18 | 19 | /** 20 | * Returns the set of the one given element. 21 | */ 22 | def singletonSet(elem: Int): Set = (x:Int) => x == elem 23 | 24 | /** 25 | * Returns the union of the two given sets, 26 | * the sets of all elements that are in either `s` or `t`. 27 | */ 28 | def union(s: Set, t: Set): Set = (x:Int) => s(x) || t(x) 29 | 30 | /** 31 | * Returns the intersection of the two given sets, 32 | * the set of all elements that are both in `s` and `t`. 33 | */ 34 | def intersect(s: Set, t: Set): Set = (x: Int) => s(x) && t(x) 35 | 36 | /** 37 | * Returns the difference of the two given sets, 38 | * the set of all elements of `s` that are not in `t`. 39 | */ 40 | def diff(s: Set, t: Set): Set = (x:Int) => s(x) && !t(x) 41 | 42 | /** 43 | * Returns the subset of `s` for which `p` holds. 44 | */ 45 | def filter(s: Set, p: Int => Boolean): Set = (x:Int) => s(x) && p(x) 46 | 47 | /** 48 | * The bounds for `forall` and `exists` are +/- 1000. 49 | */ 50 | val bound = 1000 51 | 52 | /** 53 | * Returns whether all bounded integers within `s` satisfy `p`. 54 | */ 55 | def forall(s: Set, p: Int => Boolean): Boolean = { 56 | def iter(a: Int): Boolean = { 57 | if (a > bound ) true 58 | else if (s(a) && !p(a)) false 59 | else iter( a+1 ) 60 | } 61 | iter(-bound) 62 | } 63 | 64 | /** 65 | * Returns whether there exists a bounded integer within `s` 66 | * that satisfies `p`. 67 | */ 68 | def exists(s: Set, p: Int => Boolean): Boolean = !forall(s,(elem:Int) => !p(elem)) 69 | 70 | /** 71 | * Returns a set transformed by applying `f` to each element of `s`. 72 | */ 73 | def map(s: Set, f: Int => Int): Set = (elem:Int) => exists(s,(e:Int) => f(e) == elem) 74 | 75 | /** 76 | * Displays the contents of a set 77 | */ 78 | def toString(s: Set): String = { 79 | val xs = for (i <- -bound to bound if contains(s, i)) yield i 80 | xs.mkString("{", ",", "}") 81 | } 82 | 83 | /** 84 | * Prints the contents of a set on the console. 85 | */ 86 | def printSet(s: Set) { 87 | println(toString(s)) 88 | } 89 | 90 | 91 | } 92 | -------------------------------------------------------------------------------- /streams/src/main/scala/streams/StringParserTerrain.scala: -------------------------------------------------------------------------------- 1 | package streams 2 | 3 | import common._ 4 | 5 | /** 6 | * This component implements a parser to define terrains from a 7 | * graphical ASCII representation. 8 | * 9 | * When mixing in that component, a level can be defined by 10 | * defining the field `level` in the following form: 11 | * 12 | * val level = 13 | * """------ 14 | * |--ST-- 15 | * |--oo-- 16 | * |--oo-- 17 | * |------""".stripMargin 18 | * 19 | * - The `-` character denotes parts which are outside the terrain 20 | * - `o` denotes fields which are part of the terrain 21 | * - `S` denotes the start position of the block (which is also considered 22 | inside the terrain) 23 | * - `T` denotes the final position of the block (which is also considered 24 | inside the terrain) 25 | * 26 | * In this example, the first and last lines could be omitted, and 27 | * also the columns that consist of `-` characters only. 28 | */ 29 | trait StringParserTerrain extends GameDef { 30 | 31 | /** 32 | * A ASCII representation of the terrain. This field should remain 33 | * abstract here. 34 | */ 35 | val level: String 36 | 37 | /** 38 | * This method returns terrain function that represents the terrain 39 | * in `levelVector`. The vector contains parsed version of the `level` 40 | * string. For example, the following level 41 | * 42 | * val level = 43 | * """ST 44 | * |oo 45 | * |oo""".stripMargin 46 | * 47 | * is represented as 48 | * 49 | * Vector(Vector('S', 'T'), Vector('o', 'o'), Vector('o', 'o')) 50 | * 51 | * The resulting function should return `true` if the position `pos` is 52 | * a valid position (not a '-' character) inside the terrain described 53 | * by `levelVector`. 54 | */ 55 | def terrainFunction(levelVector: Vector[Vector[Char]]): Pos => Boolean = ??? 56 | 57 | /** 58 | * This function should return the position of character `c` in the 59 | * terrain described by `levelVector`. You can assume that the `c` 60 | * appears exactly once in the terrain. 61 | * 62 | * Hint: you can use the functions `indexWhere` and / or `indexOf` of the 63 | * `Vector` class 64 | */ 65 | def findChar(c: Char, levelVector: Vector[Vector[Char]]): Pos = ??? 66 | 67 | private lazy val vector: Vector[Vector[Char]] = 68 | Vector(level.split("\n").map(str => Vector(str: _*)): _*) 69 | 70 | lazy val terrain: Terrain = terrainFunction(vector) 71 | lazy val startPos: Pos = findChar('S', vector) 72 | lazy val goal: Pos = findChar('T', vector) 73 | 74 | } 75 | -------------------------------------------------------------------------------- /actorbintree/project/ReactiveBuild.scala: -------------------------------------------------------------------------------- 1 | import sbt._ 2 | import Keys._ 3 | import ch.epfl.lamp.CourseraBuild 4 | import ch.epfl.lamp.SbtCourseraPlugin.autoImport._ 5 | 6 | import org.scalajs.sbtplugin.ScalaJSPlugin 7 | import org.scalajs.sbtplugin.ScalaJSPlugin.autoImport._ 8 | 9 | object ProgfunBuild extends CourseraBuild { 10 | override def assignmentSettings: Seq[Setting[_]] = Seq( 11 | // This setting allows to restrict the source files that are compiled and tested 12 | // to one specific project. It should be either the empty string, in which case all 13 | // projects are included, or one of the project names from the projectDetailsMap. 14 | currentProject := "", 15 | 16 | // Packages in src/main/scala that are used in every project. Included in every 17 | // handout, submission. 18 | commonSourcePackages += "common", 19 | 20 | // Packages in src/test/scala that are used for grading projects. Always included 21 | // compiling tests, grading a project. 22 | 23 | libraryDependencies += "ch.epfl.lamp" %% "scala-grading-runtime" % "0.1", 24 | 25 | // Files that we hand out to the students 26 | handoutFiles <<= (baseDirectory, projectDetailsMap, commonSourcePackages) map { 27 | (basedir, detailsMap, commonSrcs) => 28 | (projectName: String) => { 29 | val details = detailsMap.getOrElse(projectName, sys.error("Unknown project name: "+ projectName)) 30 | val commonFiles = (PathFinder.empty /: commonSrcs)((files, pkg) => 31 | files +++ (basedir / "src" / "main" / "scala" / pkg ** "*.scala") 32 | ) 33 | val forAll = { 34 | (basedir / "src" / "main" / "scala" / details.packageName ** "*.scala") +++ 35 | commonFiles +++ 36 | (basedir / "src" / "main" / "resources" / details.packageName / "*") +++ 37 | (basedir / "src" / "test" / "scala" / details.packageName ** "*.scala") +++ 38 | (basedir / "build.sbt") +++ 39 | (basedir / "project" / "build.properties") +++ 40 | (basedir / "project" ** ("*.scala" || "*.sbt")) +++ 41 | (basedir / "project" / "scalastyle_config_reactive.xml") +++ 42 | (basedir / "lib_managed" ** "*.jar") +++ 43 | (basedir * (".classpath" || ".project")) +++ 44 | (basedir / ".settings" / "org.scala-ide.sdt.core.prefs") 45 | } 46 | if (projectName == "calculator") { 47 | forAll +++ 48 | (basedir / "webui.sbt") +++ 49 | (basedir / "web-ui" / "index.html") +++ 50 | (basedir / "web-ui" / "src" / "main" / "scala" ** "*.scala") 51 | } else 52 | forAll 53 | } 54 | }) 55 | } 56 | -------------------------------------------------------------------------------- /calculator/project/ReactiveBuild.scala: -------------------------------------------------------------------------------- 1 | import sbt._ 2 | import Keys._ 3 | import ch.epfl.lamp.CourseraBuild 4 | import ch.epfl.lamp.SbtCourseraPlugin.autoImport._ 5 | 6 | import org.scalajs.sbtplugin.ScalaJSPlugin 7 | import org.scalajs.sbtplugin.ScalaJSPlugin.autoImport._ 8 | 9 | object ProgfunBuild extends CourseraBuild { 10 | override def assignmentSettings: Seq[Setting[_]] = Seq( 11 | // This setting allows to restrict the source files that are compiled and tested 12 | // to one specific project. It should be either the empty string, in which case all 13 | // projects are included, or one of the project names from the projectDetailsMap. 14 | currentProject := "", 15 | 16 | // Packages in src/main/scala that are used in every project. Included in every 17 | // handout, submission. 18 | commonSourcePackages += "common", 19 | 20 | // Packages in src/test/scala that are used for grading projects. Always included 21 | // compiling tests, grading a project. 22 | 23 | libraryDependencies += "ch.epfl.lamp" %% "scala-grading-runtime" % "0.1", 24 | 25 | // Files that we hand out to the students 26 | handoutFiles <<= (baseDirectory, projectDetailsMap, commonSourcePackages) map { 27 | (basedir, detailsMap, commonSrcs) => 28 | (projectName: String) => { 29 | val details = detailsMap.getOrElse(projectName, sys.error("Unknown project name: "+ projectName)) 30 | val commonFiles = (PathFinder.empty /: commonSrcs)((files, pkg) => 31 | files +++ (basedir / "src" / "main" / "scala" / pkg ** "*.scala") 32 | ) 33 | val forAll = { 34 | (basedir / "src" / "main" / "scala" / details.packageName ** "*.scala") +++ 35 | commonFiles +++ 36 | (basedir / "src" / "main" / "resources" / details.packageName / "*") +++ 37 | (basedir / "src" / "test" / "scala" / details.packageName ** "*.scala") +++ 38 | (basedir / "build.sbt") +++ 39 | (basedir / "project" / "build.properties") +++ 40 | (basedir / "project" ** ("*.scala" || "*.sbt")) +++ 41 | (basedir / "project" / "scalastyle_config_reactive.xml") +++ 42 | (basedir / "lib_managed" ** "*.jar") +++ 43 | (basedir * (".classpath" || ".project")) +++ 44 | (basedir / ".settings" / "org.scala-ide.sdt.core.prefs") 45 | } 46 | if (projectName == "calculator") { 47 | forAll +++ 48 | (basedir / "webui.sbt") +++ 49 | (basedir / "web-ui" / "index.html") +++ 50 | (basedir / "web-ui" / "src" / "main" / "scala" ** "*.scala") 51 | } else 52 | forAll 53 | } 54 | }) 55 | } 56 | -------------------------------------------------------------------------------- /nodescala/project/ReactiveBuild.scala: -------------------------------------------------------------------------------- 1 | import sbt._ 2 | import Keys._ 3 | import ch.epfl.lamp.CourseraBuild 4 | import ch.epfl.lamp.SbtCourseraPlugin.autoImport._ 5 | 6 | import org.scalajs.sbtplugin.ScalaJSPlugin 7 | import org.scalajs.sbtplugin.ScalaJSPlugin.autoImport._ 8 | 9 | object ProgfunBuild extends CourseraBuild { 10 | override def assignmentSettings: Seq[Setting[_]] = Seq( 11 | // This setting allows to restrict the source files that are compiled and tested 12 | // to one specific project. It should be either the empty string, in which case all 13 | // projects are included, or one of the project names from the projectDetailsMap. 14 | currentProject := "", 15 | 16 | // Packages in src/main/scala that are used in every project. Included in every 17 | // handout, submission. 18 | commonSourcePackages += "common", 19 | 20 | // Packages in src/test/scala that are used for grading projects. Always included 21 | // compiling tests, grading a project. 22 | 23 | libraryDependencies += "ch.epfl.lamp" %% "scala-grading-runtime" % "0.1", 24 | 25 | // Files that we hand out to the students 26 | handoutFiles <<= (baseDirectory, projectDetailsMap, commonSourcePackages) map { 27 | (basedir, detailsMap, commonSrcs) => 28 | (projectName: String) => { 29 | val details = detailsMap.getOrElse(projectName, sys.error("Unknown project name: "+ projectName)) 30 | val commonFiles = (PathFinder.empty /: commonSrcs)((files, pkg) => 31 | files +++ (basedir / "src" / "main" / "scala" / pkg ** "*.scala") 32 | ) 33 | val forAll = { 34 | (basedir / "src" / "main" / "scala" / details.packageName ** "*.scala") +++ 35 | commonFiles +++ 36 | (basedir / "src" / "main" / "resources" / details.packageName / "*") +++ 37 | (basedir / "src" / "test" / "scala" / details.packageName ** "*.scala") +++ 38 | (basedir / "build.sbt") +++ 39 | (basedir / "project" / "build.properties") +++ 40 | (basedir / "project" ** ("*.scala" || "*.sbt")) +++ 41 | (basedir / "project" / "scalastyle_config_reactive.xml") +++ 42 | (basedir / "lib_managed" ** "*.jar") +++ 43 | (basedir * (".classpath" || ".project")) +++ 44 | (basedir / ".settings" / "org.scala-ide.sdt.core.prefs") 45 | } 46 | if (projectName == "calculator") { 47 | forAll +++ 48 | (basedir / "webui.sbt") +++ 49 | (basedir / "web-ui" / "index.html") +++ 50 | (basedir / "web-ui" / "src" / "main" / "scala" ** "*.scala") 51 | } else 52 | forAll 53 | } 54 | }) 55 | } 56 | -------------------------------------------------------------------------------- /suggestions/project/ReactiveBuild.scala: -------------------------------------------------------------------------------- 1 | import sbt._ 2 | import Keys._ 3 | import ch.epfl.lamp.CourseraBuild 4 | import ch.epfl.lamp.SbtCourseraPlugin.autoImport._ 5 | 6 | import org.scalajs.sbtplugin.ScalaJSPlugin 7 | import org.scalajs.sbtplugin.ScalaJSPlugin.autoImport._ 8 | 9 | object ProgfunBuild extends CourseraBuild { 10 | override def assignmentSettings: Seq[Setting[_]] = Seq( 11 | // This setting allows to restrict the source files that are compiled and tested 12 | // to one specific project. It should be either the empty string, in which case all 13 | // projects are included, or one of the project names from the projectDetailsMap. 14 | currentProject := "", 15 | 16 | // Packages in src/main/scala that are used in every project. Included in every 17 | // handout, submission. 18 | commonSourcePackages += "common", 19 | 20 | // Packages in src/test/scala that are used for grading projects. Always included 21 | // compiling tests, grading a project. 22 | 23 | libraryDependencies += "ch.epfl.lamp" %% "scala-grading-runtime" % "0.1", 24 | 25 | // Files that we hand out to the students 26 | handoutFiles <<= (baseDirectory, projectDetailsMap, commonSourcePackages) map { 27 | (basedir, detailsMap, commonSrcs) => 28 | (projectName: String) => { 29 | val details = detailsMap.getOrElse(projectName, sys.error("Unknown project name: "+ projectName)) 30 | val commonFiles = (PathFinder.empty /: commonSrcs)((files, pkg) => 31 | files +++ (basedir / "src" / "main" / "scala" / pkg ** "*.scala") 32 | ) 33 | val forAll = { 34 | (basedir / "src" / "main" / "scala" / details.packageName ** "*.scala") +++ 35 | commonFiles +++ 36 | (basedir / "src" / "main" / "resources" / details.packageName / "*") +++ 37 | (basedir / "src" / "test" / "scala" / details.packageName ** "*.scala") +++ 38 | (basedir / "build.sbt") +++ 39 | (basedir / "project" / "build.properties") +++ 40 | (basedir / "project" ** ("*.scala" || "*.sbt")) +++ 41 | (basedir / "project" / "scalastyle_config_reactive.xml") +++ 42 | (basedir / "lib_managed" ** "*.jar") +++ 43 | (basedir * (".classpath" || ".project")) +++ 44 | (basedir / ".settings" / "org.scala-ide.sdt.core.prefs") 45 | } 46 | if (projectName == "calculator") { 47 | forAll +++ 48 | (basedir / "webui.sbt") +++ 49 | (basedir / "web-ui" / "index.html") +++ 50 | (basedir / "web-ui" / "src" / "main" / "scala" ** "*.scala") 51 | } else 52 | forAll 53 | } 54 | }) 55 | } 56 | -------------------------------------------------------------------------------- /forcomp/project/buildSettings.sbt: -------------------------------------------------------------------------------- 1 | resolvers += "Spray Repository" at "http://repo.spray.io" 2 | 3 | libraryDependencies += "net.databinder" %% "dispatch-http" % "0.8.10" 4 | 5 | libraryDependencies += "org.scalastyle" %% "scalastyle" % "0.3.2" 6 | 7 | libraryDependencies += "io.spray" %% "spray-json" % "1.3.1" 8 | 9 | // need scalatest also as a build dependency: the build implements a custom reporter 10 | libraryDependencies += "org.scalatest" %% "scalatest" % "1.9.1" 11 | 12 | // dispatch uses commons-codec, in version 1.4, so we can't go for 1.6. 13 | // libraryDependencies += "commons-codec" % "commons-codec" % "1.4" 14 | 15 | libraryDependencies += "org.apache.commons" % "commons-lang3" % "3.1" 16 | 17 | // sbteclipse depends on scalaz 7.0.2, so we can't use 7.1.0 18 | libraryDependencies += "org.scalaz" %% "scalaz-core" % "7.0.2" 19 | 20 | scalacOptions ++= Seq("-deprecation", "-feature") 21 | 22 | addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.5.0") 23 | 24 | // for dependency-graph plugin 25 | // net.virtualvoid.sbt.graph.Plugin.graphSettings 26 | 27 | 28 | // [info] default:default-3fdafc_2.9.1:0.1-SNAPSHOT 29 | // [info] +-cc.spray:spray-json_2.9.1:1.1.1 30 | // [info] | +-org.parboiled:parboiled-scala:1.0.2 31 | // [info] | | +-org.parboiled:parboiled-core:1.0.2 32 | // [info] | | +-org.scala-lang:scala-library:2.9.1 33 | // [info] | | 34 | // [info] | +-org.scala-lang:scala-library:2.9.1 35 | // [info] | 36 | // [info] +-com.typesafe.sbteclipse:sbteclipse-plugin:2.1.0 37 | // [info] | +-com.typesafe.sbteclipse:sbteclipse-core:2.1.0 38 | // [info] | +-org.scalaz:scalaz-core_2.9.1:6.0.3 39 | // [info] | +-org.scala-lang:scala-library:2.9.1 40 | // [info] | 41 | // [info] +-net.databinder:dispatch-http_2.9.1:0.8.8 42 | // [info] | +-net.databinder:dispatch-core_2.9.1:0.8.8 43 | // [info] | | +-org.apache.httpcomponents:httpclient:4.1.3 44 | // [info] | | | +-commons-codec:commons-codec:1.4 45 | // [info] | | | +-commons-logging:commons-logging:1.1.1 46 | // [info] | | | +-org.apache.httpcomponents:httpcore:4.1.4 47 | // [info] | | | 48 | // [info] | | +-org.scala-lang:scala-library:2.9.1 49 | // [info] | | 50 | // [info] | +-net.databinder:dispatch-futures_2.9.1:0.8.8 51 | // [info] | | +-org.scala-lang:scala-library:2.9.1 52 | // [info] | | 53 | // [info] | +-org.apache.httpcomponents:httpclient:4.1.3 54 | // [info] | | +-commons-codec:commons-codec:1.4 55 | // [info] | | +-commons-logging:commons-logging:1.1.1 56 | // [info] | | +-org.apache.httpcomponents:httpcore:4.1.4 57 | // [info] | | 58 | // [info] | +-org.scala-lang:scala-library:2.9.1 59 | // [info] | 60 | // [info] +-org.scala-lang:scala-library:2.9.1 61 | // [info] +-org.scalastyle:scalastyle_2.9.1:0.1.3-SNAPSHOT 62 | // [info] | +-com.github.scopt:scopt_2.9.1:2.0.0 63 | // [info] | | +-org.scala-lang:scala-library:2.9.1 64 | // [info] | | 65 | // [info] | +-org.scalariform:scalariform_2.9.1:0.1.1 66 | // [info] | +-org.scala-lang:scala-library:2.9.1 67 | // [info] | 68 | // [info] +-org.scalatest:scalatest_2.9.1:1.8 69 | // [info] +-org.scala-lang:scala-library:2.9.1 70 | -------------------------------------------------------------------------------- /funsets/project/buildSettings.sbt: -------------------------------------------------------------------------------- 1 | resolvers += "Spray Repository" at "http://repo.spray.io" 2 | 3 | libraryDependencies += "net.databinder" %% "dispatch-http" % "0.8.10" 4 | 5 | libraryDependencies += "org.scalastyle" %% "scalastyle" % "0.3.2" 6 | 7 | libraryDependencies += "io.spray" %% "spray-json" % "1.3.1" 8 | 9 | // need scalatest also as a build dependency: the build implements a custom reporter 10 | libraryDependencies += "org.scalatest" %% "scalatest" % "1.9.1" 11 | 12 | // dispatch uses commons-codec, in version 1.4, so we can't go for 1.6. 13 | // libraryDependencies += "commons-codec" % "commons-codec" % "1.4" 14 | 15 | libraryDependencies += "org.apache.commons" % "commons-lang3" % "3.1" 16 | 17 | // sbteclipse depends on scalaz 7.0.2, so we can't use 7.1.0 18 | libraryDependencies += "org.scalaz" %% "scalaz-core" % "7.0.2" 19 | 20 | scalacOptions ++= Seq("-deprecation", "-feature") 21 | 22 | addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.5.0") 23 | 24 | // for dependency-graph plugin 25 | // net.virtualvoid.sbt.graph.Plugin.graphSettings 26 | 27 | 28 | // [info] default:default-3fdafc_2.9.1:0.1-SNAPSHOT 29 | // [info] +-cc.spray:spray-json_2.9.1:1.1.1 30 | // [info] | +-org.parboiled:parboiled-scala:1.0.2 31 | // [info] | | +-org.parboiled:parboiled-core:1.0.2 32 | // [info] | | +-org.scala-lang:scala-library:2.9.1 33 | // [info] | | 34 | // [info] | +-org.scala-lang:scala-library:2.9.1 35 | // [info] | 36 | // [info] +-com.typesafe.sbteclipse:sbteclipse-plugin:2.1.0 37 | // [info] | +-com.typesafe.sbteclipse:sbteclipse-core:2.1.0 38 | // [info] | +-org.scalaz:scalaz-core_2.9.1:6.0.3 39 | // [info] | +-org.scala-lang:scala-library:2.9.1 40 | // [info] | 41 | // [info] +-net.databinder:dispatch-http_2.9.1:0.8.8 42 | // [info] | +-net.databinder:dispatch-core_2.9.1:0.8.8 43 | // [info] | | +-org.apache.httpcomponents:httpclient:4.1.3 44 | // [info] | | | +-commons-codec:commons-codec:1.4 45 | // [info] | | | +-commons-logging:commons-logging:1.1.1 46 | // [info] | | | +-org.apache.httpcomponents:httpcore:4.1.4 47 | // [info] | | | 48 | // [info] | | +-org.scala-lang:scala-library:2.9.1 49 | // [info] | | 50 | // [info] | +-net.databinder:dispatch-futures_2.9.1:0.8.8 51 | // [info] | | +-org.scala-lang:scala-library:2.9.1 52 | // [info] | | 53 | // [info] | +-org.apache.httpcomponents:httpclient:4.1.3 54 | // [info] | | +-commons-codec:commons-codec:1.4 55 | // [info] | | +-commons-logging:commons-logging:1.1.1 56 | // [info] | | +-org.apache.httpcomponents:httpcore:4.1.4 57 | // [info] | | 58 | // [info] | +-org.scala-lang:scala-library:2.9.1 59 | // [info] | 60 | // [info] +-org.scala-lang:scala-library:2.9.1 61 | // [info] +-org.scalastyle:scalastyle_2.9.1:0.1.3-SNAPSHOT 62 | // [info] | +-com.github.scopt:scopt_2.9.1:2.0.0 63 | // [info] | | +-org.scala-lang:scala-library:2.9.1 64 | // [info] | | 65 | // [info] | +-org.scalariform:scalariform_2.9.1:0.1.1 66 | // [info] | +-org.scala-lang:scala-library:2.9.1 67 | // [info] | 68 | // [info] +-org.scalatest:scalatest_2.9.1:1.8 69 | // [info] +-org.scala-lang:scala-library:2.9.1 70 | -------------------------------------------------------------------------------- /objsets/project/buildSettings.sbt: -------------------------------------------------------------------------------- 1 | resolvers += "Spray Repository" at "http://repo.spray.io" 2 | 3 | libraryDependencies += "net.databinder" %% "dispatch-http" % "0.8.10" 4 | 5 | libraryDependencies += "org.scalastyle" %% "scalastyle" % "0.3.2" 6 | 7 | libraryDependencies += "io.spray" %% "spray-json" % "1.3.1" 8 | 9 | // need scalatest also as a build dependency: the build implements a custom reporter 10 | libraryDependencies += "org.scalatest" %% "scalatest" % "1.9.1" 11 | 12 | // dispatch uses commons-codec, in version 1.4, so we can't go for 1.6. 13 | // libraryDependencies += "commons-codec" % "commons-codec" % "1.4" 14 | 15 | libraryDependencies += "org.apache.commons" % "commons-lang3" % "3.1" 16 | 17 | // sbteclipse depends on scalaz 7.0.2, so we can't use 7.1.0 18 | libraryDependencies += "org.scalaz" %% "scalaz-core" % "7.0.2" 19 | 20 | scalacOptions ++= Seq("-deprecation", "-feature") 21 | 22 | addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.5.0") 23 | 24 | // for dependency-graph plugin 25 | // net.virtualvoid.sbt.graph.Plugin.graphSettings 26 | 27 | 28 | // [info] default:default-3fdafc_2.9.1:0.1-SNAPSHOT 29 | // [info] +-cc.spray:spray-json_2.9.1:1.1.1 30 | // [info] | +-org.parboiled:parboiled-scala:1.0.2 31 | // [info] | | +-org.parboiled:parboiled-core:1.0.2 32 | // [info] | | +-org.scala-lang:scala-library:2.9.1 33 | // [info] | | 34 | // [info] | +-org.scala-lang:scala-library:2.9.1 35 | // [info] | 36 | // [info] +-com.typesafe.sbteclipse:sbteclipse-plugin:2.1.0 37 | // [info] | +-com.typesafe.sbteclipse:sbteclipse-core:2.1.0 38 | // [info] | +-org.scalaz:scalaz-core_2.9.1:6.0.3 39 | // [info] | +-org.scala-lang:scala-library:2.9.1 40 | // [info] | 41 | // [info] +-net.databinder:dispatch-http_2.9.1:0.8.8 42 | // [info] | +-net.databinder:dispatch-core_2.9.1:0.8.8 43 | // [info] | | +-org.apache.httpcomponents:httpclient:4.1.3 44 | // [info] | | | +-commons-codec:commons-codec:1.4 45 | // [info] | | | +-commons-logging:commons-logging:1.1.1 46 | // [info] | | | +-org.apache.httpcomponents:httpcore:4.1.4 47 | // [info] | | | 48 | // [info] | | +-org.scala-lang:scala-library:2.9.1 49 | // [info] | | 50 | // [info] | +-net.databinder:dispatch-futures_2.9.1:0.8.8 51 | // [info] | | +-org.scala-lang:scala-library:2.9.1 52 | // [info] | | 53 | // [info] | +-org.apache.httpcomponents:httpclient:4.1.3 54 | // [info] | | +-commons-codec:commons-codec:1.4 55 | // [info] | | +-commons-logging:commons-logging:1.1.1 56 | // [info] | | +-org.apache.httpcomponents:httpcore:4.1.4 57 | // [info] | | 58 | // [info] | +-org.scala-lang:scala-library:2.9.1 59 | // [info] | 60 | // [info] +-org.scala-lang:scala-library:2.9.1 61 | // [info] +-org.scalastyle:scalastyle_2.9.1:0.1.3-SNAPSHOT 62 | // [info] | +-com.github.scopt:scopt_2.9.1:2.0.0 63 | // [info] | | +-org.scala-lang:scala-library:2.9.1 64 | // [info] | | 65 | // [info] | +-org.scalariform:scalariform_2.9.1:0.1.1 66 | // [info] | +-org.scala-lang:scala-library:2.9.1 67 | // [info] | 68 | // [info] +-org.scalatest:scalatest_2.9.1:1.8 69 | // [info] +-org.scala-lang:scala-library:2.9.1 70 | -------------------------------------------------------------------------------- /patmat/project/buildSettings.sbt: -------------------------------------------------------------------------------- 1 | resolvers += "Spray Repository" at "http://repo.spray.io" 2 | 3 | libraryDependencies += "net.databinder" %% "dispatch-http" % "0.8.10" 4 | 5 | libraryDependencies += "org.scalastyle" %% "scalastyle" % "0.3.2" 6 | 7 | libraryDependencies += "io.spray" %% "spray-json" % "1.3.1" 8 | 9 | // need scalatest also as a build dependency: the build implements a custom reporter 10 | libraryDependencies += "org.scalatest" %% "scalatest" % "1.9.1" 11 | 12 | // dispatch uses commons-codec, in version 1.4, so we can't go for 1.6. 13 | // libraryDependencies += "commons-codec" % "commons-codec" % "1.4" 14 | 15 | libraryDependencies += "org.apache.commons" % "commons-lang3" % "3.1" 16 | 17 | // sbteclipse depends on scalaz 7.0.2, so we can't use 7.1.0 18 | libraryDependencies += "org.scalaz" %% "scalaz-core" % "7.0.2" 19 | 20 | scalacOptions ++= Seq("-deprecation", "-feature") 21 | 22 | addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.5.0") 23 | 24 | // for dependency-graph plugin 25 | // net.virtualvoid.sbt.graph.Plugin.graphSettings 26 | 27 | 28 | // [info] default:default-3fdafc_2.9.1:0.1-SNAPSHOT 29 | // [info] +-cc.spray:spray-json_2.9.1:1.1.1 30 | // [info] | +-org.parboiled:parboiled-scala:1.0.2 31 | // [info] | | +-org.parboiled:parboiled-core:1.0.2 32 | // [info] | | +-org.scala-lang:scala-library:2.9.1 33 | // [info] | | 34 | // [info] | +-org.scala-lang:scala-library:2.9.1 35 | // [info] | 36 | // [info] +-com.typesafe.sbteclipse:sbteclipse-plugin:2.1.0 37 | // [info] | +-com.typesafe.sbteclipse:sbteclipse-core:2.1.0 38 | // [info] | +-org.scalaz:scalaz-core_2.9.1:6.0.3 39 | // [info] | +-org.scala-lang:scala-library:2.9.1 40 | // [info] | 41 | // [info] +-net.databinder:dispatch-http_2.9.1:0.8.8 42 | // [info] | +-net.databinder:dispatch-core_2.9.1:0.8.8 43 | // [info] | | +-org.apache.httpcomponents:httpclient:4.1.3 44 | // [info] | | | +-commons-codec:commons-codec:1.4 45 | // [info] | | | +-commons-logging:commons-logging:1.1.1 46 | // [info] | | | +-org.apache.httpcomponents:httpcore:4.1.4 47 | // [info] | | | 48 | // [info] | | +-org.scala-lang:scala-library:2.9.1 49 | // [info] | | 50 | // [info] | +-net.databinder:dispatch-futures_2.9.1:0.8.8 51 | // [info] | | +-org.scala-lang:scala-library:2.9.1 52 | // [info] | | 53 | // [info] | +-org.apache.httpcomponents:httpclient:4.1.3 54 | // [info] | | +-commons-codec:commons-codec:1.4 55 | // [info] | | +-commons-logging:commons-logging:1.1.1 56 | // [info] | | +-org.apache.httpcomponents:httpcore:4.1.4 57 | // [info] | | 58 | // [info] | +-org.scala-lang:scala-library:2.9.1 59 | // [info] | 60 | // [info] +-org.scala-lang:scala-library:2.9.1 61 | // [info] +-org.scalastyle:scalastyle_2.9.1:0.1.3-SNAPSHOT 62 | // [info] | +-com.github.scopt:scopt_2.9.1:2.0.0 63 | // [info] | | +-org.scala-lang:scala-library:2.9.1 64 | // [info] | | 65 | // [info] | +-org.scalariform:scalariform_2.9.1:0.1.1 66 | // [info] | +-org.scala-lang:scala-library:2.9.1 67 | // [info] | 68 | // [info] +-org.scalatest:scalatest_2.9.1:1.8 69 | // [info] +-org.scala-lang:scala-library:2.9.1 70 | -------------------------------------------------------------------------------- /recfun/project/buildSettings.sbt: -------------------------------------------------------------------------------- 1 | resolvers += "Spray Repository" at "http://repo.spray.io" 2 | 3 | libraryDependencies += "net.databinder" %% "dispatch-http" % "0.8.10" 4 | 5 | libraryDependencies += "org.scalastyle" %% "scalastyle" % "0.3.2" 6 | 7 | libraryDependencies += "io.spray" %% "spray-json" % "1.3.1" 8 | 9 | // need scalatest also as a build dependency: the build implements a custom reporter 10 | libraryDependencies += "org.scalatest" %% "scalatest" % "1.9.1" 11 | 12 | // dispatch uses commons-codec, in version 1.4, so we can't go for 1.6. 13 | // libraryDependencies += "commons-codec" % "commons-codec" % "1.4" 14 | 15 | libraryDependencies += "org.apache.commons" % "commons-lang3" % "3.1" 16 | 17 | // sbteclipse depends on scalaz 7.0.2, so we can't use 7.1.0 18 | libraryDependencies += "org.scalaz" %% "scalaz-core" % "7.0.2" 19 | 20 | scalacOptions ++= Seq("-deprecation", "-feature") 21 | 22 | addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.5.0") 23 | 24 | // for dependency-graph plugin 25 | // net.virtualvoid.sbt.graph.Plugin.graphSettings 26 | 27 | 28 | // [info] default:default-3fdafc_2.9.1:0.1-SNAPSHOT 29 | // [info] +-cc.spray:spray-json_2.9.1:1.1.1 30 | // [info] | +-org.parboiled:parboiled-scala:1.0.2 31 | // [info] | | +-org.parboiled:parboiled-core:1.0.2 32 | // [info] | | +-org.scala-lang:scala-library:2.9.1 33 | // [info] | | 34 | // [info] | +-org.scala-lang:scala-library:2.9.1 35 | // [info] | 36 | // [info] +-com.typesafe.sbteclipse:sbteclipse-plugin:2.1.0 37 | // [info] | +-com.typesafe.sbteclipse:sbteclipse-core:2.1.0 38 | // [info] | +-org.scalaz:scalaz-core_2.9.1:6.0.3 39 | // [info] | +-org.scala-lang:scala-library:2.9.1 40 | // [info] | 41 | // [info] +-net.databinder:dispatch-http_2.9.1:0.8.8 42 | // [info] | +-net.databinder:dispatch-core_2.9.1:0.8.8 43 | // [info] | | +-org.apache.httpcomponents:httpclient:4.1.3 44 | // [info] | | | +-commons-codec:commons-codec:1.4 45 | // [info] | | | +-commons-logging:commons-logging:1.1.1 46 | // [info] | | | +-org.apache.httpcomponents:httpcore:4.1.4 47 | // [info] | | | 48 | // [info] | | +-org.scala-lang:scala-library:2.9.1 49 | // [info] | | 50 | // [info] | +-net.databinder:dispatch-futures_2.9.1:0.8.8 51 | // [info] | | +-org.scala-lang:scala-library:2.9.1 52 | // [info] | | 53 | // [info] | +-org.apache.httpcomponents:httpclient:4.1.3 54 | // [info] | | +-commons-codec:commons-codec:1.4 55 | // [info] | | +-commons-logging:commons-logging:1.1.1 56 | // [info] | | +-org.apache.httpcomponents:httpcore:4.1.4 57 | // [info] | | 58 | // [info] | +-org.scala-lang:scala-library:2.9.1 59 | // [info] | 60 | // [info] +-org.scala-lang:scala-library:2.9.1 61 | // [info] +-org.scalastyle:scalastyle_2.9.1:0.1.3-SNAPSHOT 62 | // [info] | +-com.github.scopt:scopt_2.9.1:2.0.0 63 | // [info] | | +-org.scala-lang:scala-library:2.9.1 64 | // [info] | | 65 | // [info] | +-org.scalariform:scalariform_2.9.1:0.1.1 66 | // [info] | +-org.scala-lang:scala-library:2.9.1 67 | // [info] | 68 | // [info] +-org.scalatest:scalatest_2.9.1:1.8 69 | // [info] +-org.scala-lang:scala-library:2.9.1 70 | -------------------------------------------------------------------------------- /streams/project/buildSettings.sbt: -------------------------------------------------------------------------------- 1 | resolvers += "Spray Repository" at "http://repo.spray.io" 2 | 3 | libraryDependencies += "net.databinder" %% "dispatch-http" % "0.8.10" 4 | 5 | libraryDependencies += "org.scalastyle" %% "scalastyle" % "0.3.2" 6 | 7 | libraryDependencies += "io.spray" %% "spray-json" % "1.3.1" 8 | 9 | // need scalatest also as a build dependency: the build implements a custom reporter 10 | libraryDependencies += "org.scalatest" %% "scalatest" % "1.9.1" 11 | 12 | // dispatch uses commons-codec, in version 1.4, so we can't go for 1.6. 13 | // libraryDependencies += "commons-codec" % "commons-codec" % "1.4" 14 | 15 | libraryDependencies += "org.apache.commons" % "commons-lang3" % "3.1" 16 | 17 | // sbteclipse depends on scalaz 7.0.2, so we can't use 7.1.0 18 | libraryDependencies += "org.scalaz" %% "scalaz-core" % "7.0.2" 19 | 20 | scalacOptions ++= Seq("-deprecation", "-feature") 21 | 22 | addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.5.0") 23 | 24 | // for dependency-graph plugin 25 | // net.virtualvoid.sbt.graph.Plugin.graphSettings 26 | 27 | 28 | // [info] default:default-3fdafc_2.9.1:0.1-SNAPSHOT 29 | // [info] +-cc.spray:spray-json_2.9.1:1.1.1 30 | // [info] | +-org.parboiled:parboiled-scala:1.0.2 31 | // [info] | | +-org.parboiled:parboiled-core:1.0.2 32 | // [info] | | +-org.scala-lang:scala-library:2.9.1 33 | // [info] | | 34 | // [info] | +-org.scala-lang:scala-library:2.9.1 35 | // [info] | 36 | // [info] +-com.typesafe.sbteclipse:sbteclipse-plugin:2.1.0 37 | // [info] | +-com.typesafe.sbteclipse:sbteclipse-core:2.1.0 38 | // [info] | +-org.scalaz:scalaz-core_2.9.1:6.0.3 39 | // [info] | +-org.scala-lang:scala-library:2.9.1 40 | // [info] | 41 | // [info] +-net.databinder:dispatch-http_2.9.1:0.8.8 42 | // [info] | +-net.databinder:dispatch-core_2.9.1:0.8.8 43 | // [info] | | +-org.apache.httpcomponents:httpclient:4.1.3 44 | // [info] | | | +-commons-codec:commons-codec:1.4 45 | // [info] | | | +-commons-logging:commons-logging:1.1.1 46 | // [info] | | | +-org.apache.httpcomponents:httpcore:4.1.4 47 | // [info] | | | 48 | // [info] | | +-org.scala-lang:scala-library:2.9.1 49 | // [info] | | 50 | // [info] | +-net.databinder:dispatch-futures_2.9.1:0.8.8 51 | // [info] | | +-org.scala-lang:scala-library:2.9.1 52 | // [info] | | 53 | // [info] | +-org.apache.httpcomponents:httpclient:4.1.3 54 | // [info] | | +-commons-codec:commons-codec:1.4 55 | // [info] | | +-commons-logging:commons-logging:1.1.1 56 | // [info] | | +-org.apache.httpcomponents:httpcore:4.1.4 57 | // [info] | | 58 | // [info] | +-org.scala-lang:scala-library:2.9.1 59 | // [info] | 60 | // [info] +-org.scala-lang:scala-library:2.9.1 61 | // [info] +-org.scalastyle:scalastyle_2.9.1:0.1.3-SNAPSHOT 62 | // [info] | +-com.github.scopt:scopt_2.9.1:2.0.0 63 | // [info] | | +-org.scala-lang:scala-library:2.9.1 64 | // [info] | | 65 | // [info] | +-org.scalariform:scalariform_2.9.1:0.1.1 66 | // [info] | +-org.scala-lang:scala-library:2.9.1 67 | // [info] | 68 | // [info] +-org.scalatest:scalatest_2.9.1:1.8 69 | // [info] +-org.scala-lang:scala-library:2.9.1 70 | -------------------------------------------------------------------------------- /ass_zip/example/project/buildSettings.sbt: -------------------------------------------------------------------------------- 1 | resolvers += "Spray Repository" at "http://repo.spray.io" 2 | 3 | libraryDependencies += "net.databinder" %% "dispatch-http" % "0.8.8" 4 | 5 | libraryDependencies += "org.scalastyle" %% "scalastyle" % "0.3.2" 6 | 7 | libraryDependencies += "cc.spray" %% "spray-json" % "1.1.1" 8 | 9 | // need scalatest also as a build dependency: the build implements a custom reporter 10 | libraryDependencies += "org.scalatest" %% "scalatest" % "1.9.1" 11 | 12 | // dispatch uses commons-codec, in version 1.4, so we can't go for 1.6. 13 | // libraryDependencies += "commons-codec" % "commons-codec" % "1.4" 14 | 15 | libraryDependencies += "org.apache.commons" % "commons-lang3" % "3.1" 16 | 17 | // sbteclipse-plugin uses scalaz-core 6.0.3, so we can't go 6.0.4 18 | // libraryDependencies += "org.scalaz" %% "scalaz-core" % "6.0.3" 19 | 20 | scalacOptions ++= Seq("-deprecation") 21 | 22 | addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.1.0") 23 | 24 | // for dependency-graph plugin 25 | // net.virtualvoid.sbt.graph.Plugin.graphSettings 26 | 27 | 28 | // [info] default:default-3fdafc_2.9.1:0.1-SNAPSHOT 29 | // [info] +-cc.spray:spray-json_2.9.1:1.1.1 30 | // [info] | +-org.parboiled:parboiled-scala:1.0.2 31 | // [info] | | +-org.parboiled:parboiled-core:1.0.2 32 | // [info] | | +-org.scala-lang:scala-library:2.9.1 33 | // [info] | | 34 | // [info] | +-org.scala-lang:scala-library:2.9.1 35 | // [info] | 36 | // [info] +-com.typesafe.sbteclipse:sbteclipse-plugin:2.1.0 37 | // [info] | +-com.typesafe.sbteclipse:sbteclipse-core:2.1.0 38 | // [info] | +-org.scalaz:scalaz-core_2.9.1:6.0.3 39 | // [info] | +-org.scala-lang:scala-library:2.9.1 40 | // [info] | 41 | // [info] +-net.databinder:dispatch-http_2.9.1:0.8.8 42 | // [info] | +-net.databinder:dispatch-core_2.9.1:0.8.8 43 | // [info] | | +-org.apache.httpcomponents:httpclient:4.1.3 44 | // [info] | | | +-commons-codec:commons-codec:1.4 45 | // [info] | | | +-commons-logging:commons-logging:1.1.1 46 | // [info] | | | +-org.apache.httpcomponents:httpcore:4.1.4 47 | // [info] | | | 48 | // [info] | | +-org.scala-lang:scala-library:2.9.1 49 | // [info] | | 50 | // [info] | +-net.databinder:dispatch-futures_2.9.1:0.8.8 51 | // [info] | | +-org.scala-lang:scala-library:2.9.1 52 | // [info] | | 53 | // [info] | +-org.apache.httpcomponents:httpclient:4.1.3 54 | // [info] | | +-commons-codec:commons-codec:1.4 55 | // [info] | | +-commons-logging:commons-logging:1.1.1 56 | // [info] | | +-org.apache.httpcomponents:httpcore:4.1.4 57 | // [info] | | 58 | // [info] | +-org.scala-lang:scala-library:2.9.1 59 | // [info] | 60 | // [info] +-org.scala-lang:scala-library:2.9.1 61 | // [info] +-org.scalastyle:scalastyle_2.9.1:0.1.3-SNAPSHOT 62 | // [info] | +-com.github.scopt:scopt_2.9.1:2.0.0 63 | // [info] | | +-org.scala-lang:scala-library:2.9.1 64 | // [info] | | 65 | // [info] | +-org.scalariform:scalariform_2.9.1:0.1.1 66 | // [info] | +-org.scala-lang:scala-library:2.9.1 67 | // [info] | 68 | // [info] +-org.scalatest:scalatest_2.9.1:1.8 69 | // [info] +-org.scala-lang:scala-library:2.9.1 70 | -------------------------------------------------------------------------------- /calculator/build.sbt: -------------------------------------------------------------------------------- 1 | submitProjectName := "calculator" 2 | 3 | scalaVersion := "2.11.5" 4 | 5 | scalacOptions ++= Seq("-deprecation", "-feature") 6 | 7 | (fork in Test) := false 8 | 9 | projectDetailsMap := { 10 | val currentCourseId = "reactive-002" 11 | 12 | val depsNode = Seq( 13 | "com.netflix.rxjava" % "rxjava-scala" % "0.15.0", 14 | "org.json4s" %% "json4s-native" % "3.2.11", 15 | "org.scala-lang.modules" %% "scala-swing" % "1.0.1", 16 | "net.databinder.dispatch" %% "dispatch-core" % "0.11.0", 17 | "org.scala-lang" % "scala-reflect" % scalaVersion.value, 18 | "org.slf4j" % "slf4j-api" % "1.7.5", 19 | "org.slf4j" % "slf4j-simple" % "1.7.5", 20 | "com.squareup.retrofit" % "retrofit" % "1.0.0", 21 | "org.scala-lang.modules" %% "scala-async" % "0.9.2" 22 | ) 23 | 24 | val depsAkka = Seq( 25 | "com.typesafe.akka" %% "akka-actor" % "2.3.9", 26 | "com.typesafe.akka" %% "akka-testkit" % "2.3.9", 27 | "com.typesafe.akka" %% "akka-persistence-experimental" % "2.3.9" 28 | ) 29 | 30 | Map( 31 | "example" -> ProjectDetails( 32 | packageName = "example", 33 | assignmentPartId = "fTzFogNl", 34 | maxScore = 10d, 35 | styleScoreRatio = 0.0, 36 | courseId=currentCourseId), 37 | "quickcheck" -> ProjectDetails( 38 | packageName = "quickcheck", 39 | assignmentPartId = "02Vi5q7m", 40 | maxScore = 10d, 41 | styleScoreRatio = 0.0, 42 | courseId=currentCourseId, 43 | dependencies = Seq("org.scalacheck" %% "scalacheck" % "1.12.1")), 44 | "calculator" -> ProjectDetails( 45 | packageName = "calculator", 46 | assignmentPartId = "8uURtbi7", 47 | maxScore = 10d, 48 | styleScoreRatio = 0.0, 49 | courseId=currentCourseId), 50 | "nodescala" -> ProjectDetails( 51 | packageName = "nodescala", 52 | assignmentPartId = "RvoTAbRy", 53 | maxScore = 10d, 54 | styleScoreRatio = 0.0, 55 | courseId=currentCourseId, 56 | dependencies = depsNode), 57 | "suggestions" -> ProjectDetails( 58 | packageName = "suggestions", 59 | assignmentPartId = "rLLdQLGN", 60 | maxScore = 10d, 61 | styleScoreRatio = 0.0, 62 | courseId=currentCourseId), 63 | "actorbintree" -> ProjectDetails( 64 | packageName = "actorbintree", 65 | assignmentPartId = "VxIlIKoW", 66 | maxScore = 10d, 67 | styleScoreRatio = 0.0, 68 | courseId=currentCourseId, 69 | dependencies = depsAkka), 70 | "kvstore" -> ProjectDetails( 71 | packageName = "kvstore", 72 | assignmentPartId = "nuvh59Zi", 73 | maxScore = 20d, 74 | styleScoreRatio = 0.0, 75 | courseId=currentCourseId, 76 | dependencies = depsAkka) 77 | )} 78 | -------------------------------------------------------------------------------- /nodescala/build.sbt: -------------------------------------------------------------------------------- 1 | submitProjectName := "nodescala" 2 | 3 | scalaVersion := "2.11.5" 4 | 5 | scalacOptions ++= Seq("-deprecation", "-feature") 6 | 7 | (fork in Test) := false 8 | 9 | projectDetailsMap := { 10 | val currentCourseId = "reactive-002" 11 | 12 | val depsNode = Seq( 13 | "com.netflix.rxjava" % "rxjava-scala" % "0.15.0", 14 | "org.json4s" %% "json4s-native" % "3.2.11", 15 | "org.scala-lang.modules" %% "scala-swing" % "1.0.1", 16 | "net.databinder.dispatch" %% "dispatch-core" % "0.11.0", 17 | "org.scala-lang" % "scala-reflect" % scalaVersion.value, 18 | "org.slf4j" % "slf4j-api" % "1.7.5", 19 | "org.slf4j" % "slf4j-simple" % "1.7.5", 20 | "com.squareup.retrofit" % "retrofit" % "1.0.0", 21 | "org.scala-lang.modules" %% "scala-async" % "0.9.2" 22 | ) 23 | 24 | val depsAkka = Seq( 25 | "com.typesafe.akka" %% "akka-actor" % "2.3.9", 26 | "com.typesafe.akka" %% "akka-testkit" % "2.3.9", 27 | "com.typesafe.akka" %% "akka-persistence-experimental" % "2.3.9" 28 | ) 29 | 30 | Map( 31 | "example" -> ProjectDetails( 32 | packageName = "example", 33 | assignmentPartId = "fTzFogNl", 34 | maxScore = 10d, 35 | styleScoreRatio = 0.0, 36 | courseId=currentCourseId), 37 | "quickcheck" -> ProjectDetails( 38 | packageName = "quickcheck", 39 | assignmentPartId = "02Vi5q7m", 40 | maxScore = 10d, 41 | styleScoreRatio = 0.0, 42 | courseId=currentCourseId, 43 | dependencies = Seq("org.scalacheck" %% "scalacheck" % "1.12.1")), 44 | "calculator" -> ProjectDetails( 45 | packageName = "calculator", 46 | assignmentPartId = "8uURtbi7", 47 | maxScore = 10d, 48 | styleScoreRatio = 0.0, 49 | courseId=currentCourseId), 50 | "nodescala" -> ProjectDetails( 51 | packageName = "nodescala", 52 | assignmentPartId = "RvoTAbRy", 53 | maxScore = 10d, 54 | styleScoreRatio = 0.0, 55 | courseId=currentCourseId, 56 | dependencies = depsNode), 57 | "suggestions" -> ProjectDetails( 58 | packageName = "suggestions", 59 | assignmentPartId = "rLLdQLGN", 60 | maxScore = 10d, 61 | styleScoreRatio = 0.0, 62 | courseId=currentCourseId), 63 | "actorbintree" -> ProjectDetails( 64 | packageName = "actorbintree", 65 | assignmentPartId = "VxIlIKoW", 66 | maxScore = 10d, 67 | styleScoreRatio = 0.0, 68 | courseId=currentCourseId, 69 | dependencies = depsAkka), 70 | "kvstore" -> ProjectDetails( 71 | packageName = "kvstore", 72 | assignmentPartId = "nuvh59Zi", 73 | maxScore = 20d, 74 | styleScoreRatio = 0.0, 75 | courseId=currentCourseId, 76 | dependencies = depsAkka) 77 | )} 78 | -------------------------------------------------------------------------------- /quickcheck/build.sbt: -------------------------------------------------------------------------------- 1 | submitProjectName := "quickcheck" 2 | 3 | scalaVersion := "2.11.5" 4 | 5 | scalacOptions ++= Seq("-deprecation", "-feature") 6 | 7 | (fork in Test) := false 8 | 9 | projectDetailsMap := { 10 | val currentCourseId = "reactive-002" 11 | 12 | val depsNode = Seq( 13 | "com.netflix.rxjava" % "rxjava-scala" % "0.15.0", 14 | "org.json4s" %% "json4s-native" % "3.2.11", 15 | "org.scala-lang.modules" %% "scala-swing" % "1.0.1", 16 | "net.databinder.dispatch" %% "dispatch-core" % "0.11.0", 17 | "org.scala-lang" % "scala-reflect" % scalaVersion.value, 18 | "org.slf4j" % "slf4j-api" % "1.7.5", 19 | "org.slf4j" % "slf4j-simple" % "1.7.5", 20 | "com.squareup.retrofit" % "retrofit" % "1.0.0", 21 | "org.scala-lang.modules" %% "scala-async" % "0.9.2" 22 | ) 23 | 24 | val depsAkka = Seq( 25 | "com.typesafe.akka" %% "akka-actor" % "2.3.9", 26 | "com.typesafe.akka" %% "akka-testkit" % "2.3.9", 27 | "com.typesafe.akka" %% "akka-persistence-experimental" % "2.3.9" 28 | ) 29 | 30 | Map( 31 | "example" -> ProjectDetails( 32 | packageName = "example", 33 | assignmentPartId = "fTzFogNl", 34 | maxScore = 10d, 35 | styleScoreRatio = 0.0, 36 | courseId=currentCourseId), 37 | "quickcheck" -> ProjectDetails( 38 | packageName = "quickcheck", 39 | assignmentPartId = "02Vi5q7m", 40 | maxScore = 10d, 41 | styleScoreRatio = 0.0, 42 | courseId=currentCourseId, 43 | dependencies = Seq("org.scalacheck" %% "scalacheck" % "1.12.1")), 44 | "simulations" -> ProjectDetails( 45 | packageName = "simulations", 46 | assignmentPartId = "pA3TAeu1", 47 | maxScore = 10d, 48 | styleScoreRatio = 0.0, 49 | courseId=currentCourseId), 50 | "nodescala" -> ProjectDetails( 51 | packageName = "nodescala", 52 | assignmentPartId = "RvoTAbRy", 53 | maxScore = 10d, 54 | styleScoreRatio = 0.0, 55 | courseId=currentCourseId, 56 | dependencies = depsNode), 57 | "suggestions" -> ProjectDetails( 58 | packageName = "suggestions", 59 | assignmentPartId = "rLLdQLGN", 60 | maxScore = 10d, 61 | styleScoreRatio = 0.0, 62 | courseId=currentCourseId), 63 | "actorbintree" -> ProjectDetails( 64 | packageName = "actorbintree", 65 | assignmentPartId = "VxIlIKoW", 66 | maxScore = 10d, 67 | styleScoreRatio = 0.0, 68 | courseId=currentCourseId, 69 | dependencies = depsAkka), 70 | "kvstore" -> ProjectDetails( 71 | packageName = "kvstore", 72 | assignmentPartId = "nuvh59Zi", 73 | maxScore = 20d, 74 | styleScoreRatio = 0.0, 75 | courseId=currentCourseId, 76 | dependencies = depsAkka) 77 | )} 78 | -------------------------------------------------------------------------------- /forcomp/src/test/scala/forcomp/AnagramsSuite.scala: -------------------------------------------------------------------------------- 1 | package forcomp 2 | 3 | import org.scalatest.FunSuite 4 | 5 | import org.junit.runner.RunWith 6 | import org.scalatest.junit.JUnitRunner 7 | 8 | import Anagrams._ 9 | 10 | @RunWith(classOf[JUnitRunner]) 11 | class AnagramsSuite extends FunSuite { 12 | 13 | test("wordOccurrences: abcd") { 14 | assert(wordOccurrences("abcd") === List(('a', 1), ('b', 1), ('c', 1), ('d', 1))) 15 | } 16 | 17 | test("wordOccurrences: Robert") { 18 | assert(wordOccurrences("Robert") === List(('b', 1), ('e', 1), ('o', 1), ('r', 2), ('t', 1))) 19 | } 20 | 21 | 22 | 23 | test("sentenceOccurrences: abcd e") { 24 | assert(sentenceOccurrences(List("abcd", "e")) === List(('a', 1), ('b', 1), ('c', 1), ('d', 1), ('e', 1))) 25 | } 26 | 27 | 28 | 29 | test("dictionaryByOccurrences.get: eat") { 30 | assert(dictionaryByOccurrences.get(List(('a', 1), ('e', 1), ('t', 1))).map(_.toSet) === Some(Set("ate", "eat", "tea"))) 31 | } 32 | 33 | 34 | 35 | test("word anagrams: married") { 36 | assert(wordAnagrams("married").toSet === Set("married", "admirer")) 37 | } 38 | 39 | test("word anagrams: player") { 40 | assert(wordAnagrams("player").toSet === Set("parley", "pearly", "player", "replay")) 41 | } 42 | 43 | 44 | 45 | test("subtract: lard - r") { 46 | val lard = List(('a', 1), ('d', 1), ('l', 1), ('r', 1)) 47 | val r = List(('r', 1)) 48 | val lad = List(('a', 1), ('d', 1), ('l', 1)) 49 | assert(subtract(lard, r) === lad) 50 | } 51 | 52 | 53 | 54 | test("combinations: []") { 55 | assert(combinations(Nil) === List(Nil)) 56 | } 57 | 58 | test("combinations: abba") { 59 | val abba = List(('a', 2), ('b', 2)) 60 | val abbacomb = List( 61 | List(), 62 | List(('a', 1)), 63 | List(('a', 2)), 64 | List(('b', 1)), 65 | List(('a', 1), ('b', 1)), 66 | List(('a', 2), ('b', 1)), 67 | List(('b', 2)), 68 | List(('a', 1), ('b', 2)), 69 | List(('a', 2), ('b', 2)) 70 | ) 71 | assert(combinations(abba).toSet === abbacomb.toSet) 72 | } 73 | 74 | 75 | 76 | test("sentence anagrams: []") { 77 | val sentence = List() 78 | assert(sentenceAnagrams(sentence) === List(Nil)) 79 | } 80 | 81 | test("sentence anagrams: Linux rulez") { 82 | val sentence = List("Linux", "rulez") 83 | val anas = List( 84 | List("Rex", "Lin", "Zulu"), 85 | List("nil", "Zulu", "Rex"), 86 | List("Rex", "nil", "Zulu"), 87 | List("Zulu", "Rex", "Lin"), 88 | List("null", "Uzi", "Rex"), 89 | List("Rex", "Zulu", "Lin"), 90 | List("Uzi", "null", "Rex"), 91 | List("Rex", "null", "Uzi"), 92 | List("null", "Rex", "Uzi"), 93 | List("Lin", "Rex", "Zulu"), 94 | List("nil", "Rex", "Zulu"), 95 | List("Rex", "Uzi", "null"), 96 | List("Rex", "Zulu", "nil"), 97 | List("Zulu", "Rex", "nil"), 98 | List("Zulu", "Lin", "Rex"), 99 | List("Lin", "Zulu", "Rex"), 100 | List("Uzi", "Rex", "null"), 101 | List("Zulu", "nil", "Rex"), 102 | List("rulez", "Linux"), 103 | List("Linux", "rulez") 104 | ) 105 | assert(sentenceAnagrams(sentence).toSet === anas.toSet) 106 | } 107 | 108 | } 109 | -------------------------------------------------------------------------------- /actorbintree/build.sbt: -------------------------------------------------------------------------------- 1 | submitProjectName := "actorbintree" 2 | 3 | scalaVersion := "2.11.5" 4 | 5 | scalacOptions ++= Seq("-deprecation", "-feature") 6 | 7 | (fork in Test) := false 8 | 9 | projectDetailsMap := { 10 | val currentCourseId = "reactive-002" 11 | 12 | val depsNode = Seq( 13 | "io.reactivex" %% "rxscala" % "0.23.0", 14 | "io.reactivex" % "rxswing" % "0.21.0", // for Swing Scheduler in suggestions 15 | "org.json4s" %% "json4s-native" % "3.2.11", 16 | "org.scala-lang.modules" %% "scala-swing" % "1.0.1", 17 | "net.databinder.dispatch" %% "dispatch-core" % "0.11.0", 18 | "org.scala-lang" % "scala-reflect" % scalaVersion.value, 19 | "org.slf4j" % "slf4j-api" % "1.7.5", 20 | "org.slf4j" % "slf4j-simple" % "1.7.5", 21 | "com.squareup.retrofit" % "retrofit" % "1.0.0", 22 | "org.scala-lang.modules" %% "scala-async" % "0.9.2" 23 | ) 24 | 25 | val depsAkka = Seq( 26 | "com.typesafe.akka" %% "akka-actor" % "2.3.9", 27 | "com.typesafe.akka" %% "akka-testkit" % "2.3.9", 28 | "com.typesafe.akka" %% "akka-persistence-experimental" % "2.3.9" 29 | ) 30 | 31 | Map( 32 | "example" -> ProjectDetails( 33 | packageName = "example", 34 | assignmentPartId = "fTzFogNl", 35 | maxScore = 10d, 36 | styleScoreRatio = 0.0, 37 | courseId=currentCourseId), 38 | "quickcheck" -> ProjectDetails( 39 | packageName = "quickcheck", 40 | assignmentPartId = "02Vi5q7m", 41 | maxScore = 10d, 42 | styleScoreRatio = 0.0, 43 | courseId=currentCourseId, 44 | dependencies = Seq("org.scalacheck" %% "scalacheck" % "1.12.1")), 45 | "calculator" -> ProjectDetails( 46 | packageName = "calculator", 47 | assignmentPartId = "8uURtbi7", 48 | maxScore = 10d, 49 | styleScoreRatio = 0.0, 50 | courseId=currentCourseId), 51 | "nodescala" -> ProjectDetails( 52 | packageName = "nodescala", 53 | assignmentPartId = "RvoTAbRy", 54 | maxScore = 10d, 55 | styleScoreRatio = 0.0, 56 | courseId=currentCourseId, 57 | dependencies = depsNode), 58 | "suggestions" -> ProjectDetails( 59 | packageName = "suggestions", 60 | assignmentPartId = "rLLdQLGN", 61 | maxScore = 10d, 62 | styleScoreRatio = 0.0, 63 | courseId=currentCourseId), 64 | "actorbintree" -> ProjectDetails( 65 | packageName = "actorbintree", 66 | assignmentPartId = "VxIlIKoW", 67 | maxScore = 10d, 68 | styleScoreRatio = 0.0, 69 | courseId=currentCourseId, 70 | dependencies = depsAkka), 71 | "kvstore" -> ProjectDetails( 72 | packageName = "kvstore", 73 | assignmentPartId = "nuvh59Zi", 74 | maxScore = 20d, 75 | styleScoreRatio = 0.0, 76 | courseId=currentCourseId, 77 | dependencies = depsAkka) 78 | )} 79 | -------------------------------------------------------------------------------- /suggestions/build.sbt: -------------------------------------------------------------------------------- 1 | submitProjectName := "suggestions" 2 | 3 | scalaVersion := "2.11.5" 4 | 5 | scalacOptions ++= Seq("-deprecation", "-feature") 6 | 7 | (fork in Test) := false 8 | 9 | projectDetailsMap := { 10 | val currentCourseId = "reactive-002" 11 | 12 | val depsNode = Seq( 13 | "io.reactivex" %% "rxscala" % "0.23.0", 14 | "io.reactivex" % "rxswing" % "0.21.0", // for Swing Scheduler in suggestions 15 | "org.json4s" %% "json4s-native" % "3.2.11", 16 | "org.scala-lang.modules" %% "scala-swing" % "1.0.1", 17 | "net.databinder.dispatch" %% "dispatch-core" % "0.11.0", 18 | "org.scala-lang" % "scala-reflect" % scalaVersion.value, 19 | "org.slf4j" % "slf4j-api" % "1.7.5", 20 | "org.slf4j" % "slf4j-simple" % "1.7.5", 21 | "com.squareup.retrofit" % "retrofit" % "1.0.0", 22 | "org.scala-lang.modules" %% "scala-async" % "0.9.2" 23 | ) 24 | 25 | val depsAkka = Seq( 26 | "com.typesafe.akka" %% "akka-actor" % "2.3.9", 27 | "com.typesafe.akka" %% "akka-testkit" % "2.3.9", 28 | "com.typesafe.akka" %% "akka-persistence-experimental" % "2.3.9" 29 | ) 30 | 31 | Map( 32 | "example" -> ProjectDetails( 33 | packageName = "example", 34 | assignmentPartId = "fTzFogNl", 35 | maxScore = 10d, 36 | styleScoreRatio = 0.0, 37 | courseId=currentCourseId), 38 | "quickcheck" -> ProjectDetails( 39 | packageName = "quickcheck", 40 | assignmentPartId = "02Vi5q7m", 41 | maxScore = 10d, 42 | styleScoreRatio = 0.0, 43 | courseId=currentCourseId, 44 | dependencies = Seq("org.scalacheck" %% "scalacheck" % "1.12.1")), 45 | "calculator" -> ProjectDetails( 46 | packageName = "calculator", 47 | assignmentPartId = "8uURtbi7", 48 | maxScore = 10d, 49 | styleScoreRatio = 0.0, 50 | courseId=currentCourseId), 51 | "nodescala" -> ProjectDetails( 52 | packageName = "nodescala", 53 | assignmentPartId = "RvoTAbRy", 54 | maxScore = 10d, 55 | styleScoreRatio = 0.0, 56 | courseId=currentCourseId, 57 | dependencies = depsNode), 58 | "suggestions" -> ProjectDetails( 59 | packageName = "suggestions", 60 | assignmentPartId = "rLLdQLGN", 61 | maxScore = 10d, 62 | styleScoreRatio = 0.0, 63 | courseId=currentCourseId), 64 | "actorbintree" -> ProjectDetails( 65 | packageName = "actorbintree", 66 | assignmentPartId = "VxIlIKoW", 67 | maxScore = 10d, 68 | styleScoreRatio = 0.0, 69 | courseId=currentCourseId, 70 | dependencies = depsAkka), 71 | "kvstore" -> ProjectDetails( 72 | packageName = "kvstore", 73 | assignmentPartId = "nuvh59Zi", 74 | maxScore = 20d, 75 | styleScoreRatio = 0.0, 76 | courseId=currentCourseId, 77 | dependencies = depsAkka) 78 | )} 79 | -------------------------------------------------------------------------------- /forcomp/project/StyleChecker.scala: -------------------------------------------------------------------------------- 1 | import sbt.File 2 | import java.io.ByteArrayOutputStream 3 | import java.io.PrintStream 4 | import org.scalastyle._ 5 | import Settings._ 6 | 7 | object StyleChecker { 8 | val maxResult = 100 9 | 10 | class CustomTextOutput[T <: FileSpec]() extends Output[T] { 11 | private val messageHelper = new MessageHelper(this.getClass().getClassLoader()) 12 | 13 | var fileCount: Int = _ 14 | override def message(m: Message[T]): Unit = m match { 15 | case StartWork() => 16 | case EndWork() => 17 | case StartFile(file) => 18 | print("Checking file " + file + "...") 19 | fileCount = 0 20 | case EndFile(file) => 21 | if (fileCount == 0) println(" OK!") 22 | case StyleError(file, clazz, key, level, args, line, column, customMessage) => 23 | report(line, column, messageHelper.text(level.name), 24 | Output.findMessage(messageHelper, clazz, key, args, customMessage)) 25 | case StyleException(file, clazz, message, stacktrace, line, column) => 26 | report(line, column, "error", message) 27 | } 28 | 29 | private def report(line: Option[Int], column: Option[Int], level: String, message: String) { 30 | if (fileCount == 0) println("") 31 | fileCount += 1 32 | println(" " + fileCount + ". " + level + pos(line, column) + ":") 33 | println(" " + message) 34 | } 35 | 36 | private def pos(line: Option[Int], column: Option[Int]): String = line match { 37 | case Some(line) => " at line " + line + (column match { 38 | case Some(column) => " character " + column 39 | case None => "" 40 | }) 41 | case None => "" 42 | } 43 | } 44 | 45 | def score(outputResult: OutputResult) = { 46 | val penalties = outputResult.errors + outputResult.warnings 47 | scala.math.max(maxResult - penalties, 0) 48 | } 49 | 50 | def assess(allSources: Seq[File]): (String, Int) = { 51 | val reactive = allSources.exists{ f => 52 | val path = f.getAbsolutePath 53 | path.contains("quickcheck") || 54 | path.contains("nodescala") || 55 | path.contains("suggestions") || 56 | path.contains("actorbintree") || 57 | path.contains("kvstore") 58 | } 59 | val tweak = if (reactive) "_reactive" else "" 60 | 61 | val configFile = new File("project/scalastyle_config" + tweak + ".xml").getAbsolutePath 62 | 63 | val sources = allSources.filterNot{ f => 64 | val path = f.getAbsolutePath 65 | path.contains("interpreter") || 66 | path.contains("fetchtweets") || 67 | path.contains("simulations") 68 | } 69 | 70 | val messages = new ScalastyleChecker().checkFiles( 71 | ScalastyleConfiguration.readFromXml(configFile), 72 | Directory.getFiles(None, sources)) 73 | 74 | val output = new ByteArrayOutputStream() 75 | val outputResult = Console.withOut(new PrintStream(output)) { 76 | new CustomTextOutput().output(messages) 77 | } 78 | 79 | val msg = 80 | output.toString + 81 | "Processed " + outputResult.files + " file(s)\n" + 82 | "Found " + outputResult.errors + " errors\n" + 83 | "Found " + outputResult.warnings + " warnings\n" + 84 | (if (outputResult.errors+outputResult.warnings > 0) "Consult the style guide at %s/wiki/ScalaStyleGuide".format(baseURL("progfun-005")) else "") 85 | 86 | (msg, score(outputResult)) 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /funsets/project/StyleChecker.scala: -------------------------------------------------------------------------------- 1 | import sbt.File 2 | import java.io.ByteArrayOutputStream 3 | import java.io.PrintStream 4 | import org.scalastyle._ 5 | import Settings._ 6 | 7 | object StyleChecker { 8 | val maxResult = 100 9 | 10 | class CustomTextOutput[T <: FileSpec]() extends Output[T] { 11 | private val messageHelper = new MessageHelper(this.getClass().getClassLoader()) 12 | 13 | var fileCount: Int = _ 14 | override def message(m: Message[T]): Unit = m match { 15 | case StartWork() => 16 | case EndWork() => 17 | case StartFile(file) => 18 | print("Checking file " + file + "...") 19 | fileCount = 0 20 | case EndFile(file) => 21 | if (fileCount == 0) println(" OK!") 22 | case StyleError(file, clazz, key, level, args, line, column, customMessage) => 23 | report(line, column, messageHelper.text(level.name), 24 | Output.findMessage(messageHelper, clazz, key, args, customMessage)) 25 | case StyleException(file, clazz, message, stacktrace, line, column) => 26 | report(line, column, "error", message) 27 | } 28 | 29 | private def report(line: Option[Int], column: Option[Int], level: String, message: String) { 30 | if (fileCount == 0) println("") 31 | fileCount += 1 32 | println(" " + fileCount + ". " + level + pos(line, column) + ":") 33 | println(" " + message) 34 | } 35 | 36 | private def pos(line: Option[Int], column: Option[Int]): String = line match { 37 | case Some(line) => " at line " + line + (column match { 38 | case Some(column) => " character " + column 39 | case None => "" 40 | }) 41 | case None => "" 42 | } 43 | } 44 | 45 | def score(outputResult: OutputResult) = { 46 | val penalties = outputResult.errors + outputResult.warnings 47 | scala.math.max(maxResult - penalties, 0) 48 | } 49 | 50 | def assess(allSources: Seq[File]): (String, Int) = { 51 | val reactive = allSources.exists{ f => 52 | val path = f.getAbsolutePath 53 | path.contains("quickcheck") || 54 | path.contains("nodescala") || 55 | path.contains("suggestions") || 56 | path.contains("actorbintree") || 57 | path.contains("kvstore") 58 | } 59 | val tweak = if (reactive) "_reactive" else "" 60 | 61 | val configFile = new File("project/scalastyle_config" + tweak + ".xml").getAbsolutePath 62 | 63 | val sources = allSources.filterNot{ f => 64 | val path = f.getAbsolutePath 65 | path.contains("interpreter") || 66 | path.contains("fetchtweets") || 67 | path.contains("simulations") 68 | } 69 | 70 | val messages = new ScalastyleChecker().checkFiles( 71 | ScalastyleConfiguration.readFromXml(configFile), 72 | Directory.getFiles(None, sources)) 73 | 74 | val output = new ByteArrayOutputStream() 75 | val outputResult = Console.withOut(new PrintStream(output)) { 76 | new CustomTextOutput().output(messages) 77 | } 78 | 79 | val msg = 80 | output.toString + 81 | "Processed " + outputResult.files + " file(s)\n" + 82 | "Found " + outputResult.errors + " errors\n" + 83 | "Found " + outputResult.warnings + " warnings\n" + 84 | (if (outputResult.errors+outputResult.warnings > 0) "Consult the style guide at %s/wiki/ScalaStyleGuide".format(baseURL("progfun-005")) else "") 85 | 86 | (msg, score(outputResult)) 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /objsets/project/StyleChecker.scala: -------------------------------------------------------------------------------- 1 | import sbt.File 2 | import java.io.ByteArrayOutputStream 3 | import java.io.PrintStream 4 | import org.scalastyle._ 5 | import Settings._ 6 | 7 | object StyleChecker { 8 | val maxResult = 100 9 | 10 | class CustomTextOutput[T <: FileSpec]() extends Output[T] { 11 | private val messageHelper = new MessageHelper(this.getClass().getClassLoader()) 12 | 13 | var fileCount: Int = _ 14 | override def message(m: Message[T]): Unit = m match { 15 | case StartWork() => 16 | case EndWork() => 17 | case StartFile(file) => 18 | print("Checking file " + file + "...") 19 | fileCount = 0 20 | case EndFile(file) => 21 | if (fileCount == 0) println(" OK!") 22 | case StyleError(file, clazz, key, level, args, line, column, customMessage) => 23 | report(line, column, messageHelper.text(level.name), 24 | Output.findMessage(messageHelper, clazz, key, args, customMessage)) 25 | case StyleException(file, clazz, message, stacktrace, line, column) => 26 | report(line, column, "error", message) 27 | } 28 | 29 | private def report(line: Option[Int], column: Option[Int], level: String, message: String) { 30 | if (fileCount == 0) println("") 31 | fileCount += 1 32 | println(" " + fileCount + ". " + level + pos(line, column) + ":") 33 | println(" " + message) 34 | } 35 | 36 | private def pos(line: Option[Int], column: Option[Int]): String = line match { 37 | case Some(line) => " at line " + line + (column match { 38 | case Some(column) => " character " + column 39 | case None => "" 40 | }) 41 | case None => "" 42 | } 43 | } 44 | 45 | def score(outputResult: OutputResult) = { 46 | val penalties = outputResult.errors + outputResult.warnings 47 | scala.math.max(maxResult - penalties, 0) 48 | } 49 | 50 | def assess(allSources: Seq[File]): (String, Int) = { 51 | val reactive = allSources.exists{ f => 52 | val path = f.getAbsolutePath 53 | path.contains("quickcheck") || 54 | path.contains("nodescala") || 55 | path.contains("suggestions") || 56 | path.contains("actorbintree") || 57 | path.contains("kvstore") 58 | } 59 | val tweak = if (reactive) "_reactive" else "" 60 | 61 | val configFile = new File("project/scalastyle_config" + tweak + ".xml").getAbsolutePath 62 | 63 | val sources = allSources.filterNot{ f => 64 | val path = f.getAbsolutePath 65 | path.contains("interpreter") || 66 | path.contains("fetchtweets") || 67 | path.contains("simulations") 68 | } 69 | 70 | val messages = new ScalastyleChecker().checkFiles( 71 | ScalastyleConfiguration.readFromXml(configFile), 72 | Directory.getFiles(None, sources)) 73 | 74 | val output = new ByteArrayOutputStream() 75 | val outputResult = Console.withOut(new PrintStream(output)) { 76 | new CustomTextOutput().output(messages) 77 | } 78 | 79 | val msg = 80 | output.toString + 81 | "Processed " + outputResult.files + " file(s)\n" + 82 | "Found " + outputResult.errors + " errors\n" + 83 | "Found " + outputResult.warnings + " warnings\n" + 84 | (if (outputResult.errors+outputResult.warnings > 0) "Consult the style guide at %s/wiki/ScalaStyleGuide".format(baseURL("progfun-005")) else "") 85 | 86 | (msg, score(outputResult)) 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /patmat/project/StyleChecker.scala: -------------------------------------------------------------------------------- 1 | import sbt.File 2 | import java.io.ByteArrayOutputStream 3 | import java.io.PrintStream 4 | import org.scalastyle._ 5 | import Settings._ 6 | 7 | object StyleChecker { 8 | val maxResult = 100 9 | 10 | class CustomTextOutput[T <: FileSpec]() extends Output[T] { 11 | private val messageHelper = new MessageHelper(this.getClass().getClassLoader()) 12 | 13 | var fileCount: Int = _ 14 | override def message(m: Message[T]): Unit = m match { 15 | case StartWork() => 16 | case EndWork() => 17 | case StartFile(file) => 18 | print("Checking file " + file + "...") 19 | fileCount = 0 20 | case EndFile(file) => 21 | if (fileCount == 0) println(" OK!") 22 | case StyleError(file, clazz, key, level, args, line, column, customMessage) => 23 | report(line, column, messageHelper.text(level.name), 24 | Output.findMessage(messageHelper, clazz, key, args, customMessage)) 25 | case StyleException(file, clazz, message, stacktrace, line, column) => 26 | report(line, column, "error", message) 27 | } 28 | 29 | private def report(line: Option[Int], column: Option[Int], level: String, message: String) { 30 | if (fileCount == 0) println("") 31 | fileCount += 1 32 | println(" " + fileCount + ". " + level + pos(line, column) + ":") 33 | println(" " + message) 34 | } 35 | 36 | private def pos(line: Option[Int], column: Option[Int]): String = line match { 37 | case Some(line) => " at line " + line + (column match { 38 | case Some(column) => " character " + column 39 | case None => "" 40 | }) 41 | case None => "" 42 | } 43 | } 44 | 45 | def score(outputResult: OutputResult) = { 46 | val penalties = outputResult.errors + outputResult.warnings 47 | scala.math.max(maxResult - penalties, 0) 48 | } 49 | 50 | def assess(allSources: Seq[File]): (String, Int) = { 51 | val reactive = allSources.exists{ f => 52 | val path = f.getAbsolutePath 53 | path.contains("quickcheck") || 54 | path.contains("nodescala") || 55 | path.contains("suggestions") || 56 | path.contains("actorbintree") || 57 | path.contains("kvstore") 58 | } 59 | val tweak = if (reactive) "_reactive" else "" 60 | 61 | val configFile = new File("project/scalastyle_config" + tweak + ".xml").getAbsolutePath 62 | 63 | val sources = allSources.filterNot{ f => 64 | val path = f.getAbsolutePath 65 | path.contains("interpreter") || 66 | path.contains("fetchtweets") || 67 | path.contains("simulations") 68 | } 69 | 70 | val messages = new ScalastyleChecker().checkFiles( 71 | ScalastyleConfiguration.readFromXml(configFile), 72 | Directory.getFiles(None, sources)) 73 | 74 | val output = new ByteArrayOutputStream() 75 | val outputResult = Console.withOut(new PrintStream(output)) { 76 | new CustomTextOutput().output(messages) 77 | } 78 | 79 | val msg = 80 | output.toString + 81 | "Processed " + outputResult.files + " file(s)\n" + 82 | "Found " + outputResult.errors + " errors\n" + 83 | "Found " + outputResult.warnings + " warnings\n" + 84 | (if (outputResult.errors+outputResult.warnings > 0) "Consult the style guide at %s/wiki/ScalaStyleGuide".format(baseURL("progfun-005")) else "") 85 | 86 | (msg, score(outputResult)) 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /recfun/project/StyleChecker.scala: -------------------------------------------------------------------------------- 1 | import sbt.File 2 | import java.io.ByteArrayOutputStream 3 | import java.io.PrintStream 4 | import org.scalastyle._ 5 | import Settings._ 6 | 7 | object StyleChecker { 8 | val maxResult = 100 9 | 10 | class CustomTextOutput[T <: FileSpec]() extends Output[T] { 11 | private val messageHelper = new MessageHelper(this.getClass().getClassLoader()) 12 | 13 | var fileCount: Int = _ 14 | override def message(m: Message[T]): Unit = m match { 15 | case StartWork() => 16 | case EndWork() => 17 | case StartFile(file) => 18 | print("Checking file " + file + "...") 19 | fileCount = 0 20 | case EndFile(file) => 21 | if (fileCount == 0) println(" OK!") 22 | case StyleError(file, clazz, key, level, args, line, column, customMessage) => 23 | report(line, column, messageHelper.text(level.name), 24 | Output.findMessage(messageHelper, clazz, key, args, customMessage)) 25 | case StyleException(file, clazz, message, stacktrace, line, column) => 26 | report(line, column, "error", message) 27 | } 28 | 29 | private def report(line: Option[Int], column: Option[Int], level: String, message: String) { 30 | if (fileCount == 0) println("") 31 | fileCount += 1 32 | println(" " + fileCount + ". " + level + pos(line, column) + ":") 33 | println(" " + message) 34 | } 35 | 36 | private def pos(line: Option[Int], column: Option[Int]): String = line match { 37 | case Some(line) => " at line " + line + (column match { 38 | case Some(column) => " character " + column 39 | case None => "" 40 | }) 41 | case None => "" 42 | } 43 | } 44 | 45 | def score(outputResult: OutputResult) = { 46 | val penalties = outputResult.errors + outputResult.warnings 47 | scala.math.max(maxResult - penalties, 0) 48 | } 49 | 50 | def assess(allSources: Seq[File]): (String, Int) = { 51 | val reactive = allSources.exists{ f => 52 | val path = f.getAbsolutePath 53 | path.contains("quickcheck") || 54 | path.contains("nodescala") || 55 | path.contains("suggestions") || 56 | path.contains("actorbintree") || 57 | path.contains("kvstore") 58 | } 59 | val tweak = if (reactive) "_reactive" else "" 60 | 61 | val configFile = new File("project/scalastyle_config" + tweak + ".xml").getAbsolutePath 62 | 63 | val sources = allSources.filterNot{ f => 64 | val path = f.getAbsolutePath 65 | path.contains("interpreter") || 66 | path.contains("fetchtweets") || 67 | path.contains("simulations") 68 | } 69 | 70 | val messages = new ScalastyleChecker().checkFiles( 71 | ScalastyleConfiguration.readFromXml(configFile), 72 | Directory.getFiles(None, sources)) 73 | 74 | val output = new ByteArrayOutputStream() 75 | val outputResult = Console.withOut(new PrintStream(output)) { 76 | new CustomTextOutput().output(messages) 77 | } 78 | 79 | val msg = 80 | output.toString + 81 | "Processed " + outputResult.files + " file(s)\n" + 82 | "Found " + outputResult.errors + " errors\n" + 83 | "Found " + outputResult.warnings + " warnings\n" + 84 | (if (outputResult.errors+outputResult.warnings > 0) "Consult the style guide at %s/wiki/ScalaStyleGuide".format(baseURL("progfun-005")) else "") 85 | 86 | (msg, score(outputResult)) 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /streams/project/StyleChecker.scala: -------------------------------------------------------------------------------- 1 | import sbt.File 2 | import java.io.ByteArrayOutputStream 3 | import java.io.PrintStream 4 | import org.scalastyle._ 5 | import Settings._ 6 | 7 | object StyleChecker { 8 | val maxResult = 100 9 | 10 | class CustomTextOutput[T <: FileSpec]() extends Output[T] { 11 | private val messageHelper = new MessageHelper(this.getClass().getClassLoader()) 12 | 13 | var fileCount: Int = _ 14 | override def message(m: Message[T]): Unit = m match { 15 | case StartWork() => 16 | case EndWork() => 17 | case StartFile(file) => 18 | print("Checking file " + file + "...") 19 | fileCount = 0 20 | case EndFile(file) => 21 | if (fileCount == 0) println(" OK!") 22 | case StyleError(file, clazz, key, level, args, line, column, customMessage) => 23 | report(line, column, messageHelper.text(level.name), 24 | Output.findMessage(messageHelper, clazz, key, args, customMessage)) 25 | case StyleException(file, clazz, message, stacktrace, line, column) => 26 | report(line, column, "error", message) 27 | } 28 | 29 | private def report(line: Option[Int], column: Option[Int], level: String, message: String) { 30 | if (fileCount == 0) println("") 31 | fileCount += 1 32 | println(" " + fileCount + ". " + level + pos(line, column) + ":") 33 | println(" " + message) 34 | } 35 | 36 | private def pos(line: Option[Int], column: Option[Int]): String = line match { 37 | case Some(line) => " at line " + line + (column match { 38 | case Some(column) => " character " + column 39 | case None => "" 40 | }) 41 | case None => "" 42 | } 43 | } 44 | 45 | def score(outputResult: OutputResult) = { 46 | val penalties = outputResult.errors + outputResult.warnings 47 | scala.math.max(maxResult - penalties, 0) 48 | } 49 | 50 | def assess(allSources: Seq[File]): (String, Int) = { 51 | val reactive = allSources.exists{ f => 52 | val path = f.getAbsolutePath 53 | path.contains("quickcheck") || 54 | path.contains("nodescala") || 55 | path.contains("suggestions") || 56 | path.contains("actorbintree") || 57 | path.contains("kvstore") 58 | } 59 | val tweak = if (reactive) "_reactive" else "" 60 | 61 | val configFile = new File("project/scalastyle_config" + tweak + ".xml").getAbsolutePath 62 | 63 | val sources = allSources.filterNot{ f => 64 | val path = f.getAbsolutePath 65 | path.contains("interpreter") || 66 | path.contains("fetchtweets") || 67 | path.contains("simulations") 68 | } 69 | 70 | val messages = new ScalastyleChecker().checkFiles( 71 | ScalastyleConfiguration.readFromXml(configFile), 72 | Directory.getFiles(None, sources)) 73 | 74 | val output = new ByteArrayOutputStream() 75 | val outputResult = Console.withOut(new PrintStream(output)) { 76 | new CustomTextOutput().output(messages) 77 | } 78 | 79 | val msg = 80 | output.toString + 81 | "Processed " + outputResult.files + " file(s)\n" + 82 | "Found " + outputResult.errors + " errors\n" + 83 | "Found " + outputResult.warnings + " warnings\n" + 84 | (if (outputResult.errors+outputResult.warnings > 0) "Consult the style guide at %s/wiki/ScalaStyleGuide".format(baseURL("progfun-005")) else "") 85 | 86 | (msg, score(outputResult)) 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /ass_zip/example/project/StyleChecker.scala: -------------------------------------------------------------------------------- 1 | import sbt.File 2 | import java.io.ByteArrayOutputStream 3 | import java.io.PrintStream 4 | import org.scalastyle._ 5 | import Settings._ 6 | 7 | object StyleChecker { 8 | val maxResult = 100 9 | 10 | class CustomTextOutput[T <: FileSpec]() extends Output[T] { 11 | private val messageHelper = new MessageHelper(this.getClass().getClassLoader()) 12 | 13 | var fileCount: Int = _ 14 | override def message(m: Message[T]): Unit = m match { 15 | case StartWork() => 16 | case EndWork() => 17 | case StartFile(file) => 18 | print("Checking file " + file + "...") 19 | fileCount = 0 20 | case EndFile(file) => 21 | if (fileCount == 0) println(" OK!") 22 | case StyleError(file, clazz, key, level, args, line, column, customMessage) => 23 | report(line, column, messageHelper.text(level.name), 24 | Output.findMessage(messageHelper, clazz, key, args, customMessage)) 25 | case StyleException(file, clazz, message, stacktrace, line, column) => 26 | report(line, column, "error", message) 27 | } 28 | 29 | private def report(line: Option[Int], column: Option[Int], level: String, message: String) { 30 | if (fileCount == 0) println("") 31 | fileCount += 1 32 | println(" " + fileCount + ". " + level + pos(line, column) + ":") 33 | println(" " + message) 34 | } 35 | 36 | private def pos(line: Option[Int], column: Option[Int]): String = line match { 37 | case Some(line) => " at line " + line + (column match { 38 | case Some(column) => " character " + column 39 | case None => "" 40 | }) 41 | case None => "" 42 | } 43 | } 44 | 45 | def score(outputResult: OutputResult) = { 46 | val penalties = outputResult.errors + outputResult.warnings 47 | scala.math.max(maxResult - penalties, 0) 48 | } 49 | 50 | def assess(allSources: Seq[File]): (String, Int) = { 51 | val reactive = allSources.exists{ f => 52 | val path = f.getAbsolutePath 53 | path.contains("quickcheck") || 54 | path.contains("nodescala") || 55 | path.contains("suggestions") || 56 | path.contains("actorbintree") || 57 | path.contains("kvstore") 58 | } 59 | val tweak = if (reactive) "_reactive" else "" 60 | 61 | val configFile = new File("project/scalastyle_config" + tweak + ".xml").getAbsolutePath 62 | 63 | val sources = allSources.filterNot{ f => 64 | val path = f.getAbsolutePath 65 | path.contains("interpreter") || 66 | path.contains("fetchtweets") || 67 | path.contains("simulations") 68 | } 69 | 70 | val messages = new ScalastyleChecker().checkFiles( 71 | ScalastyleConfiguration.readFromXml(configFile), 72 | Directory.getFiles(None, sources)) 73 | 74 | val output = new ByteArrayOutputStream() 75 | val outputResult = Console.withOut(new PrintStream(output)) { 76 | new CustomTextOutput().output(messages) 77 | } 78 | 79 | val msg = 80 | output.toString + 81 | "Processed " + outputResult.files + " file(s)\n" + 82 | "Found " + outputResult.errors + " errors\n" + 83 | "Found " + outputResult.warnings + " warnings\n" + 84 | (if (outputResult.errors+outputResult.warnings > 0) "Consult the style guide at %s/wiki/ScalaStyleGuide".format(baseURL("progfun-005")) else "") 85 | 86 | (msg, score(outputResult)) 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /objsets/src/main/scala/objsets/TweetReader.scala: -------------------------------------------------------------------------------- 1 | package objsets 2 | 3 | object TweetReader { 4 | 5 | object ParseTweets { 6 | import scala.util.parsing.json._ 7 | 8 | def getList[T](s: String): List[T] = 9 | JSON.parseFull(s).get.asInstanceOf[List[T]] 10 | 11 | def getMap(s: String): Map[String, Any] = 12 | JSON.parseFull(s).get.asInstanceOf[Map[String, Any]] 13 | 14 | def getTweets(user: String, json: String): List[Tweet] = 15 | for (map <- getList[Map[String, Any]](json)) yield { 16 | val text = map("text") 17 | val retweets = map("retweet_count") 18 | new Tweet(user, text.toString, retweets.toString.toDouble.toInt) 19 | } 20 | 21 | def getTweetData(user: String, json: String): List[Tweet] = { 22 | // is list 23 | val l = getList[Map[String, Any]](json) 24 | for (map <- l) yield { 25 | val text = map("text") 26 | val retweets = map("retweets") 27 | new Tweet(user, text.toString, retweets.toString.toDouble.toInt) 28 | } 29 | } 30 | } 31 | 32 | def toTweetSet(l: List[Tweet]): TweetSet = { 33 | l.foldLeft(new Empty: TweetSet)(_.incl(_)) 34 | } 35 | 36 | def unparseToData(tws: List[Tweet]): String = { 37 | val buf = new StringBuffer 38 | for (tw <- tws) { 39 | val json = "{ \"user\": \"" + tw.user + "\", \"text\": \"" + 40 | tw.text.replaceAll(""""""", "\\\\\\\"") + "\", \"retweets\": " + 41 | tw.retweets + ".0 }" 42 | buf.append(json + ",\n") 43 | } 44 | buf.toString 45 | } 46 | 47 | val sites = List("gizmodo", "TechCrunch", "engadget", "amazondeals", "CNET", "gadgetlab", "mashable") 48 | 49 | private val gizmodoTweets = TweetReader.ParseTweets.getTweetData("gizmodo", TweetData.gizmodo) 50 | private val techCrunchTweets = TweetReader.ParseTweets.getTweetData("TechCrunch", TweetData.TechCrunch) 51 | private val engadgetTweets = TweetReader.ParseTweets.getTweetData("engadget", TweetData.engadget) 52 | private val amazondealsTweets = TweetReader.ParseTweets.getTweetData("amazondeals", TweetData.amazondeals) 53 | private val cnetTweets = TweetReader.ParseTweets.getTweetData("CNET", TweetData.CNET) 54 | private val gadgetlabTweets = TweetReader.ParseTweets.getTweetData("gadgetlab", TweetData.gadgetlab) 55 | private val mashableTweets = TweetReader.ParseTweets.getTweetData("mashable", TweetData.mashable) 56 | 57 | private val sources = List(gizmodoTweets, techCrunchTweets, engadgetTweets, amazondealsTweets, cnetTweets, gadgetlabTweets, mashableTweets) 58 | 59 | val tweetMap: Map[String, List[Tweet]] = 60 | Map() ++ Seq((sites(0) -> gizmodoTweets), 61 | (sites(1) -> techCrunchTweets), 62 | (sites(2) -> engadgetTweets), 63 | (sites(3) -> amazondealsTweets), 64 | (sites(4) -> cnetTweets), 65 | (sites(5) -> gadgetlabTweets), 66 | (sites(6) -> mashableTweets)) 67 | 68 | val tweetSets: List[TweetSet] = sources.map(tweets => toTweetSet(tweets)) 69 | 70 | private val siteTweetSetMap: Map[String, TweetSet] = 71 | Map() ++ (sites zip tweetSets) 72 | 73 | private def unionOfAllTweetSets(curSets: List[TweetSet], acc: TweetSet): TweetSet = 74 | if (curSets.isEmpty) acc 75 | else unionOfAllTweetSets(curSets.tail, acc.union(curSets.head)) 76 | 77 | val allTweets: TweetSet = unionOfAllTweetSets(tweetSets, new Empty) 78 | } 79 | -------------------------------------------------------------------------------- /streams/src/main/scala/streams/Solver.scala: -------------------------------------------------------------------------------- 1 | package streams 2 | 3 | import common._ 4 | 5 | /** 6 | * This component implements the solver for the Bloxorz game 7 | */ 8 | trait Solver extends GameDef { 9 | 10 | /** 11 | * Returns `true` if the block `b` is at the final position 12 | */ 13 | def done(b: Block): Boolean = ??? 14 | 15 | /** 16 | * This function takes two arguments: the current block `b` and 17 | * a list of moves `history` that was required to reach the 18 | * position of `b`. 19 | * 20 | * The `head` element of the `history` list is the latest move 21 | * that was executed, i.e. the last move that was performed for 22 | * the block to end up at position `b`. 23 | * 24 | * The function returns a stream of pairs: the first element of 25 | * the each pair is a neighboring block, and the second element 26 | * is the augmented history of moves required to reach this block. 27 | * 28 | * It should only return valid neighbors, i.e. block positions 29 | * that are inside the terrain. 30 | */ 31 | def neighborsWithHistory(b: Block, history: List[Move]): Stream[(Block, List[Move])] = ??? 32 | 33 | /** 34 | * This function returns the list of neighbors without the block 35 | * positions that have already been explored. We will use it to 36 | * make sure that we don't explore circular paths. 37 | */ 38 | def newNeighborsOnly(neighbors: Stream[(Block, List[Move])], 39 | explored: Set[Block]): Stream[(Block, List[Move])] = ??? 40 | 41 | /** 42 | * The function `from` returns the stream of all possible paths 43 | * that can be followed, starting at the `head` of the `initial` 44 | * stream. 45 | * 46 | * The blocks in the stream `initial` are sorted by ascending path 47 | * length: the block positions with the shortest paths (length of 48 | * move list) are at the head of the stream. 49 | * 50 | * The parameter `explored` is a set of block positions that have 51 | * been visited before, on the path to any of the blocks in the 52 | * stream `initial`. When search reaches a block that has already 53 | * been explored before, that position should not be included a 54 | * second time to avoid cycles. 55 | * 56 | * The resulting stream should be sorted by ascending path length, 57 | * i.e. the block positions that can be reached with the fewest 58 | * amount of moves should appear first in the stream. 59 | * 60 | * Note: the solution should not look at or compare the lengths 61 | * of different paths - the implementation should naturally 62 | * construct the correctly sorted stream. 63 | */ 64 | def from(initial: Stream[(Block, List[Move])], 65 | explored: Set[Block]): Stream[(Block, List[Move])] = ??? 66 | 67 | /** 68 | * The stream of all paths that begin at the starting block. 69 | */ 70 | lazy val pathsFromStart: Stream[(Block, List[Move])] = ??? 71 | 72 | /** 73 | * Returns a stream of all possible pairs of the goal block along 74 | * with the history how it was reached. 75 | */ 76 | lazy val pathsToGoal: Stream[(Block, List[Move])] = ??? 77 | 78 | /** 79 | * The (or one of the) shortest sequence(s) of moves to reach the 80 | * goal. If the goal cannot be reached, the empty list is returned. 81 | * 82 | * Note: the `head` element of the returned list should represent 83 | * the first move that the player should perform from the starting 84 | * position. 85 | */ 86 | lazy val solution: List[Move] = ??? 87 | } 88 | -------------------------------------------------------------------------------- /suggestions/src/main/scala/suggestions/gui/WikipediaApi.scala: -------------------------------------------------------------------------------- 1 | package suggestions 2 | package gui 3 | 4 | import scala.language.postfixOps 5 | import scala.collection.mutable.ListBuffer 6 | import scala.collection.JavaConverters._ 7 | import scala.concurrent._ 8 | import scala.concurrent.duration._ 9 | import scala.concurrent.ExecutionContext.Implicits.global 10 | import scala.util.{ Try, Success, Failure } 11 | import rx.subscriptions.CompositeSubscription 12 | import rx.lang.scala.Observable 13 | import observablex._ 14 | import search._ 15 | 16 | trait WikipediaApi { 17 | 18 | /** Returns a `Future` with a list of possible completions for a search `term`. 19 | */ 20 | def wikipediaSuggestion(term: String): Future[List[String]] 21 | 22 | /** Returns a `Future` with the contents of the Wikipedia page for the given search `term`. 23 | */ 24 | def wikipediaPage(term: String): Future[String] 25 | 26 | /** Returns an `Observable` with a list of possible completions for a search `term`. 27 | */ 28 | def wikiSuggestResponseStream(term: String): Observable[List[String]] = ObservableEx(wikipediaSuggestion(term)).timedOut(1L) 29 | 30 | /** Returns an `Observable` with the contents of the Wikipedia page for the given search `term`. 31 | */ 32 | def wikiPageResponseStream(term: String): Observable[String] = ObservableEx(wikipediaPage(term)).timedOut(1L) 33 | 34 | implicit class StringObservableOps(obs: Observable[String]) { 35 | 36 | /** Given a stream of search terms, returns a stream of search terms with spaces replaced by underscores. 37 | * 38 | * E.g. `"erik", "erik meijer", "martin` should become `"erik", "erik_meijer", "martin"` 39 | */ 40 | def sanitized: Observable[String] = ??? 41 | 42 | } 43 | 44 | implicit class ObservableOps[T](obs: Observable[T]) { 45 | 46 | /** Given an observable that can possibly be completed with an error, returns a new observable 47 | * with the same values wrapped into `Success` and the potential error wrapped into `Failure`. 48 | * 49 | * E.g. `1, 2, 3, !Exception!` should become `Success(1), Success(2), Success(3), Failure(Exception), !TerminateStream!` 50 | */ 51 | def recovered: Observable[Try[T]] = ??? 52 | 53 | /** Emits the events from the `obs` observable, until `totalSec` seconds have elapsed. 54 | * 55 | * After `totalSec` seconds, if `obs` is not yet completed, the result observable becomes completed. 56 | * 57 | * Note: uses the existing combinators on observables. 58 | */ 59 | def timedOut(totalSec: Long): Observable[T] = ??? 60 | 61 | /** Given a stream of events `obs` and a method `requestMethod` to map a request `T` into 62 | * a stream of responses `S`, returns a stream of all the responses wrapped into a `Try`. 63 | * The elements of the response stream should reflect the order of their corresponding events in `obs`. 64 | * 65 | * E.g. given a request stream: 66 | * 67 | * 1, 2, 3, 4, 5 68 | * 69 | * And a request method: 70 | * 71 | * num => if (num != 4) Observable.just(num) else Observable.error(new Exception) 72 | * 73 | * We should, for example, get: 74 | * 75 | * Success(1), Success(2), Success(3), Failure(new Exception), Success(5) 76 | * 77 | * 78 | * Similarly: 79 | * 80 | * Observable(1, 2, 3).concatRecovered(num => Observable(num, num, num)) 81 | * 82 | * should return: 83 | * 84 | * Observable(Success(1), Succeess(1), Succeess(1), Succeess(2), Succeess(2), Succeess(2), Succeess(3), Succeess(3), Succeess(3)) 85 | */ 86 | def concatRecovered[S](requestMethod: T => Observable[S]): Observable[Try[S]] = ??? 87 | 88 | } 89 | 90 | } 91 | 92 | -------------------------------------------------------------------------------- /nodescala/src/test/scala/nodescala/tests.scala: -------------------------------------------------------------------------------- 1 | package nodescala 2 | 3 | import scala.language.postfixOps 4 | import scala.util.{Try, Success, Failure} 5 | import scala.collection._ 6 | import scala.concurrent._ 7 | import ExecutionContext.Implicits.global 8 | import scala.concurrent.duration._ 9 | import scala.async.Async.{async, await} 10 | import org.scalatest._ 11 | import NodeScala._ 12 | import org.junit.runner.RunWith 13 | import org.scalatest.junit.JUnitRunner 14 | 15 | @RunWith(classOf[JUnitRunner]) 16 | class NodeScalaSuite extends FunSuite { 17 | 18 | test("A Future should always be completed") { 19 | val always = Future.always(517) 20 | 21 | assert(Await.result(always, 0 nanos) == 517) 22 | } 23 | test("A Future should never be completed") { 24 | val never = Future.never[Int] 25 | 26 | try { 27 | Await.result(never, 1 second) 28 | assert(false) 29 | } catch { 30 | case t: TimeoutException => // ok! 31 | } 32 | } 33 | 34 | 35 | 36 | class DummyExchange(val request: Request) extends Exchange { 37 | @volatile var response = "" 38 | val loaded = Promise[String]() 39 | def write(s: String) { 40 | response += s 41 | } 42 | def close() { 43 | loaded.success(response) 44 | } 45 | } 46 | 47 | class DummyListener(val port: Int, val relativePath: String) extends NodeScala.Listener { 48 | self => 49 | 50 | @volatile private var started = false 51 | var handler: Exchange => Unit = null 52 | 53 | def createContext(h: Exchange => Unit) = this.synchronized { 54 | assert(started, "is server started?") 55 | handler = h 56 | } 57 | 58 | def removeContext() = this.synchronized { 59 | assert(started, "is server started?") 60 | handler = null 61 | } 62 | 63 | def start() = self.synchronized { 64 | started = true 65 | new Subscription { 66 | def unsubscribe() = self.synchronized { 67 | started = false 68 | } 69 | } 70 | } 71 | 72 | def emit(req: Request) = { 73 | val exchange = new DummyExchange(req) 74 | if (handler != null) handler(exchange) 75 | exchange 76 | } 77 | } 78 | 79 | class DummyServer(val port: Int) extends NodeScala { 80 | self => 81 | val listeners = mutable.Map[String, DummyListener]() 82 | 83 | def createListener(relativePath: String) = { 84 | val l = new DummyListener(port, relativePath) 85 | listeners(relativePath) = l 86 | l 87 | } 88 | 89 | def emit(relativePath: String, req: Request) = this.synchronized { 90 | val l = listeners(relativePath) 91 | l.emit(req) 92 | } 93 | } 94 | test("Server should serve requests") { 95 | val dummy = new DummyServer(8191) 96 | val dummySubscription = dummy.start("/testDir") { 97 | request => for (kv <- request.iterator) yield (kv + "\n").toString 98 | } 99 | 100 | // wait until server is really installed 101 | Thread.sleep(500) 102 | 103 | def test(req: Request) { 104 | val webpage = dummy.emit("/testDir", req) 105 | val content = Await.result(webpage.loaded.future, 1 second) 106 | val expected = (for (kv <- req.iterator) yield (kv + "\n").toString).mkString 107 | assert(content == expected, s"'$content' vs. '$expected'") 108 | } 109 | 110 | test(immutable.Map("StrangeRequest" -> List("Does it work?"))) 111 | test(immutable.Map("StrangeRequest" -> List("It works!"))) 112 | test(immutable.Map("WorksForThree" -> List("Always works. Trust me."))) 113 | 114 | dummySubscription.unsubscribe() 115 | } 116 | 117 | } 118 | 119 | 120 | 121 | 122 | -------------------------------------------------------------------------------- /funsets/src/test/scala/funsets/FunSetSuite.scala: -------------------------------------------------------------------------------- 1 | package funsets 2 | 3 | import org.scalatest.FunSuite 4 | 5 | import org.junit.runner.RunWith 6 | import org.scalatest.junit.JUnitRunner 7 | 8 | /** 9 | * This class is a test suite for the methods in object FunSets. To run 10 | * the test suite, you can either: 11 | * - run the "test" command in the SBT console 12 | * - right-click the file in eclipse and chose "Run As" - "JUnit Test" 13 | */ 14 | @RunWith(classOf[JUnitRunner]) 15 | class FunSetSuite extends FunSuite { 16 | 17 | 18 | /** 19 | * Link to the scaladoc - very clear and detailed tutorial of FunSuite 20 | * 21 | * http://doc.scalatest.org/1.9.1/index.html#org.scalatest.FunSuite 22 | * 23 | * Operators 24 | * - test 25 | * - ignore 26 | * - pending 27 | */ 28 | 29 | /** 30 | * Tests are written using the "test" operator and the "assert" method. 31 | */ 32 | test("string take") { 33 | val message = "hello, world" 34 | assert(message.take(5) == "hello") 35 | } 36 | 37 | /** 38 | * For ScalaTest tests, there exists a special equality operator "===" that 39 | * can be used inside "assert". If the assertion fails, the two values will 40 | * be printed in the error message. Otherwise, when using "==", the test 41 | * error message will only say "assertion failed", without showing the values. 42 | * 43 | * Try it out! Change the values so that the assertion fails, and look at the 44 | * error message. 45 | */ 46 | test("adding ints") { 47 | assert(1 + 2 === 3) 48 | } 49 | 50 | 51 | import FunSets._ 52 | 53 | test("contains is implemented") { 54 | assert(contains(x => true, 100)) 55 | } 56 | 57 | /** 58 | * When writing tests, one would often like to re-use certain values for multiple 59 | * tests. For instance, we would like to create an Int-set and have multiple test 60 | * about it. 61 | * 62 | * Instead of copy-pasting the code for creating the set into every test, we can 63 | * store it in the test class using a val: 64 | * 65 | * val s1 = singletonSet(1) 66 | * 67 | * However, what happens if the method "singletonSet" has a bug and crashes? Then 68 | * the test methods are not even executed, because creating an instance of the 69 | * test class fails! 70 | * 71 | * Therefore, we put the shared values into a separate trait (traits are like 72 | * abstract classes), and create an instance inside each test method. 73 | * 74 | */ 75 | 76 | trait TestSets { 77 | val s1 = singletonSet(1) 78 | val s2 = singletonSet(2) 79 | val s3 = singletonSet(3) 80 | } 81 | 82 | /** 83 | * This test is currently disabled (by using "ignore") because the method 84 | * "singletonSet" is not yet implemented and the test would fail. 85 | * 86 | * Once you finish your implementation of "singletonSet", exchange the 87 | * function "ignore" by "test". 88 | */ 89 | ignore("singletonSet(1) contains 1") { 90 | 91 | /** 92 | * We create a new instance of the "TestSets" trait, this gives us access 93 | * to the values "s1" to "s3". 94 | */ 95 | new TestSets { 96 | /** 97 | * The string argument of "assert" is a message that is printed in case 98 | * the test fails. This helps identifying which assertion failed. 99 | */ 100 | assert(contains(s1, 1), "Singleton") 101 | } 102 | } 103 | 104 | ignore("union contains all elements") { 105 | new TestSets { 106 | val s = union(s1, s2) 107 | assert(contains(s, 1), "Union 1") 108 | assert(contains(s, 2), "Union 2") 109 | assert(!contains(s, 3), "Union 3") 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /actorbintree/src/main/scala/actorbintree/BinaryTreeSet.scala: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2009-2013 Typesafe Inc. 3 | */ 4 | package actorbintree 5 | 6 | import akka.actor._ 7 | import scala.collection.immutable.Queue 8 | 9 | object BinaryTreeSet { 10 | 11 | trait Operation { 12 | def requester: ActorRef 13 | def id: Int 14 | def elem: Int 15 | } 16 | 17 | trait OperationReply { 18 | def id: Int 19 | } 20 | 21 | /** Request with identifier `id` to insert an element `elem` into the tree. 22 | * The actor at reference `requester` should be notified when this operation 23 | * is completed. 24 | */ 25 | case class Insert(requester: ActorRef, id: Int, elem: Int) extends Operation 26 | 27 | /** Request with identifier `id` to check whether an element `elem` is present 28 | * in the tree. The actor at reference `requester` should be notified when 29 | * this operation is completed. 30 | */ 31 | case class Contains(requester: ActorRef, id: Int, elem: Int) extends Operation 32 | 33 | /** Request with identifier `id` to remove the element `elem` from the tree. 34 | * The actor at reference `requester` should be notified when this operation 35 | * is completed. 36 | */ 37 | case class Remove(requester: ActorRef, id: Int, elem: Int) extends Operation 38 | 39 | /** Request to perform garbage collection*/ 40 | case object GC 41 | 42 | /** Holds the answer to the Contains request with identifier `id`. 43 | * `result` is true if and only if the element is present in the tree. 44 | */ 45 | case class ContainsResult(id: Int, result: Boolean) extends OperationReply 46 | 47 | /** Message to signal successful completion of an insert or remove operation. */ 48 | case class OperationFinished(id: Int) extends OperationReply 49 | 50 | } 51 | 52 | 53 | class BinaryTreeSet extends Actor { 54 | import BinaryTreeSet._ 55 | import BinaryTreeNode._ 56 | 57 | def createRoot: ActorRef = context.actorOf(BinaryTreeNode.props(0, initiallyRemoved = true)) 58 | 59 | var root = createRoot 60 | 61 | // optional 62 | var pendingQueue = Queue.empty[Operation] 63 | 64 | // optional 65 | def receive = normal 66 | 67 | // optional 68 | /** Accepts `Operation` and `GC` messages. */ 69 | val normal: Receive = { case _ => ??? } 70 | 71 | // optional 72 | /** Handles messages while garbage collection is performed. 73 | * `newRoot` is the root of the new binary tree where we want to copy 74 | * all non-removed elements into. 75 | */ 76 | def garbageCollecting(newRoot: ActorRef): Receive = ??? 77 | 78 | } 79 | 80 | object BinaryTreeNode { 81 | trait Position 82 | 83 | case object Left extends Position 84 | case object Right extends Position 85 | 86 | case class CopyTo(treeNode: ActorRef) 87 | case object CopyFinished 88 | 89 | def props(elem: Int, initiallyRemoved: Boolean) = Props(classOf[BinaryTreeNode], elem, initiallyRemoved) 90 | } 91 | 92 | class BinaryTreeNode(val elem: Int, initiallyRemoved: Boolean) extends Actor { 93 | import BinaryTreeNode._ 94 | import BinaryTreeSet._ 95 | 96 | var subtrees = Map[Position, ActorRef]() 97 | var removed = initiallyRemoved 98 | 99 | // optional 100 | def receive = normal 101 | 102 | // optional 103 | /** Handles `Operation` messages and `CopyTo` requests. */ 104 | val normal: Receive = { case _ => ??? } 105 | 106 | // optional 107 | /** `expected` is the set of ActorRefs whose replies we are waiting for, 108 | * `insertConfirmed` tracks whether the copy of this node to the new tree has been confirmed. 109 | */ 110 | def copying(expected: Set[ActorRef], insertConfirmed: Boolean): Receive = ??? 111 | 112 | 113 | } 114 | -------------------------------------------------------------------------------- /quickcheck/src/main/scala/quickcheck/Heap.scala: -------------------------------------------------------------------------------- 1 | package quickcheck 2 | 3 | import common._ 4 | 5 | trait IntHeap extends Heap { 6 | override type A = Int 7 | override def ord = scala.math.Ordering.Int 8 | } 9 | 10 | // http://www.brics.dk/RS/96/37/BRICS-RS-96-37.pdf 11 | 12 | // Figure 1, page 3 13 | trait Heap { 14 | type H // type of a heap 15 | type A // type of an element 16 | def ord: Ordering[A] // ordering on elements 17 | 18 | def empty: H // the empty heap 19 | def isEmpty(h: H): Boolean // whether the given heap h is empty 20 | 21 | def insert(x: A, h: H): H // the heap resulting from inserting x into h 22 | def meld(h1: H, h2: H): H // the heap resulting from merging h1 and h2 23 | 24 | def findMin(h: H): A // a minimum of the heap h 25 | def deleteMin(h: H): H // a heap resulting from deleting a minimum of h 26 | } 27 | 28 | // Figure 3, page 7 29 | trait BinomialHeap extends Heap { 30 | 31 | type Rank = Int 32 | case class Node(x: A, r: Rank, c: List[Node]) 33 | override type H = List[Node] 34 | 35 | protected def root(t: Node) = t.x 36 | protected def rank(t: Node) = t.r 37 | protected def link(t1: Node, t2: Node): Node = // t1.r==t2.r 38 | if (ord.lteq(t1.x,t2.x)) Node(t1.x, t1.r+1, t2::t1.c) else Node(t2.x, t2.r+1, t1::t2.c) 39 | protected def ins(t: Node, ts: H): H = ts match { 40 | case Nil => List(t) 41 | case tp::ts => // t.r<=tp.r 42 | if (t.r ts 51 | case (ts, Nil) => ts 52 | case (t1::ts1, t2::ts2) => 53 | if (t1.r throw new NoSuchElementException("min of empty heap") 60 | case t::Nil => root(t) 61 | case t::ts => 62 | val x = findMin(ts) 63 | if (ord.lteq(root(t),x)) root(t) else x 64 | } 65 | override def deleteMin(ts: H) = ts match { 66 | case Nil => throw new NoSuchElementException("delete min of empty heap") 67 | case t::ts => 68 | def getMin(t: Node, ts: H): (Node, H) = ts match { 69 | case Nil => (t, Nil) 70 | case tp::tsp => 71 | val (tq,tsq) = getMin(tp, tsp) 72 | if (ord.lteq(root(t),root(tq))) (t,ts) else (tq,t::tsq) 73 | } 74 | val (Node(_,_,c),tsq) = getMin(t, ts) 75 | meld(c.reverse, tsq) 76 | } 77 | } 78 | 79 | trait Bogus1BinomialHeap extends BinomialHeap { 80 | override def findMin(ts: H) = ts match { 81 | case Nil => throw new NoSuchElementException("min of empty heap") 82 | case t::ts => root(t) 83 | } 84 | } 85 | 86 | trait Bogus2BinomialHeap extends BinomialHeap { 87 | override protected def link(t1: Node, t2: Node): Node = // t1.r==t2.r 88 | if (!ord.lteq(t1.x,t2.x)) Node(t1.x, t1.r+1, t2::t1.c) else Node(t2.x, t2.r+1, t1::t2.c) 89 | } 90 | 91 | trait Bogus3BinomialHeap extends BinomialHeap { 92 | override protected def link(t1: Node, t2: Node): Node = // t1.r==t2.r 93 | if (ord.lteq(t1.x,t2.x)) Node(t1.x, t1.r+1, t1::t1.c) else Node(t2.x, t2.r+1, t2::t2.c) 94 | } 95 | 96 | trait Bogus4BinomialHeap extends BinomialHeap { 97 | override def deleteMin(ts: H) = ts match { 98 | case Nil => throw new NoSuchElementException("delete min of empty heap") 99 | case t::ts => meld(t.c.reverse, ts) 100 | } 101 | } 102 | 103 | trait Bogus5BinomialHeap extends BinomialHeap { 104 | override def meld(ts1: H, ts2: H) = ts1 match { 105 | case Nil => ts2 106 | case t1::ts1 => List(Node(t1.x, t1.r, ts1++ts2)) 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /suggestions/src/main/scala/suggestions/search/Search.scala: -------------------------------------------------------------------------------- 1 | package suggestions 2 | package search 3 | 4 | import org.json4s._ 5 | import scala.concurrent.{ ExecutionContext, Future, Promise } 6 | import ExecutionContext.Implicits.global 7 | import scala.language.postfixOps 8 | import scala.collection._ 9 | import scala.collection.JavaConverters._ 10 | import scala.util.Try 11 | import scala.async.Async._ 12 | 13 | import rx.lang.scala.Observable 14 | import observablex.{SchedulerEx, ObservableEx} 15 | import ObservableEx._ 16 | 17 | import dispatch._ 18 | import org.json4s.native._ 19 | import retrofit.http.{GET, Query} 20 | import retrofit.Callback 21 | import retrofit.client.Response 22 | import retrofit.{RetrofitError, Callback, RestAdapter} 23 | import com.google.gson.annotations.SerializedName 24 | 25 | object Search { 26 | 27 | /* implementation using Json */ 28 | 29 | implicit val formats = org.json4s.DefaultFormats 30 | 31 | def wikipediaSuggestionJson(term: String): Future[List[String]] = { 32 | async { 33 | log("querying: " + term) 34 | val search = "http://en.wikipedia.org/w/api.php?action=opensearch&format=json&limit=15&search=" 35 | val response = await { Http(url(search + term).OK(as.String)) } 36 | val json = JsonParser.parse(response) 37 | val words = json(1) 38 | words.extract[List[String]] 39 | } 40 | } 41 | 42 | def wikipediaPageJson(term: String): Future[String] = { 43 | async { 44 | val search = "http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text§ion=0&page=" 45 | val response = await { Http(url(search + term).OK(as.String)) } 46 | val json = JsonParser.parse(response) 47 | val text = for { 48 | JObject(child) <- json 49 | JField("parse", JObject(fields)) <- child 50 | JField("text", JObject(tfields)) <- fields 51 | JField("*", JString(text)) <- tfields 52 | } yield text 53 | text.head 54 | } 55 | } 56 | 57 | /* alternative implementation using Retrofit */ 58 | 59 | class Page { 60 | var parse: Content = _ 61 | } 62 | 63 | class Content { 64 | var title: String = _ 65 | var text: Text = _ 66 | } 67 | 68 | class Text { 69 | @SerializedName("*") 70 | var all: String = _ 71 | } 72 | 73 | trait WikipediaService { 74 | @GET("/w/api.php??action=opensearch&format=json&limit=15") 75 | def suggestions(@Query("search") term: String, callback: Callback[Array[AnyRef]]): Unit 76 | 77 | @GET("/w/api.php??action=parse&format=json&prop=text§ion=0") 78 | def page(@Query("page") term: String, callback: Callback[Page]): Unit 79 | } 80 | 81 | val restAdapter = new RestAdapter.Builder().setServer("http://en.wikipedia.org").build() 82 | 83 | val service = restAdapter.create(classOf[WikipediaService]) 84 | 85 | def callbackFuture[T]: (Callback[T], Future[T]) = { 86 | val p = Promise[T]() 87 | val cb = new Callback[T] { 88 | def success(t: T, response: Response) = { 89 | p success t 90 | } 91 | def failure(error: RetrofitError) = { 92 | p failure error 93 | } 94 | } 95 | 96 | (cb, p.future) 97 | } 98 | 99 | def wikipediaSuggestionRetrofit(term: String): Future[List[String]] = { 100 | async { 101 | val (cb, f) = callbackFuture[Array[AnyRef]] 102 | service.suggestions(term, cb) 103 | val result = await { f } 104 | val arraylist = result(1).asInstanceOf[java.util.List[String]] 105 | 106 | arraylist.asScala.toList 107 | } 108 | } 109 | 110 | def wikipediaPageRetrofit(term: String): Future[String] = { 111 | async { 112 | val (cb, f) = callbackFuture[Page] 113 | service.page(term, cb) 114 | val result = await { f } 115 | result.parse.text.all 116 | } 117 | } 118 | 119 | def wikipediaSuggestion(term: String): Future[List[String]] = wikipediaSuggestionRetrofit(term) 120 | 121 | def wikipediaPage(term: String): Future[String] = wikipediaPageRetrofit(term) 122 | 123 | } 124 | 125 | -------------------------------------------------------------------------------- /forcomp/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /funsets/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /objsets/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /patmat/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | --------------------------------------------------------------------------------