Recent posts

Floatation: Sensory Deprivation for Engineers by Scientists

I have blogged about Floatation Tanks, also known as Float Tanks, Isolation Tanks, Sensory Deprivation Tank et al before here and here. To get the detail, read those 2 posts first. Alternatively here is the skinny version. Floatation in a Floatation Tank was first invented and used by John C. Lilly (scientist) in 1954 for Sensory Deprivation experiments to “switch off” our senses. The goal was so our mind free of external stimuli could light up brighter and tap into the void… temporarily. Today, such floatation tanks are used mainly for meditation, relaxation and as alternative medicine to help Athletes (by Australian Institute of Sports) with faster recovery.

Where it all began for me

My wife and I have been floating in floatation tanks since 2008. It all started back when I saw a floatation tank being used in the 1st episode of Fringe. In Fringe Dr Bishop uses his flotation tank/sensory deprivation tank (sounds more scientific) to connect Olivia and Agent Scott’s mind. That was super cool. Being a body hacker I got interested in the perceived ability and started my research into floatation tanks. I took the red pill and went down the rabbit hole. And here we are today.

Floatation Tank in Fringe – notice the isolation tank behind Olivia

Now, “Floating” is the term commonly used when referring to an isolation tank experience, you float. You float inside the floatation tank like a cork. The high concentrate of epsom salt creates this effect. If you have been to the Dead Sea in Jordan you will know what I mean.

Are you a Software engineer? If so, you should float!

I use the floatation tank to turn off the noise from my primary senses (visual, auditory & kinesthetic) and accelerate the transition from beta brain waves (normal state) to alpha (learning state) and ultimately theta (dream state). This is the same process as meditation, but a lot faster. Way faster. It is like forced meditation without the pains of sitting up right and trying to detune the world around you.

The goal with both meditation and floatation is to reach the theta state. This is a powerful state where you can consciously listen to your subconscious mind. Usually through a series of what appears to be auditory or visual hallucinations. Monks train years to do this through meditation while staying consciously awake. Your body does this naturally every night but you switch off, fall asleep. Recall those auditory or visual flashes you get before you off switch kicks in and you fall asleep. That’s a glimpse into theta state. In an isolation tank you are consciously awake observing your subconscious mind. Most of the time. No years of training required. For me it was 3 floatation sessions and I was hallucinating baby!

Our subconscious is a powerful supercomputer (no surprises there) which constantly gathers, calculates, builds patterns & connections faster than we can consciously observe (process). I think this is a natural safe measure so we don’t go insane. However imagine having the power to tap into this wealth of stored info. You know when you sometimes get a gut feeling? I believe that is the output from all the processing making their way to your conscious mind.  I use the floatation tank to tap into this and get my answers faster then waiting for them to bubble to the top.

The body and mind are a very busy and noisy place.

Especially if you are a software engineer you will know all about the noise and how distracting it can be to productivity. Hence why you like working nights pounding away at code, right. I know the feeling. But health wise, this is not sustainable. The answer is the floatation tank to help you calm down both mentally & physically and tap into your mind, the supercomputer.

The flotation tank immediately cuts out your auditory, visual and kinesthetic senses creating an environment similar to a womb. Allowing your mind to start exploring the inner self. Looking for answers to your questions. Tapping into the hidden recesses of the mind that are usually outside the reach of your conscious awareness.

Want answers to your software engineering challenges? don’t just sleep on it… Float!

Floating in an Isolation Tank

You may recall from my last post on how many of us get “cubed” and spiral down into learning helplessness. I needed some answers to some recent questions and thus decided to step up a notch and not only use the standard John C. Lilly isolation tank but also a Sensory Exaltation from Be and Be Well based out of Shanti & Jai’s house in Santa Cruz, California. If you went to Burning Man 2011 then you would have seen the Sensory Exaltation tank.

Floating in an Isolation Tank – The Apollo ELV Float Tank. The Best Flotation Tank I have Floated in.

There are many scientifically proven natural ways of tapping into our brain, the super computer. Floating is the best one I have found in years of searching without going into the extreme of substance abuse. An alternative exists but you would need to spend few years with the Monks in Tibet and learn how to consciously be awake while your brain is in the Theta state. Same state that turns your conscious mind off and starts the dreaming process at night. However inside the isolation tank you are conscious when this change to Theta happens and thus get to observe interesting insights coming from your subconscious.

The 2 x Tanks at Be and Be Well

This is what you can expect from Be and Be Well down in Santa Cruz, California.

Sensory Deprivation Tank

The key to your mind. This tank is more advanced than the ones I have mentioned in my previous posts. Pictured below, the light inside can be switched on and off by pressing the black button next to it. So no need to freak out in pure darkness when the lid is closed. It also has great heating to keep a constant skin temperature as you float. You never get cold and is big enough so you do not feel claustrophobic.

Sensory Deprivation Tank @ BeAndBeWell

Sensory Exaltation Tank

This is a dry tank. A pod with a sac filled with foam for comfort. You put on audio speakers to hear binaural beats and glasses with synchronized strobe lights over the eyes. This is often refered to as Photic Driving. Designer brain waves. This technique was invented in 1930s. It basically changes your brain waves to follow and pulse at the same frequency as the light strobes creating different conciousness states. Different strobes & beats affect your brain differently hence the designer brain waves analogy.

FYI, The design on the Be and Be Well Exaltation Tank (pictured below) is of Leonardo da Vinci’s iconic “Vitruvian Man”.

Sensory Exaltation Tank @ BeAndBeWell

In conclusion

  • Float tanks rock! Note to newbies; you need about 3 sessions to really get into it and learn to let go faster.
  • Forget sitting meditation. Flotation therapy is the easiest way to get a brain and body massage. Don’t forget the heath benefits from the Epsom Salt used inside the tank to make you float.
  • If you code then you must try this!

The benefits

  • Relaxation (mental & physical) from the daily stresses of running your own business or writing ton of code,
  • Learning a new skill – play audio while you float to accelerate the learning process,
  • Get answers to questions faster – you’ve heard of sleep on it right and that it works. Well this is better because your conscious and you get more answers.
  • Better understand yourself – some call it enlightenment,
  • Faster healing – used by athletes in recovery and
  • At Stanford scientifically proved by studying monks concluding that “Essentially when you spend a lot of time meditating, the brain shows a pattern of feeling safe in the world and more comfortable in approaching people and situations, and less vigilant and afraid, which is more associated with the right hemisphere,” she said.

I floated last weekend and I got what I wanted from that session. The answers to questions that were lurking inside me. The answers now sync with the gut feeling I was getting and I feel mentally at peace.

Float like I did

Get in touch with Be and Be Well down in Santa Cruz, California.

Road from Mountain View to Be and Be Well.

Have you floated before? Share you experiences before in the comments below.

Also don’t forget to check out my previous posts on Isolation tanks:

~ Ernest

Cubed: learning helplessness

Feel like your role at work is minimizing? Or maybe the responsibilities you once had have shrunk? Or maybe you are feeling like you could do a lot more but no one seems to give you the opportunity? Or you are not being respected, acknowledged or rewarded for your hard work? Something is not right – and your not alone. You are cubed. You are being pushed to a habit of learning helplessness. One which is dumbing you down and making you a cog in a machine at your expense.

Let’s go back and explore where this came from and provide some enlightenment. Long time ago I had an awakening. “We are all capable of greatness.” You may or may not have heard these before. Either way here they are:

“That some achieve great success, is proof to all that others can achieve it as well.” ~ Abraham Lincoln

