Skip to content

Instantly share code, notes, and snippets.

View JoolsF's full-sized avatar

Julian Fenner JoolsF

  • London
View GitHub Profile
@JoolsF
JoolsF / pretty_print_with_fields.scala
Last active June 10, 2016 11:15
Pretty printer with fields and delimiter param
/**
* Iterates through fields and prints each one with its name and value
*
* Delimiter parameter seperates fields. Defaults to line seperator
*/
def toStringPrettyPrint(delimiter: String = "\n"): String = {
val fields = this.getClass.getDeclaredFields.foldLeft(new TreeMap[String,Any]) { (acc,field) =>
field.setAccessible(true)
acc + (field.getName -> field.get(this))
}
@JoolsF
JoolsF / basic_auth_akkahttp.scala
Last active June 10, 2016 11:15
Basic auth akka-http
//http://doc.akka.io/docs/akka/2.4.3/scala/http/routing-dsl/directives/security-directives/authenticateBasic.html
Object Routes {
path("basicauthtest"){
authenticateBasic(realm = "secure site", BasicAuthenticator.myUserPassAuthenticator) { user =>
complete {
HttpResponse(entity = HttpEntity("SUCCESS"))
}
}
}
@JoolsF
JoolsF / boolean_list.scala
Last active July 23, 2016 13:58
Testing boolean sequences with foldLeft
val truelist = List(true, true, true)
val falselist = List(false, false, false)
val trueFalseList = truelist ::: falselist
truelist.foldLeft(true){ (a,b) => a && b} //true
falselist.foldLeft(true){ (a,b) => a && b} //false
trueFalseList.foldLeft(true){ (a,b) => a && b} //false
//You could also write something like
truelist.forall(_== true) //true
@JoolsF
JoolsF / boolean_extractor.scala
Created July 23, 2016 13:57
Boolean extractor
/**
* A Boolean extractor
* Unapply method doesn't have to reside in companion object of the class for which it is applicable
*/
object premiumCandidate{
def unapply(user: FreeUser): Boolean = user.upgradeProbability > 0.75
}
def initiateSpamProgram(freeUser: FreeUser) = () //do something useful here
@JoolsF
JoolsF / apply_unapply.scala
Created July 23, 2016 14:15
UnapplySeq Example
/**
* For regular parameters / fixed arity these are the apply constructs and unapply de-structures:
*/
object S {
def apply(a: A):S = ... // makes a S from an A
def unapply(s: S): Option[A] = ... // retrieve the A from the S
}
val s = S(a)
s match { case S(a) => a }
@JoolsF
JoolsF / partial_func_example1.scala
Created July 23, 2016 14:38
Partial function example 1
/**
* Partial Functions
* When a function is only defined for a specific input.
*/
val between3and10: (String, Int) => Boolean = {case (_, num) => num >= 3 && num <= 10}
val wordFrequencies = ("habitual", 6) :: ("and", 56) :: ("consuetudinary", 2) ::
("additionally", 27) :: ("homely", 5) :: ("society", 13) :: Nil
wordFrequencies.filter{case (s,i) => between3and10(s,i) }.map(_._1) //res0: List[String] = List(habitual, homely)
@JoolsF
JoolsF / try_example1.scala
Created July 23, 2016 15:38
Try examples 1
import scala.util.Try
val r = new java.util.Random
def randomBoolean = r.nextInt(8) != 0
def stringOrException = if (randomBoolean) "Hello" else throw new RuntimeException
def stringOrException2(string: String) = if(randomBoolean) s"$string world" else throw new ArithmeticException()
def stringOrException3(string: String) = if(randomBoolean) s"$string human" else throw new NullPointerException
val getString: String = Try(stringOrException).getOrElse("There was a problem getting the string") // Hello
@JoolsF
JoolsF / either_example1.scala
Created July 24, 2016 13:53
Exception handling with Either 1
import scala.util.control.Exception._
val r = new java.util.Random
def randomBoolean(exceptionChance: Int) = r.nextInt(exceptionChance) == 0
def handling[Ex <: Throwable, T](exType: Class[Ex])(block: => T): Either[Ex, T] =
catching(exType).either(block).asInstanceOf[Either[Ex, T]]
def exceptionOrString = if(randomBoolean(4)) throw new RuntimeException("This is a runtime exception") else "Phew! You got a string"
@JoolsF
JoolsF / future_example1.scala
Created July 24, 2016 14:46
Future example 1
import scala.util.{Failure, Success}
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
/**
* Computation 1 depends on nothing
* Computation 1b depends on result of 1
* Computation 2 depends on nothing
*
* Computation 1b may thrown an exception
@JoolsF
JoolsF / akka_http_setup_basic.scala
Last active July 26, 2016 12:37
Akka HTTP basic setup
import akka.http.scaladsl.model.{HttpEntity, HttpResponse}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.Http
import akka.stream.ActorMaterializer
import akka.actor.ActorSystem
/**
* Basic akka http setup
* Test with
* curl localhost:9000/ping