Spoofing Nokia mobile on the Microbit

A silly little snippet you could use with the microbit and an external speaker to make someone think there’s an old Nokia mobile phone ringing somewhere in the room.


from microbit import *
import music

ringtone = [ 
    "e7:1", "d", "f#6", "g#",  
    "c#7:1", "b6", "d", "e",  
    "b", "a", "c#6", "e",  
    "a:4", "R:4"
] 

music.set_tempo(bpm=60)

for repeat in range(2):
  music.play(ringtone) 


Strangling Legacy Code

Wednesday, the 15th of August 2018 was our usual NE Bytes developer meetup, … except that it wasn’t because we had the wonderful Amitai Schleier over to visit to talk about mob programming and how to replace or enhance a legacy application without rewriting it, using the strangler pattern.

This was our first time running an event in a new venue - our home for the last four years, campus north, is closing it’s doors in September - and the Scott Logic offices provided us with a nice intimate atmosphere for gathering together to work on some code.

Amitai started off by introducing mob programming and the strangler pattern before moving onto the coding scenario and the code we, as a mob, were to build on. It’s fair to say we had a few technical challenges with connections, keyboards and mice but our newly formed mob coped with those problems, managed to make progress on new features in the code with Amitai’s guidance and gathered confidence as the evening proceeded. We swapped out drivers every 4 minutes which meant everyone who wanted to was able to experience driving for the navigator and the mob.

Here are a few photos from the night.

strangle

strangle

strangle

strangle

strangle

As a new mob, we were working in an unfamiliar IDE on unfamiliar code, in what was, for many a strange, new language and in front of lots of people who were relative strangers AND typing in front of strangers while standing up! The strength of Amitai’s approach - his facilitation and coaching skills - meant that none of this mattered. We were able to complete all of the features and have fun doing it. We would love to have Amitai back when he’s next within travelling distance of Newcastle.

Minecraft PortKey

What’s programming without an occasional Harry Potter/Minecraft mashup? In the Harry Potter universe, a Portkey is a magical teleportation device which is disguised as an ordinary, everyday object. Touch the object and it automatically teleports you to a matching location. How would we do this in Minecraft?


import mcpi.minecraft as minecraft
import mcpi.block as block
import random
import time

world = minecraft.Minecraft.create()

# place a portkey in a "random" place.
portkey_x = 0
portkey_z = 0
portkey_y = world.getHeight(portkey_x, portkey_z)

# clear some space around the port key
world.setBlocks(portkey_x - 10, portkey_y, portkey_z - 10, 
                portkey_x + 10, portkey_y + 10, portkey_z + 10, 
                block.AIR)

portkey_block = block.CHEST
world.setBlock(portkey_x, portkey_y, portkey_z, portkey_block)

destination_x = random.randint(-50, 50)
destination_z = random.randint(-50, 50)
destination_y = world.getHeight(destination_x, destination_z)

while True:
  playerTile = world.player.getTilePos()
  blockType = world.getBlock(playerTile.x, playerTile.y, playerTile.z)

  if blockType == portkey_block:
    world.postToChat("port key activated...")
    world.postToChat("hold on!")
    time.sleep(0.5)
    world.player.setPos(destination_x, destination_y + 5, destination_z)

  time.sleep(0.3)


The portkey is triggered if you stand on the object. The other way we could trigger it is by hitting the object and poll for the hits using the world.events.pollBlockHits() API.

Minecraft Forestry

We can build very simple trees programmatically in Minecraft by stacking blocks together using wood-y and leaf-y materials.

simple tree


import mcpi.minecraft as minecraft
import mcpi.block as block
import random
import time


def build_trunk(world, x, y, z, trunk_height, trunk_radius, trunk_material):
  if trunk_radius == 0:
    world.setBlocks(x, y, z, x + 1, y + trunk_height, z + 1, trunk_material)
  else:
    world.setBlocks(x - trunk_radius, 
                    y,
                    z - trunk_radius,
                    x + trunk_radius,
                    y + trunk_height,
                    z + trunk_radius, 
                    trunk_material)


def generate_leaves(world, x, y, z, leaf_height, leaf_radius, leaf_material):
  world.setBlocks(x - leaf_radius, 
                  y, 
                  z - leaf_radius, 
                  x + leaf_radius, 
                  y + leaf_height, 
                  z + leaf_radius, 
                  leaf_material)


# function to build a simple tree using the given materials
def build_tree(world, x, y, z, trunk_height=5, trunk_radius = 1, leaf_height=3, leaf_radius=4, trunk_material=block.WOOD, leaf_material=block.LEAVES):
  build_trunk(world, x, y, z, trunk_height, trunk_radius, trunk_material)
  generate_leaves(world, x, y + trunk_height, z, leaf_height, leaf_radius, leaf_material)


world = minecraft.Minecraft.create()