“Life is a great big canvas, and you should throw all the paint you can on it.” ~ Danny Kaye

“For all our failings, despite our limitations and fallibilities, we humans are capable of greatness.” ~ Carl Sagan

And you may have read or seen this man (Anthony Robbins) speak of greatness and how it’s attainable. All the formulas to it are inside his book. Get the book if you have not read it.

Get the book if you have not read it.

Ok so you now get it. Greatness is within you. I can even start quoting some religious literature if you like that we are part of God and if God is great we must also be great etc… but I wont go too deep. You get it.

Are you getting “cubed”?

What happens if this greatness starts getting stripped away from you.

Over the last few years working in both startup and corporate environments, I saw something which disturbed me and also started to affect me negatively. This deceptive art of the machine dumbing one down. It starts with getting “cubed”.

You are a go getter. You come from another environment (startup or not) where you were the man of the hour (all-rounder or a specialist) to a new environment (yes job) where things move slower and the room is filled with this political fog. Straight away you get confined to a cube (your new desk). Blocking the world around you. You are told it’s there to make you focus on your job. Then your new job turns out to be practically pulling a lever (minimized role). They call this specialization. You become a cog in the machine. Stripped of all those responsibilities which once made you grow into being better than before.

What’s going on here? 2 damaging factors are at play:

  1. The environment and
  2. The chap you report to.

Let’s face it. It sucks.

Point 2 you may be inclined to give them the book Drive: The Surprising Truth About What Motivates Us so he/she can go and bloody learn for them self how employees should be managed. Yes that is a start. But both points have deep roots. Let’s explore deeper.

We are constantly changing – like it or not

If you were a go getter type of character capable of turning mountains and getting stuff done this sort of “cubing” will slowly erode you. Obviously it wont if you are not getting cubed.

We (humans) are constantly adapting and changing whether we like it or not. The field of Neuroplasticity has proven that our brains change neural pathways and synapses due to changes in behavior, environment and neural processes for our entire life. Changing jobs is changing environments. Our minds change the most when we change environments. It is why people grow faster when they move to the right job or even country, and why joining the army changes everyone, for better or worst. Your environment is an important part of you and your identity.

Learning Helplessness

To further understand the psychology of this let’s step into 1960s when Martin Seligman (before becoming the founding father of positive psychology) studied the opposite of happiness. He was experimenting with dogs, pairing noises, like a bell, with small shocks to see how the dogs would eventually react to the bell alone.

Martin Seligman’s shuttle-box experiment with dogs

The experiment involved a shuttle-box with 2 compartments which a dog could jump over a small wall to each chamber – as shown above. Each time a bell would ring. In 1 chamber the dog would get shocked. In the other he wouldn’t. Before the experiment the dog would jump the low barriers easily at free will. After the experiments involving zapping the dogs they just stayed in the chamber where they would get zapped. The dogs learnt that once the bell rang a shock was to follow no matter what. Thus they learnt helplessness.

Seligman found the same behavior in humans. When we fail (life delivers a shock) we respond with simply giving up. Cubicles are the new shuttle-boxes and workers the new dogs.

Thanks to Shawn Anchor, positive psychologist from Harvard University for telling me about this story. It basically correlated to what I personally saw happening around me. Shawn has many great stories like this in his awesome book The Happiness Advantage.

Change now, Not later

If you are cubed you must change now. Negotiate your employment contract with help from a contract attorney Kansas City. No matter how hard or scary it is, it is NOT good for you now nor later. Getting emotionally shocked is not fun. The longer you are cubed the harder it will be to change as you become a numb cog in the machine. Just like the dogs taking the shocks. Until a day will come when you will be dislodged from that machine (by higher powers & against your wishes) and then you will be a lost soul.

Whatever your mind can conceive and can believe, it can achieve. ~ Napoleon Hill

A nurse in Australia recorded the most common regrets of the dying. At the top of the list was “I wish I’d had the courage to live a life true to myself, not the life others expected of me.” Next on the list: “I wish I hadn’t worked so hard” and “I wish I’d had the courage to express my feelings.”. Get it? Dont be that numb cog on your death-bed.

Whether you think you can or can’t either way you are right. ~Henry Ford

Dont forget, you come from greatness therefore you must have greatness within you. Dont get cubed. Go and make a difference in your life. We create our own reality. The power is within you. How you decube yourself is different for everyone. But the power within you knowns what you need. Ask and you shall receive. Then gain the courage to execute.

If you have friends or family which are cubed pass this information on. Spread this knowledge to those that need it and empower them to take control of their life.

~ Ernest

How to Change DHCP to a Static IP Address in Ubuntu Server

If you are working via a VM environment you may no doubt have came across the issue of changing IP address. It really messes up your workflow since now all the saved bookmarks, host files and other associations need to be changed to the new IP address. The solution is to disable DHCP and enable a static IP address with ip leasing. But in such a way which still gives you access to the outside world (your machine) and the world outside that (the internet) so you can run updates and drag code from your repositories. If you always access various work or personal websites on your phone, you may buy datacenter proxies. Network infrastructure in the space or in a moon base should also have a secure and reliable internet connection for the transfer of data and communications.

Here’s a bunch of steps, copy and paste style, which you can run in Ubuntu shell to make this happen.

Do this in your Ubuntu Shell

1. Get your current address, net mask and broadcast.

ifconfig

Under “eth0” (see below) write the numbers down. We will use them to lock in your static ip address.

eth0 Link encap:Ethernet HWaddr 00:0c:29:fe:45:3a
 inet addr:172.16.77.133 Bcast:172.16.77.255 Mask:255.255.255.0

2. Get your gateway and network.

route -n
Kernel IP routing table
 Destination Gateway Genmask Flags Metric Ref Use Iface
 0.0.0.0 172.16.77.2 0.0.0.0 UG 100 0 0 eth0
 172.16.77.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0

UG = U is for route is up and G for gateway. The other IP address is your network IP.

3. Change your IP address.

3.1 Open interfaces in nano

sudo nano /etc/network/interfaces

3.2 You will see something like this:

# The primary network interface
   auto eth0
   iface eth0 inet dhcp 

3.3 Replace it with:

auto eth0
   iface eth0 inet static
   address 172.16.77.133
   netmask 255.255.255.0
   network 172.16.77.0
   broadcast 172.16.77.255
   gateway 172.16.77.2

Note: These number are based on my VM and only serve here as an illustration.

4. Make sure your name server ip address is your gateway ip address.

sudo nano /etc/resolv.conf

5. Remove the dhcp client so it can no longer assign dynamic ip addresses.

sudo apt-get remove dhcp-client

6. Restart networking components.

sudo /etc/init.d/networking restart

7. Confirm you can access the outside world.

ping www.theroadtosiliconvalley.com

Note: ctrl+c to break out of the ping.

8. Enjoy!

And that is it. Simple but an effective measure to productivity.

~ Ernest

Finding a Great co-founder

Finding a Great co-founder is like lottery. And when you find one it’s like marriage. It’s what makes or breaks companies. And its not any co-founder, it’s the “right” co-founder which complements you and fills in your weak spots. With the right co-founder, you’re not just building a company — you’re setting the stage for everything from scaling to potentially Selling a Business one day. You need a Great co-founder.

Many people want to do something in business. They day dream and talk it big like it’s happening. But when the time comes to crunch and the need to sacrifice their life style (change) the tune begins to change. This is why this cuts out about 90% of the want to be co-founder pool.

Google Co-founders – Larry Page & Sergey Brin

