juan_gandhi: (VP)
I just tried this code:

sealed trait Result[+T] {
...
  def <*>[U](other: Result[U]): Result[(T,U)]
...
}
case class Good[T](value:T) extends Result[T] {
...
  def <*>[U](other: Result[U]): Result[(T, U)] = other.flatMap(u => Good((value, u)))
...
}

case class Bad[T](errors:Traversable...) extends Result[T] {
...
  def <*>[U](other: Result[U]): Result[(T, U)] = Bad(errors ++ other.errors)
...
}

scala> val op = Good((1,"one"))
op: Good[(Int, String)] = Good((1,one))

scala> for ((i,s) <- op) println(s"i=$i, s=$s")
i=1, s=one


Why is this important?

See, if I have a class Result[T], and it is applicative, so Result[T] <*> Result[U] produces Result[(T,U)], I want to use the result, naming individual fields. Like in
  val username: Result[String] = getUserNameFromTheCloud(userId)
  val prize:  Result[Prize] = rollTheDice
  
  val letter:Result[(String, Prize)] = for ((u, p) <- username <*> prize) yield congratulate(u, p)
// etc


This is better than having
for(u <- username;
    p <- prize) yield congratulate(u,p)


because in the second case if username is bad, we will never know if prize is bad too; this way we detect only one error. Not so good for fast development. It's like what ancient compilers did.

Questions?
juan_gandhi: (VP)
    val claimsListSelector = "#claimsTable"
    val claimList = "_$$('"+claimsListSelector+" a')"
...
    val clicked = js(s"clickOn($claimList[$i])")


Here i is the row number, and claimList is a script chunk that builds an array of elements to click.
juan_gandhi: (VP)
val List(_, median, _) = List(a,b,c).sorted


(c) Naftoli Gugenheim
juan_gandhi: (VP)
"There is only one value of type Unit, (), and it is not represented by any object in the underlying runtime system."

code sample

May. 4th, 2014 05:55 pm
juan_gandhi: (VP)
I have to log in to a server, send a file, then log out.
What do people do in this case? Log in, check the result, keep the session id, use it to send a file, use the session id to log out in a finally block. I mean, that's what I did all my life.
Tired of it.

So I want to log in, create a session, then, inside the session, do my operation, and then "automatically" close it. So I log in, and then call "execute". But wait, what if I don't call it? The resource will hang around.

So what I did, I inverse it. I say client execute {operation} inSession(username, password). That's how it should be.
client.execute { 
  session => {
    val response = session.send(fileInfo)
    info(s"Attachment - $fileInfo sent: $response")
    response
  }
} inSession(username, password)


How does it work? Pretty easy:

  def execute[T](op:ApiSession => Result[T]) = new {
    def inSession(name:String, password:String): Result[T] = {
      login(name, password) flatMap { s =>
        try op(s) finally s.close
      }
    }
  }


where
case class ApiSession(private val id: String, private val client: APIclient) {
  def close() = client.get(s"logout?session=$id")
  def send(fileInfo: FileInfo) = fileInfo.send(client)(id)
}


Client here is an http client that does all this multipart paraphernalia.
What I wanted to say is: the order of parameters is meaningful, is not it?
And pretty neat, too.
juan_gandhi: (VP)
Looking in the direction of frp, I'm afraid.

See, you have, say, a test. The sut you are testing has some component injected, e.g.

val sut = new FileUploader {
override def userAgent = behaveDifferentlyOnDifferentOccasions
}

def behaveDifferentlyOnDifferentOccasions = ???


and you sure want to make this behaveDifferentlyOnDifferentOccasions depend on test cases, right? So, what options do you have?
- Introduce a variable, which you change? The thing is, Scala tests use to run in parallel unless told otherwise. -- Make sut a function?

Just asking. A good answer may be kind of disruptive, as they say here in the Bay Area.
juan_gandhi: (VP)
trait Mock {
  def whatever[T] = throw new UnsupportedOperationException
}
juan_gandhi: (VP)
I need a data structure which has a file as one of its components. I've been thinking, ok, I build this structure, like case class, but what if the data are actually not so good? Throwing an exception is stupid (and rather neurotic); so I probably need a factory that returns not a SingleBatch, but a Result[SingleBatch]. But the problem is, the validity of it may change with time. So, have to deal with it in terms of temporal (or topos) logic. Or frp maybe. See, now the data are good; a second later they can turn bad (but never go back... pretty toposophical!). So we deal not with data, but with a function. So all the methods must be returning Result[T]. Or maybe instead of returning anything just use cps... hard to tell.
juan_gandhi: (VP)
Just wrote a prototype for the tests I'm going to write
class EobHandling_Test extends Specification with MoreExpectations {
  val handler = new EobHandling with MockDB {
    override def pat_ins: Patient_ins = new MockPatientIns(42, Some(2))
  }

  "existsInDB" should {
    "say 'no' if eob id is missing" in {
    }
    "say 'no' if eob is not in db" in {
    }
    "say 'yes' if one such eob is in db" in {
    }
    "say 'yes' if more than one such eob is in db" in {
    }
  }
}
juan_gandhi: (VP)
It's recursive. An array inside a map inside a map, etc. You need a context-free grammar to parse it.
But this can be fixed. See how.

1. You can convert array into a map, right? s"[[$i]]" -> arrayValue(i)

So, generally speaking, can have just maps.

2. If we ban (or escape) dots ('.') inside keys, we can "flatten" the map of maps of maps, just by merging keys.

{"a" -> {
  "key1" -> {
    "[[0]]" -> "value at a.key1[0]"
...
    }
  }
}