# clear out the space
world.setBlocks(-128, 0, -128, 128, 40, 128, block.AIR)
world.setBlocks(-128, 1, -128, 128,  2, 128, block.GRASS)

playerTile = world.player.getTilePos()

x = playerTile.x + 5
z = playerTile.z + 5
y = world.getHeight(x, z)

build_tree(world, x, y, z)


Square blocks of leaves aren’t very realistic so we can trim off the square edges like this.

better tree


def sand_off_corners(world, x1, y1, z1, x2, y2, z2):
  world.setBlock(x1, y1, z1, block.AIR)
  world.setBlock(x2, y1, z1, block.AIR)
  world.setBlock(x1, y1, z2, block.AIR)
  world.setBlock(x2, y1, z2, block.AIR)
  world.setBlock(x1, y2, z1, block.AIR)
  world.setBlock(x2, y2, z1, block.AIR)
  world.setBlock(x1, y2, z2, block.AIR)
  world.setBlock(x2, y2, z2, block.AIR)

def generate_leaves(world, x, y, z, leaf_height, leaf_radius, leaf_material):
  world.setBlocks(x - leaf_radius, 
                  y, 
                  z - leaf_radius, 
                  x + leaf_radius, 
                  y + leaf_height, 
                  z + leaf_radius, 
                  leaf_material)

  # knock out corners to make it slightly more realistic.
  sand_off_corners(world, x - leaf_radius, y, z - leaf_radius, x + leaf_radius, y + leaf_height, z + leaf_radius)



Finally, we can make ourselves a nice orchard or small forest using some random values for each tree:

forest of trees



for i in range(3):
  for j in range(2):
    tree_spacing = random.randint(8, 12)
    trunk_radius = random.randrange(1)
    trunk_height = random.randint(5, 20)
    leaf_height = random.randint(5, 15)
    leaf_radius = random.randint(trunk_radius * 4, trunk_radius * 10)
    
    build_tree(world, 
        x + (i * tree_spacing), 
        y,
        z + (j * tree_spacing), 
        trunk_height = trunk_height, 
        trunk_radius = trunk_radius, 
        leaf_height = leaf_height
        )


Note by using the ground value specific to each tree location, we can get a nice effect “planting” trees on a sloping hillside.

We can go further by changing the materials for each tree, the trunk and leaf materials, on a random basis. The setBlock function can take an extra argument for some block types. For wood and leaves, you are able to pick the exact kind of material you would like.

value Wood
0 Oak
1 Spruce
2 Birch
value Leaves
1 Oak
2 Spruce
3 Birch

In the final version, the foliage still looks a bit too false as a single monolithic block of leaves. We can change the leaf generation to work on a probability of a leaf block being at any one position in the canopy.



def generate_leaves(world, x, y, z, leaf_height, leaf_radius, leaf_material):

  leaf_probability = random.randint(30, 65)
  
  for i in range(x - leaf_radius, x + leaf_radius + 1):
    for j in range(y, y + leaf_height):
      for k in range(z - leaf_radius, z + leaf_radius + 1):
        if random.randrange(100) < leaf_probability:
          world.setBlock(i, j, k, leaf_material)
  
  sand_off_corners(world, x - leaf_radius, y, z - leaf_radius, x + leaf_radius, y + leaf_height, z + leaf_radius)


random leaves

Slow Down, Red Squirrels

Another in the continuing series of requests for slowness.

Someone clearly thought that the original sign was both not polite enough and not specific enough about where you would expect to find the squirrels.

please slow down

From a quiet (but obviously not too quiet) country lane on the way to Troutbeck in Cumbria.

Lambs Oot

A warning on the path between Skelwith and Coniston in Cumbria. Not quite sure who will be most afraid, the lambs or us?

lambs oot

Perfecting Code Reviews

I first read about the Core Protocols way back in the early 2000s from Jim & Michele McCarthy’s book “Software for your head”.

book cover

They seem like a sensible set of ideas but probably way too radical for most organizations. I recall we tried adopting the protocols with a team I was leading a few years later but due to other constraints it didn’t entirely succeed.

Like all great ideas, it came back to me again while listening to the agile weekly podcast in the early 2010’s. I had not thought about them again or had another opportunity to try using them with a new team until recently when talking to a friend about code reviews.

Describing how I do code reviews with another developer, I noticed during the conversation that I had been subconsciously using the Perfection Game in recent sessions. It was in an adapted form to suit the medium but still captured the spirit of the original.

Perfection

The Perfection Game is used as a way to help you improve something you have created. It’s at a time when you are asking for help in making something better so that the exercise becomes more collaborative than critical.

Perfect results by thinking and telling one another what you like and what would make the results perfect.

It starts with the creator (or perfectee) presenting something to someone else, asking that person to rate the performance on a scale of 1 to 10. The perfector then lists the things they liked about the performance and offers suggestions for improvement that would take the work from it’s current score to a “10”. If the perfector can’t think of a way to improve the code, they can’t withhold points.