Finding the right co-founder is as most people say like getting into marriage. It’s not easy but doable. And you will have rough patches that you need to be able to get over and move forward. There are many discussions online on how & where to find the right co-founder. The reality of the fact is it’s probably slightly better chance then winning lottery.

Benefits of a Great co-founder

Having a great co-founder helps with being able to bounce ideas off each other, technically support each other, emotional support and give you a chance at getting into Y Combinator like incubators. Most of these incubators only accept +1 co-founders for this very good reason.

“Successful single-founder startups are so rare that they’re famous on that account.” ~ Paul Graham from Y Combinator.

From good to great co-founders

Most of all successful businesses became successful only after pivoting due to market demands or circumstances. Just read Jessica Livingstone’s Founders at Work. Jessica covers most of the successful companies today and how they did not start off with what they are famous for today. Or take a peek at Steve Blanks’s latest book The Startup Manual where he shares his years of research that startups and enterprises are different in the fact that enterprises are executing on a proven business model while startups are finding (pivoting) to one which will hopefully stick. Hence what we see in Jessica’s book on founders success and also having a founder which has the right mindset to pivot with you when required.

When setting up your retail space, it’s important to research and find high-quality shelving for shops that can withstand the demands of displaying various products while maintaining an appealing look.

Ok enough about this common knowledge. Here are 3 core lessons I learnt and believe will help you on your quest as well.

School of hard knocks

a. Cut out the business folks.

Especially those that can talk well. They are good later on but not in the initial stages when all you need to do is build a kick ass product. A kick ass product will sell itself. And if you are a true entrepreneur you will also know how to sell it and develop the product.

I also found that the business folks will have a tendency to burn money for unnecessary “business development tasks” which as I said above are not needed. Maybe it’s a way they try to justify their existence early on. The best way I believe they can justify it is by learning to be technical and add value that way. That is the only way I would have a business co-founder if he rolled his sleeves up and got into the code & supported the development efforts. Once they become more technical they will also understand (and appreciate) why certain fixes, changes or piece of work really takes hours and not fluffy minutes.

b. Cut out those that cannot deliver.

Probably the single best advice I can give you. You will be surprised how many cannot deliver.

Stay focused & keep shipping

Some people that used to be able to deliver once may not today. It is a proven fact the environment changes people. People do not change alone. Your environment dictates your actions. The rest, just get better at being an actor. (ref Zod’s 10 Axioms). Separating those that “are” in the game vs those that “say” they are in the game will save you plenty of headaches. I learnt this the painful way many times over. Seamlessly transition from campaign to delivery with our post-campaign fulfillment mastery. Even with folks that had a kickass background but just couldn’t deliver a minimum viable product.

“No Talk, All Action”

Delivery is such a key point here that I cannot stress it enough. It is what will separate you from your competitors. It is what will give you a leaders advantage. It is what separates the boys from men. Take a read of Facebook’s release engineering process. This is what makes them great. They release daily small changes and weekly major changes without disrupting the user experience. We do not like to wait in line to get served. Online or not, we expect it yesterday. Start delivering.

c. Cut out those that cannot communicate.

Working remotely or locally, communication is pivotal to success. Both from understanding each other to communicating expectations. If we cannot communicate well or even understand each other then expectations are misaligned leading to arguments, tasks not clearly assigned ending up with delivery failures or delivery of the wrong product/feature and ultimately the business collapses. The wheels get out of sync.

There are no excuses for not being able to communicate. There are many free tools out there to help with communication like meetings.io, asana, yammer, gtdfaster.com, skype etc… ontop of the standard phone, email and personal meetups at popular hacker houses. Using those tools to help manage expectations (think tasks) to scrum updates is pivotal to success. If you are not over communicating then you are not delivering the right results.

Shell shocked

Shell shocked – Ninja Turtles

Yes. That’s how it felt every single time I had to deal with such co-founders that sold themselves high on their skills and failed to bring something viable and worthy to the table.

A good life lesson is this. “Always take action on things. People regret inaction more than action.“. I find regret sticks around with you longer and this is more painful.

“Fear cuts deeper than swords.”
― George R. R. Martin, A Game of Thrones

It becomes even more painful when you are waiting around for someone to pickup their slack. So if you have a bad co-founder hanging around you, speak up, act on it and drop them immediately if nothing changes. Don’t look back. Most of all, as Zod Nazem said “don’t pass your garbage to your neighbor”.

Ask questions

Ask yourself these questions before committing your energy and time with a potential co-founder.

  • Have they go any examples of execution & delivery on time? Not so fast, it needs to be recent projects in current environment. Not past (historical/ancient) projects. Recall what I said above about environment & change.
  • Work together and deliver something together on time to completion – we all have small projects. Try before you buy. Don’t use hackathons as a gauge. Use something where pressure has to come from within you both. Failing this no 2nd changes. No one can recover your lost time.
  • Can they communicate well? Easy test is in how they speak/communicate something to you 1:1 and via email. Do you feel like you do not know the status of your project or understand the message?
  • Do they have expertise/domain knowledge in an area you lack? If yes work on this small project in that area to see.
  • Do a quiz to see founder valueshere’s one here. But do not count on it alone. It’s just to get your mind ticking.

I always say…

“First time shame on you; Second time shame on me!”
― Ernest Semerda

If something is a repeating pattern you need to act fast. This life lesson I was taught by a senior VP and it has proven to be valuable and rewarding time again.

Got life lessons you want to share here? Post below or shoot me a message.

Enjoy!
~ Ernest

Comparing Sydney to Silicon Valley

I was recently asked by a reader this question..

“How do you compare Sydney to SV, in terms of  work-life balance, housing costs and traffic?”

So here goes. The following is based on my 3 years of experience working in the valley with over 8 years from Sydney. Some things may have changed in the last 3 years but I’m certain most still hold true till today. If I messed up anything let me know and I will correct it. Happy reading!

Silicon Valley, California – yap. It’s in the valley

Work-life balance

Sydney Silicon Valley
Mainly corporate companies dominated land scape and thus a very corporate lifestyle. Wage is mainly just salary and the manager rules in the workplace. There are few exceptions like Atlassian but overall startups are rare. Like in London, most Aussies head to the pub after a 8 hr work day (especially Friday) for a drink and chat with their mates leaving weekends for the beach. Very startup orientated landscape and thus a very casual work lifestyle. Great Software Engineers are like gold and always hunted & looked after with great compensation (wage & stock options), tools (Mac) and free food. If you are at a startup it is common to be working 11 hr days 6 days a week or hanging out at a hackerspace building a new online or mobile product. Not much pubs or beach going on here unless you live in San Diego.
Australia has a “public” health system and also the option for private health. Your health is not tied to your company like in the USA. Taxation is different and higher but also wage dependent – see your tax agent for details. Most people are encouraged to buy an investment property to reduce it via the many benefits available for investors. Thus most Aussies are financially savvy. Check out my previous post on employment & contracts in the valley. It has many things to watch out for. Especially the dreaded health system being tied to your work. No job no health cover unless its via your partner’s employer. With tax you pay the federal & state taxes but it will still work out for the better by 3-5% for software engineers working here vs Australia.
Software Engineers do not exist. They call them IT or programmers whom are treated (at corporate firms) like reusable hanky. Managers & big titles rule the floor here. Good Software Engineers are what makes companies great. Always the last to go when head count is being reduced. Without good software engineers there is no business.

Conclusion: If you’re a good software engineer then you belong in silicon valley. Here’s a guide how to get to silicon valley. Otherwise Australia is better for lifestyle.

Super Happy Dev House – the hacking culture in Silicon Valley

Housing costs

