Thursday, February 22, 2018

What it takes to be an Olympian



Jocelyne Lamoureux-Davidson on the winner that landed the US the gold medal at the Olympics:

“I’ve done that thousands of times around tires just set out on open ice,” she said, per the BBC. “It’s called ‘Oops, I did it again’ and I’m just thrilled beyond words.“I’ve butchered it a thousand times, ran into tires, tripped over tires just working on my hands. I’m just glad it worked out this time.”

And thats just that one - yes, read that again  - one -  shot in her whole repertoire of shots, dodges, dribbles...Tried, tested and tried and tested again thousands of times. Through blistered hands, bruised knees, painful days and nights. The one she pulled out of her whole bag and executed it to perfection when it mattered most. Of the tens and thousands of "mental representations"(Peak: Secrets from the New Science of Expertise, by Anders Ericsson and Robert Pool )  imprinted in her brain with "deliberate practice", having executed it so many times that she could probably pull it off more often than not.

As Malcolm Gladwell puts it - “Practice isn't the thing you do once you're good. It's the thing you do that makes you good.”
Good enough to win you gold at the Olympics.

Tuesday, June 13, 2017

The non-skier parents guide with kids who ski

As a transplant to the Bay Area from tropical climes, I am not good at getting even to the 'abc' of skiing. But for some reason(well, not really unknown - thanks to some great friends!), our kids took to it and enjoy everything that comes with it. From the gear to the a·près-ski, they seem to enjoy the sights, sounds, company that comes with a ski trip to the Sierras.

One of the queries that I constantly get from parents who are as good as I am skiing and are transplants,is on how one equips and prepares for a ski season.

Most importantly, learn to have fun. As arm-chair analysts on how skiing is done, it was easy to nit-pick and point out where they might have been wrong with our kids, we've realized that its just easier to let them have fun and leave it to experience for the skills to flourish.

Over time, there are some small tips that we've figured out that helps save some time and money, and here they are. Note that some of them might work only for the Bay Area.

Equipment:

  • Skis & Poles: Best bargain would be the Sports Basement rental. If you see yourself making more than 4 trips in a season, the season lease would work out cheaper.
  • Boots: Probably the most important of equipment. We have been able to get by with the season-lease package from Sports Basement but do educate yourself on what is a good fit. Take time, ask questions, wear the right socks before you try them out. Here's a video from REI that could help.



  • Thermal Layers: Dress in layers. Watch out for post season deals, set up alerts in slickdeals.net, fatwallet.com etc so you are immediately alerted on a sale based on keywords.
  • Jackets: You could go from practical $30 Costco ones to $500 fancy ones. Our kids have found the Costco ones perfectly usable. The outlet stores also carry good jackets in the $50-$80 ranges. Again, use the power of internet and tools available to bargain hunt post season.
  • Gloves: HEAD from Costco. Seasonal, keep an eye out. If you missed it, slickdeals.net and fatwallet.com to the rescue.
  • Helmets: Started with Lucky Bums from Amazon and recently moved to Bolle from Costco.
  • Goggles: Look for ones with UV protection. If your kid wears glasses (and not contacts), look for ones that are marked 'OTG'(over the glasses goggles). Trust me, they will thank you.
Lift tickets:
  • Donner ski : Great place for beginners who are trying to figure out whether they like skiing or not. 
  • Costco: Diamond peak gift cards at 20% off. They are not available online and only in some of the stores.
  • All season: If you make more than 4 trips a season, this is a better value. One problem with this is, if you buy it for a smaller resort, you would be tied to the same set of slopes for the whole season. Which might not be a bad thing as the smaller resorts would have the smaller crowds. Good value: Sierra-at-Tahoe at South Lake Tahoe. From beginner to advanced skiers, there's something for everyone. Taking a season's pass with Vail gives you access to Northstar, Heavenly and Kirkwood. Watch out for blackout dates - if they mess with your plans to 4 trips, you may want to rethink this.
The Trip and Stay:
  • AirBnb: Saves a bunch. You could bring food in, cook some, get laundry done at the end of the day  - the advantages are tremendous and at a cost that's comparable to the decent bed-and-breakfast places.
  • Goldfish properties: Again, you get to rent and use a house(and all the above listed advantages that come with it).