will be
{"a.key1.[[0]]" -> "value at a.key1[0]"
 ...
}


3. We ban or escape quotes in keys, and html-escape quotes in values, s/"\""/"&quot;"/g, we can get rid of quotes in keys and have only delimiting quotes in values.

What does it give us? We get Regular Language. That easy.

What's the point of having a regular language? Tons of them.

- You can keep it in SQL and match using regular SQL statements.
- You can check or extract data in shell scripts.
- You can parse it efficiently in your code, no need for parsers/combinators.

P.S. And fuck Crockford, he's an ignorant asshole anyway.
juan_gandhi: (VP)
Was kind of way tired of checking whether this or that stuff works in a browser by running it in real-life code, really; and eventually stopped everything and wrote this code:
class Tools_js_Test extends Specification with BeforeAfterExample {
  val server = new WebServer(7777, "biteme" -> (() => "<html><body><h1>this is a test</h1></body>"))
  var browser:SeleniumBrowsingExec = _

  def before = {
    server.start
    browser = new SeleniumBrowsingExec(NoProps)
    browser.loadPage(page) must_== OK
  }

  def after = {
    server.stop
    browser.dispose()
  }
  val page = Url("http://localhost:7777/biteme")

  "Browser" should {
    "load library" in {
      browser.runJS(JavaScript.library)
      val loaded = browser.runJS("return window.OK")
      loaded must_== Good("OK")
    }
  }
}



What happens here: I launch a server I wrote (60 lines of Scala, in total, under the cut), and a Selenium browser, and I load the test page before the test, and in my test case, just one here, I run some JavaScript, and check that it works. Then in after method I close the server and the browser, and that's it.

Read more... )
juan_gandhi: (VP)
And can't figure out why I did not need it before

  type Outcome = Result[Any]

  object OK extends Good('OK) with Outcome

  def fold(results:Traversable[Outcome]):Outcome = ((OK:Outcome) /: results)(_<*>_) map (_ => 'OK)


What happens here. I have a type for a result which value I don't care about; any result can be an Outcome.
Now I have a sequence of outcomes; I need just one, OK if everything's ok, or a list of errors.

So there. I just fold results, using tensor product, aka merge, merging the whole sequence into just one value.

naming

Apr. 16th, 2014 03:40 pm
juan_gandhi: (VP)
This is my dream, give methods the names that pop up as soon as you need them.

I have my PropTree class; if in a tree top level keys are all indexes (of the form [[i]]), I wanted to scan them and map to a sequence of trees, one per index. So I wrote props.groupByIndex, and decided to write this method. And kaboom, turned out I already have the method, wrote it 2 months ago. Is not it cool. Like with my ex, who defined love as "just as I think about something, you already do it" (no shit, it sounds funny now, but...)
juan_gandhi: (VP)
Пока ехал, на заднем сиденье, от Помоны до Сан Хосе
Read more... )

парсит вот такую фигню типа

val parsedOpt = PropTree parse "fp(Map(Deductible.Limit.Out of Network.Member -> $4,000.00,  " +
        "Deductible.Accumulated.In Network.Member -> $0.00, " +
        "Deductible.Remaining Balance.In Network.Member -> $2,000.00,  " +
        "Deductible.Limit.In Network.Member -> $2,000.00,  " +
        "Deductible.Accumulated.Out of Network.Family -> $0.00, " +
        "Deductible.Accumulated.In Network.Family -> $249.00,  " +
        "Deductible.Accumulated.Out of Network.Member -> $0.00,  " +
        "Deductible.Limit.In Network.Family -> $4,000.00, " +
        "Deductible.Remaining Balance.In Network.Family -> $3,751.00,  " +
        "Deductible.Remaining Balance.Out of Network.Member -> $4,000.00,  " +
        "Deductible.Limit.Out of Network.Family -> $8,000.00, " +
        "Deductible.Remaining Balance.Out of Network.Family -> $8,000.00)) " +
        "with dictionary  " +
            "fp(Map(Individual -> Member, max -> Limit, OutOfNetwork -> Out of Network, InNetwork -> In Network, current -> Accumulated, OutOfPocket -> Out of Pocket)) " +
        "with reordering (3,4,2,1)"


Note spaces in keys, commas in values, and total lack of quotes.

What I could not figure out is how to convert an Option[T] into a function that applies on Some and does not on None.
juan_gandhi: (VP)
  implicit class BetterFile(f:File) {
    def extensionOpt:Option[String] = f.getName.split("\\.").toList match {
      case name::tail => tail.lastOption
      case Nil        => None
    }
    def withExtension(ext:String) =
      new File(f.getParentFile,
              extensionOpt.fold(f.getName + ".")(f.getName dropRight _.length) + ext
      )

    def extension = extensionOpt getOrElse ""
    def extension_=(ext:String) = {
      val g = this withExtension ext
      if (f renameTo g) g else f
    }
  }


test:
      val sut = new File("/tmp/test" + System.currentTimeMillis() + "etc.exe")
      "this is a test" #> sut
      sut.canRead must beTrue
      sut.extension must_== "exe"
      val renamed = sut.extension = "elf"
      renamed.canRead must beTrue
      renamed.getName.endsWith("etc.elf") must beTrue
      sut.exists() must beFalse
      using (renamed) (in => { "this is a test" forall (in.read == _) }) must_== Good(true)

Profile

juan_gandhi: (Default)
Juan-Carlos Gandhi

November 2025

S M T W T F S
       1
23456 7 8
9 1011 12 1314 15
16171819 20 2122
23 24 252627 28 29
30      

Syndicate

RSS Atom

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Nov. 30th, 2025 11:26 am
Powered by Dreamwidth Studios