Source code snippets (examples)

This is a list of Alvin Alexander's source code snippets (simple source code examples).

A Scalaz putStrLn “Hello, world” IO Monad example (Scalaz 7)

Without much discussion, here is some source code for a Scalaz 7 “Hello, world” example, using the Scalaz putStrLn function:

package scalaz_tests

import scalaz._
import effect._
import IO._

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

/**
 * from http://eed3si9n.com/learning-scalaz/IO+Monad.html
 * requires these in build.sbt:
 *
 *     libraryDependencies ++= Seq(
 *         "org.scalaz" %% "scalaz-core" % "7.1.3",
 *         "org.scalaz" %% "scalaz-effect" % "7.1.3"
 *     )
 *
 */
object ScalazHelloWorld extends App {

    val action1 = for {
         _ <- putStrLn("Hello, world!")
    } yield ()

    //println("me first")
    action1.unsafePerformIO
    
}

Regarding the source code, note that no printing happens until the unsafePerformIO function is called. That’s why I put the other println statement in there before that line. If you un-comment the println statement, you’ll see that it is printed first. Or, if you remove the unsafePerformIO function call, you’ll see that there is no output.

I left all the extra import statements in there because I want to see/know/remember where things like the putStrLn function come from. (It looks like putStrLn is defined as scalaz.effect.IO.putStrln in Scalaz 7.)

Note the comment about the Scala/SBT build.sbt file. You specifically need to import the scalaz-effect library for this example to work. (I assume that you need the core library as well, but I know that it won’t work without scalaz-effect.)

A second Scalaz putStrLn example

Okay, while I’m in the neighborhood, here’s a second Scalaz putStrLn example that also uses readLn:

object ScalazTest2 extends App {

    val whoAreYou = for {
        _ <- putStrLn("who are you?")
        name <- readLn
        _ <- putStrLn("hello " + name)
    } yield ()
    
    whoAreYou.unsafePerformIO

}

That example comes from this page.

(If you know Haskell, you know that this for loop looks like a Haskell do loop.)

How to configure Intellij IDEA to show Scala data types when you hover over a field

To configure Intellij IDEA to show Scala data types when you hover over a field, you have to go into the Intellij settings to enable this feature. (On Mac OS X you can also use the [Ctrl][Shift][P] keystroke when you’re on a field whose type you want to know/confirm.)

To enable this hover-over feature, follow these steps:

  • File > Other Settings > Default Settings ...
  • Go to “Languages & Frameworks” > Scala
  • Go to the Editor tab
  • Enable “Show type info on mouse hover after X ms”

After doing this and accepting your changes, you should see your field’s data type when you hover over it in the IDE.

This works with Intellij IDEA Version 15.x on Mac OS X.

I got pointed in the right direction on how to enable this feature from this slightly out of date blog post.

A Java method that converts seconds to minutes and seconds

If you happen to need something like this, here’s some source code for a Java method that converts seconds in time to a String formatted as minutes and seconds:

private static String convertSecondsToMinutesAndSeconds(int secondsInput) {
    int minutes = secondsInput / 60;
    int seconds = secondsInput % 60;
    return String.format("%02d:%02d", minutes, seconds);
}

Feel free to use that code as a pointer in the right direction of a solution to this problem, but if you don’t already see the problem(s) here, it may help to know that this is actually a really crappy method.

Years ago I would have written that method like that and not given it a second thought, but as a programmer you (hopefully) continue to get wiser, and especially with a lot of exposure to functional programming lately, I now see that as a poor method. The question is, do you know why? If you don’t, I encourage you to think about all of the problems with this method/function. As a hint, there is more than one problem with it.

Android - “Freemarker NoClassDefFoundError TextBlock” error message

I don’t remember the exact error message, but if you’re trying to use FreeMarker with Android and you get an error that says something like “Freemarker - NoClassDefFoundError TextBlock”, the root cause of the problem seems to be that FreeMarker uses the java.beans library under the hood, and the Android version of Java does not implement this. As a result, FreeMarker won’t work with Android, at least not without some modifications, as of January, 2016.

I wish I could give you more details, but I’ve moved on from FreeMarker, and I’m looking at other templating libraries for my Android application.

Android - How to view LogCat output from the command line

From time to time I have a problem with Android Studio where it won’t show the logcat output of an app I’m trying to debug. I haven’t been able to figure out why that is, so what I do instead is look at my logcat output from my command line.

As a short tip, if you want to see Android LogCat output from your command line, just run this adb command from your Unix/Linux command line:

adb logcat

When you're developing an Android app, it's a good idea to keep this command open and running in a separate window, though of course you can also see this output in the Eclipse or Android Studio LogCat view.

Note that this command may not work if you have multiple devices connected, such as an Android emulator and a physical Android device connected on a USB port. But if you have one or the other it seems to work just fine.

RPI FAQ: How can I see what services are configured to run at startup on a Raspberry Pi? (Raspbian)

To see which services are configured to run at startup on a Rasperry Pi (Raspian) — and also see their current startup status — issue this Linux service command:

sudo service --status-all

The service man page describes what this command does:

service --status-all runs all init scripts, in alphabetical order, with the status command

On my Raspberry Pi (RPI) that command produces a long list of output that looks like this:

[ ? ]  alsa-utils
[ - ]  bootlogs
[ ? ]  bootmisc.sh
[ ? ]  cgroup-bin
[ ? ]  checkfs.sh
[ ? ]  checkroot-bootclean.sh
[ - ]  checkroot.sh
[ - ]  console-setup
[ + ]  cron
[ + ]  dbus
[ ? ]  dphys-swapfile
[ ? ]  fake-hwclock
[ - ]  hostname.sh
[ ? ]  hwclock.sh

The symbols between the brackets are read like this:

  • + means the service is running
  • - means the service is not running
  • ? means the service does not allow status as a command

In a related note, the runlevel command shows the current “run level” of your system:

$ runlevel
N 2

That output shows that the system is running at Run Level 2. The /etc/inittab file shows the meaning of the run levels:

# Runlevel 0 is halt.
# Runlevel 1 is single-user.
# Runlevels 2-5 are multi-user.
# Runlevel 6 is reboot.

In summary, if you wanted to see which of your RPI/Linux services are currently running (or not running) I hope this is helpful. Please see the page I linked to for more information.

How to size (or resize) application windows in AppleScript

AppleScript FAQ: How can I size or resize an application window using AppleScript?

To resize an application window with AppleScript, use a command like this:

tell application "Safari"
    set bounds of front window to {300, 30, 1200, 900}
end tell

That command tells the Safari browser to have the following size and location properties:

  • x = 300
  • y = 30
  • width = 1200
  • height = 900

When using this command, x and y correspond to the desired location of the application window, and those values represent where you want the upper-left corner of the window to be located.

I just used that code in a little script, and I can confirm that it works properly.

How to run a multiline AppleScript script from a Unix shell script (osascript)

This little example shows the syntax of how to run some AppleScript/osascript from a Unix shell script on a Mac OS X system:

#!/bin/sh

osascript <<EOF
tell application "Safari"
  close window 1
end tell
EOF

Just put your AppleScript in between the EOF parts, save it to a file, make the file executable, and this gives you a nice way to run a multiline AppleScript script from a shell script.

Here’s another example of what this looks like:

#!/bin/sh

osascript <<EOF
tell application "Safari" to activate
tell application "Safari"
    set bounds of front window to {300, 30, 1600, 1100}
end tell
EOF

How to close a Mac OS X app from a shell script (or command line)

If you ever need to close a Mac OS X application (gracefully) from the Mac Terminal command line or from a shell script, I can confirm that this command works:

osascript -e 'quit app "Safari"'

I use that command from a Mac/Unix shell script to close the Safari browser in an automation script I’m writing, and it works fine. Just replace Safari in that command with the name of the application you want to close.

A Scala shell script to move your mouse cursor

I’m currently trying to automate a GUI task, and as a part of that, one thing I need to do is move the mouse cursor.

In short, the solution I came up with was to write a Scala shell script that uses the Java Robot class to move the mouse. Here’s the source code for my script, which I named MoveMouse.sh:

#!/bin/sh
exec scala -savecompiled "$0" "$@"
!#

import java.awt.Robot

if (args.length != 2) {
    Console.err.println("Usage: MoveMouse x y")
    System.exit(1)
}

val x = args(0).toInt
val y = args(1).toInt

val robot = new Robot
robot.mouseMove(x, y)

You run the script like this:

$ MoveMouse.sh 5 10

That moves your mouse cursor to a position where the x-coordinate is 5 and the y-coordinate is 10. This is in the upper-left corner of your display. (I could be nicer and move the mouse with a little animation, but I won’t be watching the screen as the automation task runs, so with this script the mouse just jumps to the location you specify.)

I almost always work on Mac OS X systems, but I couldn’t find a way to do this with AppleScript, so I wrote this little shell script to solve the problem.