Source code snippets (examples)

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

A Unix/Linux 'cat' function in Scala

As a quick note today, the following Scala function is more or less the same as the Unix cat command:

package iotests

object Cat extends App {
    import HIO.using

     * `getLines` returns an iterator who returns lines (NOT including newline character(s)).
     * It will treat any of \r\n, \r, or \n as a line separator (longest match).
     * If you need more refined behavior you can subclass Source#LineIterator directly.
    def cat(filename: String) = using(Source.fromFile(filename)) { source => {
        for (line <- source.getLines) println(line)


This function can be made better in a variety of ways. For instance, it’s not a pure function. It could also have some error-handling to make sure the file exists. But if the file exists it should work fine. It should work on large files because it only uses an iterator, meaning that it shouldn’t be reading more than one line of the file in at a time.

Note that this code uses the `using` function that I describe in this blog post.

FWIW, I wrote this as a test while exploring some other code, and at some point I’ll share that other code.

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
 * 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")

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 ()


That example comes from this page.

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

Scala "timer" shell script (plays a sound file after x minutes)

This short article shows how to write a command-line timer in Scala. There are simple ways to do this as just a regular Unix/Linux shell script, but I wanted to use Scala, in part so I could try to remember how to use the Java sound libraries. (I also initially thought about writing this is a GUI app, but decided to just make it a command-line app.)

I wanted a simple command-line timer, so I wrote one in Scala.


My Scala shell script plays a sound file after the number of minutes you specify. It also takes an optional decibal level, so a command to play a “gong” sound after 30 minutes is this:

$ timer 30

This command also says to play the gong sound file in 30 minutes, but to reduce the decibal level with the -20 value:

$ timer 30 -20

Note: I copied my timer script to my ~/bin directory, and that directory is in my Unix command line path, so I can run my timer script regardless of what directory I’m currently in.

Scala timer shell script source code

Without any introduction, here’s the source code for my Scala “timer” shell script:

exec scala -savecompiled "$0" "$@"

import javax.sound.sampled._

val oneMinute = 60*1000

// usage
if (args.length < 1) showUsageAndExit

// initialize the values from the user input
val minutesToWait = args(0).toInt
val gainControl = if (args.length==2) args(1).toInt else -20

println(s"Timer started. Wait time is $minutesToWait minutes.\n")

// wait the desired time
for (i <- 1 to minutesToWait) {
    println(s"time remaining: ${minutesToWait-i} ...")

// play the sound twice
for (i <- 1 to 2) {

def playSoundfile(f: String) {
    val audioInputStream = AudioSystem.getAudioInputStream(new
    val clip = AudioSystem.getClip
    val floatGainControl = clip.getControl(FloatControl.Type.MASTER_GAIN).asInstanceOf[FloatControl]
    floatGainControl.setValue(gainControl)  //reduce volume by x decibels (like -10f or -20f)

def showUsageAndExit {
    Console.err.println("Usage: timer minutes-before-alarm <gain-control>")
    Console.err.println("       gain-control should be something like -10 or -20")

There’s nothing too special about the code, I just kicked it out pretty fast because I was tired of dealing with my kitchen timer. Because I always have a Mac Terminal window open I thought I’d do this from the command line instead of putting a GUI on it.

Note: If you have any problems with this script, it’s probably with the sound file you’re using. I don’t know all of the details, but I do know that the Java Sound API has a problem with some (many?) files, and it also won’t play MP3 files. I had a problem with an old “.au” sound file, and converted it to a WAV format, and that made it work.

How to install the Python pip command and feedparser library on Debian Linux (Raspberry Pi)

To install the Python pip command on Debian Linux, a Raspberry Pi in my case, use this command:

sudo apt-get install python-pip

That command works with Python 2. For Python 3 install information see this link.

Note: I used that command so I could install the Python feedparser libary with this pip command:

sudo pip install feedparser

A Python "RSS Feed Reader" script I use in my Radio Pi system

I just updated my Radio Pi “RSS Feed” script, and in short, here is the source code:


import feedparser
import time
from subprocess import check_output
import sys

#feed_name = 'TRIBUNE'
#url = ''

feed_name = sys.argv[1]
url = sys.argv[2]

db = '/var/www/radio/data/screensaver/feeds.db'
limit = 12 * 3600 * 1000

# function to get the current time
current_time_millis = lambda: int(round(time.time() * 1000))
current_timestamp = current_time_millis()

def post_is_in_db(title):
    with open(db, 'r') as database:
        for line in database:
            if title in line:
                return True
    return False

# return true if the title is in the database with a timestamp > limit
def post_is_in_db_with_old_timestamp(title):
    with open(db, 'r') as database:
        for line in database:
            if title in line:
                ts_as_string = line.split('|', 1)[1]
                ts = long(ts_as_string)
                if current_timestamp - ts > limit:
                    return True
    return False

def clean_string(string):
    return string.encode('utf-8').strip()

# get the feed data from the url
feed = feedparser.parse(url)

# figure out which posts to print
posts_to_print = []
posts_to_skip = []

for post in feed.entries:
    # if post is already in the database, skip it
    # TODO check the time
    title = clean_string(post.title)
    if post_is_in_db_with_old_timestamp(title):
# add all the posts we're going to print to the database with the current timestamp
# (but only if they're not already in there)
f = open(db, 'a')
for title in posts_to_print:
    title_cleaned = clean_string(title)
    if not post_is_in_db(title_cleaned):
        f.write(title_cleaned + "|" + str(current_timestamp) + "\n")
# output all of the new posts
count = 1
blockcount = 1
for title in posts_to_print:
    if count % 5 == 1:
        print("\n" + '((( ' + feed_name + ' - ' + str(blockcount) + ' )))')
        blockcount += 1
    title_cleaned = clean_string(title)
    print(title_cleaned + "\n")
    count += 1

ipAddr = check_output(["hostname", "-I"])
print "\n"
print '---------------------------------'
print 'IP Address: ' + ipAddr.strip()
print '---------------------------------'
print "\n"

When run from a crontab entry like this: NPR

this script produces output like this:

((( NPR - 1 )))

Putin Faces Frosty Reception At G20 In Australia

The Wondrous World Of Tom Thumb Weddings

Hong Kong Democracy Leaders Barred From Traveling To Beijing

Not My Job: Ron Perlman, Who Played The Beast, Gets Quizzed On Beauty

In NPR Interview, Bill Cosby Declines To Discuss Assault Allegations

((( NPR - 2 )))

The Good Listener: For Thanksgiving, Is There Music Everyone Can Agree On?

Fresh Air Weekend: Jon Stewart, Peter Mendelsund And A Review Of Bob Dylan

Gen. Dempsey Lands In Iraq As U.S. Presence Starts To Grow

IP Address:

That code and output depend on some database files, but if you know what my Radio Pi project is, the code will make a little more sense.

As one note, I get and print the IP address of the local system because the output from this script goes to a monitor on my Radio Pi system, and it’s often helpful to know the IP address of my Raspberry Pi, because I usually don't have a keyboard or mouse attached to it.

A Scala HTTP POST client example (like Java, uses Apache HttpClient)

I created this Scala class as a way to test an HTTP POST request to a web service. Although its written in Scala, it uses the Apache HttpClient Java libraries. I got the NameValuePair code from the URL I've linked to.

import org.apache.commons._
import org.apache.http._
import org.apache.http.client._
import org.apache.http.client.methods.HttpPost
import org.apache.http.impl.client.DefaultHttpClient
import java.util.ArrayList
import org.apache.http.message.BasicNameValuePair
import org.apache.http.client.entity.UrlEncodedFormEntity

object HttpPostTester {

  def main(args: Array[String]) {

    val url = "http://localhost:8080/posttest";

    val post = new HttpPost(url)

    val client = new DefaultHttpClient
    val params = client.getParams
    params.setParameter("foo", "bar")
    val nameValuePairs = new ArrayList[NameValuePair](1)
    nameValuePairs.add(new BasicNameValuePair("registrationid", "123456789"));
    nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
    post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    // send the post request
    val response = client.execute(post)
    println("--- HEADERS ---")
    response.getAllHeaders.foreach(arg => println(arg))


Again, the primary reason for creating this HTTP POST client test class is to test the HTTP REST POST listener on the other end. I create these headers, parameters, and name value pairs here, then make sure I can process them properly in my POST server class.

There is some additional HTTP POST "entity" processing at this Apache URL:

How to populate a static List (ArrayList, LinkedList) in Java (syntax)

Java FAQ: How do I initialize/populate a static List (ArrayList, LinkedList) in Java?

If you ever need to create a static List in Java (ArrayList, LinkedList), the following source code shows the correct Java syntax:

static final List<Integer> nums = new ArrayList<Integer>() {{

As you can guess, that code creates and populates a static List of integers. If your List needs to contain a different type, just change the Integer to whatever your desired type is, and of course change the add method calls accordingly.

Complete static list example

As a little summary, and for the sake of completeness, the following Java source code shows a complete working example that includes the previous static initialization example:

import java.util.ArrayList;
import java.util.List;

public class SumTest1 {

    static final List<Integer> nums = new ArrayList<Integer>() {{
    public static void main(String[] args) {
        int total = sum(nums);
        System.out.println("Sum: " + total);

    public static int sum(List<Integer> ints) {
        int sum = 0;
        for (int i : ints) {
            sum += i;
        return sum;


If you wanted to see the syntax required to create and populate a List (ArrayList, LinkedList) in Java, I hope this is helpful.

An example Haskell application (a pizza point of sales order system)

I’m currently trying to cram Haskell into my brain, and in an effort to do so, I’ve been writing a fake POS (point of sales) application. It has a command-line UI that prompts the user to add Pizzas and a Customer to an Order.

I need to re-organize the code, but this is what about 50% of the code looks like right now. The other 50% is in a module that defines what a Pizza is, and also defines its helper functions.

Example Haskell source code (pizza order entry system)

So, without further ado, here is some sample source code that represents what I know about Haskell so far:

import System.IO
import Pizza


-- TODO add breadsticks, soft drinks, etc.
data Order = Order { customer :: Customer
                   , pizzas  :: [Pizza]
                   } deriving (Show)

-- TODO expand the concept of a customer
data Customer = Customer { name :: String } deriving (Show)

createEmptyOrder :: Order
createEmptyOrder = Order {customer=(Customer "no name"), pizzas=[]}

addPizzaToOrder :: Order -> Pizza -> Order
addPizzaToOrder orderIn pizzaIn =
    -- return a new Order that has the new pizza in it
    Order {customer=(customer orderIn), pizzas=newPizzas}
    where oldPizzas = pizzas orderIn       -- get the pizzas from the incoming order
          newPizzas = pizzaIn : oldPizzas  -- add the new pizza to the old pizzas

-- TODO pass in a Customer here, not a String
-- TODO the `where` clause probably isn't needed here
addCustomerToOrder :: Order -> String -> Order
addCustomerToOrder orderIn customerNameIn =
    Order {customer=(Customer customerNameIn), pizzas=oldPizzas}
    where oldPizzas = pizzas orderIn

orderToString :: Order -> String
orderToString (Order {customer = c, pizzas = p}) =
    "Customer: " ++ (show c) ++ ", Pizzas: " ++ (show p)

printOrder :: Order -> IO ()
printOrder order = do putStrLn (orderToString order)

-- MAIN --

main = do
    putStrLn "\n--- MAIN ---"
    putStrLn "1 - New Order\nq - Quit"
    line <- getLine
    case line of
        "1" -> do let order = createEmptyOrder
                  finishedOrder <- buildOrder order
                  printOrder finishedOrder
        _   -> exit

-- buildOrder --

buildOrder :: Order -> IO Order
buildOrder orderIn = do
    putStrLn "\n--- BUILD ORDER ---"
    putStrLn "1 - New Pizza\n2 - Customer\nr - Return"
    line <- getLine
    case line of
        "1"  -> do let pizza = newPizza
                   let order = addPizzaToOrder orderIn pizza
                   putStrLn "(added a pizza to the order)"
                   buildOrder order  -- recursive
        "2"  -> do customerName <- newCustomer
                   let order = addCustomerToOrder orderIn customerName
                   putStrLn "(added a customer to the order)"
                   buildOrder order  -- recursive
        "r"  -> return orderIn
        _    -> return orderIn

-- TODO return a Customer here, not a String
newCustomer :: IO String
newCustomer = do
    putStrLn "Enter Customer Name: "
    line <- getLine
    return line

newPizza :: Pizza
newPizza = Pizza {crustSize=Medium, crustType=Thin, toppings=[Cheese]}

exit :: IO ()
exit = do putStrLn ("exited")

A big thing I am trying to do in this code is handle the concept of an “order,” and also add items in an Order instance. There may be better ways to do this, but the way I handle an order that I can add things to (and eventually remove things from) is to call the buildOrder function recursively.

The user interface (text menus)

FWIW, the two “menus” in the application look as follows. First, here’s the “main” menu:

--- MAIN ---
1 - New Order
q - Quit

Next, here’s the “build order” menu:

1 - New Pizza
2 - Customer
r - Return

If you add a Pizza and a Customer to the order and return to the main menu, you’ll see output like this:

Customer: Customer {name = "John Doe"}, Pizzas: [Pizza {crustSize = Medium, crustType = Thin, toppings = [Cheese]}]


I have no doubt that this Haskell code can be improved (probably dramatically, lol), especially the way I handle a new Customer, but as mentioned, it represents what I know today.

Haskell - How to extend a base type using data, value constructors, record syntax, and deriving

If you need to have multiple types extend a base type in Haskell, while using the data keyword, and while using Haskell’s record syntax, this approach seems to work:

data Product = Pizza { crustSize :: CrustSize
                     , crustType :: CrustType
                     , toppings  :: [Topping]
             | Breadsticks
             | SoftDrink
             deriving (Show)

Note that in addition to using the data keyword to define a type named Product and three value constructors (Pizza, Breadsticks, and SoftDrink) that have the same base type (Product), I also using the deriving keyword so my types will use the Show type class to print well.

To be clear:

  • The type I’m defining is named Product
  • The things on the right side of the = are value constructors
  • Pizza uses the Haskell record syntax
  • Pizza, Breadsticks, and SoftDrink are the different values the Product type can have
  • deriving (Show) is the thing that makes this things convert to strings nicely
  • indentation is important

In summary, if you wanted to see an example that showed all those things (data keyword, a new type, record syntax, multiple value constructors with the record syntax, and deriving, well, there you go.

How to define a Haskell function with no input parameters that returns an IO Something

I’m relatively new to Haskell, so I don’t know if there are better ways to do this, but if you need to define a function that takes no input parameters and returns a value, this function type signature works:

foo :: [Char]
foo = "foo"

I don’t know a good reason for using that specific approach, but I have found in test code that I want to do something with input/output, and so I needed a function that returned an IO String, but didn’t take any input parameters, and that function definition looks like this:

bar :: IO String
bar = return "bar"

Again, this probably shouldn’t be something that you need to do very often, but I have needed it several times in test code, and I can say that this function type declaration works.