Other tips:
  • Pack efficiently : This was an interesting learning for us as we moved from an Odyssey to an Outback (do not run out and buy an AWD if your only motivation is a few trips up to Lake Tahoe in winter. Read this first!). The space available was literally cut in half but we learnt and adapted.
  • A must-carry list:
    • Basic set of medicines (imagine the horror - 1 Tylenol tablet costs over a dollar at Heavenly), including Band Aid.
    • A multi-tool : We were in a situation where we needed to unscrew the face plate of a thermostat to replace the battery. While there were batteries readily available at the AirBnB place we rented, the screw head was almost of microscopic proportions and made it extra-hard. While on it, one of the first things to check once you land up : check if the heat and hot water works. You do not want to realize it when you're ready for bed.
    • Sunscreen, chap sticks
    • Chargers : A charger/battery pack is always helpful. There have been instances where the drive that usually takes about 3 hours has taken over 6 - Google maps is really handy but you need your phone charged to avail of this.
    • Flashlight
    • Nail clippers
    • Snow chains, gloves(you do not want to put on chains with your bare hands)
    • Your patience and sense of humor - remember, a family that skis together, stays together.
Happy skiing..

Thursday, January 19, 2017

Playing audio files with Echo using SSML and Python


Amazon offers the option of playing audio files via Echo using SSML. To quote:

" in some cases you may want additional control over how Alexa generates the speech from the text in your response. For example, you may want a longer pause within the speech, or you may want a string of digits read back as a standard telephone number. The Alexa Skills Kit provides this type of control with Speech Synthesis Markup Language (SSML) support."

I looked around for some examples to learn how this is achieved and ran into a brick wall. Here's what I learnt on (using python as my language) playing an audio file using Echo.

  • The <speak> tag: All SSML documents(text) need to be embedded within the speak tag.
  • The <audio> tag: Lets you provide the URL to an audio file.  There are some guidelines around the hosting and characteristics of the file you provide.
    • The MP3 must be hosted at an Internet-accessible HTTPS endpoint. (best bet? use S3)
    • No sensitive or customer specific information
    • Sample rate of 16000 Hz, bit rate of 48 kbps
    • No longer than 90 seconds

