Using the State Machine Compiler with Python

Today I learned about a state machine compiler and code generator. It provides a small DSL that you can use to describe a state machine and the transitions between the states, which will be compiled to create a number of classes, and then all you have to do is provide the code for the actions. Here, actions, states, and transitions are defined terms that are described in the documentation for the smc tool.

All you need to do is download the source code from SourceForge here. The jar file you’re looking for is located in smc/bin/Smc.jar. I’ll walk through the example in the SMC documentation. Copy the following snippet and save it as Turnstile.sm

%class Turnstile
%package turnstile
%start MainMap::Locked
%map MainMap
%%
Locked
{
 coin Unlocked { unlock(); }
 passs nil { alarm(); }
}
Unlocked
{
 passs Locked { lock(); }
 coin nil { thankyou(); }
}
%%

Great. Now compile that state machine script as:

java -jar Smc.jar -python Turnstile.sm

This should produce a Turnstile_sm.py in your working directory.

VERY IMPORTANT: Put smc/lib/Python/statemap.py in your PYTHONPATH or your working directory, you’ll need to import it in the next snippet.

import Turnstile_sm

class Turnstile:
    def __init__(self):
        self._fsm = Turnstile_sm.Turnstile_sm(self)
    def alarm(self):
        print("Alarming!")
    def thankyou(self):
        print("Thanks!")
    def lock(self):
        print("Locked!")
    def unlock(self):
        print("Unlocked!")

if __name__ == '__main__':
    ts = Turnstile()
    ts._fsm.coin()
    ts._fsm.passs()

Why does “pass” have an extra “s”? Because pass is reserved in Python, and I couldn’t think of a better variable name. So this doesn’t do much besides print stuff out when different actions are triggered by changes in state, but it’s still pretty cool. For more motivation for state machines, read this Robert Martin article.

The Recursive Maze Problem, Part I

Earlier this year, when I was looking for work, I got the same recursive maze problem three interviews in a row. Recursion is cute and clever, but you generally want to use iterative solutions in production.

Usually, you get a string representation of the maze, something like:

ms = '''
S####
....#
#.###
....G
##..#
...##
#..##
'''

So then you need to parse that into a list of lists, which isn’t difficult:

def maze_string_to_list_of_lists(maze: str) -> []:
    rows = maze.split()
    new_maze = []
    for row in rows:
        new_row = [i for i in row]
        new_maze.append(new_row)
    return new_maze

Next, I like to write a function to return cells orthogonal to some cell location. This originally considered cells north, south, east, and west of a location, but then I limited it to just south and east, because this is recursive and we have to worry about the stack size in Python. (Because recursion is as stupid as it is clever.)

def orthogonals(row: int, col: int, row_limit: int, col_limit: int) -> []:
    result = []
    # check input
    if row < 0 or row >= row_limit:
        return result
    if col < 0 or col >= col_limit:
        return result
    # compute output
    s = [row+1, col]
    e = [row, col+1]
    # check computed output
    if s[0] < row_limit:
        result.append(s)
    if e[1] < col_limit:
        result.append(e)
    return result

Finally, the meat and potatoes. Yeah, so SOLN is a global variable that’s laying around, which is bad. You know what else is bad? Recursive maze solvers.

SOLN = []

def find_path(row: int, col: int, maze: list) -> bool:
    if maze[row][col] == 'G':
        SOLN.append([row, col])
        return True
    if maze[row][col] == '#':
        return False
    SOLN.append([row, col])
    orthos = orthogonals(row, col, len(maze), len(maze[0]))
    for ortho in orthos:
        if ortho in SOLN:
            pass
        if find_path(ortho[0], ortho[1], maze):
            return True
    SOLN.pop()
    return False

References:

  • (Recursion: Solving a Maze)[https://www.cs.bu.edu/teaching/alg/maze/]
  • (Backtracking: Rat in a Maze)[http://www.geeksforgeeks.org/backttracking-set-2-rat-in-a-maze/]

Getting CSRF to work with Rails and Angular

I had trouble posting to my Rails server from an Angular controller until I found this SO post. In /app/controllers/application_controller.rb I added the following code.

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  after_action :set_csrf_cookie_for_ng

  def set_csrf_cookie_for_ng
    cookies['XSRF-TOKEN'] = form_authenticity_token if protect_against_forgery?
  end

  protected

    # In Rails 4.2 and above
    def verified_request?
      super || valid_authenticity_token?(session, request.headers['X-XSRF-TOKEN'])
    end
end