Scala, Java, Unix, MacOS tutorials (page 155)

For some reason or another today I was curious about this question: If you flipped a coin ten times, what are the odds that the coin would come up heads ten times, or tails ten times)?

I'm sure there is a way to determine this statistically, but I don't know how to do that, so, being new to Ruby, I wrote a little Ruby simulation program — essentially a Monte Carlo simulation of the problem — to find the answer. (Pretty boring, I know, but hey, I was bored, interested in learning Ruby, and didn't feel like reading any more of The Stand right now.)

“I touch the future – I teach.”

Christa McAuliffe

Wow, so a local sports news guy named Mike Klis tweeted, “Don’t confirm to Nicki,” then deleted that tweet and wrote this tweet, confirming that he meant to write that as a DM but made it a tweet instead, thereby shooting himself in the foot twice.

Don't confirm to Nick tweet

I don’t know how my father was raised, but at times he could be domineering, mean, and negative. That has created a “cause and effect” karmic ripple that continues to influence people generations later, and long after his death.

(To be clear, he wasn’t all bad.)

Duck looks surprisingly calm after what appears to be a rough landing.

Duck has a rough landing

westword.com has this great interview with Alfred Williams. He’s a former football player who played at the University of Colorado, and then played for the Broncos at the end of his career, helping them win two Super Bowls. These days he’s on the radio, and he’s great to listen to in the afternoon. He seems like a really nice guy, and I’ve wondered how he gets along with his radio partner, who occasionally doesn’t seem like a nice guy, and the article touches on that.

A corn farm in Spring Grove, Illinois created this nice tribute to the Chicago Cubs World Series win. From the article, “the maze is a full 28 acres of land with about 10 miles of trails.”

Corn field tribute to the Cubs

Eddie: How’s it going, man?

Tito: I’m okay.

Eddie: Yeah? Sure? ‘Cause you look like you got a little hitch in your giddyup.

From the movie, The Heartbreak Kid

(A friend said a similar thing to me recently.)

Because I think it’s often best to “learn by example,” I’ve become a connoisseur of SBT build.sbt examples, and this build.sbt file from Lihaoyi’s PPrint project demonstrates a lot of SBT variables:

val baseSettings = Seq(
    organization := "com.lihaoyi",
    name := "pprint",
    version := _root_.pprint.Constants.version,
    scalaVersion := "2.11.11",
    testFrameworks := Seq(new TestFramework("utest.runner.Framework")),
    publishTo := Some("releases"  at "https://oss.sonatype.org/service/local/staging/deploy/maven2"),
    crossScalaVersions := Seq("2.10.6", "2.11.11", "2.12.2"),
    scmInfo := Some(ScmInfo(
        browseUrl = url("https://github.com/lihaoyi/PPrint"),
        connection = "scm:git:git@github.com:lihaoyi/PPrint.git"
    )),
    homepage := Some(url("https://github.com/lihaoyi/PPrint")),
    licenses := Seq("MIT" -> url("http://www.opensource.org/licenses/mit-license.html")),
    developers += Developer(
        email = "haoyi.sg@gmail.com",
        id = "lihaoyi",
        name = "Li Haoyi",
        url = url("https://github.com/lihaoyi")
    )
)

baseSettings

lazy val pprint = crossProject.crossType(CrossType.Pure)
  .settings(
    baseSettings,
    scalacOptions ++= Seq(scalaBinaryVersion.value match {
      case x if x.startsWith("2.12") => "-target:jvm-1.8"
      case _ => "-target:jvm-1.7"
    }),
    libraryDependencies ++= Seq(
      "com.lihaoyi" %%% "fansi" % "0.2.4",
      "org.scala-lang" % "scala-reflect" % scalaVersion.value % Provided,
      "org.scala-lang" % "scala-compiler" % scalaVersion.value % Provided,
      "com.lihaoyi" %%% "sourcecode" % "0.1.3",
      "com.lihaoyi" %%% "utest" % "0.4.7" % Test,
      "com.chuusai" %%% "shapeless" % "2.3.2" % Test
    ),

    unmanagedSourceDirectories in Compile ++= {
      if (Set("2.11", "2.12", "2.13.0-M1").contains(scalaBinaryVersion.value))
        Seq(baseDirectory.value / ".." / "src" / "main" / "scala-2.10+")
      else
        Seq()
    } ,
    unmanagedSourceDirectories in Test ++= {
      if (Set("2.11", "2.12", "2.13.0-M1").contains(scalaBinaryVersion.value))
        Seq(baseDirectory.value / ".." / "src" / "test" / "scala-2.10+")
      else
        Seq()
    },
    sourceGenerators in Compile += Def.task {
      val dir = (sourceManaged in Compile).value
      val file = dir/"pprint"/"TPrintGen.scala"

      val typeGen = for(i <- 2 to 22) yield {
        val ts = (1 to i).map("T" + _).mkString(", ")
        val tsBounded = (1 to i).map("T" + _ + ": Type").mkString(", ")
        val tsGet = (1 to i).map("get[T" + _ + "](cfg)").mkString(" + \", \" + ")
        s"""
          implicit def F${i}TPrint[$tsBounded, R: Type] = make[($ts) => R](cfg =>
            "(" + $tsGet + ") => " + get[R](cfg)
          )
          implicit def T${i}TPrint[$tsBounded] = make[($ts)](cfg =>
            "(" + $tsGet + ")"
          )
        """
      }
      val output = s"""
        package pprint
        trait TPrintGen[Type[_], Cfg]{
          def make[T](f: Cfg => String): Type[T]
          def get[T: Type](cfg: Cfg): String
          implicit def F0TPrint[R: Type] = make[() => R](cfg => "() => " + get[R](cfg))
          implicit def F1TPrint[T1: Type, R: Type] = {
            make[T1 => R](cfg => get[T1](cfg) + " => " + get[R](cfg))
          }
          ${typeGen.mkString("\n")}
        }
      """.stripMargin
      IO.write(file, output)
      Seq(file)
    }.taskValue
  )

lazy val pprintJVM = pprint.jvm
lazy val pprintJS = pprint.js

lazy val readme = scalatex.ScalatexReadme(
    projectId = "readme",
    wd = file(""),
    url = "https://github.com/lihaoyi/pprint/tree/master",
    source = "Readme"
).settings(
    scalaVersion := "2.11.8",
    (unmanagedSources in Compile) += baseDirectory.value/".."/"project"/"Constants.scala"
)

Using a sonatype library with SBT

That build.sbt file includes so many variables/settings that I’m not going to try to name them all, but one thing to note is that he publishes his project to sonatype.org. If you want to use PPrint in your own SBT project, that means that you’ll need to include this line in your own build.sbt file:

resolvers += "Sonatype OSS Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots"

That tells SBT to use that URL as another repository it should look in for dependencies you’re trying to include in your project.

August 31st is a new anniversary for me: One year ago today I hit rock-bottom health-wise. On that day, despite feeling very sick, I needed groceries and went to the store. By the time I got to the milk section I was shaking quite a bit, and when I tried to pick up a half-gallon of milk, I didn’t have the hand strength to hold onto it, and it fell to the floor. It exploded open and soaked my lower legs and feet.

After a few moments of humiliation, I thought I better find a store employee so they could clean it up. As I walked around trying to find someone, tears were welling up in my eyes because I was so upset about my health; I couldn’t even grip a half-gallon of milk. I finally found someone, a young, healthy man — healthy, like I used to be — and when we got back to the milk section he nicely said, “No worries, don’t cry over spilled milk.” That made me want to cry even more.

When I was laying in bed later that afternoon (because that was all I could do by that time), I started doing research on my phone, and made a decision to stop taking a medication a kidney specialist started me on in February. Stopping that medicine made me even sicker in some ways, but that turned out to be a good thing: It became the final clue that I have Mast Cell Activation Syndrome. These days, other than significant dietary restrictions, I live a relatively normal life.

The comical part of my recent surgery was that my iPhone 5S kept dying, both before and after the surgery. Something is going on where the iPhone completely loses reception, and the only way to fix it — the only hope of fixing it — is to completely restore the phone using a secret handshake technique they taught me at the local Apple Store. (They also told me this technique only works about 10% of the time, and kindly suggested I buy a new iPhone because the 5S is almost four years old.)

Before the surgery the phone was completely dead for 2+ days, so I was driving around like Jim Rockford, borrowing other people’s phones and getting in touch with people in person. I had to talk to my surgeon, two groups at the hospital, a caregiver service, etc.

Skipping past that ... I decided to give an Android phone a chance, so I bought a relatively cheap Moto E phone, pictured here next to the dying iPhone 5S. I’ll get the Moto activated tomorrow, and I hope to give it at least a month. I’ve used Android tablets for years, but this is my first Android phone.

iPhone 5S next to a Moto E

I’m just catching up on my email backlog, and want to thank everyone for the well wishes. I’m now ~95% recovered from Surgery #6 (which was also Invasive Procedure #11), and back to full-time work.

[toc]

As a quick example of how to use a Thread with a basic Handler in an Android application, the following code creates a view where the text in the TextView is updated to show the current date and time when the Button is tapped.

Java source code

First, here’s the Java source code for a file class named ThreadHandlerActivity:

“It’s okay, I know you’re scared. Okay, just don’t be scared. Just don’t fight it, okay?”

From the excellent movie, Thunderheart

This is a quote from The Mastocytosis Society on their Facebook page. The interesting part for me is that I had almost all of these symptoms for many years, but my doctors and I didn’t know there was a disease/illness known as MCAS:

“We agree that some patients, in the early stages, manage their disease by avoiding triggers. An example would be someone who figures out that they cannot use a hand mixer because their hand and arm itches, so they use a stand mixer instead. They may not realize that this is a symptom of mast cell activation in response to vibration, but may simply avoid hand mixers. There are probably lots of people who do this for a long time until they develop multiple symptoms that affect many organ systems, such as chronic itching, dermatographism, diarrhea, abdominal bloating, reflux, headaches, lightheadedness, brain fog, skin rashes, intolerance to heat, cold, or temperature change, shortness of breath, severe reactions to bee/wasp/other venom stings, sensitivity to odors or chemical smells, reactions to medications, especially antibiotics and opioids, anxiety/depression and inability to tolerate alcohol.”

This is a list of Android code examples I’m starting to allow me to create rapid prototypes of Android applications using Android Studio. This is a very early list, I hope to be adding many more Android code snippets over time.

Jonas Bonér has put together a list of “latency numbers every programmer should know” as this gist. Peter Norvig put together a much earlier version of this list, and this berkeley.edu page has a bit of a graphic related to Norvig’s work.

Latency numbers programmers should know

If you’re interested in Android performance benchmarks, AndroidBenchmark.net seems to have some simple charts, like the image shown.

Android CPU performance benchmarks

August 27, 2017: My old cellphone (an iPhone) just died a tragic death, so I’ve been looking at cellphones, and also cellular carriers. Skipping the cellphone part of the story, cellular reception in Colorado is notoriously bad. I can barely make a phone call with AT&T in my apartment in Broomfield, CO, and I also have problems when I travel around nearby Louisville and Boulder.

AT&T coverage in Colorado (map)

Today I finally found a good map to show the problem at OpenSignal.com. This first image shows their cellular coverage map for AT&T in my area:

ATT cellular coverage in Broomfield, Colorado

As a little note today, in Scala 2 you can declare a type alias. Typically you do this to create a simple alias for a more complex type, as you’ll see in the examples below.

Scala 3 Update: Scala 3 also has opaque types, which we wrote about here on the docs.scala-lang.org website.