How do we address the requirements around characteristics? Thankfully, Amazon even identifies the tools and commands with which you can achieve this. 2 options(amongst the many available):

  • Command line: FFmpeg

    • following command converts the provided <input-file> to an MP3 file that works with the audio tag.

  • ffmpeg -i <input-file> -ac 2 -codec:a libmp3lame -b:a 48k -ar 16000 <output-file.mp3>
  • GUI: Audacity. (this needs the Lame library, available at: http://lame.buanzo.org/#lamewindl)
    • Open the file to convert.
    • Set the Project Rate in the lower-left corner to 16000.
    • Click File > Export Audio and change the Save as type to MP3 Files.
    • Set the Bit Rate Mode to Constant  and Quality to 48 kbps.
What are the code changes needed ? 
  • In the outputSpeech attribute:
    • set the type to SSML
    • use SSML for the marked up text(instead of 'text')
So, in effect, if you're used to seeing:

def build_speechlet_response(title, output, reprompt_text, should_end_session):
    return {
        'outputSpeech': {
            'type': 'PlainText',
            'text': output
        },
        'card': {
            'type': 'Simple',
            'title': title,
            'content':  output
        },
        'reprompt': {
            'outputSpeech': {
                'type': 'PlainText',
                'text': reprompt_text
            }
        },
        'shouldEndSession': should_end_session
    }

your function will now look something like:

def build_speechlet_response(title, output, reprompt_text, should_end_session):
    return {
        
        'outputSpeech': {
            'type': 'SSML',
            'ssml': output
        },
        'card': {
            'type': 'Simple',
            'title': title,
            'content':  output
        },
        'reprompt': {
            'outputSpeech': {
                'type': 'PlainText',
                'text': reprompt_text
            }
        },
        'shouldEndSession': should_end_session
    }

Here is an example of valid output(note, enclosed within the <speak> </speak>tags. Replace the bucket name and file name appropriately)

'<speak>This output speech uses SSML.<audio src="https://s3-us-west-2.amazonaws.com/<bucket name>/<file name.mp3>" />.</speak>'

When returned in outputSpeech, Echo will :
  • read out, in normal, Alexa's voice: "This output speech uses SSML."
  • and then play the audio file the URL points to.

Sunday, December 18, 2016

Home automation - Etekcity outlets meet Raspberry Pi meets Amazon Echo

I came across Sam Kear's beautiful article on controlling power outlets wirelessly and couldn't wonder about what it would take to take the next step of enabling this interaction in Amazon Echo.

It seems the universe is one boundless crucible of creativity and ideas - Chris Derossi at makermusings has already done the hard work of figuring it out.

The idea is simple:

  • Echo automatically detects Wemo devices
  • Use wireshark to reverse engineer the conversation taking place once you trigger "Discover Devices" 
  • Use fauxmo to mimic a Belkin hub and direct the request to your RESTful service that will do the needful
  • Implement your on/off behaviour via the RESTful service, internally making a system call via codesend (described in Sam Kear's posting).




This is how I went about it.

The ingredients in the recipe:
  1. Etekcity Wireless Remote Control Electrical Outlet Switch for Household Appliances: This device came on sale recently with a coupon, dropping the price to $21.48.
  2. A Raspberry Pi: I set out building it with the Model B and I hit one of the troubles he mentions in Troubleshooting,  an observation that the receiver was not super sensitive when you press the buttons on the Etekcity remote. My feeling was that the Model B is a bit underpowered for this, the frustration made me use a Model 3 (yes, Frys have it now) which was remarkably sensitive to the clicks on the receiver. Using the Model 3 also obviates the need for a Wifi dongle.
  3. Receiver transmitter
  4. A micro SD card, at least 16 GB in capacity(Elementary tip: if you want to reuse the cards on which you've written the images, you'd see a drive with reduced capacity. See the fix here.)
  5. Power adapter for the Pi (one lying around from a retired iPad came handy)
  6. GPIO Breakout and Cable for Raspberry Pi
  7. Breadboard, jumper wires, soldering iron,solder etc
  8. Wire for antenna - I used an old coat hanger connected to a wire that was soldered on to the transmitter. Works at least over 30 ft and across at least 1 floor.

Steps:
  1. Set up your Pi using Sam's posting. I don't think I can improve on something that is so well done.
  2. Find and note the on/off codes using RFSniffer.
  3. Set up fauxmo. I used the steps detailed here. 
  4. At this point, Echo should be able to find the dummy devices setup in config.json (use the Smart Home->Discover Devices link in the Alexa app). Try saying "Alexa, turn on fake switch one" and Alexa will start blinking with the blue light moving round and round, making every effort to fulfill your request, but will fail with a fairly verbose message.
  5. Install/configure flask.
    1. Create the virtual env (install virtualenv with "sudo pip install virtualenv" if you do not already have it).

      • pi@raspberrypi:~/projects/flaskserver $ virtualenv flaskvenv
        New python executable in /home/pi/projects/flaskserver/flaskvenv/bin/python
        Installing setuptools, pip, wheel...done.
        pi@raspberrypi:~/projects/flaskserver $
    2. Activate the virtual env and then install flask.
      • (flaskvenv) pi@raspberrypi:~/projects/flaskserver $ pip install Flask
    3. (This step is a placeholder for a future refinement and is not necessary). Create a directory called template and drop the index.html file here.
    4. Create your flask app . Here's mine.
    5. Create a shell script that initializes and starts flask. This will come in handy later once we start using systemd to automate flask initialization on startup.
  6. Edit the config.json file for fauxmo. Set up the codes you recorded in Step 2. Use a different port number for each device. Modify for ip address and port numbers per your setup. I've followed a format of http://ipaddress:port/<device group>/<device>/<code>. I have no idea at this point on what I might do with the device group and device values, but something tells me that some sort of grouping might be useful once I drift into tools like Home Assistant etc.
  7. Restart fauxmo. Rediscover the devices. You should see your devices from the changed config.json file now.
  8. Test with "Alexa, turn on <your device name>" and "Alexa, turn off <your device name>"
  9. If everything works all right, setup fauxmo and flask for initialization during startup. Create the service file (my samples here) and enable them with systemd (good tutorial here ):
    • sudo systemctl enable fauxmo@pi.service

Happy automating!

Saturday, November 12, 2016

A pill reminder skill


If I were to put in a time lapse photo on my journey with developing skills for the Echo, I think I would see myself poring through Amazon documentation, copying and pasting one of the skills and getting a T-shirt, writing the first set of lambda functions, making some feeble efforts at learning javascript/node and then deciding to stick with Python, figuring out how to update sets,lists and maps, in DynamoDB entities, session management, control flow for intents....and finally concluding that I'd become just about educated enough to be dangerous.

So, with a big TH to the folks at DaVincian Healthcare, who won the overall Pymnts/Alexa Challenge, I set out to build a pill reminder skill. (check out their awesome video here )

Considering that I couldn't possibly integrate with a pharmacy to just read out prescriptions and add them once prescribed by a doctor(which would have made life infinitely easier), I took the easy way out by just speaking out the names of medicines to add or remove them.

Straight off the bat, I realized a problem with this - my pronunciation of a medicine had to be identical through the life cycle of the existence of that medicine in my schedule. Variations would just add it on as a new medication, a request to remove it from my schedule would stump Alexa and have her go boing-boing at me etc. (Why am I now not surprised that, while Alexa lets me add things to my To-Do list, any removals would have to be through the app?)

Note to self:  is there a service out there that can validate text of a medicine name? If so, integrate with such service.

Secondly, a voice based interaction needs to be designed and built very differently from a screen-based interaction. eg once one start using the skill , how do they know what all they can do? Do we go, for adding a medicine, say 1, for deleting a medicine, say 2 and so on. To listen to options like those, one is better off calling Comcast - an Alexa skill needs to be a lot more friendly, engaging and intuitive. You should basically be able to have a conversation with Alexa.


But since this was an effort to be just dangerous and learn, I boldly ventured forward. I planned on developing these intents:

  • add a medicine to my schedule(which, in this case, was driven off the day of the week)
  • remove a medicine from my schedule(for a particular day of the week)
  • list all medications in my schedule
  • list medications from my schedule for a particular day of the week
  • remove all my medications from my schedule
No effort would be made to retain history of the users interactions. The last intent listed above would blow away all traces of the existence of the last known schedule for the user.

Of course, any time, you're adding or removing medicines, Alexa should prompt for a confirmation, which is where the built-in YesIntent and NoIntent intents come handy.

So, without further ado, lets get started.

  • Set up your environment (this has been discussed thread bare in all the awesome tutorials out there. Here's one in case you're still looking)
  • Attach Dynamo DB access Policy in IAM to the role you're using


  • Create a table in DynamoDB 











  • Create the lambda function. The steps are very well detailed in tutorial referenced earlier, replace the code in the handler function with code from pillButler.py
  • Setup the skill in developer portal. Use the intent schema from IntentSchema.json
  • Create the slot types
 








  • Add sample utterances from SampleUtterances.txt
  • Invoke your skill from Alexa by saying "Alexa, open pill butler"

I'd like to reiterate that this was an exercise purely for fun and learning - no effort has been made to develop a complete solution. There are many corner(and not so corner) cases that would not pass muster and I am sure that this certainly will NOT win a T-shirt from the Alexa folks at Amazon if I were to submit this for publication.There is no practical use of this skill in this shape and form, unless integrated with a pharmacy and hence, not publishing it.


Happy Echo-ing!

Wednesday, October 19, 2016

Simple behavioral changes via "Tiny Habits"


I read a book once that convinced me that habits can only be replaced, not created. To me, that was extremely convenient and served as the rationale for not changing things that worked well for me, but not so much for others.

Till I came across Dr B J Fogg and his "tiny habits". Its a very simple approach, basically trying to engender small behavioral changes by weaving in what he calls "tiny habits", and repeating them till they are ingrained.

For these to be successful, a tiny habit :
  • has an anchor .
  • is what it is - tiny. Involves an activity that can be done in less than 30 seconds and you're seeking to make a habit 
With gusto, I signed up for his session on Tiny Habits, looking to change my world, before I changed other's. Have to admit, for a free coaching session that was trying to effect behavioral change, the process was remarkably efficient.

I set out to change 3 of my behaviors that I noticed was - surprisingly - annoying others.

  • inject some positivism into my day by reminding myself, first thing in the morning, of the great day I was going to have.
  • put my shoes away once home from work
  • load my lunch box in the dishwasher once home from work.


What surprised me the most was how the changes threw up the inefficiencies around how I was organized. eg with the goal of putting away my shoes on walking in, I realized that my prevailing approach was rooted in where I'd park my car once home( in the driveway), where the shoe rack was(in the garage) and how I'd enter my home(via the front door rather than the garage!).And once I walk in thru the door, I dislike walking around the house with my shoes on, so it needs to be off and there it would lie till the next day.

Cultivating this tiny habit called for:

  • taking off shoes on walking in
  • picking them up and walking into the garage thru the connecting door(which is slightly jammed)
  • bend down to stow away the shoes on the lowest spots(age, bad back etc) - the upper ones are taken by whoever came in before me.

I think the key is to determine the sequences that help or hinder the development of a habit. And address them one by one.

Having encountered success with this, I set out to try it and help Junior who was having a hard time memorizing words to strengthen his vocabulary. So once the flash cards showed up from Walmart, we loaded a few cards on the ring that came with the set and I sat back while the process of goal-setting to cram the set of cards playing out.


The ring hardly saw any movement in the following days.

Tiny habits to the rescue. What would be a good anchor and goal to develop this tiny habit?

Anchor: ?

After a lot of deliberation, we anchored on "After I hit the bed at the end of my day". Now onto the goal.

First iteration: I will go through my set of flash cards.

Fails the sniff test. Takes more than 30 seconds and is not really tiny.

Second iteration: Reduce the number of cards to , say , 10. Still fails. It takes about 5 seconds to go through a word, especially if its new.

Third iteration: I will pick up the ring the cards are on.

Eureka!  If you've managed to remember to pick up the ring, the rest is a matter of course.