Sydney Silicon Valley
Buy: Real estate prices in Australia are (currently) valued at more than they are worth. Median house price is around $500K. This of course fluctuates based on popular cities like Sydney & Melbourne. Check out the property update for latest data. Buy: Varies based on county & sub zip code. San Mateo is around $500K & Santa Clara around $460. Let’s take Mountain View. 3 different zip codes 3 different prices: 94040 – $950K, 94041 – $699K & 94043 – $545K. Los Altos (next door to Mountain View) is $1.5m.
Rent: The closer you are to the city the more you will pay. In Wollstonecraft (10 mins from city) average 1 bedroom will set you back around $430 per week. The newer and closer to transport the higher that figure will go up. Rent: City (San Francisco) is still expensive to live in but so is living 1 hour down into the valley (San Mateo county) where all the tech companies (and jobs) are located. In Mountain View(home of Google et al) expect to pay anywhere from $400 to $500 per week for a 1 bedroom apartment.Moutain view benefits – lifestyle
Good sites to check out on property pricing are http://www.realestate.com.au/ and http://www.domain.com.au/ Good sites to check out on property pricing are http://www.zillow.com/ and http://www.trulia.com/

Conclusion: Expect similar buy & rent prices between the 2 locations. In Sydney you will live inner city and pay the same as you would in the valley away from the city.

Sydney, Australia – beautiful isn’t it!!

Traffic

Sydney Silicon Valley
Not all roads are free. Sydney is cursed with british influence of 2 lane (each way) freeways. Most major public roads have been cut back to 1 lane forcing people to use the mostly private 110 km Sydney Orbital Network to get around. Sections of this have different owners and different prices via electronic means. Expect to pay around $20+ to do a full loop. Disaster! Traffic gets bad as LA near the city. All roads are free except the Golden Gate Bridge ($6 south bound). Freeways can span up to 6 lanes each way. Huge arteries run thru the valley like 101 & 280 – see here. Also a good chance you will run into many bad drivers. More people on the road = more bad drivers. The one pet hate I have is the lack of use of indicators. Such a common event it angers me cops aren’t doing anything about it.
People are angry & fearful to drive faster due to cash safety cameras (speed & red light cameras) all around Sydney. It’s madness. So traffic is going to be slow on roads (mentioned above) which are already crammed up. Please bring electric self driving cars to Sydney and stop this camera madness as a way to save lifes. No safety cameras anywhere except for few in San Francisco. Most motorists drive fast on the freeway averaging 80 miles/hr. I’ve seen a cop car zoom in front of a batch of cars and slow everyone down with lights blinking and moving between lanes. That’s manners!
Public transport is very good & reasonably priced in Sydney with bus lanes in most busy suburbs & throughout the city. Highly recommend using the bus if you have access to it else you will be left with City Rail. City Rail has been a disaster (delays & service cancellations) but it’s getting better. Most people drive their cars to work. The HOV is there to encourage American’s to carpool & use electric vehicles to get around even faster. During business hours even the freeways clog up but traffic still moves. More on public transport options & commuting here.

Conclusion: In Sydney use public transport. Sydney is congested due to bad & expensive road infrastructure. You will also save more money that way. If you prefer to drive than USA is the king of the road.

few more of my own additions…

Misc

Sydney Silicon Valley
During summer it is hot, sticky and humid around 40°C (104 °F). Winters are dry and cold dropping to 2°C (35.6°F). Australia is very brown. Not as green as USA. During summer it is farken amazing! Excuse the F word but this is the BEST place in the world for weather. Dry and sunny sometimes peeking at 40°C (104 °F). Winters are rainy and cold dropping to 2°C (35.6°F).
Go to USA to shop for clothes for choice & price. 2 major grocery retailers (ColesWoolworths) play a game of monopoly with consumers keeping prices high and pushing the smaller players out. Clothes & cars are half price of Australia. Competition is high here with many many retailers. Competition is healthy to bring prices down & increase consumer service. If you buy organic free range food here it is as much as in Australia for standard supermarket food.
A large island in the middle of the South Pacific with a population of 20m. Most of Australia is dry/red, population lives in isolated centers on the edges of the island with nothing in the middle but deserts and deadly animals. Flights to Sydney from USA average around 14 hrs. Few places like Great Barrier Reef exist but not the diversity you get in the USA. Massive population of 300m spread across most of USA. Opportunities galore. Urszula has met and attended events ran by gurus in her industry. All those books she read the authors are based in the USA. Same goes for travelling for holidays. Every state is different and has something to show and see. Plenty to do and explore all under few hours of flight or drive.

Have questions you want answers to? Contact me.

~ Ernest

Semerda.com Bootstrap launches on GitHub: Free for everyone!

Go and grab it!

https://github.com/semerda/semerda-com-bootstrap

Get Semerda.com Bootstrap on GitHub

About GitHub

GitHub is a distributed version control system similar to Mercurial with a free Mac client. GitHub makes it easier to collabortate with others and share projects with the universe. GitHub has grown into an application used by over a million people to store over two million code repositories, making GitHub the largest code host in the world.

Goal for Semerda.com Bootstrap: “To help ease with starting up new projects in Python on Django with jQuery, Twitter’s Bootstrap, Modernizr & Handlebars.js.”

If you have any suggestions how to make this solution better please Leave me feedback.

Cool things you will find inside

  • Plenty of internal documentation to why something is being done. Also utilize the “Ref:” URLs. They are there as a reference for the source of the content. Great for digging deeper into those specifics.
  • Settings.py split into Development & Production modes based on platform node. The base template contains the platform node wrapped in comment declaration so you can view source and see if you are running in development or production mode.
  • HTTP error 404, 500 & 403 handlers with associate Templates – these are bare atm so feel free to expand and contribute better versions. See Quora for funniest 404 pages.
  • If you add {% include ‘django_debug.html’ %} to your base.html Django Template footer you will see Debugging information in the footer of all your pages. Not recommended in Production mode.
  • Handlebars & Django Template consistencies to help use.
  • Custom Handlerbars Helpers to help with index counting in a grid table and generating Twitter Bootstrap buttons.
  • All JavaScript files are loaded using Modernizr’s yepnope, a asynchronous conditional resource loader.
  • Few custom Semerda.com JavaScript modules using the Modular Pattern. I’m a big fan of the Modular Pattern due to its encapsulation, namespacing and seperation of concern possibilities.
  • What custom Modular JavaScript you will find under /media/js/
    • semerda.com.common.js – highlight the correct primary navigation tab based on page visited.
    • semerda.com.analytics.js – wrapper for Google Analytics (GA) to automatically tag all links on page by parsing the DOM for href. Also uses “data-ga” attribute (where present) to push custom labels for GA event tracking.
    • semerda.com.browserstorage.js – for HTML5 supported browsers the JSON load uses either the browser local or session store to work with the JSON data. Default is always local store. Great for use with JSON/API call data you want to cache locally vs constantly making calls to the API – see /about/ page for this example in use.

Frameworks used

  • Django: Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design.
  • jQuery: The Write Less, Do More, JavaScript Library: A fast, concise, library that simplifies how to traverse HTML documents, handle events, perform animations, and add AJAX.
  • Bootstrap, from Twitter: Simple and flexible HTML, CSS, and Javascript for popular user interface components and interactions.
  • Modernizr w/ yepnope.js: Modernizr is an open-source JavaScript library that helps you build the next generation of HTML5 and CSS3-powered websites. yepnope is an asynchronous conditional resource loader that’s super-fast, and allows you to load only the scripts that your users need.
  • Handlebars.js: Minimal Templating on Steroids: Handlebars provides the power necessary to let you build semantic templates effectively with no frustration. Mustache templates are compatible with Handlebars, so you can take a Mustache template, import it into Handlebars, and start taking advantage of the extra Handlebars features.