Review

Code reviews, by contrast, can be very negative experiences, particularly for less experienced developers presenting code to world-weary, battle-scarred bad-ass senior devs. A more experienced developer looking at the code may be tempted to start straight into statements pretending to be questions - “why did you do it that way?”, “that’s all wrong, why would you write it like that?”, “why didn’t you think about…?”, “how can that ever work?” etc.

The less experienced developer often have a lot of anxiety about others reading their code and may strongly identify with their code and feel very protective of it, may be hurt by ill considered comments or withdraw from further interactions. There’s probably a whole series of articles on using techniques, like the Socratic method, to teach self evaluation of source code.

Steps

Here’s how I approach code reviews now using my covert perfection game :)

  • Person asks for code review
  • Person explains the reason for the change
  • Person demonstrates the change
  • Person shows diffs between old and new code

During this process I am making notes on things I think could be improved, things which may be wrong, things which they may not have considered. I have a running total in my head of the “score” I think I want to give. At the end, I’ll say something like: “I would give that change a 7 out of 10”. I would then ask for permission to share my thoughts for how it could be improved (no is always an acceptable answer). Then I would suggest concrete improvements to be made to bring the score up to full marks. This might be a suggestion of how to make something more robust but might be as vague as “that name doesn’t convey what you are hoping it would, how can we make it better reflect your intention?”

Conclusion

It seems to be working well and I think I might keep it.

You can see the core protocols at the McCarthy website or download a pdf.

A Bicycle for the Mind

I think one of the things that really separates us from the high primates is that we’re tool builders. I read a study that measured the efficiency of locomotion for various species on the planet. The condor used the least energy to move a kilometer. And, humans came in with a rather unimpressive showing, about a third of the way down the list. It was not too proud a showing for the crown of creation. So, that didn’t look so good. But, then somebody at Scientific American had the insight to test the efficiency of locomotion for a man on a bicycle. And, a man on a bicycle, a human on a bicycle, blew the condor away, completely off the top of the charts.
And that’s what a computer is to me. What a computer is to me is it’s the most remarkable tool that we’ve ever come up with, and it’s the equivalent of a bicycle for our minds.

Steve Jobs

Building a sketchbook

Book making and bookbinding is a skill I knew nothing about but find fascinating so I thought I would have a go at building a cheap and cheerful A5 sketchbook with a cover. Here’s how I did it.

Find some paper. The internals of the book is paper, of course.

step 1

For A5 format, I folded 20 sheets of A4 in half to form a set of nested pages.

step 2

In book binding terms this is called a signature. I am only making a simple sketchbook so I am only going to use one signature. If you use more, the book will be thicker but you then need to start investigating sewing and binding techniques. That’s another project for me.

step 3

Notice how the pages don’t fit together perfectly, one inside the other. They sort of bulge out more as you go towards the centre. The more pages you have in a signature, the worse this gets. Don’t worry, we’ll fix this in a little while.

Once you have a signature, we need to assemble some tools. Some staples to keep the pages together and something to make holes for the staples because a standard stapler isn’t built to work with this thickness of paper or where the holes are required to be.

step 4

We also need a cover for the sketchbook. Wilkinsons sell 10 sheets of black card that’s thick enough for our purposes and it costs around £1.25 a pack.

step 4a

Mark the positions of the staples. Measure in from the outer edges of the sketchbook about an inch and make a pencil mark on the inner sheet of paper at the fold. Use the staples as a guide to mark a second hole so that both sets of pencil marks show where you need to puncture through all the paper and through the cover.

step 5

Use your tool of choice, bradawl or whatever, to make holes in the paper from the inner sheet to the outer in all four places. Be careful to keep all the sheets aligned so that the staples will fit correctly with no misplaced sheets.

step 7

Fold the A4 cover sheet in half and wrap it around the signature. Make four holes in the cover to line up with the holes in the signature.

Fit the staples through the four holes at top and bottom, from the outside cover into the book.

step 8

Bend the ends of the staples to keep the book together.

step 9

The book should now look something like this, it should open and close freely.

step 10

On close inspection, you will see that where the sheets of paper have been nested inside one another, the edges of the book are not aligned and go out in a kind of v-shape. This needs to be trimmed down.

step 11

Use a cutting mat and a sharp craft knife to trim the edges of the inner pages to line up with the outer most pages and the cover. This might also apply to the top and bottom of the sheets, depending on the relative sizes of the paper and the outer cover.

step 12

Your book should now close with no pages sticking out.

step 13

step 14

Now I have a good idea of how this basic version works, I may try some more elaborate designs and builds for other sketchbooks. Watch this space.

Gall's Law

A complex system that works is invariably found to have evolved from a simple system that worked. A complex system designed from scratch never works and cannot be patched up to make it work. You have to start over with a working simple system.

John Gall