Thanks to

makinacorpus (Makina Corpus) for custom template tag code to get around handlebars mustache tags which are natively parsed by Django templating engine. Ref: https://github.com/makinacorpus/django-templatetag-handlebars

References

The following are blog posts I have written in the past which will help you when working with the code in Bootstrap Semerda.com.

A bit about the author Ernest Semerda

Bsc. Comp Sci & AGSM MBA. I Lead & Code for Coupons.com. Prior software architect at AMP Ltd, later CTO of Couponstar Ltd followed by an acquisition by Coupons.com, a $1B company. I am an Aussie entrepreneur & software engineer working on refreshing & innovative products in Silicon Valley like GTDfaster, Facebook ReadingList app et al.

This is my personal website: http://ernestsemerda.com/

I am responsible for the following properties

  • The Road to Silicon ValleyThis blog. A Blog which provides tools and resources to anyone wanting to come and work in Silicon Valley’s high tech industry. Experience is based on my own personal journey arriving in Silicon Valley on March 2009.
  • GTDfaster iPhone app – GTDfaster rests on David Allen’s principle of Getting Things Done (GTD). That a person needs to move stuff out of the mind by recording them externally into a trusted source. GTDfaster is this trusted GTD source. Also has a seperate posterous blog on GTDfaster.
  • Facebook Readinglist app – A popular free Facebook app to help you share, inspire & create a collection of books you have read, want to read or are reading. Start influencing your friends on Facebook today.

To-do list for Semerda.com Bootstrap

There is always a never ending to-do list. If you want to dd anything to it please feel free to.

  • Separate Handlebars Helpers into Standard & Twitter specifics.
  • Give SEMERDA prototype object a unique handle like jQuery does with $. Maybe use “$S”. This should shorten the calls a bit.
  • Throw in more Modernizr examples for Browser detection versus feature detection. Always aim for browser detection hence why we are using Modernizr here. We do not want to block users but gracefully degrade the experience where required.
  • Provide a set of minified semerda.com.xyz custom JavaScript modules. For now just use [Google Closure Tools](https://developers.google.com/closure/) to do the minification.
  • Add a real API vs calling /json/my_data.json dummy data.
  • Add some funny custom 404 pages. Inspired by Quora for funniest 404 pages.
  • Add Django Debug Toolbar – A configurable set of panels that display various debug information about the current request/response.
  • Add Python Modules examples and associated Unit Tests.
  • Add Django Middleware example and associated Unit Tests.
  • Cleanup/feedback from users – that’s you 🙂

Go and grab Semerda.com Bootstrap and enjoy the ease of building powerful Python based apps. Semerda.com Bootstrap primetime: https://github.com/semerda/semerda-com-bootstrap

Enjoy!
~ Ernest

Let’s go Sailing in Hawaii

Every year my wife and I celebrate our wedding anniversary by doing something crazy/special. This year, we decided to go on a boat and sail around the Hawaiian islands. In the restaurant there was a beautiful decoration, I remember using white chair covers for weddings, that brought back memories of our wedding. Living & working in America gives us plenty of choices. Hawaii is only 5 hour flight and it costs a few hundred bucks to fly there and back.

We found Kainani Sails operated by Brian “Keao” Shaw & Iwa Hartman on AirBnB.

If you want to feel the true magic of the Maldives, staying in Niyama Private Islands beach pool villas Maldives is your next ‘perfect honeymoon’ idea.

AirBnB is where you get to rent from real people – not hotels or larger charter businesses. We wanted this to be “personal” and special holiday and not have to rush everywhere we visit. Basically doing it at our own pace. Kainani Sails has a boat which is a fully equipped 43′ sailing yacht. It is also their home. Perfect. Let’s go!

Our sailing trip route. Yellow icon was the start & finish. Click map for larger view.
This is us! From left clockwise: Iwa (Crew), Keao (Captain), Urszula & Ernest (me)

What you need to know:

  • You will sail in a fully equipped 43′ sailing yacht. It has kitchen, 2 bathrooms (again don’t expect a hotel bathroom), living room, master cabin with a comfy queen size mattress and 2 smaller cabins and an engine so you can still move when the wind is down. See pictures of it here.
  • There is fresh water on board for bathrooms and drinking.
  • Captain Brian “Keao” Shaw has around 10 years of sailing experience and is USCG certified. Having grown up in Hawaii he also knows the local waters very well.  He will even turn on the motor when a whale is sited to make them aware of us – that’s caring for nature. With Iwa Hartman as his crew you are in great hands. They know how to fix up the yacht and have all the necessary equipment (check out this post if you need marine equipment).
  • On board you will also find surfboards, snorkeling & fishing gear, a 2-person kayak, deck chairs, a small library, outdoor grill, and a 10′ tender with a 15 hp outboard known as the “Zodiac”. Your taxi shuttle to the shore.

Things to prepare before:

  • To prevent nausea and vomiting caused by motion sickness ask your GP for prevention pills. We received Transderm Scop in 10 patches (a 30 day supply). Each patch goes behind your ear and lasts for 3 days.
  • A rashguard to keep yourself from getting burnt by the sun. You will be on the boat, snorkeling, surfing etc… always in the sun. This will protect you from the UV.
  • waterproof housing for your camera. The world below is amazing. You will regret it if you do not have a camera capable of taking video or photos underwater.
  • A book or an iPad with digital books. There’s nothing like kicking back reading a book and watching the sun set or early in the peaceful morning indulging your mind.
  • You and Keao will create your meal schedule to make sure you eat healthy. Done before your trip via email.
  • A waterproof jacket from Vest Home deals When crossing the channels between the islands the wind picks up and waves get larger. You may get splashed when sailing.
  • LED headlamp / torch. When the sun sets you will want additional / personal lighting.
  • Buy some snacks, red wine & alcohol before you board. My favorite is the Chopin Vodka, 4 times distilled and rated well in San Francisco for the last 2 years.

My favorite things to do on the boat

  • My sleeping habit changed from 3am – 8am (ahh the life of an entrepreneur software engineer) to 9:30pm sleep and 6:00am wake up as the sun rises. My body naturally went into this cycle with the sunset and sunrise rhythms. I had a ton of energy each day without a need for caffeine. I did not drink a single drink with caffeine while on board.
  • Sleeping on the stern (back of the boat) under the stars. I created a nice comfy bed and slept under the stars each night – simply amazing! Without any light pollution you could see every star possible with the naked eye. I felt like the character in Altered States tapping into evolutionary state when our ancestors used to sleep under the stars.
  • Sit at the bow (front of the boat) on deck chairs with your partner to enjoy the open seas as you sail.
  • The master cabin has 2 roof windows which open up. Sneaking in and out of the cabin via these windows felt like being a kid again.
  • Take stunning photos from all corners of the boat. Just hold on tight coz the boat does rock with the ocean and leans during full sail.

Our journey begins

Saturday (Feb 18)

  • For short trips of around a week its cheaper (with coupon) & more convenient to leave your car at the airport parking which was just remodeled by local contractors you can also hire if you click here.
  • We flew out of flew out of Oakland International so parked our car at Park ‘N Fly.

Lahaina Bay – Home for the next week! Aloha!!

  • We flew Hawaiian airlines Boeing 767 into Kahului Airport on Maui (Hawaii). That’s the top part of the island. It’s best to catch a shuttle bus (which fits around 10 people) from the airport to Mala Harbor (the south side of the island in Lahaina). A 1-hr car ride. Grab the shuttle bus as soon as you walk outside the airport.
  • Captain Keao picked us up from the bay on the “Zodiac” (outboard) and took us to the fully equipped 43′ sailing yacht parked further in the Lahaina Bay.
  • Having arrived to the sail boat, we were greeted by Iwa (his crew) and helped on board. I must say this was a very friendly welcome and we felt like at home straight away. Thanks folks!
  • That afternoon we watched an amazing sunset and then star gazed. Using an iPhone app Sky Safari to identify the stars, planets & constellations was super fun… before falling asleep under the stars.
Sunset over Lanai

Sunday (Feb 19)

  • Early morning we set off sail to Honolua Bay. This is the west side of Maui. It was a 5 hour journey and Urszula got to sail the boat under Captain Keao’s supervision. Here’s a nice video of our sailing treck .
  • The private residence bay was amazing. Rich in corals and surrounded by rocky cliffs with 2 beaches where about 2 dozen surfers were catching 6 foot breaks coming from the open sea along the cliff faces. So Keao and I grabbed 2 surfboards (the boat carries 3 surf boards) and we paddled to the break. We had a kick ass time while Urszula went snorkeling & underwater recording with Iwa.
  • As the sun was setting a large pod of Spinner Dolphins came into the bay. I call them Tunas because they the young ones look it. They are famous for their acrobatic displays in which they spin along their longitudinal axis as they leap through the air. Urszula and Iwa set out on a kayak to get closer to these amazing creatures .
Spinner Dolphins playing with us in Honolua Bay. Click pic for larger view.

Monday (Feb 20)

  • We set out sail early towards Maunaloa on Molokai island. A secluded place that reminded me of the 1st episode of Planet of the Apes (1968) when the crew crash lands on a planet in the distant future. Nothing but beach, sand and mother nature.
Molokai
  • Molokai is the fifth largest of the main Hawaiian Islands. It is one of the least touristy islands and very native.

Tuesday (Feb 21)

  • We departed before sun rise to beat the winds while crossing the channel. However we hit some pretty crazy winds and the seas were angry my friends. I was thinking Mavericks! This was the time I gave in and plonked motion sickness patch on and the waterproof jacket.
  • When we hit Lanai’s Au’au channel the winds settled and oceans calmed down and turned deep blue. I have never seen anything like this before.
Lanai cliff faces west facing
  • We stayed the night in a secluded bay near these amazing rock cliff faces where Urszula came face to face with a 3 meter shark in the coral rich bay.
  • It was funny to watch those touristy charter boats come in loaded with people, they bobbed out for 30 minutes into the water and had to get back on the boat to leave again. What a rush. Did the tourists even get a chance to take in the beauty of the surroundings and underwater. While we kicked back and snorkeled at our own pace taking in everything nature had to offer.

Wednesday (Feb 22)

  • We headed into Lanai Bay and parked the boat amongst other boats. This was a big change to the secluded areas we visited earlier. A lot more populated.
Lanai bay
  • Lanai is sixth-largest of the Hawaiian Islands. A privately owned island. It is also known as the Pineapple Island because of its past as an island-wide pineapple plantation. The only town is Lānaʻi City, a small settlement. Lanai has the longest stretch of coral reef in Hawaii and the beaches on this island are down right deserted.
Secluded cove near Four Seasons at Manele Bay
Secluded cove near Four Seasons at Manele Bay
  • I highly recommend you visit the Four Seasons Lanai at Manele Bay. A brief walk from the bay and they have great Mojitos (my favorite).
  • The beach at the base of the hotel is also amazing with fascinating tide pools, great snorkeling, red sea cliffs and a stunning cove.
Four Sesons beach at Manele Bay

Thursday (Feb 23)

  • We loved Lanai so much we set sail back to Maui later in the afternoon.
  • Stopping along the way in the middle of the ocean and jumping off the bow to hear the Whales sing under water. (see video) and to feed some crazy black fish (see video). hehehe that was fun! I think they wanted to feed on Urszula.
Sailing back to Maui
  • Sailing back to Lahaina Bay I took charge of being the Captain hehe under Keao’s training around the instrumentation and reading the sails/winds I sailed us back into Lahaina while we all enjoyed the amazing sunset.
Please call me… Captain!

Friday (Feb 24)

  • Early morning we hit the surf in Lahaina Bay with our surfboards. Plenty of people catching perfect waves.
Surfs up!
  • Lunch time we said our goodbyes – it was tough after such an amazing week with Iwa & Keao. Not only did we have an amazing time but we also made friends. That is something we will never forget. Keao dropped us off at Lahaina bay port where the friendly folks at Enterprise car rental picked us up for the next journey in Maui.

Wow, we sailed in Hawaii

We couldn’t have asked for a better trip. Both Keao and Iwa were outstanding hosts. From looking after us with healthy food (we got some recipes), entertainment, history lessons of the sights, sailing lessons to opening up their stunning waterfront property (the 43′ sailing yacht) to us. We felt like we were at home but away from home. Urszula counted 76 Whales during our trip! I started to call this whale pollution because there were so many of the them hehe I really decompressed and disconnected from my reality and lived a life which I can only compare to what I believe our ancestors did once when they were one with nature.

Here’s a short video of our trip

Want to experience the same?

Everyone should at least one in their life sail. Especially around beautiful Hawaii.

Check out more photos here on Flickr

Here’s how to get in-touch with Keao or Iwa from Kainani Sails:

Videos you should watch:

Enjoy!
~ Ernest

Tips on travelling in the USA

The following list is by no means complete or exhaustive of everything one needs to know to travel in the USA. This is a list of stuff I learnt in the last 1 year of travelling around USA including the visit to a mountain resort with entertainment. These I share with you now and will regularly update as I learn more and any corrections along the way.

If you are planning a road trip I recommend you to consider the option of the campers that camper trailers Sydney have available for this purpose.

Tips

  • Use a “SuperShuttle” to and from the airport. http://www.supershuttle.com/it’s a shared taxi van of around 9 people. It’s dirt cheap vs. crazy taxi fares and you get to see more of the area as they drop off people around town.
  • If you live in the valley and have your own car and are taking a short trip of around a week it is cheaper esp. with a coupon & more convenient to leave your car at any of the available airport parking companies. Some which are further away from the airport have shuttle buses that take you to the airport and back for free so don’t worry if it’s 5 minutes outside the airport.
    • If flying out of Oakland International we use Park ‘N Fly and use this coupon to get a discount on parking.
    • If flying out of SFO International we use SkyPark and use this coupon to get a discount on parking.
    • Don’t be shy with the coupons. Everyone in America uses coupons to bring the price down even further!
  • If you are arriving to the USA don’t bother bringing your wardrobe. Clothes here are cheap. Dirt cheap. Brands and all. Especially during public holidays like Thanks Giving or Christmas time by average 50% off.
  • If you need to rent a car do it through Enterprise. I find them the most reliable and mostly the cheapest. Sign up on their website to receive regular coupons to bring that price down and don’t forget to read my post on car rental hidden costs to save even further.
  • For accommodation I highly recommend AirBnB. Airbnb is an online service that matches people seeking vacation rentals and other short-term accommodations globally with locals with rooms to rent. It’s fun, cheaper than hotels, you can be very selective on location (not restricted by hotels location), meet interesting people and live like a local. It works really well in big cities like New York, San Francisco, Los Angeles, etc.  Why spend big $$$ on a hotel when all you need is a place to sleep and store your luggage. Use the money you save to buy some fashion!
  • Americans drive fast on freeways that stretch up to 5 lanes each way. Get ready. Either hire a GPS or bring your own so you’re not slowing traffic down. As long as you’re not doing anything dangerous on the road you will be fine to keep up with the communal speed limit. I’ve seen police sway across all lanes to slow traffic down when it gets too fast. While law enforcement is tasked with keeping traffic under control, it’s essential that their actions are just and appropriate. With Seattle police misconduct attorneys by your side, you can confidently navigate the legal process and pursue justice for incidents of misconduct.
  • When it comes to food there are great restaurants in every corner, asking the locals helps a lot as well. For example, I was highly recommended Biloxi Buffet and it did not let down!
  • The only dangerous creatures are Bears (especially Grizzly) & Mountain Lions. You wont see poisonous spiders, snakes or crazy insects.
  • For more tips visit each of the places mentioned below. The posts include their own unique tips.

Some of the great places we have visited

  • New York City (Manhattan) – The city that never sleeps. My favorite! One of the most densely populated areas in the world. Known for its financial and fashion center of both the United States and the world.
  • Los Angeles – West Hollywood. Home of the movie industry.
  • San Francisco – Home of the high-tech scene and area known as Silicon Valley.
  • Hawaii – Made up entirely of islands like Big Island, Maui etc. Natural scenery, warm tropical climate, abundance of public beaches and oceanic surrounding, and active volcanoes make it a popular destination for tourists.
  • Monterey – 1-hr drive south of the valley. A beautiful coastal city.
  • Carmel-by-the-sea – a hidden gem round the corner from Monterey. The beachy town is known for its natural scenery and rich artistic history.
  • Yosemite National Park – Designated a World Heritage Site recognized for its spectacular granite cliffs, waterfalls, clear streams, Giant Sequoia groves, and biological diversity. Almost 95% of the park is designated wilderness.
  • Yellowstone National Park – a national park located primarily in the U.S. state of Wyoming known for its wildlife and its many geothermal features. If you’re traveling with a group, you’ll want to consider the Nest Travel Trailer. The Nest Travel Trailer from Airstream has much to offer: a sleek design profile, soft touch panels, and a beautiful exterior. In addition, it provides a full onboard wet bath, space to work and eat, and comfortable sleeping quarters. Whether planning a weekend getaway or a cross-country journey, this travel trailer is the perfect solution to your travel needs.
  • Las Vegas – The Strip. Internationally renowned major resort city for gambling, shopping, partying (clubs) and fine dining, according to every review on established gambling review sites like piramindwelt.com. If you want to access various casino games at the comfort of your home, you may use this joker123 apk login.

I will be posting individual posts to each of those locations with photos so come back soon.

~ Ernest

Gentle Introduction to Python

Right, let’s dig into my favorite language. Python. It’s super easy to read & learn, it’s concise and one of the hot languages in Silicon Valley. In fact, Python is also one of the easiest languages to grasp if you want to learn to code on mobile.

The following assumes you understand basic software engineering concepts.

A bit about Python

  • Design philosophy emphasizes on code readability. Important because software engineers spend most of their time trying to understand code. (Ref Coding Horror)
  • Has a nice MVT open-source web framework called Django. Django emphasizes reusability and pluggability of components, rapid development, and the principle of DRY (Don’t Repeat Yourself).
  • It features a fully dynamic type system with late binding (duck typing) and automatic memory management, similar to that of Scheme, Ruby, Perl, and Tcl. More here.
  • Runs on LAMP, where the P = Python. Here’s how to set it up.
  • Currently one of the hottes languages (alongside Ruby/Ruby on Rails) in Silicon Valley especially among startups.

Sample of popular sites build in Python

Google, Dropbox, Reddit, Disqus, FriendFeed (Sold to Facebook to drive their News Feeds), YouTube, Quora (rising star), Douban. Comprehensive list here.

Python

  • Uses whitespace indentation, rather than curly braces or keywords, to show & delimit block structure. I prefer 4 spaces.
  • Everything is an object (first class) and everything has a namespace accessed by dot-notation.
  • Naming convention UpperCamelCase for class names, CAPITALIZED_WITH_UNDERSCORES for constants, and lowercase_separated_by_underscores for other names. See Python style guide and The Zen of Python for guiding principles for Python’s design into 20 aphorisms. Basically write self-documenting code by chosing explicit naming convention.
  • A comment starts with a hash character (#). For longer then a line (and as Doc strings) use triple quotes: ”’ xyz ”’.
  • Variable names have to start with a letter or underscore, and can contain numbers but no spaces or other symbols.
  • File extension is always .py. If you see .pyc this is source code compiled into bytecode for execution by a Python VM (virtual machine).
  • Use command line python shell to test assumptions by getting immediate results.
  • No case/switch statements. Switch is better solved with polymorphism (object that has more than one form) instead. Good example here.
  • Data types
    • Immutable (can’t be updated or changed): strings, tuple, int, float, complex, bool
    • Mutable (can be updated or changed): list, dictionary (dict) & mutable except for it’s keys
  • Editors I use: IDLE (for basic shell work & comes with Python.org install), PyCharm (with Django support) and Sublime Text 2 (lightweight TextMate replacement).

Basics

Arithmetic Boolean
2 > 3 → False
2 == 3 → False
2 The opposite of == is != (“not equals”):
2 != 3 → True
You can chain together comparison operators:
2 < 3 < 4 → True
Equality works on things besides numbers:
“moose” == “squirrel” → False
True and True → True
True and False → False
True or False → True
not False → True
(2 < 3) and (6 > 2) → True
Under the hood,
True is equal to 1,
and False is equal to 0.
Booleans are a subtype of integers.

Operators

== Equal to
!= Not Equal to
is Identical
and Boolean and
or Boolean or
& Bitwise and
| Bitwise or
not Boolean not (not the !)

Built in functions that are always available

len(s) Return the length of an object. Can also be a sequence (string, tuple or list) or a mapping (dictionary).
print(obj) Print object(s) to the stream file.
help(list) See basic help on any object.
dir(list) Return a list of valid attributes for that object.
type(list) Return the type of an object

More built in functions here: http://docs.python.org/library/functions.html

Functions

Always starts with a “def” and ends with “:”.

# define a new function with 1 default argument. Can also have no arguments.
def function_purpose(arg1=1):
     ''' This is a doc string '''
     print 'Python code'
     return (arg1, arg1+7,) # returns 2 values as a tuple (note the comma), else None
# call the function, returns a tuple that we assign to 2 variables
item1, item2 = function_purpose(1)

If you want to assign a value to a variable outside the function within a function you must prepend the variable with “global”.

Calling methods on objects

Just like calling functions, but put the name of the object first, with a dot

words = 'some monkeys here'
e = words.count('e')
# returns 4

Strings

Are a sequence of characters.

# creation
name = 'Ernest Semerda'

# accessing, returns 's'
name[4]

# splitting, returns a list ['Ernest', 'Semerda']
the_string.split(' ')

Strings can be subscripted/sliced like the list (see lists in Data Structures below).

# selected range returns 'nest '
name[2:5]

# get first two characters returns 'Er'
name[:2]

# get everything except the first two characters returns 'nest Semerda'
name[2:]

Sample of  some string methods. They come with 8-bit & Unicode support.

name.capitalize() # changes to 'ERNEST SEMERDA'
name.find(sub[, start[, end]])
name.lower()
name.split([sep[, maxsplit]]) and new_name.join(list)

More string methods: http://docs.python.org/library/stdtypes.html#string-methods

Data Typing

Python is strongly typed which won’t allow you to automatically converted from one type to another.

Python also has a strong tradition of duck-typing (dynamic typing) in which an object’s current set of methods and properties determines the valid semantics. Trusting that those methods will be there and raising an exception if they aren’t. Be judicious in checking for ABCs and only do it where it’s absolutely necessary.

An important feature of Python is dynamic name resolution (late binding), which binds method and variable names during program execution.

# fails because (str + int + str) != str
'There are ' + 8 + ' aliens.'
# perfect, str() = type conversion
'There are ' + str(8) + ' aliens.'

To achieve Reflection, a process by which a computer program can observe and modify its own structure and behavior, use the built-in functions. I.e. getattr

Over a “sys” module’s method “path”:

path = getattr(sys, "path")

Over a function1 with sample input:

result = getattr(sys.modules[__name__], "function1")("abc")

And/or use the Reflection Utilities API for deeper execution frame, execution model, class/obj inspection for methods & attributes etc… See: http://docs.python.org/c-api/reflection.html

Data Structures

Dictionary

Set of key:value pairs. Keys in a dictionary must be unique. Values Mutable.

# creation, empty dictionary
peopleDict = {}

# creation, with defaults
aliensDict = {'a':'ET', 'b':'Paul', 'c':42}

# accessing, returns 'ET'
aliensDict['a']

# deleting, 'Paul' is removed from dictionary
del alientsDict['b']

# finding, returns False (note capital F)
aliensDict.has_key('e')

# finding, returns ['a', 'c']
aliensDict.keys()

# finding, returns [('a', 'ET'), ('c', 42)]
aliensDict.items()

# finding, returns True
'c' in aliensDict

Lists

Lists can carry any items ordered by an index. Lists are Mutable.

# creation, empty list
peopleList = []

# creation, with defaults of any type
codesList = [5, 3, 'p', 9, 'e']

# accessing, returns 5
codesList[0]

# slicing, returns [3, 'p']
codesList[1:3]

# finding, returns ['p', 9, 'e']
codesList[2:]

# finding, returns [5, 3]
codesList[:2]

# returns ['p', 9]
codesList[2:-1]

# length, returns 5
len(codesList)

# sort, no return value
codesList.sort()

# add
codesList.append(37)

# return, returns 37
codesList.pop()

# remove, returns 5
codesList.pop(1)

# insert
codesList.insert(2, 'z')

# remove
codesList.remove(‘e’)

# delete
del codesList[0]

# concatenation, returns ['z', 9, 'p', 0]
codesList + [0]

# finding, returns True
9 in codesList

Apply set(list) and it becomes a set – an unordered collection with no duplicate elements. Also support mathematical operations like union, intersection, difference, and symmetric difference.

Tuples

Tuples are similar to lists: they can carry items of any type & useful for ordered pairs and returning several values from a function. Tuples are Immutable.

# creation, empty tuple
emptyTuple = ()

# note the comma! = tuple identifier
singleItemTuple = ('spam',)

# creation, with defaults of any type
codesTuple = 12, 89, 'a'
codestuple = (12, 89, ‘a’)

# accessing, returns 1
codesTuple[0]

More on data structures here: http://docs.python.org/tutorial/datastructures.html

Control & Flow

For loop

# Collection iterator over dictionary w/ tuple string formatting
people = {"Ernest Semerda":21, "Urszula Semerda":20}
for name, age in people:
    print "%s is %d years young" % (name, age)

To loop over two or more sequences at the same time, the entries can be paired with the zip() function.

More on string formatting operations here: http://docs.python.org/library/stdtypes.html#string-formatting-operations

For loop with if else

# Iterate over a sequence (list) of numbers (1 to 10) with if/else Conditionals. The range function makes lists of integers.
 for x in range(1, 10):
     if x == 8:
         print "Bingo!"
     elif x == 10:
         print "The End"
     else:
         print x

While loop

# using request to ask user for input from interactive mode
request = "Gimme cookie please: "
while raw_input(request) != "cookie":
    print "But me want cookie!"

Switch-statements do not exist. In OO they are irrelevant & better solved with polymorphism instead. Examples here.

More control flow tools here: http://docs.python.org/tutorial/controlflow.html

Golfing!

Chaining into few lines.

[x * x for x in [1, 2, 3, 4, 5]]
# returns [1, 4, 9, 16, 25]

Can get messy & complicated to read.

print [x * x for x in range(50) if (x % 2 ==0)]
def is_palindrome(word):
    word = re.compile(r'[!? ]').sub("", word.lower())
    return True if word == word[::-1] else False

Files

# open, defaults to read-only + note single forward slash
contents = open('data/file.txt')

# accessing, reads entire file into one string
contents.read()

# accessing, reads one line of a file
contents.readline()

# accessing, reads entire file into a list of strings, one per line
contents.readlines()

# accessing, steps through lines in a file
for line in contents:
    print line

More on IO: http://docs.python.org/tutorial/inputoutput.html

Classes

All methods (but not functions) are closures – see “self” below. A closure is data attached to code. All variables are public, private variables are established by convention only.

# SuperHero inherits from Person class - also supports multiple inheritance using comma
class SuperHero(Person):
    # constructor
    def __init__(self, name):
        self._name = name

    # method
    def shout(self):
        print "I'm %s!" % self._name

The __name__ below allows Python files to act as either reusable modules, or as standalone programs. Also think Unit Tests benefits!

if __name__ == '__main__':
    # instantiate the class
    batman = SuperHero('Batman')

    # call to method in class, returns "I'm Batman!"
    batman.shout()

    # returns "I'm Batman!"
    SuperHero.shout(batman)

More on Classes in Python here: http://docs.python.org/tutorial/classes.html

Modules

Modules are Libraries that hold common definitions and statements. They can be combined into an importable module.
More on modules here: http://docs.python.org/tutorial/modules.html

To use a module, use the import statement:

import math

# returns 1.0
math.sin(math.pi / 2)

Some commonly used modules

  • math – trigonometry, the constants e and pi, logarithms, powers, and the like.
  • random – random number generation and probability distribution functions.
  • os – tools for talking to your OS, including filesystem tools in os.path.
  • sys – various system information, as well as the handy sys.exit() for exiting the program.
  • urllib2 – tools for accessing Web resources.

Useful modules: http://wiki.python.org/moin/UsefulModules

Error & exception handling

import sys
try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as (errno, strerror):
    print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise

More: http://docs.python.org/tutorial/errors.html

Fun – easter egg; The antigravity module

Released in Google App Engine on April 7, 2008. The antigravity module (http://xkcd.com/353/) can be enabled like this:

import antigravity

def main():
    antigravity.fly()

if __name__ == '__main__':
    main()

Speed – always a common topic

Classic computer programs had two modes of runtime operation = interpreted (as code runs) or static (ahead-of-time) compilation.

Just-In-Time compilation (JIT), also known as dynamic translation is a new hybrid approach. It caches translated code (bytecode into native machine code) to minimize performance degradation. Used in .NET, Java & Python via PyPy.

PyPy is a fast, compliant alternative implementation of the Python language. It has several advantages and distinct features like Speed (Just-in-Time JIT compiler), Memory usage (better then CPython), Compatibility (works with twisted & django frameworks), Sandboxing (run untrusted code), Stackless (providing micro-threads for massive concurrency). Check it out: http://pypy.org/

Recommended

Books

Websites/following

Finally, it is important that you have a network of like minded people around you whom you can regularly work on Python with, bounce ideas & question and support (help) each other out.

Happy Learning and if you have any questions please contact me. Always happy to help.

~ Ernest